示例#1
0
        private int GetDistance()
        {
            // First we need to pulse the port from high to low.
            _port.Active = true;  // Put port in write mode
            _port.Write(true);    // Pulse pin
            _port.Write(false);
            _port.Active = false; // Put port in read mode;

            var lineState = false;

            // Wait for the line to go high, for start of pulse.
            while (lineState == false)
            {
                lineState = _port.Read();
            }

            var startOfPulseAt = DateTime.Now.Ticks; // Save start ticks.

            // Wait for line to go low.
            while (lineState)
            {
                lineState = _port.Read();
            }

            var endOfPulse = DateTime.Now.Ticks; // Save end ticks.

            var ticks = (int)(endOfPulse - startOfPulseAt);

            return(ticks / 580);
        }
示例#2
0
        /// <summary>
        /// Retrieves measured data from the sensor.
        /// </summary>
        /// <returns>
        /// <c>true</c> if the operation succeeds and the data is valid, otherwise <c>false</c>.
        /// </returns>
        public bool Read()
        {
            if (disposed)
            {
                throw new ObjectDisposedException();
            }
            // The 'bitMask' also serves as edge counter: data bit edges plus
            // extra ones at the beginning of the communication (presence pulse).
            bitMask = 1L << 41;

            data = 0;
            // lastTicks = 0; // This is not really needed, we measure duration
            // between edges and the first three values are ignored anyway.

            // Initiate communication
            portOut.Active = true;
            portOut.Write(false);       // Pull bus low
            Thread.Sleep(StartDelay);
            portIn.EnableInterrupt();   // Turn on the receiver
            portOut.Active = false;     // Release bus

            bool dataValid = false;

            // Now the interrupt handler is getting called on each falling edge.
            // The communication takes up to 5 ms, but the interrupt handler managed
            // code takes longer to execute than is the duration of sensor pulse
            // (interrupts are queued), so we must wait for the last one to finish
            // and signal completion. 20 ms should be enough, 50 ms is safe.
            if (dataReceived.WaitOne(50, false))
            {
                // TODO: Use two short-s ?
                bytes[0] = (byte)((data >> 32) & 0xFF);
                bytes[1] = (byte)((data >> 24) & 0xFF);
                bytes[2] = (byte)((data >> 16) & 0xFF);
                bytes[3] = (byte)((data >> 8) & 0xFF);

                byte checksum = (byte)(bytes[0] + bytes[1] + bytes[2] + bytes[3]);
                if (checksum == (byte)(data & 0xFF))
                {
                    dataValid = true;
                    Convert(bytes);
                }
                else
                {
                    Debug.Print("DHT sensor data has invalid checksum.");
                }
            }
            else
            {
                portIn.DisableInterrupt();               // Stop receiver
                Debug.Print("DHT sensor data timeout."); // TODO: TimeoutException?
            }
            return(dataValid);
        }
        public long ReadRightIR()
        {
            // Turn on IR LEDs (optional)
            LEDIREmmitter.Write(true);

            // Make the I/O line connected to that sensor an output and drive it high
            RightIR.Active = true;   // Set to output pin
            RightIR.Write(true);     // Set pin to high to charge capacitor

            // Wait several microseconds to give the 1 nF capacitor node time to reach 5 V
            Thread.Sleep(5);  // Wait about 10 milliseconds to allow capacitor to charge

            // Take starting time
            StartTicks = System.DateTime.Now.Ticks;

            // Make the I/O line an input (with internal pull-up disabled)
            RightIR.Active = false;    // Set to input pin

            // Measure the time for the capacitor node to discharge by waiting for the I/O line to go low
            while (RightIR.Read() == true)
            {
            }

            //StopTicks = new tick count;
            StopTicks = System.DateTime.Now.Ticks;

            // If time is less than the threshold value, then interpret result as a detection of a white line
            TickDiff = StopTicks - StartTicks;

            // Turn off IR LEDs (optional)
            LEDIREmmitter.Write(false);

            return(TickDiff);
        }
示例#4
0
 /// <summary>
 /// Constructor. Needs to interrupt pins to be provided and linked together in Hardware.
 /// Blocking call for 1s to give sensor time to initialize.
 /// </summary>
 public DHT22(Cpu.Pin In, Cpu.Pin Out)
 {
     _dht22out = new TristatePort(Out, false, false, Port.ResistorMode.PullUp);
     _dht22in  = new SignalCapture(In, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeBoth);
     if (_dht22out.Active == false)
     {
         _dht22out.Active = true; // Make tristateport "output"
     }
     _dht22out.Write(true);       // "high up" (standby state)
     Thread.Sleep(1000);          // 1s to pass the "unstable status" as per the documentation
 }
示例#5
0
        public static void Main()
        {
            //Tristate Port init
            //Tristate Port set as input mode
            TristatePort tristate = new TristatePort((Cpu.Pin)(STM32.GPIO.GPIOD_15), false, false, Port.ResistorMode.PullUp);

            Debug.Print("Port is input port.");
            Thread.Sleep(1000);
            //Tristate Port set as output mode
            tristate.Active = true;
            Debug.Print("Port is output port");
            //Tristate set as high when output mode
            tristate.Write(true);
            Debug.Print("Output is high!");
            Thread.Sleep(5000);
            //Tristate set as low when output mode
            tristate.Write(false);
            Debug.Print("Output is low");
            Thread.Sleep(1000);
        }
示例#6
0
        // Execute transmission start sequence for commands
        private static void StartTransmission()
        {
            if (!_dataPort.Active)
            {
                _dataPort.Active = true;
            }

            // transmission start sequence
            _dataPort.Write(true);
            _clkPort.Write(true);
            _dataPort.Write(false);
            _clkPort.Write(false);
            _clkPort.Write(true);
            _dataPort.Write(true);
            _clkPort.Write(false);
        }
        public static void Main()
        {
            TristatePort tristatePort = new TristatePort(Cpu.Pin.GPIO_Pin4,
                                                         false, //initial state
                                                         false, //no glitch filter
                                                         Port.ResistorMode.PullUp);

            Debug.Print("Port is inactive and acts as input port.");
            Debug.Print("Input = " + tristatePort.Read());

            tristatePort.Active = true;
            Debug.Print("Port is active and acts as output port.");
            tristatePort.Write(true);
        }
示例#8
0
        public int read()
        {
            const int buffersize = 5;

            int[] buffer = new int[buffersize];
            int   cnt    = 7;
            int   idx    = 0;

            //clear buffer
            for (int i = 0; i < buffersize; i++)
            {
                buffer[i] = 0;
            }



            //Write frame delimiter to sensor
            Triport.Active = true;
            Triport.Write(false);
            Thread.Sleep(18); //sleep 18 miliseconds
            Triport.Write(true);

            //Now switch port to input mode and wait for signal
            long time = Microseconds();

            //(40) ~= 61 microseconds
            //DelayMicroseconds(1);
            long delta = Microseconds() - time;

            delta = Microseconds() - time;

            Debug.Print((delta / 10).ToString());


            Triport.Active = false; //set tristate to disabled

            //InputPort Inport = new InputPort(IOPin,true,

            // Countdown values are pulled from arduiono code, may require tuning
            int loopcount = 10000;

            while (Triport.Read() == false)
            {
                if (loopcount-- == 0)
                {
                    return(-2);
                }
            }

            loopcount = 10000;
            while (Triport.Read() == true)
            {
                if (loopcount-- == 0)
                {
                    return(-3);
                }
            }


            //read 40 bits or timeout
            for (int i = 0; i < 40; i++)
            {
                loopcount = 10000;
                while (Triport.Read() == false)
                {
                    if (loopcount-- == 0)
                    {
                        return(-4);
                    }
                }

                long t = Microseconds();

                loopcount = 10000;
                while (Triport.Read() == true)
                {
                    if (loopcount-- == 0)
                    {
                        return(-5);
                    }
                }


                if ((Microseconds() - t) > 40)
                {
                    buffer[idx] |= (1 << cnt);
                }
                if (cnt == 0) //next byte?
                {
                    cnt = 7;
                    idx++;
                }
                else
                {
                    cnt--;
                }
            }

            //write to vars
            humidity    = buffer[0];
            temperature = buffer[2];
            int sum = buffer[0] + buffer[2];

            if (buffer[4] != sum)
            {
                return(-1);
            }
            return(0);
        }
示例#9
0
文件: RHT03.cs 项目: valoni/NETMF44
        private bool Read(bool raiseEvent = true)
        {
            // The 'bitMask' also serves as edge counter: data bit edges plus extra ones at the beginning of the communication (presence pulse).
            _bitMask    = 1L << 42;
            _sensorData = 0;
            bool dataValid = false;

            // Initiate communication
            if (_portOut.Active == false)
            {
                _portOut.Active = true;
            }
            _portOut.Write(false);     // Pull pin low
            Thread.Sleep(5);           // At lest 1 mSec.
            _portIn.EnableInterrupt(); // Turn on the receiver
            if (_portOut.Active)
            {
                _portOut.Active = false;
            }

            // Now the interrupt handler is getting called on each falling edge.
            // The communication takes up to 5 ms, but the interrupt handler managed
            // code takes longer to execute than is the duration of sensor pulse
            // (interrupts are queued), so we must wait for the last one to finish
            // and signal completion. 20 ms should be enough, 50 ms is safe.
            // Set to 50 to minimize checksum and timeout errors. The higher the value
            // the less timeout errors, consequently longer conversion time.
            if (_dataReceived.WaitOne(200, true))
            {
                DataBytes[0] = (byte)((_sensorData >> 32) & 0xFF);
                DataBytes[1] = (byte)((_sensorData >> 24) & 0xFF);
                DataBytes[2] = (byte)((_sensorData >> 16) & 0xFF);
                DataBytes[3] = (byte)((_sensorData >> 8) & 0xFF);

                var checksum = (byte)(DataBytes[0] + DataBytes[1] + DataBytes[2] + DataBytes[3]);
                if (checksum == (byte)(_sensorData & 0xFF))
                {
                    dataValid = true;
                    Convert(DataBytes, raiseEvent);
                }
                else
                {
                    if (SensorError != null)
                    {
                        SensorError(this, "RHT sensor data has invalid checksum.");
                    }
                    _temperature = float.MinValue;
                    _humidity    = float.MinValue;
                }
            }
            else
            {
                //_temperature = float.MinValue;
                //_humidity = float.MinValue;

                _portIn.DisableInterrupt(); // Stop receiver
                if (SensorError != null)
                {
                    SensorError(this, "RHT sensor data timeout.");
                }
                return(false);
            }
            return(dataValid);
        }
        public override void Write(bool state)
        {
            Mode = Socket.SocketInterfaces.IOMode.Output;

            _port.Write(state);
        }
示例#11
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 bool ReadSensor()
        {
            uint[] buffer = new uint[80];
            int    nb, i;

            /* REQUEST SENSOR MEASURE */
            // Test if the 2 pins are connected together
            bool rt = _dht22in.InternalPort.Read(); // Should be true

            _dht22out.Write(false);                 // "low down": initiate transmission
            bool rf = _dht22in.InternalPort.Read(); // Should be false

            if (!rt || rf)
            {
                LastError = "The 2 pins are not hardwired together !";
                _dht22out.Write(true);   // "high up" (standby state)
                return(false);
            }
            Thread.Sleep(1);         // For "at least 1ms" as per the documentation
            _dht22out.Write(true);   // "high up" then listen

            /* READ MEASURE */
            _dht22out.Active     = false;             // Tristate Read
            _dht22in.ReadTimeout = 500;               // Timeout value in ms
            nb = _dht22in.Read(false, buffer, 0, 80); // get the sensor answer
            _dht22out.Active = true;                  // Tristate Write
            _dht22out.Write(true);                    // "high up"
            if (nb < 69)
            {
                LastError = "Did not receive enough data from the sensor";
                return(false);
            }

            /* CONVERT MEASURE */
            nb -= 2; // skip last 50us down
            byte checksum = 0;
            uint T = 0, H = 0;

            // Convert CheckSum
            for (i = 0; i < 8; i++, nb -= 2)
            {
                checksum |= (byte)(buffer[nb] > 35 ? 1 << i : 0);
            }

            // Convert Temperature
            for (i = 0; i < 16; i++, nb -= 2)
            {
                T |= (uint)(buffer[nb] > 35 ? 1 << i : 0);
            }
            Temperature = ((float)(T & 0x7FFF)) * ((T & 0x8000) > 0 ? -1 : 1) / 10;

            // Convert Humidity
            for (i = 0; i < 10; i++, nb -= 2)
            {
                H |= (uint)(buffer[nb] > 35 ? 1 << i : 0);
            }
            Humidity = ((float)H) / 10;

            // Check CheckSum
            if ((((H & 0xFF) + (H >> 8) + (T & 0xFF) + (T >> 8)) & 0xFF) != checksum)
            {
                LastError = "Checksum Error";
                return(false);
            }
            // No error case
            LastError = "";
            return(true);
        }