Click here to Skip to main content
15,893,722 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
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 = "";
      }
   
    }
}
Posted

1 solution

I am newer.I dont know how to post my pictures ! I am really sorry.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900