/// <summary>
        /// Returns the current temperature in Celsius
        /// </summary>
        /// <returns>Temperature in Celsius</returns>
        public async Task <double> GetTemperatureAsync()
        {
            if (!_isInitialized)
            {
                throw new Exception("Sensor is not initialized");
            }

            byte[] tempCommand = new byte[1] {
                TriggerTemperatureMeasurement
            };
            byte[] tempData = new byte[2];

            _i2cTempHumiditySensor.Write(tempCommand);

            // Per datasheet 14-bit temperature needs 10.8 msec
            await Task.Delay(50);

            _i2cTempHumiditySensor.Read(tempData);

            // Combine bytes
            var rawTempReading = tempData[0] << 8 | tempData[1];
            // Calculate relative temperature signal output
            var tempRatio = rawTempReading / (float)65536;
            // Temp conversion formula per SI7021 datasheet
            double temperature = (-46.85 + (175.72 * tempRatio));

            return(temperature);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Indicates if rtc has been reset (lost of power)
 /// </summary>
 /// <returns>true if rtc power has been lost, else false</returns>
 public bool HasBeenReset()
 {
     byte[] readBuffer = new byte[1];
     _rtcDevice.Write(new byte[] { 0x00 });
     _rtcDevice.Read(readBuffer);
     return((readBuffer[0] & 0x80) != 0);
 }
Ejemplo n.º 3
0
        private bool TryReadSensorData(Register cmd, out double temperature, out double humidity)
        {
            Write(cmd);

            Span <byte> readBuff = stackalloc byte[6];

            _i2cDevice.Read(readBuff);

            // Details in the Datasheet P7
            int st  = BinaryPrimitives.ReadInt16BigEndian(readBuff.Slice(0, 2));     // Temp
            int srh = BinaryPrimitives.ReadUInt16BigEndian(readBuff.Slice(3, 2));    // Humi

            // check 8-bit crc
            bool tCrc  = CheckCrc8(readBuff.Slice(0, 2), readBuff[2]);
            bool rhCrc = CheckCrc8(readBuff.Slice(3, 2), readBuff[5]);

            if (!tCrc || !rhCrc)
            {
                temperature = double.NaN;
                humidity    = double.NaN;
                return(false);
            }

            temperature = st;
            humidity    = srh;
            return(true);
        }
Ejemplo n.º 4
0
 private byte ReadByte(byte command)
 {
     byte[] buffer = new byte[1];
     _sensor.Write(new byte[] { command });
     _sensor.Read(buffer);
     return(buffer[0]);
 }
Ejemplo n.º 5
0
 // Read 1 byte from register
 protected byte ReadRegister(byte register)
 {
     sensor.Write(new byte[] { register });
     byte[] buffer = new byte[1];
     sensor.Read(buffer);
     return(buffer[0]);
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Read humidity value from the sensor
        /// </summary>
        /// <returns>humidity as a floating point number</returns>
        protected float ReadHumidity()
        {
            _i2CDevice.Write(TRIGGER_HUMD_MEASURE_HOLD);

            //Hang out while measurement is taken. 50mS max, page 4 of datasheet.
            Thread.Sleep(100);

            //Comes back in three bytes, data(MSB) / data(LSB) / Checksum
            byte[] readHum = new byte[3];
            _i2CDevice.Read(readHum);

            byte msb      = readHum[0];
            byte lsb      = readHum[1];
            byte checksum = readHum[2];

            uint rawHumidity = ((uint)msb << 8) | (uint)lsb;

            if (!IsCRCValid((UInt16)rawHumidity, checksum))
            {
                return(ERROR_HUMIDITY); //Error out
            }
            rawHumidity &= 0xFFFC;      //Zero out the status bits but keep them in place

            //Given the raw humidity data, calculate the actual relative humidity
            float tempRH = rawHumidity / (float)65536; //2^16 = 65536
            float rh     = -6 + (125 * tempRH);        //From page 14

            return(rh);
        }
Ejemplo n.º 7
0
 private byte Read8(byte reg)
 {
     byte[] buffer = new byte[1];
     _sensor.Write(new[] { reg });
     _sensor.Read(buffer);
     return(buffer[0]);
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Get ASG01DB VOC Gas Concentration
        /// </summary>
        /// <returns>Concentration (ppm)</returns>
        private double GetConcentration()
        {
            // The time of two measurements should be more than 2s.
            while (Environment.TickCount - _lastMeasurement < 2000)
            {
                Thread.Sleep(Environment.TickCount - _lastMeasurement);
            }

            // Details in the Datasheet P5
            // Write command MSB, LSB
            Span <byte> writeBuff = stackalloc byte[2]
            {
                (byte)Register.ASG_DATA_MSB, (byte)Register.ASG_DATA_LSB
            };
            // Return data MSB, LSB, CRC checksum
            Span <byte> readBuff = stackalloc byte[3];

            _i2cDevice.Write(writeBuff);
            _i2cDevice.Read(readBuff);

            _lastMeasurement = Environment.TickCount;

            // CRC check error
            if (!CheckCrc8(readBuff.Slice(0, 2), 2, readBuff[2]))
            {
                return(-1);
            }

            ushort res = BinaryPrimitives.ReadUInt16BigEndian(readBuff.Slice(0, 2));

            return(res / 10.0);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Read data lengh bytes
        /// Return the saved string
        // </summary>
        public String Read(int address, int datalength = PAGESIZE)
        {
            try
            {
                // Avoid wrap around issues
                if (datalength > PAGESIZE)
                {
                    // 60 max string size
                    datalength = PAGESIZE - 4;
                }


                var Data = new byte[datalength];

                EEprom.Write(new[] { (Byte)(address >> 8), (Byte)(address & 0xFF) });

                EEprom.Read(Data);

                //Get the first char in the two byte length
                char flb = Convert.ToChar(Data[0]);

                Console.WriteLine("First length char " + flb.ToString());

                // Get the second char in length
                char slb = Convert.ToChar(Data[1]);

                Console.WriteLine("Second length char " + slb.ToString());

                //make the string
                string sl = flb.ToString() + slb.ToString();

                //Convert to integer
                int length = Convert.ToInt32(sl);

                Console.WriteLine("Length " + length);

                string rs = string.Empty;

                //Start reading after the two byte saved length
                for (int i = 2; i < length + 2; i++)
                {
                    char c = Convert.ToChar(Data[i]);

                    rs = rs + c.ToString();

                    Console.WriteLine("Read Adddress  " + address + " Char Read " + c.ToString());

                    address += 1;
                }

                return(rs);
            }

            catch (Exception)
            {
                return("Error reading eeprom");
            }
        }
Ejemplo n.º 10
0
        internal ushort Read16(Register reg)
        {
            _i2cDevice.WriteByte((byte)reg);
            Span <byte> buf = stackalloc byte[2];

            _i2cDevice.Read(buf);

            return((ushort)(buf[1] << 8 | buf[0]));
        }
Ejemplo n.º 11
0
        /// <summary>
        ///  Reads a 16 bit value over I2C
        /// </summary>
        /// <param name="register">
        ///  Register to read from
        /// </param>
        /// <returns>
        ///  Value from register
        /// </returns>
        internal ushort Read16BitsFromRegister(byte register)
        {
            Span <byte> bytes = stackalloc byte[2];

            _i2cDevice.WriteByte(register);
            _i2cDevice.Read(bytes);

            return(BinaryPrimitives.ReadUInt16LittleEndian(bytes));
        }
Ejemplo n.º 12
0
 private byte ReadReg(Register reg)
 {
     byte[] writeBuffer = new byte[1];
     writeBuffer[0] = (byte)reg;
     byte[] readBuffer = new byte[1];
     _i2C.Write(writeBuffer);
     _i2C.Read(readBuffer);
     return(readBuffer[0]);
 }
Ejemplo n.º 13
0
        public int ReadC0()
        {
            Span <byte> data = stackalloc byte[1];

            _sensor.Write(new [] { (byte)0x29 });
            _sensor.Read(data);

            // return data c0
            return(data[0]);
        }
Ejemplo n.º 14
0
        private Byte[] Read(Int32 responseLength)
        {
            var buffer = new Byte[responseLength];

            lock (Hardware.LockI2C)
            {
                _fm.Read(buffer);
            }

            return(buffer);
        }
Ejemplo n.º 15
0
        internal byte ReadByte(byte address)
        {
            byte[] buffer = { address };
            byte[] value  = new byte[1];

            // _device.WriteRead(buffer, value);
            _device.Write(buffer);
            _device.Read(value);

            return(value[0]);
        }
Ejemplo n.º 16
0
        private Byte[] Read(Int32 responseLength)
        {
            var buffer = new Byte[responseLength];

            lock (_socket.LockI2c)
            {
                _fm.Read(buffer);
            }

            return(buffer);
        }
Ejemplo n.º 17
0
        private Vector3 GetVectorData(Registers reg)
        {
            Span <Byte> retArray = stackalloc byte[6];

            _i2cDevice.WriteByte((byte)reg);
            _i2cDevice.Read(retArray);
            var x = BinaryPrimitives.ReadInt16LittleEndian(retArray);
            var y = BinaryPrimitives.ReadInt16LittleEndian(retArray.Slice(2));
            var z = BinaryPrimitives.ReadInt16LittleEndian(retArray.Slice(4));

            return(new Vector3(x, y, z));
        }
Ejemplo n.º 18
0
        public double ReadTemperatureInCelcius()
        {
            byte[] buffer = new byte[2];

            // Send temperature command, read back two bytes
            _i2cDevice.WriteByte(ReadTemperatureCommand);
            _i2cDevice.Read(buffer.AsSpan());

            // Calculate temperature
            double temp_code   = buffer[0] << 8 | buffer[1];
            double tempCelcius = (((175.72 * temp_code) / 65536) - 46.85);

            return(tempCelcius);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Get double register value from GPAM
        /// </summary>
        /// <param name="register">The register to get</param>
        /// <returns></returns>
        private int GetDoubleRegister(byte register)
        {
            byte[] highByte = new byte[1];
            byte[] lowByte  = new byte[1];

            _gpsController.Write(new byte[] { register });
            _gpsController.Read(highByte);

            _gpsController.Write(new byte[] { register += 1 });
            _gpsController.Read(lowByte);

            int value = (highByte[0] * 10) + lowByte[0];

            return(value);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Read Seneor Data
        /// </summary>
        /// <returns>Mlx90614 Data</returns>
        public Mlx90614Data Read()
        {
            byte[]       readBuf = new byte[2];
            Mlx90614Data data    = new Mlx90614Data();

            sensor.Write(new byte[] { MLX90614_AMBIENT_TEMP });
            sensor.Read(readBuf);
            data.AmbientTemp = BitConverter.ToInt16(readBuf, 0) * 0.02 - 273.15;

            sensor.Write(new byte[] { MLX90614_OBJECT_TEMP });
            sensor.Read(readBuf);
            data.ObjectTemp = BitConverter.ToInt16(readBuf, 0) * 0.02 - 273.15;

            return(data);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Read Time from DS3231
        /// </summary>
        /// <returns>DS3231 Time</returns>
        protected override DateTime ReadTime()
        {
            // Sec, Min, Hour, Day, Date, Month & Century, Year
            Span <byte> rawData = stackalloc byte[7];

            _i2cDevice.WriteByte((byte)Ds3231Register.RTC_SEC_REG_ADDR);
            _i2cDevice.Read(rawData);

            return(new DateTime(1900 + (rawData[5] >> 7) * 100 + NumberHelper.Bcd2Dec(rawData[6]),
                                NumberHelper.Bcd2Dec((byte)(rawData[5] & 0b_0001_1111)),
                                NumberHelper.Bcd2Dec(rawData[4]),
                                NumberHelper.Bcd2Dec(rawData[2]),
                                NumberHelper.Bcd2Dec(rawData[1]),
                                NumberHelper.Bcd2Dec(rawData[0])));
        }
Ejemplo n.º 22
0
        // Read a byte value from the PCA9685 register address specified
        private byte _readRegister(Register register)
        {
            byte[] value = new byte[1];
            byte[] reg   = new byte[1];

            try
            {
                reg[0] = (byte)register;
                _device?.Write(reg);
                _device?.Read(value);
            }
            catch (System.IO.FileNotFoundException)
            {
                Debug.WriteLine("libPCA9685: File Not Found Exception Caught in call to _readRegister(): ");
                Debug.WriteLine(string.Format("libPCA9685: Could not communicate with device at I2C Address 0x{0}. ", Address.ToString("X2")));
                throw;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("libPCA9685: General Exception Caught in call to _readRegister(): ");
                Debug.WriteLine(string.Format("libPCA9685: {0}. ", ex.Message));
                Debug.WriteLine(string.Format("libPCA9685: Failed to read register {0} from I2C device address 0x{1}", register.ToString(), Address.ToString("X2")));
                throw;
            }

            return(value[0]);
        }
Ejemplo n.º 23
0
 private void ReadData()
 {
     lock (_socket.LockI2c)
     {
         _adc.Read(_data);
     }
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Refresh the channel statuses.
        /// </summary>
        private void RefreshChannelStatuses()
        {
            // Pause the auto-refresh to prevent possible collisions.
            var periodRefresh = PeriodRefresh;

            PeriodRefresh = 0;

            Span <byte> buffer = stackalloc byte[2];

            _device.Read(buffer);

            short rawStatus       = BinaryPrimitives.ReadInt16LittleEndian(buffer);
            bool  isStatusChanged = false;

            for (var i = 0; i < CHANNELS_NUMBER; i++)
            {
                bool status = ((1 << i) & rawStatus) > 0;
                if (_statuses[(Channels)i] != status)
                {
                    _statuses[(Channels)i] = status;
                    isStatusChanged        = true;
                }
            }

            if (isStatusChanged)
            {
                OnChannelStatusesChanged();
            }

            // Resume the auto-refresh.
            PeriodRefresh = periodRefresh;
        }
Ejemplo n.º 25
0
        private static string ReadString(I2cDevice arduino)
        {
            var readBuffer = new byte[BufferLength];

            arduino.Read(readBuffer);

            var charCount = 0;

            foreach (var b in readBuffer)
            {
                if (!b.Equals(EmptyByte))
                {
                    charCount++;
                }
            }

            if (charCount == 0)
            {
                return("{}");
            }

            var chars = Encoding.UTF8.GetString(readBuffer, 0, charCount).ToCharArray();

            return(new string(chars));
        }
            public byte[] Read(int length)
            {
                var buffer = new byte[length];

                _i2CDevice.Read(buffer);
                return(buffer);
            }
Ejemplo n.º 27
0
        private uint ReadRegister(byte register, uint byteCount)
        {
            uint result = 0;

            switch (_protocol)
            {
            case ConnectionProtocol.Spi:
                DigitalWrite(_csPin, PinValue.Low);

                // read, bit 7 high
                _spiDevice.Write((byte)(register | 0x80));
                result = (uint)_spiDevice.Read(byteCount);

                DigitalWrite(_csPin, PinValue.High);
                break;

            case ConnectionProtocol.I2c:
                _i2cDevice.Write(register);
                result = (uint)_i2cDevice.Read(byteCount);
                break;

            default:
                throw new NotSupportedException($"Connection protocol '{_protocol}' not supported");
            }

            return(result);
        }
Ejemplo n.º 28
0
        /// <summary>
        ///  Reads a 16 bit value over I2C
        /// </summary>
        /// <param name="register">
        ///  Register to read from
        /// </param>
        /// <returns>
        ///  Value from register
        /// </returns>
        internal ushort Read16BitsFromRegister(byte register)
        {
            if (_communicationProtocol == CommunicationProtocol.I2c)
            {
                Span <byte> bytes = stackalloc byte[2];

                _i2cDevice.WriteByte(register);
                _i2cDevice.Read(bytes);

                return(BinaryPrimitives.ReadUInt16LittleEndian(bytes));
            }
            else
            {
                throw new NotImplementedException();
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        ///     Force the sensor to make a reading and update the relevant properties.
        /// </summary>
        public void Update()
        {
            hih6130.Write(new byte[] { 0 });
            //
            //  Sensor takes 35ms to make a valid reading.
            //
            Thread.Sleep(40);
            var data = new byte[4];

            hih6130.Read(data);
            //
            //  Data format:
            //
            //  Byte 0: S1  S0  H13 H12 H11 H10 H9 H8
            //  Byte 1: H7  H6  H5  H4  H3  H2  H1 H0
            //  Byte 2: T13 T12 T11 T10 T9  T8  T7 T6
            //  Byte 4: T5  T4  T3  T2  T1  T0  XX XX
            //
            if ((data[0] & 0xc0) != 0)
            {
                throw new Exception("Status indicates readings are invalid.");
            }
            var reading = ((data[0] << 8) | data[1]) & 0x3fff;

            Conditions.Humidity    = ((float)reading / 16383) * 100;
            reading                = ((data[2] << 8) | data[3]) >> 2;
            Conditions.Temperature = (((float)reading / 16383) * 165) - 40;
        }
Ejemplo n.º 30
0
        private void TimerCallback(object state)
        {
            try
            {
                byte[] ReadBuf = new byte[14];
                _device.Read(ReadBuf);

                var humid = (int)ReadBuf[0];
                var temp  = (int)ReadBuf[1];
                var soil  = (float)ReadBuf[2];

                if (temp < 30 && humid < 50 && soil < 50)
                {
                    _device.Write(new byte[] { I2cConstants.SET_PINSTATE, 3, I2cConstants.PINSTATE_HIGH });
                }
                else
                {
                    _device.Write(new byte[] { I2cConstants.SET_PINSTATE, 3, I2cConstants.PINSTATE_LOW });
                }

                var task = Dispatcher.RunAsync(
                    Windows.UI.Core.CoreDispatcherPriority.Normal, () => {
                    txtTemperature.Text = temp.ToString();
                    txtHumidity.Text    = humid.ToString();
                    txtSoil.Text        = soil.ToString();
                });
            }
            catch (Exception f)
            {
                Debug.WriteLine(f.Message);
            }
        }