I have simple serial port program that is supposed to read the serial port and echo back the characters typed. I can get this to work fine by polling the serial recieved with a timer, but I’d like to use the dataReceived event instead. For some reason the event will occur once but never again.
SerialPort bsp;
public Form1()
{
InitializeComponent();
bsp = new SerialPort("COM2", 2400, Parity.None, 8, StopBits.One);
bsp.DataReceived +=new SerialDataReceivedEventHandler(whasup);
System.Threading.Thread.Sleep(1000);
bsp.Open();
}
void whasup(object sender, SerialDataReceivedEventArgs e)
{
char[] text = new char[100];
int temp = bsp.BytesToRead;
string j = temp.ToString();
bsp.Read(text, 0, temp);
bsp.Write(text, 0, temp);
}
I’ve tried porting this to a PC and it works great, but on this Windows CE device it really doesn’t want to cooperate. I know the serial object is still open because i’ve had a timer running spitting text out of the Win CE device even after it stop echoing back its receive data. I also had the timer output bsp.BytesToRead, and I could see that value climb as I typed more keys in on my PC that talked serially to the Windows CE device. Am I missing something?
We suffered similar problems with
Read()but managed it withReadExisting()instead, to always read the whole buffer. It may be this fact that allows the next event to be raised.The
Sleep(500)was included because the event is raised as soon as the first byte is written to the buffer. Through some trial/error and in the knowledge that the messages we were reading never exceeded a particular length, we knew they’d be fully written within (and in fact long before) 500ms of the event.A bit hit/miss and I’d be more than happy to see a ‘correct’ solution from a serial expert!
The code: