简体   繁体   中英

Difference between Arduino DUE and Arduino UNO when converting char

When reading a CMPS 10 compass using I2C the pitch is contained in one byte which is in the range +/- 90 degrees.

Using char to accept the result and converting to int works well on the Arduino Uno with the printout showing positive and negative numbers which is what I need.

#include "FastLED.h"

#define NUM_LEDS 150
#define DATA_PIN 6

#define CMPS_GET_ANGLE8  0x12
#define CMPS_GET_PITCH   0x14
#define BAUD38400        0xA1


CRGB leds[NUM_LEDS];

unsigned char  angle8;
char pitch;
int intpitch;



void setup()
{
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
  Serial.begin(9600);
  Serial1.begin(9600);
  delay(100);
  Serial1.write(BAUD38400); 
  Serial1.end();
  Serial1.begin(38400);
  delay(100);

}

void loop()
{
  getAngleAndPitch();  

  Serial.print("angle 8: ");        // Display 8bit angle
  Serial.print(angle8, DEC);
  Serial.print("    pitch: ");          // Display pitch data
  intpitch = pitch;
  Serial.println(intpitch);


  FastLED.showColor(CHSV(angle8, 200,200)); 
  delay(10);
}
void getAngleAndPitch()
{
  Serial1.write(CMPS_GET_ANGLE8);  // Request and read 8 bit angle
  while(Serial1.available() < 1);
  angle8 = Serial1.read();

  Serial1.write(CMPS_GET_PITCH);   // Request and read pitch value
  while(Serial1.available() < 1);
  pitch = Serial1.read();

}

On the Arduino DUE negative numbers of -1 to -90 are 255 to 165

Is this documented somewhere and how do I get the correct negative numbers without resorting to an IF statement?

The C++ standard does not specify if the char type is signed or unsigned. It appears in your case that UNO uses signed chars, but the Due uses unsigned chars.

You can specify the signedness of your variable directly:

signed char pitch; 

Or, you could use the fixed-length integer typedefs (found in the <cstdint> header):

int8_t pitch;

Generally, you should prefer to use the exact-width types unless you have a good reason not to.

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