COM Port in Visual C# 2005
-
There's a new possibility in the System.IO that is accesing to Port Coms: System.IO.Ports, I'm not good with delegates and I'm trying to make a program that when receives a data from the serial port makes an event:
private void Form1_Load(object sender, EventArgs e) { ptocom.ReceivedEvent +=new SerialReceivedEventHandler(ptocom_ReceivedEvent); //It's not complete but I dont know how to put it well } void ptocom_ReceivedEvent(object sender, SerialReceivedEventArgs e) { //Type tipo; ? //tipo = e.EventType.GetType(); ? //taken.Text = tipo.ToString(); ? //taken.Text = buffer; //throw new NotImplementedException(); <-thats appear automatic ? } private void button1_Click(object sender, EventArgs e) { SerialPort ptocom = new SerialPort("COM1", 9600, System.IO.Ports.Parity.None, 8, StopBits.One); string buffer = "j"; ptocom.Open(); ptocom.ReadTo(buffer); }
Thats all I could discover about using this new possibilities but It doesnt work, any Idea? Juan Pablo García Coello. Electronic Engineer. Projectist at the Electronic Dept.Instituto de Astrofísica de Canarias. Spain -
There's a new possibility in the System.IO that is accesing to Port Coms: System.IO.Ports, I'm not good with delegates and I'm trying to make a program that when receives a data from the serial port makes an event:
private void Form1_Load(object sender, EventArgs e) { ptocom.ReceivedEvent +=new SerialReceivedEventHandler(ptocom_ReceivedEvent); //It's not complete but I dont know how to put it well } void ptocom_ReceivedEvent(object sender, SerialReceivedEventArgs e) { //Type tipo; ? //tipo = e.EventType.GetType(); ? //taken.Text = tipo.ToString(); ? //taken.Text = buffer; //throw new NotImplementedException(); <-thats appear automatic ? } private void button1_Click(object sender, EventArgs e) { SerialPort ptocom = new SerialPort("COM1", 9600, System.IO.Ports.Parity.None, 8, StopBits.One); string buffer = "j"; ptocom.Open(); ptocom.ReadTo(buffer); }
Thats all I could discover about using this new possibilities but It doesnt work, any Idea? Juan Pablo García Coello. Electronic Engineer. Projectist at the Electronic Dept.Instituto de Astrofísica de Canarias. SpainI think your problem is, that you subscribe your event handler during the handling of the
Form.Load
event, but theSerialPort
object isn't created until button1_Click gets called or more likely is newly created there, cause otherwise the handler subscription would crash with null reference exception. So your event handler isn't subscribed to theSerialPort
object you create in click event handler and therefor doesn't fire, but to some instance created before theForm.Load
event.