/// <summary> /// Initializes new instance of Windows10SpiDevice that will use the specified settings to communicate with the SPI device. /// </summary> /// <param name="settings"> /// The connection settings of a device on a SPI bus. /// </param> public Windows10SpiDevice(SpiConnectionSettings settings) { if (settings.DataFlow != DataFlow.MsbFirst || settings.ChipSelectLineActiveState != PinValue.Low) { throw new PlatformNotSupportedException($"Changing {nameof(settings.DataFlow)} or {nameof(settings.ChipSelectLineActiveState)} options is not supported on the current platform."); } _settings = settings; var winSettings = new WinSpi.SpiConnectionSettings(_settings.ChipSelectLine) { Mode = ToWinMode(settings.Mode), DataBitLength = settings.DataBitLength, ClockFrequency = settings.ClockFrequency, }; string busFriendlyName = $"SPI{settings.BusId}"; string deviceSelector = WinSpi.SpiDevice.GetDeviceSelector(busFriendlyName); DeviceInformationCollection deviceInformationCollection = DeviceInformation.FindAllAsync(deviceSelector).WaitForCompletion(); if (deviceInformationCollection.Count == 0) { throw new ArgumentException($"No SPI device exists for bus ID {settings.BusId}.", $"{nameof(settings)}.{nameof(settings.BusId)}"); } _winDevice = WinSpi.SpiDevice.FromIdAsync(deviceInformationCollection[0].Id, winSettings).WaitForCompletion(); }
private async void Lightsetup() { var spiSettings = new SpiConnectionSettings(0); spiSettings.ClockFrequency = 3600000; spiSettings.Mode = SpiMode.Mode0; string spiQuery = SpiDevice.GetDeviceSelector("SPI0"); var deviceInfo = await DeviceInformation.FindAllAsync(spiQuery); if (deviceInfo != null && deviceInfo.Count > 0) { _mcp3008 = await SpiDevice.FromIdAsync(deviceInfo[0].Id, spiSettings); } else { textblocklight.Text = "SPI DEVICE BOT FOUND"; } }
public async void Initialize() { try { var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE); settings.ClockFrequency = 3600000; // 3.6MHz is the rated speed of the MCP3008 at 5v settings.Mode = SpiMode.Mode1; string aqs = SpiDevice.GetDeviceSelector(); /* Get a selector string that will return all SPI controllers on the system */ var dis = await DeviceInformation.FindAllAsync(aqs); /* Find the SPI bus controller devices with our selector string */ mcp3008 = await SpiDevice.FromIdAsync(dis[0].Id, settings); /* Create an SpiDevice with our bus controller and SPI settings */ if (mcp3008 == null) { Debug.WriteLine( "SPI Controller {0} is currently in use by " + "another application. Please ensure that no other applications are using SPI.", dis[0].Id); return; } } catch (Exception e) { Debug.WriteLine("Exception: " + e.Message + "\n" + e.StackTrace); throw; } }
// Sets up this instance of the SensorSource private async void Init() { await Task.Run(async () => { try { var settings = new SpiConnectionSettings(0); settings.ClockFrequency = 500000; settings.Mode = SpiMode.Mode0; string spi = SpiDevice.GetDeviceSelector("SPI0"); var deviceInfo = await DeviceInformation.FindAllAsync(spi); device = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings); isError = false; } catch (Exception ex) { isError = true; // Triggers the StateChanged event // false => sensor !isRunning (i.e. is not running due to error) / state => "INITIALIZE ERROR" StateChanged(this, new StateChangedEventArgs(false, "INITIALIZE ERROR")); Debug.WriteLine(ex.Message); } }).ContinueWith((task) => ReadData()); }
private SpiDevice spiDevice; // The SPI device the display is connected to #endregion // Member Variables #region Internal Methods 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); settings.ClockFrequency = 1000000; // 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; }
///<summary> ///Used to configure the RPi2 to communicate over the SPI bus to the MCP3008 ADC chip. /// </summary> /// public async void Initialize() { try { //Setup the SPI bus configuration var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE); //3.6MHz is the rated speed of the MCP3008 at 5V settings.ClockFrequency = 3600000; settings.Mode = SpiMode.Mode0; //Ask Windows for the list of SPI Devices //Get a selector string that will return all SPI Controllers on the system string aqs = SpiDevice.GetDeviceSelector(); //Find the SPI bus controller devices with our selector string var dis = await DeviceInformation.FindAllAsync(aqs); //Create an SPI device with our bus controller and SPI settings mcp3008 = await SpiDevice.FromIdAsync(dis[0].Id, settings); if (mcp3008 == null) { Debug.WriteLine("SPI controller {0} is currently in use by another application"); return; } } catch (Exception e) { Debug.WriteLine("Exception: " + e.Message + "\n" + e.StackTrace); throw; } }
// // Constructor // public TLC5947ControllerBase(uint latchPin, uint blackoutPin) { // Create the controller m_controller = new LedController(this, ControlerUpdateType.AllSlots); // Open the latch pin GpioController controller = GpioController.GetDefault(); m_latchPin = controller.OpenPin((int)latchPin); m_latchPin.SetDriveMode(GpioPinDriveMode.Output); // Open the black out pin, set it high and low to reset the device. m_blackoutPin = controller.OpenPin((int)blackoutPin); m_blackoutPin.SetDriveMode(GpioPinDriveMode.Output); m_blackoutPin.Write(GpioPinValue.High); m_blackoutPin.Write(GpioPinValue.Low); // Create a async task to setup SPI new Task(async () => { // Create the settings var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE); // Max SPI clock frequency, here it is 30MHz settings.ClockFrequency = 30000000; settings.Mode = SpiMode.Mode0; // Find the selector string for the SPI bus controller string spiAqs = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME); // Find the SPI bus controller device with our selector string var devicesInfo = await DeviceInformation.FindAllAsync(spiAqs); // Create an SpiDevice with our bus controller and SPI settings m_spiDevice = await SpiDevice.FromIdAsync(devicesInfo[0].Id, settings); }).Start(); }
private async Task StartScenarioAsync() { String spiDeviceSelector = SpiDevice.GetDeviceSelector(); IReadOnlyList<DeviceInformation> devices = await DeviceInformation.FindAllAsync(spiDeviceSelector); // 0 = Chip select line to use. var ADXL345_Settings = new SpiConnectionSettings(0); // 5MHz is the rated speed of the ADXL345 accelerometer. ADXL345_Settings.ClockFrequency = 5000000; // The accelerometer expects an idle-high clock polarity. // We use Mode3 to set the clock polarity and phase to: CPOL = 1, CPHA = 1. ADXL345_Settings.Mode = SpiMode.Mode3; // If this next line crashes with an ArgumentOutOfRangeException, // then the problem is that no SPI devices were found. // // If the next line crashes with Access Denied, then the problem is // that access to the SPI device (ADXL345) is denied. // // The call to FromIdAsync will also crash if the settings are invalid. // // FromIdAsync produces null if there is a sharing violation on the device. // This will result in a NullReferenceException a few lines later. adxl345Sensor = await SpiDevice.FromIdAsync(devices[0].Id, ADXL345_Settings); // // Initialize the accelerometer: // // For this device, we create 2-byte write buffers: // The first byte is the register address we want to write to. // The second byte is the contents that we want to write to the register. // // 0x31 is address of data format register, 0x01 sets range to +- 4Gs. byte[] WriteBuf_DataFormat = new byte[] { 0x31, 0x01 }; // 0x2D is address of power control register, 0x08 puts the accelerometer into measurement mode. byte[] WriteBuf_PowerControl = new byte[] { 0x2D, 0x08 }; // Write the register settings. // // If this next line crashes with a NullReferenceException, then // there was a sharing violation on the device. // (See comment earlier in this function.) // // If this next line crashes for some other reason, then there was // an error communicating with the device. adxl345Sensor.Write(WriteBuf_DataFormat); adxl345Sensor.Write(WriteBuf_PowerControl); // Start the polling timer. timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(100) }; timer.Tick += Timer_Tick; timer.Start(); }
internal async Task Initialize(byte frequency, byte nodeId, byte networkId) { var settings = new SpiConnectionSettings(0); settings.ClockFrequency = 5000000; /* 5MHz is the rated speed of the ADXL345 accelerometer */ settings.Mode = SpiMode.Mode3; string aqs = SpiDevice.GetDeviceSelector(); /* Get a selector string that will return all SPI controllers on the system */ var dis = await DeviceInformation.FindAllAsync(aqs); /* Find the SPI bus controller devices with our selector string */ _spiDevice = await SpiDevice.FromIdAsync(dis[0].Id, settings); /* Create an SpiDevice with our bus controller and SPI settings */ _spiDevice.ConnectionSettings.Mode = SpiMode.Mode0; _spiDevice.ConnectionSettings.ClockFrequency = 5000; _gpioController = GpioController.GetDefault(); _selectpin = _gpioController.OpenPin(22); _selectpin.SetDriveMode(GpioPinDriveMode.Output); byte[][] config = { new byte[] { REG_OPMODE, RF_OPMODE_SEQUENCER_ON | RF_OPMODE_LISTEN_OFF | RF_OPMODE_STANDBY }, new byte[] { REG_DATAMODUL, RF_DATAMODUL_DATAMODE_PACKET | RF_DATAMODUL_MODULATIONTYPE_FSK | RF_DATAMODUL_MODULATIONSHAPING_00 }, new byte[] { REG_BITRATEMSB, RF_BITRATEMSB_55555}, new byte[] { REG_BITRATELSB, RF_BITRATELSB_55555}, new byte[] { REG_FDEVMSB, RF_FDEVMSB_50000}, new byte[] { REG_FDEVLSB, RF_FDEVLSB_50000}, new byte[] { REG_FRFMSB, RF_FRFMSB_915 }, /* 0x08 */ new byte[] { REG_FRFMID, RF_FRFMID_915 }, /* 0x09 */ new byte[] { REG_FRFLSB, RF_FRFLSB_915 }, new byte[] { REG_RXBW, RF_RXBW_DCCFREQ_010 | RF_RXBW_MANT_16 | RF_RXBW_EXP_2 }, new byte[] { REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_01 }, new byte[] { REG_DIOMAPPING2, RF_DIOMAPPING2_CLKOUT_OFF }, new byte[]{ REG_IRQFLAGS2, RF_IRQFLAGS2_FIFOOVERRUN }, new byte[]{ REG_RSSITHRESH, 220 }, new byte[] { REG_SYNCCONFIG, RF_SYNC_ON | RF_SYNC_FIFOFILL_AUTO | RF_SYNC_SIZE_2 | RF_SYNC_TOL_0 }, new byte[]{ REG_SYNCVALUE1, 0x2D }, // attempt to make this compatible with sync1 byte of RFM12B lib /* 0x30 */ new byte[]{ REG_SYNCVALUE2, networkId }, // NETWORK ID /* 0x37 */ new byte[]{ REG_PACKETCONFIG1, RF_PACKET1_FORMAT_VARIABLE | RF_PACKET1_DCFREE_OFF | RF_PACKET1_CRC_ON | RF_PACKET1_CRCAUTOCLEAR_ON | RF_PACKET1_ADRSFILTERING_OFF }, /* 0x38 */ new byte[]{ REG_PAYLOADLENGTH, 66 }, // in variable length mode: the max frame size, not used in TX //* 0x39 */ { REG_NODEADRS, nodeID }, // turned off because we're not using address filtering /* 0x3C */ new byte[]{ REG_FIFOTHRESH, RF_FIFOTHRESH_TXSTART_FIFONOTEMPTY | RF_FIFOTHRESH_VALUE }, // TX on FIFO not empty /* 0x3D */ new byte[]{ REG_PACKETCONFIG2, RF_PACKET2_RXRESTARTDELAY_2BITS | RF_PACKET2_AUTORXRESTART_ON | RF_PACKET2_AES_OFF }, // RXRESTARTDELAY must match transmitter PA ramp-down time (bitrate dependent) //for BR-19200: /* 0x3D */ { REG_PACKETCONFIG2, RF_PACKET2_RXRESTARTDELAY_NONE | RF_PACKET2_AUTORXRESTART_ON | RF_PACKET2_AES_OFF }, // RXRESTARTDELAY must match transmitter PA ramp-down time (bitrate dependent) /* 0x6F */ new byte[]{ REG_TESTDAGC, RF_DAGC_IMPROVED_LOWBETA0 }, // run DAGC continuously in RX mode for Fading Margin Improvement, recommended default for AfcLowBetaOn=0 }; foreach (var configValue in config) { _spiDevice.Write(configValue); } SetHighPower(); }
private static async void InitSPI() { 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); }
/// <summary> /// Initializes a new instance of SpiDevice. /// </summary> /// <param name="deviceId">The unique name of the device.</param> /// <param name="settings">Settings to open the device with.</param> internal SpiDevice( string deviceId, SpiConnectionSettings settings ) { // Device ID must match the index in device information. // We don't have many buses, so just hard-code the valid ones instead of parsing. m_spiBus = GetBusNum( deviceId ); m_deviceId = deviceId.Substring( 0 ); m_settings = new SpiConnectionSettings( settings ); InitNative( ); }
/// <summary> /// Initializes a new instance of SpiDevice. /// </summary> /// <param name="deviceId">The unique name of the device.</param> /// <param name="settings">Settings to open the device with.</param> internal SpiDevice(string deviceId, SpiConnectionSettings settings) { // Device ID must match the index in device information. // We don't have many buses, so just hard-code the valid ones instead of parsing. m_spiBus = GetBusNum(deviceId); m_deviceId = deviceId.Substring(0); m_settings = new SpiConnectionSettings(settings); InitNative( ); }
public async Task Initialize() { var spiAqs = SpiDevice.GetDeviceSelector(); var devicesInfo = await DeviceInformation.FindAllAsync(spiAqs); var settings = new SpiConnectionSettings(0); settings.ClockFrequency = 1000000; settings.DataBitLength = 8; settings.SharingMode = SpiSharingMode.Shared; Device = await SpiDevice.FromIdAsync(devicesInfo[0].Id, settings); }
public async Task Initialise() { var settings = new SpiConnectionSettings(SpiChipSelectLine) { ClockFrequency = 500000, Mode = SpiMode.Mode0 }; var spiAqs = SpiDevice.GetDeviceSelector(SpiControllerName); var deviceInfo = await DeviceInformation.FindAllAsync(spiAqs); _spiDevice = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings); }
private async Task InitTSC2046SPI() { var touchSettings = new SpiConnectionSettings(CS_PIN); touchSettings.ClockFrequency = 125000; touchSettings.Mode = SpiMode.Mode0; //Mode0,1,2,3; MCP23S17 needs mode 0 string DispspiAqs = SpiDevice.GetDeviceSelector( "SPI0"); var DispdeviceInfo = await DeviceInformation.FindAllAsync(DispspiAqs); touchSPI = await SpiDevice.FromIdAsync(DispdeviceInfo[0].Id, touchSettings); //set vars _lastTouchPosition = new Point(double.NaN, double.NaN); _currentPressure = 0; }
public async Task Init(string spi) { var settings = new SpiConnectionSettings(0) { ClockFrequency = 8000000, Mode = SpiMode.Mode0 }; var spiAqs = SpiDevice.GetDeviceSelector(spi); var devicesInfo = await DeviceInformation.FindAllAsync(spiAqs); this.shiftRegister = await SpiDevice.FromIdAsync(devicesInfo[0].Id, settings); }
public async Task InitializeSPI_Async() { var selector = SpiDevice.GetDeviceSelector(); var devices = await DeviceInformation.FindAllAsync(selector); var screenSettings = new SpiConnectionSettings(_spiChannel); screenSettings.ClockFrequency = _clockSpeed; screenSettings.Mode = SpiMode.Mode0; screenSettings.DataBitLength = 8; screenSettings.SharingMode = SpiSharingMode.Shared; _screenSPI = await SpiDevice.FromIdAsync(devices[0].Id, screenSettings); }
private async Task InitSPI(ChipSelect cs) { try { var settings = new SpiConnectionSettings((int)cs); settings.ClockFrequency = 500000;// 10000000; settings.Mode = SpiMode.Mode0; //Mode3; string spiAqs = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME); var deviceInfo = await DeviceInformation.FindAllAsync(spiAqs); SpiMCP3200 = 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); } }
private async void InitSPIAndTimer() { try { var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE); settings.ClockFrequency = 3000000;// 3200000;3000000;500000 settings.Mode = SpiMode.Mode0; string spiAqs = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME); var deviceInfo = await DeviceInformation.FindAllAsync(spiAqs); m_spiDev = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings); m_timer.Start(); } catch (Exception) { uxBytes.Text = "NO SPI!"; m_spiDev = null; } }
public async void InitSPI(int selectline = 0) { try { var settings = new SpiConnectionSettings(selectline); settings.ClockFrequency = 500000; settings.Mode = SpiMode.Mode0; string deviceSelector = SpiDevice.GetDeviceSelector("SPI0"); var deviceInfo = await DeviceInformation.FindAllAsync(deviceSelector); SpiDisplay = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings); } catch (Exception ex) { throw new Exception("SPI Initialization Failed", ex); } }
private async Task InitSpi() { try { var settingsSPI = new SpiConnectionSettings(0); settingsSPI.ClockFrequency = 10000000; settingsSPI.Mode = SpiMode.Mode3; string SPIController = SpiDevice.GetDeviceSelector("SPI0"); var deviceInfo = await DeviceInformation.FindAllAsync(SPIController); SPI = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settingsSPI); } catch (Exception ex) { throw new Exception("SPI Initialization Failed", ex); } }
public async void Initialize() { GpioPin cePin = GpioController.GetDefault().OpenPin(26); SpiConnectionSettings settings = new SpiConnectionSettings(0) { ClockFrequency = 1000000, Mode = SpiMode.Mode0 }; string spiAqs = SpiDevice.GetDeviceSelector("SPI0"); DeviceInformationCollection devicesInfo = await DeviceInformation.FindAllAsync(spiAqs); SpiDevice spiDevice = await SpiDevice.FromIdAsync(devicesInfo[0].Id, settings); _radio = new Radio(cePin, spiDevice); _radio.Begin(); string details = _radio.GetDetails(); }
private async void InitMcp3008() { // using SPI0 on the Pi var spiSettings = new SpiConnectionSettings(0); //for spi bus index 0 spiSettings.ClockFrequency = 10000; // 10kHz-3.6MHz spiSettings.Mode = SpiMode.Mode0; var spiQuery = SpiDevice.GetDeviceSelector("SPI0"); var deviceInfo = await DeviceInformation.FindAllAsync(spiQuery); if (deviceInfo != null && deviceInfo.Count > 0) { _mcp3008 = await SpiDevice.FromIdAsync(deviceInfo[0].Id, spiSettings); } else { throw new InvalidOperationException("No MCP3008 found at SPI0"); } }
private async void InitializeSpi() //declare function called Spi. { try { var settings = new SpiConnectionSettings(CHIP_SELECT); //setup SPI settings. settings.ClockFrequency = 1000000; //set clock frequency to 1MHz. settings.Mode = SpiMode.Mode0; //set spi mode to 0: clk idle low, latch on rising edge string SpiInput = SpiDevice.GetDeviceSelector(INPUT_CHANNEL); //Select which Input channel to read from. var DeviceInfo = await DeviceInformation.FindAllAsync(SpiInput); //Find asynchronous signals from A/DC SpiDisplay = await SpiDevice.FromIdAsync(DeviceInfo[0].Id, settings); // Starts an asynchronous object } catch (Exception ex) //If this doesnt work. { throw new Exception("Spi Initialization Failed", ex); //send exception to UI. } }
private 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"; } }
/// <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); } }
public static async Task<SN74HC595> Create(int chipSelectLine) { var settings = new SpiConnectionSettings(chipSelectLine) { ClockFrequency = 1000000, Mode = SpiMode.Mode0, DataBitLength = 8 }; var aqs = SpiDevice.GetDeviceSelector(); var dis = await DeviceInformation.FindAllAsync(aqs); if (!dis.Any()) throw new Exception("No SPI controllers"); var spi = await SpiDevice.FromIdAsync(dis[0].Id, settings); if (spi == null) throw new Exception(string.Format("SPI Controller '{0}' could not be initialized", dis[0].Id)); return new SN74HC595(spi); }
private async Task<LEDPanel> CreateLEDPanel() { var settings = new SpiConnectionSettings(CHIP_SELECT_LINE) { ClockFrequency = 40000, Mode = SpiMode.Mode0, DataBitLength = 8 }; var aqs = SpiDevice.GetDeviceSelector(); var dis = await DeviceInformation.FindAllAsync(aqs); if (!dis.Any()) throw new Exception("No SPI controllers"); var spi = await SpiDevice.FromIdAsync(dis[0].Id, settings); if (spi == null) throw new Exception(string.Format("SPI Controller '{0}' could not be initialized", dis[0].Id)); return new LEDPanel(spi, 5); }
private async void btnConnect_Click(object sender, RoutedEventArgs e) { //using SPI0 on the Pi var spiSettings = new SpiConnectionSettings(0);//for spi bus index 0 spiSettings.ClockFrequency = 3600000; //3.6 MHz spiSettings.Mode = SpiMode.Mode0; string spiQuery = SpiDevice.GetDeviceSelector("SPI0"); //using Windows.Devices.Enumeration; var deviceInfo = await DeviceInformation.FindAllAsync(spiQuery); if(deviceInfo!=null && deviceInfo.Count > 0) { _mcp3008 = await SpiDevice.FromIdAsync(deviceInfo[0].Id, spiSettings); btnConnect.IsEnabled = false; } else { txtHeader.Text = "SPI Device Not Found :-("; } }
public OneCoreSpi(string portName, int chipSelect, int speed) { var controller = GpioController.GetDefault(); if (controller == null) { throw new InvalidOperationException("GpioController"); } var settings = new SpiConnectionSettings(chipSelect); settings.ClockFrequency = speed; /* The display expects an idle-high clock polarity, we use Mode3 * to set the clock polarity and phase to: CPOL = 1, CPHA = 1 */ settings.Mode = SpiMode.Mode3; var spiAqs = SpiDevice.GetDeviceSelector(portName); var devicesInfo = DeviceInformation.FindAllAsync(spiAqs).GetResults(); this.spi = SpiDevice.FromIdAsync(devicesInfo[0].Id, settings).GetResults(); }
/// <summary> /// Initializes a new instance of the <see cref="Windows10SpiDevice"/> class that will use the specified settings to communicate with the SPI device. /// </summary> /// <param name="settings"> /// The connection settings of a device on a SPI bus. /// </param> public Windows10SpiDevice(SpiConnectionSettings settings) { if (settings.ChipSelectLineActiveState != PinValue.Low) { throw new PlatformNotSupportedException($"Changing{nameof(settings.ChipSelectLineActiveState)} options is not supported on the current platform."); } if (settings.DataFlow == DataFlow.LsbFirst) { _isInverted = true; } _settings = settings; // -1 means ignore Chip Select Line int chipSelectLine = _settings.ChipSelectLine == -1 ? 0 : _settings.ChipSelectLine; var winSettings = new WinSpi.SpiConnectionSettings(chipSelectLine) { Mode = ToWinMode(settings.Mode), DataBitLength = settings.DataBitLength, ClockFrequency = settings.ClockFrequency, }; string busFriendlyName = $"SPI{settings.BusId}"; string deviceSelector = WinSpi.SpiDevice.GetDeviceSelector(busFriendlyName); DeviceInformationCollection?deviceInformationCollection = DeviceInformation.FindAllAsync(deviceSelector).WaitForCompletion(); if (deviceInformationCollection is null || deviceInformationCollection.Count == 0) { throw new ArgumentException($"No SPI device exists for bus ID {settings.BusId}.", $"{nameof(settings)}.{nameof(settings.BusId)}"); } WinSpi.SpiDevice?winDevice = WinSpi.SpiDevice.FromIdAsync(deviceInformationCollection[0].Id, winSettings).WaitForCompletion(); if (winDevice is null) { throw new Exception("A SPI device could not be found."); } _winDevice = winDevice; }
internal SpiDevice(string spiBus, SpiConnectionSettings settings) { // spiBus is an ASCII string with the bus name in format 'SPIn' // need to grab 'n' from the string and convert that to the integer value from the ASCII code (do this by subtracting 48 from the char value) var controllerId = spiBus[3] - '0'; // Save reference to SpiController for _syncLock on controller // Each controller needs to restrict access from multiple threads // this will also work for same device from multiple threads _spiController = SpiController.FindController(controllerId); if (_spiController == null) { // this controller doesn't exist yet, create it... _spiController = new SpiController(spiBus); } try { _connectionSettings = new SpiConnectionSettings(settings); _deviceId = NativeOpenDevice(); } catch (NotSupportedException) { // NotSupportedException // Device(chip select) already in use throw new SpiDeviceAlreadyInUseException(); } catch (Exception ex) { // ArgumentException // Invalid port or unable to init bus // IndexOutOfRangeException // Too many devices open or spi already in use throw ex; } // device doesn't exist, create it... _connectionSettings = new SpiConnectionSettings(settings); _syncLock = new object(); }
/// <summary> /// Inits the SPI for later use. Must be performed prior to any operation /// </summary> /// <param name="SelectedLine">Selected Line (0 for SPI0 port, 1 for SPI1 port...)</param> /// <param name="clockFrecuency">Clock frecuency for the MCP3008 in hz. 3.6Mhz is recommended (3600000)</param> /// <param name="mode">SPI Mode</param> /// <returns>True if init is successfull. False if not.</returns> public async Task<bool> spiInit(int SelectedLine, int clockFrecuency, SpiMode mode) { // Using SPD0 on RaspBerry PI 2 var spiSettings = new SpiConnectionSettings(SelectedLine); spiSettings.ClockFrequency = clockFrecuency; spiSettings.Mode = mode; string spiQuery = SpiDevice.GetDeviceSelector("SPI" + SelectedLine.ToString()); var deviceInfo = await DeviceInformation.FindAllAsync(spiQuery); if (deviceInfo?.Count > 0) { _mcp3008 = await SpiDevice.FromIdAsync(deviceInfo[0].Id, spiSettings); return true; } else { _mcp3008 = null; return false; } }
/// <summary> /// Initializes new instance of Windows10SpiDevice that will use the specified settings to communicate with the SPI device. /// </summary> /// <param name="settings"> /// The connection settings of a device on a SPI bus. /// </param> public Windows10SpiDevice(SpiConnectionSettings settings) { _settings = settings; var winSettings = new WinSpi.SpiConnectionSettings(_settings.ChipSelectLine) { Mode = ToWinMode(settings.Mode), DataBitLength = settings.DataBitLength, ClockFrequency = settings.ClockFrequency, }; string busFriendlyName = $"SPI{settings.BusId}"; string deviceSelector = WinSpi.SpiDevice.GetDeviceSelector(busFriendlyName); DeviceInformationCollection deviceInformationCollection = DeviceInformation.FindAllAsync(deviceSelector).WaitForCompletion(); if (deviceInformationCollection.Count == 0) { throw new ArgumentException($"No SPI device exists for bus ID {settings.BusId}.", $"{nameof(settings)}.{nameof(settings.BusId)}"); } _winDevice = WinSpi.SpiDevice.FromIdAsync(deviceInformationCollection[0].Id, winSettings).WaitForCompletion(); }
/// <summary> /// Opens a device with the connection settings provided. /// </summary> /// <param name="busId">The id of the bus.</param> /// <param name="settings"></param> /// <returns></returns> public static SpiDevice FromId(string busId, SpiConnectionSettings settings) { // FUTURE: This should be "Task<SpiDevice*> FromIdAsync(...)" switch (settings.Mode) { case SpiMode.Mode0: case SpiMode.Mode1: case SpiMode.Mode2: case SpiMode.Mode3: break; default: throw new ArgumentException( ); } switch (settings.SharingMode) { case SpiSharingMode.Exclusive: case SpiSharingMode.Shared: break; default: throw new ArgumentException( ); } switch (settings.DataBitLength) { case 8: case 16: break; default: throw new ArgumentException( ); } return(new SpiDevice(busId, settings)); }
/// <summary> /// Opens a device with the connection settings provided. /// </summary> /// <param name="busId">The id of the bus.</param> /// <param name="settings">The connection settings.</param> /// <returns>The SPI device requested.</returns> /// <remarks>This method is specific to nanoFramework. The equivalent method in the UWP API is: FromIdAsync.</remarks> /// <exception cref="System.NotSupportedException"> /// Thrown if the chip select pin is already in use</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown if the maximum number of devices on SPI bus is reached</exception> /// <exception cref="System.ArgumentException"> /// Thrown if invalid SPI bus</exception> /// <exception cref="System.SystemException"> /// Thrown if GPIO pin already in use.</exception> public static SpiDevice FromId(string busId, SpiConnectionSettings settings) { //TODO: some sanity checks on busId return(new SpiDevice(busId, settings)); }
/// <summary> /// Gets the SPI device with the specified settings. /// </summary> /// <param name="settings">The desired connection settings.</param> /// <returns>The SPI device.</returns> /// <exception cref="System.NotSupportedException"> /// Thrown if the chip select pin is already in use</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown if the maximum number of devices on SPI bus is reached</exception> /// <exception cref="System.ArgumentException"> /// Thrown if invalid SPI bus</exception> /// <exception cref="System.SystemException"> /// Thrown if GPIO pin already in use.</exception> public SpiDevice GetDevice(SpiConnectionSettings settings) { //TODO: fix return value. Should return an existing device (if any), not really documented what it does // Although examples seen to just open device against current controller return(new SpiDevice($"SPI{_controllerId}", settings)); }