【发布时间】:2019-11-12 23:30:28
【问题描述】:
我正在尝试使用 ATmega328P MCU 执行以下计算。
?????????????????????????????????? = 1000 · ????????????0 + 2000 · ????????????1 +⋯ + 8000 · ????????????7 /????????????0+????????????1+⋯+????????????7
在主程序中(如图所示):
int main(void)
{
//variables
uint16_t raw_values[8];
uint16_t position = 0;
uint16_t positions[8];
char raw[] = " raw";
char space[] = ", ";
char channelString[] = "Channel#: ";
char positionString[] = "Position: ";
//initialize ADC (Analog)
initADC();
//initialize UART
initUART(BAUD, DOUBLE_SPEED);
//give time for ADC to perform & finish 1st conversion
//8us x 25 = 200us
delay_us(200);
while(1)
{
//get the raw values from the ADC for each channel
for(uint8_t channel = 0; channel < 8; channel++)
{
raw_values[channel] = analog(channel);
//invert the raw value
raw_values[channel] = DIVISOR - raw_values[channel];
}
for(uint8_t channel = 0; channel < 8; channel++)
{
//print the channel#
transmitString(channelString);
printDec16bit(channel);
transmitString(space);
//print the raw value from the ADC conversion
printDec16bit(raw_values[channel]);
transmitString(raw);
transmitString(space);
//calculate the position value at each sensor
transmitString(positionString);
positions[channel] = (uint16_t)((POSITION_REF/DIVISOR) * raw_values[channel]);
printDec16bit(positions[channel]);
printCR();
}
printCR();
//calculate and display 'position'
position = calculatePosition(positions);
printDec16bit(position);
printCR();
printCR();
//add a delay
delay_ms(2000);
}
}
我正在调用下面的函数,但我得到的返回值是错误的。
uint16_t calculatePosition(uint16_t* channel_positions)
{
uint32_t intermediates[8];
uint32_t temp_sum = 0;
uint16_t divisor = 0;
uint16_t value = 0;
for(uint8_t i = 0; i < 8; i++)
{
intermediates[i] = channel_positions[i] * ((i + 1) * 1000);
}
for(uint8_t j = 0; j < 8; j++)
{
temp_sum = temp_sum + intermediates[j];
}
for(uint8_t k = 0; k < 8; k++)
{
divisor = divisor + channel_positions[k];
}
value = temp_sum/divisor;
return value;
}
或者,我什至尝试过这段代码,得到的结果不是我所期望的。
uint16_t calculatePosition(uint16_t* channel_positions)
{
uint16_t position;
position = ((1000 * channel_positions[0]) +
(2000 * channel_positions[1]) +
(3000 * channel_positions[2]) +
(4000 * channel_positions[3]) +
(5000 * channel_positions[4]) +
(6000 * channel_positions[5]) +
(7000 * channel_positions[6]) +
(8000 * channel_positions[7])) /
(channel_positions[0] +
channel_positions[1] +
channel_positions[2] +
channel_positions[3] +
channel_positions[4] +
channel_positions[5] +
channel_positions[6] +
channel_positions[7]);
return position;
}
我做错了什么?对于诸如 {15, 12, 5, 16, 11, 35, 964, 76} 之类的值数组,我希望得到 6504 的结果,但我得到的是 200 的值(或其他一些奇怪的值)。
【问题讨论】:
-
请创建一个minimal reproducible example,并用一个最小的主函数来说明问题所在。显示实际和预期的输出。另外,我认为你应该更好地解释你的公式。
-
与我的另一个问题中显示的程序相同,但我缩小了问题的范围。我将删除我的另一个问题,并编辑这个以显示上下文。
-
您如何将
964 * 7000表示为uint16_t?提示:你的计算溢出了。 -
我已经编辑了我的问题,并消除了我进行计算的替代方法。
-
A minimal reproducible example 并不表示您正在使用的主要功能。这意味着一个minimal main 函数足以演示问题,这意味着我们应该能够只复制问题中的代码并编译它并得到与你相同的问题。
标签: c microcontroller avr