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

            fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
        }
示例#2
0
        /// <summary>Executes the command.</summary>
        /// <returns>The command's exit code.</returns>
        public int Execute()
        {
            Console.WriteLine($"BusId={BusId}, ChipSelectLine={ChipSelectLine}, Mode={Mode}, DataBitLength={DataBitLength}, ClockFrequency={ClockFrequency}, HexString={HexString}");

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

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

            return(0);
        }
        /// <summary>
        ///     Open a connection to the ADCDAC Pi.
        /// </summary>
        public void Connect()
        {
            if (IsConnected)
            {
                return; // Already connected
            }

            try
            {
                // Create SPI initialization settings for the ADC
                var adcSettings = new SpiConnectionSettings(SPI_BUS_ID, ADC_CHIP_SELECT_LINE)
                {
                    ClockFrequency = 1100000,     // SPI clock frequency of 1.1MHz
                    Mode           = SpiMode.Mode0
                };

                adc = SpiDevice.Create(adcSettings); // Create an ADC connection with our bus controller and SPI settings

                // Create SPI initialization settings for the DAC
                var dacSettings =
                    new SpiConnectionSettings(SPI_BUS_ID, DAC_CHIP_SELECT_LINE)
                {
                    ClockFrequency = 2000000,      // SPI clock frequency of 20MHz
                    Mode           = SpiMode.Mode0
                };

                dac = SpiDevice.Create(dacSettings); // Create an ADC connection with our bus controller and SPI settings

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

                // Fire the Connected event handler
                Connected?.Invoke(this, EventArgs.Empty);
            }
            /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                IsConnected = false;
                throw new Exception("SPI Initialization Failed", ex);
            }
        }
示例#4
0
        static void Main(string[] args)
        {
            // SPI0 CS0
            SpiConnectionSettings senderSettings = new SpiConnectionSettings(0, 0)
            {
                ClockFrequency = Nrf24l01.SpiClockFrequency,
                Mode           = Nrf24l01.SpiMode
            };
            // SPI1 CS0
            SpiConnectionSettings receiverSettings = new SpiConnectionSettings(1, 2)
            {
                ClockFrequency = Nrf24l01.SpiClockFrequency,
                Mode           = Nrf24l01.SpiMode
            };
            var senderDevice   = SpiDevice.Create(senderSettings);
            var receiverDevice = SpiDevice.Create(receiverSettings);

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

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

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

                        Thread.Sleep(2000);
                    }
                }
            }
        }
示例#5
0
        /// <summary>Executes the command.</summary>
        /// <returns>The command's exit code.</returns>
        public int Execute()
        {
            Console.WriteLine($"ByteCount={ByteCount}, BusId={BusId}, ChipSelectLine={ChipSelectLine}, Mode={Mode}, DataBitLength={DataBitLength}, ClockFrequency={ClockFrequency}");

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

            using (var spiDevice = SpiDevice.Create(connectionSettings))
            {
                // Read bytes of data
                var buffer = new byte[ByteCount];
                spiDevice.Read(buffer.AsSpan());

                Console.WriteLine($"Bytes read:{Environment.NewLine}{HexStringUtilities.FormatByteData(buffer)}");
            }

            return(0);
        }
示例#6
0
        static async Task Main(string[] args)
        {
            System.Console.WriteLine("Starting");
            const int lightCount = 12;
            var       settings   = new SpiConnectionSettings(0, 0)
            {
                ClockFrequency = 2_400_000,
                Mode           = SpiMode.Mode0,
                DataBitLength  = 8
            };

            // Create a Neo Pixel x8 stick on spi 0.0
            var spi = SpiDevice.Create(settings);

            var neo = new Ws2812b(spi, lightCount);

            var img = neo.Image;

            img.Clear();
            for (var x = 0; x < lightCount; x++)
            {
                img.SetPixel(x, 0, Color.White);
            }
            neo.Update();

            MMALCamera cam = MMALCamera.Instance;

            for (var y = 0; y < 50; y++)
            {
                using (var imgCaptureHandler = new ImageStreamCaptureHandler($"_testing{y}.jpg")){
                    await cam.TakePicture(imgCaptureHandler, MMALEncoding.JPEG, MMALEncoding.I420);
                }
                Step();
            }

            img.Clear();
            neo.Update();
            cam.Cleanup();
        }
示例#7
0
        /// <summary>
        /// Initializes the device with the specified spi path.
        /// </summary>
        /// <param name="busId">The bus identifier.</param>
        /// <param name="chipSelectLine">The chip select line.</param>
        /// <param name="resetPin">The reset connector pin.</param>
        /// <param name="antennaGain">The antenna gain.</param>
        /// <exception cref="Exception">GPIO initialization failed.</exception>
        public void Initialize(int busId, int chipSelectLine, int?resetPin, AntennaGain?antennaGain = null)
        {
            try
            {
                this.resetPin = resetPin;
                if (resetPin.HasValue)
                {
                    this.gpioController.OpenPin(resetPin.Value, PinMode.Output);
                    this.gpioController.Write(resetPin.Value, PinValue.High);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(GpioInitializationFailed, ex);
            }

            try
            {
                var settings = new SpiConnectionSettings(busId, chipSelectLine)
                {
                    ClockFrequency = 1000000,
                    Mode           = SpiMode.Mode0,
                };

                this.spiDevice = SpiDevice.Create(settings);
            } /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                throw new Exception(SpiInitializationFailed, ex);
            }

            if (antennaGain != null)
            {
                this.SetRegisterBits(Registers.RFCgReg, (byte)((int)antennaGain & 0x70));
            }

            this.Reset();
        }
示例#8
0
    protected override void ProcessRecord()
    {
        var settings = new SpiConnectionSettings(this.BusId, this.ChipSelectLine);

        settings.ClockFrequency = this.Frequency;

        using (var spiDevice = SpiDevice.Create(settings))
        {
            var response = new byte[this.Data.Length];

            spiDevice.TransferFullDuplex(this.Data, response);

            if (this.Raw)
            {
                WriteObject(response);
            }
            else
            {
                SPIData spiData = new SPIData(this.BusId, this.ChipSelectLine, this.Frequency, this.Data, response);
                WriteObject(spiData);
            }
        }
    }
示例#9
0
        public SH1106(GpioController controller, int gpioReset, int gpioDc, int gpioCs, int clockFrequency)
        {
            _controller = controller;
            _gpioReset  = gpioReset;
            _gpioDc     = gpioDc;
            _gpioCs     = gpioCs;

            controller.OpenPin(_gpioReset, PinMode.Output);
            controller.OpenPin(_gpioDc, PinMode.Output);
            controller.OpenPin(_gpioCs, PinMode.Output);
            InitializeHat();

            SpiConnectionSettings spiConnectionSettings = new SpiConnectionSettings(0, 0)
            {
                ClockFrequency = clockFrequency,
                Mode           = SpiMode.Mode0 //0B00
            };

            _spiDevice = SpiDevice.Create(spiConnectionSettings);

            ResetScreen();
            InitializeScreen();
        }
示例#10
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello Mfrc522!");

            // This sample demonstrates how to read a RFID tag
            // using the Mfrc522Controller
            var connection = new SpiConnectionSettings(0, 0);

            connection.ClockFrequency = 500000;

            var spi = SpiDevice.Create(connection);

            using (var mfrc522Controller = new Mfrc522Controller(spi))
            {
                mfrc522Controller.LogLevel = LogLevel.Info;
                mfrc522Controller.LogTo    = LogTo.Console;
                //await ReadCardUidLoop(mfrc522Controller);
                //mfrc522Controller.RxGain = RxGain.G48dB;
                ReadCardAuth(mfrc522Controller);
            }

            await Task.CompletedTask;
        }
示例#11
0
        private static Ws2812b CreateInstance()
        {
            try
            {
                var count    = 256; // number of LEDs
                var settings = new SpiConnectionSettings(0, 0)
                {
                    ClockFrequency = 2_400_000, Mode = SpiMode.Mode0, DataBitLength = 8
                };

                var spi    = SpiDevice.Create(settings);
                var device = new Ws2812b(spi, count);
                device.Image.Clear();
                device.Update();
                return(device);
            }
            catch (Exception ex)
            {
                // Log error
                //throw new Exception("Error connecting to the LED matrix");
                throw ex;
            }
        }
示例#12
0
        static void Main(string[] args)
        {
            var connection = new SpiConnectionSettings(0, 0);

            connection.ClockFrequency = 1000000;
            var spi = SpiDevice.Create(connection);

            var mfrc = new MFRC522(spi);

            // Console.WriteLine("Running self test...");
            // mfrc.SelfTest();

            mfrc.Init();
            Console.WriteLine("Start scanning for tags...");
            while (true)
            {
                var requestResult = mfrc.Request(PICC_COMMAND_REQUEST_A);
                if ((requestResult.status == Status.OK) || (requestResult.status == Status.Collision))
                {
                    var sb = new StringBuilder();
                    foreach (var dataByte in requestResult.backData)
                    {
                        sb.Append($"{Convert.ToString(dataByte, 2).PadLeft(8, '0')}-");
                    }
                    System.Console.WriteLine($"ATQA: {sb.ToString()}");
                    var(antiCollStatus, serialNumber) = mfrc.AntiCollision(PICC_COMMAND_SEL_CL1);

                    // var sb = new StringBuilder();
                    // foreach (var dataByte in serialNumber)
                    // {
                    //     sb.Append($"{dataByte:X2}");
                    // }
                    // System.Console.WriteLine($"Status={antiCollStatus}, data={sb.ToString()}");
                }
                Thread.Sleep(500);
            }
        }
示例#13
0
 public static Mcp3008 CreateAdc()
 {
     return(new Mcp3008(SpiDevice.Create(new SpiConnectionSettings(0, 0))));
 }
示例#14
0
 public SpiDevice GetOrCreateSpiDevice(SpiConnectionSettings connectionSettings)
 {
     return(_spiDevices.GetOrAdd(connectionSettings, settings => SpiDevice.Create(settings)));
 }
示例#15
0
        /// <summary>
        /// Test program entry point
        /// </summary>
        /// <param name="args">Unused</param>
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello GoPiGo3!");
            // Default on the Raspberry is Bus ID = 0 and Chip Set Select Line = 1 for GoPiGo3
            var settings = new SpiConnectionSettings(0, 1)
            {
                // 500K is the SPI communication with GoPiGo
                ClockFrequency = 500000,
                // see http://tightdev.net/SpiDev_Doc.pdf
                Mode          = SpiMode.Mode0,
                DataBitLength = 8
            };

            _goPiGo3 = new GoPiGo(SpiDevice.Create(settings));
            Console.WriteLine("Choose a test by entering the number and press enter:");
            Console.WriteLine("  1. Basic GoPiGo3 info and embedded led test");
            Console.WriteLine("  2. Control left motor from motor right position");
            Console.WriteLine("  3. Read encoder of right motor");
            Console.WriteLine("  4. Test both servo motors");
            Console.WriteLine("  5. Test Ultrasonic sensor on Grove1");
            Console.WriteLine("  6. Test buzzer on Grove1");
            Console.WriteLine("  7. Change buzzer tone on Grove1 with a potentiometer on Grove2");
            Console.WriteLine("  8. Test sound sensor on Grove1");
            Console.WriteLine("  9. Test a relay on Grove1");
            Console.WriteLine(" 10. Test a button on Grove1");
            Console.WriteLine(" 11. Control a led light on Grove2 from a light sensor on Grove1");
            Console.WriteLine(" 12. Test MotorLeft speed based on encoder");
            Console.WriteLine(" 13. Test driving the vehicle");
            var readCar = Console.ReadLine();

            switch (readCar)
            {
            case "1":
                TestGoPiGoDetails();
                break;

            case "2":
                TestMotorPosition();
                break;

            case "3":
                TestMotorEncoder();
                break;

            case "4":
                TestServo();
                break;

            case "5":
                TestUltrasound();
                break;

            case "6":
                TestBuzzer();
                break;

            case "7":
                TestPotentiometer();
                break;

            case "8":
                TestSound();
                break;

            case "9":
                TestRelay();
                break;

            case "10":
                TestButton();
                break;

            case "11":
                TestLedPwmLightSensor();
                break;

            case "12":
                TestMotorTacho();
                break;

            case "13":
                Testvehicle();
                break;

            default:
                break;
            }
        }
示例#16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            Pn532UsbScWrapper nfcWrapper = null;

            // Check if we have the environment variables
            bool noNfc        = false;
            bool hasSmartCard = false;
            var  noNfcEnv     = Environment.GetEnvironmentVariable("NONFC");

            if (String.IsNullOrEmpty(noNfcEnv))
            {
                if (Configuration.GetSection("NfcSettings")["NoNfc"] == "true")
                {
                    noNfc = true;
                }
                else if (Configuration.GetSection("NfcSettings")["NoNfc"].ToLower() == "smartcard")
                {
                    noNfc        = true;
                    hasSmartCard = true;
                }
            }
            else
            {
                if (noNfcEnv == "true")
                {
                    noNfc = true;
                }
                else if (noNfcEnv.ToLower() == "smartcard")
                {
                    noNfc        = true;
                    hasSmartCard = true;
                }
            }

            if (!noNfc)
            {
                Pn532 nfc     = null;
                var   nfcMode = Environment.GetEnvironmentVariable("NFC_MODE");
                if (String.IsNullOrEmpty(nfcMode))
                {
                    nfcMode = Configuration.GetSection("NfcSettings")["Mode"];
                }
                if (Enum.TryParse <OperatingMode>(nfcMode, out OperatingMode nfcConfig))
                {
                    switch (nfcConfig)
                    {
                    case OperatingMode.HighSpeedUart:
                        var modeConfig = Environment.GetEnvironmentVariable("NFC_MODE_CONFIG");
                        if (String.IsNullOrEmpty(modeConfig))
                        {
                            modeConfig = Configuration.GetSection("NfcSettings")["ModeConfig"];
                        }
                        nfc = new Pn532(modeConfig);
                        break;

                    case OperatingMode.I2c:
                        I2cConnectionSettings connectionString = new I2cConnectionSettings(1, Pn532.I2cDefaultAddress);
                        var device = I2cDevice.Create(connectionString);
                        nfc = new Pn532(device);
                        break;

                    case OperatingMode.Spi:
                        var settings = new SpiConnectionSettings(0, 0)
                        {
                            ClockFrequency            = 2_000_000,
                            Mode                      = SpiMode.Mode0,
                            ChipSelectLineActiveState = PinValue.Low,
                            //    DataFlow = DataFlow.LsbFirst
                        };
                        SpiDevice deviceI2c = SpiDevice.Create(settings);
                        nfc = new Pn532(deviceI2c);
                        break;

                    default:
                        nfc = new Pn532("/dev/ttyS0");
                        break;
                    }
                }
                nfcWrapper = new Pn532UsbScWrapper(nfc);
                services.AddSingleton(nfcWrapper);
            }
            else if (hasSmartCard)
            {
                nfcWrapper = new Pn532UsbScWrapper(new SmartCard());
                services.AddSingleton(nfcWrapper);
            }
            else
            {
                // When NFC is not available but we still want to use this webapi. Dummy data will be sent out
                nfcWrapper = new Pn532UsbScWrapper();
                services.AddSingleton(nfcWrapper);
            }


            // Add service and create Policy with options
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });
            services.AddSingleton(new ApiSettings()
            {
                ApiUrl = Configuration.GetSection("BankioskApi")["ApiUrl"]
            });
        }
示例#17
0
        public static void Main()
        {
            GpioController gpioController = new GpioController();

#if ESP32_WROOM_32_LORA_1_CHANNEL // No reset line for this device as it isn't connected on SX127X
            int ledPinNumber        = Gpio.IO17;
            int chipSelectPinNumber = Gpio.IO16;
#endif
#if NETDUINO3_WIFI
            int ledPinNumber = PinNumber('A', 10);
            // Arduino D10->PB10
            int chipSelectPinNumber = PinNumber('B', 10);
            // Arduino D9->PE5
            int resetPinNumber = PinNumber('E', 5);
#endif
#if MBN_QUAIL
            int ledPinNumber = PinNumber('E', 15);
#if MBN_QUAIL_SOCKET1
            // CS on socket 1
            int chipSelectPinNumber = PinNumber('A', 3);
            // RST on socket 1
            int resetPinNumber = PinNumber('A', 2);
#endif
#if MBN_QUAIL_SOCKET2
            // CS on socket 2
            int chipSelectPinNumber = PinNumber('E', 0);

            // RST on socket 2
            int resetPinNumber = PinNumber('E', 1);
#endif
#if MBN_QUAIL_SOCKET3
            // CS on socket 3
            int chipSelectPinNumber = PinNumber('D', 11);

            // RST on socket 3
            int resetPinNumber = PinNumber('D', 12);
#endif
#if MBN_QUAIL_SOCKET4
            // CS on socket 4
            int chipSelectPinNumber = PinNumber('D', 1);

            // RST on socket 4
            int resetPinNumber = PinNumber('D', 0);
#endif
#endif
#if ST_NUCLEO64_F091RC // No LED for this device as driven by D13 the SPI CLK line
            // Arduino D10->PB6
            int chipSelectPinNumber = PinNumber('B', 6);
            // Arduino D9->PC7
            int resetPinNumber = PinNumber('C', 7);
#endif
#if ST_STM32F429I_DISCOVERY // No reset line for this device as I didn't bother with jumper to SX127X pin
            int ledPinNumber        = PinNumber('G', 14);
            int chipSelectPinNumber = PinNumber('C', 2);
#endif
#if ST_NUCLEO144_F746ZG
            int ledPinNumber = PinNumber('B', 7);
            // Arduino D10->PD14
            int chipSelectPinNumber = PinNumber('D', 14);
            // Arduino D9->PD15
            int resetPinNumber = PinNumber('D', 15);
#endif
#if ST_STM32F769I_DISCOVERY
            int ledPinNumber = PinNumber('J', 5);
            // Arduino D10->PA11
            int chipSelectPinNumber = PinNumber('A', 11);
            // Arduino D9->PH6
            int resetPinNumber = PinNumber('H', 6);
#endif
            Debug.WriteLine("devMobile.IoT.Rfm9x.ShieldSPI starting");

            try
            {
#if NETDUINO3_WIFI || MBN_QUAIL || ST_NUCLEO64_F091RC || ST_NUCLEO144_F746ZG || ST_STM32F769I_DISCOVERY
                // Setup the reset pin
                GpioPin resetGpioPin = gpioController.OpenPin(resetPinNumber);
                resetGpioPin.SetPinMode(PinMode.Output);
                resetGpioPin.Write(PinValue.High);
#endif

#if ESP32_WROOM_32_LORA_1_CHANNEL || MBN_QUAIL || NETDUINO3_WIFI || ST_NUCLEO144_F746ZG || ST_STM32F429I_DISCOVERY || ST_STM32F769I_DISCOVERY
                // Setup the onboard LED
                GpioPin led = gpioController.OpenPin(ledPinNumber);
                led.SetPinMode(PinMode.Output);
#endif

#if ESP32_WROOM_32_LORA_1_CHANNEL
                Configuration.SetPinFunction(nanoFramework.Hardware.Esp32.Gpio.IO12, DeviceFunction.SPI1_MISO);
                Configuration.SetPinFunction(nanoFramework.Hardware.Esp32.Gpio.IO13, DeviceFunction.SPI1_MOSI);
                Configuration.SetPinFunction(nanoFramework.Hardware.Esp32.Gpio.IO14, DeviceFunction.SPI1_CLOCK);
#endif

                var settings = new SpiConnectionSettings(SpiBusId, chipSelectPinNumber)
                {
                    ClockFrequency = 500000,
                    Mode           = SpiMode.Mode0,// From SemTech docs pg 80 CPOL=0, CPHA=0
                    SharingMode    = SpiSharingMode.Shared,
                };

                using (SpiDevice device = SpiDevice.Create(settings))
                {
                    Thread.Sleep(500);

                    while (true)
                    {
                        byte[] writeBuffer = new byte[] { RegVersion, 0x0 };
                        byte[] readBuffer  = new byte[writeBuffer.Length];

                        device.TransferFullDuplex(writeBuffer, readBuffer);

                        Debug.WriteLine(String.Format("Register 0x{0:x2} - Value 0X{1:x2}", RegVersion, readBuffer[1]));

#if ESP32_WROOM_32_LORA_1_CHANNEL || MBN_QUAIL || NETDUINO3_WIFI || ST_NUCLEO144_F746ZG || ST_STM32F429I_DISCOVERY || ST_STM32F769I_DISCOVERY
                        led.Toggle();
#endif
                        Thread.Sleep(10000);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
示例#18
0
        public void Start()
        {
            try
            {
                if (_started)
                {
                    return;
                }

                if (_lights != null)
                {
                    _lights.Clear();
                }
                else
                {
                    _lights = new List <StripLighterLight>();
                }

                if (_config.Model.lightStripSettings.lights?.Any() ?? false)
                {
                    foreach (var light in _config.Model.lightStripSettings.lights)
                    {
                        _lights.Add(new StripLighterLight()
                        {
                            Location  = new PointF(light.X, light.Y),
                            Color     = Color.FromRgb(0, 0, 0),
                            LastColor = null
                        });
                    }
                }

                if (_config.Model.ffmpegCaptureSettings.useFFMpeg && _config.Model.ffmpegCaptureSettings.lightsLocal)
                {
                    try
                    {
                        var settings = new SpiConnectionSettings(0, 0)
                        {
                            ClockFrequency = 2400000,
                            Mode           = SpiMode.Mode0,
                            DataBitLength  = 8
                        };

                        _device     = SpiDevice.Create(settings);
                        _lightStrip = new Ws2812b(_device, _lights.Count);
                    }
                    catch (Exception ex)
                    {
                        _device     = null;
                        _lightStrip = null;
                        Console.WriteLine(ex.ToString());
                        _ = Task.Run(() => _logger?.WriteLog(ex.ToString()));
                    }
                }
                else
                {
                    if (_lightClientSocket != null)
                    {
                        _lightClientSocket.Dispose();
                    }

                    _lightClientSocket   = new Socket(_config.Model.lightStripSettings.remoteAddressIp.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                    _lightClientEndpoint = new IPEndPoint(_config.Model.lightStripSettings.remoteAddressIp, _config.Model.lightStripSettings.remotePort);

                    if (_serializeStreams != null)
                    {
                        foreach (var stream in _serializeStreams)
                        {
                            stream.Value.Dispose();
                        }
                        _serializeStreams.Clear();
                    }
                    _serializeStreams = new Dictionary <byte, MemoryStream>();
                    //each light takes 3 bytes for its color
                    _packetColorSize = _packetMaxSize - _packetHeaderSize;
                    _packetCount     = (byte)Math.Ceiling((_lights.Count * _colorByteCount) / (double)(_packetColorSize));
                    for (byte i = 0; i < _packetCount; ++i)
                    {
                        _serializeStreams.Add(i, new MemoryStream(_packetMaxSize));
                    }
                }
                _started = true;

                _frameTimeSpan = TimeSpan.FromMilliseconds(1000 / _config.Model.lightStripSettings.updateFrameRate);
            }
            catch (Exception ex)
            {
                _ = Task.Run(() => _logger?.WriteLog(ex?.ToString()));
            }
        }
        static void Main(string[] args)
        {
            //var pp = new IT8951SPIDeviceExtension.PixelBuffer(0, 0, 800, 600, ImagePixelPackEnum.BPP1);
            var config = new ConfigurationBuilder()
                         .AddCommandLine(args)
                         .Build();
            bool waitEnter = config["wait"]?.ToLower() == "true";

            Console.WriteLine($"WaitEnter={waitEnter}");
            //SPI settings for raspberry pi 4B
            SpiConnectionSettings settings = new SpiConnectionSettings(0, 0);

            settings.ClockFrequency            = 12000000; //suggested 12MHZ in doc
            settings.Mode                      = SpiMode.Mode0;
            settings.ChipSelectLineActiveState = PinValue.Low;
            settings.DataFlow                  = DataFlow.MsbFirst;
            SpiDevice spi = SpiDevice.Create(settings);

            Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(settings));

            var device = new IT8951SPIDevice(new IT8951SPIDeviceIO(spi, readyPin: 24, resetPin: 17));

            //uncomment line below to output debug info
            //System.Diagnostics.Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
            Console.WriteLine($"IsLittleEndian:{BitConverter.IsLittleEndian} ");

            //uncomment following line if remote debugging
            //Console.WriteLine("Waiting for debugger attach, press ENTER continue");
            //Console.ReadLine();


            using (new Operation("Init"))
            {
                device.Init();
                device.SetVCom(-1.91f);//change this to your device VCOM value
            }
            ReadTempratureTest(device);
            ReadInfoTest(device);
            RWRegisterTest(device);
            RWVComTest(device);
            testClearScreen(device, DisplayModeEnum.INIT);


            drawImagePartialTest(device, "Images/3.jpg", new Size(96, 96), DisplayModeEnum.A2, waitEnter);

            testClearScreen(device, DisplayModeEnum.INIT);
            drawImagePartialTest(device, "Images/3.jpg", new Size(96, 96), DisplayModeEnum.GC16, waitEnter);

            testClearScreen(device, DisplayModeEnum.INIT);
            foreach (var f in Directory.GetFiles("Images"))
            {
                testClearScreen(device, DisplayModeEnum.A2);
                testdrawImage(device, f, waitEnter, DisplayModeEnum.A2);
            }

            testClearScreen(device, DisplayModeEnum.INIT);
            foreach (var f in Directory.GetFiles("Images"))
            {
                testdrawImage(device, f, waitEnter, DisplayModeEnum.GC16);
                testClearScreen(device, DisplayModeEnum.GC16);
            }


            testClearScreen(device, DisplayModeEnum.INIT);
            Console.WriteLine("done");
        }
示例#20
0
        static void Main(string[] args)
        {
            WaitForDebugger();

            // set SPI bus ID: 0
            // AD7193 CS Pin: 1
            SpiConnectionSettings settings = new SpiConnectionSettings(0, 1);

            settings.ClockFrequency = Ad7193.MaximumSpiFrequency;
            settings.Mode           = SpiMode.Mode3;
            SpiDevice ad7193SpiDevice = SpiDevice.Create(settings);


            ad7193 = new Ad7193(ad7193SpiDevice);
            ad7193.AdcValueReceived += Ad7193_AdcValueReceived;

            Console.WriteLine($"-- Resetting and calibrating AD7193.");
            ad7193.Reset();
            ad7193.PGAGain   = Ad7193.Gain.X1;
            ad7193.Averaging = Ad7193.AveragingMode.Off;
            ad7193.InputMode = Ad7193.AnalogInputMode.EightPseudoDifferentialAnalogInputs;
            ad7193.AppendStatusRegisterToData = true;
            ad7193.JitterCorrection           = true;
            ad7193.Filter = 0;

            Console.WriteLine($"AD7193 before calibration: offset={ad7193.Offset.ToString("X8")}, full-scale={ad7193.FullScale.ToString("X8")}");
            ad7193.Calibrate();
            Console.WriteLine($"AD7193  after calibration: offset={ad7193.Offset.ToString("X8")}, full-scale={ad7193.FullScale.ToString("X8")}");


            Console.WriteLine("Starting 100 single conversions on CH0...");
            ad7193.ActiveChannels = Ad7193.Channel.CH00;

            for (int i = 0; i < 100; i++)
            {
                ad7193.StartSingleConversion();
                ad7193.WaitForADC();
                ad7193.ReadADCValue();
                Thread.Sleep(25);
            }

            Thread.Sleep(1000);


            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Starting continuous conversion on CH0 and CH1...");
            ad7193.ActiveChannels = Ad7193.Channel.CH00 | Ad7193.Channel.CH01;
            ad7193.StartContinuousConversion();

            int loopcounter = 0;

            while (true)
            {
                loopcounter++;
                if (ad7193.HasErrors || (loopcounter % 50 == 0))
                {
                    Console.WriteLine();
                    Console.WriteLine($"AD7193 status: {ad7193.Status}");
                    Console.WriteLine($"AD7193 mode: {ad7193.Mode}");
                    Console.WriteLine($"AD7193 config: {ad7193.Config}");
                    Console.WriteLine();
                    Thread.Sleep(1500);
                }
                Thread.Sleep(250);
            }
        }
示例#21
0
 /// <inheritdoc />
 protected override SpiDevice CreateSimpleSpiDevice(SpiConnectionSettings settings, int[] pins)
 {
     return(SpiDevice.Create(settings));
 }
示例#22
0
        public static void Main(string[] args)
        {
            var message = "Hello World from MAX7219!";

            if (args.Length > 0)
            {
                message = string.Join(" ", args);
            }

            Console.WriteLine(message);

            var connectionSettings = new SpiConnectionSettings(0, 0)
            {
                ClockFrequency = Iot.Device.Max7219.Max7219.SpiClockFrequency,
                Mode           = Iot.Device.Max7219.Max7219.SpiMode
            };
            var spi = SpiDevice.Create(connectionSettings);

            using (var devices = new Max7219.Max7219(spi, cascadedDevices: 4))
            {
                // initialize the devices
                devices.Init();

                // reinitialize the devices
                Console.WriteLine("Init");
                devices.Init();

                // write a smiley to devices buffer
                var smiley = new byte[]
                {
                    0b00111100,
                    0b01000010,
                    0b10100101,
                    0b10000001,
                    0b10100101,
                    0b10011001,
                    0b01000010,
                    0b00111100
                };

                for (var i = 0; i < devices.CascadedDevices; i++)
                {
                    for (var digit = 0; digit < 8; digit++)
                    {
                        devices[i, digit] = smiley[digit];
                    }
                }

                // flush the smiley to the devices using a different rotation each iteration.
                foreach (RotationType rotation in Enum.GetValues(typeof(RotationType)))
                {
                    Console.WriteLine($"Send Smiley using rotation {devices.Rotation}.");
                    devices.Rotation = rotation;
                    devices.Flush();
                    Thread.Sleep(1000);
                }

                // reinitialize device and show message using the matrix graphics
                devices.Init();
                devices.Rotation = RotationType.Right;
                var graphics = new MatrixGraphics(devices, Fonts.Default);
                foreach (var font in new[]
                {
                    Fonts.CP437, Fonts.LCD, Fonts.Sinclair, Fonts.Tiny, Fonts.CyrillicUkrainian
                })
                {
                    graphics.Font = font;
                    graphics.ShowMessage(message, alwaysScroll: true);
                }
            }
        }
 public void InitSPI(SpiConnectionSettings settings)
 {
     this.SPI = SpiDevice.Create(settings);
 }
示例#24
0
        public static void Main()
        {
            SpiDevice             spiDevice;
            SpiConnectionSettings connectionSettings;

            Debug.WriteLine("Hello from sample for System.Device.Spi!");
            // You can get the values of SpiBus
            SpiBusInfo spiBusInfo = SpiDevice.GetBusInfo(1);

            Debug.WriteLine($"{nameof(spiBusInfo.ChipSelectLineCount)}: {spiBusInfo.ChipSelectLineCount}");
            Debug.WriteLine($"{nameof(spiBusInfo.MaxClockFrequency)}: {spiBusInfo.MaxClockFrequency}");
            Debug.WriteLine($"{nameof(spiBusInfo.MinClockFrequency)}: {spiBusInfo.MinClockFrequency}");
            Debug.WriteLine($"{nameof(spiBusInfo.SupportedDataBitLengths)}: ");
            foreach (var data in spiBusInfo.SupportedDataBitLengths)
            {
                Debug.WriteLine($"  {data}");
            }

            // Note: the ChipSelect pin should be adjusted to your device, here 12
            connectionSettings = new SpiConnectionSettings(1, 12);
            // You can adjust other settings as well in the connection
            connectionSettings.ClockFrequency = 1_000_000;
            connectionSettings.DataBitLength  = 8;
            connectionSettings.DataFlow       = DataFlow.LsbFirst;
            connectionSettings.Mode           = SpiMode.Mode2;

            // Then you create your SPI device by passing your settings
            spiDevice = SpiDevice.Create(connectionSettings);

            // You can write a SpanByte
            SpanByte writeBufferSpanByte = new byte[2] {
                42, 84
            };

            spiDevice.Write(writeBufferSpanByte);
            // Or a ushort buffer
            ushort[] writeBufferushort = new ushort[2] {
                4200, 8432
            };
            spiDevice.Write(writeBufferushort);
            // Or simply a byte
            spiDevice.WriteByte(42);

            // The read operations are similar
            SpanByte readBufferSpanByte = new byte[2];

            // This will read 2 bytes
            spiDevice.Read(readBufferSpanByte);
            ushort[] readUshort = new ushort[4];
            // This will read 4 ushort
            spiDevice.Read(readUshort);
            // read 1 byte
            byte readMe = spiDevice.ReadByte();

            Debug.WriteLine($"I just read a byte {readMe}");

            // And you can operate full transferts as well
            SpanByte writeBuffer = new byte[4] {
                0xAA, 0xBB, 0xCC, 0x42
            };
            SpanByte readBuffer = new byte[4];

            spiDevice.TransferFullDuplex(writeBuffer, readBuffer);
            // Same for ushirt arrays:
            ushort[] writeBufferus = new ushort[4] {
                0xAABC, 0x00BB, 0xCC00, 0x4242
            };
            ushort[] readBufferus = new ushort[4];
            spiDevice.TransferFullDuplex(writeBufferus, readBufferus);

            Thread.Sleep(Timeout.Infinite);

            // Browse our samples repository: https://github.com/nanoframework/samples
            // Check our documentation online: https://docs.nanoframework.net/
            // Join our lively Discord community: https://discord.gg/gCyBu8T
        }
示例#25
0
        static void Main()
        {
            SpiConnectionSettings connectionSettings = new SpiConnectionSettings(0, 0)
            {
                ClockFrequency = 10000000,
                Mode           = SpiMode.Mode0
            };

            using (SpiDevice spi = SpiDevice.Create(connectionSettings))
            {
                using (Max7219 device = new Max7219(spi))
                {
                    device.Init();

                    // Double init
                    device.Init();

                    device[0] = 0b01010101;
                    device[1] = 0b10101010;
                    device[2] = 0b01010101;
                    device[3] = 0b10111010;
                    device[4] = 0b01011101;
                    device[5] = 0b10111010;
                    device[6] = 0b01011101;
                    device[7] = 0b10111010;

                    device.Flush();

                    Console.WriteLine("Ready for next");
                    Console.ReadLine();



                    // Rotate the image

                    device.Rotation = RotationType.Left;
                    device.Flush();
                    Thread.Sleep(1000);

                    device.Rotation = RotationType.Half;
                    device.Flush();
                    Thread.Sleep(1000);

                    device.Rotation = RotationType.Right;
                    device.Flush();
                    Thread.Sleep(1000);

                    device.Rotation = RotationType.None;
                    device.Flush();

                    Console.WriteLine("Ready for next");
                    Console.ReadLine();



                    // Show some text

                    device.Init();

                    device.Rotation = RotationType.None;

                    MatrixGraphics graphics = new MatrixGraphics(device, Fonts.Default);

                    graphics.ShowMessage("Hello Alt.Net!", alwaysScroll: true);

                    Console.WriteLine("Done!");
                    Console.ReadLine();



                    device.ClearAll();
                }
            }
        }
        /// <summary>
        ///     Open a connection to the Expander Pi.
        /// </summary>
        public void Connect()
        {
            if (IsConnected)
            {
                return; // Already connected
            }

            try
            {
                // Create SPI initialization settings for the ADC
                var adcSettings = new SpiConnectionSettings(SPI_BUS_ID, ADC_CHIP_SELECT_LINE)
                {
                    ClockFrequency = 200000, // SPI clock frequency of 200KHz
                    Mode           = SpiMode.Mode0
                };

                adc = SpiDevice.Create(adcSettings); // Create an ADC connection with our bus controller and SPI settings

                // Create SPI initialization settings for the DAC
                var dacSettings =
                    new SpiConnectionSettings(SPI_BUS_ID, DAC_CHIP_SELECT_LINE)
                {
                    ClockFrequency = 2000000,      // SPI clock frequency of 20MHz
                    Mode           = SpiMode.Mode0
                };

                dac = SpiDevice.Create(dacSettings); // Create an ADC connection with our bus controller and SPI settings



                // Initialize the I2C bus

                var IOsettings = new I2cConnectionSettings(1, IOADDRESS);
                IOi2cbus = I2cDevice.Create(IOsettings);

                var RTCsettings = new I2cConnectionSettings(1, RTCADDRESS);
                RTCi2cbus = I2cDevice.Create(RTCsettings);

                if (IOi2cbus != null && RTCi2cbus != null)
                {
                    // Set IsConnected to true
                    IsConnected = true;

                    // i2c bus is connected so set up the initial configuration for the IO Pi
                    helper.WriteI2CByte(IOi2cbus, IOCON, config);

                    portaval = helper.ReadI2CByte(IOi2cbus, GPIOA);
                    portbval = helper.ReadI2CByte(IOi2cbus, GPIOB);
                    helper.WriteI2CByte(IOi2cbus, IODIRA, 0xFF);
                    helper.WriteI2CByte(IOi2cbus, IODIRB, 0xFF);
                    IOSetPortPullups(0, 0x00);
                    IOSetPortPullups(1, 0x00);
                    IOInvertPort(0, 0x00);
                    IOInvertPort(1, 0x00);

                    // Fire the Connected event handler
                    Connected?.Invoke(this, EventArgs.Empty);
                }
            }
            /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                IsConnected = false;
                throw new Exception("SPI and I2C Initialization Failed", ex);
            }
        }