资源简介
串口读取电子秤的重量
代码片段和文件信息
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SerialPortDemo
{
public partial class Form1 : Form
{
private SerialPort com;
public Form1()
{
InitializeComponent();
}
private void GetAutoCom()
{
//获取本地配置文件(注册表文件)
Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine;
//读取HARDWARE节点的键值
Microsoft.Win32.RegistryKey software11 = hklm.OpenSubKey(“HARDWARE“);
//打开“HARDWARE“子键
Microsoft.Win32.RegistryKey software = software11.OpenSubKey(“DEVICEMAP“);
Microsoft.Win32.RegistryKey sitekey = software.OpenSubKey(“SERIALCOMM“);
//获取当前子键
string[] Str2 = sitekey.GetValueNames();
//获得当前子键存在的键值
int i;
for (i = 0; i < Str2.Count(); i++)
{
cmbCOMPort.Items.Add(sitekey.GetValue(Str2[i]));
}
}
private void Form1_Load(object sender EventArgs e)
{
GetAutoCom();
com = new SerialPort(cmbCOMPort.Text); //实例化SerialPort并设置COM口
com.BaudRate = 9600;//波特率
com.Parity = Parity.None;//无奇偶校验位
com.StopBits = StopBits.Two;//两个停止位
com.Handshake = Handshake.RequestToSend;//控制协议
com.ReceivedBytesThreshold = 13;//设置 DataReceived 事件发生前内部输入缓冲区中的字节数我这里是13字节为一组
com.Open(); //打开串口
com.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);
}
///
/// 监听串口数据线程
///
///
///
private void Com_DataReceived(object sender SerialDataReceivedEventArgs e)
{
Thread.Sleep(500);//线程休眠500毫秒,方便接收串口的全部数据
try
{
if (com.IsOpen)
{
byte[] readBuffer = new byte[com.ReadBufferSize + 1];
try
{
int count = com.Read(readBuffer 0 com.ReadBufferSize); //读取串口数据(监听)
String SerialIn = System.Text.Encoding.ASCII.GetString(readBuffer 0 count);//将字节数组解码为字符串
if (count != 0)
{
//这里强调一下线程里不可以直接对UI进行赋值,只能使用委托操作控件
this.BeginInvoke(new System.Threading.ThreadStart(delegate ()
{
richTextBox1.Text = SerialIn;
}));
}
}
评论
共有 条评论