Tuesday, June 24, 2008

Opening a serial port in C#

Just a quick tutorial, I was trying to communicate with my LCD in C# and heres the gist of how i got it up and running:

Use the Header using System.IO.Ports; we create an object using the name serial_port which looks like:
SerialPort serial_port = new SerialPort("COM7", 9600, Parity.None, 8, StopBits.One);

Here we specify the required vars - Com port name, Baud rate, Parity bit, Data bits and stop bits. Now we simply open the com port serial_port.Open(); and this allows us to read/write from the selected port. For my purposes I used write commands so as to write data to my external LCD screen. Keep in mind the write command accepts only strings so I had to improvise as I was sending it a integer value.
serial_port.Write( i.ToString() );
where 'i' is the integer I am sending accross the COM7 port.

No comments: