RSS

SerialPort (Com1,2…) Communication in C#

20 Nov

Traditional programming Com1 and Com2 is generally tedious. With DotNet, this becomes trivial. In the toolbox, component tab, drag a SerialPort object onto the form:

SerialPort

   1: static SerialPort ComPort = new SerialPort();

   2: //configuring the serial port

   3: ComPort.PortName = "COM" + iPort.ToString();

   4: ComPort.BaudRate = 9600;

   5: ComPort.DataBits = 8;

   6: ComPort.Parity = Parity.None;

   7: ComPort.StopBits = StopBits.One;

   8:  

   9: //opening the serial port

  10: try

  11: {

  12:     ComPort.Open();

  13:     if (ComPort.IsOpen)     return true;

  14:     else                    return false;

  15: }

  16: catch (System.Exception ex)

  17: {

  18: }

To send the command to the port, use Write(byte [] ,… ) function

   1: static public void StopItNow()

   2: {

   3:             byte [] info=new byte[5];

   4:             info[0] = 64; //@

   5:             info[1] = 48; //0

   6:             info[2] = 255; // 'xff';

   7:             info[3] = 0x0D; //CR;

   8:             info[4] = 0x0A; // LF;

   9:             if (ComPort.IsOpen)

  10:                 ComPort.Write(info,0,5);

  11: }

Or use the Write(string str) method

   1: static public void SetCurPosAsZero(int axis)

   2: {

   3:             Buff = string.Empty;

   4:             SelectAxis(axis);

   5:             Buff += "@0n";

   6:             Buff += axis.ToString() + CR + LF;

   7:             if(ComPort.IsOpen) ComPort.Write(Buff);

   8: }

 
Leave a comment

Posted by on November 20, 2009 in CAD, Dotnet/C#

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: