Exemple #1
0
        private static void Dim(CancellationToken cancellationToken) =>
        Task.Run(() =>
        {
            Console.Clear();
            "Dimming".Info();
            ExitMessage.WriteLine();
            var pin             = (GpioPin)Pi.Gpio[BcmPin.Gpio13];
            pin.PinMode         = GpioPinDriveMode.PwmOutput;
            pin.PwmMode         = PwmMode.Balanced;
            pin.PwmClockDivisor = 2;
            while (!cancellationToken.IsCancellationRequested)
            {
                for (var x = 0; x <= 100; x++)
                {
                    pin.PwmRegister = (int)pin.PwmRange / 100 * x;
                    Thread.Sleep(10);
                }

                for (var x = 0; x <= 100; x++)
                {
                    pin.PwmRegister = (int)pin.PwmRange - ((int)pin.PwmRange / 100 * x);
                    Thread.Sleep(10);
                }
            }

            pin.PinMode = GpioPinDriveMode.Output;
            pin.Write(0);
        });
Exemple #2
0
        /// <summary>
        /// Test the GY521 Accelerometer and Gyroscope.
        /// </summary>
        public static void TestAccelerometer()
        {
            Console.Clear();

            // Add device
            var accelDevice = Pi.I2C.AddDevice(0x68);

            // Set accelerometer
            using (var accelSensor = new AccelerometerGY521(accelDevice))
            {
                // Present info to screen
                accelSensor.DataAvailable +=
                    (s, e) =>
                {
                    Console.Clear();
                    $"\nAccelerometer:\n{e.Accel}\n\nGyroscope:\n{e.Gyro}\n\nTemperature: {Math.Round(e.Temperature, 2)}°C\n"
                    .Info("GY-521");
                    ExitMessage.WriteLine();
                };

                // Run accelerometer
                accelSensor.Start();
                while (true)
                {
                    var input = Console.ReadKey(true).Key;
                    if (input != ConsoleKey.Escape)
                    {
                        continue;
                    }

                    break;
                }
            }
        }
        private static void ReadCard()
        {
            Console.Clear();
            "Testing RFID".Info();
            var device = new RFIDControllerMfrc522(Pi.Spi.Channel0, 500000, Pi.Gpio[18]);

            while (true)
            {
                // If a card is found
                if (device.DetectCard() != RFIDControllerMfrc522.Status.AllOk)
                {
                    continue;
                }

                // Get the UID of the card
                var uidResponse = device.ReadCardUniqueId();

                // If we have the UID, continue
                if (uidResponse.Status != RFIDControllerMfrc522.Status.AllOk)
                {
                    continue;
                }

                var cardUid = uidResponse.Data;

                // Print UID
                $"Card UID: {cardUid[0]},{cardUid[1]},{cardUid[2]},{cardUid[3]}".Info();

                // Select the scanned tag
                device.SelectCardUniqueId(cardUid);

                // Authenticate sector
                if (device.AuthenticateCard1A(RFIDControllerMfrc522.DefaultAuthKey, cardUid, 19) == RFIDControllerMfrc522.Status.AllOk)
                {
                    var data = device.CardReadData(16);
                    var text = Encoding.ASCII.GetString(data.Data);

                    $" Message read: {text}".Info();
                }
                else
                {
                    "Authentication error".Error();
                }

                device.ClearCardSelection();
                ExitMessage.WriteLine();
                while (true)
                {
                    var input = Console.ReadKey(true).Key;
                    if (input != ConsoleKey.Escape)
                    {
                        continue;
                    }

                    break;
                }

                break;
            }
        }
        /// <summary>
        /// Tests the temperature sensor.
        /// </summary>
        public static void TestTempSensor()
        {
            Console.Clear();
            using (var sensor = DhtSensor.Create(DhtType.Dht11, Pi.Gpio[BcmPin.Gpio04]))
            {
                var totalReadings = 0.0;
                var validReadings = 0.0;

                sensor.OnDataAvailable += (s, e) =>
                {
                    totalReadings++;
                    if (!e.IsValid)
                    {
                        return;
                    }

                    Console.Clear();
                    validReadings++;
                    $"Temperature: \n {e.Temperature:0.00}°C \n {e.TemperatureFahrenheit:0.00}°F  \n Humidity: {e.HumidityPercentage:P0}\n\n".Info("DHT11");
                    ExitMessage.WriteLine();
                };

                sensor.Start();
                while (true)
                {
                    var input = Console.ReadKey(true).Key;
                    if (input != ConsoleKey.Escape)
                    {
                        continue;
                    }

                    break;
                }
            }
        }
        private static void WriteCard()
        {
            Console.Clear();
            "Testing RFID".Info();

            var device    = new RFIDControllerMfrc522(Pi.Spi.Channel0, 500000, Pi.Gpio[18]);
            var userInput = "Insert a message to be written in the card (16 characters only)".ReadLine().Truncate(16);

            "Place the card on the sensor".Info();

            while (true)
            {
                // If a card is found
                if (device.DetectCard() != RFIDControllerMfrc522.Status.AllOk)
                {
                    continue;
                }

                // Get the UID of the card
                var uidResponse = device.ReadCardUniqueId();

                // If we have the UID, continue
                if (uidResponse.Status != RFIDControllerMfrc522.Status.AllOk)
                {
                    continue;
                }

                var cardUid = uidResponse.Data;

                // Select the scanned tag
                device.SelectCardUniqueId(cardUid);

                // Writing data to sector 1 blocks
                // Authenticate sector
                if (device.AuthenticateCard1A(RFIDControllerMfrc522.DefaultAuthKey, cardUid, 19) == RFIDControllerMfrc522.Status.AllOk)
                {
                    userInput = (userInput + new string(' ', 16)).Truncate(16);
                    device.CardWriteData(16, Encoding.ASCII.GetBytes(userInput));
                }

                device.ClearCardSelection();
                "Data has been written".Info();

                ExitMessage.WriteLine();
                while (true)
                {
                    var input = Console.ReadKey(true).Key;
                    if (input != ConsoleKey.Escape)
                    {
                        continue;
                    }

                    break;
                }

                break;
            }
        }
        /// <summary>
        /// Tests the infrared sensor HX1838.
        /// </summary>
        public static void TestInfraredSensor()
        {
            Console.Clear();
            "Send a signal...".Info("IR");
            var inputPin = Pi.Gpio[BcmPin.Gpio25]; // BCM Pin 25 or Physical pin 22 on the right side of the header.
            var sensor   = new InfraredSensor(inputPin, true);

            sensor.DataAvailable += (s, e) =>
            {
                Console.Clear();
                var necData = InfraredSensor.NecDecoder.DecodePulses(e.Pulses);
                if (necData != null)
                {
                    $"NEC Data: {BitConverter.ToString(necData).Replace("-", " "),12}    Pulses: {e.Pulses.Length,4}    Duration(us): {e.TrainDurationUsecs,6}    Reason: {e.FlushReason}".Warn("IR");

                    if (InfraredSensor.NecDecoder.IsRepeatCode(e.Pulses))
                    {
                        return;
                    }
                }
                else
                {
                    if (e.Pulses.Length >= 4)
                    {
                        var debugData = InfraredSensor.DebugPulses(e.Pulses);
                        $"RX    Length: {e.Pulses.Length,5}; Duration: {e.TrainDurationUsecs,7}; Reason: {e.FlushReason}".Warn("IR");
                        debugData.Info("IR");
                    }
                    else
                    {
                        $"RX (Garbage): {e.Pulses.Length,5}; Duration: {e.TrainDurationUsecs,7}; Reason: {e.FlushReason}".Error("IR");
                    }
                }

                ExitMessage.WriteLine();
            };

            while (true)
            {
                var input = Console.ReadKey(true).Key;
                if (input != ConsoleKey.Escape)
                {
                    continue;
                }

                break;
            }

            sensor.Dispose();
        }
        private static void CardDetected()
        {
            Console.Clear();
            "Testing RFID".Info();
            var device = new RFIDControllerMfrc522(Pi.Spi.Channel0, 500000, Pi.Gpio[18]);

            while (true)
            {
                // If a card is found
                if (device.DetectCard() != RFIDControllerMfrc522.Status.AllOk)
                {
                    continue;
                }
                "Card detected".Info();

                // Get the UID of the card
                var uidResponse = device.ReadCardUniqueId();

                // If we have the UID, continue
                if (uidResponse.Status != RFIDControllerMfrc522.Status.AllOk)
                {
                    continue;
                }

                var cardUid = uidResponse.Data;

                // Print UID
                $"Card UID: {cardUid[0]},{cardUid[1]},{cardUid[2]},{cardUid[3]}".Info();

                ExitMessage.WriteLine();

                while (true)
                {
                    var input = Console.ReadKey(true).Key;
                    if (input != ConsoleKey.Escape)
                    {
                        continue;
                    }

                    break;
                }

                break;
            }
        }
Exemple #8
0
        private static async Task TestSystemInfo()
        {
            Console.Clear();

            $"GPIO Controller initialized successfully with {Pi.Gpio.Count} pins".Info();
            $"{Pi.Info}".Info();
            try
            {
                $"BoardModel {Pi.Info.BoardModel}".Info();
                $"ProcessorModel {Pi.Info.ProcessorModel}".Info();
                $"Manufacturer {Pi.Info.Manufacturer}".Info();
                $"MemorySize {Pi.Info.MemorySize}".Info();
            }
            catch
            {
                // ignore
            }

            $"Uname {Pi.Info.OperatingSystem}".Info();
            $"HostName {NetworkSettings.Instance.HostName}".Info();
            $"Uptime (seconds) {Pi.Info.Uptime}".Info();
            var timeSpan = Pi.Info.UptimeTimeSpan;

            $"Uptime (timespan) {timeSpan.Days} days {timeSpan.Hours:00}:{timeSpan.Minutes:00}:{timeSpan.Seconds:00}"
            .Info();

            (await NetworkSettings.Instance.RetrieveAdapters().ConfigureAwait(false))
            .Select(adapter => $"Adapter: {adapter.Name,6} | IPv4: {adapter.IPv4,16} | IPv6: {adapter.IPv6,28} | AP: {adapter.AccessPointName,16} | MAC: {adapter.MacAddress,18}")
            .ToList()
            .ForEach(x => x.Info());

            ExitMessage.WriteLine();

            while (true)
            {
                var input = Console.ReadKey(true).Key;
                if (input != ConsoleKey.Escape)
                {
                    continue;
                }

                break;
            }
        }
Exemple #9
0
        private static void Blink(CancellationToken cancellationToken) =>
        Task.Run(() =>
        {
            Console.Clear();
            var blinkingPin = Pi.Gpio[BcmPin.Gpio13];

            // Configure the pin as an output
            blinkingPin.PinMode = GpioPinDriveMode.Output;

            // perform writes to the pin by toggling the isOn variable
            var isOn = false;
            while (!cancellationToken.IsCancellationRequested)
            {
                isOn = !isOn;
                blinkingPin.Write(isOn);
                var ledState = isOn ? "on" : "off";
                Console.Clear();
                $"Blinking {ledState}".Info();
                ExitMessage.WriteLine();
                Thread.Sleep(500);
            }

            blinkingPin.Write(0);
        });
Exemple #10
0
        public static void TestUltrasonicSensor()
        {
            ConsoleColor color;

            using (var sensor = new UltrasonicHcsr04(Pi.Gpio[BcmPin.Gpio23], Pi.Gpio[BcmPin.Gpio24]))
            {
                sensor.OnDataAvailable += (s, e) =>
                {
                    Console.Clear();

                    if (!e.IsValid)
                    {
                        return;
                    }

                    if (e.HasObstacles)
                    {
                        if (e.Distance <= 10)
                        {
                            color = ConsoleColor.DarkRed;
                        }
                        else if (e.Distance <= 20)
                        {
                            color = ConsoleColor.DarkYellow;
                        }
                        else if (e.Distance <= 30)
                        {
                            color = ConsoleColor.Yellow;
                        }
                        else if (e.Distance <= 40)
                        {
                            color = ConsoleColor.Green;
                        }
                        else if (e.Distance <= 50)
                        {
                            color = ConsoleColor.Blue;
                        }
                        else
                        {
                            color = ConsoleColor.White;
                        }

                        var distance = e.Distance < 57 ? e.Distance : 58;
                        $"{new string('█', (int)distance)}".WriteLine(color);
                        "--------------------------------------------------------->".WriteLine();
                        "          10        20        30        40        50       cm".WriteLine();
                        $"Obstacle detected at {e.Distance:N2}cm / {e.DistanceInch:N2}in\n".WriteLine();
                    }
                    else
                    {
                        "No obstacles detected.\n".Info("HC - SR04");
                    }

                    ExitMessage.WriteLine();
                };

                sensor.Start();
                while (true)
                {
                    var input = Console.ReadKey(true).Key;
                    if (input != ConsoleKey.Escape)
                    {
                        continue;
                    }

                    break;
                }
            }
        }
        private static void ReadAllCardSectors()
        {
            Console.Clear();

            "Testing RFID".Info();
            var device = new RFIDControllerMfrc522(Pi.Spi.Channel0, 500000, Pi.Gpio[18]);

            while (true)
            {
                // If a card is found
                if (device.DetectCard() != RFIDControllerMfrc522.Status.AllOk)
                {
                    continue;
                }

                // Get the UID of the card
                var uidResponse = device.ReadCardUniqueId();

                // If we have the UID, continue
                if (uidResponse.Status != RFIDControllerMfrc522.Status.AllOk)
                {
                    continue;
                }

                var cardUid = uidResponse.Data;

                // Print UID
                $"Card UID: {cardUid[0]},{cardUid[1]},{cardUid[2]},{cardUid[3]}".Info();

                // Select the scanned tag
                device.SelectCardUniqueId(cardUid);

                // Reading data
                var continueReading = true;
                for (var s = 0; s < 16 && continueReading; s++)
                {
                    // Authenticate sector
                    if (device.AuthenticateCard1A(RFIDControllerMfrc522.DefaultAuthKey, cardUid, (byte)((4 * s) + 3)) == RFIDControllerMfrc522.Status.AllOk)
                    {
                        $"Sector {s}".Info();
                        for (var b = 0; b < 3 && continueReading; b++)
                        {
                            var data = device.CardReadData((byte)((4 * s) + b));
                            if (data.Status != RFIDControllerMfrc522.Status.AllOk)
                            {
                                continueReading = false;
                                break;
                            }

                            $"  Block {b} ({data.Data.Length} bytes): {string.Join(" ", data.Data.Select(x => x.ToString("X2")))}".Info();
                        }
                    }
                    else
                    {
                        $"Authentication error, sector {s}".Error();
                    }
                }

                device.ClearCardSelection();

                ExitMessage.WriteLine();
                while (true)
                {
                    var input = Console.ReadKey(true).Key;
                    if (input != ConsoleKey.Escape)
                    {
                        continue;
                    }

                    break;
                }

                break;
            }
        }
Exemple #12
0
 private static void LogMessageOnEvent(string message)
 {
     Console.Clear();
     message.Info();
     ExitMessage.WriteLine();
 }