Frequency tracking App :: Module 1

Herewith first modul is going to be introduced .

Module 1: Code reference



          using System;
          using System.Collections.Generic;
          using System.Linq;
          using System.Threading.Tasks;
          using System.Windows.Forms;

          namespace CHRreader_2
          {
              static class Program
              {
                  /// 
                  /// The main entry point for the application.
                  /// 
                  [STAThread]
                  static void Main()
                  {
                      Application.EnableVisualStyles();
                      Application.SetCompatibleTextRenderingDefault(false);
                      Application.Run(new Form1());
                  }
              }
          }
        

A overall code structure is nicely divided into conceptual untis, i.e. it has particular regions

Form1.cs

        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.Globalization;
        using System.Diagnostics;

        using MathNet.Numerics;                    // Library for 
        using MathNet.Numerics.IntegralTransforms; // FFT

        using System.Windows.Forms.DataVisualization.Charting;
        using System.Numerics; // complex number format 


        namespace CHRreader_2
        {
            // stop button general delegate 
            public delegate void ptrf_stopPressed();
            public delegate void ptrf_startPressed();

            public partial class Form1 : Form
            {

                public event ptrf_stopPressed genStopped;
                public event ptrf_startPressed genStarted; 
                
                #region TIMER FCN

                private Timer time = new Timer(); // set of the timer 
                Stopwatch stopWatch;              // activate the stopwatch
                double ttime = 0;                 // say this is the time 0 
                static int counter = 0;           // set ticker counter to 0 
            


                private void InitializeTimer()
                {
                    stopWatch = new Stopwatch();

                    try {
                        setupMeasurement();
                        time.Interval = Convert.ToInt32(comboBox1.SelectedItem);
                        
                        
                    }
                    catch {
                        time.Interval = 100;
                    }

                    time.Tick += new EventHandler(IncreaseProgressBar);  // Tick function is a pointer to IncreaseProgressBar 
                    time.Tick += new EventHandler(timer_function1);
                    time.Start();
                    stopWatch.Start();

                }

                private void setupMeasurement()
                {
                    double tms = Convert.ToDouble(comboBox1.SelectedItem);
                    double nsteps = Convert.ToDouble(textBox1.Text);
                    double t = tms * nsteps / 1000.0;
                    label5.Text = t.ToString() + " sec";
                    progressBar1.Maximum = Convert.ToInt32(nsteps);
                }
                #endregion
            
                #region ADDITONAL UIs

                Form2 Analyser; // poniter Analyser to Form2

                #endregion
            
                #region  GLOBAL static lists which can be aproached from another classes
                public static List vec1, vec2, vec3, vec4;      // available lists    
                public static double sampFreq;
                public static bool runTime = false;   // still runing or not 


                #endregion

                #region CONSTRUCTOR
                public Form1()
                {
                    InitializeComponent();      // VSTUDIO
                    StartPosition = FormStartPosition.Manual;
                    Location = new Point(10, 50);

                    setupGenDefaults();         // sets up the form members for the first screen .. 
                    vec1 = new List(); // initialize vector;
                    vec2 = new List(); // initialize vector;
                    vec3 = new List(); // initialize vector;
                    vec4 = new List(); // initialize vector;

                    sampFreq = Convert.ToDouble(textBoxFs.Text);

                }
                private void setupGenDefaults()
                {
                    // trackBar1
                    // 
                    //
                    // setup the bars and labels for function generator ... 

                    // wave 1 setups 

                    trackBarAmp1.Maximum = 10;
                    trackBarAmp1.Value = 1;

                    labelA1.Text = "  A1 : " + trackBarAmp1.Value.ToString();  // trackBar 1
                    lblPH1.Text = "PH1: " + trackBarPhase1.Value.ToString() + " °";
                    lblF1.Text = "FR. : " + textBoxFreq1.Text + " Hz";

                    trackBarPhase1.Maximum = 10;
                    trackBarPhase1.Value = 0;

                    // wave 2 setups 
                    trackBarAmp2.Maximum = 10;
                    trackBarAmp2.Value = 1;

                    labelA2.Text = "  A2 : " + trackBarAmp1.Value.ToString(); // trackBar2
                    lblPH2.Text = "PH2: " + trackBarPhase2.Value.ToString() + " °";
                    lblF2.Text = "FR. : " + textBoxFreq2.Text + " Hz";

                    trackBarPhase2.Maximum = 10;
                    trackBarPhase2.Value = 0;

                    //wave 3 setups 
                    trackBarAmp3.Maximum = 10;
                    trackBarAmp3.Value = 1;

                    labelA3.Text = " A3 : " + trackBarAmp3.Value.ToString(); // trackBar3
                    lblPH3.Text = "PH3: " + trackBarPhase3.Value.ToString() + " °";
                    lblF3.Text = "FR. : " + textBoxFreq3.Text + " Hz";

                    trackBarPhase3.Maximum = 10;
                    trackBarPhase3.Value = 0;

                    
                }
                #endregion
                
                #region UI Components

                private void button1_Click(object sender, EventArgs e)
                {
                    runTime = true;

                    if (Analyser != null) // if object exists 
                    {
                        genStarted += new ptrf_startPressed(Analyser.setSemaphore); // conncet pointer to function 
                        genStarted(); // emit event .. 
                    
                    }

                    // clear the vectors available 

                    vec1.Clear();
                    vec2.Clear();
                    vec3.Clear();
                    vec4.Clear();

                    // set the time based variables and UI components
                    progressBar1.Value = 0;
                    ttime = 0;
                    counter = 0;

                    // clear the charts 
                    chartCleaner();

                    // restart all 
                    setupMeasurement();
                    InitializeTimer();

                    // send information about eventuall campling frequency change to globals 
                    sampFreq = Convert.ToDouble(textBoxFs.Text);



                }
        

                private void chartCleaner()
                {
                    chart1.Series["wave"].Points.Clear();
                    chart1.Series["wave2"].Points.Clear();
                    chart1.Series["wave3"].Points.Clear();
                    chart1.Series["wave4"].Points.Clear();

                }

                #endregion

                #region TIMER BASED EVENT FUNCTION CALLERS

                ///  Happens at every tick of msec setup in the UI 
                /// 
                ///  fun1: IncreaseProgressBar()
                ///  fun2: timer_function1()                        1.this block    2.this block
                ///                                     ....|----|.........|----|........|-----| ... until condition finished 
                ///                                                 50msec        50msec


                private void IncreaseProgressBar(object sender, EventArgs e)
                {
                    progressBar1.Increment(1);

                    double progVal = progressBar1.Value;
                    double nsteps = Convert.ToDouble(textBox1.Text);

                    label1.Text = Convert.ToString(100*progVal/nsteps) + "% Completed";
                    if (progressBar1.Value == progressBar1.Maximum)
                    {
                        
                        time.Stop();
                        runTime = false; // not running anymore .. .
                        if (Analyser != null)
                        {
                            genStopped += new ptrf_stopPressed(Analyser.setSemaphore);
                            genStopped();
                        }
                    }
                }

                private void timer_function1(object sender, EventArgs e)
                {

                    /// Stopwatch stops on every tick after start button pressed 
                    stopWatch.Stop();
                    TimeSpan ts = stopWatch.Elapsed;
                    ttime += ts.TotalMilliseconds/1000;
                    lblElapsed.Text = ttime.ToString() + "[sec]";         
                    lblTime.Text = ts.Milliseconds.ToString() + " [msec]";
                    counter++;

                
                    // take the sampling rate 
                    double dt = 1/Convert.ToDouble(textBoxFs.Text);
                    //
                    // Just taking inputs from the UI every time it ticks
                    //
                
                        // create the waves given the frequencies, sampling time and phase 
                        double f1 = Convert.ToDouble(textBoxFreq1.Text);
                        double a1 = Convert.ToDouble(trackBarAmp1.Value);
                        double _ph1 = Convert.ToDouble(trackBarPhase1.Value);
                        double ph1 = convert2Deg(_ph1, trackBarPhase1.Maximum);
                        if (!checkBox1.Checked)
                            a1 = 0;


                        double f2 = Convert.ToDouble(textBoxFreq2.Text);
                        double a2 = Convert.ToDouble(trackBarAmp2.Value);
                        double _ph2 = Convert.ToDouble(trackBarPhase2.Value);
                        double ph2 = convert2Deg(_ph2, trackBarPhase2.Maximum);
                        if (!checkBox2.Checked)
                            a2 = 0;

                        double f3 = Convert.ToDouble(textBoxFreq3.Text);
                        double a3 = Convert.ToDouble(trackBarAmp3.Value);
                        double _ph3 = Convert.ToDouble(trackBarPhase3.Value);
                        double ph3 = convert2Deg(_ph3, trackBarPhase3.Maximum);
                        if (!checkBox3.Checked)
                            a3 = 0;
                
                    // .............................................................. on each step update what is in UI 


                    double w1 = a1*wave(f1, dt, ph1);
                    double w2 = a2*wave(f2, dt, ph2);
                    double w3 = a3*wave(f3, dt, ph3);

                    vec1.Add(w1);
                    vec2.Add(w2);
                    vec3.Add(w3);
                    vec4.Add(w1 + w2 + w3);
            

                    // CHART1: if points are more then 250, reduce the summation wave 
                    // thickenss and do not show the first three waves anymore ... 
                    //
                    int steps = Convert.ToInt32(textBox1.Text);
                    if (steps < 250)
                    {

                        chart1.Series["wave"].Points.AddXY(counter * dt, w1);
                        chart1.Series["wave2"].Points.AddXY(counter * dt, w2);
                        chart1.Series["wave3"].Points.AddXY(counter * dt, w3);
                        chart1.Series["wave4"].BorderWidth = 3;                
                    }

                    if (steps > 1000)
                    {
                        chart1.Series["wave4"].BorderWidth = 1;
                    }
                    double sumW = w1 + w2 + w3;
                    chart1.Series["wave4"].Points.AddXY(counter * dt, sumW);         

                }
                //  STOP BUTTON
                //
                //
                //
                private void cmdStop_Click(object sender, EventArgs e)
                {
                    runTime = false; 
                    time.Stop();
                    if (Analyser != null)
                    {
                        genStopped += new ptrf_stopPressed(Analyser.setSemaphore);
                        genStopped();
                    }
            
                }


                #endregion
            
                #region UI SETUP BASED EVENTS
            
                #region FUN GEN - wave1 UI events 
                private void trackBarAmp1_Scroll(object sender, EventArgs e) //  Amp1
                {
                    
                    labelA1.Text = "A1: " + trackBarAmp1.Value.ToString();
                }

                private void trackBarPhase1_Scroll(object sender, EventArgs e) // PH1
                {
                    double phi1 = convert2Deg(trackBarPhase1.Value, trackBarPhase1.Maximum);
                    lblPH1.Text = "PH: " + phi1.ToString() + "°";
                }

                private void f1_text_new(object sender, EventArgs e) //  FREQ1
                {
                    lblF1.Text = "f1: " + textBoxFreq1.Text;
                }
                #endregion

                #region FUN GEN - wave2 UI events
                private void trackBarAmp2_Scroll(object sender, EventArgs e)
                {
                    labelA2.Text = "A2: " + trackBarAmp2.Value.ToString();

                }
                private void trackBarPhase2_Scroll(object sender, EventArgs e)
                {
                    double phi2 = convert2Deg(trackBarPhase2.Value, trackBarPhase2.Maximum);
                    lblPH2.Text = "PH: " + phi2.ToString() + "°";
                }

                private void textBoxFreq2_TextChanged(object sender, EventArgs e)
                {
                    lblF2.Text = "f2: " + textBoxFreq2.Text;
                }
                #endregion

                #region FUN GEN - wave3 UI events
                private void trackBarAmp3_Scroll(object sender, EventArgs e)
                {
                    labelA3.Text = "A3: " + trackBarAmp3.Value.ToString();
                }

                private void trackBarPhase3_Scroll(object sender, EventArgs e)
                {
                    double phi3 = convert2Deg(trackBarPhase3.Value, trackBarPhase3.Maximum);
                    lblPH3.Text = "PH: " + phi3.ToString() + "°";

                }

                private void button2_Click(object sender, EventArgs e)
                {
                    if (Analyser == null)
                    {
                        Analyser = new Form2();
                        Analyser.setSemaphore();
                        Analyser.Show();
                    }
                    else
                    {
                        Analyser.Close();
                        Analyser = null;
                        Analyser = new Form2();
                        Analyser.setSemaphore();
                        Analyser.Show();
                    
                    }
                
                }

                private void button3_Click(object sender, EventArgs e)
                {
                    Close();
                }

                #endregion

                #region APPENDIX: MATH PUBLIC FUNCTIONS 

                public double wave(double f, double dt, double phi)
                {
                    double PHI = 2 * Math.PI * phi / 360;
                    return Math.Sin(2 * Math.PI * f * ((double)counter) * dt + PHI);
                }

                public double convert2Deg(double trackBarValue, double trackBarMax)
                {
                    // returns given the relative slider value from 1 to 10 
                    // to circural degrees 

                    double u = 2.0 * Math.PI * (trackBarValue / (double)trackBarMax);
                    double Deg = u * 180.0 / Math.PI;
                    return Deg;
                }

                // computes the fft of the generated waveform 
                public void typeVector(List vec)
                {
                    try
                    {
                        for (int i = 0; i < vec.Count; i++)
                        {
                            // write what is in the vector 
                            Console.WriteLine("{0},{1}\n", i, vec.ElementAt(i));  
                        }

                    }
                    catch { 

                    }
                
                }


                #endregion

            
            }
        }