- So we started playing the with XBee! Things we learned:
- We can transmit stuffs!
- Made an LED flash on the receiving end
- We can replace the act of plugging and unplugging the XBee shield by toggling the shield switch from UART to DLINE. In UART is transmission mode, DLINE is code upload mode.
- We learned how to write to the serial monitor and transmit directly to STAMP plot
- Receiving XBee:
//const int ledPin = 13; // the pin that the LED is attached to
int incomingByte; // a variable to read incoming serial data into
// int cr = 13;
void setup() {
// initialize serial communication:
Serial.begin(9600);
// initialize the LED pin as an output:
//pinMode(ledPin, OUTPUT);
}
void loop() {
// see if there's incoming serial data:
if (Serial.available() > 0) {
// read the oldest byte in the serial buffer:
incomingByte = Serial.read();
// if it's a capital H (ASCII 72), turn on the LED:
Serial.print(incomingByte);
//Serial.write(cr);
Serial.print("\n");
//if (incomingByte == 'H') {
//Serial.print('H');
//digitalWrite(ledPin, HIGH);
//}
// if it's an L (ASCII 76) turn off the LED:
//if (incomingByte == 'L') {
//Serial.print('L');
//digitalWrite(ledPin, LOW);
//}
}
}
- Transmitting XBee:
//RAAAMP Code
int i = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
if (i < 500) {
i+=10;
}
else {
i = 0;
}
Serial.print(i);
delay(100);
}
- Flawed because Serial.print() writes individual ASCII characters, e.g. 100 -> "1" "0" "0"
- Possible fix? Serial.write (binary) transmitting, Serial.print receiving --> printing "as is"
- Other problem: Serial.write() can only send one byte at a time (0-255), so 260 -> 4
- One solution: still send ASCII characters using Serial.print() and receive as 8-bit integers, then convert into the corresponding inputNumber:
int inputChar;
int inputNumber=0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
if (Serial.available()>0){
delay(5);
while(Serial.available()>0){
inputChar=Serial.read();
inputNumber=inputNumber*10+(inputChar - '0');
}
Serial.println(inputNumber);
inputNumber=0;
inputChar=0;
}
}
- This method is more data-intensive than necessary. For example, if we want to send the number 1020, we would have to send four 8-bit integers representing each character, for a total of 32 bits. However since 1020 can be represented by 10-bits (0-1023), we really only need to send 2 8-bit packets of data. We can achieve this by using the following send code:
upper = i >> 8;
lower = i & 255;
Serial.write(upper);
Serial.write(lower);
- Receiving end loop:
// make sure both upper and lower bits have been received
if (Serial.available() >= 2) {
// read the oldest byte in the serial buffer:
upper = Serial.read();
lower = Serial.read();
incomingByte = (upper << 8) | lower;
Serial.println(incomingByte);
}
No comments:
Post a Comment