The C# langauge and the embedded processors that can harness the programs created by it are growing every year. This post will teach making a simple serial program.
The first thing we need to do is create a serial port using the code below.
SerialPort serialport = new SerialPort(); //Declare the serial port object.
The code below shows how to fill combo boxes with the possible selections for each of the settings required to create a serial port.
//Get Serial Port Names foreach (string serialname in SerialPort.GetPortNames()) { cmbSerialPort.Items.Add(serialname); } if (cmbSerialPort.Items.Count > 0) cmbSerialPort.SelectedIndex = 0; //Tie Enum Types to combo boxes for selection. cmbStopBits.DataSource = Enum.GetValues(typeof(StopBits)); cmbParity.DataSource = Enum.GetValues(typeof(Parity)); //Put all the Possible Baud rates into the combo box for selection. cmbBaud.Items.Add("1200"); cmbBaud.Items.Add("2400"); cmbBaud.Items.Add("4800"); cmbBaud.Items.Add("9600"); cmbBaud.Items.Add("19200"); cmbBaud.Items.Add("38400"); cmbBaud.Items.Add("57600"); cmbBaud.Items.Add("115200"); cmbBaud.Items.Add("230400"); cmbBaud.SelectedIndex = 3; //Set all the possible data bit values. cmbDataBits.Items.Add("4"); cmbDataBits.Items.Add("5"); cmbDataBits.Items.Add("6"); cmbDataBits.Items.Add("7"); cmbDataBits.Items.Add("8"); cmbDataBits.SelectedIndex = 4;
To create the serial port we need to set several variables.
//Set the minimum values we need to create a link serialport.PortName = cmbSerialPort.SelectedItem.ToString(); serialport.BaudRate = Convert.ToInt16(cmbBaud.SelectedItem); serialport.DataBits = Convert.ToInt16(cmbDataBits.SelectedItem); serialport.Parity = (Parity)cmbParity.SelectedItem; serialport.StopBits = (StopBits)cmbStopBits.SelectedItem; //Open the Serial Port serialport.Open();
The next thing we need to do is set up an event handler so we can catch
when new information is transmitted to us.
serialport.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
Since the event handler does not come back on the same thread as the UI
we need to invoke and delegate the information to our UI thread for
displaying.
rtbReceived.Invoke(new EventHandler(delegate { rtbReceived.AppendText(serialport.ReadExisting()); }));
To send data over the serial link all we need to do is
call the WriteLine method. The serial port also allows for sending
character or byte strings.
serialport.WriteLine(rtbSend.Text);
Putting the parts learned here together I created a simple serial
communication program that sends text from one computer to another.
This is a perfect start to developing communication between computers
and components. With a few changes to the above code you can send data
in byte streams specific to your needs or stay in Ascii characters and
make your communication easy for humans to read and interpret. Have fun
with your newly learned skills.