有很多场景应用到串口操作,比如:地磅、超市收银(串口扫码)、工业机械控制(和PLC的交互、和普通硬件的交互),今天分享一下基础版的串口操作。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Drawing.Printing;
using System.Drawing.Drawing2D;
namespace 串口操作demo2
{
public partial class Form1 : Form
{
private SerialPort ComDevice = new SerialPort();
private delegate void Control_call_back();
// public BarcodeLib.Barcode b1 = new BarcodeLib.Barcode(); //标签打印定义-此处无用
//bool tempControlbool = true;//硬件相关定义-此处无用
//bool tempControlRed = false;//硬件相关定义-此处无用
//bool tempControlGreen = false;//硬件相关定义-此处无用
bool StopGetWeight = false;
/// <summary>
/// 初始化操作
/// </summary>
public Form1()
{
InitializeComponent();
drpComList.Items.AddRange(SerialPort.GetPortNames());
if (drpComList.Items.Count > 0)
{
drpComList.SelectedIndex = 0;
btnCom.Enabled = true;
}
drpBaudRate.SelectedIndex = 5;
drpParity.SelectedIndex = 0;
drpDataBits.SelectedIndex = 0;
drpStopBits.SelectedIndex = 0;
ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived1);
// f.Show();
}
/// <summary>
/// 输出数据-定义委托
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Com_DataReceived1(object sender, SerialDataReceivedEventArgs e)
{
if (!StopGetWeight)
{
// ComDevice.ReadLine();
byte[] ReDatas = new byte[ComDevice.BytesToRead];
ComDevice.Read(ReDatas, 0, ReDatas.Length);//读取数据
DataReceived1(richTextBox1, ReDatas);
Thread.Sleep(100);
}
else//停止
{
if (ComDevice.IsOpen)
ComDevice.Close();
}
}
string tempdata = "";
string[] Data = new string[5];
/// <summary>
/// 数据解析处理
/// 没有控件,数据传输不到前端
/// 本文lock段代码完全可以不用,但是本人操作的数据要以回车作为判断标志输出,所以加此判断
/// </summary>
/// <param name="c">控件</param>
/// <param name="b">数据</param>
public void DataReceived1(Control c, byte[] b)
{
string data = Encoding.Default.GetString(b);
lock (tempdata)
{
if (data.IndexOf("\r") < 0)
{
tempdata = (tempdata + data).Trim();
MessageWrite.WriteMessage(data);
return;
}
else
{
data = tempdata.ToString() + data;
tempdata = "";
}
}
MessageWrite.WriteMessageData(data.Replace("\r", "").Replace("\n", "").Trim());
c.Invoke(new MethodInvoker(delegate
{
richTextBox1.AppendText(data);
richTextBox1.ScrollToCaret();
try
{
data = data.Split('\r')[0];
}
catch (Exception ex)
{
MessageWrite.WriteMessage(data + "\r" + ex.ToString());
}
}));
}
/// <summary>
/// 打开关闭操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCom_Click(object sender, EventArgs e)
{
if (ComDevice.IsOpen == false)
{
try
{
StopGetWeight = false;
ComDevice.PortName = drpComList.SelectedItem.ToString();
ComDevice.BaudRate = Convert.ToInt32(drpBaudRate.SelectedItem.ToString());
ComDevice.Parity = (Parity)Convert.ToInt32(drpParity.SelectedIndex.ToString());
ComDevice.DataBits = Convert.ToInt32(drpDataBits.SelectedItem.ToString());
ComDevice.StopBits = (StopBits)Convert.ToInt32(drpStopBits.SelectedItem.ToString());
ComDevice.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//WriteControl(2, tempControlbool);
btnCom.Text = "关闭串口";
picComStatus.BackgroundImage = Properties.Resources.greenlight;
}
else
{
try
{
ComDevice.Close();
StopGetWeight = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
btnCom.Text = "打开串口";
picComStatus.BackgroundImage = Properties.Resources.redlight;
}
drpComList.Enabled = !ComDevice.IsOpen;
drpBaudRate.Enabled = !ComDevice.IsOpen;
drpParity.Enabled = !ComDevice.IsOpen;
drpDataBits.Enabled = !ComDevice.IsOpen;
drpStopBits.Enabled = !ComDevice.IsOpen;
}
/ <summary>
/ 发送数据
/ </summary>
/ <param name="sender"></param>
/ <param name="data"></param>
public delegate void DataReceive(object sender, byte[] b);
public event DataReceive dr;
/// <summary>
/// 关闭串口
/// </summary>
public void ClearSelf()
{
if (ComDevice.IsOpen)
{
ComDevice.Close();
}
}
SerialPort myPort = new SerialPort();
private void button1_Click(object sender, EventArgs e)
{
//myPort.Close();
//SendData();
}
public static char[] hexDigits = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public static string ToHexString(byte[] bytes)
{
char[] chars = new char[bytes.Length * 3];
for (int i = 0; i < bytes.Length; i++)
{
int b = bytes[i];
chars[i * 3] = hexDigits[b >> 4];
chars[i * 3 + 1] = hexDigits[b & 0xF];
chars[i * 3 + 2] = ' ';
}
return new string(chars);
}
///<summary>
/// 从16进制转换成汉字
/// </summary>
/// <param name="hex"></param>
/// <param name="charset">编码,如"utf-8","gb2312"</param>
/// <returns></returns>
public static string UnHex(string hex, string charset)
{
if (hex == null)
throw new ArgumentNullException("hex");
hex = hex.Replace(",", "");
hex = hex.Replace("\n", "");
hex = hex.Replace("\\", "");
hex = hex.Replace(" ", "");
if (hex.Length % 2 != 0)
{
hex += "20";//空格
}
// 需要将 hex 转换成 byte 数组。
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
try
{
// 每两个字符是一个 byte。
bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
System.Globalization.NumberStyles.HexNumber);
}
catch
{
// Rethrow an exception with custom message.
throw new ArgumentException("hex is not a valid hex number!", "hex");
}
}
System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
return chs.GetString(bytes, 0, bytes.Length).Replace("\0", "");
}
/// <summary>
/// 字符串转16进制字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
private static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
return returnBytes;
}
private void button2_Click(object sender, EventArgs e)
{
//GetWeight();
}
bool tempbool = false;
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (ComDevice.IsOpen)
ComDevice.Close();
}
//-------------------------------------------------
}
}
https://download.csdn.net/download/dapeng2513/11002816