Instantly share code, notes, and snippets.

anonymous /SerialReader Secret
Created Jan 13, 2017

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;
namespace WindowsFormsApplication24
{
public partial class Form1 : Form
{
SerialPort serialPort;
private Action startReading;
int bufferLength = 1024;
string data;
//Decoder utf8Decoder = Encoding.UTF8.GetDecoder();
public Form1()
{
InitializeComponent();
textBox1.ScrollBars = ScrollBars.Vertical;
textBox1.WordWrap = false;
}
public bool Open()
{
serialPort = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
bool result = false;
try
{
this.serialPort.Open();
result = true;
startReading = StartAsyncSerialReading;
startReading();
}
catch (Exception)
{
this.Close();
result = false;
}
return result;
}
private void StartAsyncSerialReading()
{
byte[] buffer = new byte[bufferLength];
serialPort.BaseStream.BeginRead(buffer, 0, bufferLength, delegate (IAsyncResult ar)
{
try
{
if (serialPort.IsOpen)
{
int actualLength = serialPort.BaseStream.EndRead(ar);
byte[] received = new byte[actualLength];
Buffer.BlockCopy(buffer, 0, received, 0, actualLength);
data += Encoding.ASCII.GetString(received, 0, actualLength);
while (data.Contains("\n"))
{
string message = data.Substring(0, data.IndexOf("\n"));
textBox1.Invoke(new Action(delegate ()
{
textBox1.AppendText(message+"\n");
}));
data = data.Substring(data.IndexOf("\n") + 1);
}
}
}
catch (IOException exc)
{
//handleAppSerialError(exc);
}
if (serialPort.IsOpen)
startReading();
}, null);
}
public void Dispose()
{
serialPort.Dispose();
GC.SuppressFinalize(this);
}
public void ClosePort()
{
serialPort.BaseStream.Flush();
serialPort.BaseStream.Close();
this.serialPort.Close();
this.Dispose();
data = null;
textBox1.AppendText("\n");
}
private void button2_Click(object sender, EventArgs e)
{
ClosePort();
}
private void button1_Click(object sender, EventArgs e)
{
data = null;
Open();
StartAsyncSerialReading();
}
private void ClearButton_Click(object sender, EventArgs e)
{
textBox1.Text = String.Empty;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment