Beispiel #1
0
        static void Main(string[] args)
        {
            SpiConnectionSettings settings = new SpiConnectionSettings(0, 0)
            {
                ClockFrequency = Iot.Device.Adxl345.Adxl345.SpiClockFrequency,
                Mode           = Iot.Device.Adxl345.Adxl345.SpiMode
            };
            // get SpiDevice(In Linux)
            UnixSpiDevice device = new UnixSpiDevice(settings);

            // get SpiDevice(In Win10)
            // Windows10SpiDevice device = new Windows10SpiDevice(settings);

            // pass in a SpiDevice
            // 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);
                }
            }
        }
Beispiel #2
0
        public static void Main(string[] args)
        {
            var pinCS0 = GpioPin.FromNumber(25); // Pin 22 (BCM 25)
            var pinCS1 = GpioPin.FromNumber(26); // Pin 37 (BCM 26)
            var pinRST = GpioPin.FromNumber(16); // Pin 36 (BCM 16)

            var spiSettings = new SpiConnectionSettings(busId: 0, chipSelectLine: 0);
            var gpioPinMap  = new Dictionary <TargetChip, ChipPinConfig>
            {
                [TargetChip.Board0] = new ChipPinConfig(csPin: pinCS0, resetPin: pinRST),
                [TargetChip.Board1] = new ChipPinConfig(csPin: pinCS1, resetPin: pinRST),
            };

            using (var spiDevice = new UnixSpiDevice(spiSettings))
                using (var gpioController = new GpioController(PinNumberingScheme.Logical))
                    using (var ymf825Device = new NativeSpi(spiDevice, gpioController, gpioPinMap))
                    {
                        var driver = new Ymf825Driver(ymf825Device);
                        driver.EnableSectionMode();

                        Console.WriteLine("Software Reset");
                        driver.ResetSoftware();

                        SetupTones(driver);

                        var index = 0;
                        var score = new[]
                        {
                            60, 62, 64, 65, 67, 69, 71, 72,
                            72, 74, 76, 77, 79, 81, 83, 84,
                            84, 83, 81, 79, 77, 76, 74, 72,
                            72, 71, 69, 67, 65, 64, 62, 60
                        };

                        while (true)
                        {
                            const int noteOnTime = 250;
                            const int sleepTime  = 0;

                            NoteOn(driver, score[index]);
                            Thread.Sleep(noteOnTime);
                            NoteOff(driver);

                            Thread.Sleep(sleepTime);

                            if (Console.KeyAvailable)
                            {
                                break;
                            }

                            index++;
                            if (index >= score.Length)
                            {
                                index = 0;
                            }
                        }

                        driver.ResetHardware();
                    }
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello Max7219!");

            var connectionSettings = new SpiConnectionSettings(0, 0)
            {
                ClockFrequency = Max7219.SpiClockFrequency,
                Mode           = Max7219.SpiMode
            };
            var spi = new UnixSpiDevice(connectionSettings);

            using (var devices = new 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.Left;
                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("Hello World from MAX7219!", alwaysScroll: true);
                }
            }
        }
Beispiel #4
0
        private static Mcp25xxx GetMcp25xxxDevice()
        {
            var spiConnectionSettings = new SpiConnectionSettings(0, 0);
            var spiDevice             = new UnixSpiDevice(spiConnectionSettings);

            return(new Mcp25625(spiDevice));
        }
Beispiel #5
0
        /// <summary>
        /// Initialize SPI.
        /// </summary>
        /// <returns></returns>
        protected void InitializeSpi()
        {
            try
            {
                var connectionSettings = new SpiConnectionSettings((int)busId, (int)chipSelect)
                {
                    ClockFrequency = 10_000_000,
                    Mode           = System.Device.Spi.SpiMode.Mode0
                };

                SpiDisplay = new UnixSpiDevice(connectionSettings);

                // var settings = new SpiConnectionSettings((int)chipSelect);
                // settings.ClockFrequency = 10000000;
                // settings.Mode = SpiMode.Mode0;
                // settings.SharingMode = SpiSharingMode.Shared;

                // string spiAqs = SpiDevice.GetDeviceSelector(SPIControllerName);       /* Find the selector string for the SPI bus controller          */
                // var devicesInfo = await DeviceInformation.FindAllAsync(spiAqs);         /* Find the SPI bus controller device with our selector string  */
                // SpiDisplay = await SpiDevice.FromIdAsync(devicesInfo[0].Id, settings);  /* Create an SpiDevice with our bus controller and SPI settings */
            }
            /* If initialization fails, display the exception and stop running */
            catch (Exception ex)
            {
                throw new Exception("SPI Initialization Failed", ex);
            }
        }
Beispiel #6
0
        static void Main()
        {
            // Create a Neo Pixel x8 stick on spi 0.0
            var spi = new UnixSpiDevice(new SpiConnectionSettings(0, 0));
            var neo = new Ws2812b(spi, 8);

            // Display basic colors for 5 sec
            BitmapImageNeo3 img = neo.Image;

            img.SetPixel(0, 0, Color.White);
            img.SetPixel(1, 0, Color.Red);
            img.SetPixel(2, 0, Color.Green);
            img.SetPixel(3, 0, Color.Blue);
            img.SetPixel(4, 0, Color.Yellow);
            img.SetPixel(5, 0, Color.Cyan);
            img.SetPixel(6, 0, Color.Magenta);
            img.SetPixel(7, 0, Color.FromArgb(unchecked ((int)0xffff8000)));
            neo.Update();
            System.Threading.Thread.Sleep(5000);

            // Fade in first pixel
            byte b = 0;

            img.Clear();
            while (true)
            {
                img.SetPixel(0, 0, Color.FromArgb(0xff, b, b, b));
                neo.Update();
                System.Threading.Thread.Sleep(10);
                b++;
            }
        }
Beispiel #7
0
        private static void Spi_Roundtrip()
        {
            // For this sample connect SPI0 MOSI with SPI0 MISO.
            var settings = new SpiConnectionSettings(0, 0);

            using (var device = new UnixSpiDevice(settings))
            {
                var writeBuffer = new byte[]
                {
                    0xA, 0xB, 0xC, 0xD, 0xE, 0xF
                };

                var readBuffer = new byte[writeBuffer.Length];

                device.TransferFullDuplex(writeBuffer, readBuffer);

                Console.WriteLine("Sent data:");

                foreach (byte b in writeBuffer)
                {
                    Console.Write("{0:X2} ", b);
                }

                Console.WriteLine();
                Console.WriteLine("Received data:");

                foreach (byte b in readBuffer)
                {
                    Console.Write("{0:X2} ", b);
                }

                Console.WriteLine();
            }
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello Mcp3008!");

            // This sample implements two different ways of accessing the MCP3008.
            // The SPI option is enabled in the sample by default, but you can switch
            // to the GPIO bit-banging option by switching which one is commented out.
            // The sample uses local functions to make it easier to switch between
            // the two implementations.

            // SPI implementation
            Mcp3008 GetMcp3008WithSpi()
            {
                Console.WriteLine("Using SPI protocol.");

                var connection = new SpiConnectionSettings(0, 0)
                {
                    ClockFrequency = 1000000,
                    Mode           = SpiMode.Mode0
                };

                var spi     = new UnixSpiDevice(connection);
                var mcp3008 = new Mcp3008(spi);

                return(mcp3008);
            }

            // GPIO (via bit banging) implementation
            Mcp3008 GetMcp3008WithGpio()
            {
                Console.WriteLine("Using GPIO pins.");
                var mcp3008 = new Mcp3008(18, 23, 24, 25);

                return(mcp3008);
            }

            Mcp3008 mcp = GetMcp3008WithSpi();

            // Uncomment next line to use GPIO instead.
            // Mcp3008 mcp = GetMcp3008WithGpio();

            using (mcp)
            {
                while (true)
                {
                    double value = mcp.Read(0, Mcp3008.InputConfiguration.SingleEnded);
                    value = value / 10.24;
                    value = Math.Round(value);
                    Console.WriteLine(value);
                    Thread.Sleep(500);
                }
            }
        }
Beispiel #9
0
    public static Volume EnableVolume()
    {
        var connection = new SpiConnectionSettings(0, 0);

        connection.ClockFrequency = 1000000;
        connection.Mode           = SpiMode.Mode0;
        var spi     = new UnixSpiDevice(connection);
        var mcp3008 = new Mcp3008(spi);
        var volume  = new Volume(mcp3008);

        volume.Init();
        return(volume);
    }
Beispiel #10
0
        private static Mcp23xxx GetMcp23xxxWithSpi()
        {
            Console.WriteLine("Using SPI protocol");

            var connection = new SpiConnectionSettings(0, 0)
            {
                ClockFrequency = 1000000,
                Mode           = SpiMode.Mode0
            };

            var spi      = new UnixSpiDevice(connection);
            var mcp23xxx = new Mcp23xxx(spi);

            return(mcp23xxx);
        }
Beispiel #11
0
        private static Mcp23xxx GetMcp23xxxDevice(Mcp23xxxDevice mcp23xxxDevice)
        {
            var i2cConnectionSettings = new I2cConnectionSettings(1, s_deviceAddress);
            var i2cDevice             = new UnixI2cDevice(i2cConnectionSettings);

            // I2C.
            switch (mcp23xxxDevice)
            {
            case Mcp23xxxDevice.Mcp23008:
                return(new Mcp23008(i2cDevice));

            case Mcp23xxxDevice.Mcp23009:
                return(new Mcp23009(i2cDevice));

            case Mcp23xxxDevice.Mcp23017:
                return(new Mcp23017(i2cDevice));

            case Mcp23xxxDevice.Mcp23018:
                return(new Mcp23018(i2cDevice));
            }

            var spiConnectionSettings = new SpiConnectionSettings(0, 0)
            {
                ClockFrequency = 1000000,
                Mode           = SpiMode.Mode0
            };

            var spiDevice = new UnixSpiDevice(spiConnectionSettings);

            // SPI.
            switch (mcp23xxxDevice)
            {
            case Mcp23xxxDevice.Mcp23S08:
                return(new Mcp23S08(s_deviceAddress, spiDevice));

            case Mcp23xxxDevice.Mcp23S09:
                return(new Mcp23S09(s_deviceAddress, spiDevice));

            case Mcp23xxxDevice.Mcp23S17:
                return(new Mcp23S17(s_deviceAddress, spiDevice));

            case Mcp23xxxDevice.Mcp23S18:
                return(new Mcp23S18(s_deviceAddress, spiDevice));
            }

            throw new Exception($"Invalid Mcp23xxxDevice: {nameof(mcp23xxxDevice)}");
        }
Beispiel #12
0
        public LightStrip(int count, ILogger <LightStrip> logger)
        {
            _logger = logger;

            LedCount = count;

            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 = new UnixSpiDevice(settings);

            Device = new Ws2812b(spi, count);
        }
Beispiel #13
0
        static void Main()
        {
            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 = new UnixSpiDevice(settings);

#if WS2808
            var neo = new Ws2808(spi, count);
#else
            var neo = new Ws2812b(spi, count);
#endif

            // Display basic colors for 5 sec
            BitmapImage img = neo.Image;
            img.Clear();
            img.SetPixel(0, 0, Color.White);
            img.SetPixel(1, 0, Color.Red);
            img.SetPixel(2, 0, Color.Green);
            img.SetPixel(3, 0, Color.Blue);
            img.SetPixel(4, 0, Color.Yellow);
            img.SetPixel(5, 0, Color.Cyan);
            img.SetPixel(6, 0, Color.Magenta);
            img.SetPixel(7, 0, Color.FromArgb(unchecked ((int)0xffff8000)));
            neo.Update();
            System.Threading.Thread.Sleep(5000);

            // Fade in first pixel
            byte b = 0;
            img.Clear();
            while (true)
            {
                img.SetPixel(0, 0, Color.FromArgb(0xff, b, b, b));
                neo.Update();
                System.Threading.Thread.Sleep(10);
                b++;
            }
        }
    }
Beispiel #14
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
            };
            UnixSpiDevice senderDevice   = new UnixSpiDevice(senderSettings);
            UnixSpiDevice receiverDevice = new UnixSpiDevice(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);
                    }
                }
            }
        }
Beispiel #15
0
        static void Main(string[] args)
        {
            //new WaitForDebugger();


            SpiConnectionSettings _spiConnectionSettings = new SpiConnectionSettings(2,
                                                                                     1)
            {
                Mode          = SpiMode.Mode0,
                DataBitLength = 8
            };

            UnixSpiDevice _spiDevice = new UnixSpiDevice(_spiConnectionSettings);

            BME280Driver _bme280 = new BME280Driver(_spiDevice);

            _bme280.Initialize();

            _bme280.ChangeSettings(
                BME280SensorMode.Forced,
                BME280OverSample.X1,
                BME280OverSample.X1,
                BME280OverSample.X1,
                BME280Filter.Off);

            DateTime _lastLog = DateTime.MinValue;

            string _connectionString = @"Data Source=192.168.1.10\SQL2K16;Initial Catalog=LoggerDatabase;Persist Security Info=True;User ID=logger;Password=******;";

            SqlConnection _con = new SqlConnection(_connectionString);

            _con.Open();
            SqlCommand _command = new SqlCommand(Resources.InsertCommand, _con);

            _command.Parameters.Add(new SqlParameter("Source", "Source1"));
            _command.Parameters.Add(new SqlParameter("Id", System.Data.SqlDbType.UniqueIdentifier));
            _command.Parameters.Add(new SqlParameter("Barometric", System.Data.SqlDbType.Decimal));
            _command.Parameters.Add(new SqlParameter("Humidity", System.Data.SqlDbType.Decimal));
            _command.Parameters.Add(new SqlParameter("Temperature", System.Data.SqlDbType.Decimal));

            while (true)
            {
                _bme280.Update();
                string _data    = $"Pressure : {_bme280.Pressure:0.0} Pa, Humidity : {_bme280.Humidity:0.00}%, Temprature : {_bme280.Temperature:0.00}°C";
                string _logData = $"[{DateTime.Now.ToString("dddd MMM dd, yyyy h:mm:ss tt")}] {_data}";

                if ((DateTime.Now - _lastLog).TotalMinutes > 1)
                {
                    _lastLog = DateTime.Now;
                    File.AppendAllLines("BME280.log", new string[] { _logData });
                    Console.WriteLine(_logData);
                    _command.Parameters["Id"].Value          = Guid.NewGuid();
                    _command.Parameters["Barometric"].Value  = _bme280.Pressure;
                    _command.Parameters["Humidity"].Value    = _bme280.Humidity;
                    _command.Parameters["Temperature"].Value = _bme280.Temperature;
                    _command.ExecuteNonQuery();
                }
                else
                {
                    Console.WriteLine(_data);
                }
                Thread.Sleep(1000);
            }
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            var pin = 17;
            var lightTimeInMilliseconds = 500;
            var dimTimeInMilliseconds   = 500;

            byte[] buffer = new byte[2];
            UInt16 data = 0, config, sendValue;

            System.IO.Ports.SerialPort port = new SerialPort();

            // SPI
            // DAC on GertBoard on CS1
            // using '/dev/spidev0.1' (use chipSelect = 0 for spidev0.0)
            var busId      = 0;
            var chipSelect = 1;
            var settings   = new SpiConnectionSettings(busId, chipSelect);

            // create device to talk to DtoA (MCP4802)
            SpiDevice spi = new UnixSpiDevice(settings);

            using (GpioController controller = new GpioController())
            {
                controller.OpenPin(pin, PinMode.Output);
                Console.WriteLine($"GPIO pin enabled for use: {pin}");

                Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs eventArgs) =>
                {
                    controller.Dispose();
                };

                while (true)
                {
                    Console.WriteLine($"Light for {lightTimeInMilliseconds}ms");
                    controller.Write(pin, PinValue.High);
                    Thread.Sleep(lightTimeInMilliseconds);
                    Console.WriteLine($"Dim for {dimTimeInMilliseconds}ms");
                    controller.Write(pin, PinValue.Low);
                    Thread.Sleep(dimTimeInMilliseconds);

                    // data has to be sent as 16 bit value with CS low for both bytes
                    //
                    config = 0x3000;    // Channel A, Gain = 1 (0011)
                    // config = 0xB000;    // Channel B, Gain = 1 (1011)
                    // config = 0x1000;    // Channel A, Gain = 2 (0001)
                    // config = 0x9000;    // Channel B, Gain = 2 (1001)

                    // data left shifted by 4 bits
                    sendValue  = (ushort)(data << 4);
                    sendValue |= config;

                    buffer[0] = (byte)((sendValue & 0xFF00) >> 8);
                    buffer[1] = (byte)(sendValue & 0x00FF);

                    // send using Write(ReadOnlySpan) as WriteByte will raise CS between bytes
                    ReadOnlySpan <byte> span = buffer;

                    // write 16 bit value to DAC
                    spi.Write(span);

                    // increment data value
                    data += 10;

                    // reset data value
                    if (data >= 256)
                    {
                        data = 0;
                    }
                }
            }
        }
Beispiel #17
0
 public BME280Driver(UnixSpiDevice spiDevice)
 {
     device = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
 }