public Si7021(I2cDevice i2cDevice) { _i2cDevice = i2cDevice; }
/// <summary> /// Initiates the IO Port analog and capacitive touch functions. /// </summary> private async void Initialize() { try { I2cConnectionSettings settings = new I2cConnectionSettings(MCU_I2C_ADDRESS) { BusSpeed = I2cBusSpeed.StandardMode, SharingMode = I2cSharingMode.Shared }; DeviceInformationCollection dis = await DeviceInformation.FindAllAsync(I2cDevice.GetDeviceSelector("I2C1")); mcuIO = await I2cDevice.FromIdAsync(dis[0].Id, settings); } catch (Exception) { throw; } }
public AXP202(I2cDevice i2c) : base(i2c) { Initialize(); }
/// <summary> /// Instantiates a new <see cref="Scd4x"/>. /// </summary> /// <param name="device">The I²C device to operate on.</param> public Scd4x(I2cDevice device) { _device = device; Reset(); }
/// <summary> /// Initialize a new instance of the <see cref="Bme680"/> class. /// </summary> /// <param name="i2cDevice">The <see cref="I2cDevice"/> to create with.</param> public Bme680(I2cDevice i2cDevice) : base(DeviceId, i2cDevice) { _communicationProtocol = CommunicationProtocol.I2c; }
private static I2cDevice CreateI2cDevice() { var settings = new I2cConnectionSettings(1, I2cAddress); return(I2cDevice.Create(settings)); }
/// <summary> /// The CCS811 sensor constructor /// </summary> /// <param name="i2cDevice">A valid I2C device</param> /// <param name="gpioController">An optional controller, either the default one will be used, either none will be created if any pin is used</param> /// <param name="pinWake">An awake pin, it is optional, this pin can be set to the ground if the sensor is always on</param> /// <param name="pinInterruption">An interruption pin when a measurement is ready, best use when you specify a threshold</param> /// <param name="pinReset">An optional hard reset pin</param> /// <param name="shouldDispose">Should the GPIO controller be disposed at the end</param> public Ccs811Sensor(I2cDevice i2cDevice, GpioController?gpioController = null, int pinWake = -1, int pinInterruption = -1, int pinReset = -1, bool shouldDispose = true) { _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice)); _pinWake = pinWake; _pinInterruption = pinInterruption; _pinReset = pinReset; // We need a GPIO controller only if we are using any of the pin if ((_pinInterruption >= 0) || (_pinReset >= 0) || (_pinWake >= 0)) { _shouldDispose = _shouldDispose || gpioController is null; _controller = gpioController ?? new GpioController(); } if (_controller is object) { _controller.OpenPin(_pinWake, PinMode.Output); _controller.Write(_pinWake, PinValue.High); } if (_controller is object && _pinReset >= 0) { _controller.OpenPin(_pinReset, PinMode.Output); _controller.Write(_pinReset, PinValue.Low); // Delays from documentation CCS811-Datasheet.pdf page 8 // 15 micro second DelayHelper.DelayMicroseconds(15, true); _controller.Write(_pinReset, PinValue.High); // Need to wait at least 2 milliseconds before executing anything I2C Thread.Sleep(2); } // Initialization flow page 29 // https://www.sciosense.com/wp-content/uploads/2020/01/CCS811-Application-Note-Programming-and-interfacing-guide.pdf // do a soft reset Span <byte> toReset = stackalloc byte[4] { 0x11, 0xE5, 0x72, 0x8A }; WriteRegister(Register.SW_RESET, toReset); // Wait 2 milliseconds as per documentation Thread.Sleep(2); if (HardwareIdentification != 0x81) { throw new IOException($"CCS811 does not have a valid ID: {HardwareIdentification}. ID must be 0x81."); } if ((HardwareVersion & 0xF0) != 0x10) { throw new IOException($"CCS811 does not have a valid version: {HardwareVersion}, should be 0x1X where any X is valid."); } // Read status if (!Status.HasFlag(Status.APP_VALID)) { throw new IOException($"CCS811 has no application firmware loaded."); } // Switch to app mode and wait 1 millisecond according to doc WriteRegister(Register.APP_START); Thread.Sleep(1); if (!Status.HasFlag(Status.FW_MODE)) { throw new IOException($"CCS811 is not in application mode."); } // Set interrupt if the interruption pin is valid if (_controller is object && _pinInterruption >= 0) { _controller.OpenPin(_pinInterruption, PinMode.Input); byte mode = 0b0000_1000; WriteRegister(Register.MEAS_MODE, mode); _controller.RegisterCallbackForPinValueChangedEvent(_pinInterruption, PinEventTypes.Falling, InterruptReady); _running = true; // Start a new thread to monitor the events new Thread(() => { _isRunning = true; while (_running) { var res = _controller.WaitForEvent(_pinInterruption, PinEventTypes.Falling, new TimeSpan(0, 0, 0, 0, 50)); if ((!res.TimedOut) && (res.EventTypes != PinEventTypes.None)) { InterruptReady(_controller, new PinValueChangedEventArgs(res.EventTypes, _pinInterruption)); // We know we won't get any new measurement in next 250 milliseconds at least // Waiting to make sure the sensor will have time to remove the interrupt pin Thread.Sleep(50); } } _isRunning = false; }).Start(); } }
/// <summary> /// Constructs Mcp3427 instance /// </summary> /// <param name="i2CDevice">I2C device used to communicate with the device</param> public Mcp3427(I2cDevice i2CDevice) : base(i2CDevice, NumChannels) { }
/// <summary> /// Constructs Mcp3427 instance /// </summary> /// <param name="i2CDevice">I2C device used to communicate with the device</param> /// <param name="mode">ADC operation mode</param> /// <param name="resolution">ADC resolution</param> /// <param name="pgaGain">PGA gain</param> public Mcp3427(I2cDevice i2CDevice, AdcMode mode = AdcMode.Continuous, AdcResolution resolution = AdcResolution.Bit12, AdcGain pgaGain = AdcGain.X1) : this(i2CDevice) => SetConfig(0, mode: mode, resolution: resolution, pgaGain: pgaGain);
/// <summary> /// Create a DHT sensor through I2C (Only DHT12) /// </summary> /// <param name="i2cDevice">The I2C device used for communication.</param> public DhtBase(I2cDevice i2cDevice) { _protocol = CommunicationProtocol.I2C; _i2cDevice = i2cDevice; }
public MS5837Driver(I2cDevice device, MS5837Model model = MS5837Model.MS583730BA) { _model = model; _device = device ?? throw new ArgumentNullException(nameof(device)); }
public static void Main() { Console.WriteLine($".Net IoT with BMP280 Sensor!"); // set up for LED and pin using GpioController led = new(); led.OpenPin(Pin, PinMode.Output); // setup for BMP280 I2cConnectionSettings i2cSettings = new(BusId, Bmp280.DefaultI2cAddress); I2cDevice i2cDevice = I2cDevice.Create(i2cSettings); using var i2CBmp280 = new Bmp280(i2cDevice); // Create an X.509 certificate object. var cert = new X509Certificate2($"{DeviceID}.pfx", "1234"); var auth = new DeviceAuthenticationWithX509Certificate(DeviceID, cert); DeviceClient?azureIoTClient = DeviceClient.Create(IotBrokerAddress, auth, TransportType.Mqtt); if (azureIoTClient == null) { Console.WriteLine("Failed to create DeviceClient!"); } else { Console.WriteLine("Successfully created DeviceClient!"); Console.WriteLine("Press CTRL+D to stop application"); } while (true) // while(!Console.KeyAvailable) if you're using the app via external console { try { // set higher sampling and perform a synchronous measurement i2CBmp280.TemperatureSampling = Sampling.LowPower; i2CBmp280.PressureSampling = Sampling.UltraHighResolution; var readResult = i2CBmp280.Read(); // led on led.Write(Pin, PinValue.High); Thread.Sleep(LightTime); // print out the measured data string?temperature = readResult.Temperature?.DegreesCelsius.ToString("F"); string?pressure = readResult.Pressure?.Hectopascals.ToString("F"); Console.WriteLine("-----------------------------------------"); Console.WriteLine($"Temperature: {temperature}\u00B0C"); Console.WriteLine($"Pressure: {pressure}hPa"); // send to Iot Hub string message = $"{{\"Temperature\":{temperature},\"Pressure\":{pressure},\"DeviceID\":\"{DeviceID}\"}}"; Message eventMessage = new Message(Encoding.UTF8.GetBytes(message)); azureIoTClient?.SendEventAsync(eventMessage).Wait(); Console.WriteLine($"Data is pushed to Iot Hub: {message}"); // blink led after reading value led.Write(Pin, PinValue.Low); Thread.Sleep(75); led.Write(Pin, PinValue.High); Thread.Sleep(75); led.Write(Pin, PinValue.Low); Thread.Sleep(75); led.Write(Pin, PinValue.High); Thread.Sleep(75); led.Write(Pin, PinValue.Low); Thread.Sleep(DimTime); } catch (Exception ex) { Console.WriteLine($"An error occured: {ex.Message}"); } } }
/// <summary> /// Initializes a new instance of the Pca8574 device. /// </summary> /// <param name="device">The I2C device.</param> /// <param name="interrupt">The interrupt pin number, if present.</param> /// <param name="gpioController"> /// The GPIO controller for the <paramref name="interrupt"/>. /// If not specified, the default controller will be used. /// </param> /// <param name="shouldDispose">True to dispose the Gpio Controller</param> public Pcf8574(I2cDevice device, int interrupt = -1, GpioController gpioController = null, bool shouldDispose = true) : base(device, interrupt, gpioController, shouldDispose) { }
public void Dispose() { _i2cDevice?.Dispose(); _i2cDevice = null; }
/// <summary> /// Open a connection with the Servo Pi /// </summary> /// <returns></returns> /// <example>servopi.Connect();</example> public async Task Connect() { /* Initialize the I2C bus */ try { string aqs = I2cDevice.GetDeviceSelector(helper.I2C_CONTROLLER_NAME); /* Find the selector string for the I2C bus controller */ var dis = await DeviceInformation.FindAllAsync(aqs); /* Find the I2C bus controller device with our selector string */ var settings = new I2cConnectionSettings(Address); settings.BusSpeed = I2cBusSpeed.FastMode; i2cbus = await I2cDevice.FromIdAsync(dis[0].Id, settings); /* Create an I2cDevice with our selected bus controller and I2C settings */ if (i2cbus != null) { // Connection is established so set IsConnected to true IsConnected = true; helper.WriteI2CByte(i2cbus, MODE1, 0x00); // Check to see if the output pin has been set and if so try to connect to the GPIO pin on the Raspberry Pi if (OutputEnablePin != 0) { gpio = GpioController.GetDefault(); if (gpio != null) { GpioOpenStatus status; gpio.TryOpenPin(OutputEnablePin, GpioSharingMode.Exclusive, out pin, out status); if (status == GpioOpenStatus.PinOpened) { // Latch HIGH value first. This ensures a default value when the pin is set as output pin.Write(GpioPinValue.High); // Set the IO direction as output pin.SetDriveMode(GpioPinDriveMode.Output); } } } // Fire the Connected event handler EventHandler handler = Connected; if (handler != null) { handler(this, EventArgs.Empty); } } else { IsConnected = false; } return; } /* If initialization fails, display the exception and stop running */ catch (Exception e) { IsConnected = false; throw e; } }
private async void InitializeSystem() { byte[] i2CWriteBuffer; byte[] i2CReadBuffer; byte bitMask; // initialize I2C communications string deviceSelector = I2cDevice.GetDeviceSelector(); var i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector); if (i2cDeviceControllers.Count == 0) { ButtonStatusText.Text = "No I2C controllers were found on this system."; return; } var i2cSettings = new I2cConnectionSettings(PORT_EXPANDER_I2C_ADDRESS); i2cSettings.BusSpeed = I2cBusSpeed.FastMode; i2cPortExpander = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings); if (i2cPortExpander == null) { ButtonStatusText.Text = string.Format( "Slave address {0} is currently in use on {1}. " + "Please ensure that no other applications are using I2C.", i2cSettings.SlaveAddress, i2cDeviceControllers[0].Id); return; } // 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(); }
private async Task <bool> init() { // initialize I2C communications string deviceSelector = I2cDevice.GetDeviceSelector(); var i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector); if (i2cDeviceControllers.Count == 0) { throw new Exception("No I2C controllers were found on this system."); } var i2cSettings = new I2cConnectionSettings(PORT_EXPANDER_I2C_ADDRESS); i2cSettings.BusSpeed = I2cBusSpeed.FastMode; i2cPortExpander = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings); if (i2cPortExpander == null) { throw new Exception(string.Format( "Slave address {0} is currently in use on {1}. " + "Please ensure that no other applications are using I2C.", i2cSettings.SlaveAddress, i2cDeviceControllers[0].Id)); } // initialize I2C Port Expander registers try { GetRegisterValues(); //Disable pull up resistor i2CWriteBuffer = new byte[] { PORT_EXPANDER_GPPUA_ADDRESS, 0x00 }; i2cPortExpander.Write(i2CWriteBuffer); i2CWriteBuffer = new byte[] { PORT_EXPANDER_GPPUB_ADDRESS, 0x00 }; i2cPortExpander.Write(i2CWriteBuffer); //Set all to outputs i2CWriteBuffer = new byte[] { PORT_EXPANDER_IODIRA_REGISTER_ADDRESS, 0x00 }; i2cPortExpander.Write(i2CWriteBuffer); i2CWriteBuffer = new byte[] { PORT_EXPANDER_IODIRB_REGISTER_ADDRESS, 0x00 }; i2cPortExpander.Write(i2CWriteBuffer); //reset input polarity i2CWriteBuffer = new byte[] { PORT_EXPANDER_IPOLA_REGISTER_ADDRESS, 0x00 }; i2cPortExpander.Write(i2CWriteBuffer); i2CWriteBuffer = new byte[] { PORT_EXPANDER_IPOLB_REGISTER_ADDRESS, 0x00 }; i2cPortExpander.Write(i2CWriteBuffer); //configure device for open-drain output on the interrupt pin i2CWriteBuffer = new byte[] { PORT_EXPANDER_IOCON_ADDRESS, 0x02 }; i2cPortExpander.Write(i2CWriteBuffer); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); return(false); //throw new Exception("Failed to initialize I2C port expander: " + e.Message); } return(true); }
public I2CHelper(I2cDevice device) { _device = device; }
private DS1307(I2cDevice i2cDevice) { _i2cDevice = i2cDevice; }
/// <summary> /// Initializes a new instance of the <see cref="Bme280"/> class. /// </summary> /// <param name="i2cDevice">The <see cref="I2cDevice"/> to create with.</param> public Bme280(I2cDevice i2cDevice) : base(DeviceId, i2cDevice) { _bme280Calibration = (Bme280CalibrationData)_calibrationData; _communicationProtocol = CommunicationProtocol.I2c; }
/// <summary> /// GrovePi constructor /// </summary> /// <param name="i2cDevice">The I2C device. Device address is 0x04</param> /// <param name="shouldDispose">True to dispose the I2C device when disposing GrovePi</param> public GrovePi(I2cDevice i2cDevice, bool shouldDispose = true) { _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice)); _shouldDispose = shouldDispose; GrovePiInfo = new Info(GetFirmwareVerion()); }
private async void I2C_Switch_Toggled(object sender, RoutedEventArgs e) { if (I2C_enable.IsOn == true) { try { var settings = new I2cConnectionSettings(SHT30_I2C_addr) { BusSpeed = I2cBusSpeed.FastMode }; IReadOnlyList <DeviceInformation> devices = await DeviceInformation.FindAllAsync(I2cDevice.GetDeviceSelector()); SHT30_sensor_1 = await I2cDevice.FromIdAsync(devices[0].Id, settings); if (SHT30_sensor_1 == null) { GPIO_Info.Visibility = Visibility.Visible; GPIO_Info.Text = "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 + devices[0].Id; return; } SHT30_sensor_timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) }; SHT30_sensor_timer.Tick += SHT30_sensor_tick; SHT30_sensor_timer.Start(); CurrentHumidity.Visibility = Visibility.Visible; CurrentTemp.Visibility = Visibility.Visible; } catch (Exception ex) { GPIO_Info.Visibility = Visibility.Visible; GPIO_Info.Text += "\n" + ex.Source; } } else { SHT30_sensor_1.Dispose(); SHT30_sensor_timer.Stop(); } }
/// <summary> /// /// Initializes a new instance of the Pcf8575 device. /// </summary> /// <param name="device">The I2C device.</param> /// <param name="interrupt">The interrupt pin number, if present.</param> /// <param name="gpioController"> /// The GPIO controller for the <paramref name="interrupt"/>. /// If not specified, the default controller will be used. /// </param> public Pcf8575(I2cDevice device, int interrupt = -1, IGpioController gpioController = null) : base(device, interrupt, gpioController) { }
public void Dispose() { _i2c?.Dispose(); _i2c = null; }
/// <summary> /// Initiates the transreceiver function. /// <paramref name="enableReception">True for enable IR decoding. False for disable IR decoding.</param> /// </summary> private async void Initialize(bool enableReception) { try { I2cConnectionSettings settings = new I2cConnectionSettings(MCU_I2C_ADDRESS); settings.BusSpeed = I2cBusSpeed.FastMode; settings.SharingMode = I2cSharingMode.Shared; DeviceInformationCollection dis = await DeviceInformation.FindAllAsync(I2cDevice.GetDeviceSelector("I2C1")); mcuIR = await I2cDevice.FromIdAsync(dis[0].Id, settings); await SetIRReception(enableReception); } catch (Exception e) { throw; } }
/// <summary>Creates a new instance of the PiJuice.</summary> /// <param name="i2cDevice">The I2C device. Device address is 0x14</param> /// <param name="shouldDispose">True to dispose the I2C device</param> public PiJuice(I2cDevice i2cDevice, bool shouldDispose = true) { _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice)); _shouldDispose = shouldDispose; PiJuiceInfo = new PiJuiceInfo(GetFirmwareVersion()); }
/// <summary> /// Initializes new instance of Ssd1306 device that will communicate using I2C bus. /// A single-chip CMOS OLED/PLED driver with controller for organic/polymer /// light emitting diode dot-matrix graphic display system. /// </summary> /// <param name="i2cDevice">The I2C device used for communication.</param> public Ssd1306(I2cDevice i2cDevice) : base(i2cDevice) { }
public ImuSensor() { _peripheralManagerService = new PeripheralManagerService(); _rawDevice = _peripheralManagerService.OpenI2cDevice(_peripheralManagerService.I2cBusList.First(), ADDRESS0); }
// While the LCD controller can be set to 4 bit mode there really isn't a way to // mess with that from the I2c pins as far as I know. Other drivers try to set the // controller up for 8 bit mode, but it appears they are doing so only because they've // copied existing HD44780 drivers. public I2c(I2cDevice device) => _device = device;
public MainI2CDevice(I2cDevice device) { _device = device; }