예제 #1
0
        public static void Main()
        {
            int DacValue1 = 10;
            int DacValue2 = 10;

            Debug.Print(Resources.GetString(Resources.StringResources.String1));

            // ADC
            AnalogInput ADC0 = new AnalogInput(ADC.PA1);
            AnalogInput ADC1 = new AnalogInput(ADC.PA2);
            AnalogInput ADC2 = new AnalogInput(ADC.PA3);
            AnalogInput ADC3 = new AnalogInput(ADC.PB0); // PB0 = PA0 ???

            //DAC
            AnalogOutput DAC0 = new AnalogOutput(Cpu.AnalogOutputChannel.ANALOG_OUTPUT_0);
            AnalogOutput DAC1 = new AnalogOutput(Cpu.AnalogOutputChannel.ANALOG_OUTPUT_1);

            DAC0.Scale = 1;
            DAC0.Write(0.8);

            DAC1.Scale = 1;
            DAC1.Write(0.1);

            /* Initialize LEDs */
            LED.LEDInit();
            LED.GreenLedToggle();
            while (true)
            {
                /* Display the ADC converted value */
                //int AdcValue = (ADC0.ReadRaw() * 1);
                //string str = AdcValue.ToString();
                Debug.Print("ADC0 (pin " + ADC0.Pin + ") = " + (ADC0.ReadRaw()));
                Debug.Print("ADC1 (pin " + ADC1.Pin + ") = " + (ADC1.ReadRaw()));
                Debug.Print("ADC2 (pin " + ADC2.Pin + ") = " + (ADC2.ReadRaw()));
                Debug.Print("ADC3 (pin " + ADC3.Pin + ") = " + (ADC3.ReadRaw()));

                Debug.Print("\r\n--------------------------------\r\n");

                /* Wait for 1s */
                Thread.Sleep(250);

                /* Toggle Green LED */
                LED.GreenLedToggle();
                LED.RedLedToggle();

                DacValue1 += 100;
                if (DacValue1 > 4000)
                {
                    DacValue1 = 0;
                }
                DAC0.WriteRaw(DacValue1);

                DacValue2 += 100;
                if (DacValue2 > 4000)
                {
                    DacValue2 = 0;
                }
                DAC1.WriteRaw(DacValue2);
            }
        }
예제 #2
0
        }     // end method

        /// <summary>
        /// Returns the current Celsius temp reading for the given temp Sensor
        /// </summary>
        /// <param name="inputPort"> Temp Sensor analogPort</param>
        /// <returns></returns>
        private static double GetTempC(int inputPort)
        {
            var tempC = 0.00;

            switch (inputPort)
            {
            case 0:
                var reading0 = (int)aPort0.ReadRaw();
                // convert reading to temp value
                double voltage0 = (reading0 * 3.3) / 1024;
                tempC = (voltage0 - 0.5) * 100;
                break;

            case 1:
                var reading1 = (int)aPort1.ReadRaw();
                // convert reading to temp value
                double voltage1 = (reading1 * 3.3) / 1024;
                tempC = (voltage1 - 0.5) * 100;
                break;


            case 2:
                var reading2 = (int)aPort2.ReadRaw();
                // convert reading to temp value
                double voltage2 = (reading2 * 3.3) / 1024;
                tempC = (voltage2 - 0.5) * 100;
                break;

            default:
                break;
            }

            return(tempC);
        }
예제 #3
0
        /// <summary>
        /// Create speed cmd for land rover vehicle.
        /// </summary>
        /// <returns></returns>
        static public byte triggerSpeedCmd()
        {
            byte speedCmd = 0;

            //on land rover  0 to 134 is reverse, 135 = stop, 136 to 255 is forward.
            //about 139 is start of forward on truck

            speedCmd = (byte)convertLinearScale(speedTriggerAnalog.ReadRaw(), speedTriggerMin, speedTriggerMax, 0, 255);

            if ((speedCmd > speedTriggerNullMin) && (speedCmd < speedTriggerNullMax))
            {
                speedCmd = 135;                                                                       //deadband around neutral
            }
            else if (speedCmd >= speedTriggerNullMax)
            {
                speedCmd = (byte)convertLinearScale(speedCmd, speedTriggerNullMax, 255, 136, speedTriggerMaxOutput);
            }
            else
            {
                speedCmd = (byte)convertLinearScale(speedCmd, 0, speedTriggerNullMin, 0, 134);
            }

            return(speedCmd);
            //Debug.Print("Motor Speed: " + speed.ToString());
        }
예제 #4
0
 static void collectData()
 {
     for (int i = 0; i < nSamples; i++)
     {
         reading[i]  = (ushort)accRead.ReadRaw();
         readTime[i] = (ushort)(Utility.GetMachineTime().Ticks / ticksPerMicroSecond);
     }
 }
예제 #5
0
        public double TakeMeasurement()
        {
            var raw = aiThermistor.ReadRaw();

            double tk  = 273f;
            double t25 = tk + 25f;
            double r25 = 10000f;
            double t   = 1 / (System.Math.Log(VR1 * raw / (4096 - raw) / r25) / Bc + 1 / t25) - tk;

            return(t);
        }
예제 #6
0
        public static void Main()
        {
            // write your code here
            flex.Start();
            serial.DataReceived += serial_DataReceived;
            serial.Open();
            while (true)
            {
                Thread.Sleep(100);
                int acc = accRead.ReadRaw();
                Debug.Print(acc.ToString());
            }
            //while (true)
            //{
            //    int a = accRead.ReadRaw();
            //    Debug.Print(a.ToString());
            //}

//            Thread.Sleep(Timeout.Infinite);
        }
예제 #7
0
        private void ReadTemp()
        {
            var totalAdc    = 0;
            var sampleCount = 100;

            for (int i = 0; i < sampleCount; i++)
            {
                var adc = _input.ReadRaw();
                Debug.Print("Probe Read:" + adc.ToString());
                if (adc == 0 || adc >= 4095)
                {
                    addAdcValue(0);
                    return;
                }
                totalAdc += adc;
            }
            //totalAdc = totalAdc >> 2;
            addAdcValue(totalAdc / sampleCount);
            _lastTempRead = DateTime.Now.Ticks;
        }
예제 #8
0
        static void TestADC()
        {
            var adc1 = new AnalogInput(Cpu.AnalogChannel.ANALOG_0);
            var adc3 = new AnalogInput(Cpu.AnalogChannel.ANALOG_3);

            while (true)
            {
                Print("ADC: " + adc3.ReadRaw() + "  " + adc1.ReadRaw());

                Thread.Sleep(1000);
            }
        }
예제 #9
0
        private static int GetRandomNumber()
        {
            var R0 = new AnalogInput(AnalogChannels.ANALOG_PIN_A0);
            var R1 = new AnalogInput(AnalogChannels.ANALOG_PIN_A1);
            var R2 = new AnalogInput(AnalogChannels.ANALOG_PIN_A2);
            var R3 = new AnalogInput(AnalogChannels.ANALOG_PIN_A3);
            var R4 = new AnalogInput(AnalogChannels.ANALOG_PIN_A4);

            int num = (int)((R0.ReadRaw() + 1) * (R1.ReadRaw() + 1) * (R2.ReadRaw() + 1) * (R3.ReadRaw() + 1) * (R4.ReadRaw() + 1));

            num = num & (0xFFFF);
            return(num);
        }
예제 #10
0
        //  Calcul de la hauteur de l'ascenseur
        static int calculeHauteur()
        {
            int moyenne = 0;

            for (int i = 0; i < 100; i++)
            {
                moyenne += captBas.ReadRaw();
            }

            moyenne /= 100;

            return(moyenne);
        }
예제 #11
0
        /// <summary>
        /// Returns a new sample.
        /// If the sensor is not open, Open is called first.
        /// Postconditions
        ///     (Result == null) || (Result is int) || (Result is double)
        /// </summary>
        public object HandleGet()
        {
            if (port == null)
            {
                Open();
            }
            double value = port.Read();

            Debug.Print("raw ain value: " + port.ReadRaw());


            //Debug.Print("get (already scaled and offset) value " + value);
            return(value);
        }
예제 #12
0
        public static void Main()
        {
            //create analog input
            AnalogInput MQ3sensor = new AnalogInput(AnalogChannels.ANALOG_PIN_A0);

            //first run we need to calibrate sensors zeropoint in cleanair
            bool   calibrating = true;
            double zeroPoint   = 0;

            while (true)
            {
                // read the analog input
                int analogInputValue = MQ3sensor.ReadRaw();

                // output
                if (calibrating || analogInputValue < zeroPoint)
                {
                    //calibrate when inputvalue<last calculated zeroPoint or when just started app.
                    int analogValue = 0;
                    for (int calibrateCounter = 0; calibrateCounter < 10; calibrateCounter++)
                    {
                        analogValue += MQ3sensor.ReadRaw();
                        Debug.Print("Calibrating...Raw input:" + analogInputValue);
                        Thread.Sleep(50);
                    }
                    zeroPoint   = analogValue / 10;
                    calibrating = false;
                }
                else
                {
                    Debug.Print("Alcohollevel: " + ugl(analogInputValue, calibrating, zeroPoint) + " µg/L" +
                                ", Raw input: " + analogInputValue.ToString());
                }
                // wait 1/4 second
                Thread.Sleep(250);
            }
        }
예제 #13
0
        /// <summary>
        /// Drive rover.
        /// </summary>
        static void RoverJoystickControlTimer_Tick(object temp)
        {
            switch (DRIVE_MODE_ROVER)
            {
            case DRIVE_MODE.MANUAL:

                //get check box accessories
                //Array.Copy(byteToHex(getChkBoxAccessories()), 0, ps2Data, 4, 2);
                Array.Copy(byteToHex((byte)(convertLinearScale(steeringWheelAnalog.ReadRaw(), steeringWheelMin, steeringWheelMax, 0, 255))), 0, manualCmdOutput, 5, 2);
                Array.Copy(byteToHex(triggerSpeedCmd()), 0, manualCmdOutput, 8, 2);

                //get checksum
                Array.Copy(byteToHex(getChecksum(Encoding.UTF8.GetBytes(new string(manualCmdOutput)))), 0, manualCmdOutput, 14, 2);
                lairdComPort.Write(Encoding.UTF8.GetBytes(new string(manualCmdOutput)), 0, manualCmdOutput.Length);
                //Debug.Print(new string(manualCmdOutput));

                break;

            case DRIVE_MODE.AUTO:

                //Array.Copy(byteToHex((byte)DRIVE_MODE_ROVER), 0, autoCmdOutput, 5, 2);

                //get checksum
                Array.Copy(byteToHex(getChecksum(Encoding.UTF8.GetBytes(new string(autoCmdOutput)))), 0, autoCmdOutput, 8, 2);

                lairdComPort.Write(Encoding.UTF8.GetBytes(new string(autoCmdOutput)), 0, autoCmdOutput.Length);
                //Debug.Print(new string(autoCmdOutput));

                break;

            case DRIVE_MODE.COMPASS:

                //get checksum
                Array.Copy(byteToHex(getChecksum(Encoding.UTF8.GetBytes(new string(compassCmdOutput)))), 0, compassCmdOutput, 8, 2);

                lairdComPort.Write(Encoding.UTF8.GetBytes(new string(compassCmdOutput)), 0, compassCmdOutput.Length);

                //'$','O','C','C',','
                //   ,'0','0',        //bytes 5,6    get byte 1
                //   ,'*'
                //   ,'0','0'
                //   ,0x0D,0x0A};

                break;
            }

            SYSTEM_LED = !SYSTEM_LED;
            onBoardLed.Write(SYSTEM_LED);
        }
예제 #14
0
        private static void testLightLevel()
        {
            using (var analogInput = new AnalogInput(Cpu.AnalogChannel.ANALOG_7))
            {
                analogInput.Scale = 100;

                for (; ;)
                {
                    double currentVal = analogInput.Read();
                    //int raw = analogInput.ReadRaw();
                    Debug.Print("Results: " + currentVal + " (" + analogInput.ReadRaw().ToString() + ")");
                    Thread.Sleep(500);
                }
            }
        }
예제 #15
0

        
예제 #16
0
        public static void Main()
        {
            // {0,1,4,5,6,7,16,32,33,34}
            // PA0,PA1,PA4,PA5,PA6,PA7,PB0,PC0,PC1,PC2
            using (var analogInput = new AnalogInput(Cpu.AnalogChannel.ANALOG_1))
            {
                for (;;)
                {
                    double readVal = analogInput.Read();
                    int    rawVal  = analogInput.ReadRaw();
                    Debug.Print("readVal: " + readVal.ToString() + " ( rawVal " + rawVal.ToString() + ")");

                    Thread.Sleep(1000);
                }
            }
        }
예제 #17
0
        public void ReadTemp()
        {
            var totalAdc    = 0;
            var sampleCount = 100;

            for (int i = 0; i < sampleCount; i++)
            {
                var adc = _aInput.ReadRaw();
                if (adc == 0 || adc >= 4095)
                {
                    addAdcValue(0);
                    return;
                }
                totalAdc += adc;
            }
            //totalAdc = totalAdc >> 2;
            addAdcValue(totalAdc / sampleCount);
        }
예제 #18
0
        /// <summary>
        /// Access the sensor. Returns true if successful, false if it fails.
        /// If false, please check the LastError value for more info.
        /// </summary>
        public void ReadSensor()
        {
            uint[] buffer = new uint[80];
            //int nb, i;

            ///* CONVERT MEASURE */
            int    measure_raw      = _lightin.ReadRaw();
            double measured_voltage = (measure_raw * 3.3 / 4095);
            double res         = 10000 * (3.3 - measured_voltage) / 3.3;
            double illuminance = (double)5 * 100000000 * System.Math.Pow(res, (double)(-2));

            Brightness = (int)(illuminance);

#if (DEBUG)
            Debug.Print("Light_Measure (raw) = " + measure_raw);
            Debug.Print("illuminance = " + illuminance);
#endif
        }
예제 #19
0
        public static void Main()
        {
            // init onboard led port
            var  ledPort = new OutputPort(Pins.ONBOARD_LED, false);
            bool on      = true;

            // analog pin for temperature
            AnalogInput temperaturePin = new AnalogInput(AnalogChannels.ANALOG_PIN_A0);

            // analog pin for light
            AnalogInput lightPin = new AnalogInput(AnalogChannels.ANALOG_PIN_A1);

            // init UART
            string     message     = "";
            SerialPort _serialPort = new SerialPort("COM1", 9600, Parity.Even, 8, StopBits.One);

            _serialPort.Open();

            while (true)
            {
                // make blink on board led to know it's working
                ledPort.Write(on);
                on = !on;

                // ZX-Sensors gives values between 0 and 1023
                // read temperature value and convert it to celcius units
                int    rawTemperature = temperaturePin.ReadRaw();
                double celciusTemp    = ConvertToCelcius(rawTemperature);
                Debug.Print("Temp value: " + celciusTemp.ToString());

                // read light value
                int light = lightPin.ReadRaw();
                Debug.Print("Light value: " + light + "\n");

                // manually serialize message into JSON
                message = "{ 'temp':" + celciusTemp + ", 'light':" + light + " }";

                // send through serial port
                _serialPort.Write(Encoding.UTF8.GetBytes(message), 0, message.Length);

                // Wait to next cycle
                Thread.Sleep(frequency);
            }
        }
예제 #20
0
        public static void Main()
        {
            // write your code here

            BlueSerial ser = new BlueSerial();

            AnalogInput input = new AnalogInput(AnalogChannels.ANALOG_PIN_A4);

            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);

            UInt16 j        = 0;
            int    rawValue = 0;
            UInt16 ll       = 0;

            while (true)
            {
                //  0 e 1023 (ADC a 10 bit)
                rawValue = input.ReadRaw();
                // Debug.Print(rawValue.ToString());

                ll = (UInt16)rawValue;


                // ritorna un valore tra 0 ed 1 che va moltiplicato per
                // la ARef per ottenere il valore in Volt della tensione
                //double volt = input.Read() * 3.3;

                if (ll > 4000)
                {
                    led.Write(true);
                }
                else
                {
                    led.Write(false);
                }


                ser.Print(ll);
                Thread.Sleep(5);
            }
        }
예제 #21
0
        void Loop()
        {
            while (true)
            {
                var gap = DateTime.Now - analogSampleTimepoint;
                if (gap.Ticks / 10000.0 > 40U)     //every 40 milliseconds,read the analog value from the ADC
                {
                    analogSampleTimepoint           = DateTime.Now;
                    analogBuffer[analogBufferIndex] = tdsSensor.ReadRaw();    //read the analog value and store into the buffer
                    analogBufferIndex++;
                    if (analogBufferIndex == SCOUNT)
                    {
                        analogBufferIndex = 0;
                    }
                }

                var gap2 = DateTime.Now - printTimepoint;
                if (gap2.Ticks / 10000.0 > 800U)
                {
                    printTimepoint = DateTime.Now;
                    for (copyIndex = 0; copyIndex < SCOUNT; copyIndex++)
                    {
                        analogBufferTemp[copyIndex] = analogBuffer[copyIndex];
                    }
                    averageVoltage = getMedianNum(analogBufferTemp, SCOUNT) * VREF / 1024.0;                                                                                                         // read the analog value more stable by the median filtering algorithm, and convert to voltage value
                    double compensationCoefficient = 1.0 + 0.02 * (temperature - 25.0);                                                                                                              //temperature compensation formula: fFinalResult(25^C) = fFinalResult(current)/(1.0+0.02*(fTP-25.0));
                    double compensationVolatge     = averageVoltage / compensationCoefficient;                                                                                                       //temperature compensation
                    tdsValue = (133.42 * compensationVolatge * compensationVolatge * compensationVolatge - 255.86 * compensationVolatge * compensationVolatge + 857.39 * compensationVolatge) * 0.5; //convert voltage value to tds value
                    Debug.Print("voltage:");
                    Debug.Print(averageVoltage.ToString());
                    Debug.Print("V   ");
                    Debug.Print("TDS Value:");
                    Debug.Print(tdsValue.ToString());
                    Debug.Print("ppm");
                }
                //Thread.Sleep(20);
            }
        }
예제 #22
0
        void Loop()
        {
            while (true)
            {
                for (int i = 0; i < 10; i++)       //Get 10 sample value from the sensor for smooth the value
                {
                    buf[i] = phSensor.ReadRaw();
                    Thread.Sleep(100);
                }
                for (int i = 0; i < 9; i++)        //sort the analog from small to large
                {
                    for (int j = i + 1; j < 10; j++)
                    {
                        if (buf[i] > buf[j])
                        {
                            temp   = buf[i];
                            buf[i] = buf[j];
                            buf[j] = temp;
                        }
                    }
                }
                avgValue = 0;
                for (int i = 2; i < 8; i++)                      //take the average value of 6 center sample
                {
                    avgValue += buf[i];
                }
                double phValue = avgValue * 5.0 / 1024 / 6; //convert the analog into millivolt
                phValue = 3.5 * phValue;                    //convert the millivolt into pH value
                PhValue = phValue;
                Debug.Print("    pH:");
                Debug.Print(phValue.ToString());
                Debug.Print(" ");

                Thread.Sleep(800);
            }
        }
예제 #23
0
 public int Read()
 {
     return(_input.ReadRaw());
 }
예제 #24
0
        public static void Main()
        {
            //one heartbeat 272.72ms
            #region ECG
            int[] ecgValues = new int[] { 238, 238, 238, 238, 238, 238, 238, 248, 258, 269, 280, 294, 308, 313, 318, 313, 308, 301, 294, 287, 280, 273, 266, 259,
                                          252, 245, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 227, 217, 199, 182, 255, 329, 444, 560, 672, 784, 871,
                                          959, 773, 588, 301, 014, 059, 105, 161, 217, 227, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238,
                                          238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 248, 259, 266, 273, 280, 287, 294, 301, 308, 315, 322,
                                          329, 336, 343, 346, 350, 353, 357, 360, 364, 360, 357, 353, 350, 346, 343, 336, 329, 322, 315, 304, 294, 280, 266, 252,
                                          238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 238, 248, 259, 262, 266, 259, 252, 245, 238, 238, 238, 238, 238, 238, 238 };
            #endregion

            #region Constants
            const long TIME_ONE_MS_IN_TICK          = 10000;
            const int  TIME_ONE_MIN_IN_MS           = 60000;
            const int  STATE_DYNAMIC                = 0;
            const int  STATE_STATIC                 = 1;
            const long LENGTH_ONE_HEARTBEAT_IN_TICK = 2727272;
            const int  AVG_ECG_VALUE                = 238;
            const int  BPM_HEART_MAX                = 220;
            const int  BPM_HEART_MIN                = 40;
            #endregion

            #region Var
            Button      btnJoy = new Button(true, new InputPort(GHICard.Socket10.Pin3, false, Port.ResistorMode.Disabled), 100);
            AnalogInput joyX   = new AnalogInput(GHICard.Socket10.AnalogInput4);
            joyX.Scale  = BPM_HEART_MAX - BPM_HEART_MIN;
            joyX.Offset = BPM_HEART_MIN;
            AnalogOutput analogOut         = new AnalogOutput(GHICard.Socket9.AnalogOutput);
            int          state             = STATE_STATIC;
            long         timeToWait        = 10000000; //in tick
            int          index             = 0;
            long         ticksAtLastChange = 0;
            long         ticksAtLastWait   = 0;
            bool         isBeating         = true;
            #endregion

            //Main Loop
            while (true)
            {
                //Inputs management
                if (btnJoy.isPressed())
                {
                    if (state == STATE_DYNAMIC)
                    {
                        state = STATE_STATIC;
                    }
                    else if (state == STATE_STATIC)
                    {
                        state = STATE_DYNAMIC;
                    }
                }

                switch (state)
                {
                case STATE_DYNAMIC:
                    int  bpm = joyX.ReadRaw();
                    long timeTotalHeartbeat = bpm * LENGTH_ONE_HEARTBEAT_IN_TICK;
                    timeToWait = (TIME_ONE_MIN_IN_MS * TIME_ONE_MS_IN_TICK) - timeTotalHeartbeat;
                    break;

                case STATE_STATIC:

                default:
                    break;
                }

                //Outputs management
                long ticks = Utility.GetMachineTime().Ticks;
                if (isBeating)
                {
                    long elapsedTimeHeartbeat = ticks - ticksAtLastChange;
                    if (elapsedTimeHeartbeat >= LENGTH_ONE_HEARTBEAT_IN_TICK / ecgValues.Length)
                    {
                        if (index == ecgValues.Length - 1)
                        {
                            index           = 0;
                            isBeating       = false;
                            ticksAtLastWait = ticks;
                        }
                        else
                        {
                            index++;
                        }

                        ticksAtLastChange = ticks;
                    }
                }
                else
                {
                    long elapsedTimeWait = ticks - ticksAtLastWait;
                    if (elapsedTimeWait >= timeToWait)
                    {
                        isBeating         = true;
                        ticksAtLastChange = ticks;
                    }
                }

                //View
                if (isBeating)
                {
                    analogOut.WriteRaw(ecgValues[index]);
                }
                else
                {
                    analogOut.WriteRaw(AVG_ECG_VALUE);
                }
            }//End while
        }
예제 #25
0
        public static void recordData()
        {
            // record is true while recording, and false after
            bool record = true;
            // counter for recording loop
            int i = 0;


            while (record)
            {
                // start new recording cycle
                if (i == nSamples)
                {
                    i = 0;
                }


                reading[i] = (ushort)accRead.ReadRaw();

                #region old

                //// Check for max and min
                //if (i == 0)
                //{
                //    max = reading[i];
                //    min = max;
                //}

                //if (reading[i] > max)
                //{
                //    max = reading[i];

                //}
                //else if (reading[i] < min)
                //{
                //    min = reading[i];
                //}


                //if (reading[i] > 2500)
                //{
                //    trigger = true;
                //    triggerI = i;
                //}

                //if (i == 9999)
                //{
                //    j++;
                //    Debug.Print("Cycle" + j.ToString());
                //    Debug.Print("Maximum " + max.ToString());
                //    Debug.Print("Minimum " + min.ToString());
                //    Debug.Print("Reading length " + reading.Length.ToString());


                //    v = max;
                //    vHigh = (byte)(v >> 8);
                //    vLow = (byte)(v & 0x00FF);

                //    //serial.WriteByte(vHigh);
                //    //serial.WriteByte(vLow);

                //}

                #endregion

                i++;

                record = false;
            } // while loop
        }     // record void
예제 #26
0
        /// <summary>
        /// Most dark - 0.0
        /// Most bright - 1.0
        /// </summary>
        /// <returns></returns>
        public double TakeMeasurement()
        {
            var raw = aiLightSense.ReadRaw();

            return((double)raw / 4096);
        }
예제 #27
0
        void runReadSensorThread()
        {
            DateTime actTime = DateTime.Now;
            int      counter;
            int      sum = 0;

            for (counter = 0; counter < 100; counter++)
            {
                sum += input.ReadRaw();
            }
            oldState = sum > threshold ? InputSensorState.Low : InputSensorState.High;
            sum      = 0;

            while (true)
            {
                if (!_stopped)
                {
                    /*
                     * // This was for tests
                     * if (oldState == InputSensorState.High)
                     * {
                     *  actState = InputSensorState.Low;
                     *  OnCurrentSensorSend(this, new OnOffSensorEventArgs(actState, oldState, DateTime.Now.AddMinutes(RoSchmi.DayLihtSavingTime.DayLihtSavingTime.DayLightTimeOffset(dstStart, dstEnd, dstOffset, DateTime.Now, true)), SensorLabel, SensorLocation, MeasuredQuantity, DestinationTable, Channel, false));
                     *  oldState = InputSensorState.Low;
                     * }
                     * else
                     * {
                     *  actState = InputSensorState.High;
                     *  OnCurrentSensorSend(this, new OnOffSensorEventArgs(actState, oldState, DateTime.Now.AddMinutes(RoSchmi.DayLihtSavingTime.DayLihtSavingTime.DayLightTimeOffset(dstStart, dstEnd, dstOffset, DateTime.Now, true)), SensorLabel, SensorLocation, MeasuredQuantity, DestinationTable, Channel, false));
                     *  oldState = InputSensorState.High;
                     * }
                     * Thread.Sleep(20000);
                     */

                    lock (theLock)
                    {
                        sum = 0;
                        for (counter = 0; counter < 100; counter++)
                        {
                            sum += input.ReadRaw();
                        }
                        if (sum > threshold)  // pump is on
                        {
                            Thread.Sleep(20); // (debouncing)
                            sum = 0;
                            for (counter = 0; counter < 100; counter++)
                            {
                                sum += input.ReadRaw();
                            }
                            if (sum > threshold)  // pump is still on
                            {
                                if (oldState == InputSensorState.High)
                                {
                                    actState = InputSensorState.Low;
                                    //DateTime time = DateTime.Now;
                                    //Debug.Print("On " + time.TimeOfDay  + ": " + sum + "\r\n");
                                    //OnCurrentSensorSend(this, new CurrentSensorEventArgs(actState, oldState, DateTime.Now.AddMinutes(RoSchmi.DayLihtSavingTime.DayLihtSavingTime.DayLightTimeOffset(dstStart, dstEnd, dstOffset, DateTime.Now, true)), SensorLabel, SensorLocation, MeasuredQuantity, DestinationTable, Channel, false));
                                    OnCurrentSensorSend(this, new OnOffSensorEventArgs(actState, oldState, 0x00, DateTime.Now.AddMinutes(RoSchmi.DayLihtSavingTime.DayLihtSavingTime.DayLightTimeOffset(dstStart, dstEnd, dstOffset, DateTime.Now, true)), SensorLabel, SensorLocation, MeasuredQuantity, DestinationTable, Channel, false));
                                    oldState = InputSensorState.Low;
                                }
                            }
                        }
                        else
                        {
                            Thread.Sleep(20);             // (debouncing)
                            sum = 0;
                            for (counter = 0; counter < 100; counter++)
                            {
                                sum += input.ReadRaw();
                            }
                            if (sum <= threshold)  // pump is still off
                            {
                                if (oldState == InputSensorState.Low)
                                {
                                    actState = InputSensorState.High;
                                    //DateTime time = DateTime.Now;
                                    //Debug.Print("Off " + time.TimeOfDay  + ": " + sum + "\r\n");
                                    //OnCurrentSensorSend(this, new CurrentSensorEventArgs(actState, oldState, DateTime.Now.AddMinutes(RoSchmi.DayLihtSavingTime.DayLihtSavingTime.DayLightTimeOffset(dstStart, dstEnd, dstOffset, DateTime.Now, true)), SensorLabel, SensorLocation, MeasuredQuantity, DestinationTable, Channel, false));
                                    OnCurrentSensorSend(this, new OnOffSensorEventArgs(actState, oldState, 0x00, DateTime.Now.AddMinutes(RoSchmi.DayLihtSavingTime.DayLihtSavingTime.DayLightTimeOffset(dstStart, dstEnd, dstOffset, DateTime.Now, true)), SensorLabel, SensorLocation, MeasuredQuantity, DestinationTable, Channel, false));
                                    oldState = InputSensorState.High;
                                }
                            }
                        }
                    }
                }
                Thread.Sleep(202);
            }
        }
예제 #28
0
        public static int Look()
        {
            int reading = irPin.ReadRaw();

            return(reading);
        }
예제 #29
0
        public static void Main()
        {
            // write your code here

            BlueSerial ser = new BlueSerial();

            AnalogInput input1 = new AnalogInput(AnalogChannels.ANALOG_PIN_A0);  // 2 kN loadcell
            AnalogInput input2 = new AnalogInput(AnalogChannels.ANALOG_PIN_A1);  // 200 kN loadcell

            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);

            UInt16 j         = 0;
            int    rawValue1 = 0;
            int    rawValue2 = 0;
            float  rawAve1kN = 0;
            float  rawAve2kN = 0;
            int    rawAve1   = 0;
            int    rawAve2   = 0;
            int    i         = 0;
            UInt16 uintIn1   = 0;
            UInt16 uintIn2   = 0;

            while (true)
            {
                rawValue1 = 0;
                rawValue2 = 0;
                rawAve1   = 0;
                rawAve2   = 0;

                for (i = 1; i <= 50; i++)   // Take an average of 50 samples
                {
                    rawValue1 = input1.ReadRaw();
                    rawAve1   = rawAve1 + rawValue1;
                    rawValue2 = input2.ReadRaw();
                    rawAve2   = rawAve2 + rawValue2;
                    Thread.Sleep(2);
                }

                rawAve1 = rawAve1 / (i - 1);
                rawAve2 = rawAve2 / (i - 1);

                rawAve1kN = (float)((rawAve1 - 2071) / -943.20518975); // 2 kN loadcell calibration under "loadcellcalibration.xlsx"
                rawAve2kN = (float)((rawAve2 - 2064) / -13.75116883);  // 200 kN loadcell calibration under "loadcellcalibration.xlsx"


                // Print some values to the output window. This is primative, but works for now.

                Debug.Print("Value 1 Ave: " + rawAve1.ToString() + "    Value 1 Raw: " + rawValue1.ToString() + "    2kN Load Cell Value 1 kN: " + rawAve1kN.ToString() + "    Value 2 Ave: " + rawAve2.ToString() + "    Value 2 Raw: " + rawValue2.ToString() + "    200kN Load Cell Value 2 kN: " + rawAve2kN.ToString());

                uintIn1 = (UInt16)rawAve1;
                uintIn2 = (UInt16)rawAve2;


                // Send the data via bluetooth
                string junk = (uintIn1.ToString() + " " + uintIn2.ToString() + "\n");

                byte[] data = new byte[4] {
                    (byte)(uintIn1 & 0xFF), (byte)((uintIn1 >> 8) & 0xFF), (byte)(uintIn2 & 0xFF), (byte)((uintIn2 >> 8) & 0xFF)
                };                                                                                                                                          // Small loadcell first, then large loadcell

                // ser.Print(strain1);
                // Thread.Sleep(5);
                ser.Print(junk);
                //ser.Print(data);
                Thread.Sleep(5);
            }
        }
예제 #30
0
        public static void Main()
        {
            //Time for the screen to turn on
            Thread.Sleep(40);

            double oldtemp    = 0;
            double oldoldtemp = 0;

            while (true)
            {
                //Gets the temperature
                long ticks           = Utility.GetMachineTime().Ticks;
                int  heatSensorValue = heatSensor.ReadRaw();
                oldoldtemp  = oldtemp;
                oldtemp     = temperature;
                temperature = (heatSensorValue * HIGHEST_VOLTAGE) / System.Math.Pow(2, GHICard.SupportedAnalogInputPrecision) - (VOLTAGE_0_DEGREE / TEMPERATURE_COEFFICIENT);
                temperature = AvgDouble(new double[] { oldoldtemp, oldtemp, temperature });
                oldError    = error;
                error       = requestedTemperature - temperature;

                #region STATE MANAGEMENT
                switch (state)
                {
                case State.SettingsOff:
                    if (btnSetting.isPressed())
                    {
                        checkTime = ticks;
                        state     = State.SettingsTemperature;
                    }
                    break;

                case State.SettingsTemperature:
                    elapsedTime = ticks - checkTime;

                    if (btnAdd.isPressed())
                    {
                        state = State.IncrementTemperature;
                    }
                    if (btnRemove.isPressed())
                    {
                        state = State.DecrementTemperature;
                    }
                    if (elapsedTime >= TIMER_LENGHT * TIME_ONE_MS_IN_TICKS)
                    {
                        state = State.SettingsOff;
                    }
                    if (btnSetting.isPressed())
                    {
                        checkTime = ticks;
                        state     = State.SettingsGain;
                    }
                    break;

                case State.SettingsGain:
                    elapsedTime = ticks - checkTime;

                    if (btnAdd.isPressed())
                    {
                        state = State.IncrementGain;
                    }
                    if (btnRemove.isPressed())
                    {
                        state = State.DecrementGain;
                    }
                    if (btnSetting.isPressed() || elapsedTime >= TIMER_LENGHT * TIME_ONE_MS_IN_TICKS)
                    {
                        state = State.SettingsOff;
                    }
                    break;

                case State.IncrementTemperature:
                    requestedTemperature++;

                    checkTime = ticks;
                    state     = State.SettingsTemperature;
                    break;

                case State.DecrementTemperature:
                    requestedTemperature--;

                    checkTime = ticks;
                    state     = State.SettingsTemperature;
                    break;

                case State.IncrementGain:
                    if (gainI < MAX_GAIN)
                    {
                        gainI += GAIN_STEP;
                    }

                    checkTime = ticks;
                    state     = State.SettingsGain;
                    break;

                case State.DecrementGain:
                    if (gainI > MIN_GAIN)
                    {
                        gainI -= GAIN_STEP;
                    }

                    checkTime = ticks;
                    state     = State.SettingsGain;
                    break;

                default:
                    break;
                }
                #endregion

                #region HEAT MANAGEMENT
                errorSum += error;

                resistorDutyCycleP = gainP * error;
                resistorDutyCycleI = gainI * errorSum;
                resistorDutyCycleD = gainD * (error - oldError);
                resistorDutyCycle  = AvgDouble(new double[] { resistorDutyCycleP, resistorDutyCycleI, resistorDutyCycleD });
                resistorDutyCycle  = LimitToPercentage(resistorDutyCycle);

                resistor.DutyCycle = resistorDutyCycle;
                #endregion

                #region OUTPUT MANAGEMENT
                lcd.SetCursor(0, 0);
                lcd.Write(temperature.ToString(TEMPERATURE_FORMAT));
                lcd.SetCursor(1, 0);
                string settingsText = "";
                switch (state)
                {
                case State.SettingsOff:
                    settingsText = "Off        ";
                    break;

                case State.SettingsTemperature:
                    settingsText = "Temperature";
                    break;

                case State.SettingsGain:
                    settingsText = "Gain       ";
                    break;
                }
                lcd.Write(settingsText);
                lcd.SetCursor(0, 7);
                lcd.Write(gainI.ToString(GAIN_FORMAT));
                lcd.SetCursor(1, 12);
                lcd.Write(requestedTemperature.ToString(TEMPERATURE_FORMAT));
                #endregion
            }
        }