简体   繁体   中英

Arduino int16_t to uint8_t conversion weirdness

I have some really simply code that reads from an ADS sensor, which returns a value as int16_t . I know this value is always positive, so it saves memory. I am storing it in an array of uint8_t . But, I am getting a really odd conversion - any ideas?

Here is the code:

int16_t ads0 = ads.readADC_SingleEnded(0);
int16_t ads1 = ads.readADC_SingleEnded(1);
PLUG_ADS[0][PLUG_ADS_IDX] = (uint8_t)ads0;
PLUG_ADS[1][PLUG_ADS_IDX] = (uint8_t)ads1;
Serial.print("ADS 0: ");
Serial.print(ads0);
Serial.print(" / ");
Serial.print(PLUG_ADS[0][PLUG_ADS_IDX]);
Serial.print(" ADS 1: ");
Serial.print(ads1);
Serial.print(" / ");
Serial.println(PLUG_ADS[1][PLUG_ADS_IDX]);

And here is the output:

ADS 0: 791 / 23 ADS 1: 845 / 77
ADS 0: 792 / 24 ADS 1: 844 / 76
ADS 0: 794 / 26 ADS 1: 843 / 75
ADS 0: 790 / 22 ADS 1: 843 / 75
ADS 0: 792 / 24 ADS 1: 844 / 76
ADS 0: 793 / 25 ADS 1: 843 / 75
ADS 0: 794 / 26 ADS 1: 843 / 75
ADS 0: 791 / 23 ADS 1: 844 / 76
ADS 0: 790 / 22 ADS 1: 844 / 76
ADS 0: 793 / 25 ADS 1: 845 / 77
ADS 0: 791 / 23 ADS 1: 843 / 75
ADS 0: 792 / 24 ADS 1: 843 / 75
ADS 0: 791 / 23 ADS 1: 844 / 76
ADS 0: 792 / 24 ADS 1: 844 / 76
ADS 0: 791 / 23 ADS 1: 844 / 76
ADS 0: 792 / 24 ADS 1: 844 / 76
ADS 0: 794 / 26 ADS 1: 846 / 78
ADS 0: 793 / 25 ADS 1: 842 / 74
ADS 0: 793 / 25 ADS 1: 844 / 76
ADS 0: 793 / 25 ADS 1: 845 / 77
ADS 0: 793 / 25 ADS 1: 845 / 77
ADS 0: 793 / 25 ADS 1: 844 / 76
ADS 0: 797 / 29 ADS 1: 847 / 79
ADS 0: 792 / 24 ADS 1: 843 / 75

What the heck am I missing?

uint8_t is an unsigned 8 bit integer. It can represent values from 0 to 255. int16_t is a signed 16 bit integer. It can represent values from -32768 to 32767. See this link for a list of values that reach integer type can represent.

When you convert your value (with (uint8_t)ads0; ) you are trying to convert values in the order of 790 into a type that can only represent values up to 255. This causes a loss of data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM