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:
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: }
Posted in CAD, Dotnet/C#
