Notes About Working with Various Arduino & Netduino Microcontroller Boards

Saturday, April 13, 2013

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

The following basic example shows how to use a serial (UART) connection to send data back and forth between a Netduino Plus 2 and a Raspberry Pi using a serial connection.

In this demonstration, the two devices are connected at 115200 baud. The Netduino sends different 1 byte commands to the Raspberry Pi. These commands are just arbitrary; the programmer needs to work out how commands are sent and how responses are evaluated (including how to tell if you have received the full response or not). The Raspberry Pi then returns the full current time and date, just the date, or just the time, depending on which command byte was received.

The Python code for the Raspberry Pi part of the operation is on my Raspberry Pi blog.


Netduino Plus 2  Raspberry Pi
Digital 0        TXD
Digital 1        RXD
GND              GND

Digital pins 0 and 1 are used with the COM1 serial port. You could connect using the other COM ports available on the Netduino.  See the board's product page for information on which pins are associated with the COM ports.

Note that both must have a common ground. This example prints to the Visual Studio debug console, so I am using the current provided by the USB connection.

Both devices are 3.3 volt, so no logic level converter is needed for the serial connection.


Here is the C# code for the Netduino. See my Raspberry Pi blog for the Python code for the RPi.

My code uses the following characters to represent commands: @, $, and #. As indicated above, these are just arbitrary symbols/bytes. You could certainly use multibyte commands, but then you would need to add a loop to write the commands one byte at a time to the Pi and work out a way to tell when each command transmission was finished.

using System;
using System.Threading;
using Microsoft.SPOT;
using SecretLabs.NETMF.Hardware.Netduino;
using System.IO.Ports;

namespace RPiSerial
    public class Program
        public static void Main()
            SerialPort serial = new SerialPort(SerialPorts.COM1,
                  115200, Parity.None, 8, StopBits.One);
                // Get full date & time
                // Get date only
                // Get time of day only

        private static void getResponse(SerialPort serial)
            String response = "";
            while (serial.BytesToRead > 0)
                byte[] buf = new byte[1];
                serial.Read(buf, 0, 1);
                // Line feed - 0x0A - marks end of data.
                // Append each byte read until end of data.
                if (buf[0] != 0x0A)
                    response += (char)buf[0];

1 comment: