Skip to content

Instantly share code, notes, and snippets.

@johnschimmel
Created September 28, 2014 18:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnschimmel/95bd3d94799717d4ace5 to your computer and use it in GitHub Desktop.
Save johnschimmel/95bd3d94799717d4ace5 to your computer and use it in GitHub Desktop.
Serial reading in multiple bytes and integer values
/*
http://www.baldengineer.com/blog/2012/07/30/arduino-multi-digit-integers/
*/
unsigned int controllerInputVal=0; // Max value is 65535
char incomingByte;
char controllerInput;
void setup()
{
// start serial port at 9600 bps:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
pinMode(2, INPUT); // digital sensor is on digital pin 2
// establishContact(); // send a byte to establish contact until receiver responds
}
void loop()
{
}
/*
SerialEvent occurs whenever a new data comes in the
hardware serial RX. This routine is run between each
time loop() runs, so using delay inside loop can delay
response. Multiple bytes of data may be available.
*/
void serialEvent() {
if (Serial.available() > 0) { // something came across serial
controllerInputVal = 0; // throw away previous integerValue
controllerInput = '0';
int byteCount = 0;
while(1) { // force into a loop until 'n' is received
incomingByte = Serial.read();
byteCount++;
if (incomingByte == '\n') break; // exit the while(1), we're done receiving
if (incomingByte == -1) continue; // if no characters are in the buffer read() returns -1
if (byteCount == 1) {
controllerInput = (char) incomingByte;
}
else {
controllerInputVal *= 10; // shift left 1 decimal place
controllerInputVal = ((incomingByte - 48) + controllerInputVal); // convert ASCII to integer, add, and shift left 1 decimal place
}
}
setController(controllerInput ,controllerInputVal);
}
}
void setController(char input, int val) {
Serial.print("controller val: ");
Serial.println(input);
Serial.println(val*2); // Do something with the value
}
//
//void establishContact() {
// while (Serial.available() <= 0) {
// Serial.print('A'); // send a capital A
// delay(300);
// }
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment