Beispiel #1
0
        public bool Lunch()
        {
            try
            {
                //检查依赖
                if (!EquipmentBus.ControllerRegister.CheckRely(RelyEquipment))
                {
                    throw new Exception($"依赖设备尚未启动{string.Join("、", RelyEquipment)}");
                }

                I2CDevice = I2CDriver.I2CBus.AddDevice(Addr);
                I2CDevice.WriteAddressByte(MODE1, 0x00);
                SetPWMFreq(Freq);
                EquipmentData.IsEnable = true;
                EquipmentBus.ControllerRegister.Register(RegisterType.Pca9685, false);
            }
            catch (Exception ex)
            {
                EquipmentData.AddError(LogType.Error, $"启动地址为{Addr},频率为{Freq}的PCA9685失败!", ex);
                Logger.Add(LogType.Error, $"启动地址为{Addr},频率为{Freq}的PCA9685失败!", ex);
                EquipmentData.IsEnable = false;
                return(false);
            }
            return(true);
        }
        private void ADS1115ReadValuesWiringPi(byte busId, byte i2cAddress, byte[] configDataChunk, byte[] convertDataChunk)
        {
            Pi.Init <BootstrapWiringPi>();

            II2CDevice ads1115 = Pi.I2C.AddDevice(i2cAddress);

            var configWord = (ushort)((configDataChunk[2] << 8) + configDataChunk[1]);

            // Write config register to the ADC
            //var currentConfig = ads1115.ReadAddressWord(ADS1115.ADS1115_REG_POINTER_CONFIG);
            //Console.WriteLine($"Setting original configuration ({currentConfig.ToString("X")}) to {config.ToString("X")}");

            ads1115.WriteAddressWord(configDataChunk[0], configWord);

            //currentConfig = ads1115.ReadAddressWord(ADS1115.ADS1115_REG_POINTER_CONFIG);
            //Console.WriteLine($"New configuration: {currentConfig.ToString("X")}");

            DateTime firstDataRead = DateTime.UtcNow;

            while (true)
            {
                // Read the conversion results
                ushort result  = (ushort)(ads1115.ReadAddressWord(convertDataChunk[0]));
                float  voltage = (float)(result < 32768 ? result : -(65536 - result)) * 2.048f / 65536.0f;

                j++;
                if (j % 1000 == 0)
                {
                    Console.WriteLine(String.Format("| ADC value: {0,5} V | sample rate: {1,7} SPS |", voltage.ToString("N", CultureInfo.InvariantCulture), ((double)j / (DateTime.UtcNow - firstDataRead).TotalSeconds).ToString("N")));
                }
            }
        }
Beispiel #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AccelerometerGY521"/> class.
 /// </summary>
 /// <param name="device">I2C device.</param>
 /// <param name="gyroScale">The gyroscope sensitivity factor.</param>
 /// <param name="accelScale">The accelerometer sensitivity factor.</param>
 public AccelerometerGY521(II2CDevice device, GfsSel gyroScale, AfsSel accelScale)
 {
     Device             = device;
     GyroscopeScale     = gyroScale;
     AccelerometerScale = accelScale;
     ReadWorker         = new Thread(Run);
 }
Beispiel #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ADS1x15"/> class.
 /// </summary>
 /// <param name="device">The i2c device to use.</param>
 /// <param name="delay">amount of time to delay between write/read.</param>
 /// <param name="shift">bits to shift for sign correction.</param>
 protected ADS1x15(II2CDevice device, byte delay, byte shift)
 {
     _device          = device ?? throw new ArgumentNullException(nameof(device));
     _conversionDelay = delay;
     _bitShift        = shift;
     Gain             = AdsGain.GAINONE;
 }
Beispiel #5
0
        public static UInt32 Read24Bits(II2CDevice device, byte reg, ByteOrder byteOrder, string exceptionMessage)
        {
            try
            {
                byte[] data = new byte[3];//ReadBytes(device, reg, 3, exceptionMessage);
                for (int i = 0; i < data.Length; ++i)
                {
                    data[i] = device.ReadAddressByte(reg);                    //Read8Bits(device,reg,"error");
                }

                switch (byteOrder)
                {
                case ByteOrder.BigEndian:
                    return((UInt32)((data[0] << 16) | (data[1] << 8) | data[2]));

                case ByteOrder.LittleEndian:
                    return((UInt32)((data[2] << 16) | (data[1] << 8) | data[0]));

                default:
                    throw new SensorException($"Unsupported byte order {byteOrder}");
                }
            }
            catch (Exception exception)
            {
                throw new SensorException(exceptionMessage, exception);
            }
        }
Beispiel #6
0
        //Method to initialize the BME280 sensor
        public async Task InitializeAsync()
        {
            Console.WriteLine("BME280::Initialize");

            try
            {
                Console.WriteLine("0ab");
                bme280 = Pi.I2C.AddDevice(BME280_Address);

                Console.WriteLine("0ac");
                //Check if device was found
                if (bme280 == null)
                {
                    Console.WriteLine("Device not found");
                }
                else
                {
                    try
                    {
                        //Make sure the I2C device is initialized
                        await BeginAsync();
                    }
                    catch (Exception e)
                    {
                        init = false;
                        Console.WriteLine("Exception: " + e.Message + "\n" + e.StackTrace);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message + "\n" + e.StackTrace);
                throw;
            }
        }
Beispiel #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ADS1x15"/> class.
        /// </summary>
        /// <param name="delay">amount of time to delay between write/read.</param>
        /// <param name="shift">bits to shift for sign correction.</param>
        /// <param name="address">I2C Address.</param>
        protected ADS1x15(byte delay, byte shift, byte address = ADS1x15ADDRESS)
        {
            device          = Pi.I2C.AddDevice(i2cAddress = address);
            conversionDelay = delay;
            bitShift        = shift;

            Gain = AdsGaint.GAINTWOTHIRDS; /* +/- 6.144V range (limited to VDD +0.3V max!) */
        }
        public LSM9DS1()
        {
            Pi.Init <BootstrapWiringPi>();

            Console.WriteLine(Pi.Info.ToString());

            _accGyroDevice = Pi.I2C.AddDevice(AccGyroAddress);
            _magDevice     = Pi.I2C.AddDevice(MagAddress);
        }
Beispiel #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ADS1x15"/> class.
        /// </summary>
        /// <param name="delay">amount of time to delay between write/read.</param>
        /// <param name="shift">bits to shift for sign correction.</param>
        /// <param name="address">I2C Address.</param>
        protected ADS1x15(byte delay, byte shift, byte address = ADS1x15ADDRESS)
        {
            device          = Pi.I2C.AddDevice(i2cAddress = address);
            conversionDelay = delay;
            bitShift        = shift;

            Console.WriteLine($"did: {device.DeviceId} desc:{device.FileDescriptor}");
            Gain = AdsGaint.GAINTWOTHIRDS; /* +/- 6.144V range (limited to VDD +0.3V max!) */
        }
        public override void Execute(II2CDevice i2CDevice)
        {
            i2CDevice.Write(GenerateRegisterSensorPackage());

            byte[] buffer = new byte[9];
            i2CDevice.Read(buffer);

            ParseResponse(buffer);
        }
Beispiel #11
0
        public override void Execute(II2CDevice i2CDevice)
        {
            i2CDevice.Write(GenerateRegisterSensorPackage());

            byte[] buffer = new byte[9];
            i2CDevice.Read(buffer);

            ParseResponse(buffer);
        }
Beispiel #12
0
        public Display(II2CDevice I2cDevice, uint WidthPx = 128, uint HeightPx = 32, bool flipDisplay = false)
        {
            ScreenWidthPX  = WidthPx;
            ScreenHeightPx = HeightPx;
            i2cDevice      = I2cDevice;
            FlipDisplay    = flipDisplay;

            ScreenPages   = ScreenHeightPx / 8;
            DisplayBuffer = new byte[ScreenPages, ScreenWidthPX];
        }
Beispiel #13
0
 //Method to initialize the BMP280 sensor
 public BME280()
 {
     try
     {
         bme280 = Pi.I2C.AddDevice(BME280_Address);
     }
     catch (Exception e)
     {
         Logger.Log(ConsoleColor.Red, "Exception: " + e.Message + "\n" + e.StackTrace);
     }
 }
Beispiel #14
0
 public static UInt16 Read16Bits(II2CDevice device, byte reg, ByteOrder byteOrder, string exceptionMessage)
 {
     try
     {
         return(device.ReadAddressWord(reg));
     }
     catch (Exception exception)
     {
         throw new SensorException(exceptionMessage, exception);
     }
 }
Beispiel #15
0
 public static byte Read8Bits(II2CDevice device, byte reg, string exceptionMessage)
 {
     try
     {
         return(device.ReadAddressByte(reg));
     }
     catch (Exception exception)
     {
         throw new SensorException(exceptionMessage, exception);
     }
 }
Beispiel #16
0
 public static void Write(II2CDevice device, byte reg, byte command, string exceptionMessage)
 {
     try
     {
         device.WriteAddressByte(reg, command);
     }
     catch (Exception exception)
     {
         throw new SensorException(exceptionMessage, exception);
     }
 }
Beispiel #17
0
 private void ConnectToI2CDevices()
 {
     try
     {
         _i2CDevice = Pi.I2C.AddDevice(_i2CAddress);
     }
     catch (Exception exception)
     {
         throw new SensorException("Failed to connect to HTS221", exception);
     }
 }
Beispiel #18
0
 private void ConnectToI2CDevices()
 {
     try
     {
         _accelGyroI2CDevice = Pi.I2C.AddDevice(_accelGyroI2CAddress);
         _magI2CDevice       = Pi.I2C.AddDevice(_magI2CAddress);
     }
     catch (Exception exception)
     {
         throw new SensorException("Failed to connect to LSM9DS1", exception);
     }
 }
        public override void Execute(II2CDevice i2CDevice)
        {
            i2CDevice.Write(GenerateClearSignalCachePackage());

            int offset = 0;
            while (offset < _signal.Length)
            {
                var buffer = _signal.Skip(offset).Take(30).ToArray();
                offset += buffer.Length;

                i2CDevice.Write(GenerateFillSignalCachePackage(buffer));
            }

            i2CDevice.Write(GenerateSendCachedSignalPackage());
        }
        public override void Execute(II2CDevice i2CDevice)
        {
            i2CDevice.Write(GenerateClearSignalCachePackage());

            int offset = 0;

            while (offset < _signal.Length)
            {
                var buffer = _signal.Skip(offset).Take(30).ToArray();
                offset += buffer.Length;

                i2CDevice.Write(GenerateFillSignalCachePackage(buffer));
            }

            i2CDevice.Write(GenerateSendCachedSignalPackage());
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="OledDisplaySsd1306"/> class.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="model">The model.</param>
        /// <param name="vccSource">State of the VCC.</param>
        /// <exception cref="ArgumentException">Invalid display model - model.</exception>
        /// <exception cref="ArgumentNullException">device.</exception>
        public OledDisplaySsd1306(II2CDevice device, DisplayModel model, VccSourceMode vccSource)
        {
            switch (model)
            {
            case DisplayModel.Display128X32:
            {
                Width  = 128;
                Height = 32;
                break;
            }

            case DisplayModel.Display128X64:
            {
                Width  = 128;
                Height = 64;
                break;
            }

            case DisplayModel.Display96X16:
            {
                Width  = 96;
                Height = 16;
                break;
            }

            default:
            {
                throw new ArgumentException("Invalid display model", nameof(model));
            }
            }

            Model            = model;
            Device           = device ?? throw new ArgumentNullException(nameof(device));
            VccSource        = vccSource;
            _bufferPageCount = Height / 8;
            _bitBuffer       = new BitArray(Width * Height);
            _byteBuffer      = new byte[1 + (_bitBuffer.Length / 8)];
            _byteBuffer[0]   = 0x40; // The first byte signals data
            _bitsPerPage     = 8 * Width;
            Initialize();
            IsActive = true;
        }
Beispiel #22
0
        // public static UInt32 Read32Bits(II2CDevice device, byte reg, ByteOrder byteOrder, string exceptionMessage)
        // {
        //     try
        //     {
        //         byte[] data = ReadBytes(device, reg, 4, exceptionMessage);

        //         switch (byteOrder)
        //         {
        //             case ByteOrder.BigEndian:
        //                 return (UInt32)((data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]);

        //             case ByteOrder.LittleEndian:
        //                 return (UInt32)((data[3] << 24) | (data[2] << 16) | (data[1] << 8) | data[0]);

        //             default:
        //                 throw new SensorException($"Unsupported byte order {byteOrder}");
        //         }
        //     }
        //     catch (Exception exception)
        //     {
        //         throw new SensorException(exceptionMessage, exception);
        //     }
        // }

        public static byte[] ReadBytes(II2CDevice device, byte reg, int count, string exceptionMessage)
        {
            try
            {
                byte[] addr = { reg };

                byte[] data = new byte[count];

                device.Write(reg);
                for (int i = 0; i < count; ++i)
                {
                    data[i] = device.ReadAddressByte(reg);
                }
                return(data);
                //return device.ReadAddressBlock(reg, count);
            }
            catch (Exception exception)
            {
                throw new SensorException(exceptionMessage, exception);
            }
        }
 public override void Execute(II2CDevice i2CDevice)
 {
     i2CDevice.Write(ToPackage());
 }
Beispiel #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ADS1015"/> class.
 /// </summary>
 /// <param name="address">The I2C Address for this device.</param>
 public ADS1015(II2CDevice device)
     : base(device, ADS1015CONVERSIONDELAY, 4)
 {
 }
Beispiel #25
0
 public void Execute(II2CDevice i2CDevice)
 {
     i2CDevice.Write(ToPackage());
 }
Beispiel #26
0
 public Pcf8574(int address)
 {
     dev = Pi.I2C.AddDevice(address);
     Read();
 }
Beispiel #27
0
 public PCA9685(int address, int frequency = 1600) // NOTE: The I2C address is configurable by the chip between 0x40 through 0x7F with some exclusions
 {
     device = Pi.I2C.AddDevice(i2cAddress = address);
     Setup(frequency);
 }
Beispiel #28
0
 /// <summary>
 /// Write to the I2C register, ADS1x15 is byte swapped.
 /// </summary>
 /// <param name="registery">register address to write to</param>
 /// <param name="value">value to set</param>
 public static void WriteAddressWordSwapped(this II2CDevice device, byte registery, ushort value)
 {
     device.WriteAddressWord(registery, SwapWord(value));
 }
Beispiel #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AccelerometerGY521"/> class
 /// with default values for gyroscope (250 °/s) and accelerometer (2g) scale range.
 /// </summary>
 /// <param name="device">The device.</param>
 public AccelerometerGY521(II2CDevice device)
     : this(device, GfsSel.Fsr250, AfsSel.Fsr2G)
 {
 }
 public abstract void Execute(II2CDevice i2CDevice);
Beispiel #31
0
        public PCA9685(int busId = 2, int address = 0x46)
        {
            device = Pi.I2C.AddDevice(i2cAddress = address);

            Setup();
        }
Beispiel #32
0
        public void UpdateAccelConfig(II2CDevice device) 
        {
            /* CTRL_REG0_XM (0x1F) (Default value: 0x00)
            Bits (7-0): BOOT FIFO_EN WTM_EN 0 0 HP_CLICK HPIS1 HPIS2
            BOOT - Reboot memory content (0: normal, 1: reboot)
            FIFO_EN - Fifo enable (0: disable, 1: enable)
            WTM_EN - FIFO watermark enable (0: disable, 1: enable)
            HP_CLICK - HPF enabled for click (0: filter bypassed, 1: enabled)
            HPIS1 - HPF enabled for interrupt generator 1 (0: bypassed, 1: enabled)
            HPIS2 - HPF enabled for interrupt generator 2 (0: bypassed, 1 enabled)   */
            byte reg0Config = (byte)((HPFEnabledGenerator2 ? 1 : 0) << 7 &
                                     (HPFEnabledGenerator1 ? 1 : 0) << 6 &
                                     (HPFEnabledForClick ? 1 : 0) << 5 &
                                     (FifoWatermarkEnabled ? 1 : 0) << 2 &
                                     (FifoEnabled ? 1 : 0) << 1 &
                                     (RebootMemory ? 1 : 0));

            /* CTRL_REG1_XM (0x20) (Default value: 0x07)
            Bits (7-0): AODR3 AODR2 AODR1 AODR0 BDU AZEN AYEN AXEN
            AODR[3:0] - select the acceleration data rate:
                0000=power down, 0001=3.125Hz, 0010=6.25Hz, 0011=12.5Hz, 
                0100=25Hz, 0101=50Hz, 0110=100Hz, 0111=200Hz, 1000=400Hz,
                1001=800Hz, 1010=1600Hz, (remaining combinations undefined).
            BDU - block data update afor accel AND mag
                0: Continuous update
                1: Output registers aren't updated until MSB and LSB have been read.
            AZEN, AYEN, and AXEN - Acceleration x/y/z-axis enabled.
                0: Axis disabled, 1: Axis enabled									 */
            byte reg1Config = (byte)((XAxisEnabled ? 1 : 0) << 7 &
                                     (YAxisEnabled ? 1 : 0) << 6 &
                                     (ZAxisEnabled ? 1 : 0) << 5 &
                                     (BlockDataUpdateForAccelAndMag ? 1 : 0) << 4 &
                                     (int) DataRate);

            /* CTRL_REG2_XM (0x21) (Default value: 0x00)
            Bits (7-0): ABW1 ABW0 AFS2 AFS1 AFS0 AST1 AST0 SIM
            ABW[1:0] - Accelerometer anti-alias filter bandwidth
                00=773Hz, 01=194Hz, 10=362Hz, 11=50Hz
            AFS[2:0] - Accel full-scale selection
                000=+/-2g, 001=+/-4g, 010=+/-6g, 011=+/-8g, 100=+/-16g
            AST[1:0] - Accel self-test enable
                00=normal (no self-test), 01=positive st, 10=negative st, 11=not allowed
            SIM - SPI mode selection
                0=4-wire, 1=3-wire													 */
            byte reg2Config = (byte)((SPI3WireMode ? 1 : 0) << 7 &
                                     (int)SelfTest << 5 &
                                     (int)Scale << 2 &
                                     (int)AntiAliasFilterBandwidth);




            device.WriteByte(DOFConsts.CTRL_REG0_XM, reg0Config);
            device.WriteByte(DOFConsts.CTRL_REG1_XM, reg1Config);
            device.WriteByte(DOFConsts.CTRL_REG2_XM, reg2Config);

            // NOTE: Not sure how this register should be set documentation says:
            /* CTRL_REG3_XM is used to set interrupt generators on INT1_XM
               Bits (7-0): P1_BOOT P1_TAP P1_INT1 P1_INT2 P1_INTM P1_DRDYA P1_DRDYM P1_EMPTY
            */
            // Accelerometer data ready on INT1_XM (0x04)
            device.WriteByte(DOFConsts.CTRL_REG3_XM, 0x04);
        }
Beispiel #33
0
 public I2C(byte adress)
 {
     _device = Pi.I2C.AddDevice(adress);
 }
Beispiel #34
0
 public void UpdateGyroConfig(II2CDevice device)
 {
     device.WriteByte(CTRL_REG1_G, this.OutputDataRate);
     device.WriteByte(CTRL_REG2_G, this.HighPassFilter);
     device.WriteByte(CTRL_REG3_G, this.InteruptDRDY);
     device.WriteByte(CTRL_REG4_G, this.ScaleAndUpdate);
     device.WriteByte(CTRL_REG5_G, this.FIFOHPFINT1);
 }
 public abstract void Execute(II2CDevice i2CDevice);
Beispiel #36
0
        protected ADS1x15(byte address = ADS1x15_ADDRESS)
        {
            device = Pi.I2C.AddDevice(i2cAddress = address);

            Gain = adsGain_t.GAIN_TWOTHIRDS; /* +/- 6.144V range (limited to VDD +0.3V max!) */
        }