c#(串口测试工具)-0

来源:互联网 发布:数据恢复视频教程 编辑:程序博客网 时间:2024/06/05 15:48

    工控机,作为主控部份控制中心,存储数据,分析数据,发送指令,接收指令。。。总的来说这就是一个指挥部,但是在我们看到的产器部份来说其实真的没有看出有什么卵用。

    要想发挥点用作用,使指令传到下位机,让下位机动作,接收下位机的指令分析后再让下位机动作,都离不开一个关键的玩意,串口。

    先写个串口助手一类的东西吧,反正这东西还是挺常用的,像单片机什么的主要通迅口不就是串口吗,虽然说串口速度不怎么的,但你一个单片机还能有多大的要求?

    说了这么多废话,其实是因为无聊,不说了,用C#写客户端一类的东西,开始就是画个界面吧,哦,不对,如果是搞一个项目一类的东西可能是先写个数据库接口搞个数据模型样的东西吧,呃,,,又要跑题了,这只是个小玩意,先画个图吧。

就画成这样了,如果还想要有其它功能,就往右边画吧,反正空间多的是。。。

画完了,就开始加一此代码了,vs写这个就是方便,专为我这种小白设计,搬砖的嘛,要那么聪明搞毛呀,你说是吧

先是loadfrom嘛:

        private void UboxTestFrom_Load(object sender, EventArgs e)
        {
            this.serialPort = new SerialPort();
            this.serialPort.DataReceived += new SerialDataReceivedEventHandler(this.serialPort_DataReceived);
            this.comboBoxSerialPort.SelectedIndex = 0;      //默认串口端品
            this.comboBoxDataBits.SelectedIndex = 1;        //默认串口数据位
            this.comboBoxBaudRate.SelectedIndex = 4;        //默认串口波特率
            this.comboBoxParityBit.SelectedIndex = 0;       //默认串口效验
            this.comboBoxStopBit.SelectedIndex = 0;         //默认串口停止位

            this.buttonSend.Enabled = false;

            radioReceiveHex.Checked = true;
            radioSendHEX.Checked = true;

        }

没太多新意,就是串中控件new一个实体类,毕竟面向对象一new一个东西,没法搞事,然后是串口接收事件的处理函数,然后就是一些控件的初始化了,没毛病,常用的控件,用来设置常用的串口属性。

接下来就是三个个玩意了,

首先开关串口嘛:

 private void buttonSerialOnOff_Click(object sender, EventArgs e)
        {
            if (!serialPort.IsOpen) //如果串口没打开
            {
                int stopBitNumber = 0;

                serialPort.PortName = comboBoxSerialPort.Text;
                serialPort.BaudRate = Convert.ToInt32(comboBoxBaudRate.Text);
                serialPort.DataBits = Convert.ToInt32(comboBoxDataBits.Text);
                stopBitNumber = comboBoxStopBit.SelectedIndex;

                switch (stopBitNumber)
                {
                    case 0:
                        serialPort.StopBits = StopBits.One;
                        break;
                    case 1:
                        serialPort.StopBits = StopBits.OnePointFive;
                        break;
                    case 2:
                        serialPort.StopBits = StopBits.Two;
                        break;
                    default:
                        break;
                }

                int parityBitNumber = 0;
                parityBitNumber = comboBoxParityBit.SelectedIndex;
                switch (parityBitNumber)
                {
                    case 0:
                        serialPort.Parity = Parity.None;
                        break;
                    case 1:
                        serialPort.Parity = Parity.Odd;
                        break;
                    case 2:
                        serialPort.Parity = Parity.Even;
                        break;
                    case 3:
                        serialPort.Parity = Parity.Mark;
                        break;
                    case 4:
                        serialPort.Parity = Parity.Space;
                        break;
                    default:
                        break;
                }

                //异常处理
                try
                {
                    serialPort.Open();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误:" + ex.Message);
                }
                if (serialPort.IsOpen)
                {
                    comboBoxSerialPort.Enabled = false;
                    comboBoxDataBits.Enabled = false;
                    comboBoxBaudRate.Enabled = false;
                    comboBoxParityBit.Enabled = false;
                    comboBoxStopBit.Enabled = false;

                    buttonSerialOnOff.Text = "关闭串口";
                    buttonSend.Enabled = true;
                    setAllButtonEnable();
                }
            }
            else //如果串口已经打开
            {
                try
                {
                    serialPort.Close();
                }
                catch (TimeoutException ex)
                {
                    MessageBox.Show("错误:" + ex.Message);
                }
                if (!serialPort.IsOpen)
                {
                    comboBoxSerialPort.Enabled = true;
                    comboBoxDataBits.Enabled = true;
                    comboBoxBaudRate.Enabled = true;
                    comboBoxParityBit.Enabled = true;
                    comboBoxStopBit.Enabled = true;

                    buttonSerialOnOff.Text = "打开串口";
                    buttonSend.Enabled = false;
                }
            }

        }

哈,准备工作就好了,然后呢写发送吧,这里面有个注意的地方String 与byte[]之间的转换,还有一个hex格式与Assic的转换,我用了一个try catch,因为hex格式只有0-9 a-f 嘛。
        private void buttonSend_Click(object sender, EventArgs e)
        {   
            if(radioSendAscci.Checked == true)
            {
                byte[] cmd = System.Text.Encoding.Default.GetBytes(textBoxSend.Text);
                serialPort.Write(cmd, 0, cmd.Length);
            }
            else
            {
                string str = textBoxSend.Text.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "");
                string[] chars = str.Split(new String[] { "0x" }, StringSplitOptions.RemoveEmptyEntries);
                try
                {
                    byte[] bytes = Array.ConvertAll(chars, s => Convert.ToByte(s, 16));
                    serialPort.Write(bytes, 0, bytes.Length);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误:" + ex.Message);
                }
            }                        
        }

最后就是接收部份了:

在这里除了有byte[] 与String 之间的转换还有一个跨线程的问题,也就是所谓的“不在在创建它的线程操作了这玩意”

在类外里先写个这东西(写在namespace xx下吧)

    public delegate void WriteText(string msg);

 然后在类里写个这方法

        public void WriteReceiveText(String msg)
        {
            if (textBoxReceived.InvokeRequired)
            {
                textBoxReceived.BeginInvoke(new WriteText(WriteReceiveText), msg);
                return;
            }
            if (receiveTextCount >= 10000)
            {
                receiveTextCount = 0;
                textBoxReceived.Clear();
            }
            textBoxReceived.AppendText(msg);
            receiveTextCount++;
        }

有点个C里面的函数指针的意思,这个叫什么来着,“代理”还是叫“委托”,我操有点蒙逼。。。这样就可发放心的把接收到的东西显示出来了。。。

没错,就是loadfrom是搞出来的串口事件处理函数:

        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            String hexStr;
            int bytesToRead = serialPort.BytesToRead;
            byte[] buff = new byte[bytesToRead];
            serialPort.Read(buff, 0, bytesToRead);
            if (radioReceiveAscci.Checked == true)
            {
                WriteReceiveText(System.Text.Encoding.Default.GetString(buff));
            }
            else
            {   for(int i=0; i<buff.Length; i++ )
                {
                    if (buff[i] < 0x10)
                    {
                        hexStr = "0x0" + Convert.ToString(buff[i], 16);
                    }
                    else
                    {
                        hexStr = "0x" + Convert.ToString(buff[i], 16);
                    }
                    
                    WriteReceiveText(hexStr+" ");  
                }
                              
            }
        }

嗯,有这么个意思了,用R232,tx与rx搞到一起,可以自发自收了,没毛病,老铁!

呃,关闭窗口的时候要不要关闭串口呢!啊,我要去瞅下委托了这个不说了。。。。




0 0
原创粉丝点击