Advertisement
CuriousScientist

Chart Drawing with Data from Arduino

Oct 17th, 2019
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.80 KB | None | 0 0
  1. //If you found my video helpful, please SUBSCRIBE:  https://www.youtube.com/channel/UCKp1MzuAceJnDqAvsZl_46g
  2. //The code belongs to this tutorial video: https://youtu.be/rBDJ-KPIxq8
  3.  
  4.  
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Data;
  9. using System.Drawing;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using System.Windows.Forms;
  14. using System.IO.Ports; //Serial port handling
  15. using System.Windows.Forms.DataVisualization.Charting;
  16. using System.IO;
  17.  
  18. namespace Serial_Arduino
  19. {
  20.     public partial class Form1 : Form
  21.     {
  22.         /*
  23.          *  Structure of the input data
  24.          *  col1 \t col2 \t col3 \n
  25.          *  col1 \t col2 \t col3 \n
  26.          *  col1 \t col2 \t col3 \n
  27.          *  .
  28.          *  .
  29.          *  .
  30.          */
  31.  
  32.         private string[] split = new string[3]; //3 -> because of col1,2,3.
  33.         private double _split1, _split2, _split3;
  34.         private double[] Split1, Split2, Split3; //arrays for the split data
  35.         private int counter; //counter
  36.         private string foutput; //file-output
  37.  
  38.  
  39.         private SerialPort SerPort;  //serial port
  40.         private string ReceivedData; //received data from serial port.
  41.        
  42.         public Form1()
  43.         {
  44.             InitializeComponent();
  45.             FetchAvailablePorts(); //at the start we check the list of available COM ports
  46.             InitChart(); //at the start we initialize the chart
  47.            
  48.             //creating the arrays. make sure that you have enough space (number in the [])
  49.             //for dynamic array you might want to use List<>.
  50.             Split1 = new double[1000];
  51.             Split2 = new double[1000];
  52.             Split3 = new double[1000];
  53.         }
  54.  
  55.         void FetchAvailablePorts()
  56.         {
  57.             String[] ports = SerialPort.GetPortNames(); //We get the available COM ports
  58.             AvailablePortsBox.Items.AddRange(ports);
  59.  
  60.         }
  61.  
  62.         private void ConnectToPort_Click(object sender, EventArgs e)
  63.         {
  64.             SerPort = new SerialPort(); //instantiate our serial port SerPort
  65.            
  66.             //hardcoding some parameters, check MSDN for more
  67.             SerPort.BaudRate = 9600;
  68.             SerPort.PortName = AvailablePortsBox.Text;
  69.             SerPort.Parity = Parity.None;
  70.             SerPort.DataBits = 8;
  71.             SerPort.StopBits = StopBits.One;
  72.             SerPort.ReadBufferSize = 200000000;
  73.             SerPort.DataReceived += SerPort_DataReceived;
  74.  
  75.             try
  76.             {
  77.                 SerPort.Open();
  78.             }
  79.             catch(Exception ex)
  80.             {
  81.                 MessageBox.Show(ex.Message, "Error...!");
  82.             }
  83.  
  84.  
  85.         }
  86.  
  87.         private void SerPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
  88.         {
  89.             ReceivedData = SerPort.ReadLine(); //read the line from the serial port
  90.  
  91.             this.Invoke(new Action(ProcessingData)); //at each received line from serial port we "trigger" a new processingdata delegate
  92.         }
  93.  
  94.         private void ProcessingData() //processing received data and plotting it on a chart
  95.         {
  96.  
  97.             try
  98.             {
  99.                 ReceivedDataBox.Text += ReceivedData.ToString() + Environment.NewLine; //print the received data into the textbox
  100.  
  101.                 //reminder: col1 \t col2 \t col3 \n
  102.  
  103.                 split = ReceivedData.Split('\t'); //split the data separated by tabs; split[3] -> split[col1], split[col2], split[col3]; split[i]
  104.                
  105.                 //parsing the string to double (we expect numbers from the Arduino)
  106.                 Double.TryParse(split[0], out _split1);
  107.                 Double.TryParse(split[1], out _split2);
  108.                 Double.TryParse(split[2], out _split3);
  109.  
  110.                 //the ith element of the Split array will be the recently parsed _split.
  111.                 Split1[counter] = _split1;
  112.                 Split2[counter] = _split2;
  113.                 Split3[counter] = _split3;
  114.  
  115.                 //plot
  116.                 DataChart.Series["Channel1"].Points.AddXY(Split1[counter], Split2[counter]); //col1 , col2
  117.                 DataChart.Series["Channel2"].Points.AddXY(Split1[counter], Split3[counter]); //col1 , col3
  118.                 DataChart.ChartAreas[0].RecalculateAxesScale(); //recalculate.rescale
  119.  
  120.                 //handle the output
  121.                 foutput = _split1.ToString() + "\t" + _split2.ToString() + "\t" + _split3.ToString() + Environment.NewLine;
  122.                 //we put together the variables into a string (foutput) again
  123.  
  124.                 if (FileSavingCheckBox.Checked == true) //file saving, same folder as executable
  125.                 {
  126.                     using (StreamWriter sw = File.AppendText("Outputfile.txt"))//appendtext = the previous file will be continued
  127.                     {
  128.                         sw.Write(foutput); //write the content of foutput into the file
  129.                     }
  130.                 }
  131.  
  132.             }
  133.             catch { }
  134.  
  135.             counter++;
  136.             //the value of the counter is increased by one at each loop (at each new data)
  137.             //this makes sure that the next series of data is written in the next line of the arrays
  138.  
  139.  
  140.         }
  141.  
  142.         private void SendSerialButton_Click(object sender, EventArgs e)
  143.         {
  144.             SerPort.WriteLine(SenderTextBox.Text.ToString());
  145.         }
  146.  
  147.         private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  148.         {
  149.             try
  150.             {
  151.                 SerPort.Close();
  152.             }
  153.             catch { }
  154.         }
  155.  
  156.         private void InitChart() //initializing the chart
  157.         {
  158.             DataChart.ChartAreas[0].AxisX.IsStartedFromZero = false; //in case we get negative number
  159.             DataChart.ChartAreas[0].AxisX.MajorGrid.LineWidth = 0; //no grids
  160.             DataChart.ChartAreas[0].AxisY.MajorGrid.LineWidth = 0;
  161.             DataChart.ChartAreas[0].AxisX.Title = "X-axis ()"; //name of the x-y axis
  162.             DataChart.ChartAreas[0].AxisY.Title = "Y-axis ()";
  163.             DataChart.ChartAreas[0].AxisX.Enabled = AxisEnabled.True;
  164.             DataChart.ChartAreas[0].AxisY.Enabled = AxisEnabled.True;
  165.             DataChart.ChartAreas[0].CursorX.AutoScroll = true;
  166.  
  167.             //Check the MSDN documentation!
  168.  
  169.             //series for the channel1
  170.             Series series = new Series()
  171.             {
  172.                 Name = "Channel1",
  173.                 Color = System.Drawing.Color.Black,
  174.                 ChartType = SeriesChartType.FastLine,
  175.                 IsXValueIndexed = true
  176.             };
  177.  
  178.             DataChart.Series.Add(series);
  179.  
  180.             //series for the channel2
  181.             Series series2 = new Series()
  182.             {
  183.                 Name = "Channel2",
  184.                 Color = System.Drawing.Color.Red,
  185.                 ChartType = SeriesChartType.FastLine,
  186.                 IsXValueIndexed = true
  187.             };
  188.  
  189.             DataChart.Series.Add(series2);
  190.  
  191.         }
  192.        
  193.     }
  194. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement