Ejemplo n.º 1
0
        /**************************************************************************/

        /*!
         *  @brief  Instantiates a new ADS1015 class w/appropriate properties
         */
        /**************************************************************************/

        public Adafruit_ADS1015(I2CBus i2c)
            : base(i2c, ADS1015_ADDRESS)
        {
            this.m_conversionDelay = ADS1015_CONVERSIONDELAY;
            this.m_bitShift        = 4;
            this.m_gain            = adsGain_t.GAIN_TWOTHIRDS; /* +/- 6.144V range (limited to VDD +0.3V max!) */
        }
Ejemplo n.º 2
0
        public bool GetFailsafe(Logger_class log = null)
        {
            if (!_CheckInit())
            {
                throw new NullReferenceException("ThunderBorg not initiated.");
            }

            bool tempReturn = false;

            using (var bus = I2CBus.Open("/dev/i2c-" + this._bus.ToString()))
            {
                bus.WriteBytes(_TBorgAddress, new byte[] { COMMAND_GET_FAILSAFE });
                byte[] response = bus.ReadBytes(_TBorgAddress, I2C_MAX_LEN);
                if (log != null)
                {
                    log.WriteLog("Got response on failsafe: " + _BytesToString(response));
                }

                if (response[0] == COMMAND_GET_FAILSAFE)
                {
                    tempReturn = Convert.ToBoolean(response[1]);
                }
            }

            return(tempReturn);
        }
Ejemplo n.º 3
0
 public AMG8833()
 {
     i2cPath = "/dev/i2c-1";
     _i2cBus = I2CBus.Open(i2cPath);
     _i2cBus.set_slave_address(0x69);
     init();
 }
        private void scanBusAddresses()
        {
            Debug.Print(MethodNames.SCAN_BUS_ADDRESSES);
            if (loadAddressWhitelist())
            {
                Debug.Print(LogMessages.LOADED_WHITELIST);
                return;
            }
            ushort speed   = 100;
            ushort timeout = 200;

            for (byte i = SLAVE_SCAN_LOW; i < SLAVE_SCAN_HIGH; i++)
            {
                I2CBus i2C = new I2CBus(i, speed, timeout);
                try
                {
                    i2C.WriteByte(0);
                    var slaveAddressOnly = new Slave {
                        address = i, clock_stretch = 40000, name = "not_assigned", role = Role.UNDEFINED
                    };
                    _assimSlaves.Add(slaveAddressOnly);
                }
                catch { }
            }
            if (_assimSlaves.Count == 0)
            {
                //Debug.Print("No I2C devices found.");
            }
            else
            {
                //Debug.Print(_numberOfDevices.ToString() + " I2C devices found.");
            }
        }
Ejemplo n.º 5
0
 public Adafruit_ADS1115(I2CBus i2c, byte address)
     : base(i2c, address)
 {
     this.m_conversionDelay = ADS1115_CONVERSIONDELAY;
     this.m_bitShift        = 0;
     this.m_gain            = adsGain_t.GAIN_TWOTHIRDS; /* +/- 6.144V range (limited to VDD +0.3V max!) */
 }
Ejemplo n.º 6
0
        public static void Main(string[] args)
        {
            using (var i2cBus = new I2CBus("/dev/i2c-1"))
            {
                var i2cDevice = new I2CDevice(i2cBus, Display.DefaultI2CAddress);

                display = new SSD1306.Display(i2cDevice, 128, 32);
                display.Init();

                var Tahmona8       = new Tahmona8();
                var tahmona10      = new Tahmona10();
                var tahmona12      = new Tahmona12();
                var tahmona14      = new Tahmona14();
                var dinerRegular24 = new DinerRegular24();

                display.WriteLineBuffProportional(dinerRegular24, "192.168.0.5");
                display.DisplayUpdate();

                while (true)
                {
                    foreach (var dfont in new IFont[] { dinerRegular24, Tahmona8, tahmona10, tahmona12, tahmona14 })
                    {
                        display.WriteLineBuff(dfont, "Hello World 123456", dfont.GetType().Name);
                        display.DisplayUpdate();
                        Console.ReadLine();
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public byte[] GetLED2(Logger_class log)
        {
            byte[] tempReturn;

            if (!_CheckInit())
            {
                return(null);
            }

            log.WriteLog("Calling results for get LED 2...");

            using (var bus = I2CBus.Open("/dev/i2c-" + this._bus.ToString()))
            {
                bus.WriteBytes(_TBorgAddress, new byte[] { COMMAND_GET_LED2 });
                tempReturn = bus.ReadBytes(_TBorgAddress, I2C_MAX_LEN);
                if (tempReturn[0] == COMMAND_GET_LED2)
                {
                    if (log != null)
                    {
                        log.WriteLog("Get LED2 response: " + this._BytesToString(tempReturn));
                    }

                    return(tempReturn);
                }
                else
                {
                    if (log != null)
                    {
                        log.WriteLog("Got a nonsense reponse from COMMAND_GET_LED2..." + this._BytesToString(tempReturn));
                    }

                    throw new InvalidProgramException("Nonsense response during COMMAND_GET_LED2.");
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Sets the battery monitoring limits used for setting the LED color.  The colors shown range from full red at minimum (or below), yellow at half, and green at maximum or higher.  These values are stored in the EEPROM and reloaded when the board is powered.
        /// </summary>
        /// <param name="minimum">Minimum voltage (0 V minimum)</param>
        /// <param name="maximum">Maximum voltage (36.3 V maximum)</param>
        /// <param name="log">Optional logging output routine</param>
        public void SetBatteryMonitoringLimits(decimal minimum, decimal maximum, Logger_class log = null)
        {
            // my original values were 6.98 / 35.02; I don't know what the defaults are
            if (!_CheckInit())
            {
                throw new NullReferenceException("ThunderBorg not initiated.");
            }

            minimum /= Convert.ToDecimal(VOLTAGE_PIN_MAX);
            maximum /= Convert.ToDecimal(VOLTAGE_PIN_MAX);

            byte levelMin = Math.Max(Convert.ToByte(0x00), Math.Min(Convert.ToByte(0xFF), Convert.ToByte(minimum * 0xFF)));
            byte levelMax = Math.Max(Convert.ToByte(0x00), Math.Min(Convert.ToByte(0xFF), Convert.ToByte(maximum * 0xFF)));

            if (log != null)
            {
                log.WriteLog("Trying to set battery monitoring limits to: 0x" + levelMin.ToString("X2") + " V. min and 0x" + levelMax.ToString("X2") + " V. max...");
            }

            using (var bus = I2CBus.Open("/dev/i2c-" + this._bus.ToString()))
            {
                bus.WriteBytes(_TBorgAddress, new byte[] { COMMAND_SET_BATT_LIMITS, levelMin, levelMax });
                System.Threading.Thread.Sleep(200);     // note: this was recommended in the Python version for EEPROM writing
            }
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Use this method to create AMG88xx device if you are using PI 1
 /// </summary>
 /// <param name="devPath"></param>
 /// <param name="address">address of AMG88xx</param>
 public AMG8833(string devPath, byte address)
 {
     i2cPath = devPath;
     _i2cBus = I2CBus.Open(i2cPath);
     _i2cBus.set_slave_address(address);
     init();
 }
Ejemplo n.º 10
0
        public MCP23008(byte address = 0x20, ushort speed = 100)
        {
            // tried this, based on a forum post, but seems to have no effect.
            //H.OutputPort SDA = new H.OutputPort(N.Pins.GPIO_PIN_A4, false);
            //H.OutputPort SCK = new H.OutputPort(N.Pins.GPIO_PIN_A5, false);
            //SDA.Dispose();
            //SCK.Dispose();

            // configure our i2c bus so we can talk to the chip
            this._i2cBus = new I2CBus(address, speed);

            Debug.Print("initialized.");

            // make sure the chip is in a default state
            Initialize();
            Debug.Print("Chip Reset.");
            //Thread.Sleep(100);

            // read in the initial state of the chip
            _iodir = this._i2cBus.ReadRegister(_IODirectionRegister);
            // tried some sleeping, but also has no effect on its reliability
            //Thread.Sleep(100);
            //Debug.Print("IODIR: " + _iodir.ToString("X"));
            _gpio = this._i2cBus.ReadRegister(_GPIORegister);
            //Thread.Sleep(100);
            //Debug.Print("GPIO: " + _gpio.ToString("X"));
            _olat = this._i2cBus.ReadRegister(_OutputLatchRegister);
            //Thread.Sleep(100);
            //Debug.Print("OLAT: " + _olat.ToString("X"));
        }
Ejemplo n.º 11
0
        /// <summary>
        ///     Create a new instance of the TSL2561 class with the specified I2C address.
        /// </summary>
        /// <remarks>
        ///     By default the sensor will be set to low gain.
        /// <remarks>
        /// <param name="address">I2C address of the TSL2561</param>
        /// <param name="speed">Speed of the I2C bus (default = 100 KHz).</param>
        /// <param name="updateInterval">Update interval for the sensor (in milliseconds).</param>
        /// <param name="lightLevelChangeNotificationThreshold">Changes in light level greater than this value will generate an interrupt in auto-update mode.</param>
        public TSL2561(byte address = (byte)Addresses.Default, ushort speed = 100, ushort updateInterval = MinimumPollingPeriod,
                       float lightLevelChangeNotificationThreshold = 10.0F)
        {
            if ((address != (byte)Addresses.Address0) && (address != (byte)Addresses.Default) &&
                (address != (byte)Addresses.Address1))
            {
                throw new ArgumentOutOfRangeException(nameof(address), "Address should be 0x29, 0x39 or 0x49.");
            }
            if (speed > 1000)
            {
                throw new ArgumentOutOfRangeException(nameof(speed), "Speed should be between 0 and 1000 KHz");
            }
            if (lightLevelChangeNotificationThreshold < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(lightLevelChangeNotificationThreshold), "Light level threshold change values should be >= 0");
            }
            LightLevelChangeNotificationThreshold = lightLevelChangeNotificationThreshold;
            _updateInterval = updateInterval;

            var device = new I2CBus(address, speed);

            _tsl2561 = device;
            //
            //  Wait for the sensor to prepare the first reading (402ms after power on).
            //
            Thread.Sleep(410);
            if (updateInterval > 0)
            {
                StartUpdating();
            }
            else
            {
                Update();
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        ///     Create a new SSD1306 object using the default parameters for
        /// </summary>
        /// <remarks>
        ///     Note that by default, any pixels out of bounds will throw and exception.
        ///     This can be changed by setting the <seealso cref="IgnoreOutOfBoundsPixels" />
        ///     property to true.
        /// </remarks>
        /// <param name="address">Address of the bus on the I2C display.</param>
        /// <param name="speed">Speed of the I2C bus.</param>
        /// <param name="displayType">Type of SSD1306 display (default = 128x64 pixel display).</param>
        public SSD1306(byte address = 0x3c, ushort speed = 400, DisplayType displayType = DisplayType.OLED128x64)
        {
            var display = new I2CBus(address, speed);

            _ssd1306 = display;
            switch (displayType)
            {
            case DisplayType.OLED128x64:
                _width  = 128;
                _height = 64;
                SendCommands(_oled128x64SetupSequence);
                break;

            case DisplayType.OLED128x32:
                _width  = 128;
                _height = 32;
                SendCommands(_oled128x32SetupSequence);
                break;
            }
            var pages = _height / 8;

            _buffer                 = new byte[_width * pages];
            _showPreamble           = new byte[] { 0x21, 0x00, (byte)(_width - 1), 0x22, 0x00, (byte)(pages - 1) };
            IgnoreOutOfBoundsPixels = false;
            //
            //  Finally, put the display into a known state.
            //
            InvertDisplay = false;
            Sleep         = false;
            Contrast      = 0xff;
            StopScrolling();
        }
Ejemplo n.º 13
0
        public static void Main()
        {
            // setup some configs
            ushort speed           = 100;
            ushort timeout         = 100;
            ushort numberOfDevices = 0;

            // loop forever
            while (true)
            {
                numberOfDevices = 0;

                // loop through all the possible I2C addresses (0-127)
                for (byte i = 0; i < 127; i++)
                {
                    I2CBus i2C = new I2CBus(i, speed, timeout);
                    try
                    {
                        i2C.WriteByte(0);
                        Debug.Print("Found I2C device at: " + i.ToString("X"));
                        numberOfDevices++;
                    }
                    catch (Exception e) { }
                }

                if (numberOfDevices == 0)
                {
                    Debug.Print("No I2C devices found.");
                }

                // wait five seconds before scanning again.
                Thread.Sleep(5000);
            }
        }
Ejemplo n.º 14
0
        public byte GetBoardID(Logger_class log = null)
        {
            byte tempReturn = 0x00;

            if (!_CheckInit())
            {
                throw new NullReferenceException("ThunderBorg not initiated.");
            }

            if (log != null)
            {
                log.WriteLog("Checking board ID...");
            }

            using (var bus = I2CBus.Open("/dev/i2c-" + this._bus.ToString()))
            {
                bus.WriteBytes(_TBorgAddress, new byte[] { COMMAND_GET_ID });
                byte[] response = bus.ReadBytes(_TBorgAddress, I2C_MAX_LEN);
                if (response[0] == COMMAND_GET_ID)
                {
                    tempReturn = response[1];
                }
            }

            return(tempReturn);
        }
Ejemplo n.º 15
0
        /// <summary>
        ///     Create a new GroveTH02 object using the default parameters for the component.
        /// </summary>
        /// <param name="address">Address of the Grove TH02 (default = 0x4-).</param>
        /// <param name="speed">Speed of the I2C bus (default = 100 KHz).</param>
        /// <param name="updateInterval">Number of milliseconds between samples (0 indicates polling to be used)</param>
        /// <param name="humidityChangeNotificationThreshold">Changes in humidity greater than this value will trigger an event when updatePeriod > 0.</param>
        /// <param name="temperatureChangeNotificationThreshold">Changes in temperature greater than this value will trigger an event when updatePeriod > 0.</param>
        public GroveTH02(byte address = 0x40, ushort speed = 100, ushort updateInterval = MinimumPollingPeriod,
                         float humidityChangeNotificationThreshold    = 0.001F,
                         float temperatureChangeNotificationThreshold = 0.001F)
        {
            I2CBus device = new I2CBus(address, speed);

            _groveTH02 = (ICommunicationBus)device;
            if (humidityChangeNotificationThreshold < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(humidityChangeNotificationThreshold), "Humidity threshold should be >= 0");
            }
            if (humidityChangeNotificationThreshold < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(temperatureChangeNotificationThreshold), "Temperature threshold should be >= 0");
            }
            TemperatureChangeNotificationThreshold = temperatureChangeNotificationThreshold;
            HumidityChangeNotificationThreshold    = humidityChangeNotificationThreshold;
            _updateInterval = updateInterval;
            if (updateInterval > 0)
            {
                StartUpdating();
            }
            else
            {
                Update();
            }
        }
Ejemplo n.º 16
0
        public void SetFailsafe(bool setting, Logger_class log = null)
        {
            if (!_CheckInit())
            {
                return;
            }

            bool currentState = this.GetFailsafe(log);

            if (currentState == setting)
            {
                if (log != null)
                {
                    log.WriteLog("Called setting for failsafe: " + setting.ToString() + " but it already was...");
                }
                return;
            }

            using (var bus = I2CBus.Open("/dev/i2c-" + this._bus.ToString()))
            {
                bus.WriteBytes(_TBorgAddress, new byte[] { COMMAND_SET_FAILSAFE, Convert.ToByte(!currentState) });
                if (log != null)
                {
                    log.WriteLog("Set failsafe to " + (!currentState).ToString());
                }
            }
        }
Ejemplo n.º 17
0
        public byte[] GetDriveFaultB(Logger_class log = null)
        {
            if (!_CheckInit(log, true))
            {
                return(null);
            }

            byte[] tempReturn;

            if (log != null)
            {
                log.WriteLog("Getting drive fault B status...");
            }

            using (var bus = I2CBus.Open("/dev/i2c-" + this._bus.ToString()))
            {
                bus.WriteBytes(_TBorgAddress, new byte[] { COMMAND_GET_DRIVE_B_FAULT });
                tempReturn = bus.ReadBytes(_TBorgAddress, I2C_MAX_LEN);

                if (log != null)
                {
                    log.WriteLog("Raw Response: " + _BytesToString(tempReturn));
                }
            }

            return(tempReturn);
        }
Ejemplo n.º 18
0
        public int GetMotorB(Logger_class log = null)
        {
            int tempReturn = 0;

            if (!_CheckInit(log, true))
            {
                return(0);
            }

            if (log != null)
            {
                log.WriteLog("Getting power level for B motors...");
            }

            using (var bus = I2CBus.Open("/dev/i2c-" + this._bus.ToString()))
            {
                bus.WriteBytes(_TBorgAddress, new byte[] { COMMAND_GET_B });
                byte[] response = bus.ReadBytes(_TBorgAddress, I2C_MAX_LEN);
                if (response == null)
                {
                    if (log != null)
                    {
                        log.WriteLog("*** ERROR: no response from ThunderBorg...");
                    }

                    throw new NullReferenceException("No parseable response from B motors on GetMotorB request.");
                }
                else if (response[0] != COMMAND_GET_B)
                {
                    if (log != null)
                    {
                        log.WriteLog("Didn't get an expected response from the B motors on GetMotorB request.");
                    }

                    throw new IndexOutOfRangeException("Unexpected response from B motors on GetMotorB request.");
                }
                else
                {
                    byte power_direction = response[1];
                    byte power_level     = response[2];

                    if (log != null)
                    {
                        log.WriteLog("Raw response: " + _BytesToString(response));
                    }

                    if (power_direction == COMMAND_VALUE_FWD)
                    {
                        tempReturn = power_level;
                    }
                    else if (power_direction == COMMAND_VALUE_REV)
                    {
                        tempReturn = -power_level;
                    }
                }
            }

            return(tempReturn);
        }
Ejemplo n.º 19
0
        /// <summary>
        ///     Create a new AT24Cxx object using the default parameters for the component.
        /// </summary>
        /// <param name="address">Address of the MAG3110 (default = 0x50).</param>
        /// <param name="speed">Speed of the I2C bus (default = 400 KHz).</param>
        /// <param name="pageSize">Number of bytes in a page (default = 32 - AT24C32).</param>
        /// <param name="memorySize">Total number of bytes in the EEPROM (default = 8192 - AT24C32).</param>
        public AT24Cxx(byte address = 0x50, ushort speed = 10, ushort pageSize = 32, ushort memorySize = 8192)
        {
            var device = new I2CBus(address, speed);

            _eeprom     = device;
            _pageSize   = pageSize;
            _memorySize = memorySize;
        }
Ejemplo n.º 20
0
 public DefaultRadio(I2CBus twiBus, RadioSettings settings) :
     base(0, new AircraftPrincipalAxes {
     Pitch = 0, Roll = 0, Yaw = 0
 }, false)
 {
     _twiBus   = twiBus;
     _settings = settings;
 }
Ejemplo n.º 21
0
 public override void Disconnect()
 {
     foreach (var pollID in pollIDs)
     {
         try { I2CBus.RemovePoll(pollID); }
         catch (I2CException) { }
     }
     pollIDs.Clear();
 }
Ejemplo n.º 22
0
        /// <summary>
        ///     Create a new SI1145 sensor object.
        /// </summary>
        /// <param name="address">Address of the chip on the I2C bus (default to 0x60).</param>
        /// <param name="speed">Communication speed (default to 400 KHz).</param>
        public SI1145(byte address = 0x60, ushort speed = 400)
        {
            I2CBus device = new I2CBus(address, speed);

            _si1145 = (ICommunicationBus)device;
            if (_si1145.ReadRegister(Registers.PartID) != 0x45)
            {
                throw new Exception("Invalid part ID");
            }
        }
Ejemplo n.º 23
0
 public override bool CheckIfPossibleToConnect()
 {
     if (I2CBus.State != BusState.Connected)
     {
         return(false);
     }
     try { I2CBus.Get(CompassI2CAddress, 0); }
     catch (I2CException) { return(false); }
     return(true);
 }
Ejemplo n.º 24
0
        /// <summary>
        ///     Create a new MAG3110 object using the default parameters for the component.
        /// </summary>
        /// <param name="address">Address of the DS3231 (default = 0x68).</param>
        /// <param name="speed">Speed of the I2C bus (default = 100 KHz).</param>
        /// <param name="interruptPin">Digital pin connected to the alarm interrupt pin on the RTC.</param>
        public DS3231(byte address = 0x68, ushort speed = 100, Cpu.Pin interruptPin = Cpu.Pin.GPIO_NONE)
        {
            var device = new I2CBus(address, speed);

            _ds323x = device;
            if (interruptPin != Cpu.Pin.GPIO_NONE)
            {
                InterruptPin = interruptPin;
            }
        }
 public Bmp180(I2CBus bus, byte address = 0x77, Mode mode = Mode.Bmp085_Mode_Ultralowpower)
 {
     _bus          = bus;
     Bmp085Address = address;
     _slaveConfig  = new I2CDevice.Configuration(Bmp085Address, 100);
     while (!Init(mode))
     {
         Debug.Print("BMP sensor not detected...");
     }
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Constructor for SPI LCD connection (Adafruit I2C LCD backpack)
        /// </summary>
        public clsLCD_MLC(byte rows, byte cols)
        {
            // initialize i2c bus (only one instance is allowed)
            I2CBus bus = new I2CBus();

            // initialize provider (multiple devices can be attached to same bus)
            MCP23008LcdTransferProvider lcdProvider = new MCP23008LcdTransferProvider(bus);

            lcd = new Lcd(lcdProvider);
            lcd_begin(rows, cols);
        }
        private short ReadShort(byte registerAddress)
        {
            // write register address
            I2CBus.GetInstance().Write(_slaveConfig, new byte[] { registerAddress }, TransactionTimeout);

            // get MSB and LSB result
            byte[] inputData = new byte[2];
            I2CBus.GetInstance().Read(_slaveConfig, inputData, TransactionTimeout);

            return((short)((inputData[0] << 8) | inputData[1]));
        }
Ejemplo n.º 28
0
 public Eeprom(IC chip, I2CBus i2cBus, byte address, int clockRateKHz)
 {
     if (address > 7)
     {
         address = 0;
     }
     I2CBus            = i2cBus;
     this.address      = address;
     this.clockRateKHz = clockRateKHz;
     MaxSize           = (ushort)chip;
     SetConfig();
 }
Ejemplo n.º 29
0
        public override bool OnConnecting()
        {
            try
            {
                // Put HMC5883L into continuous measurement mode.
                I2CBus.Set(CompassI2CAddress, CompassRegisters.Mode, 0);
                AddPoll(1000, CompassI2CAddress, CompassRegisters.DataXMsb, 6);
            }
            catch (I2CException e) { return(false); }

            return(true);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Write operation to the BlinkM.
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public int Write(Command.BaseCommand command)
        {
            I2CBus bus      = I2CBus.GetInstance();
            int    retValue = bus.Write(this._I2CConfig, command.GetSendBytes(), I2CTimeout);

            if (command.WaitMillis > 0)
            {
                Thread.Sleep(command.WaitMillis);
            }

            return(retValue);
        }
Ejemplo n.º 31
0
 public MPU6050(I2CBus bus, ushort address, int clockRate)
     : base(bus, address, clockRate)
 {
 }