本文介绍了如何从Com端口收到数据(Tempareature)如图2所示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 ZedGraph;
using System.IO;
using System.IO.Ports;


namespace Ex2
{
    public partial class Form1 : Form
    {
        // Starting time in milliseconds
        int tickStart = 0;


        private SerialPort COMport;
       // private string buffer = "";
        delegate void axisChangeZedGraphCallBack(ZedGraphControl zg);
        delegate void SetText(string text);// Phuc vu comport
        delegate void SetTextCallback(string text); // Khai bao delegate SetTextCallBack voi //         //tham so string
        string chuoi;
        double dulieu;


        public Form1()
        {
            InitializeComponent();
        }
        //------------------------------
        private void connect()
        {
            COMport = new SerialPort("COM1", 1200, Parity.None, 8, StopBits.One);
            COMport.DataReceived += new SerialDataReceivedEventHandler(DataReceive);
            // P.DataReceived += new SerialDataReceivedEventHandler(DataReceive);
            if (!COMport.IsOpen)
                COMport.Open();
        }
        //------------------------------

        private string Byte2Decimal(byte[] comByte)
        {
            
            StringBuilder builder = new StringBuilder(comByte.Length * 3);
            foreach (byte data in comByte)
                //chuyen sang he 10
                builder.Append(Convert.ToString(data, 10)).Append(",");//Convert.ToString(data, //16): hexa
            return builder.ToString().ToUpper();
        }
        //===============================================
        int cnt = 0;
        private void DataReceive(object sender, SerialDataReceivedEventArgs e)
        {
           
            try
            {
                //Chuoi = Comm.ReadExisting(); // đọc giá trị trong trường hợp là ASCII (<= 127)
                int bytes = COMport.BytesToRead;
                byte[] comBuf = new byte[bytes];
                
                COMport.Read(comBuf, 0, bytes);
                 this.BeginInvoke(new SetText(ProcessData), new object[] { Byte2Decimal(comBuf) });// ProcessData va Byte2Decimal viet phia tren              
            }
            catch
            {
                MessageBox.Show("Can not read from COM PORT ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        //===============================================
       int i,cnt2;
        private void ProcessData(string data)
        {
           // this.txtkq.Text += data;
            chuoi += data;
            string[] subChuoi = chuoi.Split(new char[] { ',' });
            dulieu = Convert.ToDouble(data);
            cnt2++;
            txtkq.Text += data.Trim();// show data on text box
           
            //-------------------------------------------
               
            if (cnt == 20)// count upto 20 bytes autoclear textbox
            {
                txtkq.Text = "";
                cnt = 0;
            }

       }
        
        //========================================================
        private void Form1_Load(object sender, EventArgs e)
        {
            connect();
           // cnt2 = 0;
            GraphPane myPane = zedGraphControl1.GraphPane;// khai bao bien Zedgraph
            myPane.Title.Text = "Test of Dynamic Data Update with ZedGraph\n" +
                  "(After 25 seconds the graph scrolls)";//  title
            myPane.XAxis.Title.Text = "Time, Seconds";//  x
            myPane.YAxis.Title.Text = "Temparature ";// y

            // Save 1200 points.  At 50 ms sample rate, this is one minute
            // The RollingPointPairList is an efficient storage class that always
            // keeps a rolling set of point data without needing to shift any data values
            RollingPointPairList list = new RollingPointPairList(1200);// create a list 1200 samples

            // Initially, a curve is added with no data points (list is empty)
            // Color is blue, and there will be no symbols
            LineItem curve = myPane.AddCurve("Data", list, Color.Red, SymbolType.None);

            // Sample at 50ms intervals
            timer1.Interval = 50;// time to get sample
            timer1.Enabled = true;//  timer
            timer1.Start();// enable timer

            // Just manually control the X axis range so it scrolls continuously
            // instead of discrete step-sized jumps
            myPane.XAxis.Scale.Min = 0;
            myPane.XAxis.Scale.Max = 30;// leght x
            myPane.XAxis.Scale.MinorStep = 1;//
            myPane.XAxis.Scale.MajorStep = 5;

            // Scale the axes
            zedGraphControl1.AxisChange();//update 

            // Save the beginning time for reference
            tickStart = Environment.TickCount;// restart

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            // Make sure that the curvelist has at least one curve
            if (zedGraphControl1.GraphPane.CurveList.Count <= 0)
                return;

            // Get the first CurveItem in the graph
            LineItem curve = zedGraphControl1.GraphPane.CurveList[0] as LineItem;
            if (curve == null)
                return;

            // Get the PointPairList
            IPointListEdit list = curve.Points as IPointListEdit;
            // If this is null, it means the reference at curve.Points does not
            // support IPointListEdit, so we won't be able to modify it
            if (list == null)
                return;

            // Time is measured in seconds
            double time = (Environment.TickCount - tickStart) / 1000.0;

            
        
                list.Add(time,dulieu);
                
                    Scale xScale = zedGraphControl1.GraphPane.XAxis.Scale;
                    if (time > xScale.Max - xScale.MajorStep)
                    {
                        xScale.Max = time + xScale.MajorStep;
                        xScale.Min = xScale.Max - 30.0;
                    }
               
            }
            // Make sure the Y axis is rescaled to accommodate actual data
            zedGraphControl1.AxisChange();
            // Force a redraw
            zedGraphControl1.Invalidate();
        }
        private void Form1_Resize( object sender, EventArgs e )
      {
         SetSize();
      }

      // Set the size and location of the ZedGraphControl
      private void SetSize()
      {
         // Control is always 10 pixels inset from the client rectangle of the form
         Rectangle formRect = this.ClientRectangle;
         formRect.Inflate( -10, -10 );

         if ( zedGraphControl1.Size != formRect.Size )
         {
            zedGraphControl1.Location = formRect.Location;
            zedGraphControl1.Size = formRect.Size;
         }
      }

      private void checkBox1_CheckedChanged(object sender, EventArgs e)
      {
          //this.checkBox1 = true;
         // this.TopMost = TopMost;
          this.TopMost = checkBox1.Checked;
      }

      private void button1_Click(object sender, EventArgs e)
      {
          txtkq.Text = "";
      }
   
    }
}

推荐答案


这篇关于如何从Com端口收到数据(Tempareature)如图2所示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 19:47