Skip to content

Instantly share code, notes, and snippets.

@mkchandler
Created December 15, 2012 23:41
Show Gist options
  • Save mkchandler/4300971 to your computer and use it in GitHub Desktop.
Save mkchandler/4300971 to your computer and use it in GitHub Desktop.
Some C# code to read a serial port. Using this as a starting point for an Arduino project.
using System;
using System.IO.Ports;
namespace SerialReader
{
class Program
{
static void Main(string[] args)
{
var reader = new ArduinoSerialReader("COM3");
Console.ReadLine();
}
static void ListComPorts()
{
// 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);
}
}
}
public class ArduinoSerialReader : IDisposable
{
private SerialPort _serialPort;
public ArduinoSerialReader(string portName)
{
_serialPort = new SerialPort(portName);
_serialPort.Open();
_serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
Console.WriteLine(_serialPort.ReadLine());
}
public void Dispose()
{
if (_serialPort != null)
{
_serialPort.Dispose();
}
}
}
}
@PabloRoldanCRM
Copy link

thanks bro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment