|
|
View previous topic :: View next topic |
Author |
Message |
hamid9543
Joined: 31 Jan 2013 Posts: 63
|
Sum of two unsigned int8 |
Posted: Sun Apr 25, 2021 1:47 pm |
|
|
Code: |
#include <16F1937.h>
#device ADC=8
#use delay(internal=32MHz)
#fuses MCLR,NOWDT
#use rs232(baud=9600,parity=N,xmit=PIN_C6,rcv=PIN_C7,bits=8,stream=PORT1)
unsigned int16 threshold[8];
unsigned int8min_Ir[8],max_Ir[8];
unsigned int8 AN[8]={1,2,3,4,5,6,7,8},irvalue=0;
main()
{
set_analog_pins(PIN_A1,PIN_A2,PIN_A3,PIN_A5,PIN_E0,PIN_E1,PIN_E2,PIN_B0);
setup_adc(ADC_CLOCK_DIV_32);
for(int i=0;i<8;i++)
{
min_ir[i] = 255;
max_ir[i] = 0;
}
while(true)
{
for(int i=0;i<8;i++)
{
set_adc_channel(AN[i]);
delay_us(10);
ir_value=read_adc();
if( ir_value>max_ir[i]) max_ir[i]= ir_value;
if( ir_value<min_ir[i]) min_ir[i]= ir_value;
}
for(int i=0;i<8;i++)
{
threshold[i]=(min_ir[i]+max_ir[i])/2;
printf("%lu %lu %lu\r\n",min_ir[i],max_ir[i] ,threshold[i]);
}
}
}
|
When unsigned int16 min_ir[i] and max_ir[i],and int16 threshold[i] result is correct
but when unsigned int8 min_ir[i] and max_ir[i],and int16 threshold[i] result is not correct.
Example:
When min and max both unsigned int8 then min=31 and max=247 threshold=11
but
when min and max both unsigned int16 then min=32 and max=247 threshold=139. |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Sun Apr 25, 2021 3:26 pm |
|
|
You're right. CCS doesn't do automatic type promotion.
Use a cast to int16 on min_ir[i]. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19488
|
|
Posted: Mon Apr 26, 2021 12:58 am |
|
|
The 'pity' is that for multiplication, CCS offer mul, which can take two
int8's and automatically extend the result to a higher type without needing
a cast. However they don't offer a similar function for addition.
Automatic promotion, is common on chips where the actual maths is
done using something like an FPU, which routinely extends the result.
However CCS keep to the original K&R structure for the arithmetic, that the
maths 'type' used, is determined only by the source variables, not the type
of the destination. So as PCM says, you simply have to cast one of the
source variables to force a larger maths type to be used. |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|