基本信息
源码名称:串口通信程序源码(入门级)
源码大小:0.06M
文件格式:.rar
开发语言:C#
更新时间:2019-08-23
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 15 元×
微信扫码支付:15 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
串口调试
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;
namespace PowerControl
{
public partial class Fm_Main : Form
{
private SerialPort comm = new SerialPort();
//可变字符串类,用于存储接收到的字符
private StringBuilder Builder = new StringBuilder();
public Fm_Main()
{
InitializeComponent();
}
private void Fm_Main_Load(object sender, EventArgs e)
{
init();
comm.NewLine = "\r\n";
comm.RtsEnable = true;
}
public void init()
{
btn_Send.Enabled = false;
cbbComList.Items.AddRange(SerialPort.GetPortNames());
if (cbbComList.Items.Count > 0)
{
cbbComList.SelectedIndex = 0;
}
cbbBaudRate.SelectedIndex = 6;
cbbDataBits.SelectedIndex = 0;
cbbStopBits.SelectedIndex = 0;
cbbParity.SelectedIndex = 0;
comm.DataReceived = new SerialDataReceivedEventHandler(Com_DataReceived);//绑定事件
}
void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int n = comm.BytesToRead;
byte[] buf = new byte[n];
comm.Read(buf, 0, n);
//先清空
Builder.Clear();
//因为要访问ui资源,所以需要使用invoke方式同步ui
this.Invoke((EventHandler)(delegate
{
Builder.Append(Encoding.ASCII.GetString(buf));
this.txGet.AppendText(Builder.ToString());
}));
}
private void btn_Open_Click(object sender, EventArgs e)
{
//如果串口已经是打开状态,则此按钮关闭串口
if (this.comm.IsOpen)
{
this.comm.Close();
btn_Send.Enabled = false;
}
//串口关闭状态,打开之
else
{
comm.PortName = this.cbbComList.Text;
comm.BaudRate = int.Parse(this.cbbBaudRate.Text);
comm.Parity = (Parity)Convert.ToInt32(cbbParity.SelectedIndex.ToString());
comm.DataBits = Convert.ToInt32(cbbDataBits.SelectedItem.ToString());
comm.StopBits = (StopBits)Convert.ToInt32(cbbStopBits.SelectedItem.ToString());
try
{
comm.Open();
}
catch (Exception ex)
{
comm = new SerialPort();
MessageBox.Show(ex.Message);
}
}
this.btn_Open.Text = comm.IsOpen ? "关闭串口" : "打开串口";
this.btn_Send.Enabled = comm.IsOpen;
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="sender"></param>
/// <param name="data"></param>
public bool SendData(byte[] data)
{
if (comm.IsOpen)
{
try
{
comm.Write(data, 0, data.Length);//发送数据
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("串口未打开", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
private void btn_Send_Click(object sender, EventArgs e)
{
comm.Write(this.txSend.Text);
byte[] sendData = null;
sendData = strToHexByte(txSend.Text.Trim());
if (this.SendData(sendData)) //发送数据成功计数
{
}
}
/// <summary>
/// 字符串转换16进制字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
private byte[] strToHexByte(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).Replace(" ", ""), 16);
return returnBytes;
}
private void txGet_TextChanged(object sender, EventArgs e)
{
}
//public Form1()
//{
// InitializeComponent();
// serialPort1.DataReceived = new SerialDataReceivedEventHandler(port_DataReceived); //串口数据接收事件
// serialPort1.Encoding = Encoding.GetEncoding("GB2312"); //串口接收编码
// System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
//}
//private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) //串口接收事件
//{
// if (!radioButton3.Checked)
// {
// txGet.AppendText(comm.ReadExisting()); //串口类会自动处理汉字,所以不需要特别转换
// }
// else
// {
// byte[] data = new byte[comm.BytesToRead]; //定义缓冲区,因为串口事件触发时有可能收到不止一个字节
// comm.Read(data, 0, data.Length);
// foreach (byte Member in data) //遍历用法
// {
// string str = Convert.ToString(Member, 16).ToUpper();
// txGet.AppendText("" (str.Length == 1 ? "0" str : str) " ");
// }
// }
//}
private void txSend_TextChanged(object sender, EventArgs e)
{
}
private void cbbDataBits_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void cbbBaudRate_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void cbbComList_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}