Xbee Serial.read is not clearing buffer - arduino

I wrote a example program to test Serial read from xbee. I was expecting a message passed from transmitter to receiver every 5 sec's but in serial monitor of receiver I am observing a continuous stream of repeat messages. Can anyone what I am missing. FYI: Also attached link to serial monitor screenshot.
[1]: https://i.stack.imgur.com/Lgxx5.png
/* ~ Simple Arduino - xBee Transmitter sketch ~ Router
*/
int count = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
//Send the message:
count ++;
Serial.println(String("Hello World : " + String(count)));
delay(5000);
}
/* ~ Simple Arduino - xBee Receiver sketch ~ Coordinator
*/
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0){
Serial.write(Serial.read());
}
}

For the receiver, don't you just want to pass Serial.read() to print() instead of Serial.write()? If you have two serial ports, one to the console and one to the XBee, they should have different names.
Could you provide some more details on your serial connections? What are COM3 and COM6 attached to? Are you sharing serial port pins with the XBee and your console? it seems like that could be part of your problem, if either the Arduino or XBee can drive the RX pin of your receiver's serial port, you'd end up echoing your characters back to yourself.

Figured out a work around to address the issue. Here are the details:
https://i.stack.imgur.com/3qZMi.png
Circuit connections from Arduino to XBEE Shield:
D0/RX to TX
D1/TX to RX
5V to 5V
GND to GND
/* ~ Simple Arduino - xBee Transmitter sketch ~ Router
*/
void setup() {
Serial.begin(9600);
}
void loop() {
//Send the message:
Serial.print('<');
Serial.print("Hello World");
Serial.println('>');
delay(1000);
}
/* ~ Simple Arduino - xBee Receiver sketch ~ Coordinator
*/
bool started = false; //True: Message is strated
bool ended = false; //True: Message is finished
byte index; //Index of array
char character; //Variable to store the incoming byte
char msg[13]; //Message - array
void setup()
{
Serial.begin(9600);
}
void loop()
{
while (Serial.available())
{
character = Serial.read();
if (character == '<')
{
started = true;
index = 0;
msg[index] = '\0'; // Throw away any incomplete packet
}
//End the message when the '>' symbol is received
else if (character == '>')
{
ended = true;
break; // Done reading - exit from while loop!
}
//Read the message!
else
{
if (index < 11)
{ // Make sure there is room
msg[index] = character; // Add char to array
index++;
msg[index] = '\0'; // Add NULL to end
}
}
}
if (started && ended)
{
Serial.print("Message: ");
Serial.println(msg);
index = 0;
msg[index] = '\0';
started = false;
ended = false;
}
}

Related

How can I create an automated GPS tracker using A9G AI Thinker module?

I have an AI Thinker A9G module connected to an ESP8266 D1 mini. I have the following script to send and receive AT commands to/from the module. The idea is to get a SMS with the Google maps GPS location of the module onto my mobile phone.
// GPS tracker with AI Thinker A9G module and AZ Delivery D1 Mini ESP8266 module
#include <SoftwareSerial.h>
#define rxPin D7
#define txPin D8
SoftwareSerial A9modem(rxPin, txPin); // Pins D7 Rx and D8 Tx are used as used as software serial pins
String incomingData; // For storing incoming serial data
String gpsData; // For storing location data
char msg;
char call;
void setup()
{
Serial.begin(115200); // Baud rate for serial monitor
A9modem.begin(115200); // Baud rate for GSM shield
Serial.println("GPS/GSM A9G BEGIN");
Serial.println("Enter character for control option: ");
Serial.println("h : to disconnect a call");
Serial.println("s : to send a message");
Serial.println("r : to receive a message");
Serial.println("c : to make a call");
Serial.println("l : to read location");
Serial.println("d : to disconnect gps");
Serial.println();
delay(100);
// Set SMS mode to text mode
A9modem.print("AT+CMGF=1\r");
delay(100);
// Set GSM module to TP show the output on serial out
A9modem.print("AT+CNMI=2,2,0,0,0\r");
delay(100);
}
void loop()
{
ReceiveMessage();
gpsData = incomingData.substring(33, 52);
Serial.print("Location: ");
Serial.println(gpsData);
delay(2000);
if (Serial.available() > 0)
switch(Serial.read())
{
case 's':
SendMessage();
break;
case 'r':
ReceiveMessage();
break;
case 'c':
MakeCall();
break;
case 'h':
HangupCall();
break;
case 'l':
ReadLocation();
break;
case 'd':
DisconnectGps();
break;
}
}
void ReceiveMessage()
{
if (A9modem.available() > 0)
{
incomingData = A9modem.readString(); // Get the data from the serial port
Serial.print(incomingData);
delay(100);
}
}
void SendMessage()
{
A9modem.println("AT+CMGF=1"); // Sets the GSM Module into text mode
delay(1000); // Delay of one second
A9modem.println("AT+CMGS=\"xxxxxxxxxxxxx\"\r"); // Replace your mobile number here
delay(1000);
String sms = "http://maps.google.com/maps?q=" + gpsData; // Create the SMS location string
A9modem.println(sms);
delay(100);
A9modem.println((char)26); // ASCII code of CTRL+Z
delay(1000);
}
void MakeCall()
{
A9modem.println("ATD+xxxxxxxxxxxxx;"); // Replace your mobile number here
Serial.println("Calling "); // Print response over serial port
delay(1000);
}
void HangupCall()
{
A9modem.println("ATH");
Serial.println("Hangup Call");
delay(1000);
}
void DisconnectGps()
{
A9modem.println("AT+GPS=0");
Serial.println("Disconnect GPS");
delay(1000);
}
void ReadLocation()
{
A9modem.println("AT+GPS=1");
delay(1000);
A9modem.println("AT+LOCATION=2"); // Check location every two seconds
delay(2000);
}
So if I use the commands "l" and "s" in Arduino IDE serial monitor everything is working well but I don't know how to change the code in a way that I get a fully automated GPS tracker. The idea is the following: Power on starts the tracker. When gpsData string is not empty the first SMS will be send to my mobile phone. The next SMS follows 20 minutes later and so on until power is switched off. Could you help please?
Thanks in advance!
Finally I came up with this solution but I'm not very happy with it (it is working but I have to restart the module from time to time because there are no GPS data). There are 3 reasons for this: There is no error handling for the GPS function, I set the delays in a more ore less random way to get everything working but I don't know if the values make sense and I don't know if the substring() function is the best way to get the location from the serial response.
// GPS tracker with AI Thinker A9G module and AZ Delivery D1 Mini
ESP8266 module
#include <SoftwareSerial.h>
#define rxPin D7
#define txPin D8
SoftwareSerial A9modem(rxPin, txPin); // Pins D7 Rx and D8 Tx are used as used as software serial pins
String incomingData; // For storing incoming serial data
String gpsData; // For storing location data
int runGps = 1;
int sendSms = 0;
void setup()
{
pinMode(LED_BUILTIN, OUTPUT); // Use builtin LED for correct GPS status
Serial.begin(115200); // Baud rate for serial monitor
A9modem.begin(115200); // Baud rate for GSM shield
// Set SMS mode to text mode
A9modem.print("AT+CMGF=1\r");
delay(300);
// Set GSM module to TP show the output on serial out
A9modem.print("AT+CNMI=2,2,0,0,0\r");
delay(1000);
Serial.end();
delay(500);
}
void loop()
{
Serial.begin(115200);
ReceiveMessage(); // Start a new serial stream
gpsData = incomingData.substring(33, 52); // Strip all unnessesary data from the stream
Serial.print("Location: "); // Check if the location data are correct
Serial.println(gpsData);
delay(1000);
if(runGps == 1) { // Start GPS
ReadLocation();
delay(20000); // Wait for GPS to be ready
}
if(gpsData.length() == 19 && sendSms == 0) { // If the location string is correct send SMS
if (isdigit(gpsData.charAt(0))) { // Check if the stream starts with a number
SendMessage();
digitalWrite(LED_BUILTIN, HIGH);
delay(300);
digitalWrite(LED_BUILTIN, LOW);
delay(300);
digitalWrite(LED_BUILTIN, HIGH);
delay(300);
digitalWrite(LED_BUILTIN, LOW);
delay(300);
digitalWrite(LED_BUILTIN, HIGH);
}
}
if(runGps == 0 && sendSms == 1) {
runGps = 1;
sendSms = 0;
delay(6000); // Make sure that all SMS serial communication is over
while (A9modem.available()) {
A9modem.read(); // Delete all data from serial buffer
}
delay(300000); // If SMS was sent wait 5 minutes before running the main loop again
Serial.end();
delay(500);
}
}
void ReceiveMessage()
{
if (A9modem.available() > 0)
{
incomingData = A9modem.readString(); // Get the data from the serial port
Serial.print(incomingData);
delay(500);
}
}
void SendMessage()
{
sendSms = 1; // Stop starting the SendMessage function
A9modem.println("AT+CMGF=1"); // Sets the GSM Module into text mode
delay(1000);
A9modem.println("AT+CMGS=\"xxxxxxxxxx\"\r"); // Replace your mobile number here
delay(1000);
String sms = "http://maps.google.com/maps?q=" + gpsData; // Create the SMS string
A9modem.println(sms);
delay(500);
A9modem.println((char)26); // ASCII code of CTRL+Z
delay(500);
}
void ReadLocation()
{
runGps = 0; // Stop starting the ReadLocation function
A9modem.println("AT+GPS=1");
delay(1000);
A9modem.println("AT+LOCATION=2"); // Check location every two seconds
delay(2000);
}
Try turning ON the NMEA stream from the A9G. Say you want to get the NMEA data every t seconds, you can add and then call the following function once in the void setup()
void TurnOnNMEA(int t)
{
if(t > 3600)
t = 3600; // Because the max time is 3600s
A9modem.print("AT+GPSRD=");
A9modem.println(t);
while(!A9modem.available()); // wait till the A9G sends a response
char c;
while(A9modem.available())
{
c = A9modem.read();
Serial.print(c);
delay(2); // Time needed for the next character
}
}
This will start the NMEA data stream every t seconds which you can print using the following function,
void ReadNMEA()
{
char c; // Read each character from the stream as it comes
if(A9modem.available())
{
c = A9modem.read();
Serial.print(c);
delay(2); // Time needed for the next character
}
}
Parsing and decoding the NMEA is a bit tricky thing to do. There is a lot of information inside it and the decoding depends on what you want to do with it. If you just want the location, you can parse the $GNGGA line.
When parsing the data, DO NOT USE Arduino String() class. It is a very bad idea when handling this kind of stream. Instead, use char array.

Arduino SIM900 GSM how to Join Char on String

I am currently making an Arduino project with GSM900 GSM GPRS. In this project, I have to receive data sent from a phone. I could easily receive data with a single character, but I can`t join does character to obtain a full word (String). I have to use this full word inside an If statement if this word equals to that other word (string), make something...
#include <SoftwareSerial.h>
// Configure software serial port
SoftwareSerial SIM900(7, 8);
//Variable to save incoming SMS characters
char incoming_char=0;
String newchar = "";
void setup() {
// Arduino communicates with SIM900 GSM shield at a baud rate of 19200
SIM900.begin(19200);
Serial.begin(19200);
// Give time to your GSM shield log on to network
delay(20000);
// AT command to set SIM900 to SMS mode
SIM900.print("AT+CMGF=1\r");
delay(100);
// Set module to send SMS data to serial out upon receipt
SIM900.print("AT+CNMI=2,2,0,0,0\r");
delay(100);
}
void loop() {
if(SIM900.available() >0) {
incoming_char=SIM900.read();
Serial.print(incoming_char);
}
}
I tried putting this command on the the if statement inside the loop, but after i tried comparing the words, it wouldnt work.
void loop() {
if(SIM900.available() >0) {
incoming_char=SIM900.read();
newString = incoming_char + "";
Serial.print(incoming_char);
}
if (newString == "Test"){
Serial.println("It worked");
}
}
The output that i get from the Monitor Serial is this:
+CMT: "+myNumber","","19/09/20,16:31:05-12"
Test
void loop() {
if (SIM900.available() >0) {
incoming_char=SIM900.read();
newString += incoming_char;
Serial.print(incoming_char);
}
if (newString.endsWith("Test")) {
Serial.println("It worked");
}
}
For does who are wondering how it finished:
Thanks to phoenixstudio...
void loop() {
if(SIM900.available() >0) {
incoming_char=SIM900.read();
newString += incoming_char;
Serial.print(incoming_char);
}
if (newString.endsWith("Test1")){
Serial.println("Worked1");
}
if (newString.endsWith("Test2")){
Serial.println("Worked2");
}
if (newString.endsWith("Test3"){
Serial.println("Worked3");
}
}

Arduino Xbee Data parsing

Im sorry to make a post like this but i have tried everything and i cant get this working!
I have two arduinos hooked up with xbee's.
One is connected to my computer recieving data and the other is bettery powered and has a Wii nunchuck attached.
I know im getting good data from the nunchcuck cause i tested it without the xbee.
But i want to send the data over serial and recieve on the other to use for something else but doesnt seem to be working. Here is the code:
Arduino with wii:
#include <Wire.h>
#include <Servo.h>
const int vccPin = A3;
const int gndPin = A2;
Servo servo;
const int dataLength = 6; // Number of bytes to request
static byte rawData[dataLength];
enum nunchuckItems {
JoyX, JoyY, accelX, accelY, accelZ, btnZ, btnC};
void setup()
{
pinMode(gndPin, OUTPUT);
pinMode(vccPin, OUTPUT);
digitalWrite(gndPin, LOW);
digitalWrite(vccPin, HIGH);
servo.attach(9);
delay(1000);
Serial.begin(9600);
nunchuckInit();
}
void loop()
{
nunchuckRead();
int joyX = getValue(JoyX);
int joyY = getValue(JoyY);
Serial.print(joyX);
Serial.print(",");
Serial.print(joyY);
Serial.println();
}
void nunchuckInit(){
Wire.begin();
Wire.beginTransmission(0x52);
Wire.write((byte)0x40);
Wire.write((byte)0x00);
Wire.endTransmission();
}
static void nunchuckRequest(){
Wire.beginTransmission(0x52);
Wire.write((byte)0x00);
Wire.endTransmission();
}
boolean nunchuckRead(){
int cnt = 0;
Wire.requestFrom(0x52, dataLength);
while (Wire.available()){
rawData[cnt] = nunchuckDecode(Wire.read());
cnt++;
}
nunchuckRequest();
if (cnt >= dataLength)
return true;
else
return false;
}
static char nunchuckDecode(byte x){
return (x ^ 0x17) + 0x17;
}
int getValue(int item){
if (item <= accelZ)
return (int)rawData[item];
else if (item == btnZ)
return bitRead(rawData[5], 0) ? 0: 1;
else if (item == btnC)
return bitRead(rawData[5], 1) ? 0: 1;
}
How could i recieve this data on the recieving arduino?
Please help its for my school project!
Thank you!!
When you read the terminal (without the Xbee) do you see line with X,Y appear ? Because if your arduino terminal see it, the problem comes from the Xbee.
If your terminal see the line, look at your Xbee with Xctu. You must set the panID on both Xbee to see them communicate. you must also make the SL address of the sender equal to the DL address of the receiver (and same for the SH/DH).
Can you say us which Arduino, Xbee, shield you use. It can help us to have more details

Leonardo serial comunication

I wrote this sample sketch to test serial communication with Arduino Leonardo (using Arduino IDE 1.0.5 on Windows 7):
int delayTime = 10000;
long lastExec = 0;
void setup()
{
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
}
void loop()
{
long t = millis();
if (t - lastExec >= delayTime) {
if(Serial.available() > 0){
Serial.println('Hello world');
}
lastExec = t;
}
}
The serial port selected seems working because the sketch uploads correctly.
However I didn't get anything in the serial monitor window. Why?
You first need to send a character to the Arduino.
Because you have if(Serial.available() > 0), the Arduino won't Serial.println("Hello World"); unless there is something in the Serial buffer.
You may also want to reduce the delayTime which is very long.
In conclusion, you can try this by typing something in your Serial Monitor:
void setup()
{
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
}
void loop()
{
if(Serial.available() > 0){
Serial.println('Hello world');
}
}
Hope it helps! :)
Does help to have "Hello world", not 'Hello world'.

xbee pro s2b receiving random data

I have a trouble with xbee s2b.
I try to receive two joystick values using only xbee placed on sparkfun regulated board (Coordinator API) and process these data on Arduino Uno connected to other xbee s2b placed on explorer board.(Router API). I configured xbees using X-CTU properly and I adjusted DIO0 and DIO1 to ADC[2] on Router Xbee. There is no problem when working with one joystick. But when I try to receive two joystick values at the same time, they are not working correctly. When I look the incoming data on serial monitor, I see;
https://lh3.googleusercontent.com/-20vjr0EchsQ/VqyZXgq84VI/AAAAAAAAA_0/WhEtoOU61vA/s1280-Ic42/Screenshot_3.jpg
My Arduino code is:
int packet[32];
void setup()
{
Serial.begin(9600);
}
void loop(){
if (Serial.available() > 0) {
if (Serial.read() == 0x7E) {
packet[0] = 0x7E; //start delimiter
packet[1] = readByte(); //MSB1
packet[2] = readByte(); //MSB2
int dataLength = (packet[1] << 8) | packet[2]; //between the length and the checksum
printPacket(dataLength+4);
Serial.println("");
}
}
delay(1000);
}
void printPacket(int k) {
for(int i=0; i < k; i++) {
Serial.print(packet, HEX);
Serial.print(" ");
delay(1000);
}
}
int readByte() {
while (true) {
if (Serial.available() > 0) {
return Serial.read();
}
}
}
What is the point I missed? Can you help me about this issue. Thank you in advance.
The delay(1000) statements may be causing you to lose characters from your serial buffer, and might not be necessary.
The code you shared appears incomplete. Where are you reading the dataLength bytes of the packet? How does printPacket() print the bytes?
Your inbound packet buffer should be larger -- I think the XBee S2B can have network payloads of up to 255 characters, in addition to the frame header and checksum.
You've created a blocking readByte() call, which isn't good program design. Consider something like this instead:
unsigned char packet[300];
int packet_index = 0;
int packet_length;
void loop() {
while (Serial.available() > 0) {
packet[packet_index++] = Serial.read();
if (packet_index == 3) {
packet_length = (packet[1] << 8) | packet[2];
}
if (packet_index > 2 && packet_index == packet_length) {
print_packet();
packet_index = 0;
}
}
}
void print_packet() {
int i;
for (i = 0; i < packet_length; ++i) {
Serial.print(packet[i], HEX);
Serial.print(" ");
}
Serial.println("");
}
If you have too much data to print and you're overflowing your outbound serial buffer, try increasing the speed of the console's serial port to 115200bps. Or print the bytes as you receive them instead of waiting until the packet is complete.

Resources