首页

C#实现串口通讯助手

c#

2020-9-28

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.Threading;

namespace P1
{
    public partial class Form1 : Form
    {

        //SerialPort sp1 = null;
        bool isOpen = false;
        //bool isSetProperty = false;
        private static volatile bool DelayOver = false;                       //调度器锁 true:加锁  false:解锁


        public Form1()
        {
            InitializeComponent();

            //列出常用的波特率
            cbxBaudRate.Items.Add("300");
            cbxBaudRate.Items.Add("600");
            cbxBaudRate.Items.Add("1200");
            cbxBaudRate.Items.Add("2400");
            cbxBaudRate.Items.Add("4800");
            cbxBaudRate.Items.Add("9600");
            cbxBaudRate.Items.Add("19200");
            cbxBaudRate.Items.Add("38400");
            cbxBaudRate.Items.Add("43000");
            cbxBaudRate.Items.Add("56000");
            cbxBaudRate.Items.Add("57600");
            cbxBaudRate.Items.Add("115200");
            cbxBaudRate.SelectedIndex = 5;
            //列出停止位
            cbxStopBits.Items.Add("0");
            cbxStopBits.Items.Add("1");
            cbxStopBits.Items.Add("1.5");
            cbxStopBits.Items.Add("2");
            cbxStopBits.SelectedIndex = 1;
            //列出数据位
            cbxDataBits.Items.Add("8");
            cbxDataBits.Items.Add("7");
            cbxDataBits.Items.Add("6");
            cbxDataBits.Items.Add("5");
            cbxDataBits.SelectedIndex = 0;
            //列出奇偶校验位
            cbxParity.Items.Add("无");
            cbxParity.Items.Add("奇校验");
            cbxParity.Items.Add("偶校验");
            cbxParity.SelectedIndex = 0;
        }

    

        private bool CheckPortSetting()
        {//检查串口是否设置
            if (cbxCOMPort.Text.Trim() == "") return false;
            //if (cbxBaudRate.Text.Trim() == "") return false;
            //if (cbxDataBits.Text.Trim() == "") return false;
            //if (cbxParity.Text.Trim() == "") return false;
            //if (cbxStopBits.Text.Trim() == "") return false;
            return true;
        }
        private bool CheckSendData()
        { 

        if (tbxSendData.Text.Trim() ==  "") return false;
        return true;
        }

        private void TestBaudRate(UInt16 TBR)
        {
            byte[] t = new byte[8] { 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x85, 0xDB };

            sp1.BaudRate = TBR;

            //打开串口
            try
            {
                //sp1.Open();
                sp1.Write(t, 0, 8);

            }
            catch (Exception)
            {
                return;
            }
        }

        private void SetPortProperty()
        {
            if (isOpen == false)
            {

                //*设置停止位
                sp1.StopBits = StopBits.One;
                //*设置数据位
                sp1.DataBits = 8;
                //*设置奇偶校验位
                sp1.Parity = Parity.None;
                //设置超时读写时间
                sp1.ReadTimeout = 10;
                sp1.WriteTimeout = 10;
                ////串口波特率测试
                //sp1.BaudRate = 9600;
                //打开串口
                try
                {

                    sp1 = new SerialPort();
                    sp1.PortName = cbxCOMPort.Text.Trim();//设置串口名

                    sp1.Open();
                    isOpen = true;
                    tbxRecvData.AppendText(">>打开串口成功\r\n");
                    //MessageBox.Show("打开串口成功,请重新启动设备!", "温馨提示");
                    tbxRecvData.ScrollToCaret();
                    pbxLED.Image = P1.Properties.Resources.Red_LED;
                    btnOpenCOM.Text = "关闭串口";

                }
                catch (Exception)
                {
                    MessageBox.Show("打开串口时发生错误!", "错误提示");
                    pbxLED.Image = P1.Properties.Resources.OFF_LED;
                    btnOpenCOM.Text = "打开串口";
                }
            }
            else
            {
                sp1.Close();
                isOpen = false;
                tbxRecvData.AppendText(">>串口关闭\r\n");
                tbxRecvData.ScrollToCaret();
                pbxLED.Image = P1.Properties.Resources.OFF_LED;
                btnOpenCOM.Text = "打开串口";
            }


        }

        private void button3_Click(object sender, EventArgs e)
        {

            byte[] t = new byte[8];
            t[0] = 0xAA;
            t[1] = 0xBB;
            t[2] = 0x11;
            t[3] = 0x22;
            t[4] = 0x33;
            t[5] = 0x44;
            t[6] = 0x55;
            t[7] = 0x66;

                try
                {
                    sp1.Write(t, 0, 8);
                        //(Convert.ToInt16(tbxSendData.Text));
                    //sp.Write("0");
                }
                catch (Exception)
                {
                    lblStatus.Text = "发送数据时发生错误!";
                    return;
                }
    
        }


        private void button2_Click(object sender, EventArgs e)
        {
            sp1.Close();
            this.Close(); 
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //if (isOpen)
            //{
                try
                {//读取串口数据
                tbxRecvData.Text  = sp1.ReadLine();
                }
                catch (Exception)
                {
                    lblStatus.Text = "读取串口时发生错误!";
                    return;
                }
            //}
            //else
            //{
            //    MessageBox.Show("串口未打开!", "错误提示");
            //    return;
            //}
        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        private void btnOpenCOM_Click(object sender, EventArgs e)
        {
            
            if (!CheckPortSetting())
            {
                MessageBox.Show("串口未设置!", "错误提示");
                return;
            }
           
            //*设置串口的属性


            SetPortProperty();


            this.sp1.DataReceived  = new System.IO.Ports.SerialDataReceivedEventHandler(this.sp1_DataReceived);
            Control.CheckForIllegalCrossThreadCalls = false;
            //Thread.Sleep(100);

            TestBaudRate(9600);
            Delay(500);
            TestBaudRate(1200);
            //Thread.Sleep(500);
            //TestBaudRate(2400);
            //Thread.Sleep(500);
            //TestBaudRate(4800);
            //Thread.Sleep(500);
            //TestBaudRate(19200);

        }


        private void cbxCOMPort_MouseDown(object sender, MouseEventArgs e)
        {
            //检测哪些串口可用
            cbxCOMPort.Items.Clear();
            for (int i = 0; i < 20; i  )
            {
                try
                {
                    SerialPort sp1 = new SerialPort("COM"   (i  1).ToString());
                    sp1.Open();
                    sp1.Close();
                    cbxCOMPort.Items.Add("COM"   (i   1).ToString());
                }
                catch (Exception)
                {
                    continue;
                }
            }

        }

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

        private void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                timer1.Enabled = true;
            }
            catch
            {
                return;
            }

        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

            int i, j;
            timer1.Enabled = false;
            j = sp1.BytesToRead;
            for (i = 0; i < j; i  )
            {
                try
                {//读取串口数据
                    tbxRecvData.AppendText(Convert.ToString(sp1.ReadByte(), 16)   " ");//10进制转换为16进制,显示出来
                    tbxRecvData.ScrollToCaret();
                    //timer2.Enabled = true;
                }
                catch (Exception)
                {
                    return;
                }
            }

            tbxRecvData.AppendText("\r\n");


            //try
            //{//读取串口数据
            //    //tbxRecvData.Text  = sp.ReadLine();
            //    //tbxRecvData.ScrollToCaret();
            //    tbxRecvData.AppendText(Convert.ToString(sp1.ReadByte(), 16)   " ");//10进制转换为16进制,显示出来
            //    tbxRecvData.ScrollToCaret();
            //    timer2.Enabled = true;
            //}
            //catch (Exception)
            //{
            //    return;
            //}

        }

        private void timer2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DelayOver = true;
            timer2.Enabled = false;
        }

        private void Delay(UInt16 ms)
        {
            timer2.Interval = ms;
            timer2.Enabled = true;
            //while (!DelayOver) { }
            DelayOver = false;


        }

       
    }
}

资源下载此资源下载价格为2D币(VIP免费),请先
资源文件列表
P1/Backup/P1/Form1.cs , 9870
P1/Backup/P1/Form1.Designer.cs , 28830
P1/Backup/P1/Form1.resx , 6568
P1/Backup/P1/obj/Debug/P1.exe , 30208
P1/Backup/P1/P1.csproj , 4067
P1/Backup/P1/P1.csproj.user , 168
P1/Backup/P1/Program.cs , 536
P1/Backup/P1/Properties/AssemblyInfo.cs , 1340
P1/Backup/P1/Properties/Resources.Designer.cs , 3334
P1/Backup/P1/Properties/Resources.resx , 6459
P1/Backup/P1/Properties/Settings.Designer.cs , 1087
P1/Backup/P1/Properties/Settings.settings , 249
P1/Backup/P1/Resources/OFF LED.bmp , 4348
P1/Backup/P1/Resources/Red LED.bmp , 4348
P1/Backup/P1.sln , 896
P1/Backup/P1.v12.suo , 26112
P1/e461c56cb0549325fd12871280ed34ff.jpg , 7592
P1/Green LED.bmp , 5732
P1/OFF LED.bmp , 4348
P1/P1/bin/Debug/P1.exe , 30720
P1/P1/bin/Debug/P1.pdb , 48640
P1/P1/bin/Debug/P1.vshost.exe , 22704
P1/P1/Form1.cs , 9865
P1/P1/Form1.Designer.cs , 28831
P1/P1/Form1.resx , 6568
P1/P1/obj/Debug/DesignTimeResolveAssemblyReferences.cache , 1231
P1/P1/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache , 7074
P1/P1/obj/Debug/P1.csproj.FileListAbsolute.txt , 1341
P1/P1/obj/Debug/P1.csproj.GenerateResource.Cache , 987
P1/P1/obj/Debug/P1.csprojResolveAssemblyReference.cache , 1881
P1/P1/obj/Debug/P1.exe , 30720
P1/P1/obj/Debug/P1.Form1.resources , 180
P1/P1/obj/Debug/P1.pdb , 48640
P1/P1/obj/Debug/P1.Properties.Resources.resources , 9356
P1/P1/obj/Debug/TempPE/Properties.Resources.Designer.cs.dll , 5120
P1/P1/P1.csproj , 4220
P1/P1/P1.csproj.user , 228
P1/P1/Program.cs , 536
P1/P1/Properties/AssemblyInfo.cs , 1340
P1/P1/Properties/Resources.Designer.cs , 3588
P1/P1/Properties/Resources.resx , 6459
P1/P1/Properties/Settings.Designer.cs , 1102
P1/P1/Properties/Settings.settings , 249
P1/P1/Resources/OFF LED.bmp , 4348
P1/P1/Resources/Red LED.bmp , 4348
P1/P1.sln , 975
P1/P1.suo , 26112
P1/P1.v12.suo , 49664
P1/Red LED.bmp , 4348
P1/UpgradeLog.htm , 41304
P1/Yeyllow LED.bmp , 7386
没有账号? 忘记密码?

社交账号快速登录