Пример #1
0
        public async Task <bool> OpenConnection(string i2cMasterId)
        {
            //Establish I2C connection
            __connection = await I2cDevice.FromIdAsync(i2cMasterId, new I2cConnectionSettings(this.__i2cAddress));

            // soft reset
            I2cTransferResult result = __connection.WritePartial(new byte[] { Registers.MPR121_SOFTRESET, 0x63 });

            if (result.Status == I2cTransferStatus.SlaveAddressNotAcknowledged)
            {
                throw new Exception(string.Format("MPR121 at address {0} not responding.", this.__i2cAddress));
            }

            await Task.Delay(1);

            writeRegister(Registers.MPR121_ECR, 0x0);

            byte c = readRegister8(Registers.MPR121_CONFIG2);

            if (c != 0x24)
            {
                return(false);
            }


            SetThresholds(12, 6);

            //Section A Registers - Ref: AN3944, MPR121 Quick Start Guide
            //This group of setting controls the filtering of the system when the data is greater than the baseline.
            //Settings from Adafruit Libary.. Most probably callibrated for the Adafruit's MPR121 breakout board.
            writeRegister(Registers.MPR121_MHDR, 0x01);
            writeRegister(Registers.MPR121_NHDR, 0x01);
            writeRegister(Registers.MPR121_NCLR, 0x0E);
            writeRegister(Registers.MPR121_FDLR, 0x00);

            //Section B Registers - Ref: AN3944, MPR121 Quick Start Guide
            writeRegister(Registers.MPR121_MHDF, 0x01);
            writeRegister(Registers.MPR121_NHDF, 0x05);
            writeRegister(Registers.MPR121_NCLF, 0x01);
            writeRegister(Registers.MPR121_FDLF, 0x00);

            writeRegister(Registers.MPR121_NHDT, 0x00);
            writeRegister(Registers.MPR121_NCLT, 0x00);
            writeRegister(Registers.MPR121_FDLT, 0x00);

            writeRegister(Registers.MPR121_DEBOUNCE, 0);
            writeRegister(Registers.MPR121_CONFIG1, 0x10); // default, 16uA charge current
            writeRegister(Registers.MPR121_CONFIG2, 0x20); // 0.5uS encoding, 1ms period

            writeRegister(Registers.MPR121_ECR, 0x8F);     // start with first 5 bits of baseline tracking

            InitMPR121TouchInterrupt();

            return(true);
        }
 private bool WriteI2cPacket(byte[] data)
 {
     lock (DeviceLock) {
         I2cTransferResult resultShow = I2CDevice.WritePartial(data);
         if (resultShow.BytesTransferred == 0)
         {
             return(false);
         }
         return(true);
     }
 }
Пример #3
0
        /// <summary>
        /// Read data from given address as bytes
        /// </summary>
        /// <param name="addr">The address to begin reading from</param>
        /// <param name="len">How many data elements to read</param>
        /// <returns>byte[] if read successful, else null</returns>
        public override byte[] ReadBytes(uint addr, uint len)
        {
            CheckRange(addr, len);

            byte[]            eepromData  = new byte[len];
            byte[]            addrAsBytes = AddressAsBytes(addr, _addrSizeInBytes, _addrModeLE);
            I2cTransferResult xferResult  = _i2cDevice.WriteReadPartial(addrAsBytes, eepromData);

            if (xferResult.Status != I2cTransferStatus.FullTransfer && xferResult.Status != I2cTransferStatus.PartialTransfer)
            {
                eepromData = null;
            }
            return(eepromData);
        }
        private byte ReadRegister(byte reg_addr)
        {
            byte[] RegAddrBuf = { reg_addr };
            byte[] ReadBuf    = new byte[1];

            I2cTransferResult result = Adaptor.WriteReadPartial(RegAddrBuf, ReadBuf);

            if (result.Status == I2cTransferStatus.FullTransfer)
            {
                return(ReadBuf[0]);
            }
            else
            {
                return(0);
            }
        }
Пример #5
0
    public int WriteReadPartial(byte[] dataOut, int numberOfBytesToRead)
    {
        byte[]            dataIn  = new byte[numberOfBytesToRead];
        int               success = 0;
        I2cTransferResult result  = new I2cTransferResult();

        try
        {
            result = device.WriteReadPartial(dataOut, dataIn);
        }
        catch (Exception e)
        {
            success = e.HResult;
        }

        return(success);
    }
Пример #6
0
        //protected override void RegisterNativeServices()
        //{
        //    _container.RegisterSingleton<IGpioController, RaspberryGpioController>();
        //    _container.RegisterSingleton<II2cBus, RaspberryI2cBus>();
        //    _container.RegisterSingleton<ISerialDevice, RaspberrySerialDevice>();
        //    _container.RegisterSingleton<ISoundPlayer, RaspberrySoundPlayer>();
        //    _container.RegisterSingleton<IStorage, RaspberryStorage>();
        //}

        protected override void RegisterNativeServices()
        {
            var transferResult = new I2cTransferResult()
            {
                Status = I2cTransferStatus.FullTransfer, BytesTransferred = 0
            };
            var i2cBus          = Mock.Of <II2cBus>();
            var i2cNativeDevice = Mock.Of <II2cDevice>();

            Mock.Get(i2cBus).Setup(s => s.CreateDevice(It.IsAny <string>(), It.IsAny <int>())).Returns(i2cNativeDevice);
            Mock.Get(i2cNativeDevice).Setup(s => s.WritePartial(It.IsAny <byte[]>())).Returns(transferResult);
            Mock.Get(i2cNativeDevice).Setup(s => s.ReadPartial(It.IsAny <byte[]>())).Returns(transferResult);

            _container.RegisterInstance(i2cBus);

            _container.RegisterInstance(Mock.Of <IGpioController>());
            _container.RegisterInstance(Mock.Of <ISerialDevice>());
            _container.RegisterInstance(Mock.Of <ISoundPlayer>());
        }
Пример #7
0
        private void Timer_Tick(ThreadPoolTimer timer)
        {
            byte [] emptyBuffer = new byte[0];
            byte[]  byteBuffer  = new byte[1];
            byte[]  wordBuffer  = new byte[2];

            sensor.Write(byteBuffer);
            sensor.Read(byteBuffer);
            WriteLine($"Got first byte of {byteBuffer[0]}");

            byteBuffer[0] = 0x81;
            I2cTransferResult result = sensor.WriteReadPartial(byteBuffer, wordBuffer);

            WriteLine($"Result is {result.Status} Bytes transferred is {result.BytesTransferred} temp is 0x{wordBuffer[1]:X2}{wordBuffer[0]:X2}");


            byteBuffer[0] = 0x82;
            result        = sensor.WriteReadPartial(byteBuffer, wordBuffer);
            WriteLine($"Result is {result.Status} Bytes transferred is {result.BytesTransferred} light is 0x{wordBuffer[1]:X2}{wordBuffer[0]:X2}");
        }
Пример #8
0
        private void WaitReady()
        {
            int count = 0;

            // Wait for Acknowledge from eeprom by sending 0 length write until acknowledged or other error
            // End anyway if slave not acknowledging, normaly slave starts to Ack after 4 or 5 count which means
            // previous write is complete
            while (count < 20)
            {
                I2cTransferResult res = EEprom.WritePartial(null);


                if (res.Status != I2cTransferStatus.SlaveAddressNotAcknowledged)
                {
                    break;
                }
                {
                    count++;

                    Thread.Sleep(1);  // Give time to other threads
                }
            }
        }
Пример #9
0
        private async void InitI2CBMP()
        {
            BMPInitVals.oversamp_setting = 0;
            try {
                string aqs = I2cDevice.GetDeviceSelector();                     /* Get a selector string that will return all I2C controllers on the system */
                var    dis = await DeviceInformation.FindAllAsync(aqs);         /* Find the I2C bus controller device with our selector string           */

                if (dis.Count == 0)
                {
                    Text_Status.Text = "No I2C controllers were found on the system";
                    return;
                }


                var settings = new I2cConnectionSettings(BMP_I2C_ADDR);
                settings.BusSpeed = I2cBusSpeed.StandardMode;
                I2CBmp            = await I2cDevice.FromIdAsync(dis[0].Id, settings); /* Create an I2cDevice with our selected bus controller and I2C settings */

                if (I2CBmp == null)
                {
                    Text_Status.Text = string.Format(
                        "Slave address {0} on I2C Controller {1} is currently in use by " +
                        "another application. Please ensure that no other applications are using I2C.",
                        settings.SlaveAddress,
                        dis[0].Id);
                    return;
                }

                settings          = new I2cConnectionSettings(ADS1x15_I2C_ADDR);
                settings.BusSpeed = I2cBusSpeed.StandardMode;
                I2CAdc            = await I2cDevice.FromIdAsync(dis[0].Id, settings); /* Create an I2cDevice with our selected bus controller and I2C settings */

                if (I2CAdc == null)
                {
                    Text_Status.Text = string.Format(
                        "Slave address {0} on I2C Controller {1} is currently in use by " +
                        "another application. Please ensure that no other applications are using I2C.",
                        settings.SlaveAddress,
                        dis[0].Id);
                    return;
                }
            }
            catch (Exception ex)
            {
                Text_Status.Text = "Failed to create the device: " + ex.Message;
                return;
            }

            /*
             * Initialize the accelerometer:
             *
             * For this device, we create 2-byte write buffers:
             * The first byte is the register address we want to write to.
             * The second byte is the contents that we want to write to the register.
             */


            try
            {   // Lets try and read the EEprom Callibration data out.
                I2cTransferResult tResult = I2CBmp.WriteReadPartial(CmdBuf_ChipID, ReadByte);
                if (tResult.Status == I2cTransferStatus.FullTransfer && ReadByte[0] == 0x55)
                {   // The I2C transfer succeded and we recieved the correct Chip ID from the expected Register Address
                    Text_Status.Text    = "Success: Chip ID matched BMP180.";
                    BMPInitVals.chip_id = ReadByte[0];
                }
                else
                {
                    //Text_Status.Text = "Failed: Chip ID dosn't match BMP180.";
                    return;
                }

                tResult = I2CBmp.WriteReadPartial(CmdBuf_PromData, ReadEEPromBuff);
                if (tResult.Status == I2cTransferStatus.FullTransfer)
                {
                    // The I2C transfer succeded and we recieved the correct Chip ID from the expected Register Address
                    Text_Status.Text = "Success: Read Prom Data";
                }
                else
                {
                    Text_Status.Text = "Failed: Didnt read Prom Data";
                    return;
                }

                //
                // Fill in the Param Structure from the Prom Data.
                //
                BMPInitVals.calibParam.ac1 = (short)((ReadEEPromBuff[0] << 8) + ReadEEPromBuff[1]);
                BMPInitVals.calibParam.ac2 = (short)((ReadEEPromBuff[2] << 8) + ReadEEPromBuff[3]);
                BMPInitVals.calibParam.ac3 = (short)((ReadEEPromBuff[4] << 8) + ReadEEPromBuff[5]);
                BMPInitVals.calibParam.ac4 = (ushort)((ReadEEPromBuff[6] << 8) + ReadEEPromBuff[7]);
                BMPInitVals.calibParam.ac5 = (ushort)((ReadEEPromBuff[8] << 8) + ReadEEPromBuff[9]);
                BMPInitVals.calibParam.ac6 = (ushort)((ReadEEPromBuff[10] << 8) + ReadEEPromBuff[11]);
                BMPInitVals.calibParam.b1  = (short)((ReadEEPromBuff[12] << 8) + ReadEEPromBuff[13]);
                BMPInitVals.calibParam.b2  = (short)((ReadEEPromBuff[14] << 8) + ReadEEPromBuff[15]);
                BMPInitVals.calibParam.mb  = (short)((ReadEEPromBuff[16] << 8) + ReadEEPromBuff[17]);
                BMPInitVals.calibParam.mc  = (short)((ReadEEPromBuff[18] << 8) + ReadEEPromBuff[19]);
                BMPInitVals.calibParam.md  = (short)((ReadEEPromBuff[20] << 8) + ReadEEPromBuff[21]);


                periodicTimer = new Timer(this.TimerCallback, null, 1000, 2000);
            }
            /* If the write fails display the error and stop running */
            catch (Exception ex)
            {
                Text_Status.Text = "Failed to communicate with device: " + ex.Message;
                return;
            }
        }