Update: I get An unhandled exception of type 'System.TimeoutException' occurred in System.dll error for the sp2.ReadLine();
This program uses C# as an interface for an Arduino Serial Monitor. Sending an initiation command to the arduino from the C# interface does nothing for the first time. The Arduino sends back its output only after restarting the C# program.
So my process looks likes this: Run C# program -> send input to arduino -> nothing happens -> Stop the Program -> Run C# program again -> send input -> get result.
I think the issue lies within the DataRecievedEventHandler method.
Specifically:
private void DataReceivedHandler2(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp2 = (SerialPort)sender;
String write = sp2.ReadLine(); <-- Error for this line
if (write != String.Empty)
{
Invoke(new Action(() => textBox2.AppendText(write)));
}
}
Couldn't find many relevant threads online.
Here's the rest of my code:
private void search_btn1_Click(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
ports_txt1.Items.Add(port);
}
}
string t;
private void start_btn1_Click(object sender, EventArgs e)
{
t = ports_txt1.Text.ToString();
serial(t);
}
SerialPort sp;
void serial(string port_name)
{
sp = new SerialPort(port_name, 9600, Parity.None, 8, StopBits.One);
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
sp.Open();
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string write = sp.ReadLine();
if (write != string.Empty)
{
Invoke(new Action(() => display_txt.AppendText(write)));
}
}
private void id_btn1_Click(object sender, EventArgs e)
{
string findID = display_txt.Text;
string decID = findID;
int indexOfFirstPhrase = findID.IndexOf("In dec: ");
if (indexOfFirstPhrase >= 0)
{
indexOfFirstPhrase += "In dec: ".Length;
int indexOfSecondPhrase = findID.IndexOf(" PICC", indexOfFirstPhrase);
if (indexOfSecondPhrase >= 0)
decID = findID.Substring(indexOfFirstPhrase, indexOfSecondPhrase - indexOfFirstPhrase);
else
decID = findID.Substring(indexOfFirstPhrase);
MessageBox.Show(decID);
string cardID = decID.Replace(" ", String.Empty); //Remove the spaces for the RFID ID code
long intID = Int64.Parse(cardID); //Parse to Int
if (intID == 9615987126) //Identify Each Card
{
MessageBox.Show("Welcome Card No.1");
}
if (intID == 104382516)
{
MessageBox.Show("Welcome Card No.2");
}