首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

c# 串口数据求大神解决方法

2013-07-01 
c# 串口数据求大神最近在做医疗传感器的端口数据读取,希望边读边存到TXT中。串口数据一直在进这是部分代码p

c# 串口数据求大神
最近在做医疗传感器的端口数据读取,希望边读边存到TXT中。串口数据一直在进
这是部分代码

        private void button4_Click(object sender, EventArgs e)
        {   //接收数据
            byte[] data = new byte[port1.BytesToRead];
            port1.Read(data, 0, data.Length);
            string ss;
            ss = byteToHexStr(data);   //十六进制显示      
            Write(ss);
         }
 为什么只存了部分数据,没有一直储存。  难道只是read读取的缓冲区 ?  缓冲区满了就读不了了吗?  

            
[解决办法]
”串口数据一直在进“  

你这样写代码肯定只能读到一部分了

参考以下代码吧


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;

namespace 读取串口数据
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        System.IO.Ports.SerialPort comport = new System.IO.Ports.SerialPort();
        private void Form1_Load(object sender, EventArgs e)
        {
            comport.BaudRate = 9600;
            comport.DataBits = 8;


            comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), "One");
            comport.Parity = (Parity)Enum.Parse(typeof(Parity), "None");
            comport.Encoding = Encoding.GetEncoding("utf-8");//Encoding.GetEncoding("utf-8")和Encoding.Default
            comport.PortName = "COM14";
            comport.Open();
            comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
        }
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
               string   data = comport.ReadExisting();
                this.textBox1.Invoke(new EventHandler(delegate
                {
                    string[] arr = data.Split('
[解决办法]
');
                    if (arr.Length > 1)
                    {
                        this.textBox1.Text = this.textBox1.Text +arr[1] ;
                    }
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);


            }
        }
    }
}

热点排行