Thursday, August 28, 2008

How to communicate from the Arduino up to the TouchShield

Chris found a pretty compact way to send data from the Arduino up to the TouchShield. Since more and more projects that I'm building rely on this code, I figured I'd pull it out of the Pin Visualizer project, just to illustrate how it works. At the least, it sure beats trying to manually "bit-bang" across the pins!

On the Arduino, this code sends an unsigned integer up to the TouchShield, by sending the high byte first, then the low byte:

#include //include the serial library
#define RXPIN 3 //set up the receive pin
#define TXPIN 2 //and transmit pin, which will connect to software serial on the TouchShield
AFSoftSerial mySerial = AFSoftSerial(RXPIN, TXPIN); //init the software serial connection
mySerial.begin(9600); //and set the speed

while(mySerial.read() != 'U'); //wait until the TouchShield sends a sync character

unsigned char lowByte, highByte; //define this wherever you want to use the code below
unsigned int val = 123; //this is the value that will be sent

lowByte = (unsigned char)val; //extract the lower byte
highByte = (unsigned char)(val >> 8); //extract the upper byte
mySerial.print(highByte); //send the upper/high byte first
delay(1); //hang on a millisec
mySerial.print(lowByte); //send the low
delay(1); //hang on a millisec


On the TouchShield, this code accepts the high byte first, then the low byte, and then recombines them to make a single unsigned integer:


Serial.begin(9600); //set up the TouchShield serial connection
delay(3000); //and wait a little for the Arduino to boot up

Serial.print('U'); //send a sync character to the Arduino

unsigned int val; //define this variable in the function wherever you want to receive

val = (Serial.read() << 8) + Serial.read(); //read the high first, shift it up, then read the low

//Now you can use the val, which was sent from the Arduino

I hope it works for you! Let me know if you find anything cool to make with it...

No comments: