Skip to content

Instantly share code, notes, and snippets.

@kzkamiya
Created June 22, 2020 14:44
Show Gist options
  • Save kzkamiya/c9e85213b3bfecb10a3a7d462be78e40 to your computer and use it in GitHub Desktop.
Save kzkamiya/c9e85213b3bfecb10a3a7d462be78e40 to your computer and use it in GitHub Desktop.
hello_serialport
using System;
using System.IO.Ports;
using System.Threading;
using System.Threading.Tasks;
namespace hello_serialport
{
//
// /dev/ttyS0
// /dev/ttySUB0
//
class Program
{
// Create a new SerialPort object with default settings.
private static SerialPort _serialPort1 = new SerialPort()
{
PortName = "/dev/ttyUSB0"
,
BaudRate = 115200
,
Parity = Parity.None
,
DataBits = 8
,
StopBits = StopBits.One
,
Handshake = Handshake.None
,
ReadTimeout = 500
,
WriteTimeout = 500
};
private static SerialPort _serialPort2 = new SerialPort()
{
PortName = "/dev/ttyS0"
,
BaudRate = 115200
,
Parity = Parity.None
,
DataBits = 8
,
StopBits = StopBits.One
,
Handshake = Handshake.None
,
ReadTimeout = 500
,
WriteTimeout = 500
};
private static bool _continue1 = false;
private static bool _continue2 = false;
static void Main(string[] args)
{
// Get a list of serial port names.
string[] ports = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
// Display each port name to the console.
foreach (string port in ports)
{
Console.WriteLine(port);
}
Console.ReadLine();
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread1 = new Thread(Read1);
_serialPort1.Open();
_continue1 = true;
readThread1.Start();
Thread readThread2 = new Thread(Read2);
_serialPort2.Open();
_continue2 = true;
readThread2.Start();
Console.Write("Name: ");
name = Console.ReadLine();
Console.WriteLine("Type QUIT to exit");
while (_continue1)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue1 = false;
}
else
{
_serialPort1.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread1.Join();
_serialPort1.Close();
readThread2.Join();
_serialPort2.Close();
}
public static void Read1()
{
while (_continue1)
{
try
{
string message = _serialPort1.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
public static void Read2()
{
while (_continue2)
{
try
{
string message = _serialPort2.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment