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 Microsoft.Win32;

namespace PotrTEST
{
public partial class Form1 : Form
{
public SerialPort com = new SerialPort();
//定义端口类
private SerialPort ComDevice = new SerialPort();
public Form1()
{
InitializeComponent();
InitralConfig(int.Parse(comboBox_BaudRate.Text));
}
/// <summary>
/// 从注册表获取系统串口列表
/// </summary>
public string[] GetComList()
{
RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
string[] sSubKeys = keyCom.GetValueNames();
string[] str = new string[sSubKeys.Length];
for (int i = 0; i < sSubKeys.Length; i++)
{
str[i] = (string)keyCom.GetValue(sSubKeys[i]);
}
return str;
}
/// <summary>
/// 配置初始化
/// </summary>
private void InitralConfig(int btl)
{
Boolean open = false;
string[] coms = GetComList();
for (int i = 0; i < coms.Length; i++)
{
open = false;
if (com.IsOpen)
{
com.Close();
}
comboBox_Port.Items.Add(coms[i]);
}
//向ComDevice.DataReceived(是一个事件)注册一个方法Com_DataReceived,当端口类接收到信息时时会自动调用Com_DataReceived方法
ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);
}
/// <summary>
/// 一旦ComDevice.DataReceived事件发生,就将从串口接收到的数据显示到接收端对话框
/// </summary>
/// <param name="sender"></param>
/// <param name="sender"></param>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//开辟接收缓冲区
byte[] ReDatas = new byte[ComDevice.BytesToRead];
//从串口读取数据
ComDevice.Read(ReDatas, 0, ReDatas.Length);
//实现数据的解码与显示
AddData(ReDatas);
}

/// <summary>
/// 解码过程
/// </summary>
/// <param name="data">串口通信的数据编码方式因串口而异,需要查询串口相关信息以获取</param>
public void AddData(byte[] data)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sb.AppendFormat("{0:x2}" + " ", data[i]);
}
AddContent(sb.ToString());//.ToUpper()
}

/// <summary>
/// 接收端对话框显示消息
/// </summary>
/// <param name="content"></param>
private void AddContent(string content)
{
BeginInvoke(new MethodInvoker(delegate
{
textBox_Receive.AppendText(content);
}));
}
/// <summary>
/// 串口开关
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button_Switch_Click(object sender, EventArgs e)
{
if (comboBox_Port.Items.Count <= 0)
{
MessageBox.Show("未发现可用串口,请检查硬件设备");
return;
}
if (ComDevice.IsOpen == false)
{
//设置串口相关属性
ComDevice.PortName = comboBox_Port.Text;//comboBox_Port.SelectedItem.ToString();
ComDevice.BaudRate = Convert.ToInt32(comboBox_BaudRate.Text);//(comboBox_BaudRate.SelectedItem.ToString());
ComDevice.Parity = (Parity)Convert.ToInt32(comboBox_CheckBits.Text);//(comboBox_CheckBits.SelectedIndex.ToString());
ComDevice.DataBits = Convert.ToInt32(comboBox_DataBits.Text);// (comboBox_DataBits.SelectedItem.ToString());
ComDevice.StopBits = (StopBits)Convert.ToInt32(comboBox_StopBits.Text); //(comboBox_StopBits.SelectedItem.ToString());
try
{
//开启串口
ComDevice.Open();
button_Send.Enabled = true;
button_Switch.Text = "关闭";
//while (true)
{
//接收数据
ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "未能成功开启串口", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
try
{
ComDevice.Close();
button_Send.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "串口关闭错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
button_Switch.Text = "开启";
}
comboBox_Port.Enabled = !ComDevice.IsOpen;
comboBox_BaudRate.Enabled = !ComDevice.IsOpen;
comboBox_DataBits.Enabled = !ComDevice.IsOpen;
comboBox_StopBits.Enabled = !ComDevice.IsOpen;
comboBox_CheckBits.Enabled = !ComDevice.IsOpen;
}
/// <summary>
/// 将消息编码并发送
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button_Send_Click(object sender, EventArgs e)
{
//if (textBox_Receive.Text.Length > 0)
//{
// textBox_Receive.AppendText("\n");
//}

byte[] sendData = null;
//sendData = Encoding.UTF8.GetBytes(textBox_Receive.Text);
sendData = Hex16StringToHex16Byte(textBox_Receive.Text);
SendData(sendData);
}
/// <summary>
/// 此方法用于将16进制的字符串转换成16进制的字节数组
/// </summary>
/// <param name="_hex16ToString">要转换的16进制的字符串。</param>
public static byte[] Hex16StringToHex16Byte(string _hex16String)
{
//去掉字符串中的空格。
_hex16String = _hex16String.Replace(" ", "");
if (_hex16String.Length / 2 == 0)
{
_hex16String += " ";
}
//声明一个字节数组,其长度等于字符串长度的一半。
byte[] buffer = new byte[_hex16String.Length / 2];
for (int i = 0; i < buffer.Length; i++)
{
//为字节数组的元素赋值。
buffer[i] = Convert.ToByte((_hex16String.Substring(i * 2, 2)), 16);
}
//返回字节数组。
return buffer;
}
/// <summary>
/// 此函数将编码后的消息传递给串口
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public bool SendData(byte[] data)
{
if (ComDevice.IsOpen)
{
try
{
//将消息传递给串口
ComDevice.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;
}

/// <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 Form1_Load(object sender, EventArgs e)
{
//button_Send.PerformClick();
}
//以下两个指令是结合一款继电器而设计的
//private void button_On_Click(object sender, EventArgs e)
//{
// textBox_Send.Text = "005A540001010000B0";
//}

//private void button_Off_Click(object sender, EventArgs e)
//{
// textBox_Send.Text = "005A540002010000B1";
//}
}
}

C#串口数据收发数据的更多相关文章

  1. Arduino通过串口监视器收发数据

    在串口监视器中发送数据,板子收到数据并打印出来. 不需要额外电路,但是板子必须连接电脑,Arduino IDE的串口监视器也需要被打开. 代码 /* 串口事件 当新的串口数据到来时,我们会将它添加到一 ...

  2. 【AT91SAM3S】串口UART初始化及收发数据

    SAM3S中的UART串口是一个两线异步收发器.这个串口能用来通信或者跟踪.有两个DMA通道与UART串口关联,可通过使用DMA处理串口传输以节省CPU时间. SAM3S4C中有两个UART.与外设引 ...

  3. STM32F407的串口采用DMA收发数据

    源:STM32F407的串口采用DMA收发数据

  4. python 简单的串口收发数据

    # -*- coding: utf- -*- import serial #打开串口 serialPort="COM3" #串口 baudRate= #波特率 ser=serial ...

  5. Java 实现TCP/IP协议的收发数据(服务端)

    功能如下: 注: 只有服务端,没有客户端,测试时采用第三方软件作为客户端的. 收发数据目前能正常收发数据,只是中文的会变成乱码显示. 采用Thread类实现一个收发数据的线程. 服务端代码: impo ...

  6. C#串口通信及数据表格存储

    1.开发环境 系统:win10 开发工具:Visual Studio 2017 2.界面设计 串口通信的界面大致如此,在此基础上添加项目所需的调试指令与数据存储功能,界面排布方面可参考其他教程. 3. ...

  7. HAL UART DMA 数据收发

    UART使用DMA进行数据收发,实现功能,串口2发送指令到上位机,上位机返回数据给串口2,串口2收到数据后由串口1进行转发,该功能为实验功能 1.UART与DMA通道进行绑定 void HAL_UAR ...

  8. STM32与物联网02-网络数据收发

    在上一节中,介绍了 ESP8266 的使用方法.不过上一节中都是通过串口调试工具手动发送信息的方式来操作 ESP8266 ,这肯定不能用于实际开发.因此,本节介绍如何编写合适的程序来和 ESP8266 ...

  9. 在Linux中如何使用命令进行RS-232串口通信和数据包解析

    文章首发于浩瀚先森博客 1. 获取串口号 在Linux系统中一切皆为文件,所以串口端口号也不例外,都是以设备文件的形式出现.也就是说我们可以用访问文本文件的命令来访问它们. a. 一般串口都是以/de ...

随机推荐

  1. MPU9250九轴陀螺仪--读接口数据

    1.使用i2c链接到树莓派的scl , sda 接口vcc给3v引脚,gnd接树莓派gnd就ok. 2.要操作mpu必须使用mpu的寄存器实现对参数的设定以及读取,取官方下载资料看了一下,在githu ...

  2. 使用 random() 生成礼包码

    需求:生成100个游戏礼包码 具体如下 # 1.构造100个5位随机数 listNumA = [] for n in range(100): listNumA.append(random.randin ...

  3. JRockit检测Tomcat内存溢出JAVA内存泄漏问题

    http://blog.csdn.net/liyanhui1001/article/details/8240473 公司的一个Java应用系统上线以来,基本每1天OutOfMemoryError: P ...

  4. 黄聪:C#中CefSharp的简单使用

    C#中CefSharp的简单使用 https://blog.csdn.net/qq_26712977/article/details/78282995

  5. 工控随笔_03_西门子_Step7项目打开后CPU显示问号解决方法

    我们在利用西门子的S7-300/400 PLC的编程软件Step7的时候会出现下面如图所示的问题. 在打开项目的时候,我们会在Simatic Manager里面看到CPU以及一些其他一些组件显示问号. ...

  6. sql 查询结果自定义排序

    sqlserver 使用case when then 语句来实现 select name from fruit order by case name end oracle 使用decode实现 ,,, ...

  7. Linux(CentOS)用户修改密码有效期(chage命令)

    Linux设置用户密码的有效期限 解决: 先查看密码过期时间,现在是90天 1 2 3 4 5 6 7 8 [root@01 ~]# chage -l testuser Last password c ...

  8. Bootstrap treeview增加或者删除节点

    参考(AddNode: http://blog.csdn.net/qq_25628235/article/details/51719917,deleteNode:http://blog.csdn.ne ...

  9. python3 数独

    数独 最近在网上看到数独,感觉非常有意思,所以就来实现以下. 一个数独题的网站(https://www.oubk.com/DailySudoku/17778/1),偷懒直接爬虫抓下来了,哈哈 代码实现 ...

  10. docker:学习笔记

    docker run -itd --net=none 22565cef72c2 /usr/sbin/sshd -Dpipework br0 5a3e7bab4c5c5260a93e153aa7fec3 ...