Esempio n. 1
0
        public static void Main()
        {
            #region debug
            debugLed             = new OutputPort(device.DebugLed, false);
            debugBtn             = new InputPort(device.Socket6.Pin3, false, Port.ResistorMode.Disabled);
            ifDebug              = false;
            currentDebugBtnValue = false;
            oldDebugBtnValue     = false;
            #endregion

            // Initialisation des entrées
            capteurFrontal = new AnalogInput(device.Socket9.AnalogInput3);
            capteurGauche  = new AnalogInput(device.Socket9.AnalogInput4);
            capteurDroite  = new AnalogInput(device.Socket9.AnalogInput5);

            // Initialisation des sorties
            roueDroite = new PWM(device.Socket11.Pwm7, 2500, (int)VITESSE_MAX_D, PWM.ScaleFactor.Microseconds, false);
            roueGauche = new PWM(device.Socket11.Pwm8, 2500, (int)VITESSE_MAX_G, PWM.ScaleFactor.Microseconds, false);

            // Démarrage des roues
            roueGauche.Start();
            roueDroite.Start();

            while (true)
            {
                #region debug

                /*
                 * currentDebugBtnValue = debugBtn.Read();
                 * if (currentDebugBtnValue == false && oldDebugBtnValue == true)
                 * {
                 *  roueGauche.Duration++;
                 * }
                 *
                 * oldDebugBtnValue = currentDebugBtnValue;
                 */
                #endregion

                // Calcul de la vitesse en fonction des données des capteurs
                //double vitesseG = -((((capteurFrontal.Read() - 0.5) * 2.0) -0.5)- (capteurGauche.Read() - capteurDroite.Read())) / 2 * VMAX;
                //double vitesseD = ((((capteurFrontal.Read() - 0.5) * 2.0) -0.5)+ (capteurGauche.Read() - capteurDroite.Read())) / 2 * VMAX;


                double vitesseG = -(((capteurFrontal.Read() - 0.5) * 2.0) - 0.5) * VMAX;
                double vitesseD = (((capteurFrontal.Read() - 0.5) * 2.0) - 0.5) * VMAX;


                // Régulation des vitesses des roues
                roueGauche.Duration = (uint)(VITESSE_MAX_G + vitesseG);
                roueDroite.Duration = (uint)(VITESSE_MAX_D + vitesseD);

                #region debug (affichage des données)
                //Debug.Print("Capteurs : " + capteurDroite.Read() + " || " + capteurFrontal.Read() + " || " + capteurGauche.Read());
                Debug.Print("Moteurs : " + roueDroite.Duration.ToString() + " || " + roueGauche.Duration.ToString());
                #endregion
            }
        }
Esempio n. 2
0
        private static void ReadPhotoCell()
        {
            WriteLog(INFO, "Reading photocell");

            //2014-09-24 loop testing showed max of 1 in full light, min of 0.09 with lights out
            //2014-10-19 loop testing with soldered board and 3.3v showing light condition as lower value, dark condition approaching 1

            photocellReading = photoCellPin.Read();

            WriteLog(INFO, "Photocell raw value: " + photocellReading.ToString());

            //may need to convert value here

            //boundaries: 1 to 0.75
            if (photocellReading >= 0.75 && photocellReading < 1)
            {
                photocellReadingLevel = 1; //dark
            }
            else if (photocellReading >= 0.5 && photocellReading <= 0.74)
            {
                photocellReadingLevel = 2; //twilight
            }
            else if (photocellReading <= 0.49)
            {
                photocellReadingLevel = 3; //light
            }
        }
Esempio n. 3
0
        static void SendFridgeReport()
        {
            // Generate egg positions
            string eggPositions = ((eggReader0.Read() == true) ? "1" : "0") + ","
                                  + ((eggReader1.Read() == true) ? "1" : "0") + ","
                                  + ((eggReader2.Read() == true) ? "1" : "0") + ","
                                  + ((eggReader3.Read() == true) ? "1" : "0") + ","
                                  + ((eggReader4.Read() == true) ? "1" : "0") + ","
                                  + ((eggReader5.Read() == true) ? "1" : "0");

            // Read weights
            //double weightReader0 = 0.745;
            //double weightReader1 = 0.00000;

            weights[0] = CalculateWeight(weightReader0.Read());
            weights[1] = CalculateWeight(weightReader1.Read());


#if CreatingJson
            JsonObject jo = new JsonObject();

            jo.Add("eggs", eggPositions);
            jo.Add("fridgeid", fridgeId.ToString());
            jo.Add("slot1weight", weights[0].ToString());
            jo.Add("slot2weight", weights[1].ToString());

            Debug.Print(jo.ToString());
#endif

#if SendingToSparkfun
            // https://data.sparkfun.com/input/*********
            try
            {
                byte[] postData = Encoding.UTF8.GetBytes(jo.ToString());

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://data.sparkfun.com/input/********");
                request.Method = "POST";
                request.Headers.Add("Phant-Private-Key", "xxxxxxxxxxxxxx");
                request.ContentType   = "application/json";
                request.ContentLength = postData.Length;
                request.KeepAlive     = false;

                Debug.Print("request set");

                Stream postDataStream = request.GetRequestStream();
                postDataStream.Write(postData, 0, postData.Length);
                postDataStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                request.Dispose();
                Debug.Print(response.StatusCode.ToString());

                Debug.Print("response done");
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message.ToString());
            }
#endif
        }
Esempio n. 4
0
        /// <summary>
        /// Sensor Tests for Relay Control
        /// </summary>
        /// <param name="WaterLevel">Water Level Sensor</param>
        /// <param name="LDR">LDR Sensor</param>
        /// <param name="MotionDetection"> Motion Detection Sensor</param>
        static void sensorTest(AnalogInput WaterLevel, AnalogInput LDR, AnalogInput MotionDetection)
        {
            if (!sensorAction((WaterLevel.Read() * 100), waterLimit))
            {                                              //Stop the pumping water relay
                RelayController(RelaySelection(1), false); //In this case, 1st Relay will be closed
                timeMode = false;
            }
            else
            {
                RelayController(RelaySelection(1), true);
                timeMode = true;
            }

            if (sensorAction((LDR.Read() * 100), ldrLimit))
            {                                             //If LDR shows value that is under 20, then close chicken's door
                RelayController(RelaySelection(4), true); //In this case, 4th Relay will be opened
                timeMode = false;
            }
            else
            {
                RelayController(RelaySelection(4), false);
                timeMode = true;
            }

            if (sensorAction((MotionDetection.Read() * 100), motionLimit))
            {                                             //If motion is understood, then open the light
                RelayController(RelaySelection(6), true); //In this case, 6nd Relay will be opened
                timeMode = false;
            }
            else
            {
                RelayController(RelaySelection(6), false);
                timeMode = true;
            }
        }
Esempio n. 5
0
        public static void Main()
        {
            AnalogInput capt        = new AnalogInput((Cpu.AnalogChannel)Cpu.AnalogChannel.ANALOG_0);
            OutputPort  dir         = new OutputPort(FEZSpider.Socket8.Pin9, true);
            InputPort   microswitch = new InputPort(FEZSpider.Socket4.Pin3, false, Port.ResistorMode.PullDown);

            double frequence       = 38000; // Période en microseconde
            double rapportCyclique = 0.5;   // Période en microseconde

            PWM motorDriver = new PWM(FEZSpider.Socket8.Pwm7, frequence, rapportCyclique, false);

            motorDriver.Stop();


            while (true)
            {
                if (microswitch.Read())
                {
                    motorDriver.Stop();
                }

                Debug.Print("Distance : " + capt.Read().ToString());

                Debug.Print(microswitch.Read().ToString());
                Thread.Sleep(50);
            }
        }
Esempio n. 6
0
        public static void Main()
        {
            var currentState = GetCurrentState();

            Debug.Print(currentState);

            AnalogInput analogInput = new AnalogInput(AnalogChannels.ANALOG_PIN_A0);
            var         data        = analogInput.Read() * 10D;

            try
            {
                var setStateResult = SetCurrentState((int)data);
                Debug.Print(setStateResult);
            }
            catch (WebException wex)
            {
                //I expect this to time out - the gateway blocks the call and my netduino is going to
                //give up before completing.
                Debug.Print("Call did not return, check state manually");
            }

            while (true)
            {
                currentState = GetCurrentState();
                Debug.Print(currentState);

                Thread.Sleep(5000);
            }
        }
Esempio n. 7
0
        public static void MeasureBattery()
        {
            const double AVG = 4.0;
            double       ad5, ad6, mVr;
            int          mV5, mV6;


            // param read
            ad5 = 0;
            ad6 = 0;
            for (int i = 0; i < 4; i++)
            {
                ad5 += Ain5.Read();
                ad6 += Ain6.Read();
            }

            ad5 /= AVG;
            ad6 /= AVG;

            mV6            = (int)(3300.0 * ad6 + 0.5);
            iBatt[battIdx] = mV6 / RCURR;

            mV5            = (int)(3300.0 * ad5 + 0.5);
            mVr            = (3300.0 * ad5 * (10.0 + 15.0)) / 15.0 + 0.5;
            vBatt[battIdx] = (int)mVr - mV6;
        }
        public static void Main()
        {
            AnalogInput analogSensor1 = new AnalogInput
                                        (
                Pins.Analog.Socket1Pin1
                //Pins.Analog.Socket2Pin1
                //Pins.Analog.Socket3Pin1
                //Pins.Analog.Socket4Pin1
                                        );
            AnalogInput analogSensor2 = new AnalogInput
                                        (
                Pins.Analog.Socket1Pin2
                //Pins.Analog.Socket2Pin2
                //Pins.Analog.Socket3Pin2
                //Pins.Analog.Socket4Pin2
                                        );

            Debug.Print("Program running");

            while (true)
            {
                double sensorValue1 = analogSensor1.Read();
                double sensorValue2 = analogSensor2.Read();

                Debug.Print("Value 1:" + sensorValue1.ToString("F2") + " Value 2:" + sensorValue2.ToString("F2"));

                Thread.Sleep(500);
            }
        }
Esempio n. 9
0
            public double Read()
            {
                var analogValue = _analogInput.Read();

                // now, if we want, we can calculate the number of volts by multiplying
                // the converted value by 3.3
                var voltageValue = analogValue * 3.3;//convert analog_x-->voltage value(v)

                var rangeValue = voltageValue - _voltage;

                var gramValue = rangeValue / 0.8;//calculate the gram value

                if (gramValue > 1)
                {
                    return(90);
                }
                if (gramValue < -1)
                {
                    return(-90);
                }

                var degrees = System.Math.Asin(gramValue) * 180.0 / System.Math.PI;

                var multiplier = System.Math.Pow(10, Precision);

                return(System.Math.Round(degrees * multiplier) / multiplier);
            }
Esempio n. 10
0
        private static void ReadPhotoCell()
        {
            WriteLog(INFO, "Reading photocell");

            //2014-09-24 loop testing showed max of 1 in full light, min of 0.09 with lights out

            photocellReading = photoCellPin.Read();

            WriteLog(INFO, "Photocell raw value: " + photocellReading.ToString());

            //may need to convert value here

            //boundaries: 1 to 0.75
            if (photocellReading >= 0.75 && photocellReading < 1)
            {
                photocellReadingLevel = 1; //dark
            }
            else if (photocellReading >= 0.5 && photocellReading <= 0.74)
            {
                photocellReadingLevel = 2; //twilight
            }
            else if (photocellReading <= 0.49)
            {
                photocellReadingLevel = 3; //light
            }
        }
Esempio n. 11
0
        public static void Main()
        {
            strip     = new NeoPixelStrip(50, "LaughOMeter");
            analogPin = new AnalogInput(Cpu.AnalogChannel.ANALOG_3);

            while (true)
            {
                try
                {
                    Debug.Print(analogPin.Read().ToString());
                    strip.SetLevel(((ushort)(analogPin.Read() * 100 / maxVal)), palette);
                }
                catch { }
                Thread.Sleep(500);
            }
        }
Esempio n. 12
0
        //This loop polls the aio value set by the trimpot to determine the duty cycle which
        // determines the amplitude on the sin curve of a given itteration.
        private void SinLEDLoop(AnalogInput pot, PWM led, OutputPort relay, LCD_Display display)
        {
            double startValue = 0;
            bool   laststate  = false;
            double potValue   = 0.0;

            TimeSpan lastPeak = Utility.GetMachineTime();

            while (true)
            {
                potValue = pot.Read();

                startValue += .5 * potValue;

                if (startValue > 2 * System.Math.PI)
                {
                    startValue = 0;
                    laststate  = !laststate;
                    //relay.Write(laststate);

                    if (display != null)
                    {
                        display.writeValue("Frequency: " + getFreq(lastPeak) + " Hz");
                    }
                    lastPeak = Utility.GetMachineTime();
                }
                Thread.Sleep(5);


                led.DutyCycle = System.Math.Max(0, System.Math.Sin(startValue));
            }
        }
Esempio n. 13
0
        public static void Main()
        {
            // AnalogInput przetwarza różnicę poziomów pomiędzy 0 a 3,3V na 1024 poziomy odczytu, lub liczbę niecałkowitą z zakresu 0;1
            AnalogInput lux = new AnalogInput(AnalogChannels.ANALOG_PIN_A0);

            // SerialPort połączony jest na COM2 (piny 2 i 3) do modułu Bluetooth na parametrach 38400, 8, N, 1
            SerialPort sp = new SerialPort(SerialPorts.COM2, 38400, Parity.None, 8, StopBits.One);

            sp.Open();

            // na wieczność
            while (true)
            {
                // wykonaj odczyt, przetwórz na string, dodaj znak końca linii
                var data = lux.Read().ToString() + "\r\n";
                Debug.Print(data);

                // wyślij przez Bluetooth
                var buf = Encoding.UTF8.GetBytes(data);
                sp.Write(buf, 0, buf.Length);

                // czekaj 200 milisekund do następnego pomiaru
                Thread.Sleep(200);
            }

            sp.Close();
        }
Esempio n. 14
0
        /// <summary>
        /// Calculate Temperature value
        /// </summary>
        /// <returns>Float value of current Temperature reading</returns>
        /// <remarks>Assuming AREF of 3.3v, the default for Rev. B Netduino Plus boards.
        /// It's an internal value, no feed to AREF required.
        /// Using code tutorial from adafruit http://www.ladyada.net/learn/sensors/thermistor.html </remarks>
        private float CalculateTemperature()
        {
            AnalogInput ain = new AnalogInput(AnalogChannels.ANALOG_PIN_A0);

            // take 10 readings to even out the noise
            float average = 0.0F;

            for (int i = 0; i < 10; i++)
            {
                average += (int)ain.Read();
            }
            average /= 10;

            if (average == 0)
            {
                return(10.0F);
            }

            // convert to a resistance
            average = 1023 / average - 1;
            average = SeriesResistor / average;

            // apply steinhart
            float tempValue = average / ThermistorNominal;

            tempValue  = Extensions.Math.Log(tempValue);
            tempValue /= BetaCoefficient;
            tempValue += 1.0F / (TemperatureNominal + 273.15F);
            tempValue  = 1.0F / tempValue;
            tempValue -= 273.15F;

            ain.Dispose();
            return(tempValue);
        }
Esempio n. 15
0
        private double get_voltage(AnalogInput input)
        {
            // read a digital value from the ADC
            double digitalValue = input.Read();

            // convert digital value to analog voltage value
            return(digitalValue * AnalogReference);
        }
Esempio n. 16
0
        public static void Main()
        {
            var axisX         = new AnalogInput(Pins.GPIO_PIN_A0);
            var axisY         = new AnalogInput(Pins.GPIO_PIN_A1);
            var axisZ         = new AnalogInput(Pins.GPIO_PIN_A2);
            var IrFloorSensor = new AnalogInput(Pins.GPIO_PIN_A3);


            var out1 = new OutputPort(Pins.GPIO_PIN_D1, false);
            var out2 = new OutputPort(Pins.GPIO_PIN_D12, false);


            var in1 = new InputPort(Pins.GPIO_PIN_D2, false, Port.ResistorMode.Disabled);
            var in2 = new InputPort(Pins.GPIO_PIN_D4, false, Port.ResistorMode.PullUp);


            var servo1 = new PWM(Pins.GPIO_PIN_D9);

            servo1.SetDutyCycle(0);
            var servo2 = new PWM(Pins.GPIO_PIN_D10);

            servo2.SetDutyCycle(0);


            var stopWatch = Stopwatch.StartNew();

            stopWatch.Start();
            int  i        = 0;
            bool digState = false;


            while (i < 5000)
            {
                axisX.Read();
                axisY.Read();
                axisZ.Read();
                IrFloorSensor.Read();


                in1.Read();
                in2.Read();


                digState = !digState;
                out1.Write(digState);
                out2.Write(digState);


                servo1.SetPulse(20000, 1500);
                servo2.SetPulse(20000, 1500);


                i++;
            }
            stopWatch.Stop();
            Debug.Print("Elapsed: " + stopWatch.ElapsedMilliseconds.ToString());
        }
Esempio n. 17
0
        public AnalogInputPin(Cpu.AnalogChannel pin, double updateFrequency = DefaultUpdateFrequency)
            : base(updateFrequency)
        {
            input = new AnalogInput(pin, -1);

            var initialValue = input.Read();

            Analog = AddPort("Analog", Units.Ratio, initialValue);
        }
Esempio n. 18
0
        public static void Main()
        {
            OutputPort  led = new OutputPort(Pins.ONBOARD_LED, false);
            AnalogInput an0 = new AnalogInput(AnalogChannels.ANALOG_PIN_A0);

            //an0. SetRange(0, 100);
            trimpot = an0.Read().ToString();

            Listener webServer = new Listener(RequestReceived);

            while (true)
            {
                // Blink LED to show we're still responsive
                led.Write(!led.Read());
                trimpot = an0.Read().ToString();
                Thread.Sleep(500);
            }
        }
Esempio n. 19
0
 /// <summary>
 ///     Read the sensor output and convert the sensor readings into acceleration values.
 /// </summary>
 public void Update()
 {
     X = ((_x.Read() * SupplyVoltage) - _zeroGVoltage) / XVoltsPerG;
     Y = ((_y.Read() * SupplyVoltage) - _zeroGVoltage) / YVoltsPerG;
     Z = ((_z.Read() * SupplyVoltage) - _zeroGVoltage) / ZVoltsPerG;
     if ((_updateInterval != 0) &&
         ((Math.Abs(X - _lastX) > AccelerationChangeNotificationThreshold) ||
          (Math.Abs(Y - _lastY) > AccelerationChangeNotificationThreshold) ||
          (Math.Abs(Z - _lastZ) > AccelerationChangeNotificationThreshold)))
     {
         Vector lastNotifiedReading = new Vector(_lastX, _lastY, _lastZ);
         Vector currentReading      = new Vector(X, Y, Z);
         _lastX = X;
         _lastY = Y;
         _lastZ = Z;
         AccelerationChanged(this, new SensorVectorEventArgs(lastNotifiedReading, currentReading));
     }
 }
Esempio n. 20
0
        public static void Main()
        {
            //tidy up
            File.Delete("\\SD\\Data.csv");

            try
            {
                //retrive and set device time via NTP
                var networkTime = NtpClient.GetNetworkTime();
                Utility.SetLocalTime(networkTime);

                _macAddress  = GetMAC();
                _blobClient  = new BlobClient(AccountName, AccountKey);
                _tableClient = new TableClient(AccountName, AccountKey);
                _tableClient.CreateTable("netmfdata");

                _onBoardButton = new InterruptPort(Pins.ONBOARD_SW1, true,
                                                   Port.ResistorMode.Disabled,
                                                   Port.InterruptMode.InterruptEdgeHigh);
                _onBoardButton.OnInterrupt += onBoardButton_OnInterrupt;

                _analogInput = new AnalogInput(AnalogChannels.ANALOG_PIN_A0);
            }
            catch (Exception ex)
            {
                Debug.Print("Error setting up Device: " + ex.ToString());
            }

            int counter = 0;

            while (true)
            {
                counter++;
                var data = _analogInput.Read() * 40D;
                _tableClient.AddTableEntityForTemperature("netmfdata", _macAddress, counter.ToString(), DateTime.Now, data, "UK");

                lock (Padlock)
                {
                    using (FileStream fs = File.Open("\\SD\\Data.csv", FileMode.Append, FileAccess.Write))
                    {
                        Debug.Print(data.ToString());
                        var dataBytes = Encoding.UTF8.GetBytes(
                            StringUtility.Format("{0}, {1}, {2}\r\n",
                                                 _macAddress, DateTime.Now.ToString(),
                                                 data)
                            );

                        fs.Write(dataBytes, 0, dataBytes.Length);
                        fs.Flush();
                    }
                }

                Thread.Sleep(1000);
                Debug.Print("Working");
            }
        }
Esempio n. 21
0
        public static void Main()
        {
            AnalogInput capt = new AnalogInput((Cpu.AnalogChannel)Cpu.AnalogChannel.ANALOG_0);

            while (true)
            {
                Debug.Print("Distance : " + capt.Read().ToString());
                Thread.Sleep(250);
            }
        }
Esempio n. 22
0
        public static bool CheckReady()
        {
            bool state = false;

            if (activePin.Read() >= 0.9)
            {
                state = true;
            }
            return(state);
        }
Esempio n. 23
0
        public static void Main()
        {
            DeviceAssist.SetupDefault();

            try
            {
                if (File.Exists("\\SD\\Data.csv"))
                {
                    File.Delete("\\SD\\Data.csv");
                }

                _onBoardButton = new InterruptPort(Pins.ONBOARD_SW1, true,
                                                   Port.ResistorMode.Disabled,
                                                   Port.InterruptMode.InterruptEdgeHigh);
                _onBoardButton.OnInterrupt += onBoardButton_OnInterrupt;

                _macAddress = "holding";

                _blobClient = new BlobClient(new netmfazurestorage.Account.CloudStorageAccount(AccountName, AccountKey));
            }
            catch (Exception ex)
            {
                //there was an error setting up the device
                throw;
            }

            _analogInput = new AnalogInput(AnalogChannels.ANALOG_PIN_A0);

            int counter = 0;

            while (true)
            {
                counter++;
                var data = _analogInput.Read() * 40D;

                lock (Padlock)
                {
                    using (FileStream fs = File.Open("\\SD\\Data.csv", FileMode.Append, FileAccess.Write))
                    {
                        Debug.Print(data.ToString());
                        var dataBytes = Encoding.UTF8.GetBytes(
                            StringUtility.Format("{0}, {1}, {2}\r\n",
                                                 _macAddress, DateTime.Now.ToString(),
                                                 data)
                            );

                        fs.Write(dataBytes, 0, dataBytes.Length);
                        fs.Flush();
                    }
                }

                System.Threading.Thread.Sleep(1000);
                Debug.Print("Working");
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Returns a new sample.
        /// If the sensor is not open, Open is called first.
        /// Postconditions
        ///     Result is double
        ///     (Result greaterOrEqual MinValue) && (Result lessOrEqual MaxValue)
        /// </summary>
        public object HandleGet()
        {
            if (port == null)
            {
                Open();
            }
            double value = port.Read();

            // NETMF has already done the scaling
            return(value);
        }
Esempio n. 25
0
        protected int ReadAverageDistance(AnalogInput analogInput)
        {
            var count = AverageMeasurementCount;
            var total = 0;

            while (--count >= 0)
            {
                total += analogInput.Read();
            }
            return(total / AverageMeasurementCount);
        }
Esempio n. 26
0
        public static void Main()
        {
            AnalogInput dial = new AnalogInput(Cpu.AnalogChannel.ANALOG_0);

            while (true)
            {
                Thread.Sleep(100);
                Debug.Print(dial.Read().ToString());
            }
            ;
        }
        private void UpdateSensors()
        {
            _left  = photoCellL.Read();
            _right = photoCellR.Read();
            //_bottomLeft = photoCellBL.Read();
            //_bottomRight = photoCellBR.Read();

            Debug.Print("TL: " + _left);
            Debug.Print("TR: " + _right);
            //Debug.Print("BL: " + _bottomLeft);
            //Debug.Print("TR: " + _bottomRight);
        }
Esempio n. 28
0
        public double ReadDistance()
        {
            var total = 0d;
            var min   = double.MaxValue;
            var max   = double.MinValue;
            var count = _data.Length;

            for (int i = 0; i < count; i++)
            {
                var raw = _input.Read();
                _data[i] = raw;
                total   += raw;

                if (raw < min)
                {
                    min = raw;
                }
                if (raw > max)
                {
                    max = raw;
                }
            }

            var average = total / count;
            var stDev   = StandardDeviation(_data, average);

            if (stDev > 0.01)
            {
                var position = 0;
                min = average - stDev;
                max = average + stDev;


                for (int i = 0; i < count; i++)
                {
                    var data = _data[i];
                    if (data > min && data < max)
                    {
                        _data[position++] = data;
                    }
                }
                average = Average(_data, position);
            }
            var volts = average * 3.3;

            return(8.30330497051182 * Math.Pow(volts, 6d)
                   - 89.8292932369688 * Math.Pow(volts, 5d)
                   + 391.808954977875 * Math.Pow(volts, 4d)
                   - 885.170571942885 * Math.Pow(volts, 3d)
                   + 1106.23720332132 * Math.Pow(volts, 2d)
                   - 753.770168858126 * volts
                   + 250.173288592975);
        }
Esempio n. 29
0
        //This is the method that gets run by the threadpool persistently... notice its name is
        //listed above as a parameter...
        private void DumpAccelData()
        {
            //keeps track of the current index in the packet... notice how it increments
            //    as we continue adding data to it...
            var currentDataIndex = MetaDataCount;

            //get our stopwatch's elapsed ms, stick it in our packet
            var time = BitConverter.GetBytes(Clock.Instance.ElapsedMilliseconds);

            _dataArray[currentDataIndex++] = time[0];
            _dataArray[currentDataIndex++] = time[1];
            _dataArray[currentDataIndex++] = time[2];

            //anything beyond simply filling RAM with data is S-L-O-W on the .NetMF due to the
            // overhead associated with it.
            //
            //The switch statement decides whether we're on x, y, or z... our first index is
            //0, and 0 % 3 is 0, so it makes sense to store x here...
            //       1 % 3 is 1, so it makes sense to store y here... and so on.
            for (var i = 0; i < _dataCount / 2; i++)
            {
                short raw = 0;
                switch (i % 3)
                {
                case 0:
                    raw = (short)(XPin.Read() * 1000);
                    break;

                case 1:
                    raw = (short)(YPin.Read() * 1000);
                    break;

                case 2:
                    raw = (short)(ZPin.Read() * 1000);
                    break;
                }
                var msb = (byte)((raw >> 8) & 0xFF);
                var lsb = (byte)(raw & 0xff);

                _dataArray[currentDataIndex++] = msb;
                _dataArray[currentDataIndex++] = lsb;
            }

            time = BitConverter.GetBytes(Clock.Instance.ElapsedMilliseconds);

            //last 8 bytes store end time stamp
            _dataArray[currentDataIndex++] = time[0];
            _dataArray[currentDataIndex++] = time[1];
            _dataArray[currentDataIndex]   = time[2];

            //pass this off to the packet so it gets recorded to the sd card.
            Array.Copy(_dataArray, _workItem.PacketData, _dataArray.Length);
        }
Esempio n. 30
0
        public static void Main()
        {
            var   photoresistor       = new AnalogInput(Pins.GPIO_PIN_A3);
            int   ambientLight        = 0;
            int   averageAmbientLight = 0;
            float sensorVoltage       = 0;

            float lightThresholdVoltage = 0.85f;
            float darkThresholdVoltage  = 2.1f;

            // setup an array to hold our samples
            int numberOfSamplesToAverage = 3;

            int[] previousSamples = new int[numberOfSamplesToAverage];
            for (int i = 0; i < numberOfSamplesToAverage; i++)
            {
                previousSamples[i] = 0;
            }

            while (true)
            {
                // read the analog input
                ambientLight = photoresistor.Read();

                // average (oversample) the last two readings
                averageAmbientLight = AverageAndStore(ref previousSamples, ambientLight);

                // convert the digital value back to voltage
                // sensorVoltage = AnalogValueToVoltage(ambientLight);
                sensorVoltage = AnalogValueToVoltage(averageAmbientLight);

                // output
                Debug.Print("Light Level = Raw: " + ambientLight.ToString() +
                            ", Average: " + averageAmbientLight.ToString() +
                            ", Voltage: " + AnalogValueToVoltage(averageAmbientLight).ToString());

                if (sensorVoltage < lightThresholdVoltage)
                {
                    Debug.Print("Very bright.");
                }
                else if (sensorVoltage > darkThresholdVoltage)
                {
                    Debug.Print("Dark.");
                }
                else
                {
                    Debug.Print("Moderately Bright.");
                }

                // wait 1/4 second
                Thread.Sleep(250);
            }
        }
        /// <summary>
        /// Calculate Temperature value
        /// </summary>
        /// <returns>Float value of current Temperature reading</returns>
        /// <remarks>Assuming AREF of 3.3v, the default for Rev. B Netduino Plus boards.
        /// It's an internal value, no feed to AREF required.
        /// Using code tutorial from adafruit http://www.ladyada.net/learn/sensors/thermistor.html </remarks>
        private float CalculateTemperature()
        {
            AnalogInput ain = new AnalogInput(Pins.GPIO_PIN_A0);

            // take 10 readings to even out the noise
            float average = 0.0F;
            for (int i = 0; i < 10; i++) { average += ain.Read(); }
            average /= 10;

            // convert to a resistance
            average = 1023 / average - 1;
            average = SeriesResistor / average;

            // apply steinhart
            float tempValue = average / ThermistorNominal;
            tempValue = Controller.Math.Log(tempValue);
            tempValue /= BetaCoefficient;
            tempValue += 1.0F / (TemperatureNominal + 273.15F);
            tempValue = 1.0F / tempValue;
            tempValue -= 273.15F;

            ain.Dispose();
            return tempValue;
        }