我需要一点帮助。我想将数组中的元素向上移动一个元素,以便新位置 1 包含位置 1 的旧值,new-2 包含 old-1,依此类推。旧的最后一个值被丢弃,第一个位置的新值是我每秒给的一个新值。
我使用大小为 10 的数组:
uint32_t TEST[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
我使用的代码必须每秒执行一次。
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
/* Code for shifting the elements */
for (int i = 0; i < 9; i++)
{
TEST[i+1] = TEST[i];
}
TEST[0] = HAL_ADC_GetValue(&hadc);
}
最佳答案
Ringbuffer 导致较少的数据复制,如果您希望 last_pos 指向最新的样本,您可以在读取之前增加它。
uint32_t TEST[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int last_pos = 0; /* init to any valid number between 0 and 9 inclusively */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
last_pos = (last_pos + 1) % 10;
TEST[last_pos] = HAL_ADC_GetValue(&hadc);
}
关于c - 移动数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36997652/