my Code for sending the serial data is simple and straightforward:
public class Program { private static SerialPort m_SerialPort; static OutputPort ledPort = new OutputPort(Pins.ONBOARD_LED, false); static InterruptPort button = new InterruptPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLow); static bool state = false; public static void Main() { // write your code here m_SerialPort = new SerialPort(Serial.COM2, 9600, Parity.None, 8, StopBits.One); m_SerialPort.Open(); button.OnInterrupt += new NativeEventHandler(button_OnInterrupt); while (true) { if (state == true) { ledPort.Write(true); SendSerialData("Hello World"); ledPort.Write(false); Thread.Sleep(2000); } } } static void button_OnInterrupt(uint data1, uint data2, DateTime time) { state = !state; } public static bool SendSerialData(string sendData) { // Declare the required variables bool returnValue = false; byte[] sendBuffer; try { // Make sure we have a open Serial Port if ((m_SerialPort != null) && (m_SerialPort.IsOpen)) { // Create the Send Buffer sendBuffer = UTF8Encoding.UTF8.GetBytes(sendData + "\n"); m_SerialPort.Write(sendBuffer, 0, sendBuffer.Length); } } catch (Exception runtimeException) { Debug.Print("[WMServerComms.SendSerialData] " + runtimeException.ToString()); } // Return to calling method return (returnValue); } }
So I'm Sending the following Value
Text: "Hello World"
HEX: "48 65 6C 6C 6F 20 57 6F 72 6C 64"
Bytes: "72 101 108 108 111 32 87 111 114 108 100"
On the PC my Code is as follows:
class Program { static SerialPort com1 = new SerialPort("COM8", 9600, Parity.None, 8, StopBits.One); static void Main(string[] args) { com1.DataReceived += new SerialDataReceivedEventHandler(com1_DataReceived); com1.Open(); Console.ReadKey(); } static void com1_DataReceived(object sender, SerialDataReceivedEventArgs e) { byte[] output = new byte[com1.BytesToRead]; //string value = com1.Read(output, 0, com1.BytesToRead); foreach (byte item in output) { Console.WriteLine(item.ToString()); } } }
However the Data I Receive is
Text: "«::.ú‹….'7ë."
HEX: "AB 3A 3A 0A FA 8B 85 1B 27 37 EB 00"