In the previous blog, I showed how to get all the dependencies required to be able to use Mbed with the Arduino IDE (if you haven’t read that yet, click here). In this blog I will be showing how to get into programming with a few examples. Let’s get started!
Simple Blink Example
FIrst, let’s rewrite the the Blink example (which could be called the “Hello World” of Arduino programming) using Mbed functions instead of the regular Arduino functions. For reference, here is the regular Blink example-
Start by opening a new sketch and including the Mbed library. Then type in the following code before the setup, which creates an object of the DigitalOut class to control the state of pin LED1. I have named it led but you can use any valid identifier name. LED1 refers to the pin name of the built in led of your Arduino (pin 13 in this case). A list of all the pin numbers and their corresponding Mbed pin names is given at the end of this blog for reference.
Next, enter the following code in the loop, which sets the state of led to 1 (or HIGH), waits for 1 second, sets it to 0 (or LOW), then waiting for another second, with everything repeating indefinitely. Setup will kept empty as its purpose has already been served.
The completed code should now look like this-
Finally, compile and upload the code. You should start to see the built in LED of your Arduino blink. You can even try playing around with the wait values to really make sure it is working. You’re done!
In this example, we will spawn two threads which can perform multiple tasks simultaneously, giving the illusion of multitasking.
Once again, start by including the Mbed library and the Mbed namespace, but this time also include the rtos namespace, under which the thread class and all its functions are present. Now, create two threads as shown-
I have named the threads t1 and t2, however you can use any valid identifier name. These threads will require code to execute, so create two functions to pass to them. I have named the functions func1 and func2. However, remember that these functions must require any parameter or return any value.
In the above example, the func1 and func2 print “A” and “B” and wait for 2 and 3 seconds respectively. To make them work indefinitely, while(1) loops have been used.
Finally, in the setup, begin Serial communication and start the threads by passing them the functions as parameters. Void loop can be kept empty as the two threads are already present to execute code.
Here is how the completed code should look-
Now, compile and upload the program and open the Serial monitor. You should see the letters A and B being printed onto the Serial monitor asynchronously.
And that’s it, you’re all done!
Here are the pins mappings from Arduino to Mbed-
|Arduino Pins||Corresponding Mbed name|
|D0/TX||P1_3 (not recommended for use)|
|D1/RX||P1_10 (not recommended for use)|
|D13/Built in LED||P0_13|