public static void TestAnalogIn(ArduinoBoard board) { // Use Pin 6 const int gpio = 6; int analogPin = GetAnalogPin1(board); var gpioController = board.CreateGpioController(); var analogController = board.CreateAnalogController(0); var pin = analogController.OpenPin(analogPin); gpioController.OpenPin(gpio); gpioController.SetPinMode(gpio, PinMode.Output); Console.WriteLine("Blinking GPIO6, based on analog input."); while (!Console.KeyAvailable) { ElectricPotential voltage = pin.ReadVoltage(); gpioController.Write(gpio, PinValue.High); Thread.Sleep((int)(voltage * 100).Volts); voltage = pin.ReadVoltage(); gpioController.Write(gpio, PinValue.Low); Thread.Sleep((int)(voltage * 100).Volts); } pin.Dispose(); Console.ReadKey(); analogController.Dispose(); gpioController.Dispose(); }
public static void TestAnalogCallback(ArduinoBoard board) { int analogPin = GetAnalogPin1(board); var analogController = board.CreateAnalogController(0); board.SetAnalogPinSamplingInterval(TimeSpan.FromMilliseconds(10)); var pin = analogController.OpenPin(analogPin); pin.EnableAnalogValueChangedEvent(null, 0); pin.ValueChanged += (sender, args) => { if (args.PinNumber == analogPin) { Console.WriteLine($"New voltage: {args.Value}."); } }; Console.WriteLine("Waiting for changes on the analog input"); while (!Console.KeyAvailable) { // Nothing to do Thread.Sleep(100); } Console.ReadKey(); pin.DisableAnalogValueChangedEvent(); pin.Dispose(); analogController.Dispose(); }
public static void TestEventsCallback(ArduinoBoard board) { const int Gpio2 = 2; var gpioController = board.CreateGpioController(); // Opening GPIO2 gpioController.OpenPin(Gpio2); gpioController.SetPinMode(Gpio2, PinMode.Input); Console.WriteLine("Setting up events on GPIO2 for rising and falling"); gpioController.RegisterCallbackForPinValueChangedEvent(Gpio2, PinEventTypes.Falling | PinEventTypes.Rising, MyCallback); Console.WriteLine("Event setup, press a key to remove the falling event"); while (!Console.KeyAvailable) { // Nothing to do Thread.Sleep(100); } Console.ReadKey(); gpioController.UnregisterCallbackForPinValueChangedEvent(Gpio2, MyCallback); gpioController.RegisterCallbackForPinValueChangedEvent(Gpio2, PinEventTypes.Rising, MyCallback); Console.WriteLine("Now only waiting for rising events, press a key to remove all events and quit"); while (!Console.KeyAvailable) { // Nothing to do Thread.Sleep(100); } Console.ReadKey(); gpioController.UnregisterCallbackForPinValueChangedEvent(Gpio2, MyCallback); gpioController.Dispose(); }
public static void TestSpi(ArduinoBoard board) { const double vssValue = 5; // Set this to the supply voltage of the arduino. Most boards have 5V, some newer ones run at 3.3V. SpiConnectionSettings settings = new SpiConnectionSettings(0, 10); using (var spi = board.CreateSpiDevice(settings)) using (Mcp3008 mcp = new Mcp3008(spi)) { Console.WriteLine("SPI Device open"); while (!Console.KeyAvailable) { double vdd = mcp.Read(5); double vss = mcp.Read(6); double middle = mcp.Read(7); Console.WriteLine($"Raw values: VSS {vss} VDD {vdd} Average {middle}"); vdd = vssValue * vdd / 1024; vss = vssValue * vss / 1024; middle = vssValue * middle / 1024; Console.WriteLine($"Converted values: VSS {vss:F2}V, VDD {vdd:F2}V, Average {middle:F2}V"); Thread.Sleep(200); } } Console.ReadKey(); }
private static void TestPwm(ArduinoBoard board) { int pin = 6; using (var pwm = board.CreatePwmChannel(0, pin, 100, 0)) { Console.WriteLine("Now dimming LED. Press any key to exit"); while (!Console.KeyAvailable) { pwm.Start(); for (double fadeValue = 0; fadeValue <= 1.0; fadeValue += 0.05) { // sets the value (range from 0 to 255): pwm.DutyCycle = fadeValue; // wait for 30 milliseconds to see the dimming effect Thread.Sleep(30); } // fade out from max to min in increments of 5 points: for (double fadeValue = 1.0; fadeValue >= 0; fadeValue -= 0.05) { // sets the value (range from 0 to 255): pwm.DutyCycle = fadeValue; // wait for 30 milliseconds to see the dimming effect Thread.Sleep(30); } } Console.ReadKey(); pwm.Stop(); } }
public static void TestEventsDirectWait(ArduinoBoard board) { const int Gpio2 = 2; var gpioController = board.CreateGpioController(); // Opening GPIO2 gpioController.OpenPin(Gpio2); gpioController.SetPinMode(Gpio2, PinMode.Input); Console.WriteLine("Waiting for both falling and rising events"); while (!Console.KeyAvailable) { var res = gpioController.WaitForEvent(Gpio2, PinEventTypes.Falling | PinEventTypes.Rising, new TimeSpan(0, 0, 0, 0, 50)); if ((!res.TimedOut) && (res.EventTypes != PinEventTypes.None)) { Console.WriteLine($"Event on GPIO {Gpio2}, event type: {res.EventTypes}"); } } Console.ReadKey(); Console.WriteLine("Waiting for only rising events"); while (!Console.KeyAvailable) { var res = gpioController.WaitForEvent(Gpio2, PinEventTypes.Rising, new TimeSpan(0, 0, 0, 0, 50)); if ((!res.TimedOut) && (res.EventTypes != PinEventTypes.None)) { MyCallback(gpioController, new PinValueChangedEventArgs(res.EventTypes, Gpio2)); } } gpioController.Dispose(); }
public void TestStreamIsReadWrite() { _streamMock = new Mock <Stream>(); _streamMock.Setup(x => x.CanRead).Returns(true); _streamMock.Setup(x => x.CanWrite).Returns(false); var board = new ArduinoBoard(_streamMock.Object); Assert.Throws <NotSupportedException>(() => board.FirmataVersion); }
public static void TestDht(ArduinoBoard board) { Console.WriteLine("Reading DHT11. Any key to quit."); while (!Console.KeyAvailable) { if (board.TryReadDht(3, 11, out var temperature, out var humidity)) { Console.WriteLine($"Temperature: {temperature}, Humidity {humidity}"); }
public static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: Arduino.sample <PortName>"); Console.WriteLine("i.e.: Arduino.sample COM4"); return; } string portName = args[0]; var loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); }); // Statically register our factory. Note that this must be done before instantiation of any class that wants to use logging. LogDispatcher.LoggerFactory = loggerFactory; using (var port = new SerialPort(portName, 115200)) { Console.WriteLine($"Connecting to Arduino on {portName}"); try { port.Open(); } catch (UnauthorizedAccessException x) { Console.WriteLine($"Could not open COM port: {x.Message} Possible reason: Arduino IDE connected or serial console open"); return; } ArduinoBoard board = new ArduinoBoard(port.BaseStream); try { // This implicitly connects Console.WriteLine($"Connecting... Firmware version: {board.FirmwareVersion}, Builder: {board.FirmwareName}"); while (Menu(board)) { } } catch (TimeoutException x) { Console.WriteLine($"No answer from board: {x.Message} "); } finally { port.Close(); board?.Dispose(); } } }
public void InitializeWithStreamNoConnection() { var streamMock = new Mock <Stream>(MockBehavior.Strict); streamMock.Setup(x => x.WriteByte(255)); streamMock.Setup(x => x.WriteByte(249)); streamMock.Setup(x => x.Flush()); streamMock.Setup(x => x.CanRead).Returns(true); streamMock.Setup(x => x.CanWrite).Returns(true); streamMock.Setup(x => x.Close()); var board = new ArduinoBoard(streamMock.Object); Assert.Throws <TimeoutException>(() => board.FirmataVersion); }
public CharacterDisplay(ArduinoBoard board) { _controller = board.CreateGpioController(); _display = new Lcd1602(8, 9, new int[] { 4, 5, 6, 7 }, -1, 1.0f, -1, _controller); _display.BlinkingCursorVisible = false; _display.UnderlineCursorVisible = false; _display.Clear(); _textController = new LcdConsole(_display, "SplC780", false); _textController.Clear(); LcdCharacterEncodingFactory f = new LcdCharacterEncodingFactory(); var cultureEncoding = f.Create(CultureInfo.CurrentCulture, "SplC780", '?', _display.NumberOfCustomCharactersSupported); _textController.LoadEncoding(cultureEncoding); }
private static int GetFirstAnalogPin(ArduinoBoard board) { int analogPin = 14; foreach (var pin in board.SupportedPinConfigurations) { if (pin.AnalogPinNumber == 0) { analogPin = pin.Pin; break; } } return(analogPin); }
public static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: Arduino.sample <PortName>"); Console.WriteLine("i.e.: Arduino.sample COM4"); return; } string portName = args[0]; using (var port = new SerialPort(portName, 115200)) { Console.WriteLine($"Connecting to Arduino on {portName}"); try { port.Open(); } catch (UnauthorizedAccessException x) { Console.WriteLine($"Could not open COM port: {x.Message} Possible reason: Arduino IDE connected or serial console open"); return; } ArduinoBoard board = new ArduinoBoard(port.BaseStream); try { board.LogMessages += BoardOnLogMessages; // This implicitly connects Console.WriteLine($"Connecting... Firmware version: {board.FirmwareVersion}, Builder: {board.FirmwareName}"); while (Menu(board)) { } } catch (TimeoutException x) { Console.WriteLine($"No answer from board: {x.Message} "); } finally { port.Close(); board?.Dispose(); } } }
public static void TestDht(ArduinoBoard board) { Console.WriteLine("Reading DHT11. Any key to quit."); DhtSensor?handler = board.GetCommandHandler <DhtSensor>(); if (handler == null) { Console.WriteLine("DHT Command handler not available."); return; } while (!Console.KeyAvailable) { // Read from DHT11 at pin 3 if (handler.TryReadDht(3, 11, out var temperature, out var humidity)) { Console.WriteLine($"Temperature: {temperature}, Humidity {humidity}"); }
private static void TestFrequency(ArduinoBoard board) { Console.Write("Which pin number to use? "); string?input = Console.ReadLine(); if (input == null) { return; } if (!int.TryParse(input, out int pin)) { return; } FrequencySensor?sensor = board.GetCommandHandler <FrequencySensor>(); if (sensor == null) { Console.WriteLine("Frequency handling software module missing"); return; } try { sensor.EnableFrequencyReporting(pin, FrequencyMode.Rising, 500); while (!Console.KeyAvailable) { var f = sensor.GetMeasuredFrequency(); Console.Write($"\rFrequency at GPIO{pin}: {f} "); Thread.Sleep(100); } } finally { sensor.DisableFrequencyReporting(pin); } Console.ReadKey(true); Console.WriteLine(); }
private static void ScanDeviceAddressesOnI2cBus(ArduinoBoard board) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(" 0 1 2 3 4 5 6 7 8 9 a b c d e f"); stringBuilder.Append(Environment.NewLine); for (int startingRowAddress = 0; startingRowAddress < 128; startingRowAddress += 16) { stringBuilder.Append($"{startingRowAddress:x2}: "); // Beginning of row. for (int rowAddress = 0; rowAddress < 16; rowAddress++) { int deviceAddress = startingRowAddress + rowAddress; // Skip the unwanted addresses. if (deviceAddress < 0x3 || deviceAddress > 0x77) { stringBuilder.Append(" "); continue; } var connectionSettings = new I2cConnectionSettings(0, deviceAddress); using (var i2cDevice = board.CreateI2cDevice(connectionSettings)) { try { i2cDevice.ReadByte(); // Only checking if device is present. stringBuilder.Append($"{deviceAddress:x2} "); } catch { stringBuilder.Append("-- "); } } } stringBuilder.Append(Environment.NewLine); } Console.WriteLine(stringBuilder.ToString()); }
public FirmataTestFixture() { try { var loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole().AddProvider(new DebuggerOutputLoggerProvider()); }); // Statically register our factory. Note that this must be done before instantiation of any class that wants to use logging. LogDispatcher.LoggerFactory = loggerFactory; _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.Connect(IPAddress.Loopback, 27016); _socket.NoDelay = true; _networkStream = new NetworkStream(_socket, true); Board = new ArduinoBoard(_networkStream); if (!(Board.FirmataVersion > new Version(1, 0))) { // Actually not expecting to get here (but the above will throw a SocketException if the remote end is not there) throw new NotSupportedException("Very old firmware found"); } return; } catch (SocketException) { Console.WriteLine("Unable to connect to simulator, trying hardware..."); } if (!ArduinoBoard.TryFindBoard(SerialPort.GetPortNames(), new List <int>() { 115200 }, out var board)) { Board = null; return; } Board = board; }
/// <summary> /// Main entry point /// </summary> /// <param name="args">The first argument gives the Port name. Default "COM4"</param> public static void Main(string[] args) { string portName = "COM4"; if (args.Length > 0) { portName = args[0]; } using (var port = new SerialPort(portName, 115200)) { Console.WriteLine($"Connecting to Arduino on {portName}"); try { port.Open(); } catch (UnauthorizedAccessException x) { Console.WriteLine($"Could not open COM port: {x.Message} Possible reason: Arduino IDE connected or serial console open"); return; } ArduinoBoard board = new ArduinoBoard(port.BaseStream); try { board.LogMessages += BoardOnLogMessages; Console.WriteLine($"Firmware version: {board.FirmwareVersion}, Builder: {board.FirmwareName}"); DisplayModes(board); } catch (TimeoutException x) { Console.WriteLine($"No answer from board: {x.Message} "); } finally { port.Close(); board?.Dispose(); } } }
public static void TestInput(ArduinoBoard board) { const int gpio = 2; var gpioController = board.CreateGpioController(); // Opening GPIO2 gpioController.OpenPin(gpio); gpioController.SetPinMode(gpio, PinMode.Input); if (gpioController.GetPinMode(gpio) != PinMode.Input) { throw new InvalidOperationException("Couldn't set pin mode"); } Console.WriteLine("Polling input pin 2"); var lastState = gpioController.Read(gpio); while (!Console.KeyAvailable) { var newState = gpioController.Read(gpio); if (newState != lastState) { if (newState == PinValue.High) { Console.WriteLine("Button pressed"); } else { Console.WriteLine("Button released"); } } lastState = newState; Thread.Sleep(10); } Console.ReadKey(); gpioController.Dispose(); }
private static void ConnectWithStream(Stream stream) { ArduinoBoard board = new ArduinoBoard(stream); try { Console.WriteLine( $"Connection successful. Firmware version: {board.FirmwareVersion}, Builder: {board.FirmwareName}"); while (Menu(board)) { } } catch (TimeoutException x) { Console.WriteLine($"No answer from board: {x.Message} "); } finally { stream.Close(); board?.Dispose(); } }
public static void TestGpio(ArduinoBoard board) { // Use Pin 6 const int gpio = 6; var gpioController = board.CreateGpioController(); // Opening GPIO2 gpioController.OpenPin(gpio); gpioController.SetPinMode(gpio, PinMode.Output); Console.WriteLine("Blinking GPIO6"); while (!Console.KeyAvailable) { gpioController.Write(gpio, PinValue.High); Thread.Sleep(500); gpioController.Write(gpio, PinValue.Low); Thread.Sleep(500); } Console.ReadKey(); gpioController.Dispose(); }
private static void TestI2c(ArduinoBoard board) { var device = board.CreateI2cDevice(new I2cConnectionSettings(0, Bmp280.DefaultI2cAddress)); var bmp = new Bmp280(device); bmp.StandbyTime = StandbyTime.Ms250; bmp.SetPowerMode(Bmx280PowerMode.Normal); Console.WriteLine("Device open"); while (!Console.KeyAvailable) { bmp.TryReadTemperature(out var temperature); bmp.TryReadPressure(out var pressure); Console.Write($"\rTemperature: {temperature.DegreesCelsius:F2}°C. Pressure {pressure.Hectopascals:F1} hPa "); Thread.Sleep(100); } bmp.Dispose(); device.Dispose(); Console.ReadKey(); Console.WriteLine(); }
public ArduinoBoard OpenArduino(string port) { if (_boards.ContainsKey(port)) { throw new ArgumentException("Port wurde schon hinzugefügt."); } SerialPort serialport = new SerialPort(port, 9600); serialport.Open(); ArduinoBoard board = new ArduinoBoard(port, serialport.BaseStream); board.Start(); _boards.Add(port, board); return(board); }
public FirmataTestFixture() { try { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.Connect(IPAddress.Loopback, 27016); _socket.NoDelay = true; _networkStream = new NetworkStream(_socket, true); Board = new ArduinoBoard(_networkStream); if (!(Board.FirmataVersion > new Version(1, 0))) { // Actually not expecting to get here (but the above will throw a SocketException if the remote end is not there) throw new NotSupportedException("Very old firmware found"); } Board.LogMessages += (x, y) => Console.WriteLine(x); return; } catch (SocketException) { Console.WriteLine("Unable to connect to simulator, trying hardware..."); } if (!ArduinoBoard.TryFindBoard(SerialPort.GetPortNames(), new List <int>() { 115200 }, out var board)) { Board = null; return; } Board = board; Board.LogMessages += (x, y) => Console.WriteLine(x); }
public static void DisplayModes(ArduinoBoard board) { const int Gpio2 = 2; const int MaxMode = 10; Length stationAltitude = Length.FromMeters(650); int mode = 0; var gpioController = board.CreateGpioController(); gpioController.OpenPin(Gpio2); gpioController.SetPinMode(Gpio2, PinMode.Input); CharacterDisplay disp = new CharacterDisplay(board); Console.WriteLine("Display output test"); Console.WriteLine("The button on GPIO 2 changes modes"); Console.WriteLine("Press x to exit"); disp.Output.ScrollUpDelay = TimeSpan.FromMilliseconds(500); AutoResetEvent buttonClicked = new AutoResetEvent(false); void ChangeMode(object sender, PinValueChangedEventArgs pinValueChangedEventArgs) { mode++; if (mode > MaxMode) { // Don't change back to 0 mode = 1; } buttonClicked.Set(); } gpioController.RegisterCallbackForPinValueChangedEvent(Gpio2, PinEventTypes.Falling, ChangeMode); var device = board.CreateI2cDevice(new I2cConnectionSettings(0, Bmp280.DefaultI2cAddress)); Bmp280?bmp; try { bmp = new Bmp280(device); bmp.StandbyTime = StandbyTime.Ms250; bmp.SetPowerMode(Bmx280PowerMode.Normal); } catch (IOException) { bmp = null; Console.WriteLine("BMP280 not available"); } OpenHardwareMonitor hardwareMonitor = new OpenHardwareMonitor(); hardwareMonitor.EnableDerivedSensors(); TimeSpan sleeptime = TimeSpan.FromMilliseconds(500); string modeName = string.Empty; string previousModeName = string.Empty; int firstCharInText = 0; while (true) { if (Console.KeyAvailable && Console.ReadKey(true).KeyChar == 'x') { break; } // Default sleeptime = TimeSpan.FromMilliseconds(500); switch (mode) { case 0: modeName = "Display ready"; disp.Output.ReplaceLine(1, "Button for mode"); // Just text break; case 1: { modeName = "Time"; disp.Output.ReplaceLine(1, DateTime.Now.ToLongTimeString()); sleeptime = TimeSpan.FromMilliseconds(200); break; } case 2: { modeName = "Date"; disp.Output.ReplaceLine(1, DateTime.Now.ToShortDateString()); break; } case 3: modeName = "Temperature / Barometric Pressure"; if (bmp != null && bmp.TryReadTemperature(out Temperature temp) && bmp.TryReadPressure(out Pressure p2)) { Pressure p3 = WeatherHelper.CalculateBarometricPressure(p2, temp, stationAltitude); disp.Output.ReplaceLine(1, string.Format(CultureInfo.CurrentCulture, "{0:s1} {1:s1}", temp, p3)); }
public void Close(ArduinoBoard board) { board.Close(); _boards.Remove(board.Port); }
private static bool Menu(ArduinoBoard board) { Console.WriteLine("Hello I2C and GPIO on Arduino!"); Console.WriteLine("Select the test you want to run:"); Console.WriteLine(" 1 Run I2C tests with a BMP280"); Console.WriteLine(" 2 Run GPIO tests with a simple led blinking on GPIO6 port"); Console.WriteLine(" 3 Run polling button test on GPIO2"); Console.WriteLine(" 4 Run event wait test event on GPIO2 on Falling and Rising"); Console.WriteLine(" 5 Run callback event test on GPIO2"); Console.WriteLine(" 6 Run PWM test with a LED dimming on GPIO6 port"); Console.WriteLine(" 7 Blink the LED according to the input on A1"); Console.WriteLine(" 8 Read analog channel as fast as possible"); Console.WriteLine(" 9 Run SPI tests with an MCP3008 (experimental)"); Console.WriteLine(" 0 Detect all devices on the I2C bus"); Console.WriteLine(" H Read DHT11 Humidity sensor on GPIO 3 (experimental)"); Console.WriteLine(" X Exit"); var key = Console.ReadKey(); Console.WriteLine(); switch (key.KeyChar) { case '1': TestI2c(board); break; case '2': TestGpio(board); break; case '3': TestInput(board); break; case '4': TestEventsDirectWait(board); break; case '5': TestEventsCallback(board); break; case '6': TestPwm(board); break; case '7': TestAnalogIn(board); break; case '8': TestAnalogCallback(board); break; case '9': TestSpi(board); break; case '0': ScanDeviceAddressesOnI2cBus(board); break; case 'h': case 'H': TestDht(board); break; case 'x': case 'X': return(false); } return(true); }
public ApiBehaviorTests() { _streamMock = new Mock <Stream>(); _board = new ArduinoBoard(_streamMock.Object); }