Hi Homey!
I'm actually on ND+ (not 2) - Hope no issues here
So I'm posting working examples made from other examples that:
-use threads
-one thread is posting test message every 5sec
-second is printing in debug received messages
Everything works for me - thanks to all who made some code for serial and sharing it
using System;using System.Net;using System.Net.Sockets;using System.Threading;using Microsoft.SPOT;using Microsoft.SPOT.Hardware;using SecretLabs.NETMF.Hardware;using SecretLabs.NETMF.Hardware.NetduinoPlus;using System.IO.Ports;using System.Text;namespace NetduinoPlus_serial_test{ public class Program { static SerialPort serial; static string msg = ""; static object monitor = new object(); public static void Main() { //serial(using D0 - RX & D1 - TX) serial = new SerialPort(SerialPorts.COM1, 9600, Parity.None, 8, StopBits.One); serial.ReadTimeout = -1; serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived); serial.Open(); //threads var thread1 = new Thread(recive); var thread2 = new Thread(transmit); thread1.Start(); thread2.Start(); Thread.Sleep(Timeout.Infinite); } static void serial_DataReceived(object sender, SerialDataReceivedEventArgs e) { lock (monitor) { int bytesToRead = serial.BytesToRead; byte[] buffer = new byte[bytesToRead]; if (bytesToRead > 0) { serial.Read(buffer, 0, buffer.Length); } String str = new String(System.Text.Encoding.UTF8.GetChars(buffer)); msg = str; Debug.Print(msg + " in serial_DataReceived"); } } static void recive() { while (true) { lock (monitor) { if (msg.Length > 0) { Debug.Print(msg + " in thread"); msg = ""; } } } } static void transmit() { while (true) { lock (monitor) { Debug.Print("transmit thread works"); const string input = "Test$n"; byte[] sender = Encoding.UTF8.GetBytes(input); serial.Write(sender, 0, sender.Length); } Thread.Sleep(5000); } } }}
- NeonMika / Markus VV. likes this