C# 串口通信 最基础程序(附带注释)

前提
C#要实现串口通信一定要创建一个Form

源码及说明
这是一个连接COM3串口,通过键盘摁键发出信息的基础程序(摁键对应小键盘的1,2,3)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.Text.RegularExpressions;

namespace 上位机串口程序
{
    public partial class Form1 : Form
    {
        SerialPort sp1 = new SerialPort();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;    //这个类中我们不检查跨线程的调用是否合法(因为.net 2.0以后加强了安全机制,,不允许在winform中直接跨线程访问控件的属性)
            sp1.DataReceived += new SerialDataReceivedEventHandler(sp1_DataReceived);//接收到数据时的委托事件
            //sp1.ReceivedBytesThreshold = 1;
            //准备就绪              
            sp1.DtrEnable = true;
            sp1.RtsEnable = true;
            //设置数据读取超时为1秒
            sp1.ReadTimeout = 1000;
            sp1.Close();

            if (!sp1.IsOpen)
            {
                sp1.PortName = "COM3";
                sp1.BaudRate = 4800;       //波特率
                sp1.DataBits = 8;       //数据位
                sp1.StopBits = StopBits.One;
                sp1.Parity = Parity.None;
                if (sp1.IsOpen == true)//如果打开状态,则先关闭一下
                {
                    sp1.Close();
                }
                sp1.Open();     //打开串口
                judge.Text = "串口连接成功";
            }
        }

        //委托方法
        void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] byteRead = new byte[sp1.BytesToRead];    //BytesToRead:sp1接收的字符个数
            Byte[] receivedData = new Byte[sp1.BytesToRead];        //创建接收字节数组
            sp1.Read(receivedData, 0, receivedData.Length);         //读取数据
            sp1.DiscardInBuffer();                                  //清空SerialPort控件的Buffer
            string strRcv = null;
            for (int i = 0; i < receivedData.Length; i++) //窗体显示
            {
                strRcv += receivedData[i].ToString("X2");  //16进制显示
            }
            receive.Text += strRcv + "\r\n";
        }


        void text_send(string send_str)
        {
            String strSend = send_str;
            string sendBuf = strSend;
            string sendnoNull = sendBuf.Trim();
            string sendNOComma = sendnoNull.Replace(',', ' ');    
            string sendNOComma1 = sendNOComma.Replace(',', ' '); 
            string strSendNoComma2 = sendNOComma1.Replace("0x", "");   
            strSendNoComma2.Replace("0X", "");   
            string[] strArray = strSendNoComma2.Split(' ');
            int byteBufferLength = strArray.Length;
            for (int i = 0; i < strArray.Length; i++)
            {
                if (strArray[i] == "")
                {
                    byteBufferLength--;
                }
            }

            byte[] byteBuffer = new byte[byteBufferLength];
            int ii = 0;
            for (int i = 0; i < strArray.Length; i++)       
            {
                Byte[] bytesOfStr = Encoding.Default.GetBytes(strArray[i]);
                int decNum = 0;
                if (strArray[i] == "")
                {
                    continue;
                }
                else
                {
                    decNum = Convert.ToInt32(strArray[i], 16); 
                }
                    byteBuffer[ii] = Convert.ToByte(decNum);
                ii++;
            }
            sp1.Write(byteBuffer, 0, byteBuffer.Length);
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            switch(e.KeyValue)
            {
                case 97: text_send("01"); break;
                case 98: text_send("02"); break;
                case 99: text_send("03"); break;
                default:text_send("04");break;
            }
        }
    }
}

C#串口介绍以及简单串口通信程序设计实现 源代码和串口程序介绍连接:https://www.cnblogs.com/JiYF/p/6618696.html 本站积分太贵,自己变得。。直接到连接地址下载代码 周末,没事干,写个简单的串口通信工具,也算是本周末曾来过,废话不多,直接到主题 串口介绍   串行接口简称串口,也称串行通信接口或串行通讯接口(通常指COM接口),是采用串行通信方式的扩展接口。(至于再详细,自己百度) 串口应用:   工业领域使用较多,比如:数据采集,设备控制等等,好多都是用串口通信来实现!你要是细心的话,你会发现,目前家用国网智能电能表就具备RS485通信总线(串行总线的一种)与RS232可以相互转化(当然一般,非专业的谁也不会闲的蛋疼,趴电表上瞎看,最多也就看看走了多少度电) RS232 DB9介绍: 1.示意图 2.针脚介绍: 载波检测(DCD) 接受数据(RXD) 发出数据(TXD) 数据终端准备好(DTR) 信号地线(SG) 数据准备好(DSR) 请求发送(RTS) 清除发送(CTS) 振铃指示(RI) 3.实物图: 以下是我购买XX公司的一个usb转串口线:这个头就是一个公头,另一端是一个usb口 笨小孩串口工具运行图: 1.开启程序 2.发送一行字符串HelloBenXH,直接将针脚的发送和接收链接起来就可以测试了(针脚2 接受数据(RXD) 和3 发出数据(TXD))直接链接, C#代码实现:采用SerialPort 1.实例化一个SerialPort [csharp] view plain copy 在CODE上查看代码片派生到我的代码片 private SerialPort ComDevice = new SerialPort(); 2.初始化参数绑定接收数据事件 [csharp] view plain copy 在CODE上查看代码片派生到我的代码片 public void init() { btnSend.Enabled = false; cbbComList.Items.AddRange(SerialPort.GetPortNames()); if (cbbComList.Items.Count > 0) { cbbComList.SelectedIndex = 0; } cbbBaudRate.SelectedIndex = 5; cbbDataBits.SelectedIndex = 0; cbbParity.SelectedIndex = 0; cbbStopBits.SelectedIndex = 0; pictureBox1.BackgroundImage = Properties.Resources.red; ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);//绑定事件 }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rory_wind

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值