Ejemplo n.º 1
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="i2cBus">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(string i2cBus, byte address = (byte)Addresses.Default, ushort updateInterval = MinimumPollingPeriod,
                       float lightLevelChangeNotificationThreshold = 10.0F)
        {
            if (lightLevelChangeNotificationThreshold < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(lightLevelChangeNotificationThreshold), "Light level threshold change values should be >= 0");
            }

            LightLevelChangeNotificationThreshold = lightLevelChangeNotificationThreshold;
            this.updateInterval = updateInterval;

            var settings   = new I2cConnectionSettings(address, 100_000); //The slave's address and the bus speed.
            var controller = I2cController.FromName(i2cBus);
            var device     = controller.GetDevice(settings);

            //var device = new I2cPeripheral(i2cBus, address);
            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.º 2
0
        static async void i2cget(string[] input)
        {
            if (input.Length == 3)
            {
                int           slave      = Convert.ToInt32(input[1], 16);
                UpBridge.Up   upb        = new UpBridge.Up();
                I2cController controller = await I2cController.GetDefaultAsync();

                // Int32.TryParse(input[1], out slave);
                I2cConnectionSettings Settings = new I2cConnectionSettings(slave);
                byte[] writebuf = new byte[1];
                writebuf[0] = Convert.ToByte(input[2], 16);
                byte[] readbuf = new byte[1];
                try
                {
                    controller.GetDevice(Settings).WriteRead(writebuf, readbuf);
                    Console.WriteLine("Sucess to get data,\n" +
                                      Convert.ToString(readbuf[0], 16));
                }
                catch (Exception e)
                {
                    Console.WriteLine("error to get data\n");
                }
            }
            else
            {
                Console.WriteLine("command error,plese refer to below example \n" +
                                  "i2cget {i2c address} {i2c register}\n");
                Console.WriteLine(Usage);
            }
        }
Ejemplo n.º 3
0
        /**
         * Start I2C Communication
         **/
        public async Task StartI2CAsync(byte deviceAddress, string controllerName = null)
        {
            try
            {
                var i2cSettings = new I2cConnectionSettings(deviceAddress);
                i2cSettings.BusSpeed = I2cBusSpeed.FastMode;
                if (string.IsNullOrEmpty(controllerName))
                {
                    var controller = await I2cController.GetDefaultAsync();

                    _i2cPortExpander = controller.GetDevice(i2cSettings);
                }
                else
                {
                    string deviceSelector       = I2cDevice.GetDeviceSelector(controllerName);
                    var    i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector);

                    _i2cPortExpander = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings);
                }
                await InitializeAsync();
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Exception: {e.Message}");
            }
        }
Ejemplo n.º 4
0
        public static void Execute()
        {
            var settings = BME280Driver.GetI2CConnectionSettings(BME280Address.Primary);

            var controller = I2cController.FromName(G120E.I2cBus.I2c0);


            var device = controller.GetDevice(settings);

            var driver = new BME280Driver(device);

            driver.Initialize();

            driver.ChangeSettings(
                BME280SensorMode.Forced,
                BME280OverSample.X1,
                BME280OverSample.X1,
                BME280OverSample.X1,
                BME280Filter.Off);

            driver.Read();

            Debug.WriteLine("Pressure: " + driver.Pressure);
            Debug.WriteLine("Humidity: " + driver.Humidity);
            Debug.WriteLine("Temperature:" + driver.Temperature);
        }
Ejemplo n.º 5
0
        private void ThreadTest()
        {
            this.isRuning = true;

            try {
                var i2cController = I2cController.FromName("GHIElectronics.TinyCLR.NativeApis.STM32H7.I2cController\\0");
                var lis2hh12      = new LIS2HH12Controller(i2cController);

                while (this.isRuning)
                {
                    var x = (int)lis2hh12.X;
                    var y = (int)lis2hh12.Y;
                    var z = (int)lis2hh12.Z;

                    this.UpdateStatusText("X = " + x + ", Y = " + y + ", Z = " + z, true);

                    Thread.Sleep(1);
                }
            }
            catch {
            }

            this.isRuning = false;

            return;
        }
        private bool DoTestI2c()
        {
            this.UpdateStatusText("Reading LIS2HH12 sensor...", true);

            try {
                var i2cController = I2cController.FromName("GHIElectronics.TinyCLR.NativeApis.STM32H7.I2cController\\0");
                var lis2hh12      = new LIS2HH12Controller(i2cController);

                while (this.isRunning)
                {
                    var x = (int)lis2hh12.X;
                    var y = (int)lis2hh12.Y;
                    var z = (int)lis2hh12.Z;

                    if (x != y &&
                        x != z &&
                        y != z &&
                        x != 0 &&
                        y != 0 &&
                        z != 0 &&
                        x != double.MaxValue &&
                        y != double.MaxValue &&
                        z != double.MaxValue)
                    {
                        break;
                    }

                    Thread.Sleep(20);
                }
            }
            catch {
            }

            return(true);
        }
Ejemplo n.º 7
0
        /// <summary>Constructs a new instance.</summary>
        public FMClick(int reset, int chipSelect, I2cController controller)
        {
            this.radioTextWorkerRunning = true;
            this.currentRadioText       = "N/A";
            this.spacingDivisor         = 2;
            this.baseChannel            = 875;
            this.registers = new ushort[16];

            this.resetPin = GpioController.GetDefault().OpenPin(reset);
            this.resetPin.SetDriveMode(GpioPinDriveMode.Output);

            this.selPin = GpioController.GetDefault().OpenPin(chipSelect);
            this.selPin.SetDriveMode(GpioPinDriveMode.Output);
            this.selPin.Write(GpioPinValue.High);

            var settings = new I2cConnectionSettings(FMClick.I2C_ADDRESS, 400_000);

            this.i2cBus = controller.GetDevice(settings);


            this.InitializeDevice();
            this.SetChannelConfiguration(Spacing.USAAustrailia, Band.USAEurope);
            this.Channel = this.MinChannel;
            //this.Volume = FMClick.MAX_VOLUME;
            this.radioTextWorkerThread = new Thread(this.RadioTextWorker);
        }
        //==========================================================================
        //  GPIO Methods
        //==========================================================================


        //==========================================================================
        //  I2C Methods
        //==========================================================================

        //Initialise connection to I2C Device
        public async void I2C_init()
        {
            I2cController controller = await I2cController.GetDefaultAsync();

            tempSensor     = controller.GetDevice(new I2cConnectionSettings(0x5C));
            humiditySensor = controller.GetDevice(new I2cConnectionSettings(0x5F));
        }
 public YahboomPianoController(I2cController i2cController, PwmChannel buzzer, int colorLedPin)
 {
     this.i2c    = i2cController.GetDevice(new I2cConnectionSettings(0x50, 100_000));
     this.buzzer = buzzer;
     //var sg = new SignalGenerator(GpioController.GetDefault().OpenPin(colorLedPin));
     this.ws2812 = new WS2812Controller(GpioController.GetDefault().OpenPin(colorLedPin), 2, WS2812Controller.DataFormat.rgb888);
 }
Ejemplo n.º 10
0
        private void ThreadTest()
        {
            this.isRunning = true;


            var i2cController = I2cController.FromName(SC20260.I2cBus.I2c1);

            try {
                var ov9655 = new Ov9655Controller(i2cController);

read_id:
                try {
                    var id = ov9655.ReadId();
                }
                catch {
                    goto read_id;
                }

                byte[]          data           = null;
                UnmanagedBuffer unmangedBuffer = null;

                if (Memory.UnmanagedMemory.FreeBytes != 0)
                {
                    unmangedBuffer = new UnmanagedBuffer(640 * 480 * 2);
                    data           = unmangedBuffer.Bytes;
                }
                else
                {
                    data = new byte[640 * 480 * 2];
                }

                ov9655.SetResolution(Ov9655Controller.Resolution.Vga);
                var displayController = Display.DisplayController;

                while (this.isRunning)
                {
                    try {
                        ov9655.Capture(data, 500);

                        displayController.DrawBuffer(0, this.TopBar.ActualHeight, 0, 0, 480, 272 - this.TopBar.ActualHeight, 640, data, 0);
                    }
                    catch {
                    }

                    Thread.Sleep(10);
                }

                if (unmangedBuffer != null)
                {
                    unmangedBuffer.Dispose();
                }
            }
            catch {
            }


            this.isRunning = false;

            return;
        }
Ejemplo n.º 11
0
        public ArducamMini(string spiBus, int chipSelectPin, string i2cBus, byte address = 0x30)
        {
            //i2cDevice = new I2cPeripheral(i2cBus, address);
            var settings   = new I2cConnectionSettings(address, 100_000); //The slave's address and the bus speed.
            var controller = I2cController.FromName(i2cBus);

            i2cDevice = controller.GetDevice(settings);
            //chipSelectPort = device.CreateDigitalOutputPort(chipSelectPin);
            var gpio = GpioController.GetDefault();

            chipSelectPort = gpio.OpenPin(chipSelectPin);
            chipSelectPort.SetDriveMode(GpioPinDriveMode.Output);
            chipSelectPort.Write(GpioPinValue.Low);

            var settingsSpi = new SpiConnectionSettings()
            {
                ChipSelectType = SpiChipSelectType.Gpio,
                ChipSelectLine = chipSelectPort,
                Mode           = SpiMode.Mode1,
                ClockFrequency = 4_000_000,
            };

            var Spicontroller = SpiController.FromName(spiBus);

            spiDevice = Spicontroller.GetDevice(settingsSpi);
            //spiDevice = new SpiPeripheral(spiBus, chipSelectPort);

            Initialize();
        }
Ejemplo n.º 12
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>
        public JoystickClick(Hardware.Socket socket, Byte address = 0x40)
        {
            // Create the driver's I²C configuration
            _joystick = I2cController.FromName(socket.I2cBus).GetDevice(new I2cConnectionSettings(address, 100000));

            WriteRegister(Registers.CONTROL1, 0b11110000);

            _reset = GpioController.GetDefault().OpenPin(socket.PwmPin);
            _reset.SetDriveMode(GpioPinDriveMode.Output);
            Reset(ResetModes.Hard);

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

            Button = GpioController.GetDefault().OpenPin(socket.Cs);
            Button.SetDriveMode(GpioPinDriveMode.Input);

            PowerMode = PowerModes.On;      // Interrupt mode

            InterruptLine = GpioController.GetDefault().OpenPin(socket.Int);
            InterruptLine.SetDriveMode(GpioPinDriveMode.InputPullUp);

            TimeBase = 3;
            ReadRegister(0x11);     // Don't care about the first data available
        }
Ejemplo n.º 13
0
        /// <summary>Constructs a new instance.</summary>
        /// <param name="DataReadyIntPin">The GPIO pin on the FEZ board that will connect to the DRDY (Data Ready, Interupt) pin on the slave device.</param>
        public Compass(int DataReadyIntPin)
        {
            this.writeBuffer1 = new byte[1];
            this.readBuffer6  = new byte[6];

            // Device I2C1 Slave address
            I2cConnectionSettings Setting = new I2cConnectionSettings(I2C_SLAVE_ADDRESS);

            Setting.BusSpeed = I2cBusSpeed.StandardMode; // 100kHz

            var ctrler = I2cController.FromName(FEZ.I2cBus.I2c1);
            var device = ctrler.GetDevice(Setting);

            i2c = device;

            TimerInterval = new TimeSpan(0, 0, 0, 0, 200);
            autoEvent     = new AutoResetEvent(false);
            var controller = GpioController.GetDefault();

            this.dataReady = controller.OpenPin(DataReadyIntPin);//GTI.InterruptdataReadyFactory.Create(socket, GT.Socket.Pin.Three, GTI.GlitchFilterMode.On, GTI.ResistorMode.PullUp, GTI.InterruptMode.RisingAndFallingEdge, this);

            if (dataReady.IsDriveModeSupported(DataReadyIntPin, GpioPinDriveMode.InputPullUp))
            {
                dataReady.SetDriveMode(GpioPinDriveMode.InputPullUp);
            }
            else
            {
                dataReady.SetDriveMode(GpioPinDriveMode.Input);
            }

            dataReady.ValueChanged += OnInterrupt;
        }
Ejemplo n.º 14
0
        public ScrollBitController(I2cController i2cController)
        {
            var settings = new I2cConnectionSettings(0x74, 100_000);

            this.i2c = i2cController.GetDevice(settings);

            this.WriteByte(REG_BANK, BANK_CONFIG);

            Thread.Sleep(1);
            this.WriteByte(REG_SHUTDOWN, 0);
            Thread.Sleep(1);

            this.WriteByte(REG_SHUTDOWN, 1);
            Thread.Sleep(1);


            this.WriteByte(REG_MODE, 0);
            this.WriteByte(REG_AUDIOSYNC, 0);

            var enable = new byte[17];// let enable = pins.createBuffer(17);

            for (var i = 0; i < 17; i++)
            {
                enable[i] = 255;
            }
            this.WriteByte(REG_BANK, 0);
            this.WriteBuffer(0, enable);
            this.WriteByte(REG_BANK, 1);
            this.WriteBuffer(0, enable);
        }
Ejemplo n.º 15
0
        static void InitBot()
        {
            var chip = new GHIElectronics.TinyCLR.Drivers.Nxp.PCA9685.PCA9685Controller(
                I2cController.FromName(FEZBit.I2cBus.Edge));

            var gpioController             = GpioController.GetDefault();
            var buzzerController           = PwmController.FromName(FEZBit.PwmChannel.Controller3.Id);
            var buzzerChannel              = buzzerController.OpenChannel(FEZBit.PwmChannel.Controller3.EdgeP0Channel);
            var frontsensorenable          = gpioController.OpenPin(FEZBit.GpioPin.EdgeP9);
            var frontsensorvaluecontroller = AdcController.FromName(FEZBit.Adc.Controller1.Id);
            var frontvalue      = frontsensorvaluecontroller.OpenChannel(FEZBit.Adc.Controller1.EdgeP3);
            var lineDetectLeft  = AdcController.FromName(FEZBit.Adc.Controller1.Id).OpenChannel(FEZBit.Adc.Controller1.EdgeP2);
            var lineDetectRight = AdcController.FromName(FEZBit.Adc.Controller1.Id).OpenChannel(FEZBit.Adc.Controller1.EdgeP1);
            var p2remove        = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.EdgeP1);

            p2remove.SetDriveMode(GpioPinDriveMode.Input);


            bot = new BitBotController(
                chip, buzzerChannel,
                lineDetectLeft, lineDetectRight,
                gpioController.OpenPin(FEZBit.GpioPin.EdgeP14), gpioController.OpenPin(FEZBit.GpioPin.EdgeP15),
                frontsensorenable, frontvalue,
                gpioController.OpenPin(FEZBit.GpioPin.EdgeP16));

            bot.SetHeadlight(200, 50, 0);
            bot.SetStatusLeds(false, true, false);
            bot.SetColorLeds(0, 0xff, 0, 0);
            bot.SetColorLeds(1, 0, 0xff, 0);
            bot.SetColorLeds(2, 0, 0, 0xff);
            bot.Beep();
        }
Ejemplo n.º 16
0
        static void TestCuteBot()
        {
            var buzzerController = PwmController.FromName(FEZBit.PwmChannel.Controller3.Id);
            var buzzerChannel    = buzzerController.OpenChannel(FEZBit.PwmChannel.Controller3.EdgeP0Channel);
            var lineDetectLeft   = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.EdgeP13);
            var lineDetectRight  = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.EdgeP14);

            var bot = new GHIElectronics.TinyCLR.Elecfreaks.TinyBit.CuteBotController(
                I2cController.FromName(FEZBit.I2cBus.Edge),
                buzzerChannel,
                lineDetectLeft, lineDetectRight,
                GpioController.GetDefault().OpenPin(FEZBit.GpioPin.EdgeP15)
                );

            bot.Beep();
            bot.SetColorLeds(1, 100, 0, 0);
            bot.SetColorLeds(0, 0, 50, 100);
            bot.SetHeadlight(true, 30, 100, 100);
            bot.SetHeadlight(false, 30, 0, 200);
            bot.SetMotorSpeed(0.5, 0.5);
            bot.SetMotorSpeed(0.5, -0.5);
            bot.SetMotorSpeed(-0.5, 0.5);
            bot.SetMotorSpeed(0, 0);
            while (true)
            {
                var l = bot.ReadLineSensor(true);
                var r = bot.ReadLineSensor(false);

                Thread.Sleep(50);
                bot.Beep();
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Will dispose all related attributes.
        /// </summary>
        public void Dispose()
        {
            // Cancel timers
            captiveButtonsValueReadTimer.Cancel();
            temperatureValueReadTimer.Cancel();
            pressureValueReadTimer.Cancel();

            // Dispose child controller
            apa102.Dispose();
            bmp280.Dispose();
            ht16k33.Dispose();

            // Dispose pins
            redPin.Dispose();
            greenPin.Dispose();
            bluePin.Dispose();
            buttonAPin.Dispose();
            buttonBPin.Dispose();
            buttonCPin.Dispose();
            buzzerPin.Dispose();

            // Dispose controllers
            pwmController  = null;
            i2cController  = null;
            gpioController = null;
        }
Ejemplo n.º 18
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="TempHum6Click" /> class.
        /// </summary>
        /// <param name="socket">The socket on which the TempHum6Click module is plugged on MikroBus.Net board</param>
        public TempHum6Click(Hardware.Socket socket)
        {
            _socket = socket;
            _sensor = I2cController.FromName(socket.I2cBus).GetDevice(new I2cConnectionSettings(0x43, 100000));

            // Reset device
            Reset(ResetModes.Soft);

            // Deactivate Low Power to be able to read the PartID and UID registers.
            PowerMode = PowerModes.On;

            PartID = BitConverter.ToUInt16(ReadRegister(ENS210_REG_PART_ID, 2), 0);

            if (PartID != 0x210)
            {
                throw new DeviceInitialisationException("TempHum6 Click not found on I2C Bus.");
            }
            UniqueID = BitConverter.ToInt64(ReadRegister(ENS210_REG_UID, 8), 0);

            ConfigureSensor(new SensorConfiguration(
                                true,
                                true,
                                MeasurementMode.Continuous,
                                MeasurementMode.Continuous,
                                false));
        }
        private async Task I2cConnect(int panel)
        {
            try {
                var settings = new I2cConnectionSettings(I2CAddress[panel]);
                settings.BusSpeed = I2cBusSpeed.FastMode;

                // If the system is using the Lightning memory mapped driver ther use the Lightning I2CProvider
                if (LightningProvider.IsLightningEnabled)
                {
                    //LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();
                    var i2cControllers = await I2cController.GetControllersAsync(LightningI2cProvider.GetI2cProvider());

                    i2cDevice[panel] = i2cControllers[0].GetDevice(settings);
                }
                else
                {
                    // Otherwise, if the inbox provider will continue to be the default
                    string aqs = I2cDevice.GetDeviceSelector();                          /* Find the selector string for the I2C bus controller                   */
                    var    dis = (await DeviceInformation.FindAllAsync(aqs)).ToArray();  /* Find the I2C bus controller device with our selector string           */
                    i2cDevice[panel] = await I2cDevice.FromIdAsync(dis[0].Id, settings); /* Create an I2cDevice with our selected bus controller and I2C settings */
                }
            }
            catch (Exception e) {
                throw new Exception("ht16k33 initisation problem: " + e.Message);
            }
        }
        public async Task Initialize()
        {
            var settings = new I2cConnectionSettings(I2C_ADDRESS)
            {
                BusSpeed = I2cBusSpeed.FastMode, SharingMode = I2cSharingMode.Shared
            };
            var controller = await I2cController.GetDefaultAsync();

            _accelerometer = controller.GetDevice(settings);

            QueuedLock.Enter();

            //Enable all axes with normal mode
            _accelerometer.Write(new byte[] { REGISTER_POWER_MANAGEMENT_1, 0 });    //Wake up device
            _accelerometer.Write(new byte[] { REGISTER_POWER_MANAGEMENT_1, 0x80 }); //Reset the device

            QueuedLock.Exit();

            await Task.Delay(20);

            QueuedLock.Enter();

            _accelerometer.Write(new byte[] { REGISTER_POWER_MANAGEMENT_1, 1 });   //Set clock source to gyro x
            _accelerometer.Write(new byte[] { REGISTER_GYROSCOPE_CONFIG, 0 });     //+/- 250 degrees sec
            _accelerometer.Write(new byte[] { REGISTER_ACCELEROMETER_CONFIG, 0 }); //+/- 2g

            _accelerometer.Write(new byte[] { REGISTER_CONFIG, 1 });               //184 Hz, 2ms delay
            _accelerometer.Write(new byte[] { REGISTER_SAMPLE_RATE_DIVIDER, 19 }); //Set rate 50Hz
            _accelerometer.Write(new byte[] { REGISTER_POWER_MANAGEMENT_1, 0 });   //Wake up device

            QueuedLock.Exit();
        }
Ejemplo n.º 21
0
        private async Task Tml_Init(int irqPinNumber, int resetPinNumber)
        {
            if (LightningProvider.IsLightningEnabled)
            {
                LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();
            }

            GpioController gpio = GpioController.GetDefault();

            pinIRQ   = gpio.OpenPin(irqPinNumber);
            pinRESET = gpio.OpenPin(resetPinNumber);

            pinRESET.Write(GpioPinValue.High);

            pinIRQ.SetDriveMode(GpioPinDriveMode.Input);
            pinRESET.SetDriveMode(GpioPinDriveMode.Output);

            I2cConnectionSettings settings = new I2cConnectionSettings(NXP_NCI_I2C_ADDR)
            {
                BusSpeed    = I2cBusSpeed.FastMode,
                SharingMode = I2cSharingMode.Shared
            };

            //string aqs = I2cDevice.GetDeviceSelector(I2C_CONTROLLER_NAME);
            //DeviceInformationCollection dis = await DeviceInformation.FindAllAsync(aqs);
            //i2c7120 = await I2cDevice.FromIdAsync(dis[0].Id, settings);

            I2cController i2cController = await I2cController.GetDefaultAsync();

            i2c7120 = i2cController.GetDevice(settings);
        }
Ejemplo n.º 22
0
        private async void InitializeSystem()
        {
            byte[] i2CWriteBuffer;
            byte[] i2CReadBuffer;
            byte   bitMask;


            var i2cSettings = new I2cConnectionSettings(PORT_EXPANDER_I2C_ADDRESS);
            var controller  = await I2cController.GetDefaultAsync();

            i2cPortExpander = controller.GetDevice(i2cSettings);


            // initialize I2C Port Expander registers
            try
            {
                // initialize local copies of the IODIR, GPIO, and OLAT registers
                i2CReadBuffer = new byte[1];

                // read in each register value on register at a time (could do this all at once but
                // for example clarity purposes we do it this way)
                i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_IODIR_REGISTER_ADDRESS }, i2CReadBuffer);
                iodirRegister = i2CReadBuffer[0];

                i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_GPIO_REGISTER_ADDRESS }, i2CReadBuffer);
                gpioRegister = i2CReadBuffer[0];

                i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_OLAT_REGISTER_ADDRESS }, i2CReadBuffer);
                olatRegister = i2CReadBuffer[0];

                // configure the LED pin output to be logic high, leave the other pins as they are.
                olatRegister  |= LED_GPIO_PIN;
                i2CWriteBuffer = new byte[] { PORT_EXPANDER_OLAT_REGISTER_ADDRESS, olatRegister };
                i2cPortExpander.Write(i2CWriteBuffer);

                // configure only the LED pin to be an output and leave the other pins as they are.
                // input is logic low, output is logic high
                bitMask        = (byte)(0xFF ^ LED_GPIO_PIN); // set the LED GPIO pin mask bit to '0', all other bits to '1'
                iodirRegister &= bitMask;
                i2CWriteBuffer = new byte[] { PORT_EXPANDER_IODIR_REGISTER_ADDRESS, iodirRegister };
                i2cPortExpander.Write(i2CWriteBuffer);
            }
            catch (Exception e)
            {
                ButtonStatusText.Text = "Failed to initialize I2C port expander: " + e.Message;
                return;
            }

            // setup our timers, one for the LED blink interval, the other for checking button status

            ledTimer          = new DispatcherTimer();
            ledTimer.Interval = TimeSpan.FromMilliseconds(TIMER_INTERVAL);
            ledTimer.Tick    += LedTimer_Tick;
            ledTimer.Start();

            buttonStatusCheckTimer          = new DispatcherTimer();
            buttonStatusCheckTimer.Interval = TimeSpan.FromMilliseconds(BUTTON_STATUS_CHECK_TIMER_INTERVAL);
            buttonStatusCheckTimer.Tick    += ButtonStatusCheckTimer_Tick;
            buttonStatusCheckTimer.Start();
        }
Ejemplo n.º 23
0
        /// <summary>Initializes a new instance of the <see cref="Proximity3Click" /> class.</summary>
        /// <param name="socket">The socket on which the ADC3 Click board is plugged on MikroBus.Net</param>
        /// <param name="address">The I2C address of the module</param>
        public Proximity3Click(Hardware.Socket socket, Byte address = 0x51)
        {
            _prox = I2cController.FromName(socket.I2cBus).GetDevice(new I2cConnectionSettings(address, 100000));

            if (ChipRevision.Major == 0x10 & ChipRevision.Minor == 0x58)
            {
                _prox.Write(new Byte[] { ALS_CONF_REG, _alsConf, 0b00000000 });
Ejemplo n.º 24
0
        static void DisplayConfigWPF()
        {
            var backlight = GpioController.GetDefault().OpenPin(BACKLIGHT);

            backlight.SetDriveMode(GpioPinDriveMode.Output);
            backlight.Write(GpioPinValue.High);

            var displayController = GHIElectronics.TinyCLR.Devices.Display.DisplayController.GetDefault();
            var controllerSetting = new GHIElectronics.TinyCLR.Devices.Display.ParallelDisplayControllerSettings {
                // 480x272
                Width                    = SCREEN_WIDTH,
                Height                   = SCREEN_HEIGHT,
                DataFormat               = GHIElectronics.TinyCLR.Devices.Display.DisplayDataFormat.Rgb565,
                PixelClockRate           = 10000000,
                PixelPolarity            = false,
                DataEnablePolarity       = false,
                DataEnableIsFixed        = false,
                HorizontalFrontPorch     = 2,
                HorizontalBackPorch      = 2,
                HorizontalSyncPulseWidth = 41,
                HorizontalSyncPolarity   = false,
                VerticalFrontPorch       = 2,
                VerticalBackPorch        = 2,
                VerticalSyncPulseWidth   = 10,
                VerticalSyncPolarity     = false,
            };

            displayController.SetConfiguration(controllerSetting);
            displayController.Enable();

            var i2cController = I2cController.FromName(SC20260.I2cBus.I2c1);

            var settings = new I2cConnectionSettings(0x38)  // the slave's address
            {
                BusSpeed      = 100000,
                AddressFormat = I2cAddressFormat.SevenBit,
            };

            var i2cDevice = i2cController.GetDevice(settings);

            var interrupt = GpioController.GetDefault().OpenPin(TOUCH_IRQ);

            touch            = new FT5xx6Controller(i2cDevice, interrupt);
            touch.TouchDown += Touch_TouchDown;
            touch.TouchUp   += Touch_TouchUp;

            // Create WPF window
            app = new Program(displayController);

            SelectPage  = new SelectPage();
            ConnectPage = new ConnectPage("");
            SplashPage  = new SplashPage();

            WpfWindow            = Program.CreateWindow(displayController);
            WpfWindow.Child      = SplashPage.Elements;
            WpfWindow.Visibility = Visibility.Visible;

            app.Run(WpfWindow);
        }
Ejemplo n.º 25
0
        /// <summary>
        ///
        /// </summary>
        private async void InitSensor()
        {
            if (LightningProvider.IsLightningEnabled)
            {
                LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();
            }

            var i2c = await I2cController.GetDefaultAsync();

            SENSOR = i2c.GetDevice(new I2cConnectionSettings(SensorAddr));

            //SENSOR初期化
            uint osrs_t   = 3;
            uint osrs_p   = 3;
            uint osrs_h   = 3;
            uint mode     = 3;
            uint t_sb     = 5;
            uint filter   = 0;
            uint spi3w_en = 0;

            uint ctrlMeasReg = (osrs_t << 5) | (osrs_p << 2) | mode;
            uint configReg   = (t_sb << 5) | (filter << 2) | spi3w_en;
            uint ctrlHumReg  = osrs_h;

            SENSOR.Write(new byte[] { 0xf2, (byte)ctrlHumReg });
            SENSOR.Write(new byte[] { 0xf4, (byte)ctrlMeasReg });
            SENSOR.Write(new byte[] { 0xf5, (byte)configReg });

            await Task.Delay(10);


            //キャリブレーションデータ読み込み
            //温度
            T1 = ReadUInt16((byte)Register.dig_T1);
            T2 = (Int16)ReadUInt16((byte)Register.dig_T2);
            T3 = (Int16)ReadUInt16((byte)Register.dig_T3);

            //気圧
            P1 = ReadUInt16((byte)Register.dig_P1);
            P2 = (Int16)ReadUInt16((byte)Register.dig_P2);
            P3 = (Int16)ReadUInt16((byte)Register.dig_P3);
            P4 = (Int16)ReadUInt16((byte)Register.dig_P4);
            P5 = (Int16)ReadUInt16((byte)Register.dig_P5);
            P6 = (Int16)ReadUInt16((byte)Register.dig_P6);
            P7 = (Int16)ReadUInt16((byte)Register.dig_P7);
            P8 = (Int16)ReadUInt16((byte)Register.dig_P8);
            P9 = (Int16)ReadUInt16((byte)Register.dig_P9);

            //湿度
            H1 = ReadByte((byte)Register.dig_H1);
            H2 = (Int16)ReadUInt16((byte)Register.dig_H2);
            H3 = ReadByte((byte)Register.dig_H3);
            H4 = (short)(ReadByte((byte)Register.dig_H4) << 4 | ReadByte((byte)Register.dig_H4 + 1) & 0xf);
            H5 = (short)(ReadByte((byte)Register.dig_H5 + 1) << 4 | ReadByte((byte)Register.dig_H5) >> 4);
            H6 = (sbyte)ReadByte((byte)Register.dig_H6);

            //Timerのセット(1秒毎)
            periodicTimer = new Timer(this.TimerCallback, null, 0, 1000);
        }
Ejemplo n.º 26
0
        /// <summary>
        ///     Create a new HIH6130 object using the default parameters for the component.
        /// </summary>
        /// <param name="address">Address of the HIH6130 (default = 0x27).</param>
        /// <param name="i2cBus">I2C bus (default = 100 KHz).</param>
        public Hih6130(string i2cBus, byte address = 0x27)
        {
            var settings   = new I2cConnectionSettings(address, 100_000); //The slave's address and the bus speed.
            var controller = I2cController.FromName(i2cBus);

            hih6130 = controller.GetDevice(settings);
            //hih6130 = new I2cPeripheral(i2cBus, address);
        }
Ejemplo n.º 27
0
        public Ags01Db(string i2cBus, byte address = 0x11)
        {
            var settings   = new I2cConnectionSettings(address, 100_000); //The slave's address and the bus speed.
            var controller = I2cController.FromName(i2cBus);

            sensor = controller.GetDevice(settings);
            //sensor = new I2cPeripheral(i2cBus, address);
        }
Ejemplo n.º 28
0
        public Ds1307(string i2cBus)
        {
            var settings   = new I2cConnectionSettings(Address, 100_000); //The slave's address and the bus speed.
            var controller = I2cController.FromName(i2cBus);

            _bus = controller.GetDevice(settings);
            //_bus = bus;
        }
Ejemplo n.º 29
0
        /// <summary>
        ///     Create a new SHT31D object.
        /// </summary>
        /// <param name="address">Sensor address (should be 0x44 or 0x45).</param>
        /// <param name="i2cBus">I2cBus (0-1000 KHz).</param>
        public Sht31D(string i2cBus, byte address = 0x44)
        {
            var settings   = new I2cConnectionSettings(address, 100_000); //The slave's address and the bus speed.
            var controller = I2cController.FromName(i2cBus);

            sht31d = controller.GetDevice(settings);
            //sht31d = new I2cPeripheral(i2cBus, address);
        }
Ejemplo n.º 30
0
        private async void Init()
        {
            // The code below should work the same with any provider, including Lightning and the default one.
            //I2cController controller = await I2cController.GetDefaultAsync();
            I2cController controller = (await I2cController.GetControllersAsync(LightningI2cProvider.GetI2cProvider()))[0];

            sensor = controller.GetDevice(new I2cConnectionSettings(0x90 >> 1));
        }