How do you read the serial port with windows 10 core

Code Junkie picture Code Junkie · May 12, 2015 · Viewed 15.5k times · Source

using python on the Raspberry PI I use similar code to what is shown below to read data from the serial port:

baud = 9600                 # baud rate
port = '/dev/ttyACM0'       # serial URF port on this computer

ser = serial.Serial(port, baud)
ser.timeout = 0 
var message = ser.read(9);

Essentially I just want to be able to read a message off the serial port and perform an action based on that message.

How can this be achieved using Windows 10 Core and c#, Can anyone point me in the right direction or provide a code sample?

Thanks in Advance for any help received.

Answer

Code Junkie picture Code Junkie · May 12, 2015

it turns out that the Serial Port on the PI is not supported yet, which is very frustrating: https://www.raspberrypi.org/forums/viewtopic.php?t=109047&p=751638

Here is the supported way:

serialPort = await SerialDevice.FromIdAsync(comPortId);

serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000); 

serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000); 

serialPort.BaudRate = 115200;

serialPort.Parity = SerialParity.None; 

serialPort.StopBits = SerialStopBitCount.One; 

serialPort.DataBits = 7; 

serialPort.Handshake = SerialHandshake.None; 

serialPort.IsRequestToSendEnabled = true; 

dataReaderObject = new DataReader(serialPort.InputStream);

  // Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available
dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
 // Create a task object to wait for data on the serialPort.InputStream
loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken);

// Launch the task and wait
            UInt32 bytesRead = await loadAsyncTask;
            if (bytesRead > 0)
            {
                try
                {
                    var msg = dataReaderObject.ReadString(bytesRead);
                }
                catch (Exception ex ) {
                }
}