Serial communication Python to Arduino - can't recognise carriage return


Question

I'm trying to communicate via serial between a BeagleBone running Ubuntu 10.04 and an Arduino. So far, I can send a string okay, but I'm having problems recognising the newline character.

From the BB side, in Python3 and using PySerial, I have (edited for just the relevant bits):

import serial
ser = serial.Serial('/dev/ttyACM0', 9600)

ser.write(chr(13).encode('ascii')) # establishes serial connection 
                                   # which will reset Arduino

delay(3000) # give time for reset. This method is from my own library

mesg = 'Beagle\n'
ser.write(mesg.encode('ascii'))

On the Arduino side I have:

boolean newMsg = false;
String incomingMsg = "";

void setup()
{
   /* some stuff - not relevant */
   Serial.begin(9600);
}

void loop()
{
    if(newMsg) {
        lcd.print(incomingMsg);
        newMsg = false;
    }
}

void serialEvent()
{
    incomingMsg = "";
    while (Serial.available() > 0) {
        char inByte = Serial.read();
        if (inByte == '\n') {
            newMsg = true;
        } else {
            incomingMsg = incomingMsg + inByte;
        }
    }
}

The problem is that newMsg never gets set to true because the if (inByte == '\n') never gets validated as true. I'even tried using '\r' on both sides and even a type-able character ('#'), but this test never works. The string 'Beagle' makes it through fine, though, so incomingMsg builds up okay.

Weirdly, I have this working between an Arduino and Processing (the Arduino on a robot connecting to Processing on a laptop via Bluetooth). I just can't see why it isn't working here. Any thoughts?

UPDATE: I have a partial answer, and one that will work for now, although I'd still like to know what's broken.

The if (inByte == '\n') is getting validated as true. But for some reason, the assignment of true to the global boolean var newMsg isn't working. Despite the assignment in serialEvent(), its value remains resolutely false inside loop(). Yet it's a global var (which, despite most programmers' aversion to them, are used quite a bit with the Arduino). I replaced the test in loop() with:

if (messageReceived != "")

and now it works. But I'd still like to know why that boolean problem exists.

1
3
9/27/2013 2:05:08 PM

Since newMsg is being changed in an interrupt driven function you may need to declare newMsg as volatile:

volatile boolean newMsg = false;

The will inform the compiler that the value may change and it should not optimize it.

Arduino Volatile reference

4
5/9/2012 8:02:17 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon