C#串口中文GBK或UTF-8正常 串口类助手源码 接收单片机整条数据

在串口初始化中设置编码方式:

mycomm.Encoding = System.Text.Encoding.GetEncoding("UTF-8");//根据实际情况选择UTF-8还是GB2312
 

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.Windows.Forms.DataVisualization.Charting;
using System.Drawing.Drawing2D;
using SerialCommDemo.Properties;
using System.Threading;
namespace SerialCommDemo
{public partial class Form1 : Form{//public string fileName = "配置.txt";public Form1(){InitializeComponent();}public Boolean SendByte(byte b){if (!mycomm.IsOpen){MessageBox.Show("串口没有打开,请打开串口!");return false;}byte[] package = { b };mycomm.Write(package, 0, package.Length);//向串口发送一包的数据 return false;}public Boolean SendArr(byte[] package){if (!mycomm.IsOpen){MessageBox.Show("串口没有打开,请打开串口!");return false;}mycomm.Write(package, 0, package.Length);//向串口发送一包(18字节)的数据 return false;}public byte[] hexConvertToByteArray(String str){str = str.Replace(" ", "");byte[] b = new byte[str.Length / 2];for (int i = 0; i < str.Length; i = i + 2){b[i / 2] = (byte)Convert.ToInt32(str.Substring(i, 2), 16);   //将十六进制“10”转换为十进制i}return b;}private void button1_Click(object sender, EventArgs e){//this.SendArr(hexConvertToByteArray(textBoxSend.Text));//十六进制mycomm.Write(textBoxSend.Text); //字符}private void comm_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e){Thread.Sleep(1000);//这个延时非常重要 等整条数据接收完if (mycomm.BytesToRead > 0){//因为要访问ui资源,所以需要使用invoke方式同步ui。this.Invoke((EventHandler)(delegate{//byte[] bytes = new byte[mycomm.BytesToRead];//mycomm.Read(bytes, 0, bytes.Length);//textBoxRx.Text = "" + System.Text.Encoding.Default.GetString(bytes);textBoxRx.Text=(mycomm.ReadExisting());    //汉字正常了 字符模式//十六进制//byte[] data = new byte[mycomm.BytesToRead];                                //定义缓冲区,因为串口事件触发时有可能收到不止一个字节//mycomm.Read(data, 0, data.Length);//foreach (byte Member in data)                                                   //遍历用法//{//    string str = Convert.ToString(Member, 16).ToUpper();//    textBoxRx.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + " ");//}}));}}private void btnOpen_Click(object sender, EventArgs e){if (mycomm.IsOpen){mycomm.Close();btnOpen.Text = "打开串口";uartStatus();//(false);}else{try{mycomm.PortName = comboBoxPortSelect.Text;mycomm.ReadTimeout = 32;mycomm.Encoding = System.Text.Encoding.GetEncoding("UTF-8");//根据实际情况选择UTF-8还是GB2312mycomm.Open();btnOpen.Text = "关闭串口";//按钮打开uartStatus();//(true);}catch{btnOpen.Text = "打开串口";MessageBox.Show("没有发现串口或串口已被占用!");uartStatus();//(false);}}}private void comboBoxPortSelect_SelectedIndexChanged(object sender, EventArgs e){mycomm.Close();mycomm.PortName = comboBoxPortSelect.Text;btnOpen_Click(null,null); //重新打开}private void uartStatus(){if (mycomm.IsOpen){Settings.Default.comIndex = comboBoxPortSelect.SelectedIndex; //保存上次成功打开的端口Properties.Settings.Default.Save();//使用Save方法保存更改pictureBox1.Image = Properties.Resources.LED_OnR;}elsepictureBox1.Image = Properties.Resources.LED_OffR;}private void Form1_Load(object sender, EventArgs e){textBoxInterval.Text = Settings.Default.interval;string[] ports = SerialPort.GetPortNames();Array.Sort(ports);comboBoxPortSelect.Items.AddRange(ports);if (Settings.Default.comIndex >= ports.Length){//默认选中第一个comboBoxPortSelect.SelectedIndex = 0;}elsecomboBoxPortSelect.SelectedIndex = Settings.Default.comIndex;// btnOpen_Click(null, null);//打开本计算机的串口  //添加事件注册mycomm.DataReceived += comm_DataReceived;}private void timer1_Tick(object sender, EventArgs e){if (mycomm.IsOpen){//timer1.Interval = Convert.ToInt32(this.textBoxInterval.Text);//设置timer1的timer1_Tick实践执行周期为N毫秒this.SendArr(hexConvertToByteArray(textBoxSend.Text));}else{timer1.Enabled = false;}}private void buttonAuto_Click(object sender, EventArgs e){buttonAuto.Enabled = false;timer1.Interval = Convert.ToInt32(this.textBoxInterval.Text);//设置timer1的timer1_Tick实践执行周期为N毫秒timer1.Enabled = true;//设置为truetimer1_Tick实践就会执行,开始计时}private void buttonDoor1_Click(object sender, EventArgs e){textBoxSend.Text = "{\"cmd\":\"control\",\"smartId\":\"6359\",\"smartChannel\":\"1\",\"sensorId\":\"6361\",\"sensorChannel\":\"1\",\"para\":\"1\"}";button1_Click(null, null);}private void buttonDoor2_Click(object sender, EventArgs e){textBoxSend.Text = "{\"cmd\":\"control\",\"smartId\":\"6359\",\"smartChannel\":\"1\",\"sensorId\":\"6362\",\"sensorChannel\":\"3\",\"para\":\"1\"}";button1_Click(null,null);}private void buttonUPSOpen_Click(object sender, EventArgs e){textBoxSend.Text = "{\"cmd\":\"control\",\"smartId\":\"6358\",\"smartChannel\":\"1\",\"sensorId\":\"6437\",\"sensorChannel\":\"1\",\"para\":\"1\"}";button1_Click(null, null);}private void buttonUPSClose_Click(object sender, EventArgs e){textBoxSend.Text = "{\"cmd\":\"control\",\"smartId\":\"6358\",\"smartChannel\":\"0\",\"sensorId\":\"6437\",\"sensorChannel\":\"0\",\"para\":\"0\"}";button1_Click(null, null);}}
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:https://dhexx.cn/news/show-6487826.html

如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网进行投诉反馈,一经查实,立即删除!


相关文章:

  • Ubuntu和Windows相互共享文件夹
  • C语言提示multiple definition of displayPC以为是重复定义 ,实际原因是变量在头文件中不能初始化
  • XFTP问题解决Inconsistency detected by ld.so: dl-version.c: 230: _dl_check_map_versions:
  • 查询sick编码器型号是否支持hiperface接口方法,软件支持所有带此接口sick编码器
  • 0.6闪光灯二进制编码通信android源码手电筒手机密码器频率控制 as4.0版 密码123456 支持所有android2.2到10及以上系统 Android7.0以前和7.0以后开启闪光灯
  • Linux中的工具使用【vim的存活级】
  • c语言源码ping ip通不通 检测摄像头在不在线 立即返回结果linux
  • C#解决动态显示控件闪烁,使Windows Forms启用双缓冲于所有窗体以及其子控件就不闪了。
  • gcc编译mtserver Using ‘dlopen‘ in statically linked applications requires at runtime
  • arm Linux Shell 学习 shell获取命令输出结果放到test变量wget T3超时3秒,t1只试一次 必须加2>1 否则得不到 测试端口是否通 定时重启+单一实例守护
  • C# 汉字字符取模韩语日语意大利语俄语法语西班牙兼并葡萄牙等 任意语言 任意大小 任意字体 任意排列 字符汉字取模及显示编码unicode
  • 2020-09-30Linux v4l2 camera获得一张jpeg图片 C语言完整源码
  • 2020-10-02Linux shell判断url是否能访问,定时访问网站如果有问题就重启,懒得去查故障
  • STM32L4xx standard peripherals library想找这个,居然官网没有。
  • STM32L471re PB5接LED闪烁测试
  • Docker MongoDB中的数据导出带过滤条件的excel CSV 文件
  • gradle慢Error 1020 使用阿里镜像代理解决
  • docker时区问题少8小时 国内Linux统一将UTC时间改为CST时间,即修改时区为Asia/Shanghai
  • Windows 无法验证此文件的数字签名。原来是这个原因。解决方案1: 关闭Secure Boot
  • js中三个等号=== 值且类型相同时true,否则false
  • tcp模拟http测试
  • RS485两台设备用了半年,今天突然没数了,并上串口一直时不时有多余FF等乱码输出。单独串口接电脑试都正常,共地就正常了
  • 汉字ASCII取模后按协议通过串口把编码和字节码按协议发送到下位机 支持任意语言Unicode 任意扫描方式 任意大小可定制软件
  • 使用宝塔面板 网站流量大使服务器一直超负载运行,网站启用流量控制 后 xftp提示“你有没权限下载此文件“关了就正常。是8088端口被其他占用了。
  • 织梦软件下载链接改为个人收款码扫码收费下载 个人收款码支付平台是没有反馈信息,做了一个虚拟的。
  • 织梦备份还原后提示再生成DedeTag Engine Create File False 生成目录/a及子目录的权限设为777正常
  • VC6.0创建wm_close时自动把好几个自动函数定义全删了bug
  • VUE简单上手学习 摸摸就上道1
  • ,,会跳过空值splitstring。N305 C语言从GPS获得时间UTC,并把UTC转为CTS本地时间 时间转为秒+8小时
  • vc6.0 mfc保存导出数据到txt
  • npm run dev关闭终端后如何停止?退出vscode不行, 杀掉进程node.exe就行  Port 3030 is already in use [nodemon] app crashed
  • VUE导出数据为txt或csv文件
  • mongodb VUE时间 数据库原始date类型 2020-12-22T01:01:49.545Z 查询出来的结果是UTC nodejs把查询结果转本地时间CST 24小时模式google bug
  • linux cron crontab定时任务--重启\运行脚本等
  • java从网络下载文件无需库
  • 2021--2100收集新玩意
  • bladex环境搭建OK 图文log1
  • mysql处理json 比用like好 MySQL对JSON数据的增删改查
  • 程序员进入发展瓶颈?孤独?迷芒反思
  • 嵌入式arm Linux下使用BusyBox的crond服务的定时任务方法 之前的程序有问题tcp经常中断,程序还在,linux端口还在占用10777,tcp能连一会就断了,暂时用定时重启
  • springboot使用Map接收请求参数 @RequestBody 使用RestTemplate发送http get和post源码 接口中转相当于反向代理
  • 2021-03-04 mysql in里加个参数就查不到??是JSON_EXTRACT导致的,用JSON_UNQUOTE()去掉双引号就正常了
  • C#数组索引必须使用Convert.ToByte(“1“) 使用Convert.ToChar(“1“)报错
  • springcloud加入新模块
  • mysql子语句查询 ,引用子查询结果(多参数,单参数)或with as
  • 2021-3-18全国个人所得税 完税证明开具 最新 其它经验都过时了,我北京网上打印
  • C语言切割split多条json源码
  • 2021-04-07Springboot两种获取get所有URL路径中的参数 getQueryString 和 @RequestParam
  • android老项目改成支持所有新android版本10 11等 编码乱码This app was built for an older version of 蓝牙搜不到设备
  • 从一个账号批量复制用户到另一个账号alibaba工具源码 按键精灵