I have had luck writing serial data from a PIC microcontroller to a textbox using the following code in C#:
private void serialPort1_DataReceived_1(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
txtToDisplay = serialPort1.ReadExisting();
DisplayText();
}
public void DisplayText()
{
if (txtIn.InvokeRequired)
{
this.BeginInvoke(new MethodInvoker(DisplayText));
}
else
{
txtIn.AppendText(txtToDisplay);
}
}
Also, I set the comm port parameters in the same place I open the port, rather than the receive event:
private void GetComPorts() //populate the comm port list with the available system ports
{
foreach (string s in SerialPort.GetPortNames() )
{
lbPort.Items.Add(s);
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
this.lbPort.SelectedIndex = this.lbPort.TopIndex; // which port?
this.lbRate.SelectedIndex = this.lbRate.TopIndex; // baud rate?
this.lbProtocol.SelectedIndex = this.lbProtocol.TopIndex; // N,8,1 or N,7,1 (strings in a collection)
string crlf = Environment.NewLine; // this might be the real trick...
serialPort1.BaudRate = Int32.Parse(lbRate.Text);
serialPort1.PortName = lbPort.Text;
serialPort1.Open();
if (serialPort1.IsOpen)
{
btnOpen.Enabled = false;
btnClose.Enabled = true;
txtIn.AppendText(string.Format("Port {0} opened successfully." + crlf, serialPort1.PortName));
}
}
Anyway, this seems to work in my situation. Also, my PIC code is using "\r\n" so I am actually sending a {10} and a {13} pair. Hope this helps, Adam