Project updated to V1.0 Release Candidate 1 (October 23th, 2022)
In this introductory project we're going to learn how simple is to get temperature data from a LM35 analog sensor on a Meadow board with a MAUI app using Bluetooth!
Meadow.Foundation is a platform for quickly and easily building connected things using.NET on Meadow. Created by Wilderness Labs, it's completely open source and maintained by the Wilderness Labs community.
If you're new working with Meadow, I suggest you go to the Getting Started w/ Meadow by Controlling the Onboard RGB LED project to properly set up your development environment, including flashing your board to the latest version of Meadow.OS.
Step 1 - Assemble the circuitWire your project like this:
Create a new Meadow Application project in Visual Studio 2019 for Windows or macOS and name it MeadowBleTemperature.
Step 3 - Write the code for MeadowBleLedCopy the following code below:
TemperatureController.cs
public class TemperatureController
{
private static readonly Lazy<TemperatureController> instance =
new Lazy<TemperatureController>(() => new TemperatureController());
public static TemperatureController Instance => instance.Value;
public event EventHandler<Temperature> TemperatureUpdated = delegate { };
AnalogTemperature analogTemperature;
private TemperatureController()
{
Initialize();
}
private void Initialize()
{
analogTemperature = new AnalogTemperature(MeadowApp.Device,
MeadowApp.Device.Pins.A01, AnalogTemperature.KnownSensorType.LM35);
analogTemperature.TemperatureUpdated += AnalogTemperatureUpdated;
}
void AnalogTemperatureUpdated(object sender, Meadow.IChangeResult<Temperature> e)
{
TemperatureUpdated.Invoke(this, e.New);
}
public void StartUpdating(TimeSpan timeSpan)
{
analogTemperature.StartUpdating(timeSpan);
}
}
This singleton class encapsulates the temperature sensor driver and uses its built-in monitoring feature calling analogTemperature.StartUpdating(timeSpan);
to internally perform a reading every given time, and will trigger the analogTemperature.TemperatureUpdated
event, which fires a delegate event to wherever is registered to (in this project, in the main MeadowApp class).
MeadowApp.cs
// public class MeadowApp : App<F7FeatherV1> <- If you have a Meadow F7v1.*
public class MeadowApp : App<F7FeatherV2>
{
readonly string TEMPERATURE = "e78f7b5e-842b-4b99-94e3-7401bf72b870";
IDefinition bleTreeDefinition;
ICharacteristic temperatureCharacteristic;
public override Task Initialize()
{
var onboardLed = new RgbPwmLed(
device: Device,
redPwmPin: Device.Pins.OnboardLedRed,
greenPwmPin: Device.Pins.OnboardLedGreen,
bluePwmPin: Device.Pins.OnboardLedBlue);
onboardLed.SetColor(Color.Red);
TemperatureController.Instance.StartUpdating(TimeSpan.FromSeconds(5));
bleTreeDefinition = GetDefinition();
TemperatureController.Instance.TemperatureUpdated += TemperatureUpdated;
Device.BluetoothAdapter.StartBluetoothServer(bleTreeDefinition);
onboardLed.SetColor(Color.Green);
return base.Initialize();
}
private void TemperatureUpdated(object sender, Meadow.Units.Temperature e)
{
temperatureCharacteristic.SetValue($"{e.Celsius:N2}°C;");
}
Definition GetDefinition()
{
temperatureCharacteristic = new CharacteristicString(
name: "Temperature",
uuid: TEMPERATURE,
maxLength: 20,
permissions: CharacteristicPermission.Read,
properties: CharacteristicProperty.Read);
var service = new Service(
name: "ServiceA",
uuid: 253,
temperatureCharacteristic
);
return new Definition("MeadowTemperature", service);
}
}
In the Initialize
method:
- Meadow's onboard RGB LED turns on Red to inficate the app has started.
- Call
TemperatureController's
StartUpdating
method to perform a reading every five seconds, and register theTemperatureUpdated
event handler to update the bluetooth's temperature characteristic with the latest reading. - Activate Meadow's Bluetooth capabilities by first setting up its Definition configuration, which in this project is a
CharacteristicString
that will store the latest Temperature readings, constantly being updated in theTemperatureUpdated
event handler. - Start Bluetooth server passing the BLE definition object
- Turn the onboard RGB LED to green to indicate the app has finished initializing successfully.
As we mentioned, in this project we included a MAUI ap that runs on iOS and Android.
The basic things we need to understand here are:
If you check their official GitHub docs, you'll see how to add the required permissions in the Android's manifest file and iOS's info.plist file, how to scan for devices and handle the event of discovered devices.
If you check the BaseViewModel class, in the AdapterDeviceDiscovered event handler we have:
void AdapterDeviceDiscovered(object sender,
Plugin.BLE.Abstractions.EventArgs.DeviceEventArgs e)
{
if (DeviceList.FirstOrDefault(x => x.Name == e.Device.Name) == null &&
!string.IsNullOrEmpty(e.Device.Name))
{
DeviceList.Add(e.Device);
}
if (e != null &&
e.Device != null &&
!string.IsNullOrEmpty(e.Device.Name) &&
e.Device.Name.Contains("Meadow"))
{
await adapter.StopScanningForDevicesAsync();
IsDeviceListEmpty = false;
DeviceSelected = e.Device;
}
}
In every device discovered, if its named Meadow, it'll be set as DeviceSelected, which you'll see it selected automatically in the device Picker.
Connecting/Disconnecting to Meadow
Once MeadowRGB is selected, you can now tap on the connect/disconnect toggle button on the right next to the search for devices button.
async Task ToggleConnection()
{
try
{
if (IsConnected)
{
await adapter.DisconnectDeviceAsync(DeviceSelected);
IsConnected = false;
}
else
{
await adapter.ConnectToDeviceAsync(DeviceSelected);
IsConnected = true;
}
}
catch (DeviceConnectionException ex)
{
Debug.WriteLine(ex.Message);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
Once connected to the Meadow board, IsConnected
property becomes true
, and you'll see the connected icon, and the Set Color and Turn On/Off buttons are enabled.
When running both the MAUIapp and Meadow app, once connected successfully, you should be able to change the color on the RGB LED by selecting it from the wheel color, or turn it on and off. It should look like to the following GIF:
This project is only the tip of the iceberg in terms of the extensive exciting things you can do with Meadow.Foundation.
- It comes with a huge peripheral driver library with drivers for the most common sensors and peripherals.
- The peripheral drivers encapsulate the core logic and expose a simple, clean, modern API.
- This project is backed by a growing community that is constantly working on building cool connected things and are always excited to help new-comers and discuss new projects.
Comments