资源简介
C#串口通讯上位机源码(打包为7z格式),源码为Visual Studio的C#工程,非常适合想通过C#编写上位机的初学者参考学习。代码包含串口上位机的基本功能,如可用串口检测、收发字符和Hex数据、保存上次使用的串口号、收发数据量记录等。此代码为本人学习C#时编写的,参考了他人的教程,并在其基础上加以改进。此工程源码可二次开发,添加代码扩展为你需要的串口上位机。
代码片段和文件信息
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Runtime.InteropServices;
namespace Serial_Communicate
{
public partial class Form1 : Form
{
int Received_Data_Cnt = 0 Transmit_Data_Cnt=0;
string CurrentPortName;
[DllImport(“kernel32“)]
private static extern long WritePrivateProfileString(string section string key string val string filePath);//系统dll导入ini写函数
[DllImport(“kernel32“)]
private static extern int GetPrivateProfileString(string section string key string def StringBuilder retVal int size string filePath);//系统dll导入ini读函数
string FileName = System.AppDomain.CurrentDomain.baseDirectory + “data.ini“;//ini文件名
StringBuilder temp = new StringBuilder(255);//存储读出ini内容变量
public Form1()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
serialPort1.Encoding = Encoding.GetEncoding(“GB2312“);//加入汉字支持
}
private void Form1_Load(object sender EventArgs e)
{
SearchAndAddSerialToComboBox(serialPort1 comboBox1);//查找可用串口
comboBox2.Text = “115200“;
serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);//串口事件处理程序声明
GetPrivateProfileString(“PortData“ “PortName“ “COM1“ temp 256 FileName);//读取ini值,默认是COM1
comboBox1.Text = temp.ToString();//初始化
}
private void port_DataReceived(object sender SerialDataReceivedEventArgs e)//串口数据接收事件
{
Received_Data_Cnt += serialPort1.BytesToRead;//记录接收字节数
Received_Data_Cnt = Received_Data_Cnt > 9999 ? 9999 : Received_Data_Cnt;//限幅
label5.Text = “RX:“+Received_Data_Cnt.ToString();//显示到lable中
if (!radioButton3.Checked)//接收模式为接收字符
{
textBox1.AppendText(serialPort1.ReadExisting()+“ “); //将读取到的字符串添加到窗口显示
}
else//接收模式为接收数值
{
byte[] data = new byte[serialPort1.BytesToRead];//定义缓冲区,串口事件触发时有可能收到不止一个字节
serialPort1.Read(data 0 data.Length);
foreach (byte Member in data)//遍历用法
{
string str = Convert.ToString(Member16).ToUpper();//转换为大写16进制字符串
textBox1.AppendText(“0x“ + (str.Length == 1 ? “0“ + str : str) + “ “);
}
}
}
private void button1_Click(object sender EventArgs e)//打开串口
{
if (!serialPort1.IsOpen)//串口未开
{
try
{
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text 10);//串口波特率设置
serialPort1.PortName = comboBox1.Text;/
评论
共有 条评论