I am trying to use the DataReceived
event but my method OnDataReceived()
is not able to be called from the method Main()
. I've proven this by adding the line System.Windows.Forms.Application.Exit();
which would effectively close the windows form application; but it does not.
Basically I just want to run the method OnDataReceived
upon receiving data through my serial port. I was hoping to do this with arduino.DataReceived += OnDataReceived;
but it was proven unsuccessful. Feel free to view my comments for guidance. Also I have introduced the string received
and serial port arduino
outside of any method, would this affect the functionality?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
string received;
private SerialPort arduino;
private void button2_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
comboBox1.Items.Add(port);
}
comboBox1.SelectedIndex = 0;
}
private void Main(string port)
{
using (arduino = new SerialPort(port))
{
arduino.Open();
arduino.DtrEnable = true;
arduino.RtsEnable = true;
arduino.BaudRate = 9600;
arduino.DataReceived += OnDataReceived; //when data is received, call method below.
//System.Windows.Forms.Application.Exit(); //this works, which means the above line has been run too.
}
}
private void OnDataReceived(object sender, SerialDataReceivedEventArgs e) //this method does not get called from the above method.
{
System.Windows.Forms.Application.Exit();
received = arduino.ReadLine();
}
public void checkBox1_CheckedChanged(object sender, EventArgs e)
{
Main(comboBox1.Text);
if (checkBox1.Checked)
{
checkBox1.Text = "Listening...";
if (received == "S\r")
{
arduino.Close();
//System.Diagnostics.Process.Start("shutdown", "/f /r /t 0");
//System.Windows.Forms.Application.Exit();
}
}
else
{
checkBox1.Text = "Start";
}
}
}
}