串口通讯系列-串口通讯实现

/*======================================================
//使用到的控件有:
//Panel 分组框 容器
//GroupBox  组合框 容器
//Label 标签
//RadioButton 单选按钮
//TextBox 文本编辑框
//SerialPort 串行端口
//ComboBox 组合框
//Button 按钮
=======================================================*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace WindowsFormsSerial
{
    public partial class Form1 : Form
    {


        private SerialPort ComDevice;
        //private int flag = 0;
        public Form1() {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e) {
            //初始化串口
            ComInit();
            Refresh_CB_comport();
            ComDevice.DataReceived += CD_DataReceived;
            ComDevice.Encoding = Encoding.GetEncoding("GB2312");
            CheckForIllegalCrossThreadCalls = false;
        }
        //串口初始化
        private void ComInit() {
            ComDevice = new SerialPort();//实例化SerialPort对象
            //ComDevice.BaudRate = 115200;//波特率
            ComDevice.StopBits = StopBits.One; //停止位
            ComDevice.DataBits = 8;//数据位
            int[] com = new int[6] { 4800, 9600, 19200, 38400, 57600, 115200 };
            for(int i = 0; i < 6; i++) {
                comboBox2.Items.Add(com[i]);
            }
            comboBox2.Text = "4800";
        }
        //读数据
        private void CD_DataReceived(object sender, SerialDataReceivedEventArgs e) {
            if(!radioButton3.Checked) {//字符读取
                textBox1.AppendText(ComDevice.ReadExisting());
            }
            else {//数值读取
                byte[] data = new byte[ComDevice.BytesToRead];
                ComDevice.Read(data, 0, data.Length);
                foreach(byte ByRead in data) {//转换成16进制
                    string str = Convert.ToString(ByRead, 16).ToUpper();
                    textBox1.AppendText((str.Length == 1 ? "0" + str : str) + " ");
                }
            }

        }
        //获取计算机串口号
        private void Refresh_CB_comport() {
            object n = comboBox1.Items;//获取一个对象,该对象表示此 ComboBox 中所含的项的集合
            comboBox1.Items.Clear();//清空comboBox1
            comboBox1.Items.AddRange(SerialPort.GetPortNames());//获取计算机串口号并储存到comboBox1集合中,AddRange->一次可以添加多个元素
            if(comboBox1.Items.Contains(n))//判断comboBox1集合里面是否存在相同的元素
                comboBox1.SelectedItem = n;//有,设置 ComboBox 中当前选定的项
            else
                comboBox1.SelectedIndex = 0;//没有,设置指定当前选定项的索引为0
        }
        //打开\关闭串口操作
        private void button_comctr_Click(object sender, EventArgs e) {
            //判断串口是否处于关闭状态
            if(button2.Text == "打开串口") {
                if(comboBox1.Text == "") {//判断是否选择串口号
                    MessageBox.Show("选择一个COM口");
                    return;
                }
                ComDevice.PortName = comboBox1.Text;//默认串口号
                ComDevice.BaudRate = Convert.ToInt32(comboBox2.Text);//默认波特率
                try {
                    ComDevice.Open();//打开串口
                }
                catch(Exception ex) {
                    MessageBox.Show(ex.Message);
                    return;
                }
                button2.Text = "关闭串口";
                button2.ForeColor = Color.Red;//字体显示红色
                comboBox1.Enabled = false;//控件不可选
                comboBox2.Enabled = false;
            }
            else {
                try {//关闭串口
                    ComDevice.Close();
                }
                catch(Exception ex) {
                    MessageBox.Show(ex.Message);
                }
                resfresh_all();
            }
        }
        //关闭串口后回复正常状态
        private void resfresh_all() {
            button2.Text = "打开串口";
            comboBox1.Enabled = true;
            comboBox2.Enabled = true;
            button2.ForeColor = Color.Black;
        }
        //发送数据
        private void button_send_Click(object sender, EventArgs e) {
            byte[] data = new byte[1];


            if(ComDevice.IsOpen) {//判断串口是否打开
                if(textBox2.Text != "") {//判断是否有数据
                    if(!radioButton1.Checked) {//字符发送
                        try {
                            ComDevice.Write(textBox2.Text);
                        }
                        catch {
                            MessageBox.Show("写入数据错误", "错误");
                        }
                    }
                    else {
                        try {
                            string buffer = textBox2.Text;
                            buffer = buffer.Replace("0x", "");                                    //为了保证汉字转编码输出结果(0xXX)可以通用,所以程序允许输入0xXX(可以带空格),程序会将0x和空格自动去除
                            buffer = buffer.Replace(" ", string.Empty);
                            //处理偶数部分
                            for(int i = 0; i < (buffer.Length - buffer.Length % 2) / 2; i++) {
                                data[0] = Convert.ToByte(buffer.Substring(i * 2, 2), 16);
                                ComDevice.Write(data, 0, 1);
                            }
                            if(buffer.Length % 2 != 0) {//处理剩下的数据
                                data[0] = Convert.ToByte(buffer.Substring(buffer.Length - 1, 1), 16);
                                ComDevice.Write(data, 0, 1);
                            }
                        }
                        catch {
                            MessageBox.Show("请输入数字", "错误");
                        }
                    }
                }
            }
        }
        //清空接收区域
        private void button3_Click(object sender, EventArgs e) {
            textBox1.Text = " ";
        }
        //清空发送区域
        private void button4_Click(object sender, EventArgs e) {
            textBox2.Text = " ";
        }
    }
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值