Send serial data:
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using system. Io. ports;
Namespace senddata
{
Class Program
{
Static void main (string [] ARGs)
{
SerialPort Port = new SerialPort ();
Console. writeline ("Serial Port (such as COM1 ):");
Port. portname = console. Readline ();
Console. writeline ("baud rate :");
Port. baudrate = convert. toint32 (console. Readline ());
Console. writeline ("Data bit :");
Port. databits = convert. toint32 (console. Readline ());
Int stopbits = 0;
Console. writeline ("Stop bit :");
Stopbits = convert. toint32 (console. Readline ());
Switch (stopbits)
{
Case 0:
Port. stopbits = stopbits. None;
Break;
Case 1:
Port. stopbits = stopbits. One;
Break;
Case 2:
Port. stopbits = stopbits. Two;
Break;
Default:
Port. stopbits = stopbits. None;
Break;
}
Try
{
Port. open ();
String senddata = "";
Bool exitflag = false;
While (exitflag = false)
{
Console. writeline ("data to be sent :");
Senddata = console. Readline ();
If (senddata. compareto ("exit") = 0)
Break;
Else
Port. writeline (senddata );
}
Port. Close ();
}
Catch (exception E)
{
Console. writeline (E. Message );
Console. Readline ();
}
}
}
}
Accept serial data:
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using system. Io. ports;
Namespace recvdata
{
Class Program
{
Static void main (string [] ARGs)
{
SerialPort Port = new SerialPort ();
Console. writeline ("Serial Port (such as COM1 ):");
Port. portname = console. Readline ();
Console. writeline ("baud rate :");
Port. baudrate = convert. toint32 (console. Readline ());
Console. writeline ("Data bit :");
Port. databits = convert. toint32 (console. Readline ());
Int stopbits = 0;
Console. writeline ("Stop bit :");
Stopbits = convert. toint32 (console. Readline ());
Switch (stopbits)
{
Case 0:
Port. stopbits = stopbits. None;
Break;
Case 1:
Port. stopbits = stopbits. One;
Break;
Case 2:
Port. stopbits = stopbits. Two;
Break;
Default:
Port. stopbits = stopbits. None;
Break;
}
Try
{
Port. open ();
Bool exitflag = false;
Int n = 0;
While (exitflag = false)
{
Console. writeline (port. Readline ());
N ++;
If (n = 999999)
{
Console. writeline ("continue? (Y/s )");
String ans = console. Readline ();
If (ANS. compareto ("Y") = 0)
Exitflag = true;
Else
N = 0;
}
}
Port. Close ();
}
Catch (exception E)
{
Console. writeline (E. Message );
Console. Readline ();
}
}
}
}