Click here to Skip to main content
15,885,365 members
Home / Discussions / C#
   

C#

 
GeneralRe: Implementing a moving average Pin
auting8217-Feb-18 0:36
auting8217-Feb-18 0:36 
AnswerRe: Implementing a moving average Pin
Ralf Meier17-Feb-18 0:53
mveRalf Meier17-Feb-18 0:53 
GeneralRe: Implementing a moving average Pin
auting8217-Feb-18 1:13
auting8217-Feb-18 1:13 
GeneralRe: Implementing a moving average Pin
Ralf Meier17-Feb-18 3:30
mveRalf Meier17-Feb-18 3:30 
AnswerRe: Implementing a moving average Pin
Ralf Meier17-Feb-18 3:50
mveRalf Meier17-Feb-18 3:50 
GeneralRe: Implementing a moving average Pin
auting8217-Feb-18 7:40
auting8217-Feb-18 7:40 
GeneralRe: Implementing a moving average Pin
Ralf Meier17-Feb-18 10:11
mveRalf Meier17-Feb-18 10:11 
GeneralRe: Implementing a moving average Pin
auting8218-Feb-18 8:40
auting8218-Feb-18 8:40 
Hi Ralf, I think I have solved the problem now.
I created a class for MovingAverageFilter.
The only little problem I have left is implementing an automatic sampling by ticking off check box. Struggling with that at the moment.
Also I guess I do not have proper Random numbers as I always start off from the same Seed No., would be great to Randomize that properly, so that it creates completely new numbers next time I run the app.

See my code:
Main Form1.cs

C#
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.IO;
using System.Xml.Linq;
using System.Windows.Forms;
using System.Globalization;
using System.Linq;
using System.Collections.Generic;
using System.Collections;



namespace DAQ_Simulator
{
    public partial class Form1 : Form
    {
        int counter;
        int count_lines; 
        System.Timers.Timer t;
        //Log time varibles
        int LoggingTime=56;
        int LogTimeLeft;

        //Sampling variables
        float SamplingTime = 5.9f;        
        private int clickcounterSampling;
        private DateTime datetime;
        private DateTime datetime2;
        private DateTime NextLoggingTime;
        int maxAI = 7;
        int maxDI = 3;
        int maxSid = 9;
        String SensorText;
        String sTxt1;
        String fTxt;
        // Create an array of 10 sensor objects
        Sensor[] SensorObject = new Sensor[10];
        MA_Filter[] FilterObject = new MA_Filter[10];
        
        public Form1()
        {
            InitializeComponent();

            for (counter = 0; counter < maxSid; counter++)
            {
                SensorObject[counter] = new Sensor(counter);
               FilterObject[counter] = new MA_Filter(counter); //Create filters
            }        
        }
        private void displaySensorData(object sender, EventArgs e)
        {
        }
        private void groupSampl_Enter(object sender, EventArgs e)
        {

        }
        private void textSampling_TextChanged(object sender, EventArgs e)
        {



        }
        private void btnSampling_Click(object sender, EventArgs e)
        {
            txtNextSamplingTime.Text = "5.9sec";
            clickcounterSampling++;
            if (clickcounterSampling == 1)
            {
                txtSensorValues.Text = "TimeStamp        AI.1,      AI.2,      AI.3,      AI.4,      AI.5,      AI.6,    AI.7,           DI.1,      DI.2,       DI.3" + "\r\n";
                txtFilterValues.Text = "AI.1,   AI.2,   AI.3,   AI.4,   AI.5,   AI.6,   AI.7" ;
               
            }
            if (clickcounterSampling >= 5)
            { txtFilterValues.Text += "\r\n"; }
            
            if (SamplingTime <= 0)
            {
               
                SamplingTime = SamplingTime + 5.9f;
            }
            
            if (SamplingTime <= 5.9f && SamplingTime >= 0)
            {

                btnSampling.Enabled = false;

            }
            timer1 = new System.Windows.Forms.Timer();
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Interval = 1000; // 1 second
            timer1.Start();
           // txtNextSamplingTime.Text = SamplingTime.ToString();

            datetime2 = DateTime.Now.AddSeconds(5).AddMilliseconds(900);
            String time2 = datetime2.ToString("HH:mm:ss.FFF", CultureInfo.InvariantCulture);
            textSampling.Text = time2;

            //counts the lines in textbox

            count_lines = txtFilterValues.Lines.Length;
            count_lines =count_lines- 1;//minus header line
            txtNumberWritings.Text = count_lines.ToString();

            Sampling(); // sample the signals

        }

        private void groupLogg_Enter(object sender, EventArgs e)
        {

        }
        private void labelLoggingText_Click(object sender, EventArgs e)
        {


        }
        private void btnLogging_Click(object sender, EventArgs e)
        {
            if (LoggingTime == 0)
            {
               
                LoggingTime = LoggingTime + 56;
            }
            
            if (LoggingTime <= 56 && LoggingTime >= 0)
            {
                
                btnLogging.Enabled = false;

            }
            timer2 = new System.Windows.Forms.Timer();
            timer2.Tick += new EventHandler(timer2_Tick);
            timer2.Interval = 1000; // 1 second
            timer2.Start();
            txtLogging.Text = LoggingTime.ToString();

            NextLoggingTime = DateTime.Now.AddSeconds(4);
            String time3 = NextLoggingTime.ToString("HH:mm:ss.FFF", CultureInfo.InvariantCulture);
           
            txtLogging.Text =time3;

            Logging();


        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            SamplingTime--;
            txtNextSamplingTime.Text = SamplingTime.ToString("F2")+"sec";
            if (SamplingTime <= 0)
            {
                timer1.Stop();
                btnSampling.Enabled = true;
                txtNextSamplingTime.Clear();
            }                      
        }

        private void Sampling()
        {
            datetime = DateTime.Now;
           
            txtSensorValues.Text += datetime.ToString("HH:mm:ss.FFF", CultureInfo.InvariantCulture) + "    ";
            
            double[] AnalogSensorValues = new double[maxAI];
            
          
                      
            for (int id = 0; id < maxAI; id++)
            {
                AnalogSensorValues[id] = SensorObject[id].GetAnalogValue(); //for loops runs through the loop and inserts random number between 0-1 for each sensors ID

                double filter=+FilterObject[id].CalculateMovingAverage(AnalogSensorValues[id]);
                SensorText = AnalogSensorValues[id].ToString("F3");//defines a string variable in order to print out sensor values
                fTxt = filter.ToString("F3");
                txtSensorValues.Text += SensorText + "    ";//prints out sesnor values in text box
                
                if (clickcounterSampling >= 5)
                {                   
                    txtFilterValues.Text += "  " + fTxt + " ";                   
                }              
            }
            
            for (int id = maxSid - maxDI; id < maxSid; id++)
            {
                int DigitalSensorValues = SensorObject[id].GetDigitalValue();
                sTxt1 = DigitalSensorValues.ToString();
                txtSensorValues.Text += "         " + sTxt1 + "    ";
            }
            txtSensorValues.Text += "\r\n";
            
        }
        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("This is a DAQ Simulator that recieves 7analog and 3 digital signals and displayes the values in a textbox." +
                "Raw measuremnt data is filtered with a Moving Average filter where average of the 5 last measuremnts are displayed","Input Information",System.Windows.Forms.MessageBoxButtons.OK);


        }

        private void Logging()
        {
            

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
           if (saveFileDialog1.ShowDialog() == DialogResult.OK)
           {
           using (Stream s = File.Open(saveFileDialog1.FileName,FileMode.CreateNew))
           using (StreamWriter sw = new StreamWriter(s))
               {
              sw.WriteLine(txtSensorValues.Text+txtSensorValues);

               textFilePath.Text = string.Format("{0}", openFileDialog1.FileName);
           }

           textFilePath.Text = saveFileDialog1.FileName.ToString();
           }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            


        }

        
        private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
        {

        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
           
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            LoggingTime--;
            txtNextLogg.Text = LoggingTime.ToString()+"sec";
            if (LoggingTime <= 0)
            {             
                timer2.Stop();
                btnLogging.Enabled = true;
                
                txtNextLogg.Clear();
                txtNextLogg.Text = "56 sec";
            }
        }

        private void chckAutSampl_CheckedChanged(object sender, EventArgs e)
        {
            if (chckAutSampl.Enabled==true)
            {
                SamplingTime--;
                txtNextSamplingTime.Text = SamplingTime.ToString("F2") + "sec";
                if (SamplingTime <= 0)
                {
                    timer3.Stop();
                    txtNextSamplingTime.Clear();
                }
                timer3 = new System.Windows.Forms.Timer();
                timer3.Tick += new EventHandler(timer1_Tick);
                timer3.Interval = 1000; // 1 second
                timer3.Start();
            }
           
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            SamplingTime--;
            txtNextSamplingTime.Text = SamplingTime.ToString("F2") + "sec";
            if (SamplingTime <= 0)
            {

                timer3.Stop();
                
                chckAutSampl.Enabled = false;

                txtNextSamplingTime.Clear();


            }
        }
    }
}



Sensor class,

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAQ_Simulator
{
    public class Sensor
    {
       
        double AnalogVal;
        int DigVal;
        int sId;
        Random  rSensVal;
        public Sensor(int id)
        {
            sId = id;
            rSensVal = new Random(id);           
            AnalogVal = 0.0F;
        }        
        public double GetAnalogValue(double minAnalogVolt=0.00F,double maxAnalogVolt=1.00F) 
        {
            if(minAnalogVolt <= AnalogVal && AnalogVal<= maxAnalogVolt) //defines measurement interval for sensor
                 AnalogVal = rSensVal.NextDouble(); //generates values between 0-1           
                 return AnalogVal; //return a value        
        }
        public int GetDigitalValue(int digMin = 0, int digMax = 1)
        {
            DigVal = rSensVal.Next(0,2);
            return DigVal;
        }
        public int GetSensId()
        {
            return sId;
        }              
    }
}


Moving Average Filter Class,


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAQ_Simulator
{
    


    public class MA_Filter

    {
        public double[] samples = new double[5];
        public int index;
        public int count;

        public MA_Filter(int id)
        {
            count = 0;
            index = 0;
        }      
            public double CalculateMovingAverage(double newVal)
            {
                // Insert
                if (count != samples.Length) count++;
                samples[index++] = newVal;
                if (index == samples.Length) index = 0;
                // Get average
                double sum = 0.0;
                for (int i = 0; i < count; i++)
                {
                    sum += samples[i];
                }
                return sum / (double)(count);
            }
        }
    }

GeneralRe: Implementing a moving average Pin
Ralf Meier18-Feb-18 9:32
mveRalf Meier18-Feb-18 9:32 
GeneralRe: Implementing a moving average Pin
auting8227-Feb-18 21:33
auting8227-Feb-18 21:33 
AnswerRe: Implementing a moving average Pin
Gerry Schmitz15-Feb-18 8:16
mveGerry Schmitz15-Feb-18 8:16 
Question.NET - choose correct service for conversion Pin
Bulgarin14-Feb-18 4:54
Bulgarin14-Feb-18 4:54 
AnswerRe: .NET - choose correct service for conversion Pin
Gerry Schmitz14-Feb-18 6:40
mveGerry Schmitz14-Feb-18 6:40 
Questioncreating trial version and expiry date issue Pin
Mou_kol14-Feb-18 0:30
Mou_kol14-Feb-18 0:30 
AnswerRe: creating trial version and expiry date issue Pin
Pete O'Hanlon14-Feb-18 0:38
mvePete O'Hanlon14-Feb-18 0:38 
GeneralRe: creating trial version and expiry date issue Pin
Mou_kol15-Feb-18 21:16
Mou_kol15-Feb-18 21:16 
AnswerRe: creating trial version and expiry date issue Pin
Eddy Vluggen14-Feb-18 3:22
professionalEddy Vluggen14-Feb-18 3:22 
AnswerRe: creating trial version and expiry date issue Pin
OriginalGriff14-Feb-18 4:30
mveOriginalGriff14-Feb-18 4:30 
AnswerRe: creating trial version and expiry date issue Pin
Gerry Schmitz14-Feb-18 6:32
mveGerry Schmitz14-Feb-18 6:32 
QuestionHow dotnet application run Pin
Mou_kol13-Feb-18 22:12
Mou_kol13-Feb-18 22:12 
AnswerRe: How dotnet application run Pin
phil.o13-Feb-18 23:00
professionalphil.o13-Feb-18 23:00 
GeneralRe: How dotnet application run Pin
Mou_kol14-Feb-18 0:09
Mou_kol14-Feb-18 0:09 
GeneralRe: How dotnet application run Pin
phil.o14-Feb-18 0:59
professionalphil.o14-Feb-18 0:59 
GeneralRe: How dotnet application run Pin
Mou_kol14-Feb-18 1:10
Mou_kol14-Feb-18 1:10 
GeneralRe: How dotnet application run Pin
Dave Kreskowiak14-Feb-18 2:27
mveDave Kreskowiak14-Feb-18 2:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.