Skip to content

Instantly share code, notes, and snippets.

@chrismeyersfsu
Created August 6, 2012 04:22
Show Gist options
  • Save chrismeyersfsu/3270358 to your computer and use it in GitHub Desktop.
Save chrismeyersfsu/3270358 to your computer and use it in GitHub Desktop.
Arduino Poor man's oscilloscope
#define ANALOG_IN 0
void setup() {
Serial.begin(9600);
//Serial.begin(115200);
}
void loop() {
int val = analogRead(ANALOG_IN);
Serial.write( 0xff );
Serial.write( (val >> 8) & 0xff );
Serial.write( val & 0xff );
}
@stephanmantler
Copy link

@HKH13 Serial.write only works with bytes, so to send larger values (int is 16 bit) you need to split them up into their components. The first 0xff is likely just for synchronisation and not essential. Then the higher 8 bits are sent by shifting them right until they fit into a byte, and finally the lower 8 bits. For example, let's say val = 1342 (that is actually too high, analogRead only returns values between 0 and 1023, but whatever). 1342 is 00000101 00111110 in binary. So the shift and truncation yields 00000101, and val & 0xff is just the lower byte 00111110 which can then be sent piece wise and reassembled on the other side.

@tcedar
Copy link

tcedar commented Apr 7, 2019

Thanks @stephanmantler , that's really helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment