Example #1
0
        private void EnsureConfiguration(SpiDevice spiDevice)
        {
            if ((_currentRegisters.Gain == Gain) &&
                (_currentRegisters.DataRate == DataRate) &&
                (_currentRegisters.DetectCurrentSources == DetectCurrentSources) &&
                (_currentRegisters.AutoCalibrate == AutoSelfCalibrate) &&
                (_currentRegisters.UseInputBuffer == UseInputBuffer))
            {
                return;
            }

            _currentRegisters = new Registers(
                Gain,
                DataRate,
                DetectCurrentSources,
                AutoSelfCalibrate,
                UseInputBuffer);

            WriteRegisters(spiDevice, _currentRegisters);
        }
        private async void InitSPI()
        {
            try
            {
                var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE);
                settings.ClockFrequency = 500000;        // 10000000;
                settings.Mode           = SpiMode.Mode0; //Mode3;

                string spiAqs     = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME);
                var    deviceInfo = await DeviceInformation.FindAllAsync(spiAqs);

                SpiDisplay = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings);
            }

            /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                throw new Exception("SPI Initialization Failed", ex);
            }
        }
Example #3
0
        async Task InitSPI()
        {
            try
            {
                var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE);
                settings.ClockFrequency = 500000;        /* 0.5MHz clock rate                                        */
                settings.Mode           = SpiMode.Mode0; /* The ADC expects idle-low clock polarity so we use Mode0  */

                string spiAqs     = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME);
                var    deviceInfo = await DeviceInformation.FindAllAsync(spiAqs);

                SpiADC = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings);
            }

            /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                throw new Exception("SPI Initialization Failed", ex);
            }
        }
        public static async Task InitSPI()
        {
            try
            {
                var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE);
                settings.ClockFrequency = 1000000;       // 10000000;
                settings.Mode           = SpiMode.Mode0; //Mode0,1,2,3;  MCP23S17 needs mode 0

                string spiAqs     = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME);
                var    deviceInfo = await DeviceInformation.FindAllAsync(spiAqs);

                SpiGPIO = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings);
            }

            /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                //statusText.Text = "\nSPI Initialization Failed";
            }
        }
Example #5
0
        /* Initialize the SPI bus */

        public async Task InitSpi()
        {
            try
            {
                var settings = new SpiConnectionSettings(SSD1306DeviceConfiguration.SPI_CHIP_SELECT_LINE); /* Create SPI initialization settings                               */
                settings.ClockFrequency = 10000000;                                                        /* Datasheet specifies maximum SPI clock frequency of 10MHz         */
                settings.Mode           = SpiMode.Mode3;                                                   /* The display expects an idle-high clock polarity, we use Mode3
                                                                                                            * to set the clock polarity and phase to: CPOL = 1, CPHA = 1
                                                                                                            */

                var controller = await SpiController.GetDefaultAsync();

                SpiDisplay = controller.GetDevice(settings);  /* Create an SpiDevice with our bus controller and SPI settings */
            }
            /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                throw new Exception("SPI Initialization Failed", ex);
            }
        }
Example #6
0
        /// <summary>
        /// Initialize SPI.
        /// </summary>
        /// <returns></returns>
        private async Task InitSpi()
        {
            try
            {
                var settings = new SpiConnectionSettings((int)chipSelect);
                settings.ClockFrequency = 10000000;
                settings.Mode           = SpiMode.Mode0;
                settings.SharingMode    = SpiSharingMode.Shared;

                string spiAqs      = SpiDevice.GetDeviceSelector(SPIControllerName);   /* Find the selector string for the SPI bus controller          */
                var    devicesInfo = await DeviceInformation.FindAllAsync(spiAqs);     /* Find the SPI bus controller device with our selector string  */

                SpiDisplay = await SpiDevice.FromIdAsync(devicesInfo[0].Id, settings); /* Create an SpiDevice with our bus controller and SPI settings */
            }
            /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                throw new Exception("SPI Initialization Failed", ex);
            }
        }
Example #7
0
        /// <summary>Executes the command.</summary>
        /// <returns>The command's exit code.</returns>
        public int Execute()
        {
            Console.WriteLine($"BusId={BusId}, ChipSelectLine={ChipSelectLine}, Mode={Mode}, DataBitLength={DataBitLength}, ClockFrequency={ClockFrequency}, HexString={HexString}");

            var connectionSettings = new SpiConnectionSettings(BusId, ChipSelectLine)
            {
                ClockFrequency = ClockFrequency,
                DataBitLength  = DataBitLength,
                Mode           = Mode,
            };

            using (var spiDevice = SpiDevice.Create(connectionSettings))
            {
                // This will verify value as in hexadecimal.
                var writeBuffer = HexStringUtilities.HexStringToByteArray(HexString);
                spiDevice.Write(writeBuffer.AsSpan());
            }

            return(0);
        }
Example #8
0
        public async Task InitAsync()
        {
            var gpioController = GpioController.GetDefault();

            rstPin = gpioController.OpenPin(17);
            rstPin.SetDriveMode(GpioPinDriveMode.Output);
            busyPin = gpioController.OpenPin(24);
            busyPin.SetDriveMode(GpioPinDriveMode.Input);
            dataPin = gpioController.OpenPin(25);
            dataPin.SetDriveMode(GpioPinDriveMode.Output);
            //tstPin = gpioController.OpenPin(18);
            var spiController = await SpiController.GetDefaultAsync();

            var spiSetting = new SpiConnectionSettings(0);

            spiSetting.ClockFrequency = 2000000;
            spiSetting.Mode           = SpiMode.Mode0;
            //spiSetting.DataBitLength = 8;
            spi = spiController.GetDevice(spiSetting);
        }
        public BinaryChunkWriterTest(string fileName)
        {
            using (SpiDevice spi = SpiDevice.Create(new SpiConnectionSettings(1, 0)
            {
                Mode = SpiMode.Mode0, ClockFrequency = 900000
            }))
            {
                _accelerometerDevice = new Mcp3208Custom(spi, (int)Channel.X, (int)Channel.Y, (int)Channel.Z);
            }
            // _accelerometerDevice = new Accelerometer(new SpiConnectionSettings(0, 0) { Mode = SpiMode.Mode0, ClockFrequency = 1900000 });
            _gyroscopeDevice = new Gyroscope(new SpiConnectionSettings(0, 0)
            {
                Mode = SpiMode.Mode0, ClockFrequency = 900000
            });
            _cpuDevice = new CpuTemperature();
            _rtcDevice = new RTC();
            _uart      = new UART();

            fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
        }
Example #10
0
        ///<summary>
        ///Initializes the component asynchronously.
        ///</summary>
        ///<param name="spiControllerName">The name of the Spi controller.</param>
        ///<param name="spiChipLine">The spi chip select line number.</param>
        ///<returns><see cref="IAsyncAction"/></returns>
        public async Task InitAsync(string spiControllerName, int spiChipLine)
        {
            var settings = new SpiConnectionSettings(spiChipLine)
            {
                Mode           = SpiMode.Mode3,
                ClockFrequency = SpiClockFrequency
            };

            string spis        = SpiDevice.GetDeviceSelector(spiControllerName);
            var    devicesInfo = await DeviceInformation.FindAllAsync(spis);

            if (devicesInfo.Count == 0)
            {
                throw new ArgumentException("No device information for the provided parameters.");
            }

            _spiDevice = await SpiDevice.FromIdAsync(devicesInfo[0].Id, settings);

            Reset();
        }
Example #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BarGraphClick"/> class.
        /// </summary>
        /// <param name="socket">The socket on which the BarGraph Click board is plugged on MikroBus.Net</param>
        /// <param name="initialBrightness">Initial brightness in the range 0.0 (no display) to 1.0 (full brightness)</param>
        public BarGraphClick(Hardware.Socket socket, Double initialBrightness = 1.0)
        {
            _socket = socket;
            // Initialize SPI
            _bargraph = SpiController.FromName(socket.SpiBus).GetDevice(new SpiConnectionSettings()
            {
                ChipSelectType = SpiChipSelectType.Gpio,
                ChipSelectLine = GHIElectronics.TinyCLR.Devices.Gpio.GpioController.GetDefault().OpenPin(socket.Cs),
                Mode           = SpiMode.Mode0,
                ClockFrequency = 2000000
            });

            // Initialize PWM and set initial brightness
            var PWM = PwmController.FromName(socket.PwmController);

            PWM.SetDesiredFrequency(5000);
            _pwm = PWM.OpenChannel(socket.PwmChannel);
            _pwm.SetActiveDutyCyclePercentage(initialBrightness);
            _pwm.Start();
        }
        /// <summary>
        /// Initialize SPI
        /// </summary>
        private async Task InitSPI()
        {
            Message = "Initializing SPI..";
            var spiController = await SpiController.GetDefaultAsync();

            if (spiController == null)
            {
                return;
            }

            // Sepcify settings for the SPI device.
            this.spiDevice = spiController.GetDevice(new SpiConnectionSettings(0)
            {
                ClockFrequency = 10000,
                DataBitLength  = 8,
                Mode           = SpiMode.Mode0
            });

            Message = "SPI initialized correctly.";
        }
Example #13
0
        private static async void InitSPI()
        {
            try
            {
                var settings = new SpiConnectionSettings(SpiChipSelectLine)
                {
                    ClockFrequency = 500000,
                    Mode           = SpiMode.Mode0
                };

                var spiAqs     = SpiDevice.GetDeviceSelector(SpiControllerName);
                var deviceInfo = await DeviceInformation.FindAllAsync(spiAqs);

                _spiDisplay = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings);
            }
            catch (Exception ex)
            {
                throw new Exception("SPI Initialization Failed", ex);
            }
        }
Example #14
0
        public Mpu9250Device(SpiDevice device)
        {
            // Validate
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }

            // Initialize hardware
            Hardware = device;

            // Reset the device to default setting
            this.Reset();

            // Set clock source
            Hardware.WriteJoinByte((byte)Mpu9250Register.PowerManagment1, 0x01);

            // Set I2C master mode
            Hardware.WriteJoinByte((byte)Mpu9250Register.UserControl, 0x20);

            // Set I2C configureation multi-master IIC 400KHz.
            Hardware.WriteJoinByte((byte)Mpu9250Register.I2cMasterControl, 0x0D);

            // Set temprature bandwidth to 188Hz and gyroscope bandwidth to 184Hz.
            Hardware.WriteJoinByte((byte)Mpu9250Register.Config, 0x00);

            // Verify the device is connected, accessable and ready for use.
            if (ChipId == 0x71 & Ak8963ChipId == 0x48)
            {
                IsConnected = true;
            }

            // Initialize sensor reading
            SensorReading = new Mpu9250SensorReading();

            // Initialize sensor axis offset data
            AxisOffset = new Mpu9250OffsetReading()
            {
                MagXAxisSensitivity = 1, MagYAxisSensitivity = 1, MagZAxisSensitivity = 1
            };
        }
Example #15
0
        /// <summary>
        /// Setup for the MAX31856, which sets the chip select pin and the configurations/defaults
        /// </summary>
        /// <param name="thermocoupleType">Type of thermocouple based on ThermocoupleType enum</param>
        /// <param name="averageSamples">Representation of the number of samples to get an average from, range from 0 to 4, which respectively corresponds to 1, 2, 4, 8, or 16 samples (1*(2^averageSamples))</param>
        /// <param name="gpioController">GpioController specified for this device</param>
        /// <param name="spiDisplay">SpiDevice specified for this device</param>
        /// <param name="chipSelectPin">Chip select pin number specified by the device</param>
        public MAX31856(ref GpioController _gpioController, ref SpiDevice _spiDisplay, int chipSelectPin, ThermocoupleType thermocoupleType = ThermocoupleType.K, int averageSamples = 0)
        {
            // Set up device's gpio controller and spi device and chip select pin
            this.Setup(ref _gpioController, ref _spiDisplay, chipSelectPin);

            /*** SET UP THE CONFIGURATION AND ALL DEFAULTS FOR THE MAX31856 ***/

            // Set the Cold-Junction Temperature Offset to 0 first (important to do before setting up Configuration 0)
            WriteRegister(MAX31856_REG_WRITE_CJTO, 0x0);

            // Set Configuration 0 (conversion mode, one-shot mode fault configuration)
            WriteRegister(MAX31856_REG_WRITE_CR0, 0x82); // 0x80 is for continuous reading, but 0x40 is for one shot reading

            // Set Configuration 1 (Type of thermocouple, how many samples to average from)
            // Do some checks on averageSamples: default to 0, make sure it's not more than 4 or less than 0
            averageSamples = (averageSamples < 0 || averageSamples > 4) ? 0 : averageSamples;
            WriteRegister(MAX31856_REG_WRITE_CR1, (byte)((averageSamples << 4) + (int)thermocoupleType));

            // Set Fault Mask Register
            WriteRegister(MAX31856_REG_WRITE_MASK, 0xFF);

            // Set Cold-Junction Temperature Thresholds (defaults for now)
            WriteRegister(MAX31856_REG_WRITE_CJHF, 0x7F);
            WriteRegister(MAX31856_REG_WRITE_CJLF, 0xC0);

            // Set Linear Temperature Thresholds (defaults for now)
            WriteRegister(MAX31856_REG_WRITE_LTHFTH, 0x7F);
            WriteRegister(MAX31856_REG_WRITE_LTHFTL, 0xFF);
            WriteRegister(MAX31856_REG_WRITE_LTLFTH, 0x80);
            WriteRegister(MAX31856_REG_WRITE_LTLFTL, 0x00);

            // Just for testing to see if it accurately sets values to the register
            var cr0Config = ReadRegister(MAX31856_REG_READ_CR0);
            var cr1Config = ReadRegister(MAX31856_REG_READ_CR1);
            var faultMask = ReadRegister(MAX31856_REG_READ_MASK);
            var coldJunctionThresholds        = ReadRegister(MAX31856_REG_READ_CJHF, 2);   // Gets MAX31856_REG_READ_CJHF and MAX31856_REG_READ_CJLF
            var linearTemperatureThresholds   = ReadRegister(MAX31856_REG_READ_LTHFTH, 4); // Grabs MAX31856_REG_READ_LTHFTH, MAX31856_REG_READ_LTHFTL, MAX31856_REG_READ_LTLFTH, and MAX31856_REG_READ_LTLFTL
            var coldJunctionTemperatureOffset = ReadRegister(MAX31856_REG_READ_CJTO);
            //Verify the defaults
            var taco = cr0Config;
        }
Example #16
0
        private async Task EnsureInitializedAsync()
        {
            // If already initialized, done
            if (isInitialized)
            {
                return;
            }

            // Validate
            if (string.IsNullOrWhiteSpace(controllerName))
            {
                throw new MissingIoException(nameof(ControllerName));
            }

            // Create SPI initialization settings
            var settings = new SpiConnectionSettings(chipSelectLine);

            // Datasheet specifies maximum SPI clock frequency of 0.5MHz
            settings.ClockFrequency = 500000;

            // The ADC expects idle-low clock polarity so we use Mode0
            settings.Mode = SpiMode.Mode0;

            // Find the selector string for the SPI bus controller
            string spiAqs = SpiDevice.GetDeviceSelector(controllerName);

            // Find the SPI bus controller device with our selector string
            var deviceInfo = (await DeviceInformation.FindAllAsync(spiAqs)).FirstOrDefault();

            // Make sure device was found
            if (deviceInfo == null)
            {
                throw new DeviceNotFoundException(controllerName);
            }

            // Create an SpiDevice with our bus controller and SPI settings
            spiDevice = await SpiDevice.FromIdAsync(deviceInfo.Id, settings);

            // Done initializing
            isInitialized = true;
        }
Example #17
0
        public SpiDeviceManager(Board board, SpiConnectionSettings connectionSettings, int[]?pins, Func <SpiConnectionSettings, int[], SpiDevice> createOperation)
        {
            if (pins == null || pins.Length < 3 || pins.Length > 4)
            {
                throw new ArgumentException("Must provide a valid set of 3 or 4 pins", nameof(pins));
            }

            _board             = board;
            ConnectionSettings = connectionSettings;
            try
            {
                _board.ReservePin(pins[0], PinUsage.Spi, this);
                _board.ReservePin(pins[1], PinUsage.Spi, this);
                _board.ReservePin(pins[2], PinUsage.Spi, this);
                if (pins.Length == 4)
                {
                    // The fourth pin, if provided, is the CS line. This may be handled manually, but if done in hardware, SPI
                    // numbering must be used here I think. So the value would be 0 or 1 for CE0 and CE1 in ALT 0 mode, which are
                    // the logical pins 7 and 8.
                    _board.ReservePin(pins[3], PinUsage.Spi, this);
                }

                _device = createOperation(connectionSettings, pins);
            }
            catch (Exception x)
            {
                // TODO: Replace with logging
                Debug.WriteLine($"Exception: {x}");
                _board.ReleasePin(pins[0], PinUsage.Spi, this);
                _board.ReleasePin(pins[1], PinUsage.Spi, this);
                _board.ReleasePin(pins[2], PinUsage.Spi, this);
                if (pins.Length == 4)
                {
                    _board.ReleasePin(pins[3], PinUsage.Spi, this);
                }

                throw;
            }

            _pins = pins;
        }
Example #18
0
        private void InitSPI()
        {
            try
            {
                var settings = new SpiConnectionSettings(0);
                settings.ClockFrequency = 5000000;
                settings.Mode           = SpiMode.Mode0;

                string spiAqs     = SpiDevice.GetDeviceSelector("SPI0");
                var    deviceInfo = DeviceInformation.FindAllAsync(spiAqs).AsTask();
                Task.WaitAll(deviceInfo);
                var device = SpiDevice.FromIdAsync(deviceInfo.Result.First().Id, settings).AsTask();
                Task.WaitAll(device);
                thermocouple = device.Result;
            }

            catch (Exception ex)
            {
                throw new Exception("SPI Initialization Failed", ex);
            }
        }
        public async void InitializeSystem()
        {
            try
            {
                var deviceSelector = SpiDevice.GetDeviceSelector();
                var spiControllers = await DeviceInformation.FindAllAsync(deviceSelector);

                piFaceDigital = new PiFaceDigital(spiControllers[0]);
                await piFaceDigital.Init();

                this.TitleText.Text = "Use the outputs to control the LEDs.";
                piFaceDigital?.LEDs[7].SetAll();
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception: {0}", e.Message);
                piFaceDigital?.Dispose();
                this.TitleText.Text = "Initialization failed.";
                piFaceDigital       = null;
            }
        }
Example #20
0
        private async void InitSPI(int chipSelect, int clock, SpiMode mode, string controllerName)
        {
            try
            {
                //await Task.Delay(2000);

                var settings = new SpiConnectionSettings(chipSelect);
                settings.ClockFrequency = clock; // 0.5MHz clock rate
                settings.Mode           = mode;  // The ADC expects idle-low clock polarity so we use Mode0

                var controller = await SpiController.GetDefaultAsync();

                _spiDevice = controller.GetDevice(settings);
            }

            // If initialization fails, display the exception and stop running
            catch (Exception ex)
            {
                throw new Exception("SPI Initialization Failed", ex);
            }
        }
Example #21
0
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                    _spiDevice.Dispose();

                    CloseHat();

                    _controller.ClosePin(_gpioReset);
                    _controller.ClosePin(_gpioDc);
                    _controller.ClosePin(_gpioCs);
                }

                _spiDevice  = null;
                _controller = null;

                _disposedValue = true;
            }
        }
Example #22
0
        public async void InitSPIASync(byte vMinLevel, byte vMaxLevel)
        {
            SpiLog(LogType.Information, "Start initialization", "The intialization of the SPI communication class has started.");

            MinLevel = vMinLevel;
            MaxLevel = vMaxLevel;

            try
            {
                this.controller = await SpiController.GetDefaultAsync();

                this.AtMega_Settings = new SpiConnectionSettings(0);
                this.AtMega_Settings.ClockFrequency = 10000;         // 10kHz
                this.AtMega_Settings.Mode           = SpiMode.Mode3; // Mode3: CPOL = 1, CPHA = 1
                this.AtMega32A = this.controller.GetDevice(AtMega_Settings);
            }
            catch (Exception e)
            {
                SpiLog(LogType.Error, "Class Erro SPI Initializing", e.Message);
            }
        }
Example #23
0
        /* Initialize the SPI bus */
        private async Task InitSpi()
        {
            try
            {
                var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE);        /* Create SPI initialization settings                               */
                settings.ClockFrequency = 10000000;                                    /* Datasheet specifies maximum SPI clock frequency of 10MHz         */
                settings.Mode           = SpiMode.Mode3;                               /* The display expects an idle-high clock polarity, we use Mode3
                                                                                        * to set the clock polarity and phase to: CPOL = 1, CPHA = 1
                                                                                        */

                string spiAqs      = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME); /* Find the selector string for the SPI bus controller          */
                var    devicesInfo = await DeviceInformation.FindAllAsync(spiAqs);     /* Find the SPI bus controller device with our selector string  */

                SpiDisplay = await SpiDevice.FromIdAsync(devicesInfo[0].Id, settings); /* Create an SpiDevice with our bus controller and SPI settings */
            }
            /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                throw new Exception("SPI Initialization Failed", ex);
            }
        }
        private async void InitSPI()
        {
            try
            {
                // CS 0 -> Pin 24 in RPi
                var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE);
                /* 1MHz clock rate */
                settings.ClockFrequency = 1000000;
                /* The ADC expects idle-low clock polarity so we use Mode0  */
                settings.Mode = SpiMode.Mode0;
                /* Controller Name in the Pi SPI0 or SPI1  */
                string spiAqs     = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME);
                var    deviceInfo = await DeviceInformation.FindAllAsync(spiAqs);

                SpiADC = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Example #25
0
        public Rfm9XDevice(string spiPort, int chipSelectPin, int resetPin)
        {
            var settings = new SpiConnectionSettings(chipSelectPin)
            {
                ClockFrequency = 1000000,
                Mode           = SpiMode.Mode0,// From SemTech docs pg 80 CPOL=0, CPHA=0
                SharingMode    = SpiSharingMode.Shared
            };

            rfm9XLoraModem = SpiDevice.FromId(spiPort, settings);

            // Factory reset pin configuration
            GpioController gpioController = GpioController.GetDefault();
            GpioPin        resetGpioPin   = gpioController.OpenPin(resetPin);

            resetGpioPin.SetDriveMode(GpioPinDriveMode.Output);
            resetGpioPin.Write(GpioPinValue.Low);
            Thread.Sleep(10);
            resetGpioPin.Write(GpioPinValue.High);
            Thread.Sleep(10);
        }
Example #26
0
        static void Main(string[] args)
        {
            // SPI0 CS0
            SpiConnectionSettings senderSettings = new SpiConnectionSettings(0, 0)
            {
                ClockFrequency = Nrf24l01.SpiClockFrequency,
                Mode           = Nrf24l01.SpiMode
            };
            // SPI1 CS0
            SpiConnectionSettings receiverSettings = new SpiConnectionSettings(1, 2)
            {
                ClockFrequency = Nrf24l01.SpiClockFrequency,
                Mode           = Nrf24l01.SpiMode
            };
            var senderDevice   = SpiDevice.Create(senderSettings);
            var receiverDevice = SpiDevice.Create(receiverSettings);

            // SPI Device, CE Pin, IRQ Pin, Receive Packet Size
            using (Nrf24l01 sender = new Nrf24l01(senderDevice, 23, 24, 20))
            {
                using (Nrf24l01 receiver = new Nrf24l01(receiverDevice, 5, 6, 20))
                {
                    // Set sender send address, receiver pipe0 address (Optional)
                    byte[] receiverAddress = Encoding.UTF8.GetBytes("NRF24");
                    sender.Address         = receiverAddress;
                    receiver.Pipe0.Address = receiverAddress;

                    // Binding DataReceived event
                    receiver.DataReceived += Receiver_ReceivedData;

                    // Loop
                    while (true)
                    {
                        sender.Send(Encoding.UTF8.GetBytes("Hello! .NET Core IoT"));

                        Thread.Sleep(2000);
                    }
                }
            }
        }
Example #27
0
        // ReSharper disable once SuggestBaseTypeForParameter
        private void PrepareSpiCommunication(SpiDevice device)
        {
            var timeout = DateTime.Now.AddSeconds(1);

            while (timeout > DateTime.Now)
            {
                var buff = new byte[1];

                device.Read(buff);

                while (_destination.Count > 7)
                {
                    _destination.Dequeue();
                }

                _destination.Enqueue(buff[0]);

                var arrayVal = _destination.ToArray();

                if (arrayVal != null &&
                    arrayVal[0] == 0 &&
                    arrayVal[1] == 250 &&
                    arrayVal[2] == 0 &&
                    arrayVal[3] == 85 &&
                    arrayVal[4] == 14 &&
                    arrayVal[5] == 236 &&
                    arrayVal[6] == 189 &&
                    arrayVal[7] == 0)
                {
                    return;
                }
            }

            throw new Exception("SPI Syncronization failed for SPI Device" +
                                " ChipSelectLine:" + device.ConnectionSettings?.ChipSelectLine +
                                " ClockFrequency:" + device.ConnectionSettings?.ClockFrequency +
                                " DataBitLength:" + device.ConnectionSettings?.DataBitLength +
                                " Mode:" + device.ConnectionSettings?.Mode +
                                " SharingMode:" + device.ConnectionSettings?.SharingMode);
        }
        /// <summary>
        ///     Open a connection to the ADCDAC 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 = 1100000,     // SPI clock frequency of 1.1MHz
                    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

                IsConnected = true;                  // connection established, set IsConnected to true.

                // 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 Initialization Failed", ex);
            }
        }
Example #29
0
        private async Task InitSPI()
        {
            try
            {
                var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE);
                settings.ClockFrequency = 1000000;// 1000000;// 10000000;// 3600000;// 1000000;// 500000;
                settings.Mode           = SpiMode.Mode0;

                string spiAqs     = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME);
                var    deviceInfo = await DeviceInformation.FindAllAsync(spiAqs);

                SpiADC = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings);

                ledPin2.Write(GpioPinValue.High);
            }

            catch (Exception ex)
            {
                Message = ex.Message;
                //throw new Exception("Lux:", ex);
            }
        }
Example #30
0
        public async void InitializeMCP3008(SerialCommunication serialcomunication, Channel channel, SpiCommunication spiComunication, SpiMode mode)
        {
            var spiConnectionSettings = new SpiConnectionSettings((int)spiComunication);

            //spiConnectionSettings.ClockFrequency = _P1733.CLOCK_SIGNAL;
            spiConnectionSettings.Mode = mode;

            string spiDevice         = SpiDevice.GetDeviceSelector(spiComunication.ToString());
            var    deviceInformation = await DeviceInformation.FindAllAsync(spiDevice);

            if (deviceInformation != null && deviceInformation.Count > 0)
            {
                _device = await SpiDevice.FromIdAsync(deviceInformation[0].Id, spiConnectionSettings);

                _CHOICECHANNEL = channel.ToString();
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Device could not be found");
                return;
            }
        }