Created
December 15, 2012 23:41
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks bro