/// <summary> /// Transfers data to and from the SPI device in duplex mode. /// </summary> /// <param name="Buffer">The buffer containing the data to write. After the transfer, this will contain /// the data that was read from the device.</param> public void TransferData(byte[] Buffer) { lock (TransferLock) { GCHandle bufferHandle = GCHandle.Alloc(Buffer, GCHandleType.Pinned); PiSpi_Result result = PiSpi_TransferData(Handle, bufferHandle.AddrOfPinnedObject(), (uint)Buffer.Length); bufferHandle.Free(); if (result != PiSpi_Result.PiSpi_OK) { string error = Marshal.PtrToStringAnsi(PiSpi_GetLastError()); throw new Exception($"Error during a SPI transfer: {error}"); } } }
/// <summary> /// Creates a new SPI device. This will use the standard SPI device 0 pins for SCLK, MISO, and MOSI. /// It will also initialize the chip select pin to output mode and set it HIGH. /// </summary> /// <param name="ChipSelectPin">The number of the chip select pin for this device. This uses the /// BCM pin layout. To find what the pin number is for a given physical pin, run `gpio readall` /// on your Pi.</param> /// <param name="BitRate">The speed of the SPI communications for this device, in Hz.</param> /// <param name="Mode">The SPI mode that this device uses</param> /// <param name="TimeBeforeRead">The delay (in microseconds) between pulling the chip select pin low /// and starting to read/write data from/to the device.</param> /// <param name="TimeBetweenBytes">The delay (in microseconds) to wait between reading and writing /// individual bytes. Some devices have specific timings for this; consult your device's datasheet. /// </param> /// <param name="TimeAfterRead">The delay (in microseconds) to wait after finishing a data read/write /// before setting the chip select pin back to high (unselecting the device).</param> /// <param name="TimeBetweenReads">The delay (in microseconds) to wait after unselecting a device before /// it can be selected again for a subsequent read/write.</param> public SpiDevice( byte ChipSelectPin, uint BitRate, SpiMode Mode, byte TimeBeforeRead, byte TimeBetweenBytes, byte TimeAfterRead, byte TimeBetweenReads) { PiSpi_Result result = PiSpi_CreateDevice(ChipSelectPin, BitRate, Mode, TimeBeforeRead, TimeBetweenBytes, TimeAfterRead, TimeBetweenReads, out IntPtr handle); if (result != PiSpi_Result.PiSpi_OK) { string error = Marshal.PtrToStringAnsi(PiSpi_GetLastError()); throw new Exception($"Error creating SPI device: {error}"); } Handle = handle; }