简单的C#串口连接

本文介绍了如何在WindowsForms应用程序中实现串口通信,包括设置COM端口、数据接收(字符和字节模式)、16进制数据转换以及发送操作。
摘要由CSDN通过智能技术生成
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.Threading.Tasks;
using System.Windows.Forms;


namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            /*string str;
            for (int i = 0; i < 256; i++)
            {
                str = i.ToString("X").ToUpper();//i.ToString("X")是将数字转换为16进制,同时字母大写
                if (str.Length == 1)
                {
                    str = "0" + str;//如果是一位的(0xA),为了对齐,在数据前加一个0(0x0A)
                }
                comboBox1.Items.Add("0x" + str);
            }
            comboBox1.Text = "0X00";*/
            for (int i = 0; i < 20; i++)
            {
                comboBox1.Items.Add("COM"+i);
            }
            comboBox1.Text = "COM1";
            comboBox2.Items.Add("9600");
            //创建串口           
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_DataReceive);
        }

        private void port_DataReceive(object sender, SerialDataReceivedEventArgs e)//串口接收事件
        {
            if (!radioButton3.Checked)//如果接收模式为字符模式
            {
                string str = serialPort1.ReadExisting();
                textBox2.AppendText(str+"\r\n");//
            }
            else
            {
                byte data;
                data=(byte)serialPort1.ReadByte();//转换为byte类型
                string str=Convert.ToString(data,16).ToUpper();//转换为大写16进制符
                textBox2.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + "\r\n");
            }
          
        }

     
        /// <summary>
        /// 点击发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            /* string data = comboBox1.Text;
             string converdata = data.Substring(2, 2);
             byte[] buffer = new byte[1];
             buffer[0]=Convert.ToByte(converdata,16);//将16位字符转换为Byte字符*/
            byte[] Date=new byte[1];
            if (serialPort1.IsOpen)
            {
                if (textBox1.Text != "")
                {
                    if (!radioButton1.Checked)//如果发送模式是字符模式
                    {
                        try
                        {
                            serialPort1.Write(textBox1.Text);          
                        }
                        catch 
                        {
                            MessageBox.Show("串口数据写入错误");
                        }
                    }
                    else
                    {
                        for (int i = 0; i < (textBox1.Text.Length-textBox1.Text.Length%2)/2; i++)
                        {
                            Date[0] = Convert.ToByte(textBox1.Text.Substring(i*2,2),16);
                            serialPort1.Write(Date, 0, 1);
                        }
                        if (textBox1.Text.Length % 2 != 0)
                        {
                            Date[0] = Convert.ToByte(textBox2.Text.Substring(textBox1.Text.Length - 1, 1),16);
                            serialPort1.Write(Date, 0, 1);
                        }
                    }
                }
            }
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 打开端口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.PortName=comboBox1.Text;
                serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
                serialPort1.Open();
                button2.Enabled = false;
                button3.Enabled=true;
            }
            catch 
            {
                MessageBox.Show("端口错误");
            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {

        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值