获取串口数据

1. .net获取,在后端获取后直接显示在页面中或写入数据库,如果需要写入数据库,只需将获取到的accept作为参数向后传递即可

        /// 
        /// 获取本机串口列表
        /// 
        /// 
        /// 
        private List GetComlist(bool isUseReg)
        {
            List list = new List();
            try
            {
                if (isUseReg)
                {
                    RegistryKey RootKey = Registry.LocalMachine;
                    RegistryKey Comkey = RootKey.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM");

                    String[] ComNames = Comkey.GetValueNames();

                    foreach (String ComNamekey in ComNames)
                    {
                        string TemS = Comkey.GetValue(ComNamekey).ToString();
                        list.Add(TemS);
                    }
                }
                else
                {
                    foreach (string com in SerialPort.GetPortNames())  //自动获取串行口名称  
                        list.Add(com);
                }
            }
            catch
            {
                MessageBox.Show("串行端口检查异常!");
                // System.Environment.Exit(0); //彻底退出应用程序   
            }
            return list;
        }
        /// 
        /// 判断是否存在当前串口
        /// 
        string targetCOMPort = null;
        private void StartSerialPortMonitor()
        {
            List comList = GetComlist(false); //首先获取本机关联的串行端口列表     
            if (comList.Count == 0)
            {
                MessageBox.Show("当前设备不存在串行端口!");
                // System.Environment.Exit(0); //彻底退出应用程序   
            }
            else
            {
                targetCOMPort = comList[0];
                //string targetCOMPort = "COM3";
                //判断串口列表中是否存在目标串行端口
                if (!comList.Contains(targetCOMPort))
                {
                    MessageBox.Show("当前设备不存在配置的串行端口!");
                    //System.Environment.Exit(0); //彻底退出应用程序   
                }
            }
        }

        /// 
        /// 设置通讯串口
        /// 
        SerialPort serialPort = new SerialPort();
        public void setcom()
        {
            try
            {
                StartSerialPortMonitor();
                serialPort = new SerialPort(targetCOMPort);
                serialPort.PortName = targetCOMPort; //通信端口
                serialPort.BaudRate = 115200; //串行波特率
                serialPort.DataBits = 8; //每个字节的标准数据位长度
                serialPort.StopBits = StopBits.One; //设置每个字节的标准停止位数
                serialPort.Parity = Parity.None; //设置奇偶校验检查协议
                                                 //下面这句是当信息中有汉字时,能正确传输,不然会出现问号。

                //对编码进行注册GB2312;
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

                serialPort.Encoding = System.Text.Encoding.GetEncoding("GB2312");
                //串口控件成员变量,字面意思为接收字节阀值,
                //串口对象在收到这样长度的数据之后会触发事件处理函数
                //一般都设为1
                serialPort.ReceivedBytesThreshold = 1;
                serialPort.DataReceived += new SerialDataReceivedEventHandler(CommDataReceived); //设置数据接收事件(监听)

                serialPort.Open(); //打开串口
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            } 

        }
        ///  
        /// 发送数据 
        ///  
        ///  
/*        private void SendData(string sendData)
        {
            try
            {
                serialPort.Encoding = EncodingType;
                serialPort.Write(sendData);
            }
            catch (Exception e)
            {
                throw e;
            }
        }*/

        /// 
        /// 通讯有数据进执行
        /// 
        /// 
        /// 
        private void CommDataReceived(Object sender, SerialDataReceivedEventArgs e)
        {
            getcom();

        }


        //通过串口读取数据,处理数据

        string accept = null;
        StringBuilder sup = new StringBuilder();
        int j;
        public void getcom()
        {
            try
            {
                //定义一个字段,来保存串口传来的信息。
                string str = "";
                int len = serialPort.BytesToRead;
                Byte[] readBuffer = new Byte[len];
                serialPort.Read(readBuffer, 0, len);
                str = Encoding.Default.GetString(readBuffer);

                for (j = 0; j < str.Length; j++)
                {
                    if (str[j] == '=')
                        break;
                }
                for (int i = j + 1; i < j + 5; i++)
                {
                    sup.Append(str[i]);
                }
                accept = sup.ToString();
                sup = null;
                str = "";
                serialPort.DiscardInBuffer();  //清空接收缓冲区     
                serialPort.Close();
            }
            catch (Exception ex)
            {
                serialPort.Close();
            }
        }
        /// 
        /// 获取温度
        /// 
        ///   
        public List GetTemp(int Id, string Type)
        {
            setcom();
            if (!serialPort.IsOpen)
            {
                serialPort.Open();
            }
            getcom();
            if (serialPort.IsOpen)
            {
                SerialPort serialPort = new SerialPort();
                serialPort.Close();
            }
            string result = accept;
            bool success = _TempRepository.GetTemp(Id, Type, accept);
            if(success == true)
            {
                return result;
            }
            else 
            { 
                return result;
            }

        }

2.winform串口助手

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.IO;
using System.Runtime.InteropServices;
using main;

namespace message
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            System.Threading.Thread.Sleep(2000);//延时200ms等待接收完数据

        }

        #region 初始化窗体
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                string[] str = SerialPort.GetPortNames();   //获取连接到电脑的串口号并存进数组
                comboBox_PortNames.Items.Clear();           //清除串口号下拉框的内容
                comboBox_PortNames.Items.AddRange(str);     //将串口号添加到下拉框

                if (str.Length > 0)
                {
                    comboBox_PortNames.SelectedIndex = 0;   //设置ComboBox框的初始值
                    comboBox_BaudRate.SelectedIndex = 7;
                    comboBox_DataBit.SelectedIndex = 3;
                    comboBox_StopBit.SelectedIndex = 0;
                    comboBox_Parity.SelectedIndex = 2;
                }
                else
                {
                    MessageBox.Show("当前无串口连接!");
                }
            }
            catch
            {
                MessageBox.Show("无串口设备!\r\n请检查是否连接设备!\r\n请检查设备驱动!");
            }

        }
        #endregion

        /**************************************************************************/
        #region 接收串口数据
        /*
        开辟缓存区 根据具体协议内容获取一帧数据进行接收中断处理
         */
        //变量
        List sp_buffer = new List(64);    //串口缓存区
        int sp_buffer_max = 64;   //串口缓存区最大缓存字节数
        byte[] ruffer = new byte[9192]; //用来存放缓冲区的数据流

        private void SerialDataReceive(object sender, SerialDataReceivedEventArgs e)
        {
            if (serialPort1.IsOpen == false)
            {
                serialPort1.Close();
                return;
            }


            int Byte_len = serialPort1.BytesToRead; //读取缓存的数据长度
            byte[] Rc_byte = new byte[Byte_len];

            serialPort1.Read(Rc_byte, 0, Byte_len);   //将缓存数据存储进字节数组里面

            sp_buffer.AddRange(Rc_byte);    //存入缓存区
            if (sp_buffer.Count > sp_buffer_max)    //缓存超过字节数 先丢弃前面的字节  
                sp_buffer.RemoveRange(0, sp_buffer_max); //丢弃前面的字节0到sp_buffer_max



           // byte[] ruffer = new byte[9192]; //用来存放缓冲区的数据流

            //对数据流进行筛选,缓冲区每一组数据个数大于4则为我们想要的数据流
            if (sp_buffer.Count > 4)
            {
                sp_buffer.CopyTo(0, ruffer, 0, sp_buffer.Count);
                Task.Run(() => printf_data(ruffer, sp_buffer.Count, 1));  //打印数据流

            }
        }
        #endregion


        /**************************************************************************/

        string strplus = null;
        #region 打印数据流
        void printf_data(byte[] Frame, int Length, int T_R)   //打印串口数据
        {
            Int16 i_len;
            StringBuilder s = new StringBuilder();
            if (T_R == 0)
                s.Append("发送:" + "\r\n");
            else
                s.Append("接收:" + "\r\n");

            //清除无用多余的数据
            /*            int i = 0;
                        for (i = 0; i
            {
                if (richTextBox_Receive.Lines.Count() > 20)
                    richTextBox_Receive.Clear();
                richTextBox_Receive.AppendText(str_show);
            });
            BeginInvoke(mi);
            /*
            richTextBox_Receive.Focus(); //获取焦点
            richTextBox_Receive.Select(richTextBox_Receive.TextLength, 0);//光标
            richTextBox_Receive.ScrollToCaret(); //滚动条
            */
        }
        #endregion
        public void timer1_Tick(object sender, EventArgs e)
        {
            byte[] ruffer = new byte[9192];
        }
        private void richTextBox_Receive_TextChanged(object sender, EventArgs e)
        {

        }

        private void comboBox_PortNames_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void richTextBox_Send_TextChanged(object sender, EventArgs e)
        {

        }

        /**************************************************************************/
        #region 打开串口
        private void button_OpenOrClose_Click_1(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen)
            {
                if (comboBox_PortNames.SelectedItem == null)
                {
                    MessageBox.Show("请选择正确的串口", "提示");
                    return;
                }

                //设置串口参数
                serialPort1.PortName = comboBox_PortNames.Text.ToString();  //serialPort1是serialPort组件的Name 
                serialPort1.BaudRate = Convert.ToInt32(comboBox_BaudRate.SelectedItem.ToString());
                serialPort1.DataBits = Convert.ToInt32(comboBox_DataBit.SelectedItem.ToString());

                //设置停止位
                if (comboBox_StopBit.Text == "One")
                {
                    serialPort1.StopBits = StopBits.One;
                }
                else if (comboBox_StopBit.Text == "Two")
                {
                    serialPort1.StopBits = StopBits.Two;
                }
                else if (comboBox_StopBit.Text == "OnePointFive")
                {
                    serialPort1.StopBits = StopBits.OnePointFive;
                }
                else if (comboBox_StopBit.Text == "None")
                {
                    serialPort1.StopBits = StopBits.None;
                }

                //设置奇偶校验位
                if (comboBox_Parity.Text == "Odd")
                {
                    serialPort1.Parity = Parity.Odd;
                }
                else if (comboBox_Parity.Text == "Even")
                {
                    serialPort1.Parity = Parity.Even;
                }
                else if (comboBox_Parity.Text == "None")
                {
                    serialPort1.Parity = Parity.None;
                }

                try
                {
                    //禁止操作组件
                    comboBox_PortNames.Enabled = false;
                    comboBox_BaudRate.Enabled = false;
                    comboBox_DataBit.Enabled = false;
                    comboBox_StopBit.Enabled = false;
                    comboBox_Parity.Enabled = false;
                    button_Serach.Enabled = false;

                    serialPort1.Open(); //设置完参数后打开串口
                    button_OpenOrClose.Text = "关";  //更改Open按钮文本内容
                }
                catch
                {
                    MessageBox.Show("串口打开失败!");
                }


                serialPort1.DataReceived += new SerialDataReceivedEventHandler(SerialDataReceive);  //打开串口后绑定数据接收
            }
            else if (button_OpenOrClose.Text == "关")
            {
                try
                {
                    //允许操作组件
                    comboBox_PortNames.Enabled = true;
                    comboBox_BaudRate.Enabled = true;
                    comboBox_DataBit.Enabled = true;
                    comboBox_StopBit.Enabled = true;
                    comboBox_Parity.Enabled = true;
                    button_Serach.Enabled = true;


                    serialPort1.DiscardInBuffer();  //清除缓冲区的数据

                    serialPort1.Close();
                    button_OpenOrClose.Text = "开";   //更改Close按钮文本内容
                }
                catch
                {
                    MessageBox.Show("串口打开失败!");
                }
            }
        }
        #endregion
        /**************************************************************************/
        #region 清除输出框
        private void button_CLEAR_Click(object sender, EventArgs e)
        {
            richTextBox_Receive.Clear();     //清楚数据接收框数据
        }
        #endregion
        /**************************************************************************/
        #region 搜索串口(与初始化函数一样)
        private void button_Serach_Click_1(object sender, EventArgs e)
        {

            try
            {
                string[] str = SerialPort.GetPortNames();
                comboBox_PortNames.Items.Clear();
                comboBox_PortNames.Items.AddRange(str);

                if (str.Length > 0)
                {
                    comboBox_PortNames.SelectedIndex = 0;
                    comboBox_BaudRate.SelectedIndex = 7;
                    comboBox_DataBit.SelectedIndex = 3;
                    comboBox_StopBit.SelectedIndex = 0;
                    comboBox_Parity.SelectedIndex = 2;
                }
                else
                {
                    MessageBox.Show("当前无串口连接!");
                }
            }
            catch
            {
                MessageBox.Show("无串口设备!\r\n请检查是否连接设备!\r\n请检查设备驱动!");
            }
        }
        #endregion
        /**************************************************************************/
        #region 发送数据
        private void button_Send_Click_1(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                string[] sendbuff = richTextBox_Send.Text.Split();  //分割输入的字符串,判断有多少个字节需要发送
                int Buff_Len = sendbuff.Length;
                byte[] buff = new byte[Buff_Len];

                for (int i = 0; i < sendbuff.Length; i++)
                {
                    buff[i] = byte.Parse(sendbuff[i], System.Globalization.NumberStyles.HexNumber); //格式化字符串为十六进制数值
                }

                try
                {
                    serialPort1.Write(buff, 0, buff.Length);    //写数据
                    Task.Run(() => printf_data(buff, Buff_Len, 0));
                }
                catch
                {
                    MessageBox.Show("发送失败!!");
                }
            }
            else
            {
                MessageBox.Show("串口未打开!");
            }

        }

        private void updateSQL_Tick(object sender, EventArgs e)
        {
            string sqlupdate = null;
            StringBuilder sqlmess = new StringBuilder();
            for (int j = 13; j < 20; j++)
            {
                sqlmess.Append(strplus[j]);
            }
            sqlupdate = sqlmess.ToString();


            Dao dao = new Dao();
            string sql = $"update dbo.Temp set Temperature = '{sqlupdate}' where No = '1'";
            IDataReader dc = dao.read(sql);
            dc.Close();
            dao.DaoClose();
        }


        #endregion
        /**************************************************************************/
    }
}

效果图1(有连接)

获取串口数据_第1张图片

 效果图2(无连接)

获取串口数据_第2张图片

你可能感兴趣的:(c#)