Saturday, April 13, 2013

Serial (UART) Communication between a Netduino Plus 2 & a Raspberry Pi

This code is part of a small experiment to work out how to send data between a Raspberry Pi and a Netduino Plus 2 via a serial (UART) connection. See this posting on one of my Arduino/Netduino blog for more information (including notes on how the two devices are wired together).

This code waits for a '@', '$', or '#' sent as a 1-byte "command" from the Netduion. The Raspberry Pi then responds with the requested information. The end of the response is marked with a linefeed (0x0A) character.


Python Code


import serial
import datetime

ser = serial.Serial("/dev/ttyAMA0", baudrate=115200)
while True:
        # Read 1-byte command from Netduino
        c = ser.read()
        # @ = get full date & time
        if c == '@':
                now = datetime.datetime.now()
                ser.write(str(now))
                ser.write('\x0A')
        # $ = get date
        elif c == '$':
                today = datetime.date.today()
                ser.write(str(today))
                ser.write('\x0A')
        # # = get time of day
        elif c == '#':
                now = datetime.datetime.now()
                time = "%02d:%02d:%02d" % (now.hour, now.minute, now.second)
                ser.write(time)
                ser.write('\x0A')

No comments:

Post a Comment