The Arduino is accessed using Firmata. To do that, we use the Windows.Devices.Enumeration, Microsoft.Maker.RemoteWiring, and Microsoft.Maker.Serial namespaces, available in the Windows-Remote-Arduino NuGet. We begin by enumerating all the devices it finds:
DeviceInformationCollection Devices =
await UsbSerial.listAvailableDevicesAsync();
foreach (DeviceInformationDeviceInfo in Devices)
{
If our Arduino device is found, we will have to connect to it using USB:
if (DeviceInfo.IsEnabled&&DeviceInfo.Name.StartsWith("Arduino"))
{
Log.Informational("Connecting to " + DeviceInfo.Name);
this.arduinoUsb = new UsbSerial(DeviceInfo);
this.arduinoUsb.ConnectionEstablished += () =>
Log.Informational("USB connection established.");
Attach a remote device to the USB port class:
this.arduino = new RemoteDevice(this.arduinoUsb);
We need to initialize our hardware, when the remote device is ready:
this.arduino.DeviceReady += () =>
{
Log.Informational("Device ready.");
this.arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED.
this.arduino.digitalWrite(13, PinState.HIGH);
this.arduino.pinMode(8, PinMode.INPUT); // PIR sensor.
MainPage.Instance.DigitalPinUpdated(8,
this.arduino.digitalRead(8));
this.arduino.pinMode(9, PinMode.OUTPUT); // Relay.
this.arduino.digitalWrite(9, 0); // Relay set to 0
this.arduino.pinMode("A0", PinMode.ANALOG); // Light sensor.
MainPage.Instance.AnalogPinUpdated("A0",
this.arduino.analogRead("A0"));
};
Important: the analog input must be set to PinMode.ANALOG, not PinMode.INPUT. The latter is for digital pins. If used for analog pins, the Arduino board and Firmata firmware may become unpredictable.
Our inputs are then reported automatically by the Firmata firmware. All we need to do to read the corresponding values is to assign the appropriate event handlers. In our case, we forward the values to our main page, for display:
this.arduino.AnalogPinUpdated += (pin, value) =>
{
MainPage.Instance.AnalogPinUpdated(pin, value);
};
this.arduino.DigitalPinUpdated += (pin, value) =>
{
MainPage.Instance.DigitalPinUpdated(pin, value);
};
Communication is now set up. If you want, you can trap communication errors, by providing event handlers for the ConnectionFailed and ConnectionLost events. All we need to do now is to initiate communication. We do this with a simple call:
this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);