serial port - C#: DataReceived Event handler for serialPort not firing -
i'm writing basic application, 1 of tasks communicating arduino uno card.
write serial communication separate module, forms calls input arduino, , module handle creating , opening of serialport , reading data it.
testing purposes wrote program arduino prints elapsed milliseconds every half second serialport.
populate textbox of form output arduino after press button.
create serialport in serialcomm class, , although attach datareceived event handler it, never seems fire.
here code serialcomm class:
class serialcomm { private list<string> availableports; private serialport arduino; private string receivedtext; public string[] portlist { { enumports(); return availableports.toarray(); } } public string receiveddata { { return receivedtext; } } public void initialiseserial() { arduino = new serialport(); arduino.baudrate = 9600; arduino.dtrenable = true; // add event handler arduino.datareceived += new serialdatareceivedeventhandler(arduino_datareceived); } public void enumports() { availableports = new list<string>(); foreach (string s in serialport.getportnames()) { availableports.add(s); } } public void startmc(serialport serialport, string portname) { arduino = serialport; if (arduino.isopen) { arduino.close(); } else { //initialise serial port arduino.portname = portname; arduino.open(); } } //this never fires================== private void arduino_datareceived(object sender, serialdatareceivedeventargs e) { receivedtext = arduino.readexisting(); } public void closemc() { if (arduino.isopen) { arduino.close(); arduino.dispose(); } } }
in form call text arduino this: (i have button (button1), combobox selecting com port (combobox1) , textbox on form)
public partial class form1 : form { serialcomm arduino = new serialcomm(); public form1() { initializecomponent(); } private void form1_load(object sender, eventargs e) { //arduino arduino.initialiseserial(); string[] portlist = arduino.portlist; foreach (string com in portlist) { combobox1.items.add(com); } if (portlist.length > 0) { combobox1.selecteditem = combobox1.items[0]; } else { combobox1.text = "no microcontroller found!"; } } private void button1_click(object sender, eventargs e) { arduino.startmc(serialport1, combobox1.selecteditem.tostring()); //as datareceived never fires arduino.receiveddata stays null if (arduino.receiveddata != null) { (int = 0; < 101; i++) { textbox1.appendtext(arduino.receiveddata); } } } private void form1_formclosing(object sender, formclosingeventargs e) { arduino.closemc(); } }
do see reason why event handler doesn't trigger? thank in advance.
best regards, peter
Comments
Post a Comment