/// <summary>
        ///   Initializes SPI connection and control pins
        /// </summary>
        public void Initialize(SpiMode spiMode, int chipSelectPin, int chipEnablePin, int interruptPin)
        {
            var gpio = GpioController.GetDefault();
            // Chip Select : Active Low
            // Clock : Active High, Data clocked in on rising edge
            _spiDevice = InitSpi(chipSelectPin, spiMode).Result;

            _irqPin = gpio.OpenPin(interruptPin);
            _irqPin.SetDriveMode(GpioPinDriveMode.InputPullUp);

            // Initialize IRQ Port
            // _irqPin = new InterruptPort(interruptPin, false, Port.ResistorMode.PullUp,
            //                            Port.InterruptMode.InterruptEdgeLow);
            _irqPin.ValueChanged += _irqPin_ValueChanged;

            _cePin = gpio.OpenPin(chipEnablePin);
            // Initialize Chip Enable Port
            _cePin.SetDriveMode(GpioPinDriveMode.Output);

            // Module reset time
            var task = Task.Delay(100);
            task.Wait();

            _initialized = true;
        }
Beispiel #2
0
        internal async void ad5360_Setup(SpiMode spi_Mode, int clkFreq, int chipSelectLine, string spiDeviceSelection)
        {
            if (clkFreq > 50000000) //Max write frequency 50 mHz
            {
                errorMsgs = "Clock Speed greater than 50 mHz";
                return;
            }
            try
            {
                var settings = new SpiConnectionSettings(chipSelectLine)
                {
                    ClockFrequency = clkFreq,
                    Mode           = spi_Mode,
                };

                string spiAqs = SpiDevice.GetDeviceSelector(spiDeviceSelection);

                var deviceInfo = await DeviceInformation.FindAllAsync(spiAqs);

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

                System.Diagnostics.Debug.WriteLine("InitSpi seccessful");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("InitSpi threw " + ex);
            }
        }
        /// <summary>
        /// Connects to an SPI device if it exists.
        /// </summary>
        /// <param name="controllerIndex">Controller index.</param>
        /// <param name="chipSelectLine">Slave Chip Select Line.</param>
        /// <param name="bits">Data length in bits.</param>
        /// <param name="frequency">Frequency in Hz.</param>
        /// <param name="mode">Communication mode, i.e. clock polarity.</param>
        /// <param name="sharingMode">Sharing mode.</param>
        /// <returns>Device when controller and device exist, otherwise null.</returns>
        public static SpiDevice ConnectSpi(int controllerIndex, int chipSelectLine, int frequency, int bits,
                                           SpiMode mode, SpiSharingMode sharingMode = SpiSharingMode.Exclusive)
        {
            // Validate
            if (controllerIndex < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(controllerIndex));
            }

            // Initialize
            Initialize();

            // Get controller (return null when doesn't exist)
            if (Spi.Count < controllerIndex + 1)
            {
                return(null);
            }
            var controller = Spi[controllerIndex];

            // Connect to device and return (if exists)
            var settings = new SpiConnectionSettings(chipSelectLine)
            {
                ClockFrequency = frequency,
                DataBitLength  = bits,
                Mode           = mode,
                SharingMode    = sharingMode
            };

            return(controller.GetDevice(settings));
        }
Beispiel #4
0
 public SpiDeviceHandler(int chipSelect = 0, int clock = 3600000,
                         SpiMode mode   = SpiMode.Mode0, string controllerName = "SPI0")
 {
     // Anche se il metodo è dichiarato con async non è possibile invocarlo con await perché,
     //giustamente, non è possibile attendere che sia restituito qualcosa (che è quello che fa await)
     // in quanto non restituirà nulla.
     InitSPI(chipSelect, clock, mode, controllerName);
 }
Beispiel #5
0
 /// <summary>
 /// Construct a copy of an SpiConnectionSettings object.
 /// </summary>
 /// <param name="source">Source object to copy from.</param>
 internal SpiConnectionSettings(SpiConnectionSettings source)
 {
     m_chipSelectionLine = source.m_chipSelectionLine;
     m_dataBitLength     = source.m_dataBitLength;
     m_clockFrequency    = source.m_clockFrequency;
     m_mode        = source.m_mode;
     m_sharingMode = source.m_sharingMode;
 }
 /// <summary>
 /// Construct a copy of an SpiConnectionSettings object.
 /// </summary>
 /// <param name="source">Source object to copy from.</param>
 internal SpiConnectionSettings(SpiConnectionSettings source)
 {
     m_chipSelectionLine = source.m_chipSelectionLine;
     m_dataBitLength = source.m_dataBitLength;
     m_clockFrequency = source.m_clockFrequency;
     m_mode = source.m_mode;
     m_sharingMode = source.m_sharingMode;
 }
Beispiel #7
0
 public ad5360(SpiMode spi_Mode, int clkFreq, int chipSelectLine, string spiDeviceSelection)
 {
     IsActive = InitGPIO();
     if (IsActive)
     {
         this.ad5360_Setup(spi_Mode, clkFreq, chipSelectLine, spiDeviceSelection);
     }
 }
 /// <summary>
 ///     Set up a ChainableShiftRegisterOutput connected to an SPI port.
 /// </summary>
 /// <param name="spiModule">the SPI module to use</param>
 /// <param name="latchPin">The latch pin to use</param>
 /// <param name="numBytes">The number of bytes to write to this device</param>
 /// <param name="mode">The SPI mode to use for all shift registers in this chain</param>
 /// <param name="csMode">The ChipSelectMode to use for all shift registers in this chain</param>
 /// <param name="speedMhz">The speed to use for all shift registers in this chain</param>
 public ChainableShiftRegisterOutput(Spi spiModule, SpiChipSelectPin latchPin, int numBytes = 1,
                                     double speedMhz = 6, SpiMode mode = SpiMode.Mode00, ChipSelectMode csMode = ChipSelectMode.PulseHighAtEnd)
 {
     spiDevice     = new SpiDevice(spiModule, latchPin, csMode, speedMhz, mode);
     this.numBytes = numBytes;
     CurrentValue  = new byte[numBytes];
     lastValues    = new byte[numBytes];
 }
Beispiel #9
0
 /// <summary>
 /// Sets the <see cref="SpiMode"/>.
 /// </summary>
 /// <param name="spiMode">SPI mode.</param>
 public void SetSpiMode(SpiMode spiMode)
 {
     this.mode = (uint)spiMode;
     this.deviceFile.Control(SpiIocWrMode, ref this.mode)
     .ThrowOnPInvokeError <SetSpiModeException>("Can't set SPI mode (SPI_IOC_WR_MODE). Error {1}: {2}");
     this.deviceFile.Control(SpiIocRdMode, ref this.mode)
     .ThrowOnPInvokeError <SetSpiModeException>("Can't set SPI mode (SPI_IOC_RD_MODE). Error {1}: {2}");
 }
 /// <summary>
 /// Sets the <see cref="SpiMode"/>.
 /// </summary>
 /// <param name="spiMode">SPI mode</param>
 public void SetSpiMode(SpiMode spiMode)
 {
     mode = (UInt32)spiMode;
     deviceFile.Control(SPI_IOC_WR_MODE, ref mode)
     .ThrowOnPInvokeError <SetSpiModeException>("Can't set SPI mode (SPI_IOC_WR_MODE). Error {1}: {2}");
     deviceFile.Control(SPI_IOC_RD_MODE, ref mode)
     .ThrowOnPInvokeError <SetSpiModeException>("Can't set SPI mode (SPI_IOC_RD_MODE). Error {1}: {2}");
 }
Beispiel #11
0
 private static extern PiSpi_Result PiSpi_CreateDevice(
     byte ChipSelectPin,
     uint BitRate,
     SpiMode Mode,
     byte TimeBeforeRead,
     byte TimeBetweenBytes,
     byte TimeAfterRead,
     byte TimeBetweenReads,
     out IntPtr Device);
Beispiel #12
0
 /// <summary>
 /// Initializes a copy of a <see cref="SpiConnectionSettings"/> object.
 /// </summary>
 /// <param name="value">Object to copy from.</param>
 internal SpiConnectionSettings(SpiConnectionSettings value)
 {
     _csLine         = value._csLine;
     _clockFrequency = value._clockFrequency;
     _databitLength  = value._databitLength;
     _spiMode        = value._spiMode;
     _spiSharingMode = value._spiSharingMode;
     _bitOrder       = value._bitOrder;
 }
 private UnixSpiMode SpiModeToUnixSpiMode(SpiMode mode)
 {
     return(mode switch
     {
         SpiMode.Mode0 => UnixSpiMode.SPI_MODE_0,
         SpiMode.Mode1 => UnixSpiMode.SPI_MODE_1,
         SpiMode.Mode2 => UnixSpiMode.SPI_MODE_2,
         SpiMode.Mode3 => UnixSpiMode.SPI_MODE_3,
         _ => throw new ArgumentException("Invalid SPI mode.", nameof(mode))
     });
 private static WinSpi.SpiMode ToWinMode(SpiMode mode)
 {
     return(mode switch
     {
         SpiMode.Mode0 => WinSpi.SpiMode.Mode0,
         SpiMode.Mode1 => WinSpi.SpiMode.Mode1,
         SpiMode.Mode2 => WinSpi.SpiMode.Mode2,
         SpiMode.Mode3 => WinSpi.SpiMode.Mode3,
         _ => throw new ArgumentException($"SPI mode {mode} not supported.", nameof(mode))
     });
Beispiel #15
0
 public ILI9341Bit18(LCDSettings lcdSettings,
                     GpioPin chipSelectPin  = null,
                     GpioPin dataCommandPin = null,
                     GpioPin resetPin       = null,
                     GpioPin backlightPin   = null,
                     int spiClockFrequency  = 18 * 1000 * 1000,
                     SpiMode spiMode        = SpiMode.Mode0,
                     string spiBus          = "SPI1") : base(lcdSettings, chipSelectPin,
                                                             dataCommandPin, resetPin, backlightPin, spiClockFrequency, spiMode, spiBus)
 {
 }
        /// <summary>
        /// Construct an SPI device attached to a particular module
        /// </summary>
        /// <param name="SpiModule">The module this device is attached to</param>
        /// <param name="ChipSelect">The chip select pin used by this device</param>
        /// <param name="csMode">The ChipSelectMode to use with this device</param>
        /// <param name="SpeedMHz">The speed to operate this device at</param>
        /// <param name="mode">The SpiMode of this device</param>
        public SpiDevice(Spi SpiModule, Pin ChipSelect, ChipSelectMode csMode = ChipSelectMode.SpiActiveLow, double SpeedMHz = 1, SpiMode mode = SpiMode.Mode00)
        {
            this.ChipSelectMode = csMode;
            this.ChipSelect = ChipSelect;
            this.spi = SpiModule;
            this.Frequency = SpeedMHz;
            this.Mode = mode;

            this.ChipSelect.Mode = PinMode.PushPullOutput;

            spi.Enabled = true;
        }
Beispiel #17
0
        public ILI9341(LCDSettings lcdSettings,
                       GpioPin chipSelectPin  = null,
                       GpioPin dataCommandPin = null,
                       GpioPin resetPin       = null,
                       GpioPin backlightPin   = null,
                       int spiClockFrequency  = 18 * 1000 * 1000,
                       SpiMode spiMode        = SpiMode.Mode0,
                       string spiBus          = "SPI1")
        {
            if (chipSelectPin != null)
            {
                _chipSelectPin = chipSelectPin;
                _chipSelectPin.SetDriveMode(GpioPinDriveMode.Output);
            }
            else
            {
                throw new ArgumentNullException("chipSelectPin");
            }

            if (dataCommandPin != null)
            {
                _dataCommandPin = dataCommandPin;
                _dataCommandPin.SetDriveMode(GpioPinDriveMode.Output);
            }
            else
            {
                throw new ArgumentNullException("dataCommandPin");
            }

            if (resetPin != null)
            {
                _resetPin = resetPin;
                _resetPin.SetDriveMode(GpioPinDriveMode.Output);
            }

            if (backlightPin != null)
            {
                _backlightPin = backlightPin;
                _backlightPin.SetDriveMode(GpioPinDriveMode.Output);
            }

            var connectionSettings = new SpiConnectionSettings(chipSelectPin.PinNumber)
            {
                DataBitLength  = 8,
                ClockFrequency = spiClockFrequency,
                Mode           = spiMode
            };

            _spi = SpiDevice.FromId(spiBus, connectionSettings);
            InitializeScreen();
            _lcdSettings = lcdSettings;
            SetOrientation(lcdSettings);
        }
 public Ili9341EighteenBit(
     GpioPin chipSelectPin  = null,
     GpioPin dataCommandPin = null,
     GpioPin resetPin       = null,
     GpioPin backlightPin   = null,
     int spiClockFrequency  = MaxSPIFrequency,
     SpiMode spiMode        = SpiMode.Mode0,
     string spiBus          = "SPI1",
     Orientations rotation  = Orientations.Landscape,
     Font textFont          = null)
     : base(chipSelectPin, dataCommandPin, resetPin, backlightPin, spiClockFrequency, spiMode, spiBus, rotation, textFont)
 {
 }
Beispiel #19
0
        /// <summary>
        /// Creates an instance using the specified I2C device.
        /// </summary>
        /// <param name="busNumber">Bus controller number, zero based.</param>
        /// <param name="chipSelectLine">Slave Chip Select Line.</param>
        /// <param name="mode">Communication mode, i.e. clock polarity.</param>
        /// <param name="dataBitLength">Data length in bits.</param>
        /// <param name="clockFrequency">Frequency in Hz.</param>
        /// <param name="sharingMode">Sharing mode.</param>
        public Px4ioDevice(int busNumber, int chipSelectLine, SpiMode mode, int dataBitLength, int clockFrequency, SpiSharingMode sharingMode)
        {
            // Connect to hardware
            _hardware = SpiExtensions.Connect(busNumber, chipSelectLine, mode, dataBitLength, clockFrequency, sharingMode);
            if (_hardware == null)
            {
                // Initialization error
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
                                                                  Resources.Strings.SpiErrorDeviceNotFound, chipSelectLine, busNumber));
            }

            // Initialize configuration
            Read();
        }
Beispiel #20
0
        private UnixSpiMode SpiModeToUnixSpiMode(SpiMode mode)
        {
            switch (mode)
            {
            case SpiMode.Mode0:
                return(UnixSpiMode.SPI_MODE_0);

            case SpiMode.Mode1:
                return(UnixSpiMode.SPI_MODE_1);

            case SpiMode.Mode2:
                return(UnixSpiMode.SPI_MODE_2);

            default:
                throw new ArgumentException("Invalid SPI mode.", nameof(mode));
            }
        }
Beispiel #21
0
        public SRAM_23LC1024(SpiMode mode, int clkFreq, int ChipSelectLine, string spiDeviceSelection)
        {
            cs_Pin    = ChipSelectLine;
            spi_Speed = clkFreq;
            Sram_Name = spiDeviceSelection;
            _mode     = mode;
            _23LC1024_Setup();

            var gpio = GpioController.GetDefault();

            if (gpio == null)
            {
                return;
            }

            GPIO_CS = gpio.OpenPin(25);
            GPIO_CS.Write(GpioPinValue.High);
            GPIO_CS.SetDriveMode(GpioPinDriveMode.Output);
        }
        public async void Init(List<int> adc_channel, SPIPort spi,int clockfrequency, SpiMode mode)
        {
            try
            {
                InitChannel(adc_channel);
                var settings = new SpiConnectionSettings((int)spi);
                settings.ClockFrequency = clockfrequency;
                settings.Mode = mode;

                string spiAqs = SpiDevice.GetDeviceSelector(Enum.GetName(typeof(SPIPort), spi));
                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);
            }
        }
Beispiel #23
0
        public AD5360_Controller(SpiMode spi_Mode, int clkFreq, int ChipSelectLine, string spiDeviceSelection)
        {
            ad5360_Board = new ad5360(spi_Mode, clkFreq, ChipSelectLine, spiDeviceSelection);
            playBack     = true;

            GpioOpenStatus status = new GpioOpenStatus();
            var            gpio   = GpioController.GetDefault();

            if (gpio == null)
            {
                return;
            }

            var open = gpio.TryOpenPin(arduinoTimer, GpioSharingMode.Exclusive, out GPIO_Timer, out status);

            if (open == true)
            {
                GPIO_Timer.SetDriveMode(GpioPinDriveMode.Input);
            }
        }
Beispiel #24
0
        /// <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;
        }
Beispiel #25
0
        private static WinSpi.SpiMode ToWinMode(SpiMode mode)
        {
            switch (mode)
            {
            case SpiMode.Mode0:
                return(WinSpi.SpiMode.Mode0);

            case SpiMode.Mode1:
                return(WinSpi.SpiMode.Mode1);

            case SpiMode.Mode2:
                return(WinSpi.SpiMode.Mode2);

            case SpiMode.Mode3:
                return(WinSpi.SpiMode.Mode3);

            default:
                throw new ArgumentException($"SPI mode {mode} not supported.", nameof(mode));
            }
        }
        /// <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;
            }
        }
Beispiel #27
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);
            }
        }
Beispiel #28
0
        private async void Initialize(Int32 chipSelect, Int32 speed, SpiMode mode, SpiSharingMode sharingMode = SpiSharingMode.Shared)
        {
            DeviceInformation devInfo = null;

            try
            {
                var settings = new SpiConnectionSettings(chipSelect);
                settings.ClockFrequency = speed;
                settings.Mode           = mode;
                settings.SharingMode    = sharingMode;

                try
                {
                    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

                    devInfo = dis[0];
                }
                catch (Exception e)
                {
                    throw new Exception("SPI Initialization failed. Exception: " + e.Message + "\n\r");
                }

                if (spiDevice == null)
                {
                    throw new Exception("SPI Controller is currently in use by " +
                                        "another application. Please ensure that no other applications are using SPI.");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("SPI Initialization failed. Exception: " + ex.Message + "\n\r");
            }
        }
Beispiel #29
0
        /// <summary>
        /// Constructor of LedStrip
        /// </summary>
        /// <param name="size">Size of strip in led number</param>
        /// <param name="spiBus">Id of spi bus</param>
        /// <param name="order">Order of colors</param>
        /// <param name="frequency">Frequency of spi bus (default 4M).</param>
        /// <param name="spiMode">Mode of spi bus (default Mode0)</param>
        public LedStrip(int size, string spiBus, ColorOrder order, int frequency = 4 * 1000 * 1000, SpiMode spiMode = SpiMode.Mode0)
        {
            if (size < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(size), "must be greater than 0");
            }
            Size  = size;
            _leds = new Led[size];
            for (int i = 0; i < size; i++)
            {
                _leds[i] = new Led(order);
            }
            var nbBytes = 4 + 4 * size + (size >> 4) + 1;

            _dummy = new byte[nbBytes];
            _data  = new byte[nbBytes];
            SpiConnectionSettings settings = new SpiConnectionSettings()
            {
                ChipSelectType = SpiChipSelectType.None,
                DataBitLength  = 8,
                ClockFrequency = frequency,
                Mode           = spiMode
            };

            _spi = SpiController.FromName(spiBus).GetDevice(settings);
            PrepareStart();
            PrepareEnd();
        }
 public Sram_Controller(SpiMode spi_Mode, int clkFreq)
 {
     _Sram0 = new SRAM_23LC1024(spi_Mode, clkFreq, 0, "SPI0");
     // _Sram1 = new SRAM_23LC1024(spi_Mode, clkFreq, 1,"SPI1");
 }
        public static async Task InitILI9341DisplaySPI(ILI9341Display display, int SPIDisplaypin, int speed, SpiMode mode, string SPI_CONTROLLER_NAME, string DefaultDisplay)
        {
            var displaySettings = new SpiConnectionSettings(SPIDisplaypin);
            displaySettings.ClockFrequency = speed;// 500kHz;
            displaySettings.Mode = mode; //Mode0,1,2,3;  MCP23S17 needs mode 0
            string DispspiAqs = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME);
            var DispdeviceInfo = await DeviceInformation.FindAllAsync(DispspiAqs);
            display.SpiDisplay = await SpiDevice.FromIdAsync(DispdeviceInfo[0].Id, displaySettings);

            //await ResetDisplay(display);
            //await InitRegisters(display);
            //await Wakeup(display);

            if (String.IsNullOrEmpty(DefaultDisplay))
                InitializeDisplayBuffer(display, ILI9341Display.BLACK);
            else
            {
                await LoadBitmap(display, DefaultDisplay);
            }
            await PowerOnSequence(display);
            await Wakeup(display);
            Flush(display);


        }
        /// <summary>
        /// Connects to an SPI device if it exists.
        /// </summary>
        /// <param name="controllerIndex">Controller index.</param>
        /// <param name="chipSelectLine">Slave Chip Select Line.</param>
        /// <param name="bits">Data length in bits.</param>
        /// <param name="frequency">Frequency in Hz.</param>
        /// <param name="mode">Communication mode, i.e. clock polarity.</param>
        /// <param name="sharingMode">Sharing mode.</param>
        /// <returns>Device when controller and device exist, otherwise null.</returns>
        public static SpiDevice ConnectSpi(int controllerIndex, int chipSelectLine, int frequency, int bits, 
            SpiMode mode, SpiSharingMode sharingMode = SpiSharingMode.Exclusive)
        {
            // Validate
            if (controllerIndex < 0) throw new ArgumentOutOfRangeException(nameof(controllerIndex));

            // Initialize
            Initialize();

            // Get controller (return null when doesn't exist)
            if (Spi.Count < controllerIndex + 1)
                return null;
            var controller = Spi[controllerIndex];

            // Connect to device and return (if exists)
            var settings = new SpiConnectionSettings(chipSelectLine)
            {
                ClockFrequency = frequency,
                DataBitLength = bits,
                Mode = mode,
                SharingMode = sharingMode
            };
            return controller.GetDevice(settings);
        }
Beispiel #33
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;
            }
        }
Beispiel #34
0
        public Ili9341EighteenBit(
            GpioPin chipSelectPin   = null,
            GpioPin dataCommandPin  = null,
            GpioPin resetPin        = null,
            GpioPin backlightPin    = null,
            int spiClockFrequency   = MaxSPIFrequency,
            SpiMode spiMode         = SpiMode.Mode0,
            string spiBus           = "SPI1",
            Orientations rotation   = Orientations.Landscape,
            byte[] orientationFlags = null,
            Font textFont           = null)
        {
            if (chipSelectPin != null)
            {
                _chipSelectPin = chipSelectPin;
                _chipSelectPin.SetDriveMode(GpioPinDriveMode.Output);
            }
            else
            {
                throw new ArgumentNullException("chipSelectPin");
            }

            if (dataCommandPin != null)
            {
                _dataCommandPin = dataCommandPin;
                _dataCommandPin.SetDriveMode(GpioPinDriveMode.Output);
            }
            else
            {
                throw new ArgumentNullException("dataCommandPin");
            }

            if (resetPin != null)
            {
                _resetPin = resetPin;
                _resetPin.SetDriveMode(GpioPinDriveMode.Output);
            }

            if (backlightPin != null)
            {
                _backlightPin = backlightPin;
                _backlightPin.SetDriveMode(GpioPinDriveMode.Output);
            }

            if (orientationFlags == null)
            {
                _orientationFlags = new byte[]
                {
                    (byte)MemoryAccessControl.MX,
                    (byte)MemoryAccessControl.MV,
                    (byte)(MemoryAccessControl.MY | MemoryAccessControl.ML),
                    (byte)(MemoryAccessControl.ML | MemoryAccessControl.MV | MemoryAccessControl.MX | MemoryAccessControl.MY)
                };
            }
            else if (orientationFlags.Length == 4)
            {
                _orientationFlags = orientationFlags;
            }
            else
            {
                throw new ArgumentOutOfRangeException("orientationFlags");
            }

            if (textFont == null)
            {
                _textFont = new StandardFixedWidthFont();
            }


            var connectionSettings = new SpiConnectionSettings(chipSelectPin.PinNumber)
            {
                DataBitLength  = DataBitLength,
                ClockFrequency = spiClockFrequency,
                Mode           = spiMode,
            };

            _spi = SpiDevice.FromId(spiBus, connectionSettings);

            InitializeScreen();
            SetRotation(rotation);
        }
        /* Initialize the SPI bus */
        private async Task<SpiDevice> InitSpi(int chipSelectPin, SpiMode mode)
        {
            try
            {
                
                //new SPI(new SPI.Configuration(chipSelectPin, false, 0, 0, false, true, 2000, spi));
                //public Configuration(Cpu.Pin ChipSelect_Port, bool ChipSelect_ActiveState, uint ChipSelect_SetupTime, uint ChipSelect_HoldTime, bool Clock_IdleState, bool Clock_Edge, uint Clock_RateKHz, SPI.SPI_module SPI_mod);
                var settings = new SpiConnectionSettings(0); /* Create SPI initialization settings                               */
                settings.ClockFrequency = 2000000;                             /* Datasheet specifies maximum SPI clock frequency of 10MHz         */
                settings.Mode = mode;
                settings.DataBitLength = 8;
                settings.SharingMode = SpiSharingMode.Exclusive;                                                    /* 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();       /* 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  */
                return 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);
            }
        }
 /// <summary>
 /// Sets the <see cref="SpiMode"/>.
 /// </summary>
 /// <param name="spiMode">SPI mode</param>
 public void SetSpiMode(SpiMode spiMode)
 {
     mode = (UInt32) spiMode;
     deviceFile.Control(SPI_IOC_WR_MODE, ref mode)
         .ThrowOnPInvokeError<SetSpiModeException>("Can't set SPI mode (SPI_IOC_WR_MODE). Error {1}: {2}");
     deviceFile.Control(SPI_IOC_RD_MODE, ref mode)
         .ThrowOnPInvokeError<SetSpiModeException>("Can't set SPI mode (SPI_IOC_RD_MODE). Error {1}: {2}");
 }
Beispiel #37
0
 public SPI(Int32 chipSelect = 0, Int32 speed = 10000000, SpiMode mode = SpiMode.Mode3, SpiSharingMode sharingMode = SpiSharingMode.Shared)
 {
     Initialize(chipSelect, speed, mode, sharingMode);
 }
Beispiel #38
0
 public void SetMode(SpiMode mode) => spiDevice.ConnectionSettings.Mode = mode;
        // Initialize the display class creating the SPI references and GPIO needed for operation, User app provides the parameters
        // you can also provide a default bitmap to load, JPG, GIF, PNG etc it will be scaled to fit
        public static async Task InitILI9488DisplaySPI(WS_ILI9488Display display, int SPIDisplaypin, int speed, SpiMode mode, string SPI_CONTROLLER_NAME, string DefaultDisplay)
        {
            var displaySettings = new SpiConnectionSettings(SPIDisplaypin);

            displaySettings.ClockFrequency = speed; // 500kHz;
            displaySettings.Mode           = mode;  //Mode0,1,2,3;  MCP23S17 needs mode 0
            string DispspiAqs     = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME);
            var    DispdeviceInfo = await DeviceInformation.FindAllAsync(DispspiAqs);

            display.SpiDisplay = await SpiDevice.FromIdAsync(DispdeviceInfo[0].Id, displaySettings);

            await ResetDisplay(display);
            await InitRegisters(display);
            await wakeup(display);

            if (String.IsNullOrEmpty(DefaultDisplay))
            {
                InitializeDisplayBuffer(display, WS_ILI9488Display.BLACK);
            }
            else
            {
                await LoadBitmap(display, DefaultDisplay);
            }
            Flush(display);
        }