Example #1
0
        private static void UpdateBlinkM(I2CDevice.Configuration blinkM, I2CDevice i2cDevice, NetworkCredential credential)
        {
            string deviceAddressText = blinkM.Address.ToString();
            string defaultHsbText    = "38,255,42";
            string hsbText           = ConfigUtil.GetOrInitConfigValue(NapkinServerUri, DeviceId, "blinkM_" + deviceAddressText + "_hsb", defaultHsbText, credential);

            string[] hsbArray = hsbText.Split(',');
            if ((hsbArray == null) || (hsbArray.Length != 3))
            {
                Debug.Print("Badly formed HSB data: " + hsbText);
                hsbText = defaultHsbText;
            }

            try
            {
                byte hue        = (byte)int.Parse(hsbArray[0]);
                byte saturation = (byte)int.Parse(hsbArray[1]);
                byte brightness = (byte)int.Parse(hsbArray[2]);
                BlinkMCommand.FadeToHSB.Execute(i2cDevice, blinkM, hue, saturation, brightness);
            }
            catch (Exception)
            {
                Debug.Print("Error parsing HSB data: " + hsbText);
            }
        }
Example #2
0
        /// <summary>
        ///     Read array of bytes at specific register from the I2C slave device.
        /// </summary>
        /// <param name="config">I2C slave device configuration.</param>
        /// <param name="register">The register to read bytes from.</param>
        /// <param name="readBuffer">The array of bytes that will contain the data read from the device.</param>
        /// <param name="transactionTimeout">The amount of time the system will wait before resuming execution of the transaction.</param>
        public void ReadRegister(I2CDevice.Configuration config, byte register, byte[] readBuffer)
        {
            byte[] writeBuffer = { register };

            // create an i2c write transaction to be sent to the device.
            I2CDevice.I2CTransaction[] transactions = new I2CDevice.I2CTransaction[]
            {
                I2CDevice.CreateWriteTransaction(writeBuffer),
                I2CDevice.CreateReadTransaction(readBuffer)
            };

            // the i2c data is sent here to the device.
            int transferred;

            lock (this.m_i2c)
            {
                this.m_i2c.Config = config;
                transferred       = this.m_i2c.Execute(transactions, TransactionTimeout);
            }

            // make sure the data was sent.
            if (transferred != writeBuffer.Length + readBuffer.Length)
            {
                throw new IOException("Read Failed: " + transferred + "!=" + (writeBuffer.Length + readBuffer.Length));
            }
        }
Example #3
0
 public void Read(I2CDevice.Configuration config, byte[] buffer, int transactionTimeout)
 {
     _slaveDevice.Config = config;
     I2CDevice.I2CTransaction[] i2CTransactions = new I2CDevice.I2CTransaction[] { I2CDevice.CreateReadTransaction(buffer) };
     lock (_slaveDevice)
         _slaveDevice.Execute(i2CTransactions, transactionTimeout);
 }
Example #4
0
 public static void SetBits(this I2CDevice device, I2CDevice.Configuration config, int timeout, byte register, byte bitstart, byte length, byte value)
 {
     if (!device.TrySetBits(config, timeout, register, bitstart, length, value))
     {
         throw new Exception();
     }
 }
Example #5
0
        public LSM303DLM_Accelerometer()
        {
            _config = new I2CDevice.Configuration(0x18, 400);

            // 0x27 = 00100111  Normal mode
            Write(Register.CTRL_REG1_A, 0x27);
        }
Example #6
0
 public static void SetRegister(this I2CDevice device, I2CDevice.Configuration config, int timeout, byte register, params byte[] value)
 {
     if (!TrySetRegister(device, config, timeout, register, value))
     {
         throw new Exception();
     }
 }
Example #7
0
 public static void SetBit(this I2CDevice device, I2CDevice.Configuration config, int timeout, byte register, byte bitNum, bool value)
 {
     if (!device.TrySetBit(config, timeout, register, bitNum, value))
     {
         throw new Exception();
     }
 }
Example #8
0
        public byte ReadRegister(I2CDevice.Configuration config, byte register)
        {
            var buf = new byte[1];

            ReadRegister(config, register, buf);
            return(buf[0]);
        }
Example #9
0
        public static void Main()
        {
            //our 10 bit address
            const ushort address10Bit = 0x1001; //binary 1000000001 = 129
            const byte   addressMask  = 0x78;   //reserved address mask 011110XX for 10 bit addressing

            //first MSB part of address
            ushort address1 = addressMask | (address10Bit >> 8); //is 7A and contains the two MSB of the 10 bit address

            I2CDevice.Configuration config = new I2CDevice.Configuration(address1, 100);
            I2CDevice device = new I2CDevice(config);

            //second LSB part of address
            byte address2 = (byte)(address10Bit & 0xFF); //the other 8 bits (LSB)

            byte[] address2OutBuffer = new byte[] { address2 };
            I2CDevice.I2CWriteTransaction addressWriteTransaction = device.CreateWriteTransaction(address2OutBuffer);

            //prepare buffer to write data
            byte[] outBuffer = new byte[] { 0xAA };
            I2CDevice.I2CWriteTransaction writeTransaction = device.CreateWriteTransaction(outBuffer);

            //prepare buffer to read data
            byte[] inBuffer = new byte[4];
            I2CDevice.I2CReadTransaction readTransaction = device.CreateReadTransaction(inBuffer);

            //execute transactions
            I2CDevice.I2CTransaction[] transactions =
                new I2CDevice.I2CTransaction[] { addressWriteTransaction, writeTransaction, readTransaction };
            device.Execute(transactions, 100);
        }
Example #10
0
 public EEPROM_I2C()
 {
     I2C_Address   = EEPROM_I2C_1;
     I2C_ClockRate = 100;
     I2CDevice.Configuration config = new I2CDevice.Configuration(I2C_Address, I2C_ClockRate);
     I2C_device = new I2CDevice(config);
 }
Example #11
0
        public void SetupDevice()
        {
            relayPort = new OutputPort((Cpu.Pin) 21, false);
            relayPort.Write(true);
            var i2cConfig = new I2CDevice.Configuration(0x51, 400);

            i2cSensor = new I2CDevice(i2cConfig);
            var xwsaction = I2CDevice.CreateWriteTransaction(new byte[] { 0x01 });
            var xrsaction = I2CDevice.CreateReadTransaction(new byte[8]);

            i2cSensor.Execute(new I2CDevice.I2CTransaction[] { xwsaction, xrsaction }, 100);

            var read = xrsaction.Buffer;

            var temperature = BitConverter.ToDouble(read, 0);

            var accelOrder = I2CDevice.CreateWriteTransaction(new byte[] { 0x02 });
            var accelRead  = I2CDevice.CreateReadTransaction(new byte[24]);

            i2cSensor.Execute(new I2CDevice.I2CTransaction[] { accelOrder, accelRead }, 100);

            var accelX = BitConverter.ToDouble(accelRead.Buffer, 0);
            var accelY = BitConverter.ToDouble(accelRead.Buffer, 8);
            var accelZ = BitConverter.ToDouble(accelRead.Buffer, 16);
        }
Example #12
0
 public EEPROM_I2C(byte subordinate_address, byte subordinate_clockrate)
 {
     I2C_Address   = subordinate_address;
     I2C_ClockRate = subordinate_clockrate;
     I2CDevice.Configuration config = new I2CDevice.Configuration(I2C_Address, I2C_ClockRate);
     I2C_device = new I2CDevice(config);
 }
Example #13
0
        public bool Write(I2CDevice.Configuration config, byte[] writeBuffer, int timeoutMilliseconds)
        {
            DeviceBuffers device = GetDevice(config.Address);

            device.Output.Append(writeBuffer);
            return(true);
        }
Example #14
0
        public bool Read(I2CDevice.Configuration config, byte[] readBuffer, int timeoutMilliseconds)
        {
            DeviceBuffers device = GetDevice(config.Address);

            device.Input.ReadInto(readBuffer, 0, readBuffer.Length);
            return(true);
        }
Example #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AltitudeClick"/> class.
        /// </summary>
        /// <param name="socket">The <see cref="Hardware.Socket"/> that the AltitudeClick is inserted into.</param>
        /// <param name="clockRateI2">The <see cref="MBN.Enums.ClockRatesI2C"/> for I2C communication.</param>
        /// <param name="i2CTimeout">The universal I2C Transaction Timeout value to wait for I2C transactions to complete.</param>
        /// <exception cref="DeviceInitialisationException">A DeviceInitialisationException will be thrown if the AltitudeClick does not complete its initialization properly.</exception>
        /// <exception cref="PinInUseException">A PinInUseException will be thrown if the I2C pins are being used for non-I2C function.</exception>
        public AltitudeClick(Hardware.Socket socket, ClockRatesI2C clockRateI2, int i2CTimeout = 1000)
        {
            try
            {
                // Checks if needed I²C pins are available
                Hardware.CheckPinsI2C(socket);

                // Create the driver's I²C configuration
                _i2CConfig = new I2CDevice.Configuration(I2CAddress, (int)clockRateI2);

                _i2CTimeout = i2CTimeout;

                // Check if it's the first time an I²C device is created
                if (Hardware.I2CBus == null)
                {
                    Hardware.I2CBus = new I2CDevice(_i2CConfig);
                }

                if (!Init())
                {
                    throw new DeviceInitialisationException("The AltitudeClick has failed to initialize");
                }
            }
            // Catch only the PinInUse exception, so that program will halt on other exceptions and send it directly to caller.
            catch (PinInUseException ex)
            {
                throw new PinInUseException(ex.Message);
            }
        }
Example #16
0
 public void WriteRegister(I2CDevice.Configuration config, byte register, byte[] writeBuffer, int transactionTimeout)
 {
     byte[] registerBuffer = { register };
     //Write(config,new byte[] {0x3C, 0x00, 0x70},transactionTimeout);
     Write(config, registerBuffer, transactionTimeout);
     Write(config, writeBuffer, transactionTimeout);
 }
Example #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JoystickClick"/> class.
        /// </summary>
        /// <param name="socket">The socket on which the JoystickClick module is plugged on MikroBus.Net board</param>
        /// <param name="address">The address of the module.</param>
        /// <param name="clockRateKHz">The clock rate of the I²C device. <seealso cref="ClockRatesI2C"/></param>
        public JoystickClick(Hardware.Socket socket, Byte address = 0x40, ClockRatesI2C clockRateKHz = ClockRatesI2C.Clock100KHz)
        {
            try
            {
                // Checks if needed I²C pins are available.
                Hardware.CheckPinsI2C(socket, socket.Int, socket.Rst, socket.Cs);

                // Create the driver's I²C configuration
                _config = new I2CDevice.Configuration(address, (Int32)clockRateKHz);

                _reset = new OutputPort(socket.Rst, true);
                Reset(ResetModes.Hard);

                Sensitivity = 0x3F; // Max sensitivity
                Scaling     = 0x09; // 100% scaling

                Button = new InterruptPort(socket.Cs, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
                Button.EnableInterrupt();

                PowerMode     = PowerModes.On;  // Interrupt mode
                InterruptLine = new InterruptPort(socket.Int, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLow);
                TimeBase      = 3;
                ReadRegister(0x11);     // Don't care about the first data available
                InterruptLine.EnableInterrupt();
            }
            // Catch only the PinInUse exception, so that program will halt on other exceptions
            // Send it directly to the caller
            catch (PinInUseException) { throw new PinInUseException(); }
        }
Example #18
0
 public void WriteRegister(I2CDevice.Configuration config, byte[] everyThing, int transactionTimeout)
 {
     //Write(config, new byte[] { 0x3C, 0x00, 0x70 }, transactionTimeout);
     //Write(config, registerBuffer, transactionTimeout);
     Write(config, everyThing, transactionTimeout);
     //Write(config, valueBuffer, transactionTimeout);
 }
Example #19
0
        public TSL2561(byte I2CAddress, int ClockinKHz)
        {
            I2CConfig = new I2CDevice.Configuration(I2CAddress, ClockinKHz);
            I2C       = new I2CDevice(I2CConfig);

            // read the ID register.
            var Actions = new I2CDevice.I2CTransaction[2];

            byte[] rx = new byte[1];
            Actions[0] = I2CDevice.CreateWriteTransaction(new byte[] { 0x0a });
            Actions[1] = I2CDevice.CreateReadTransaction(rx);
            if (I2C.Execute(Actions, 1000) == 0)
            {
                Debug.Print("Read ID Register failed");
                // exit or something
            }
            else
            {
                Debug.Print("ID value: " + rx[0].ToString());
            }
            // 4 msb must be 0001 for a TSL2561
            if ((rx[0] & 0xf0) != 0xa0)
            {
                // exit or something
            }

            setGain(0x10);
            Thread.Sleep(5); // Mandatory after each Write transaction !!!
        }
Example #20
0
 public void ReadRegister(I2CDevice.Configuration config, byte register, byte[] readBuffer, int transactionTimeout)
 {
     byte[] registerBuffer = { register };
     Write(config, new byte[] { 0x3D }, transactionTimeout);
     Write(config, registerBuffer, transactionTimeout);
     Read(config, readBuffer, transactionTimeout);
 }
Example #21
0
        public static void Scan(II2CBus bus)
        {
            if (bus == null)
            {
                throw new ArgumentNullException("bus");
            }
            int        count        = 0;
            const int  clockRateKhz = 100;
            const int  timeout      = 100;
            const byte startAddress = 0x08;
            const byte endAddress   = 127;

            Debug.Print("Scanning I2C Bus for devices starting at: " + HexString.GetString(startAddress) + " ... ");
            for (byte address = startAddress; address < endAddress; address++)
            {
                var configuration = new I2CDevice.Configuration(address, clockRateKhz);
                var buffer        = new byte[] {
                    0
                };
                bool canRead  = bus.Read(configuration, buffer, timeout);
                bool canWrite = bus.Write(configuration, buffer, timeout);
                if (canRead || canWrite)
                {
                    count++;
                    Debug.Print("Address: 0x" + HexString.GetString(address) + ", Read => " + canRead + ", Write => " + canWrite);
                }
            }
            Debug.Print("Scanning ended at: " + HexString.GetString(endAddress));
            Debug.Print("Scanning found " + count + " devices.");
        }
Example #22
0
        public L3G4200D_Gyro()
        {
            _config = new I2CDevice.Configuration(0x69, 400); //68

            // 0x1F = 00011111 Normal mode
            Write(Register.CTRL_REG1, 0x1F);
        }
Example #23
0
        /// <summary>
        /// Generic write operation to I2C slave device.
        /// </summary>
        /// <param name="config">I2C slave device configuration.</param>
        /// <param name="writeBuffer">The array of bytes that will be sent to the device.</param>
        /// <param name="transactionTimeout">The amount of time the system will wait before resuming execution of the transaction.</param>
        public int Write(I2CDevice.Configuration config, byte[] writeBuffer, int transactionTimeout)
        {
            lock (_slaveDevice)
            {
                // Set i2c device configuration.
                _slaveDevice.Config = config;

                // create an i2c write transaction to be sent to the device.
                I2CDevice.I2CTransaction[] writeXAction = new I2CDevice.I2CTransaction[]
                {
                    I2CDevice.CreateWriteTransaction(writeBuffer)
                };

                // the i2c data is sent here to the device.
                int transferred = 0;
                do
                {
                    transferred = _slaveDevice.Execute(writeXAction, transactionTimeout);

                    if (transferred == 0)
                    {
                        throw new Exception("Could not write to device.");
                    }
                }while (transferred == 0);

                // make sure the data was sent.
                if (transferred != writeBuffer.Length)
                {
                    throw new Exception("Could not write to device.");
                }

                return(transferred);
            }
        }
Example #24
0
        /// <summary>
        /// Generic read operation from I2C slave device.
        /// </summary>
        /// <param name="config">I2C slave device configuration.</param>
        /// <param name="readBuffer">The array of bytes that will contain the data read from the device.</param>
        /// <param name="transactionTimeout">The amount of time the system will wait before resuming execution of the transaction.</param>
        public int Read(I2CDevice.Configuration config, byte[] readBuffer, int transactionTimeout)
        {
            lock (_slaveDevice)
            {
                // Set i2c device configuration.
                _slaveDevice.Config = config;

                // create an i2c read transaction to be sent to the device.
                I2CDevice.I2CTransaction[] readXAction = new I2CDevice.I2CTransaction[]
                {
                    I2CDevice.CreateReadTransaction(readBuffer)
                };

                // the i2c data is received here from the device.
                int transferred = _slaveDevice.Execute(readXAction, transactionTimeout);

                // make sure the data was received.
                if (transferred != readBuffer.Length)
                {
                    throw new Exception("Could not read from device.");
                }

                return(transferred);
            }
        }
Example #25
0
 public NativeI2CBus(Socket socket, ushort address, int clockRateKhz, Module module)
 {
     if (_device == null)
     {
         _device = new I2CDevice(new I2CDevice.Configuration(0, 50));
     }
     this._configuration = new I2CDevice.Configuration(address, clockRateKhz);
 }
Example #26
0
        public WiiChuck(bool disableEncryption)
        {
            _disableEncryption = disableEncryption;

            var config = new I2CDevice.Configuration(DeviceAddress, ClockRateKHz);

            _device = new I2CDevice(config);
        }
Example #27
0
        /// <summary>
        /// Executes the specified I²C transaction.
        /// </summary>
        /// <param name="I2CDev">The underlying I²C object. Omit this parameter when you call that method</param>
        /// <param name="pConfig">The I²C configuration used for this transfer.</param>
        /// <param name="xActions">Array containing a list of I²C transactions.</param>
        /// <param name="timeout">Timeout before telling that there was an error executing the transaction(s).</param>
// ReSharper disable once InconsistentNaming
        public static Int32 Execute(this I2CDevice I2CDev, I2CDevice.Configuration pConfig, I2CDevice.I2CTransaction[] xActions, int timeout)
        {
            lock (Hardware.I2CLock)
            {
                I2CDev.Config = pConfig;
                return(I2CDev.Execute(xActions, timeout));
            }
        }
Example #28
0
        /// <summary>
        /// Constructor
        /// </summary>
        public DS1307()
        {
            I2CDevice.Configuration i2cConfig = new I2CDevice.Configuration(ADDRESS, CLOCK_RATE_KHZ);
            this.i2c = new I2CDevice(i2cConfig);

            this.ramAddress = new byte[RAM_ADDRESS_SIZE];
            this.ramData    = new byte[RAM_DATA_SIZE];
        }
 public static void SetConfig(I2CDevice.Configuration config)
 {
     currentConfig = config;
     if (theBus == null) // good time to initialize the bus
     {
         theBus = new I2CDevice(currentConfig);
     }
 }
 public static void SetConfig(ushort address, int clockRate)
 {
     currentConfig = new I2CDevice.Configuration(address, clockRate); //ClockRate KiloHertz
     if (theBus == null)                                              // good time to initialize the bus
     {
         theBus = new I2CDevice(currentConfig);
     }
 }