Hi all,
On my PC side I have
gooby.Write(xmit, 0, 4);
where gooby is a SerialPort and xmit is a 4 byte array.
On the Netduino side, inside the event handler I have
gooby.Read(xmit, 0, 4);
where gooby and xmit are declared as on the PC side. The settings for the serial ports match identically.
What I'm trying to do is transmit an integer 0-5000 from the PC to the Netduino. Easy enough, I break the integer into its component bytes and transmit them. However, on the Netduino side, all 4 bytes don't always arrive. Sometimes the event handler thinks there are 3, sometimes 1, sometimes 0. Also, occasionally it will offset by a whole byte, making a number like 1250 come out to 320000. This is easy enough to fix with a while loop, but on the occasion where it receives 0 bytes, not only does it crash the PWM (by passing a frequency of 0) but it will result in creepy offsets for all subsequent serial communications.
Ideas?
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.Netduino;using System.IO.Ports;using System.Text;namespace Chatty{ public class Program { public static SerialPort gooby = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One); public static PWM rawr = new PWM(PWMChannels.PWM_PIN_D10, 1000, 0.5, false); public static OutputPort light = new OutputPort(Pins.ONBOARD_LED, false); public static void Main() { gooby.DataReceived += new SerialDataReceivedEventHandler(on_rec); gooby.Open(); Thread.Sleep(Timeout.Infinite); } public static void on_rec(object sender, SerialDataReceivedEventArgs e) { light.Write(true); Debug.Print("Bytes in buffer: " + gooby.BytesToRead.ToString()); rawr.Stop(); byte[] xmit = new byte[4]; gooby.Read(xmit, 0, 4); int result = 0; for (int i = 0; i < 4; i++) { Debug.Print("Byte " + (i + 1).ToString() + ": " + xmit[i].ToString()); result += ((Int32)(xmit[i]) << (24 - (i * 8))); } while (result > 5000) { result = result >> 8; } Debug.Print("Result: " + result.ToString()); rawr.Frequency = result; rawr.Start(); light.Write(false); } }}