int sensorValue = analogRead(A0); Serial.println(sensorValue, DEC);Outputs (text):
0 1023for the same input values the following code:
int sensorValue = analogRead(A0); Serial.write(sensorValue);Outputs (bytes)
00 63The 0 got through, but the 1023 resulted in 63. This happens because:
- ADC resolution is 10-bit
- Thus the maximum value is 1023 (0x3FF)
- Serial.Write writes the more valuable 8 bits
- Serial.Write considers the ADC output as a 12 bit variable
- 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 03With
int upperByte = (sensorValue & 0x3FC) >> 2; int lowerByte = (sensorValue & 0x3) << 6;You get left aligned data for unsigned integers
00 00 C0 FFWith
int upperByte = (sensorValue & 0x3F8) >> 3; int lowerByte = (sensorValue & 0x7) << 5;You get left aligned data for signed integers
00 00 E0 7F
have you developed another way to do 10 bit digital.write ? Greetings!
ReplyDelete