Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello Bme280!");

            //bus id on the raspberry pi 3
            const int busId = 1;
            //set this to the current sea level pressure in the area for correct altitude readings
            const double defaultSeaLevelPressure = 1033.00;

            var i2cSettings = new I2cConnectionSettings(busId, Bme280.DefaultI2cAddress);
            var i2cDevice   = I2cDevice.Create(i2cSettings);
            var i2CBmpe80   = new Bme280(i2cDevice);

            using (i2CBmpe80)
            {
                while (true)
                {
                    //set higher sampling
                    i2CBmpe80.TemperatureSampling = Sampling.LowPower;
                    i2CBmpe80.PressureSampling    = Sampling.UltraHighResolution;
                    i2CBmpe80.HumiditySampling    = Sampling.Standard;

                    //set mode forced so device sleeps after read
                    i2CBmpe80.SetPowerMode(Bmx280PowerMode.Forced);

                    // wait for measurement to be performed
                    var measurementTime = i2CBmpe80.GetMeasurementDuration();
                    Thread.Sleep(measurementTime);

                    //read values
                    i2CBmpe80.TryReadTemperature(out var tempValue);
                    Console.WriteLine($"Temperature: {tempValue.Celsius} C");
                    i2CBmpe80.TryReadPressure(out var preValue);
                    Console.WriteLine($"Pressure: {preValue} Pa");
                    i2CBmpe80.TryReadAltitude(defaultSeaLevelPressure, out var altValue);
                    Console.WriteLine($"Altitude: {altValue} meters");
                    i2CBmpe80.TryReadHumidity(out var humValue);
                    Console.WriteLine($"Humidity: {humValue} %");
                    Thread.Sleep(1000);

                    //change sampling and filter
                    i2CBmpe80.TemperatureSampling = Sampling.UltraHighResolution;
                    i2CBmpe80.PressureSampling    = Sampling.UltraLowPower;
                    i2CBmpe80.HumiditySampling    = Sampling.UltraLowPower;
                    i2CBmpe80.FilterMode          = Bmx280FilteringMode.X2;

                    //set mode forced and read again
                    i2CBmpe80.SetPowerMode(Bmx280PowerMode.Forced);

                    // wait for measurement to be performed
                    measurementTime = i2CBmpe80.GetMeasurementDuration();
                    Thread.Sleep(measurementTime);

                    //read values
                    i2CBmpe80.TryReadTemperature(out tempValue);
                    Console.WriteLine($"Temperature: {tempValue.Celsius} C");
                    i2CBmpe80.TryReadPressure(out preValue);
                    Console.WriteLine($"Pressure: {preValue} Pa");
                    i2CBmpe80.TryReadAltitude(defaultSeaLevelPressure, out altValue);
                    Console.WriteLine($"Altitude: {altValue} meters");
                    i2CBmpe80.TryReadHumidity(out humValue);
                    Console.WriteLine($"Humidity: {humValue} %");
                    Thread.Sleep(5000);
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Entry point for example program
        /// </summary>
        /// <param name="args">Command line arguments</param>
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello Bmp280!");

            Length stationHeight = Length.FromMeters(640); // Elevation of the sensor

            // bus id on the raspberry pi 3 and 4
            const int busId = 1;
            // set this to the current sea level pressure in the area for correct altitude readings
            var defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel;

            var i2cSettings = new I2cConnectionSettings(busId, Bmp280.DefaultI2cAddress);
            var i2cDevice   = I2cDevice.Create(i2cSettings);
            var i2CBmp280   = new Bmp280(i2cDevice);

            using (i2CBmp280)
            {
                while (true)
                {
                    // set higher sampling
                    i2CBmp280.TemperatureSampling = Sampling.LowPower;
                    i2CBmp280.PressureSampling    = Sampling.UltraHighResolution;

                    // set mode forced so device sleeps after read
                    i2CBmp280.SetPowerMode(Bmx280PowerMode.Forced);

                    // wait for measurement to be performed
                    var measurementTime = i2CBmp280.GetMeasurementDuration();
                    Thread.Sleep(measurementTime);

                    // read values
                    i2CBmp280.TryReadTemperature(out var tempValue);
                    Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
                    i2CBmp280.TryReadPressure(out var preValue);
                    Console.WriteLine($"Pressure: {preValue.Hectopascals:0.##}hPa");

                    // Note that if you already have the pressure value and the temperature, you could also calculate altitude by using
                    // double altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue) which would be more performant.
                    i2CBmp280.TryReadAltitude(out var altValue);

                    Console.WriteLine($"Calculated Altitude: {altValue:0.##}m");
                    Thread.Sleep(1000);

                    // change sampling rate
                    i2CBmp280.TemperatureSampling = Sampling.UltraHighResolution;
                    i2CBmp280.PressureSampling    = Sampling.UltraLowPower;
                    i2CBmp280.FilterMode          = Bmx280FilteringMode.X4;

                    // set mode forced and read again
                    i2CBmp280.SetPowerMode(Bmx280PowerMode.Forced);

                    // wait for measurement to be performed
                    measurementTime = i2CBmp280.GetMeasurementDuration();
                    Thread.Sleep(measurementTime);

                    // read values
                    i2CBmp280.TryReadTemperature(out tempValue);
                    Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
                    i2CBmp280.TryReadPressure(out preValue);
                    Console.WriteLine($"Pressure: {preValue.Hectopascals:0.##}hPa");

                    // This time use altitude calculation
                    altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue);

                    Console.WriteLine($"Calculated Altitude: {altValue:0.##}m");

                    // Calculate the barometric (corrected) pressure for the local position.
                    // Change the stationHeight value above to get a correct reading, but do not be tempted to insert
                    // the value obtained from the formula above. Since that estimates the altitude based on pressure,
                    // using that altitude to correct the pressure won't work.
                    var correctedPressure = WeatherHelper.CalculateBarometricPressure(preValue, tempValue, stationHeight);

                    Console.WriteLine($"Pressure corrected for altitude {stationHeight:F0}m (with average humidity): {correctedPressure.Hectopascals:0.##} hPa");

                    Thread.Sleep(5000);
                }
            }
        }
Ejemplo n.º 3
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello Bme280!");

            //bus id on the raspberry pi 3
            const int busId = 1;
            //set this to the current sea level pressure in the area for correct altitude readings
            const double defaultSeaLevelPressure = 1033.00;

            var i2cSettings = new I2cConnectionSettings(busId, Bme280.DefaultI2cAddress);
            var i2cDevice   = I2cDevice.Create(i2cSettings);
            var i2CBmpe80   = new Bme280(i2cDevice);

            using (i2CBmpe80)
            {
                while (true)
                {
                    //set mode forced so device sleeps after read
                    i2CBmpe80.SetPowerMode(PowerMode.Forced);

                    //set samplings
                    i2CBmpe80.SetTemperatureSampling(Sampling.UltraLowPower);
                    i2CBmpe80.SetPressureSampling(Sampling.UltraLowPower);
                    i2CBmpe80.SetHumiditySampling(Sampling.UltraLowPower);

                    //read values
                    Temperature tempValue = await i2CBmpe80.ReadTemperatureAsync();

                    Console.WriteLine($"Temperature: {tempValue.Celsius} C");
                    double preValue = await i2CBmpe80.ReadPressureAsync();

                    Console.WriteLine($"Pressure: {preValue} Pa");
                    double altValue = await i2CBmpe80.ReadAltitudeAsync(defaultSeaLevelPressure);

                    Console.WriteLine($"Altitude: {altValue} meters");
                    double humValue = await i2CBmpe80.ReadHumidityAsync();

                    Console.WriteLine($"Humidity: {humValue} %");
                    Thread.Sleep(1000);

                    //set higher sampling
                    i2CBmpe80.SetTemperatureSampling(Sampling.LowPower);
                    Console.WriteLine(i2CBmpe80.ReadTemperatureSampling());
                    i2CBmpe80.SetPressureSampling(Sampling.UltraHighResolution);
                    Console.WriteLine(i2CBmpe80.ReadPressureSampling());
                    i2CBmpe80.SetHumiditySampling(Sampling.Standard);
                    Console.WriteLine(i2CBmpe80.ReadHumiditySampling());

                    i2CBmpe80.SetFilterMode(FilteringMode.Off);
                    Console.WriteLine(i2CBmpe80.ReadFilterMode());

                    //set mode forced and read again
                    i2CBmpe80.SetPowerMode(PowerMode.Forced);

                    //read values
                    tempValue = await i2CBmpe80.ReadTemperatureAsync();

                    Console.WriteLine($"Temperature: {tempValue.Celsius} C");
                    preValue = await i2CBmpe80.ReadPressureAsync();

                    Console.WriteLine($"Pressure: {preValue} Pa");
                    altValue = await i2CBmpe80.ReadAltitudeAsync(defaultSeaLevelPressure);

                    Console.WriteLine($"Altitude: {altValue} meters");
                    humValue = await i2CBmpe80.ReadHumidityAsync();

                    Console.WriteLine($"Humidity: {humValue} %");
                    Thread.Sleep(5000);

                    //set sampling to higher
                    i2CBmpe80.SetTemperatureSampling(Sampling.UltraHighResolution);
                    Console.WriteLine(i2CBmpe80.ReadTemperatureSampling());
                    i2CBmpe80.SetPressureSampling(Sampling.UltraLowPower);
                    Console.WriteLine(i2CBmpe80.ReadPressureSampling());
                    i2CBmpe80.SetHumiditySampling(Sampling.UltraLowPower);
                    Console.WriteLine(i2CBmpe80.ReadHumiditySampling());

                    i2CBmpe80.SetFilterMode(FilteringMode.X2);
                    Console.WriteLine(i2CBmpe80.ReadFilterMode());
                }
            }
        }
Ejemplo n.º 4
0
        public static void Test()
        {
            Console.WriteLine("Starting...");

#if USEI2C
            var i2cDevice  = I2cDevice.Create(new I2cConnectionSettings(busId: 1, deviceAddress: 0x21));
            var controller = new Mcp23008(i2cDevice);
            var lcd        = new Lcd1602(registerSelectPin: 1, enablePin: 2, dataPins: new int[] { 3, 4, 5, 6 }, backlightPin: 7, controller: controller);
#elif USERGB
            var i2cLcdDevice = I2cDevice.Create(new I2cConnectionSettings(busId: 1, deviceAddress: 0x3E));
            var i2cRgbDevice = I2cDevice.Create(new I2cConnectionSettings(busId: 1, deviceAddress: 0x62));
            var lcd          = new LcdRgb1602(i2cLcdDevice, i2cRgbDevice);
#else
            Hd44780 lcd = new Hd44780(new Size(20, 4), LcdInterface.CreateGpio(12, 26, new int[] { 16, 17, 18, 19, 20, 21, 22, 23 }, readWritePin: 13));
#endif
            using (lcd)
            {
                Console.WriteLine("Initialized");
                Console.ReadLine();

                TestPrompt("SetCursor", lcd, SetCursorTest);
                TestPrompt("Underline", lcd, l => l.UnderlineCursorVisible = true);
                lcd.UnderlineCursorVisible = false;
                TestPrompt("Walker", lcd, WalkerTest);
                CreateTensCharacters(lcd);
                TestPrompt("CharacterSet", lcd, CharacterSet);

                // Shifting
                TestPrompt("Autoshift", lcd, AutoShift);
                TestPrompt("DisplayLeft", lcd, l => ShiftDisplayTest(l, a => a.ShiftDisplayLeft()));
                TestPrompt("DisplayRight", lcd, l => ShiftDisplayTest(l, a => a.ShiftDisplayRight()));
                TestPrompt("CursorLeft", lcd, l => ShiftCursorTest(l, a => a.ShiftCursorLeft()));
                TestPrompt("CursorRight", lcd, l => ShiftCursorTest(l, a => a.ShiftCursorRight()));

                // Long string
                TestPrompt("Twenty", lcd, l => l.Write(Twenty));
                TestPrompt("Fourty", lcd, l => l.Write(Fourty));
                TestPrompt("Eighty", lcd, l => l.Write(Eighty));

                TestPrompt("Twenty-", lcd, l => WriteFromEnd(l, Twenty));
                TestPrompt("Fourty-", lcd, l => WriteFromEnd(l, Fourty));
                TestPrompt("Eighty-", lcd, l => WriteFromEnd(l, Eighty));

                TestPrompt("Wrap", lcd, l => l.Write(new string('*', 80) + ">>>>>"));
                TestPrompt("Perf", lcd, PerfTests);

#if USERGB
                TestPrompt("Colors", lcd, SetBacklightColorTest);
#endif

                // Shift display right
                lcd.Write("Hello .NET!");
                try
                {
                    int   state = 0;
                    Timer timer = new Timer(1000);
                    timer.Elapsed += (o, e) =>
                    {
                        lcd.SetCursorPosition(0, 1);
                        lcd.Write(DateTime.Now.ToLongTimeString() + " ");
                        if (state == 0)
                        {
                            state = 1;
                        }
                        else
                        {
                            lcd.ShiftDisplayRight();
                            state = 0;
                        }
                    };
                    timer.AutoReset = true;
                    timer.Enabled   = true;
                    Console.ReadLine();
                }
                finally
                {
                    lcd.DisplayOn   = false;
                    lcd.BacklightOn = false;
                    Console.WriteLine("Done...");
                }
            }
        }
Ejemplo n.º 5
0
        public static void MagnetometerCalibrationDeepDive(int calibrationCount)
        {
            var     mpui2CConnectionSettingmpus = new I2cConnectionSettings(1, Mpu9250.DefaultI2cAddress);
            Mpu9250 mpu9250 = new Mpu9250(I2cDevice.Create(mpui2CConnectionSettingmpus));

            mpu9250.MagnetometerOutputBitMode   = Iot.Device.Magnetometer.OutputBitMode.Output16bit;
            mpu9250.MagnetometerMeasurementMode = Iot.Device.Magnetometer.MeasurementMode.ContinuousMeasurement100Hz;
            Console.WriteLine("Please move the magnetometer during calibration");
            using (var ioWriter = new StreamWriter("mag.csv"))
            {
                // First we read the data without calibration at all
                Console.WriteLine("Reading magnetometer data without calibration");
                ioWriter.WriteLine($"X;Y;Z");
                for (int i = 0; i < calibrationCount; i++)
                {
                    try
                    {
                        var magne = mpu9250.ReadMagnetometerWithoutCorrection();
                        ioWriter.WriteLine($"{magne.X};{magne.Y};{magne.Z}");
                        // 10 ms = 100Hz, so waiting to make sure we have new data
                        Thread.Sleep(10);
                    }
                    catch (TimeoutException)
                    {
                        Console.WriteLine("Error reading");
                    }
                }

                Console.WriteLine("Performing calibration");
                // then we calibrate
                var magnetoBias = mpu9250.CalibrateMagnetometer(calibrationCount);
                ioWriter.WriteLine();
                ioWriter.WriteLine("Factory calibration data");
                ioWriter.WriteLine($"X;Y;Z");
                ioWriter.WriteLine($"{magnetoBias.X};{magnetoBias.Y};{magnetoBias.Z}");
                ioWriter.WriteLine();
                ioWriter.WriteLine("Magnetometer bias calibration data");
                ioWriter.WriteLine($"X;Y;Z");
                ioWriter.WriteLine($"{mpu9250.MagnometerBias.X};{mpu9250.MagnometerBias.Y};{mpu9250.MagnometerBias.Z}");
                ioWriter.WriteLine();
                // Finally we read the data again
                Console.WriteLine("Reading magnetometer data including calibration");
                ioWriter.WriteLine($"X corr;Y corr;Z corr");
                for (int i = 0; i < calibrationCount; i++)
                {
                    try
                    {
                        var magne = mpu9250.ReadMagnetometer();
                        ioWriter.WriteLine($"{magne.X};{magne.Y};{magne.Z}");
                        // 10 ms = 100Hz, so waiting to make sure we have new data
                        Thread.Sleep(10);
                    }
                    catch (TimeoutException)
                    {
                        Console.WriteLine("Error reading");
                    }
                }
            }

            Console.WriteLine("Calibration deep dive over, file name is mag.csv");
        }
Ejemplo n.º 6
0
 public I2cDevice GetOrCreateI2CDevice(int deviceAddress)
 {
     return(_i2cBusses.GetOrAdd(deviceAddress, address => I2cDevice.Create(new I2cConnectionSettings(I2CBusId, deviceAddress))));
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Example program main entry point
        /// </summary>
        /// <param name="args">Command line arguments, see <see cref="PrintHelp"/></param>
        public static void Main(string[] args)
        {
            var busId = 1;
            var selectedI2cAddress = 0b000000; // A5 A4 A3 A2 A1 A0
            var deviceAddress      = Pca9685.I2cAddressBase + selectedI2cAddress;

            var settings = new I2cConnectionSettings(busId, deviceAddress);
            var device   = I2cDevice.Create(settings);

            using (var pca9685 = new Pca9685(device))
            {
                Console.WriteLine(
                    $"PCA9685 is ready on I2C bus {device.ConnectionSettings.BusId} with address {device.ConnectionSettings.DeviceAddress}");
                Console.WriteLine($"PWM Frequency: {pca9685.PwmFrequency}Hz");
                Console.WriteLine();
                PrintHelp();

                while (true)
                {
                    var command = Console.ReadLine().ToLower().Split(' ');
                    if (string.IsNullOrEmpty(command[0]))
                    {
                        return;
                    }

                    switch (command[0][0])
                    {
                    case 'q':
                        pca9685.SetDutyCycleAllChannels(0.0);
                        return;

                    case 'f':
                    {
                        var freq = double.Parse(command[1]);
                        pca9685.PwmFrequency = freq;
                        Console.WriteLine($"PWM Frequency has been set to {pca9685.PwmFrequency}Hz");
                        break;
                    }

                    case 'd':
                    {
                        switch (command.Length)
                        {
                        case 2:
                        {
                            double value = double.Parse(command[1]);
                            pca9685.SetDutyCycleAllChannels(value);
                            Console.WriteLine($"PWM duty cycle has been set to {value}");
                            break;
                        }

                        case 3:
                        {
                            int    channel = int.Parse(command[1]);
                            double value   = double.Parse(command[2]);
                            pca9685.SetDutyCycle(channel, value);
                            Console.WriteLine($"PWM duty cycle has been set to {value}");
                            break;
                        }
                        }

                        break;
                    }

                    case 'h':
                    {
                        PrintHelp();
                        break;
                    }

                    case 't':
                    {
                        int channel = int.Parse(command[1]);
                        ServoDemo(pca9685, channel);
                        PrintHelp();
                        break;
                    }
                    }
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Entry point for example program
        /// </summary>
        /// <param name="args">Command line arguments</param>
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello Bme280!");

            // bus id on the raspberry pi 3
            const int busId = 1;
            // set this to the current sea level pressure in the area for correct altitude readings
            var defaultSeaLevelPressure = Pressure.MeanSeaLevel;

            var i2cSettings = new I2cConnectionSettings(busId, Bme280.DefaultI2cAddress);
            var i2cDevice   = I2cDevice.Create(i2cSettings);
            var i2CBmpe80   = new Bme280(i2cDevice);

            using (i2CBmpe80)
            {
                while (true)
                {
                    // set higher sampling
                    i2CBmpe80.TemperatureSampling = Sampling.LowPower;
                    i2CBmpe80.PressureSampling    = Sampling.UltraHighResolution;
                    i2CBmpe80.HumiditySampling    = Sampling.Standard;

                    // set mode forced so device sleeps after read
                    i2CBmpe80.SetPowerMode(Bmx280PowerMode.Forced);

                    // wait for measurement to be performed
                    var measurementTime = i2CBmpe80.GetMeasurementDuration();
                    Thread.Sleep(measurementTime);

                    // read values
                    i2CBmpe80.TryReadTemperature(out var tempValue);
                    i2CBmpe80.TryReadPressure(out var preValue);
                    i2CBmpe80.TryReadHumidity(out var humValue);

                    // Note that if you already have the pressure value and the temperature, you could also calculate altitude by using
                    // var altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue) which would be more performant.
                    i2CBmpe80.TryReadAltitude(defaultSeaLevelPressure, out var altValue);

                    Console.WriteLine($"Temperature: {tempValue.Celsius:0.#}\u00B0C");
                    Console.WriteLine($"Pressure: {preValue.Hectopascal:0.##}hPa");
                    Console.WriteLine($"Altitude: {altValue:0.##}m");
                    Console.WriteLine($"Relative humidity: {humValue:0.#}%");

                    // WeatherHelper supports more calculations, such as saturated vapor pressure, actual vapor pressure and absolute humidity.
                    Console.WriteLine($"Heat index: {WeatherHelper.CalculateHeatIndex(tempValue, humValue).Celsius:0.#}\u00B0C");
                    Console.WriteLine($"Dew point: {WeatherHelper.CalculateDewPoint(tempValue, humValue).Celsius:0.#}\u00B0C");
                    Thread.Sleep(1000);

                    // change sampling and filter
                    i2CBmpe80.TemperatureSampling = Sampling.UltraHighResolution;
                    i2CBmpe80.PressureSampling    = Sampling.UltraLowPower;
                    i2CBmpe80.HumiditySampling    = Sampling.UltraLowPower;
                    i2CBmpe80.FilterMode          = Bmx280FilteringMode.X2;

                    // set mode forced and read again
                    i2CBmpe80.SetPowerMode(Bmx280PowerMode.Forced);

                    // wait for measurement to be performed
                    measurementTime = i2CBmpe80.GetMeasurementDuration();
                    Thread.Sleep(measurementTime);

                    // read values
                    i2CBmpe80.TryReadTemperature(out tempValue);
                    i2CBmpe80.TryReadPressure(out preValue);
                    i2CBmpe80.TryReadHumidity(out humValue);

                    // Note that if you already have the pressure value and the temperature, you could also calculate altitude by using
                    // var altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue) which would be more performant.
                    i2CBmpe80.TryReadAltitude(defaultSeaLevelPressure, out altValue);

                    Console.WriteLine($"Temperature: {tempValue.Celsius:0.#}\u00B0C");
                    Console.WriteLine($"Pressure: {preValue.Hectopascal:0.##}hPa");
                    Console.WriteLine($"Altitude: {altValue:0.##}m");
                    Console.WriteLine($"Relative humidity: {humValue:0.#}%");

                    // WeatherHelper supports more calculations, such as saturated vapor pressure, actual vapor pressure and absolute humidity.
                    Console.WriteLine($"Heat index: {WeatherHelper.CalculateHeatIndex(tempValue, humValue).Celsius:0.#}\u00B0C");
                    Console.WriteLine($"Dew point: {WeatherHelper.CalculateDewPoint(tempValue, humValue).Celsius:0.#}\u00B0C");
                    Thread.Sleep(5000);
                }
            }
        }
        public Result <Unit> Init()
        {
            _controller = new GpioController(PinNumberingScheme.Logical, new RaspberryPi3Driver());
            _controller.OpenPin(Pin.HallBottom, PinMode.InputPullUp);
            _controller.OpenPin(Pin.HallTop, PinMode.InputPullUp);
            _controller.OpenPin(Pin.PhotoelectricBarrier, PinMode.InputPullUp);
            _controller.OpenPin(Pin.MotorEnable, PinMode.Output);
            _controller.OpenPin(Pin.MotorLeft, PinMode.Output);
            _controller.OpenPin(Pin.MotorRight, PinMode.Output);
            _controller.OpenPin(Pin.EmergencyTop, PinMode.InputPullUp);
            _controller.OpenPin(Pin.DC12_1, PinMode.Output);
            _controller.OpenPin(Pin.DC12_2, PinMode.Output);

            //_pwmMotor = new SoftwarePwmChannel(Pin.MotorEnable, 200, 0.1);
            //_pwmMotor.Start();

            _controller.Write(Pin.MotorEnable, PinValue.High);

            _controller.Write(Pin.MotorLeft, PinValue.Low);
            _controller.Write(Pin.MotorRight, PinValue.Low);
            _controller.Write(Pin.DC12_1, PinValue.Low);
            _controller.Write(Pin.DC12_2, PinValue.Low);


            Console.WriteLine($"Init sensor");

            _bh1750Fvi = new Bh1750fvi(I2cDevice.Create(new I2cConnectionSettings(1, Bh1750fviExtenstion.DefaultI2cAddress))); // 23

            _vl53L0X = new Vl53L0X(I2cDevice.Create(new I2cConnectionSettings(1, Vl53L0X.DefaultI2cAddress)));                 // 29

            _bme280 = new Bme280(I2cDevice.Create(new I2cConnectionSettings(1, Bmx280Base.SecondaryI2cAddress)));              // 76

            _measurementTime = _bme280.GetMeasurementDuration();
            _bme280.SetPowerMode(Bmx280PowerMode.Normal);
            //Thread.Sleep(_measurementTime);

            //_bme280.TryReadTemperature(out var tempValue);
            //_bme280.TryReadPressure(out var preValue);
            //_bme280.TryReadHumidity(out var humValue);
            //_bme280.TryReadAltitude(out var altValue);

            //Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
            //Console.WriteLine($"Pressure: {preValue.Hectopascals:#.##} hPa");
            //Console.WriteLine($"Relative humidity: {humValue.Percent:#.##}%");
            //Console.WriteLine($"Estimated altitude: {altValue.Meters:#} m");

            _amg88xx = new Amg88xx(I2cDevice.Create(new I2cConnectionSettings(1, Amg88xx.AlternativeI2cAddress))); // 69

            try
            {
                _mpu9250 = new Mpu9250(I2cDevice.Create(new I2cConnectionSettings(1, Mpu6500.DefaultI2cAddress))); // 68
            }
            catch (IOException e)
            {
                Console.WriteLine("AK8963 is exposed, try to connect directly.");
                _mpu9250 = new Mpu9250(I2cDevice.Create(new I2cConnectionSettings(1, Mpu6500.DefaultI2cAddress)), i2CDeviceAk8963: I2cDevice.Create(new I2cConnectionSettings(1, Ak8963.DefaultI2cAddress)));
            }

            _mpu9250.MagnetometerMeasurementMode = MeasurementMode.ContinuousMeasurement100Hz;

            Thread.Sleep(100);


            Console.WriteLine($"Finished Init sensor");

            Run();

            Thread.Sleep(100);

            Calibrate();

            return(Unit.Instance);
        }
        private static I2cDevice CreateI2cDevice()
        {
            I2cConnectionSettings settings = new(1, I2cAddress);

            return(I2cDevice.Create(settings));
        }
Ejemplo n.º 11
0
        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)
            {
                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 and led off
                    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}");
                }
            }
        }
Ejemplo n.º 12
0
 public PwmController(int busId = 1, int address = 0x40)
 {
     this.i2cDevice = I2cDevice.Create(new I2cConnectionSettings(busId, address));
 }
Ejemplo n.º 13
0
 public void Init()
 {
     _i2c = I2cDevice.Create(new I2cConnectionSettings(1, 0x27));
     _mcp = new Mcp23008(_i2c);
     _lcd = new Lcd2004(registerSelectPin: 0, enablePin: 2, dataPins: new int[] { 4, 5, 6, 7 }, backlightPin: 3, backlightBrightness: 0.1f, readWritePin: 1, controller: _mcp);
 }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            var busId = 1;  // /dev/i2c-1

            var deviceAddress_fixed      = 0x40;
            var deviceAddress_selectable = 0b000000;    // A5 A4 A3 A2 A1 A0
            var deviceAddress            = deviceAddress_fixed | deviceAddress_selectable;

            var settings = new I2cConnectionSettings(busId, deviceAddress);
            var device   = I2cDevice.Create(settings);

            using (var pca9685 = new Pca9685(device))
            {
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"PCA9685 is ready on I2C bus {device.ConnectionSettings.BusId} with address {device.ConnectionSettings.DeviceAddress}");

                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Command:  F {freq_hz}             set PWM frequency");
                Console.WriteLine("          P {prescale}            set PRE_SCALE register");
                Console.WriteLine("          S {off}                 set off step with on step is 0 to all channels");
                Console.WriteLine("          S {on} {off}            set on step and off step to all channels");
                Console.WriteLine("          S {on} {off} {channel}  set on step and off step to specified channel");

                Console.WriteLine();
                while (true)
                {
                    try
                    {
                        Console.ResetColor();
                        Console.Write("> ");
                        var command = Console.ReadLine().ToLower().Split(' ');

                        switch (command[0][0])
                        {
                        case 'f':       // set PWM frequency
                        {
                            var freq = double.Parse(command[1]);
                            pca9685.PwmFrequency = freq;

                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine($"PWM Frequency has been set to about {pca9685.PwmFrequency}Hz with prescale is {pca9685.Prescale}");
                            break;
                        }

                        case 'p':       // set PRE_SCALE register
                        {
                            var prescale = (byte)int.Parse(command[1]);
                            pca9685.Prescale = prescale;

                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine($"PWM Frequency has been set to about {pca9685.PwmFrequency}Hz with prescale is {pca9685.Prescale}");
                            break;
                        }

                        case 's':       // set PWM steps
                        {
                            switch (command.Length)
                            {
                            case 2:             // 1 parameter : set off step with on step is 0 to all channels
                            {
                                var off = int.Parse(command[1]);
                                pca9685.SetPwm(0, off);

                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine($"PWM pulse width has been set to {off}/4096");
                                break;
                            }

                            case 3:             // 2 parametes : set on step and off step to all channels
                            {
                                var on  = int.Parse(command[1]);
                                var off = int.Parse(command[2]);
                                pca9685.SetPwm(on, off);

                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine($"PWM pulse pull up at step {on} and pull down at step {off} on all channels");
                                break;
                            }

                            case 4:             // 3 parametes : set on step and off step to specified channel
                            {
                                var on      = int.Parse(command[1]);
                                var off     = int.Parse(command[2]);
                                var channel = int.Parse(command[3]);
                                pca9685.SetPwm(on, off, channel);

                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine($"PWM pulse pull up at step {on} and pull down at step {off} on channel {channel}");
                                break;
                            }
                            }
                            break;
                        }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(ex.GetBaseException().Message);
                        Console.ResetColor();
                    }
                }
            }
        }
Ejemplo n.º 15
0
        public static void Main(string[] args)
        {
            // set I2C bus ID: 1
            // ADS1115 Addr Pin connect to GND
            I2cConnectionSettings settings = new I2cConnectionSettings(1, (int)I2cAddress.GND);
            // get I2cDevice (in Linux)
            I2cDevice device = I2cDevice.Create(settings);

            Console.WriteLine("Press any key to continue");
            // pass in I2cDevice
            // repeatedly measure the voltage AIN0
            // set the maximum range to 4.096V
            using (Iot.Device.Ads1115.Ads1115 adc = new Iot.Device.Ads1115.Ads1115(device, InputMultiplexer.AIN0, MeasuringRange.FS4096))
            {
                // loop
                while (Console.KeyAvailable == false)
                {
                    // read raw data form the sensor
                    short raw = adc.ReadRaw();
                    // raw data convert to voltage
                    ElectricPotential voltage = adc.RawToVoltage(raw);

                    Console.WriteLine($"ADS1115 Raw Data: {raw}");
                    Console.WriteLine($"Voltage: {voltage}");
                    Console.WriteLine();

                    // wait for 2s
                    Thread.Sleep(2000);
                }

                Console.ReadKey(true);
            }

            // Read all channels in a loop.
            // We set the device mode to power-down, because we have to wait for a sample after each channel swap anyway.
            using (var adc = new Iot.Device.Ads1115.Ads1115(device, InputMultiplexer.AIN0, MeasuringRange.FS4096, DataRate.SPS250, DeviceMode.PowerDown))
            {
                // loop
                while (Console.KeyAvailable == false)
                {
                    Console.Clear();

                    ElectricPotential voltage0 = adc.ReadVoltage(InputMultiplexer.AIN0);
                    ElectricPotential voltage1 = adc.ReadVoltage(InputMultiplexer.AIN1);
                    ElectricPotential voltage2 = adc.ReadVoltage(InputMultiplexer.AIN2);
                    ElectricPotential voltage3 = adc.ReadVoltage(InputMultiplexer.AIN3);

                    Console.WriteLine($"ADS1115 Voltages: (Any key to continue)");
                    Console.WriteLine($"Channel0: {voltage0:s3}");
                    Console.WriteLine($"Channel1: {voltage1:s3}");
                    Console.WriteLine($"Channel2: {voltage2:s3}");
                    Console.WriteLine($"Channel3: {voltage3:s3}");
                    Console.WriteLine();

                    // wait for 100ms
                    Thread.Sleep(100);
                }

                while (Console.KeyAvailable)
                {
                    Console.ReadKey(true);
                }
            }

            // Provide a callback that triggers each time the ADC has a new value available. The DataRate parameter will define the sample rate.
            // We are using pin 23 as interrupt input from the ADC, but note that the trigger signal from the ADC may be to short to be properly recognized by the Raspberry Pi and
            // some extra electronics is required to make this reliably work (see readme).
            using (var controller = new GpioController(PinNumberingScheme.Logical))
            {
                Console.Clear();
                Console.WriteLine("This triggers an interrupt each time a new value is available on AIN0");
                using (Iot.Device.Ads1115.Ads1115 adc = new Iot.Device.Ads1115.Ads1115(device, controller, 23, false, InputMultiplexer.AIN0, MeasuringRange.FS2048, DataRate.SPS250))
                {
                    Stopwatch         w = Stopwatch.StartNew();
                    int               totalInterruptsSeen        = 0;
                    int               previousNumberOfInterrupts = 0;
                    ElectricPotential lastVoltage = default;
                    adc.AlertReadyAsserted += () =>
                    {
                        ElectricPotential voltage = adc.ReadVoltage();
                        lastVoltage = voltage;
                        totalInterruptsSeen++;
                    };

                    adc.EnableConversionReady();
                    // (Do something else, here we print the output (as the console operations use to much time in the interrupt callback)
                    while (Console.KeyAvailable == false)
                    {
                        int    interruptsThisPeriod = totalInterruptsSeen - previousNumberOfInterrupts;
                        double intsSecond           = interruptsThisPeriod / w.Elapsed.TotalSeconds;

                        Console.WriteLine($"ADS1115 Voltage: {lastVoltage}");
                        Console.WriteLine($"Interrups total: {totalInterruptsSeen}, last: {interruptsThisPeriod} Average: {intsSecond}/s (should be ~ {adc.FrequencyFromDataRate(adc.DataRate)})");
                        w.Restart();
                        previousNumberOfInterrupts = totalInterruptsSeen;
                        // wait for 2s
                        Thread.Sleep(2000);
                    }

                    Console.ReadKey(true);
                }
            }

            // Use an interrupt handler, but this time when the value on AIN1 exceeds a threshold
            using (var controller = new GpioController(PinNumberingScheme.Logical))
            {
                Console.Clear();
                Console.WriteLine("This triggers an interrupt as long as the value is above 2.0V (and then stays above 1.8V)");
                using (Iot.Device.Ads1115.Ads1115 adc = new Iot.Device.Ads1115.Ads1115(device, controller, 23, false, InputMultiplexer.AIN1, MeasuringRange.FS4096, DataRate.SPS860))
                {
                    Stopwatch         w = Stopwatch.StartNew();
                    int               totalInterruptsSeen        = 0;
                    int               previousNumberOfInterrupts = 0;
                    ElectricPotential lastVoltage = default;
                    adc.AlertReadyAsserted += () =>
                    {
                        ElectricPotential voltage = adc.ReadVoltage();
                        lastVoltage = voltage;
                        totalInterruptsSeen++;
                    };

                    adc.EnableComparator(adc.VoltageToRaw(ElectricPotential.FromVolts(1.8)), adc.VoltageToRaw(ElectricPotential.FromVolts(2.0)), ComparatorMode.Traditional, ComparatorQueue.AssertAfterTwo);
                    // Do something else, here we print the output (as the console operations use to much time in the interrupt callback)
                    while (Console.KeyAvailable == false)
                    {
                        int    interruptsThisPeriod = totalInterruptsSeen - previousNumberOfInterrupts;
                        double intsSecond           = interruptsThisPeriod / w.Elapsed.TotalSeconds;

                        if (interruptsThisPeriod > 0)
                        {
                            Console.WriteLine($"Interrupt voltage: {lastVoltage}");
                            Console.WriteLine($"Interrups total: {totalInterruptsSeen}, last: {interruptsThisPeriod} Average: {intsSecond}/s");
                        }
                        else
                        {
                            Console.WriteLine($"Current Voltage (no interrupts seen): {adc.ReadVoltage()}");
                        }

                        lastVoltage = default;
                        w.Restart();
                        previousNumberOfInterrupts = totalInterruptsSeen;
                        // wait for 2s
                        Thread.Sleep(2000);
                    }

                    Console.ReadKey(true);
                }
            }
        }
Ejemplo n.º 16
0
        private static void Main(string[] args)
        {
            Ccs811Sensor ccs811;

            Console.WriteLine("Hello CCS811!");
            // Simple menu to select native I2C/GPIO or thru FT4222, with GPIO pins and specific features to test
            Console.WriteLine("Select which platform I2C/GPIO you want to use:");
            Console.WriteLine(" 1. Native I2C/GPIO");
            Console.WriteLine(" 2. FT4222");
            var platformChoice = Console.ReadKey();

            Console.WriteLine();
            Console.WriteLine("Which I2C address do you want to use? Use the first one if Address pin is to ground, use the second one if to VCC.");
            Console.WriteLine($" 1. First 0x{Ccs811Sensor.I2cFirstAddress:X2}");
            Console.WriteLine($" 2. Second 0x{Ccs811Sensor.I2cSecondAddress:X2}");
            var addressChoice = Console.ReadKey();

            Console.WriteLine();
            Console.WriteLine("Do you want to the interrupt pin and events?");
            Console.WriteLine("(Y)es,(N)o");
            var pinChoice = Console.ReadKey();

            Console.WriteLine();
            int pinInterrupt = CheckAndAskPinNumber(pinChoice.KeyChar);

            Console.WriteLine($"Do you want to use the Wake pin?");
            Console.WriteLine("(Y)es,(N)o");
            pinChoice = Console.ReadKey();
            Console.WriteLine();
            int pinWake = CheckAndAskPinNumber(pinChoice.KeyChar);

            Console.WriteLine($"Do you want to use the Reset pin?");
            Console.WriteLine("(Y)es,(N)o");
            pinChoice = Console.ReadKey();
            Console.WriteLine();
            int pinReset = CheckAndAskPinNumber(pinChoice.KeyChar);

            if (platformChoice.KeyChar == '1')
            {
                Console.WriteLine("Creating an instance of a CCS811 using the platform drivers.");
                ccs811 = new Ccs811Sensor(I2cDevice.Create(new I2cConnectionSettings(3, addressChoice.KeyChar == '1' ? Ccs811Sensor.I2cFirstAddress : Ccs811Sensor.I2cSecondAddress)), pinWake: pinWake, pinInterruption: pinInterrupt, pinReset: pinReset);
            }
            else if (platformChoice.KeyChar == '2')
            {
                Console.WriteLine("Creating an instance of a CCS811 using FT4222 drivers.");
                var ftdiI2C        = new Ft4222I2c(new I2cConnectionSettings(0, addressChoice.KeyChar == '1' ? Ccs811Sensor.I2cFirstAddress : Ccs811Sensor.I2cSecondAddress));
                var gpioController = new GpioController(PinNumberingScheme.Board, new Ft4222Gpio());
                ccs811 = new Ccs811Sensor(ftdiI2C, gpioController, pinWake, pinInterrupt, pinReset, false);
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error: Invalid platform choice.");
                Console.ResetColor();
                return;
            }

            Console.WriteLine("Choose your operation mode:");
            int           i             = 0;
            OperationMode operationMode = OperationMode.ConstantPower1Second;

            foreach (var mode in Enum.GetValues(typeof(OperationMode)))
            {
                Console.WriteLine($" {i++}. {mode}");
            }

            var modeChoice = Console.ReadKey();

            try
            {
                // Converting the char to decimal, removing '0' = 0x30
                int selectedMode = Convert.ToInt32(modeChoice.KeyChar) - 0x30;
                if ((selectedMode >= 0) && (selectedMode <= 4))
                {
                    operationMode = (OperationMode)Convert.ToInt32(selectedMode);
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Error selecting mode, default {operationMode} will be selected");
                }
            }
            catch (StackOverflowException)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine($"Error selecting mode, default {operationMode} will be selected");
            }

            Console.ResetColor();
            DisplayBasicInformatio(ccs811);
            Console.WriteLine($"Current operating mode: {ccs811.OperationMode}, changing for {operationMode}");
            ccs811.OperationMode = operationMode;
            Console.WriteLine($"Current operating mode: {ccs811.OperationMode}");
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"Warning: the sensor needs to run for 48h in operation mode {OperationMode.ConstantPower1Second} before getting accurate results. " +
                              $"Also, every time you'll start the sensor, it will need approximately 20 minutes to get accurate results as well");
            Console.ResetColor();

            if (pinInterrupt >= 0)
            {
                Console.WriteLine("Interruption mode selected.");
                Console.WriteLine("Do you want to enable Threshold interruption?");
                Console.WriteLine("(Y)es,(N)o");
                var threshChoice = Console.ReadKey();
                Console.WriteLine();
                if ((threshChoice.KeyChar == 'Y') || (threshChoice.KeyChar == 'y'))
                {
                    TestThresholdAndInterrupt(ccs811);
                }
                else
                {
                    Console.Write(", once a measurement will be available, it will be displayed. Press any key to exit the program.");
                    ccs811.MeasurementReady += Ccs811MeasurementReady;
                    while (!Console.KeyAvailable)
                    {
                        Thread.Sleep(10);
                    }
                }
            }
            else
            {
                Console.WriteLine("What to you want to test?");
                Console.WriteLine(" 1. Read and display gas information for 10 times.");
                Console.WriteLine(" 2. Read and display gas information for 1000 times.");
                Console.WriteLine(" 3. Read and display detailed gas information for 10 times.");
                Console.WriteLine(" 4. Read and display detailed gas information for 1000 times.");
                Console.WriteLine(" 5. Read, load and change back the baseline.");
                Console.WriteLine(" 6. Test temperature and humidity changes.");
                Console.WriteLine(" 7. Read and log gas information 10000 times.");
                var operationChoice = Console.ReadKey();
                Console.WriteLine();
                switch (operationChoice.KeyChar)
                {
                case '1':
                    ReadAnDisplay(ccs811);
                    break;

                case '2':
                    ReadAnDisplay(ccs811, 1000);
                    break;

                case '3':
                    ReadAndDisplayDetails(ccs811);
                    break;

                case '4':
                    ReadAndDisplayDetails(ccs811, 1000);
                    break;

                case '5':
                    TestBaseline(ccs811);
                    break;

                case '6':
                    TestTemperatureHumidityAdjustment(ccs811);
                    break;

                case '7':
                    Console.WriteLine("Result file will be log.csv. The file is flushed on the disk every 100 results.");
                    ReadAndLog(ccs811, 10000);
                    break;

                default:
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Error: Sorry, didn't get your choice, program will now exit.");
                    Console.ResetColor();
                    break;
                }
            }

            Console.WriteLine($"Current operating mode: {ccs811.OperationMode}, changing for {OperationMode.Idle}");
            ccs811.OperationMode = OperationMode.Idle;
            Console.WriteLine($"Current operating mode: {ccs811.OperationMode}");
            // Dispose the CCS811 sensor
            ccs811.Dispose();
        }
Ejemplo n.º 17
0
 public OrientationSensor(int busId = 1, int address = 0x28)
 {
     this.i2cDevice = I2cDevice.Create(new I2cConnectionSettings(busId, address));
 }
Ejemplo n.º 18
0
        static void Main()
        {
            // pins
            const int ledOne    = 9;
            const int ledTwo    = 10;
            const int ledThree  = 11;
            const int buttonOne = 14;

            const int buttonSleep = 50;
            const int volumeSleep = 50;

            // volume support
            const int initialSleep = 100;
            int       sleep        = initialSleep;
            Volume    volume       = null;

            TimeEnvelope[] envelopes = new TimeEnvelope[] { new TimeEnvelope(1000), new TimeEnvelope(1000), new TimeEnvelope(4000) };

            Console.WriteLine("Hello World!");

            Console.WriteLine($"Let's blink some LEDs!");

            using (Seesaw seesawDevice = new Seesaw(I2cDevice.Create(new I2cConnectionSettings(1, 0x49))))
                using (SeesawGpioDriver seesawGpioDevice = new SeesawGpioDriver(seesawDevice))
                    using (GpioController controller = new GpioController(PinNumberingScheme.Logical, seesawGpioDevice))
                    {
                        // this line should only be enabled if a trimpot is connected
                        volume = Volume.EnableVolume(seesawDevice);

                        controller.OpenPin(ledOne, PinMode.Output);
                        controller.OpenPin(ledTwo, PinMode.Output);
                        controller.OpenPin(ledThree, PinMode.Output);
                        controller.OpenPin(buttonOne, PinMode.InputPullDown);

                        Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs eventArgs) =>
                        {
                            controller.Dispose();
                            Console.WriteLine("Pin cleanup complete!");
                        };

                        while (true)
                        {
                            // behavior for ledOne
                            if (envelopes[0].Time == 0)
                            {
                                Console.WriteLine($"Light LED one for 800ms");
                                controller.Write(ledOne, PinValue.High);
                            }
                            else if (envelopes[0].IsLastMultiple(200))
                            {
                                Console.WriteLine($"Dim LED one for 200ms");
                                controller.Write(ledOne, PinValue.Low);
                            }

                            // behavior for ledTwo
                            if (envelopes[1].IsMultiple(200))
                            {
                                Console.WriteLine($"Light LED two for 100ms");
                                controller.Write(ledTwo, PinValue.High);
                            }
                            else if (envelopes[1].IsMultiple(100))
                            {
                                Console.WriteLine($"Dim LED two for 100ms");
                                controller.Write(ledTwo, PinValue.Low);
                            }

                            // behavior for ledThree
                            if (envelopes[2].Time == 0)
                            {
                                Console.WriteLine("Light LED three for 2000 ms");
                                controller.Write(ledThree, PinValue.High);
                            }
                            else if (envelopes[2].IsFirstMultiple(2000))
                            {
                                Console.WriteLine("Dim LED three for 2000 ms");
                                controller.Write(ledThree, PinValue.Low);
                            }

                            // behavior for buttonOne
                            if (volume != null)
                            {
                                var update = true;
                                var value  = 0;
                                while (update)
                                {
                                    (update, value) = volume.GetSleepForVolume(initialSleep);
                                    if (update)
                                    {
                                        sleep = value;
                                        Thread.Sleep(volumeSleep);
                                    }
                                }
                            }

                            while (controller.Read(buttonOne) == PinValue.High)
                            {
                                Console.WriteLine("Button one pin value high!");
                                controller.Write(ledOne, PinValue.High);
                                controller.Write(ledTwo, PinValue.High);
                                controller.Write(ledThree, PinValue.High);
                                Thread.Sleep(buttonSleep);
                            }

                            Console.WriteLine($"Sleep: {sleep}");
                            Thread.Sleep(sleep);                  // starts at 100ms
                            TimeEnvelope.AddTime(envelopes, 100); // always stays at 100
                        }
                    }
        }
Ejemplo n.º 19
0
        //NO READONLY STRUCTS

        public Mpu6050(int busID)
        {
            _i2c = I2cDevice.Create(new I2cConnectionSettings(busID, 0x68, I2cBusSpeed.FastMode));
        }
Ejemplo n.º 20
0
        public static void MainTest()
        {
            var     mpui2CConnectionSettingmpus = new I2cConnectionSettings(1, Mpu9250.DefaultI2cAddress);
            Mpu9250 mpu9250 = new Mpu9250(I2cDevice.Create(mpui2CConnectionSettingmpus));

            Console.WriteLine($"Check version magnetometer: {mpu9250.GetMagnetometerVersion()}");
            Console.WriteLine(
                "Magnetometer calibration is taking couple of seconds, please be patient! Please make sure you are not close to any magnetic field like magnet or phone.");
            Console.WriteLine(
                "Please move your sensor as much as possible in all direction in space to get as many points in space as possible");
            var mag = mpu9250.CalibrateMagnetometer();

            Console.WriteLine($"Hardware bias multiplicative:");
            Console.WriteLine($"Mag X = {mag.X}");
            Console.WriteLine($"Mag Y = {mag.Y}");
            Console.WriteLine($"Mag Z = {mag.Z}");
            Console.WriteLine($"Calculated corrected bias:");
            Console.WriteLine($"Mag X = {mpu9250.MagnometerBias.X}");
            Console.WriteLine($"Mag Y = {mpu9250.MagnometerBias.Y}");
            Console.WriteLine($"Mag Z = {mpu9250.MagnometerBias.Z}");

            var resSelfTest = mpu9250.RunGyroscopeAccelerometerSelfTest();

            Console.WriteLine($"Self test:");
            Console.WriteLine($"Gyro X = {resSelfTest.Item1.X} vs >0.005");
            Console.WriteLine($"Gyro Y = {resSelfTest.Item1.Y} vs >0.005");
            Console.WriteLine($"Gyro Z = {resSelfTest.Item1.Z} vs >0.005");
            Console.WriteLine($"Acc X = {resSelfTest.Item2.X} vs >0.005 & <0.015");
            Console.WriteLine($"Acc Y = {resSelfTest.Item2.Y} vs >0.005 & <0.015");
            Console.WriteLine($"Acc Z = {resSelfTest.Item2.Z} vs >0.005 & <0.015");
            Console.WriteLine("Running Gyroscope and Accelerometer calibration");
            mpu9250.CalibrateGyroscopeAccelerometer();
            Console.WriteLine("Calibration results:");
            Console.WriteLine($"Gyro X bias = {mpu9250.GyroscopeBias.X}");
            Console.WriteLine($"Gyro Y bias = {mpu9250.GyroscopeBias.Y}");
            Console.WriteLine($"Gyro Z bias = {mpu9250.GyroscopeBias.Z}");
            Console.WriteLine($"Acc X bias = {mpu9250.AccelerometerBias.X}");
            Console.WriteLine($"Acc Y bias = {mpu9250.AccelerometerBias.Y}");
            Console.WriteLine($"Acc Z bias = {mpu9250.AccelerometerBias.Z}");
            Console.WriteLine("Press a key to continue");
            var readKey = Console.ReadKey();

            mpu9250.GyroscopeBandwidth     = GyroscopeBandwidth.Bandwidth0250Hz;
            mpu9250.AccelerometerBandwidth = AccelerometerBandwidth.Bandwidth0460Hz;
            Console.Clear();

            while (!Console.KeyAvailable)
            {
                Console.CursorTop = 0;
                var gyro = mpu9250.GetGyroscopeReading();
                Console.WriteLine($"Gyro X = {gyro.X,15}");
                Console.WriteLine($"Gyro Y = {gyro.Y,15}");
                Console.WriteLine($"Gyro Z = {gyro.Z,15}");
                var acc = mpu9250.GetAccelerometer();
                Console.WriteLine($"Acc X = {acc.X,15}");
                Console.WriteLine($"Acc Y = {acc.Y,15}");
                Console.WriteLine($"Acc Z = {acc.Z,15}");
                Console.WriteLine($"Temp = {mpu9250.GetTemperature().Celsius.ToString("0.00")} °C");
                var magne = mpu9250.ReadMagnetometer();
                Console.WriteLine($"Mag X = {magne.X,15}");
                Console.WriteLine($"Mag Y = {magne.Y,15}");
                Console.WriteLine($"Mag Z = {magne.Z,15}");
                Thread.Sleep(100);
            }

            readKey = Console.ReadKey();
            // SetWakeOnMotion
            mpu9250.SetWakeOnMotion(300, AccelerometerLowPowerFrequency.Frequency0Dot24Hz);
            // You'll need to attach the INT pin to a GPIO and read the level. Once going up, you have
            // some data and the sensor is awake
            // In order to simulate this without a GPIO pin, you will see that the refresh rate is very low
            // Setup here at 0.24Hz which means, about every 4 seconds
            Console.Clear();

            while (!Console.KeyAvailable)
            {
                Console.CursorTop = 0;
                var acc = mpu9250.GetAccelerometer();
                Console.WriteLine($"Acc X = {acc.X,15}");
                Console.WriteLine($"Acc Y = {acc.Y,15}");
                Console.WriteLine($"Acc Z = {acc.Z,15}");
                Thread.Sleep(100);
            }
        }
        public GrovePiPlus(int busId)
        {
            var i2cConnectionString = new I2cConnectionSettings(busId, 0x04);

            grovePiPlusDevice = I2cDevice.Create(i2cConnectionString);
        }
Ejemplo n.º 22
0
        private static I2cDevice CreateI2cDevice(byte address)
        {
            var settings = new I2cConnectionSettings(1, address);

            return(I2cDevice.Create(settings));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Main entry point for the program.
        /// </summary>
        public static void Main()
        {
            Console.WriteLine("Hello BME680!");

            // The I2C bus ID on the Raspberry Pi 3.
            const int busId = 1;
            // set this to the current sea level pressure in the area for correct altitude readings
            var defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel;

            var i2cSettings = new I2cConnectionSettings(busId, Bme680.DefaultI2cAddress);
            var i2cDevice   = I2cDevice.Create(i2cSettings);

            using (var bme680 = new Bme680(i2cDevice, Temperature.FromDegreesCelsius(20.0)))
            {
                while (true)
                {
                    // get the time a measurement will take with the current settings
                    var measurementDuration = bme680.GetMeasurementDuration(bme680.HeaterProfile);

                    // 10 consecutive measurement with default settings
                    for (var i = 0; i < 10; i++)
                    {
                        // This instructs the sensor to take a measurement.
                        bme680.SetPowerMode(Bme680PowerMode.Forced);

                        // wait while measurement is being taken
                        Thread.Sleep(measurementDuration.ToTimeSpan());

                        // Print out the measured data
                        bme680.TryReadTemperature(out var tempValue);
                        bme680.TryReadPressure(out var preValue);
                        bme680.TryReadHumidity(out var humValue);
                        bme680.TryReadGasResistance(out var gasResistance);
                        var altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue);

                        Console.WriteLine($"Gas resistance: {gasResistance:0.##}Ohm");
                        Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
                        Console.WriteLine($"Pressure: {preValue.Hectopascals:0.##}hPa");
                        Console.WriteLine($"Altitude: {altValue:0.##}m");
                        Console.WriteLine($"Relative humidity: {humValue:0.#}%");

                        // WeatherHelper supports more calculations, such as saturated vapor pressure, actual vapor pressure and absolute humidity.
                        Console.WriteLine($"Heat index: {WeatherHelper.CalculateHeatIndex(tempValue, humValue).DegreesCelsius:0.#}\u00B0C");
                        Console.WriteLine($"Dew point: {WeatherHelper.CalculateDewPoint(tempValue, humValue).DegreesCelsius:0.#}\u00B0C");

                        // when measuring the gas resistance on each cycle it is important to wait a certain interval
                        // because a heating plate is activated which will heat up the sensor without sleep, this can
                        // falsify all readings coming from the sensor
                        Thread.Sleep(1000);
                    }

                    // change the settings
                    bme680.TemperatureSampling = Sampling.HighResolution;
                    bme680.HumiditySampling    = Sampling.UltraHighResolution;
                    bme680.PressureSampling    = Sampling.Skipped;

                    bme680.ConfigureHeatingProfile(Bme680HeaterProfile.Profile2, Temperature.FromDegreesCelsius(280), Duration.FromMilliseconds(80), Temperature.FromDegreesCelsius(24));
                    bme680.HeaterProfile = Bme680HeaterProfile.Profile2;

                    measurementDuration = bme680.GetMeasurementDuration(bme680.HeaterProfile);

                    // 10 consecutive measurements with custom settings
                    for (int i = 0; i < 10; i++)
                    {
                        // perform the measurement
                        bme680.SetPowerMode(Bme680PowerMode.Forced);
                        Thread.Sleep(measurementDuration.ToTimeSpan());

                        // Print out the measured data
                        bme680.TryReadTemperature(out var tempValue);
                        bme680.TryReadPressure(out var preValue);
                        bme680.TryReadHumidity(out var humValue);
                        bme680.TryReadGasResistance(out var gasResistance);
                        var altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue);

                        Console.WriteLine($"Gas resistance: {gasResistance:0.##}Ohm");
                        Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
                        Console.WriteLine($"Pressure: {preValue.Hectopascals:0.##}hPa");
                        Console.WriteLine($"Altitude: {altValue:0.##}m");
                        Console.WriteLine($"Relative humidity: {humValue:0.#}%");

                        // WeatherHelper supports more calculations, such as saturated vapor pressure, actual vapor pressure and absolute humidity.
                        Console.WriteLine($"Heat index: {WeatherHelper.CalculateHeatIndex(tempValue, humValue).DegreesCelsius:0.#}\u00B0C");
                        Console.WriteLine($"Dew point: {WeatherHelper.CalculateDewPoint(tempValue, humValue).DegreesCelsius:0.#}\u00B0C");
                        Thread.Sleep(1000);
                    }

                    // reset will change settings back to default
                    bme680.Reset();
                }
            }
        }
Ejemplo n.º 24
0
        public static void SampleEntryPoint()
        {
            Console.WriteLine("Starting...");
            // for PCF8574T i2c addresses can be between 0x27 and 0x20 depending on bridged solder jumpers
            // for PCF8574AT i2c addresses can be between 0x3f and 0x38 depending on bridged solder jumpers
            var i2cDevice = I2cDevice.Create(new I2cConnectionSettings(busId: 1, deviceAddress: 0x27));
            var driver    = new Pcf8574(i2cDevice);
            var lcd       = new Lcd1602(registerSelectPin: 0, enablePin: 2, dataPins: new int[] { 4, 5, 6, 7 }, backlightPin: 3, readWritePin: 1, controller: new GpioController(PinNumberingScheme.Logical, driver));

            using (lcd)
            {
                Console.WriteLine("Initialized");
                Console.ReadLine();

                TestPrompt("SetCursor", lcd, SetCursorTest);
                TestPrompt("Underline", lcd, l => l.UnderlineCursorVisible = true);
                lcd.UnderlineCursorVisible = false;
                TestPrompt("Walker", lcd, WalkerTest);
                CreateTensCharacters(lcd);
                TestPrompt("CharacterSet", lcd, CharacterSet);

                // Shifting
                TestPrompt("Autoshift", lcd, AutoShift);
                TestPrompt("DisplayLeft", lcd, l => ShiftDisplayTest(l, a => a.ShiftDisplayLeft()));
                TestPrompt("DisplayRight", lcd, l => ShiftDisplayTest(l, a => a.ShiftDisplayRight()));
                TestPrompt("CursorLeft", lcd, l => ShiftCursorTest(l, a => a.ShiftCursorLeft()));
                TestPrompt("CursorRight", lcd, l => ShiftCursorTest(l, a => a.ShiftCursorRight()));

                // Long string
                TestPrompt("Twenty", lcd, l => l.Write(Twenty));
                TestPrompt("Fourty", lcd, l => l.Write(Fourty));
                TestPrompt("Eighty", lcd, l => l.Write(Eighty));

                TestPrompt("Twenty-", lcd, l => WriteFromEnd(l, Twenty));
                TestPrompt("Fourty-", lcd, l => WriteFromEnd(l, Fourty));
                TestPrompt("Eighty-", lcd, l => WriteFromEnd(l, Eighty));

                TestPrompt("Wrap", lcd, l => l.Write(new string('*', 80) + ">>>>>"));
                TestPrompt("Perf", lcd, PerfTests);

                // Shift display right
                lcd.Write("Hello .NET!");
                try
                {
                    int   state = 0;
                    Timer timer = new Timer(1000);
                    timer.Elapsed += (o, e) =>
                    {
                        lcd.SetCursorPosition(0, 1);
                        lcd.Write(DateTime.Now.ToLongTimeString() + " ");
                        if (state == 0)
                        {
                            state = 1;
                        }
                        else
                        {
                            lcd.ShiftDisplayRight();
                            state = 0;
                        }
                    };
                    timer.AutoReset = true;
                    timer.Enabled   = true;
                    Console.ReadLine();
                }
                finally
                {
                    lcd.DisplayOn   = false;
                    lcd.BacklightOn = false;
                    Console.WriteLine("Done...");
                }
            }
        }
Ejemplo n.º 25
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello DHT!");
            Console.WriteLine("Select the DHT sensor you want to use:");
            Console.WriteLine(" 1. DHT10 on I2C");
            Console.WriteLine(" 2. DHT11 on GPIO");
            Console.WriteLine(" 3. DHT12 on GPIO");
            Console.WriteLine(" 4. DHT21 on GPIO");
            Console.WriteLine(" 5. DHT22 on GPIO");
            var choice = Console.ReadKey();

            Console.WriteLine();
            if (choice.KeyChar == '1')
            {
                Console.WriteLine("Press any key to stop the reading");
                // Init DHT10 through I2C
                I2cConnectionSettings settings = new I2cConnectionSettings(1, Dht10.DefaultI2cAddress);
                I2cDevice             device   = I2cDevice.Create(settings);

                using (Dht10 dht = new Dht10(device))
                {
                    Dht(dht);
                }

                return;
            }

            Console.WriteLine("Which pin do you want to use in the logical pin schema?");
            var pinChoise = Console.ReadLine();
            int pin;

            try
            {
                pin = Convert.ToInt32(pinChoise);
            }
            catch (Exception ex) when(ex is FormatException || ex is OverflowException)
            {
                Console.WriteLine("Can't convert pin number.");
                return;
            }

            Console.WriteLine("Press any key to stop the reading");

            switch (choice.KeyChar)
            {
            case '2':
                Console.WriteLine($"Reading temperature and humidity on DHT11, pin {pin}");
                using (var dht11 = new Dht11(pin))
                {
                    Dht(dht11);
                }

                break;

            case '3':
                Console.WriteLine($"Reading temperature and humidity on DHT12, pin {pin}");
                using (var dht12 = new Dht12(pin))
                {
                    Dht(dht12);
                }

                break;

            case '4':
                Console.WriteLine($"Reading temperature and humidity on DHT21, pin {pin}");
                using (var dht21 = new Dht21(pin))
                {
                    Dht(dht21);
                }

                break;

            case '5':
                Console.WriteLine($"Reading temperature and humidity on DHT22, pin {pin}");
                using (var dht22 = new Dht22(pin))
                {
                    Dht(dht22);
                }

                break;

            default:
                Console.WriteLine("Please select one of the option.");
                break;
            }
        }
Ejemplo n.º 26
0
        private static I2cDevice CreateDefaultI2cDevice()
        {
            var settings = new I2cConnectionSettings(1, I2cAddress);

            return(I2cDevice.Create(settings));
        }
        /// <summary>
        ///     Open a connection to the Expander Pi.
        /// </summary>
        public void Connect()
        {
            if (IsConnected)
            {
                return; // Already connected
            }

            try
            {
                // Create SPI initialization settings for the ADC
                var adcSettings = new SpiConnectionSettings(SPI_BUS_ID, ADC_CHIP_SELECT_LINE)
                {
                    ClockFrequency = 200000, // SPI clock frequency of 200KHz
                    Mode           = SpiMode.Mode0
                };

                adc = SpiDevice.Create(adcSettings); // Create an ADC connection with our bus controller and SPI settings

                // Create SPI initialization settings for the DAC
                var dacSettings =
                    new SpiConnectionSettings(SPI_BUS_ID, DAC_CHIP_SELECT_LINE)
                {
                    ClockFrequency = 2000000,      // SPI clock frequency of 20MHz
                    Mode           = SpiMode.Mode0
                };

                dac = SpiDevice.Create(dacSettings); // Create an ADC connection with our bus controller and SPI settings



                // Initialize the I2C bus

                var IOsettings = new I2cConnectionSettings(1, IOADDRESS);
                IOi2cbus = I2cDevice.Create(IOsettings);

                var RTCsettings = new I2cConnectionSettings(1, RTCADDRESS);
                RTCi2cbus = I2cDevice.Create(RTCsettings);

                if (IOi2cbus != null && RTCi2cbus != null)
                {
                    // Set IsConnected to true
                    IsConnected = true;

                    // i2c bus is connected so set up the initial configuration for the IO Pi
                    helper.WriteI2CByte(IOi2cbus, IOCON, config);

                    portaval = helper.ReadI2CByte(IOi2cbus, GPIOA);
                    portbval = helper.ReadI2CByte(IOi2cbus, GPIOB);
                    helper.WriteI2CByte(IOi2cbus, IODIRA, 0xFF);
                    helper.WriteI2CByte(IOi2cbus, IODIRB, 0xFF);
                    IOSetPortPullups(0, 0x00);
                    IOSetPortPullups(1, 0x00);
                    IOInvertPort(0, 0x00);
                    IOInvertPort(1, 0x00);

                    // Fire the Connected event handler
                    Connected?.Invoke(this, EventArgs.Empty);
                }
            }
            /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                IsConnected = false;
                throw new Exception("SPI and I2C Initialization Failed", ex);
            }
        }