Saturday, October 30, 2010

How to write 10-bit ADC values to the 8-bit serial with Arduino?

The following code:
int sensorValue = analogRead(A0);
Serial.println(sensorValue, DEC);
Outputs (text):
0
1023
for the same input values the following code:
int sensorValue = analogRead(A0);
Serial.write(sensorValue);
Outputs (bytes)
00 63
The 0 got through, but the 1023 resulted in 63. This happens because:

  1. ADC resolution is 10-bit
  2. Thus the maximum value is 1023 (0x3FF)
  3. Serial.Write writes the more valuable 8 bits
  4. Serial.Write considers the ADC output as a 12 bit variable
  5. 63 (0x3F) are the 8 more valuable bits in this variable

So what you have to do is to fix this behavior
int upperByte = (sensorValue & 0x300) >> 8;
int lowerByte = sensorValue & 0xFF;
Serial.write(lowerByte);
Serial.write(upperByte);
Then you will get right aligned data:
00 00 FF 03
With
int upperByte = (sensorValue & 0x3FC) >> 2;
int lowerByte = (sensorValue & 0x3) << 6;
You get left aligned data for unsigned integers
00 00 C0 FF
With
int upperByte = (sensorValue & 0x3F8) >> 3;
int lowerByte = (sensorValue & 0x7) << 5;
You get left aligned data for signed integers
00 00 E0 7F

1 comment:

  1. have you developed another way to do 10 bit digital.write ? Greetings!

    ReplyDelete