예제 #1
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // Have to setup the SPI bus with custom Chip Select line rather than std CE0/CE1
            SpiController spiController = SpiController.GetDefaultAsync().AsTask().GetAwaiter().GetResult();
            var           settings      = new SpiConnectionSettings(0)
            {
                ClockFrequency = 500000,
                Mode           = SpiMode.Mode0,
            };

            GpioController gpioController    = GpioController.GetDefault();
            GpioPin        chipSelectGpioPin = gpioController.OpenPin(ChipSelectLine);

            chipSelectGpioPin.SetDriveMode(GpioPinDriveMode.Output);
            chipSelectGpioPin.Write(GpioPinValue.High);

            rfm9XLoraModem = spiController.GetDevice(settings);

            while (true)
            {
                byte[] writeBuffer = new byte[] { 0x42 };                // RegVersion
                byte[] readBuffer  = new byte[1];

                chipSelectGpioPin.Write(GpioPinValue.Low);
                rfm9XLoraModem.Write(writeBuffer);
                rfm9XLoraModem.Read(readBuffer);
                chipSelectGpioPin.Write(GpioPinValue.High);

                Debug.WriteLine("RegVersion {0:x2}", readBuffer[0]);

                Task.Delay(10000).Wait();
            }
        }
예제 #2
0
        public Rfm9XDevice(string spiPort, int chipSelectPin, int resetPin, int interruptPin)
        {
            var settings = new SpiConnectionSettings(chipSelectPin)
            {
                ClockFrequency = 500000,
                //DataBitLength = 8,
                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);

            // Interrupt pin for RX message & TX done notification
            InterruptGpioPin = gpioController.OpenPin(interruptPin);
            InterruptGpioPin.SetDriveMode(GpioPinDriveMode.Input);

            InterruptGpioPin.ValueChanged += InterruptGpioPin_ValueChanged;
        }
예제 #3
0
        internal async Task Start()
        {
            try
            {
                IoController    = GpioController.GetDefault();
                _resetPowerDown = IoController.OpenPin(RESET_PIN);
                _resetPowerDown.Write(GpioPinValue.High);
                _resetPowerDown.SetDriveMode(GpioPinDriveMode.Output);
            }
            /* If initialization fails, throw an exception */
            catch (Exception ex)
            {
                throw new Exception("GPIO initialization failed", ex);
            }

            try
            {
                var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE);
                settings.ClockFrequency = 1000000;
                settings.Mode           = SpiMode.Mode0;
                String spiDeviceSelector = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME);
                var    devices           = await DeviceInformation.FindAllAsync(spiDeviceSelector);

                _spi = await SpiDevice.FromIdAsync(devices[0].Id, settings);
            }
            /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                throw new Exception("SPI Initialization Failed", ex);
            }


            Reset();
        }
        internal static SpiDevice GetDevice(int busId, int chipSelectLine, SpiMode mode = 0, int dataBitLength = 8, int clockFrequency = 500000)
        {
            var settings = new SpiConnectionSettings(busId, chipSelectLine)
            {
                Mode           = mode,
                DataBitLength  = dataBitLength,
                ClockFrequency = clockFrequency,
            };

            try
            {
                return(new System.Device.Spi.Drivers.UnixSpiDevice(settings));
            }
            catch
            {
                try
                {
                    return(new System.Device.Spi.Drivers.Windows10SpiDevice(settings));
                }
                catch
                {
                    return(null);
                }
            }
        }
예제 #5
0
        /// <summary>
        /// Init SP-interfaces
        /// </summary>
        /// <returns></returns>
        private async Task InitSpi()
        {
            try
            {
                var settings = new SpiConnectionSettings(HW_SPI_CS_Line);
                settings.ClockFrequency = 2000000;
                settings.Mode           = SpiMode.Mode0; // CLK-Idle ist low, Dataset on Falling Edge, Sample on Rising Edge
                string spiAqs      = SpiDevice.GetDeviceSelector(HW_SPI_IO_Controller);
                var    devicesInfo = await DeviceInformation.FindAllAsync(spiAqs);

                SPIOInterface = await SpiDevice.FromIdAsync(devicesInfo[0].Id, settings);
            }
            /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                throw new Exception("SPI Initialization Failed", ex);
            }
            try
            {
                var settings = new SpiConnectionSettings(HW_SPI_CS_Line);
                settings.ClockFrequency = 4000000;
                settings.Mode           = SpiMode.Mode0; // CLK-Idle ist low, Dataset on Falling Edge, Sample on Rising Edge
                string spiAqs      = SpiDevice.GetDeviceSelector(HW_SPI_LED_Controller);
                var    devicesInfo = await DeviceInformation.FindAllAsync(spiAqs);

                StatusLEDInterface = await SpiDevice.FromIdAsync(devicesInfo[0].Id, settings);
            }
            /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                throw new Exception("SPI Initialization Failed", ex);
            }
        }
예제 #6
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            GpioPin   ChipSelectGpioPin   = null;
            const int chipSelectPinNumber = 25;

            SpiController spiController = SpiController.GetDefaultAsync().AsTask().GetAwaiter().GetResult();
            var           settings      = new SpiConnectionSettings(1)
            {
                ClockFrequency = 500000,
                Mode           = SpiMode.Mode0,         // From SemTech docs pg 80 CPOL=0, CPHA=0
            };

            // Chip select pin configuration
            GpioController gpioController = GpioController.GetDefault();

            ChipSelectGpioPin = gpioController.OpenPin(chipSelectPinNumber);
            ChipSelectGpioPin.SetDriveMode(GpioPinDriveMode.Output);
            ChipSelectGpioPin.Write(GpioPinValue.High);

            SpiDevice Device = spiController.GetDevice(settings);

            while (true)
            {
                byte[] writeBuffer = new byte[] { 0x42 };                 // RegVersion
                byte[] readBuffer  = new byte[1];

                // Read the RegVersion silicon ID to check SPI works
                ChipSelectGpioPin.Write(GpioPinValue.Low);
                Device.TransferSequential(writeBuffer, readBuffer);
                ChipSelectGpioPin.Write(GpioPinValue.High);
                Debug.WriteLine("Register RegVer 0x{0:x2} - Value 0X{1:x2} - Bits {2}", writeBuffer[0], readBuffer[0], Convert.ToString(readBuffer[0], 2).PadLeft(8, '0'));

                Thread.Sleep(10000);
            }
        }
예제 #7
0
        public Rfm9XDevice(string spiPortName, int chipSelectPin, int resetPin, int interruptPin)
        {
            GpioController gpioController = GpioController.GetDefault();

            GpioPin chipSelectGpio = gpioController.OpenPin(chipSelectPin);

            var settings = new SpiConnectionSettings()
            {
                ChipSelectType        = SpiChipSelectType.Gpio,
                ChipSelectLine        = chipSelectGpio,
                Mode                  = SpiMode.Mode0,
                ClockFrequency        = 500000,
                ChipSelectActiveState = false,
                ChipSelectHoldTime    = new TimeSpan(1),
            };

            SpiController spiController = SpiController.FromName(spiPortName);

            rfm9XLoraModem = spiController.GetDevice(settings);

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

            resetGpioPin.SetDriveMode(GpioPinDriveMode.Output);
            resetGpioPin.Write(GpioPinValue.Low);
            Thread.Sleep(10);
            resetGpioPin.Write(GpioPinValue.High);
            Thread.Sleep(10);

            // Interrupt pin for RX message & TX done notification
            InterruptGpioPin = gpioController.OpenPin(interruptPin);
            InterruptGpioPin.SetDriveMode(GpioPinDriveMode.Input);

            InterruptGpioPin.ValueChanged += InterruptGpioPin_ValueChanged;
        }
예제 #8
0
        static void Main()
        {
            var settings = new SpiConnectionSettings()
            {
                ChipSelectType = SpiChipSelectType.Gpio,
                ChipSelectLine = FEZ.GpioPin.D10,
                Mode           = SpiMode.Mode0,
                //Mode = SpiMode.Mode1,
                //Mode = SpiMode.Mode2,
                //Mode = SpiMode.Mode3,
                ClockFrequency = 500000,
                DataBitLength  = 8,
                //ChipSelectActiveState = true
                ChipSelectActiveState = false,
                //ChipSelectHoldTime = new TimeSpan(0, 0, 0, 0, 500),
                //ChipSelectSetupTime = new TimeSpan(0, 0, 0, 0, 500),
            };

            var controller = SpiController.FromName(FEZ.SpiBus.Spi1);
            var device     = controller.GetDevice(settings);

            Thread.Sleep(500);

            while (true)
            {
                byte   register;
                byte[] writeBuffer;
                byte[] readBuffer;

                // Silicon Version info
                register = 0x42; // RegVersion expecting 0x12

                // Frequency
                //register = 0x06; // RegFrfMsb expecting 0x6C
                //register = 0x07; // RegFrfMid expecting 0x80
                //register = 0x08; // RegFrfLsb expecting 0x00

                //register = 0x17; //RegPayoadLength expecting 0x47

                // Preamble length
                //register = 0x18; // RegPreambleMsb expecting 0x32
                //register = 0x19; // RegPreambleLsb expecting 0x3E

                //register <<= 1;
                //register |= 0x80;

                //writeBuffer = new byte[] { register };
                writeBuffer = new byte[] { register, 0x0 };
                //writeBuffer = new byte[] { register, register, 0x0 };

                readBuffer = new byte[writeBuffer.Length];

                //device.TransferSequential(writeBuffer, readBuffer);
                device.TransferFullDuplex(writeBuffer, readBuffer);

                Debug.WriteLine("Value = 0x" + BytesToHexString(readBuffer));

                Thread.Sleep(1000);
            }
        }
예제 #9
0
        // Setup the MCP3008 chip
        public async void Initialize()
        {
            Debug.WriteLine("Setting up the MCP3008.");
            try
            {
                // Settings for the SPI bus
                var SPI_settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE);
                SPI_settings.ClockFrequency = 3600000;
                SPI_settings.Mode           = SpiMode.Mode0;

                SpiController controller = await SpiController.GetDefaultAsync();     /* Get the default SPI controller */

                mcp_var = controller.GetDevice(SPI_settings);

                if (mcp_var == null)
                {
                    Debug.WriteLine("ERROR! SPI device may be in use.");
                    return;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("EXEPTION CAUGHT: " + e.Message + "\n" + e.StackTrace);
                throw;
            }
        }
예제 #10
0
        // 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);
        }
예제 #11
0
        static async Task spifullduplex(string[] input)
        {
            try
            {
                UpBridge.Up   upb        = new UpBridge.Up();
                SpiController controller = await SpiController.GetDefaultAsync();

                SpiConnectionSettings settings = new SpiConnectionSettings(spi.ChipSelectLine);
                settings.ClockFrequency = spi.ClockFrequency;
                settings.DataBitLength  = spi.DataBitLength;
                settings.Mode           = spi.Mode;
                settings.SharingMode    = spi.SharingMode;
                byte[] wrtiebuf = new byte[input.Length - 1];
                byte[] readbuf  = new byte[wrtiebuf.Length];
                for (int i = 1; i < input.Length; i++)
                {
                    wrtiebuf[i - 1] = Convert.ToByte(input[i], 16);
                }
                controller.GetDevice(settings).TransferFullDuplex(wrtiebuf, readbuf);
                for (int i = 0; i < readbuf.Length; i++)
                {
                    Console.WriteLine(i + " byte: " + readbuf[i].ToString("X"));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
예제 #12
0
        static async Task spiread(string[] input)
        {
            try
            {
                if (input.Length == 2)
                {
                    UpBridge.Up   upb        = new UpBridge.Up();
                    SpiController controller = await SpiController.GetDefaultAsync();

                    SpiConnectionSettings settings = new SpiConnectionSettings(spi.ChipSelectLine);
                    settings.ClockFrequency = spi.ClockFrequency;
                    settings.DataBitLength  = spi.DataBitLength;
                    settings.Mode           = spi.Mode;
                    settings.SharingMode    = spi.SharingMode;
                    byte[] readbuf = new byte[Convert.ToInt32(input[1])];
                    controller.GetDevice(settings).Read(readbuf);
                    for (int i = 0; i < readbuf.Length; i++)
                    {
                        Console.WriteLine(i + " byte: " + readbuf[i].ToString("X"));
                    }
                }
                else
                {
                    Console.WriteLine("please input : read N");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
예제 #13
0
        private static Mcp25xxx GetMcp25xxxDevice()
        {
            var spiConnectionSettings = new SpiConnectionSettings(0, 0);
            var spiDevice             = SpiDevice.Create(spiConnectionSettings);

            return(new Mcp25625(spiDevice));
        }
예제 #14
0
        static void Main(string[] args)
        {
            SpiConnectionSettings settings = new SpiConnectionSettings(0, 0)
            {
                ClockFrequency = Iot.Device.Adxl345.Adxl345.SpiClockFrequency,
                Mode           = Iot.Device.Adxl345.Adxl345.SpiMode
            };

            var device = SpiDevice.Create(settings);

            // set gravity measurement range ±4G
            using (Iot.Device.Adxl345.Adxl345 sensor = new Iot.Device.Adxl345.Adxl345(device, GravityRange.Range04))
            {
                // loop
                while (true)
                {
                    // read data
                    Vector3 data = sensor.Acceleration;

                    Console.WriteLine($"X: {data.X.ToString("0.00")} g");
                    Console.WriteLine($"Y: {data.Y.ToString("0.00")} g");
                    Console.WriteLine($"Z: {data.Z.ToString("0.00")} g");
                    Console.WriteLine();

                    // wait for 500ms
                    Thread.Sleep(500);
                }
            }
        }
예제 #15
0
        public Rfm9XDevice(byte chipSelectPin, byte resetPin, byte interruptPin)
        {
            SpiController spiController = SpiController.GetDefaultAsync().AsTask().GetAwaiter().GetResult();
            var           settings      = new SpiConnectionSettings(0)
            {
                ClockFrequency = 500000,
                Mode           = SpiMode.Mode0,
            };

            // Chip select pin configuration
            GpioController gpioController = GpioController.GetDefault();

            ChipSelectGpioPin = gpioController.OpenPin(chipSelectPin);
            ChipSelectGpioPin.SetDriveMode(GpioPinDriveMode.Output);
            ChipSelectGpioPin.Write(GpioPinValue.High);

            // Reset pin configuration to do factory reset
            GpioPin resetGpioPin = gpioController.OpenPin(resetPin);

            resetGpioPin.SetDriveMode(GpioPinDriveMode.Output);
            resetGpioPin.Write(GpioPinValue.Low);
            Task.Delay(10);
            resetGpioPin.Write(GpioPinValue.High);
            Task.Delay(10);

            // Interrupt pin for RX message & TX done notification
            InterruptGpioPin = gpioController.OpenPin(interruptPin);
            InterruptGpioPin.SetDriveMode(GpioPinDriveMode.Input);

            InterruptGpioPin.ValueChanged += InterruptGpioPin_ValueChanged;

            Rfm9XLoraModem = spiController.GetDevice(settings);
        }
예제 #16
0
        /// <summary>
        /// Create an SPI FT4222 class
        /// </summary>
        /// <param name="settings">SPI Connection Settings</param>
        public Ft4222Spi(SpiConnectionSettings settings)
        {
            _settings = settings;
            // Check device
            var devInfos = FtCommon.GetDevices();

            if (devInfos.Count == 0)
            {
                throw new IOException("No FTDI device available");
            }

            // Select the one from bus Id
            // FT4222 propose depending on the mode multiple interfaces. Only the A is available for SPI or where there is none as it's the only interface
            var devInfo = devInfos.Where(m => m.Description == "FT4222 A" || m.Description == "FT4222").ToArray();

            if ((devInfo.Length == 0) || (devInfo.Length < _settings.BusId))
            {
                throw new IOException($"Can't find a device to open SPI on index {_settings.BusId}");
            }

            DeviceInformation = devInfo[_settings.BusId];
            // Open device
            var ftStatus = FtFunction.FT_OpenEx(DeviceInformation.LocId, FtOpenType.OpenByLocation, out _ftHandle);

            if (ftStatus != FtStatus.Ok)
            {
                throw new IOException($"Failed to open device {DeviceInformation.Description} with error: {ftStatus}");
            }

            // Set the clock but we need some math
            var(ft4222Clock, tfSpiDiv) = CalculateBestClockRate();

            ftStatus = FtFunction.FT4222_SetClock(_ftHandle, ft4222Clock);
            if (ftStatus != FtStatus.Ok)
            {
                throw new IOException($"Failed set clock rate {ft4222Clock} on device: {DeviceInformation.Description}with error: {ftStatus}");
            }


            SpiClockPolarity pol = SpiClockPolarity.ClockIdleLow;

            if ((_settings.Mode == SpiMode.Mode2) || (_settings.Mode == SpiMode.Mode3))
            {
                pol = SpiClockPolarity.ClockIdelHigh;
            }

            SpiClockPhase pha = SpiClockPhase.ClockLeading;

            if ((_settings.Mode == SpiMode.Mode1) || (_settings.Mode == SpiMode.Mode3))
            {
                pha = SpiClockPhase.ClockTailing;
            }

            // Configure the SPI
            ftStatus = FtFunction.FT4222_SPIMaster_Init(_ftHandle, SpiOperatingMode.Single, tfSpiDiv, pol, pha, (byte)_settings.ChipSelectLine);
            if (ftStatus != FtStatus.Ok)
            {
                throw new IOException($"Failed setup SPI on device: {DeviceInformation.Description} with error: {ftStatus}");
            }
        }
예제 #17
0
        public async Task Initialize()
        {
            Debug.WriteLine("BMP280::Initialize");

            try
            {
                var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE);
                settings.ClockFrequency = 5000000;                            // 10MHz is the max speed of the chip
                settings.Mode           = SpiMode.Mode0;                      // TODO: Figure out why Mode1 doesn't work.

                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             */

                bmp280 = await SpiDevice.FromIdAsync(dis[0].Id, settings);    /* Create an SpiDevice with our bus controller and SPI settings             */

                if (bmp280 == 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;
            }
        }
예제 #18
0
            public void SetActiveSettings(SpiConnectionSettings connectionSettings)
            {
                if (connectionSettings.DataBitLength != 8)
                {
                    throw new NotSupportedException();
                }
                if (connectionSettings.ChipSelectType == SpiChipSelectType.Controller)
                {
                    throw new NotSupportedException();
                }

                this.captureOnRisingEdge   = ((((int)connectionSettings.Mode) & 0x01) == 0);
                this.clockActiveState      = (((int)connectionSettings.Mode) & 0x02) == 0 ? GpioPinValue.High : GpioPinValue.Low;
                this.clockIdleState        = this.clockActiveState == GpioPinValue.High ? GpioPinValue.Low : GpioPinValue.High;
                this.chipSelectHoldTime    = connectionSettings.ChipSelectHoldTime;
                this.chipSelectSetupTime   = connectionSettings.ChipSelectSetupTime;
                this.chipSelectActiveState = connectionSettings.ChipSelectActiveState;

                if (connectionSettings.ChipSelectType == SpiChipSelectType.Gpio)
                {
                    if (!this.chipSelects.Contains(connectionSettings.ChipSelectLine))
                    {
                        var cs = this.gpioController.OpenPin(connectionSettings.ChipSelectLine);

                        this.chipSelects[connectionSettings.ChipSelectLine] = cs;

                        cs.Write(GpioPinValue.High);
                        cs.SetDriveMode(GpioPinDriveMode.Output);
                    }

                    this.cs = (GpioPin)this.chipSelects[connectionSettings.ChipSelectLine];
                    this.cs.Write(this.chipSelectActiveState ? GpioPinValue.Low : GpioPinValue.High);
                }
            }
예제 #19
0
        private async Task InitSpiAsync()
        {
            // Create SPI initialization settings
            var settings = new SpiConnectionSettings(chipSelectLine);

            // Use configured clock speed
            settings.ClockFrequency = clockFrequency;

            // The port says idle is low and polarity is not specified. Using Mode0.
            settings.Mode = SpiMode.Mode0;

            // 8 bits per transfer
            settings.DataBitLength = 8;

            // 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);
        }
예제 #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OLEDCClick"/> class.
        /// </summary>
        /// <param name="socket">The socket on which the OLEDc Click board is inserted on MikroBus.Net</param>
        /// <example>Example usage:
        /// <code language = "C#">
        ///	var _oled = new OLEDCClick(Hardware.SocketFour);
        /// </code>
        /// </example>
        public OLEDCClick(Hardware.Socket socket)
        {
            _socket = socket;
            SpiConnectionSettings settings = new SpiConnectionSettings
            {
                ChipSelectType        = SpiChipSelectType.Gpio,
                ChipSelectLine        = GpioController.GetDefault().OpenPin(socket.Cs),
                ChipSelectActiveState = false,
                Mode           = SpiMode.Mode3,
                ClockFrequency = 40 * 1000 * 1000
            };

            _oled = SpiController.FromName(socket.SpiBus).GetDevice(settings);

            _resetPin = GpioController.GetDefault().OpenPin(socket.Rst);
            _resetPin.SetDriveMode(GpioPinDriveMode.Output);
            _resetPin.Write(GpioPinValue.High);

            _dataCommandPin = GpioController.GetDefault().OpenPin(socket.PwmPin);
            _dataCommandPin.SetDriveMode(GpioPinDriveMode.Output);
            _dataCommandPin.Write(GpioPinValue.High);

            _readWritePin = GpioController.GetDefault().OpenPin(socket.AnPin);
            _readWritePin.SetDriveMode(GpioPinDriveMode.Output);
            _readWritePin.Write(GpioPinValue.High);

            Canvas = new MikroBitmap(_canvasWidth, _canvasHeight);

            InitilizeOLED();
        }
예제 #21
0
        private async Task InitSpi()
        {
            try
            {
                var adcSettings = new SpiConnectionSettings(0)                      // Chip Select line 0
                {
                    ClockFrequency = 500 * 1000,                                    // Don't exceed 3.6 MHz
                    Mode           = SpiMode.Mode0,
                    SharingMode    = SpiSharingMode.Shared
                };

                var controller = await SpiController.GetDefaultAsync(); /* Find the SPI bus controller device with our selector string  */

                ADC = controller.GetDevice(adcSettings);                /* Create an SpiDevice with our bus controller and SPI settings */
                System.Diagnostics.Debug.WriteLine("Init ADC successful");

                var gyroSettings = new SpiConnectionSettings(1)                    // Chip Select line 0
                {
                    ClockFrequency = 500 * 100,                                    // Don't exceed 3.6 MHz
                    Mode           = SpiMode.Mode3,
                    SharingMode    = SpiSharingMode.Shared
                };

                Gyro = controller.GetDevice(gyroSettings);   /* Create an SpiDevice with our bus controller and SPI settings */
                System.Diagnostics.Debug.WriteLine("Init Gyro successful");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("InitSpi threw " + ex);
            }
        }
예제 #22
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
#if CS0
            const int chipSelectPinNumber = 0;
#endif
#if CS1
            const int chipSelectPinNumber = 1;
#endif
            SpiController spiController = SpiController.GetDefaultAsync().AsTask().GetAwaiter().GetResult();
            var           settings      = new SpiConnectionSettings(chipSelectPinNumber)
            {
                ClockFrequency = 500000,
                Mode           = SpiMode.Mode0,         // From SemTech docs pg 80 CPOL=0, CPHA=0
            };
            SpiDevice Device = spiController.GetDevice(settings);

            while (true)
            {
                byte[] writeBuffer = new byte[] { 0x42 };                 // RegVersion
                byte[] readBuffer  = new byte[1];

                // Read the RegVersion silicon ID to check SPI works
                Device.TransferSequential(writeBuffer, readBuffer);

                Debug.WriteLine("Register RegVer 0x{0:x2} - Value 0X{1:x2} - Bits {2}", writeBuffer[0], readBuffer[0], Convert.ToString(readBuffer[0], 2).PadLeft(8, '0'));

                Thread.Sleep(10000);
            }
        }
        private async void InitSPIAndTimer()
        {
            try {
                //if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Devices.WiFi.WiFiAdapter"))
                //    Application.Current.Exit();//No bo co zrobić??
                //if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Devices.Spi.Devices"))
                //    Application.Current.Exit();//No bo co zrobić??
                if (Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily != "Windows.IoT")
                {
                    Application.Current.Exit();//No bo co zrobić??
                }
                var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE);
                settings.ClockFrequency = 8000000;// 4000000, 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();
                ReadSPIAsync();
            } catch (Exception) {
                m_spiDev = null;
            }
        }
예제 #24
0
        /// <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();
        }
예제 #25
0
        public Display(int CtrlPin, int ChipSelect, string SpiBus)
        {
            buffer1          = new byte[1];
            buffer2          = new byte[2];
            buffer4          = new byte[4];
            clearBuffer      = new byte[160 * 2 * 16];
            characterBuffer1 = new byte[80];
            characterBuffer2 = new byte[320];
            characterBuffer4 = new byte[1280];
            GpioController GPIO = GpioController.GetDefault();

            controlPin = GPIO.OpenPin(CtrlPin);

            controlPin.SetDriveMode(GpioPinDriveMode.Output);

            var settings = new SpiConnectionSettings(ChipSelect);

            settings.Mode           = SpiMode.Mode3;
            settings.ClockFrequency = 4000;
            settings.DataBitLength  = 8;
            //var aqs = SpiDevice.GetDeviceSelector("SPI1");
            spi = SpiDevice.FromId(SpiBus, settings);


            //Reset();
            Init();
            Init();// the display only seem to work when init twice!

            Clear();
        }
예제 #26
0
        private async void initSpi(int spiBusNo)
        {
            try {
                System.Diagnostics.Debug.WriteLine("Initializing the SPI");
                var settings = new SpiConnectionSettings(spiBusNo);
                settings.ClockFrequency = 1_000_000;                    // Okay
                settings.Mode           = SpiMode.Mode0;                // Okay


                var controller = await SpiController.GetDefaultAsync();

                spiPort = controller.GetDevice(settings);

                System.Diagnostics.Debug.WriteLine("SPI Initialized");
                spiIsInitialized = true;


                //string spiAqs = SpiDevice.GetDeviceSelector();
                //var devicesInfo = await DeviceInformation.FindAllAsync(spiAqs);
                //System.Diagnostics.Debug.WriteLine("Device id: "+ devicesInfo[0].Id);
                //spiPort = await SpiDevice.FromIdAsync(devicesInfo[0].Id, settings);
            } catch (Exception e) {
                System.Diagnostics.Debug.WriteLine("SPI Initialisation Error: " + e.Message);
            }
        }
예제 #27
0
        protected virtual void InitDriver(string spiDevice, int selectPin, int dataCommandPin, int resetPin, int backlightPin, Orientation orientation)
        {
            // Init the SPI
            _settings = new SpiConnectionSettings(selectPin)
            {
                Mode           = SpiMode.Mode0,
                ClockFrequency = 40 * 1000 * 1000,
                DataBitLength  = 8
            };
            _display = SpiDevice.FromId(spiDevice, _settings);

            // Start using the Gpio
            _gpio = GpioController.GetDefault();

            // The data/command line
            _dataCommandPin = _gpio.OpenPin(dataCommandPin);
            _dataCommandPin.SetDriveMode(GpioPinDriveMode.Output);
            _dataCommandPin.Write(GpioPinValue.High);

            // The backlight line
            _backlightPin = _gpio.OpenPin(backlightPin);
            _backlightPin.SetDriveMode(GpioPinDriveMode.Output);
            _backlightPin.Write(GpioPinValue.Low);

            // The reset line
            _resetPin = _gpio.OpenPin(resetPin);
            _resetPin.SetDriveMode(GpioPinDriveMode.Output);
            _resetPin.Write(GpioPinValue.High);

            // Init and Set orientation
            InitDisplay(orientation);
        }
예제 #28
0
        /// <summary>
        /// Initialize
        /// </summary>
        public async Task InitializeAsync()
        {
            var settings = new SpiConnectionSettings(CS);

            settings.ClockFrequency = 2000000;
            settings.Mode           = SpiMode.Mode0;

            string aqs = SpiDevice.GetDeviceSelector(spi);
            var    dis = await DeviceInformation.FindAllAsync(aqs);

            sensor = await SpiDevice.FromIdAsync(dis[0].Id, settings);

            var gpio = GpioController.GetDefault();

            ce  = gpio.OpenPin(CE);
            irq = gpio.OpenPin(IRQ);
            ce.SetDriveMode(GpioPinDriveMode.Output);
            irq.SetDriveMode(GpioPinDriveMode.Input);
            irq.ValueChanged += Irq_ValueChanged;

            await Task.Delay(50);

            SetRxPayload(packetSize);
            SetAutoAck(false);
            ce.Write(GpioPinValue.Low);
            sensor.Write(new byte[] { FLUSH_TX });
            sensor.Write(new byte[] { FLUSH_RX });
            sensor.Write(new byte[] { W_REGISTER + CONFIG, 0x3B });
            ce.Write(GpioPinValue.High);
        }
예제 #29
0
        /// <summary>
        /// Initializes the SPI bus.
        /// </summary>
        /// <returns>
        /// A <see cref="Task"/> that represents the operation.
        /// </returns>
        private async Task InitSpiAsync()
        {
            // 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 10MHz
            settings.ClockFrequency = 10000000;

            // 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;

            // 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);
        }
예제 #30
0
        /// <summary>
        /// Initialize the brick including SPI communication
        /// </summary>
        /// <param name="spiAddress">The Spi Address of the brick</param>
        /// <param name="busId">The bus id that the device is connected to</param>
        /// <param name="ChipSelectLine">The chip select line that the device is connected to</param>
        public Brick(byte spiAddress = 1, int busId = 0, int ChipSelectLine = 1)
        {
            try
            {
                SpiAddress = spiAddress;
                // SPI 0 is used on Raspberry with ChipSelectLine 1
                var settings = new SpiConnectionSettings(busId, ChipSelectLine);
                // 500K is the SPI communication with the brick
                settings.ClockFrequency = 500000;
                // see http://tightdev.net/SpiDev_Doc.pdf
                settings.Mode          = SpiMode.Mode0;
                settings.DataBitLength = 8;
                // as the SPI is a static, checking if it has already be initialised
                if (_brickPiSPI == null)
                {
                    _brickPiSPI = SpiDevice.Create(settings);
                }

                BrickPi3Info = new BrickPiInfo();
                BrickPi3Info.Manufacturer    = GetManufacturer();
                BrickPi3Info.Board           = GetBoard();
                BrickPi3Info.HardwareVersion = GetHardwareVersion();
                BrickPi3Info.SoftwareVersion = GetFirmwareVersion();
                BrickPi3Info.Id = GetId();
            }
            catch (Exception ex) when(ex is IOException)
            {
                Debug.Write($"Exception: {ex.Message}");
            }
        }
 /// <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;
 }