コード例 #1
0
ファイル: I2CSharedBus.cs プロジェクト: valoni/nf-companion
        /// <summary>
        /// Scan for devices on the I2C bus and populate the internal list. By default,
        /// the standard speed (100KHz) and shared bus mode is used
        /// </summary>
        /// <param name="startAddr">The I2C address to start scanning</param>
        /// <param name="endAddr">The I2C address to end scanning</param>
        /// <returns>Total devices found on the bus</returns>
        public int ScanDevicesOnBus(int startAddr, int endAddr)
        {
            if (startAddr < 0 || startAddr > 127 || startAddr > endAddr || endAddr > 127)
            {
                throw new ArgumentException("Invalid I2C address range");
            }

            byte[]            tempBuffer = new byte[8]; //why 8??
            I2cDevice         device     = null;
            I2cTransferStatus xferStatus = I2cTransferStatus.FullTransfer;

            for (int addr = startAddr; addr <= endAddr; addr++)
            {
                device = I2cDevice.FromId(_deviceSelector, new I2cConnectionSettings(addr)
                {
                    BusSpeed = I2cBusSpeed.StandardMode, SharingMode = I2cSharingMode.Shared
                });
                xferStatus = device.ReadPartial(tempBuffer).Status;
                if (xferStatus == I2cTransferStatus.FullTransfer || xferStatus == I2cTransferStatus.PartialTransfer)
                {
                    //we have a device...
                    _i2CDevices.Add(addr, device);
                }
            }
            return(_i2CDevices.Count);
        }
コード例 #2
0
        public Model.Native.I2cTransferResult ReadPartial(byte[] buffer)
        {
            var result = _i2CDevice.ReadPartial(buffer);

            return(new HomeCenter.Model.Native.I2cTransferResult {
                BytesTransferred = result.BytesTransferred, Status = (Model.Native.I2cTransferStatus)result.Status
            });
        }
コード例 #3
0
 public static void Get(ref byte[] buffer)
 {
     if (device == null)
     {
         throw new InvalidOperationException();
     }
     device.ReadPartial(buffer);
 }
コード例 #4
0
        public double GetDistance()
        {
            byte[] result = new byte[1];

            lock (DeviceLock) {
                I2cTransferResult resultShow = I2CDevice.ReadPartial(result);
            }

            return(result[0]);
        }
コード例 #5
0
    public async Task <HIH8120_Reading> TakeReadingAsync()
    {
        var readBuffer           = new byte[4];
        var measureRequestResult = _hih8120.WritePartial(new byte[] { 0 });
        await Task.Delay(1000);

        var readRequest = _hih8120.WritePartial(new byte[] { 1 });
        await Task.Delay(1000);

        var wrPartialResult = _hih8120.ReadPartial(readBuffer);

        var status = (readBuffer[0] >> 6);

        switch (status)
        {
        case 0:
            Debug.WriteLine("Normal Operation");
            break;

        case 1:
            Debug.WriteLine("Stale Data");
            break;

        case 2:
            Debug.WriteLine("Command mode");
            break;

        case 3:
            Debug.WriteLine("Diagnostic");
            break;
        }

        //byte 0    byte 1      byte 2      byte 3
        //sshhhhhh  hhhhhhhh    tttttttt    ttttttXX <-- s=status bits, h=humid bits, X=don't care
        //00111111  11111111 <-- humidity mask 0x3f

        var humidityReading = ((readBuffer[0] & 0x3f) << 8) | readBuffer[1];

        Debug.WriteLine("Humidity Bits: " + Convert.ToString(humidityReading, 2));
        var tempReading = (readBuffer[2] << 6) | (readBuffer[3] >> 2);

        Debug.WriteLine("Temperature Bits: " + Convert.ToString(tempReading, 2));
        HIH8120_Reading reading = new HIH8120_Reading();

        reading.RelativeHumidity = ((humidityReading * 100) / (Math.Pow(2, 14) - 1));
        reading.TemperatureC     = (tempReading / (Math.Pow(2, 14) - 1)) * 165 - 40;
        reading.TemperatureF     = reading.TemperatureC * 1.8 + 32;

        Debug.WriteLine("Relative Humidity: " + reading.RelativeHumidity);
        Debug.WriteLine("Temp C: " + reading.TemperatureC);
        Debug.WriteLine("Temp F: " + reading.TemperatureF);

        return(reading);
    }
コード例 #6
0
        internal bool Read(int byteCount, out byte[] data)
        {
            data = new byte[byteCount];

            if (byteCount == 0)
            {
                data = new byte[1];
                return(false);
            }

            try
            {
                var r = _i2CDevice.ReadPartial(data);

                return(r.BytesTransferred == byteCount);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                return(false);
            }
        }
コード例 #7
0
        public static async Task <byte[]> WriteRead(int slaveAddress, byte[] byteToBeSend)
        {
            byte[] receivedData = new byte[32];


            /* Arduino Nano's I2C SLAVE address */

            try
            {
                // Initialize I2C
                var settings = new I2cConnectionSettings(slaveAddress)
                {
                    BusSpeed = I2cBusSpeed.StandardMode
                };

                if (_aqs == null || _dis == null)
                {
                    _aqs = I2cDevice.GetDeviceSelector("I2C1");
                    _dis = await DeviceInformation.FindAllAsync(_aqs);
                }


                using (I2cDevice device = await I2cDevice.FromIdAsync(_dis[0].Id, settings))
                {
                    var send = device.WritePartial((byteToBeSend));
                    if (send.Status == I2cTransferStatus.SlaveAddressNotAcknowledged)
                    {
                        throw new Exception(String.Format("Urz¹dzenie i2c o adresie {0} nie jest dostêpne!", settings.SlaveAddress));
                    }
                    await Task.Delay(1000);

                    var a = device.ReadPartial(receivedData);
                    if (a.Status != I2cTransferStatus.FullTransfer)
                    {
                        throw new Exception("Nie ostrzymano komunikatu zwrotnego od urz¹dzenia: " + settings.SlaveAddress.ToString());
                    }
                    //  Debug.WriteLine(a.Status);
                }
            }
            catch (Exception ex)
            {
                // SUPPRESS ANY ERROR
                string val = String.Join(",", byteToBeSend);
                LoggerFactory.LogException(ex, "WriteRead", new { val });
            }

            /* Return received data or ZERO on error */
            return(receivedData);
        }
コード例 #8
0
        /// <summary>
        /// Reads all data from the nunchuk
        /// </summary>
        public void Read()
        {
            byte[]            WaitWriteBuffer = { 0 };
            I2cTransferResult result;

            result = Device.WritePartial(WaitWriteBuffer);
            if (result.Status != I2cTransferStatus.FullTransfer)
            {
                throw new ApplicationException("Something went wrong reading the Nunchuk. Did you use proper pull-up resistors?");
            }

            byte[] ReadBuffer = new byte[6];
            result = Device.ReadPartial(ReadBuffer);
            if (result.Status != I2cTransferStatus.FullTransfer)
            {
                throw new ApplicationException("Something went wrong reading the Nunchuk. Did you use proper pull-up resistors?");
            }

            // Parses data according to http://wiibrew.org/wiki/Wiimote/Extension_Controllers/Nunchuck#Data_Format

            // Analog stick
            this.AnalogStickX = ReadBuffer[0];
            this.AnalogStickY = ReadBuffer[1];

            // Accellerometer
            ushort AX = (ushort)(ReadBuffer[2] << 2);
            ushort AY = (ushort)(ReadBuffer[3] << 2);
            ushort AZ = (ushort)(ReadBuffer[4] << 2);

            AZ += (ushort)((ReadBuffer[5] & 0xc0) >> 6); // 0xc0 = 11000000
            AY += (ushort)((ReadBuffer[5] & 0x30) >> 4); // 0x30 = 00110000
            AX += (ushort)((ReadBuffer[5] & 0x0c) >> 2); // 0x0c = 00001100
            this.AcceleroMeterX = AX;
            this.AcceleroMeterY = AY;
            this.AcceleroMeterZ = AZ;

            // Buttons
            ButtonC = (ReadBuffer[5] & 0x02) != 0x02; // 0x02 = 00000010
            ButtonZ = (ReadBuffer[5] & 0x01) != 0x01; // 0x01 = 00000001
        }
コード例 #9
0
ファイル: I2CScanner.cs プロジェクト: valoni/nf-companion
        /// <summary>
        /// Scan bus for devices...Looks in the address range 9....118
        /// Uses standard speed (100KHz) and shared bus mode
        /// </summary>
        /// <param name="deviceSelector">The I2C device selector</param>
        /// <returns>Count of devices found</returns>
        public int ScanForDevices(string deviceSelector)
        {
            if (FoundDevices != null)
            {
                FoundDevices = null;
            }
            FoundDevices = new Hashtable();

            I2cConnectionSettings i2cConfig = new I2cConnectionSettings(0)
            {
                BusSpeed = I2cBusSpeed.StandardMode, SharingMode = I2cSharingMode.Shared
            };

            byte[]            i2cBuffer = new byte[32];
            I2cTransferResult i2cResult;

            for (byte addr = 9; addr <= 118; addr++)
            {
                i2cConfig.SlaveAddress = addr;
                I2cDevice device = I2cDevice.FromId(deviceSelector, i2cConfig);
                i2cResult = device.ReadPartial(i2cBuffer);
                if (i2cResult.Status == I2cTransferStatus.FullTransfer || i2cResult.Status == I2cTransferStatus.PartialTransfer)
                {
                    FoundDevices.Add(addr, device);
                    if (I2CDeviceFound != null)
                    {
                        I2CDeviceFound(addr);
                    }
                }
                else
                {
                    device.Dispose();
                }
            }
            i2cBuffer = null;
            return(FoundDevices.Count);
        }
コード例 #10
0
        private async void InitI2C()
        {
            byte[] i2CWriteBuffer;
            byte[] i2CReadBuffer;
            byte   bitMask;

            // Inicjalizacja I2C - urządzenie z RPI2
            string deviceSelector       = I2cDevice.GetDeviceSelector();
            var    i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector);

            if (i2cDeviceControllers.Count == 0)
            {
                return;
            }

            //Ustawienia dla MCP230008
            var i2cSettings = new I2cConnectionSettings(I2C_ADDR_MCP23008);

            i2cSettings.BusSpeed = I2cBusSpeed.FastMode;
            i2cMCP23008          = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings);

            if (i2cMCP23008 == null)
            {
                return;
            }

            //Ustawienia dla PCF8591
            i2cSettings.SlaveAddress = I2C_ADDR_PCF8591;
            i2cPCF8591 = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings);

            if (i2cPCF8591 == null)
            {
                return;
            }

            //Ustawienia dla Arduino
            i2cSettings.SlaveAddress = I2C_ADDR_ARDUINO;
            i2cArduino = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings);

            if (i2cArduino == null)
            {
                return;
            }


            // Inicjalizacja port Expander
            // Za: https://ms-iot.github.io/content/en-US/win10/samples/I2CPortExpander.htm
            try {
                i2CReadBuffer = new byte[1];
                i2cMCP23008.WriteRead(new byte[] { MCP23008_IODIR }, i2CReadBuffer);
                iodirRegister = i2CReadBuffer[0];
                i2cMCP23008.WriteRead(new byte[] { MCP23008_GPIO }, i2CReadBuffer);
                gpioRegister = i2CReadBuffer[0];
                i2cMCP23008.WriteRead(new byte[] { MCP23008_OLAT }, i2CReadBuffer);
                olatRegister = i2CReadBuffer[0];

                // Konfiguracja PIN-a z laserem na 1; reszta bez zmian
                olatRegister  |= LED_GPIO_PIN;
                i2CWriteBuffer = new byte[] { MCP23008_OLAT, olatRegister };
                i2cMCP23008.Write(i2CWriteBuffer);

                bitMask        = (byte)(0xFF ^ LED_GPIO_PIN); // Tylko nasz PIN będzie miał maskę 0 - reszta będzie równa 1, co spowoduje że nie zmienią wartości
                iodirRegister &= bitMask;
                i2CWriteBuffer = new byte[] { MCP23008_IODIR, iodirRegister };
                i2cMCP23008.Write(i2CWriteBuffer);
            } catch (Exception e) {
                return;
            }


            //Komunikacja z Arduino
            byte[] wbuffer = new byte[] { 1, 2, 3, 4, 5, 6 };
            byte[] rbuffer = new byte[2];
            //Wysłanie liczb do dodania
            i2cArduino.Write(wbuffer);
            await Task.Delay(1000);

            //Odczytanie wyniku
            var result = i2cArduino.ReadPartial(rbuffer);
            //Wyświetlenie
            int sum = (((int)rbuffer[1]) << 8) + (int)rbuffer[0];

            Debug.WriteLine($"Suma:{sum}");

            //Błyskanie laserem co sekundę
            m_timer          = new DispatcherTimer();
            m_timer.Interval = TimeSpan.FromMilliseconds(1000);
            m_timer.Tick    += timer_Tick;
            m_timer.Start();

            //Zapis "trójkąta" do PCF8591 (w pętli, nieskończonej)
            await WritePCF8591();
        }