Hi i’ve got here a simple program, but it’s not working properly.
When i receive ‘A’ on the serial port i set checkbox1, and when ‘a’ i unset checkbox1.
public partial class MainWindow : Window
{
public static SerialPort sp = new SerialPort();
public MainWindow()
{
InitializeComponent();
sp.BaudRate = 2400;
sp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Prijem);
if (!sp.IsOpen)
sp.Open();
}
private delegate void UpdateUiTextDelegate(char text);
private void Prijem(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
char c = (char)sp.ReadChar();
Dispatcher.Invoke(DispatcherPriority.Send,
new UpdateUiTextDelegate(WriteData), c);
}
private void WriteData(char c)
{
if (c == 'A')
{
checkBox1.IsChecked = true;
}
else if (c == 'a')
{
checkBox1.IsChecked = false;
}
}
}
When the
DataReceivedevent is thrown it is not guaranteed how many characters are within the buffer. So if you simply callReadChar()you don’t read the full content of the buffer. So if the characters are send quite fast it would be possible that you miss something, cause your event handler is called when two or more characters are within the buffer.Also you should set ALL serial port properties and not just the baud rate. This is needed cause the serial port has no default state and will remain the last set option for each parameter. So if you use some terminal program to change some lesser used settings (like Xon/off, HW Handshake, StartBits, etc.) your program will simply use the same settings if you don’t reset them to your desired values.