You are on page 1of 93

ARM Mbed for STM32

Training #1
Rawat Siripokarpirom
KMUTNB
E-mail: rawat.s @eng.kmutnb.ac.th
12 / 01 / 2018
Outline

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• Introduction to ARM Mbed and STM32 Nucleo Boards
• First Example: LED Blink
IoT Engineering Education

• With Web-based Simulator


• With Online Mbed Compiler + ST-Link Utility + Nucleo Board
• Digital Input / Output / InOut (single-bit and multi-bit)
• LED / Buzzer (Output), Push Button (Input), RGB LED (multi-bit output)
• Ultrasonic Distance Sensor
• PWM Output: PWM-based LED Dimming
1
Outline (Cont’d)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• Analog Input & Output with ADC and DAC
• Analog Sensor Reading:
IoT Engineering Education

• Voltage-controlled LED Dimming


• External Interrupt Handling
• Rotary Encoder Switch
• Timers
• Timer-based Periodic Task Execution
• Low Power Operation with sleep mode
2
Outline (Cont’d)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• Sensor / Display Module Interfacing Demo
• BH1750 Light Sensor (I2C)
IoT Engineering Education

• DHT22 Temperature & Relative Humidity Sensor (GPIO)


• LCD16x2 + I2C Adapter
• Developing Your Own C++ Libraries for Reuse
• Wrap-Up & Discussion

3
Objectives

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• To explore the software development tools and the Mbed OS
provided by ARM Mbed, targeting at the STM32 MCUs and boards.
IoT Engineering Education

• To compare the ARM Mbed APIs with the Arduino APIs.


• To investigate how to use STM32-based MCU boards as alternatives
to Arduino boards.

4
IoT Engineering Education

https://www.mbed.com/en/

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


What is Mbed IoT Platform?

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• It is an online platform (www.mbed.org) for developing Internet of
Things (IoT) and embedded devices, supported by ARM Ltd.
IoT Engineering Education

• It supports over 100 Mbed-enabled development boards.


• For example, low-cost STM32 Nucleo boards
• It provides online IDE and compilation tools for ARM-based MCUs.
• It provides an SDK, various libraries and examples.
• based on Mbed OS -- an open-source platform operating system.
• It has a large community of developers and supporters.
6
IoT Engineering Education

Mbed IoT Platform (Big Picture)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

ARM Mbed: Partners & Supporters (Partial List)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


Mbed-Enabled Boards

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


https://os.mbed.com/platforms/?mbed-enabled
IoT Engineering Education

In order to use the Mbed online tools,


you have to register and create a user
account (free).

9
STM32 Nucleo Boards (Mbed-enabled)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• A set of development boards with 32-bit ARM-Cortex-based MCUs
• URL: http://www.st.com/en/evaluation-tools/stm32-mcu-nucleo.html
IoT Engineering Education

• Three types available; classified by the number of MCU pins / sizes


• Boards: Nucleo-32, Nucleo-64, Nucleo-144
• With Arduino I/O Connectors & Interfacing
• Nucleo-64: Arduino Uno Rev3
• Nucleo-32: Arduino Nano connectors
• I/Os: 3.3V logic-level only !!!
Some digital I/O pins of the STM32 MCUs are 5V tolerant. Read the datasheets carefully.
10
Types: STM32 Nucleo Boards

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Flash (Program) Size

Increasing Pin Count


& Board Size

http://www.st.com/en/evaluation-tools/stm32-mcu-nucleo.html 11
Nucleo F401RE Board

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• MCU: STM32F401RET6 (ARM 32-bit Cortex-M4 CPU with FPU, 84 MHz, 512 KB Flash, 96 KB SRAM)
• On-board debugger/programmer: ST-LINK/V2-1 with SWD connector ST-LINK/V2-1
• Connectors
IoT Engineering Education

• Arduino Uno Revision 3 connectivity


• STMicroelectronics “Morpho extension” pin headers
• User LED (LD2 pin)
• Two push buttons: USER and RESET (active-low)
• USB connector: Mini-USB
• Board power supply
• USB VBUS (5V)
• External source (3.3 V, 5V, 7-12V)
• https://os.mbed.com/platforms/ST-Nucleo-F401RE/

12
Nucleo F401RE Board: Connectors

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

https://www.mbed.com/en/platform/hardware/boards/st/nucleo_f401re/ 13
Nucleo F401RE Board: Connector (Top-Left Side)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


https://os.mbed.com/platforms/ST-Nucleo-F401RE/
IoT Engineering Education

14
Nucleo F401RE Board: Connector (Top-Right Side)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


https://os.mbed.com/platforms/ST-Nucleo-F401RE/
IoT Engineering Education

Nucleo F401RE (STM32F401RET6)


PA_5 (STM32 Pin) = D13 (Arduino Pin)

15
Nucleo L053R8 (with STM32L053R8T6 MCU)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


STM32L053R8T6 (LQFP64 package)
• CPU: ARM32-bit Cortex-M0+
• Flash: 64 KB
• SRAM: 8 KB
IoT Engineering Education

• CPU frequency: 32 MHz max


• VDD: from 1.65 V to 3.6 V (3.3V typ.)
• GPIO (51) with external interrupt capability
• 12-bit ADC with 16 channels
• 12-bit DAC with 1 channel
• RTC
• Timers (5)
• I2C (2)
• USART (3)
• SPI (2)
• USB 2.0 full-speed

16
Nucleo L053R8 Board: Connectors

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

https://mbed.org/media/platforms/ST-Nucleo-L053R8-Arduino.png 17
Nucleo L432KC Board: Connectors

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


https://os.mbed.com/platforms/ST-Nucleo-L432KC/
IoT Engineering Education

18
ARM Mbed OS Simulator

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


Select
Demo
Example
IoT Engineering Education

http://ec2-52-211-146-247.eu-west-1.compute.amazonaws.com:7829/
19
Two-LED Blinking

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

1. Click “Add Component” and add


new LEDs (one by one); select pins
“p5” and “p6” for the red LED and
the blue LED respectively.
2. Edit the code and press ‘Run’

20
Two-LED Blinking : Demo Code (ARM Mbed Style)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

DigitalOut redLed(p5);
DigitalOut blueLed(p6);
IoT Engineering Education

int main() {
redLed = 0; // Red LED off
blueLed = 1; // Blue LED on
wait_ms(100);
printf( "Toggle two LEDs\n" );
while (1) {
redLed = !redLed;
blueLed = !blueLed;
wait_ms(100);
}
}

21
Two-LED Blinking : Demo Code (Arduino Style)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "Arduino.h"

#define RED_LED_PIN D5
#define BLUE_LED_PIN D6
IoT Engineering Education

void setup() {
pinMode( RED_LED_PIN, OUTPUT );
pinMode( BLUE_LED_PIN, OUTPUT );
digitalWrite( RED_LED_PIN, 0 ); // Red LED off
digitalWrite( BLUE_LED_PIN, 1 ); // Blue LED on
delay( 100 );
Serial.begin( 115200 );
Serial.print( "Toggle two LEDs\n" );
}
void loop() {
digitalWrite( RED_LED_PIN, !digitalRead( RED_LED_PIN ) );
digitalWrite( BLUE_LED_PIN, !digitalRead( BLUE_LED_PIN ) );
delay( 100 ); // delay in msec
}
22
Two-LED Blinking : Demo Code (Arduino C++ Style)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "Arduino.h"
#include "DigitalOut.h"

#define wait_ms(dly) delay(dly)


IoT Engineering Education

DigitalOut redLed( D5 );
DigitalOut blueLed( D6 );

void setup() {
redLed = 0; // turn off the Red LED
blueLed = 1; // turn on the Blue LED
wait_ms( 100 );
Serial.begin( 115200 );
Serial.printf( "Toggle two LEDs\n" );
}
void loop() {
redLed = !redLed; // toggle the Red LED pin
blueLed = !blueLed; // toggle the Blue LED pin
wait_ms( 100 ); // delay in msec
}
23
Write Your Own C++ Class (DigitalOut.h) for Arduino

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


class DigitalOut {
public:
DigitalOut( int pin ) : _pin(pin) { pinMode( _pin, OUTPUT ); }
inline void write( int value ) { digitalWrite( _pin, _value=value ); }
IoT Engineering Education

inline int read() { return _value; }


inline operator int() { return this->read(); }
inline DigitalOut& operator=( DigitalOut& rhs ) {
this->write( rhs.read() );
return *this;
}
inline DigitalOut& operator=(int value) {
this->write( value );
return *this;
}

private:
int _pin, _value;
};

24
ARM Mbed Signup & Login

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

https://os.mbed.com/account/login/?next=/platforms/
25
IoT Engineering Education

Step 1) Select the Target Board

26

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


Step 2) Add the Selected Board to your Mbed Compiler

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Platform: “NUCLEO-L053R8”

27
IoT Engineering Education

Step 3) Open Mbed Compiler (for the selected board)

28

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Step 4) Select Demo Example

29

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Step 5) Specify the Program Name

30

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Step 6) Open main.cpp

31

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Step 7) View / Edit / Modify main.cpp

32

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Step 8) Compile the Program

33

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Pin Names for Nucleo L053R8 Board

34

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


Steps to program the Nucleo board with a “.bin” file

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• Download and install STM32 ST Link Utility (for Windows).
• URL: http://www.st.com/en/development-tools/stsw-link004.html
IoT Engineering Education

• Connect and Detect the Nucleo Board:


• Connect the Nucleo board to the host computer (via USB cable).
• Make a connection between the ST Link Utility software and the Nucleo board.
• Program the Device:
• Select the “.bin” File and upload it to the Nucleo board.

35
IoT Engineering Education

Open ST Link Utility & Connect the Nucleo Board

36

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Successful Connection with Nucleo Board

37

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Load the .bin File into ST Link Utility

38

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Program the Target Board

39

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


Target Programming Done

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

If done correctly, you will see the on-board


LED blink slowly.

40
IoT Engineering Education

Mbed: Create an new & empty program

41

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Mbed: Import Library

42

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Mbed: Search the ‘mbed’ Library

43

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Mbed: Import the mbed library

44

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Mbed: Library Files & Structures

45

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Mbed: Create and Insert a new File for ‘main.cpp’

46

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Mbed: Edit ‘main.cpp’

47

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Mbed: Clone / Rename a Program

48

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


ARM Mbed Programming

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• Two Mbed OS (RTOS) Versions
• Mbed 2.x (Old)
IoT Engineering Education

• Mbed 5.x (New): The latest version is 5.7 (January 2018).


• Mbed OS Documents (latest version)
• https://os.mbed.com/docs/latest
• Mbed OS 5.7 Reference
• https://os.mbed.com/docs/v5.7/reference/index.html

49
Digital Input and Output Programming

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• C++ Classes (Drivers) for Digital I/Os
• Single-Bit:
IoT Engineering Education

• Pin-based: DigitalIn, DigitalOut, DigitalInOut


• Multi-Bit
• Port-based: PortIn, PortOut, PortInOut
• Bus-based: BusIn, BusOut, BusInOut

50
Digital Input and Output Programming

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• Single-Bit Pins
• DigitalIn: a digital input pin  Arduino’s digitalRead()
IoT Engineering Education

• https://os.mbed.com/docs/latest/reference/digitalin.html
• DigitalOut: a digital output pin  Arduino’s digitalWrite()
• https://os.mbed.com/docs/latest/reference/digitalout.html
• DigitalInOut: a digital inout pin
• https://os.mbed.com/docs/latest/reference/digitalinout.html

51
DigitalIn Reference

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

https://os.mbed.com/docs/latest/reference/digitalin.html

PullUp, PullDown,
PullNone, OpenDrain

52
DigitalOut Reference

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

https://os.mbed.com/docs/latest/reference/digitalout.html

53
DigitalIn/Out Example: Examples of logical operations

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

DigitalIn a(D0);
DigitalIn b(D1);
IoT Engineering Education

DigitalOut z_not(LED1);
DigitalOut z_and(LED2);
DigitalOut z_or(LED3);
DigitalOut z_xor(LED4);

int main() {
while(1) {
z_not = !a; // NOT
z_and = a && b; // AND
z_or = a || b; // OR
z_xor = a ^ b; // XOR
}
} https://os.mbed.com/docs/latest/reference/digitalin.html

54
Digital Input and Output Programming

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• Multi-Bit Bus-based Pins (up to 16 bits)
• BusIn: a digital multiple-bit input pins
IoT Engineering Education

• https://os.mbed.com/docs/latest/reference/busin.html
• BusOut: a digital multiple-bit output pins
• https://os.mbed.com/docs/latest/reference/busout.html
• BusInout: a digital multiple-bit inout pins
• https://os.mbed.com/docs/latest/reference/businout.html

55
Digital Input and Output Programming

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• Multi-Bit Port-based Pins (up to 16 bits)
• PortIn: a digital multiple-bit input pins
IoT Engineering Education

• https://os.mbed.com/docs/latest/reference/portin.html
• PortOut: a digital multiple-bit output pins
• https://os.mbed.com/docs/latest/reference/portout.html
• PortInout: a digital multiple-bit inout pins
• https://os.mbed.com/docs/latest/reference/portinout.html

The PortIn / PortOut / PortInOut classes are much less flexible but faster than the BusIn,
BusOut/ BusInOut classes; they are constrained by the port and bit layout of the
underlying GPIO ports.
56
Analog Input and Analog Output Programming

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• Analog Input Reading using ADC (12-bit resolution)
• AnalogIn: an analog input pin  Arduino’s analogRead()
• https://os.mbed.com/docs/latest/reference/analogin.html
IoT Engineering Education

• Analog Output Driving using DAC (12-bit resolution, if available)


• AnalogOut: an analog output pin
• https://os.mbed.com/docs/latest/reference/analogout.html
• PWM-based Output (Digital): similar to Arduino’s analogWrite()
• PwmOut: a hardware PWM output pin
• https://os.mbed.com/docs/latest/reference/pwmout.html

57
More Mbed Drivers

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


• Digital Input Pin with External Interrupt: InterruptIn
• Timers:
IoT Engineering Education

• TimeOut, Timer
• Ticker, LowPowerTicker
• Communications:
• Serial, RawSerial
• SPI, SPISlave
• I2C, I2CSlave

58
Mbed Coding Example 1 (LED Blink)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

const int DELAY_MS = 100; // delay in msec


IoT Engineering Education

DigitalOut led( PB_3 ); // specify the LED pin

int main() {
int state = 0;
while(1) { // endless loop
led = state; // update LED output
state ^= 1; // toggle state
wait_ms( DELAY_MS ); // delay in msec
}
}

59
Mbed Coding Example 2 (LED & Push Button)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

DigitalOut led( PB_3 ); // specify the LED pin


DigitalIn button( PB_4 ); // specify the button pin
IoT Engineering Education

int main() {
button.mode( PullUp ); // enable internal pullup on button pin
while (1) {
led = !button;
}
}

Note that:
1) The button is active-low; If the button is pressed, the input logic is 0, otherwise 1.
2) If the button is held down (pressed), the LED is ON.

60
IoT Engineering Education

Hardware Testing: LED + Push Button

Capacitor
LED
Push
Button

61

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


Mbed Coding Example 3 (External Interrupt) - Part 1

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

DigitalOut led( PB_3 ); // digital output pin


InterruptIn button( PB_4 ); // digital input pin with ext. interrupt enabled
IoT Engineering Education

volatile bool changed = false;

void irq_callback() {
button.disable_irq(); // disable the interrupt on the Button pin
changed = true;
}

// Code continues on the next page.

62
Mbed Coding Example 3 (External Interrupt) - Part 2

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


// Code continues from the previous page.

int main() {
button.fall( &irq_callback ); // detect falling-edge
IoT Engineering Education

button.mode( PullUp ); // enable internal pull-up resistor


button.enable_irq(); // enable interrupt
while(1) {
if ( changed ) {
led = !led; // toggle and update LED output
changed = false;
wait_ms(50);
button.enable_irq(); // re-enable the interrupt on the Button pin
}
wait_ms( 10 );
}
}
63
Mbed Coding Example 4 (PWM-based LED Dimming)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

PwmOut led( PB_3 ); // use a hardware-PWM pin


int value = 0; // used to store the PWM duty cycle between 0..100
IoT Engineering Education

int pm = 1; // count direction: 1 (up) or -1 (down)

int main() {
led.period_ms( 2.0 ); // period = 2 msec, freq = 500 Hz
led = 0.0f; // value between 0.0 to 1.0 (100% duty cycle)
while(1) {
if ( value == 255 && pm == 1 ) { pm = -1; } // change to decrement
else if ( value == 0 && pm == -1 ) { pm = 1; } // change to increment
led = (value/255.0f); // update the PWM output value
value += pm;
wait_ms( 5 );
}
}
64
Mbed Coding Example 5 (RGB LED with BusOut)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

BusOut rgb( PB_5, PB_4, PB_10 ); // Nucleo L053R8 D4, D5, D6


IoT Engineering Education

int main() {
uint8_t value = 1;
while(1) {
rgb = ~value; // invert the logic (for active-low LEDs) and write to output
// Rotate shift-left
value = ((value << 1) | (value >> 2)) & 0b111;
wait_ms(500);
}
}

65
IoT Engineering Education

Hardware Testing: RGB LED

anode)
RGB LED
(common-

66

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


Mbed Coding Example 6 (Timer-based Ticker)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

DigitalOut led1( PB_5 ), led2( PB_4 );


Ticker ticker1, ticker2;
IoT Engineering Education

void led1_toggle() { led1 = !led1; }


void led2_toggle() { led2 = !led2; }

int main() {
led1 = 0;
led2 = 0;
ticker1.attach( &led1_toggle, 0.1 ); // callback every 0.1 seconds
ticker2.attach( &led2_toggle, 0.5 ); // callback every 0.5 seconds
while(1) {
wait_ms(10);
}
}
67
Mbed Coding Example 7 (Rotary Encoder) - Part 1

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

// Nucleo L053R8: PB_5, PB_4 => D4, D5


#define QA_PIN PB_5
IoT Engineering Education

#define QB_PIN PB_4

Serial pc( SERIAL_TX, SERIAL_RX, 115200 );


InterruptIn qa_pin( QA_PIN );
DigitalIn qb_pin( QB_PIN );

volatile int last_a = 1, last_b = 1;


volatile bool encoder_update = false;
volatile int16_t encoder_cnt = 0;

// Code continues on the next page.

68
Mbed Coding Example 7 (Rotary Encoder) - Part 2

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


// Code continues from the previous page.

void encode_inputs() {
qa_pin.disable_irq();
IoT Engineering Education

int a = qa_pin.read();
int b = qb_pin.read();
if ( (a != last_a) || (b != last_b) ) {
if ( a == b ) { encoder_cnt++; }
else { encoder_cnt--; }
encoder_update = true;
last_a = a;
last_b = b;
}
qa_pin.enable_irq();
}

// Code continues on the next page.


69
Mbed Coding Example 7 (Rotary Encoder) - Part 3

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


// Code continues from the previous page.

int main() {
// qa_pin.mode( PullUp );
IoT Engineering Education

// qb_pin.mode( PullUp );
qa_pin.fall( &encode_inputs );
qa_pin.rise( &encode_inputs );
qa_pin.enable_irq();
pc.printf( "Rotary Encoder Reading Demo\r\n" );
while(1) {
if ( encoder_update ) {
encoder_update = false;
pc.printf( "Encoder Counter: %d\r\n", encoder_cnt );
}
}
}

70
IoT Engineering Education

Mbed Coding Example 7: Output Sample

71

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Hardware Testing: Rotary Encoder

72

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


Mbed Coding Example 8 (AnalogOut LED Dimming)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

const PinName AOUT_PIN = PA_4; // Nucleo L053R8: PA_4 / A2 pin !!!!


AnalogOut aout( AOUT_PIN );
IoT Engineering Education

int value = 0; // used to store the PWM duty cycle between 0..100
int pm = 1; // count direction: 1 = Up or -1 = Down

int main() {
while(1) {
aout = value/255.0f;
if ( value == 255 && pm == 1 ) {
pm = -1; // decrement
} else if ( value == 0 && pm == -1 ) {
pm = 1; // increment
}
value += pm;
wait_ms(10); // delay for 10 ms
}
}
73
Mbed Coding Example 9 (AnalogIn / AnalogOut)

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

// Nucleo L053R8: PA_4 / A2 pin, PA_2 = A0 pin


const PinName AOUT_PIN = PA_4;
IoT Engineering Education

const PinName AIN_PIN = PA_0;

AnalogIn ain( AIN_PIN );


AnalogOut aout( AOUT_PIN );
Serial pc( SERIAL_TX, SERIAL_RX, 115200 );

int main() {
uint16_t value;
while(1) {
value = ain.read_u16(); // value
pc.printf( "%u\r\n", value );
aout.write_u16( value );
wait_ms(100); // delay for 100 ms
}
}
74
Mbed Coding Example 10 (Ultrasonic Sensor) – Part 1

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

#define TRIG_PIN D4 // Output


#define ECHO_PIN D5 // Input
IoT Engineering Education

DigitalIn echo( ECHO_PIN );


DigitalOut trig( TRIG_PIN );

Serial pc( SERIAL_TX, SERIAL_RX, 115200 );

Timer timer;

const float sound_speed = 34300; // in cm/s

// Code continues on the next page.

75
Mbed Coding Example 10 (Ultrasonic Sensor) – Part 2

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


// Code continues from the previous page.

float measure() {
// generate a TRIGGER pulse (20 usec width)
IoT Engineering Education

trig = 1;
wait_us( 20 );
trig = 0;
while ( echo == 0 ) { wait_us(10); } // wait for rising edge
timer.reset(); // reset timer
while ( echo == 1 ) { wait_us(10); } // wait for falling edge
uint32_t duration_us = timer.read_us();
float distance = (sound_speed * duration_us)/(1000000*2);
return distance;
}

// Code continues on the next page.


76
Mbed Coding Example 10 (Ultrasonic Sensor) – Part 3

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


// Code continues from the previous page.

int main() {
timer.start(); // start timer
IoT Engineering Education

while(1) {
float distance = measure();
if (distance > 5000)
pc.printf( "Distance: Out of range !!!\r\n" );
else
pc.printf( "Distance: %.1f cm\r\n", distance );
wait_ms(500);
}
}

77
IoT Engineering Education

Hardware Testing: Ultrasonic Sensor (SR04+)

78

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

Mbed Coding Example 10: Output Sample

79

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


Mbed Coding Example 11 (Sleep & Wakeup) – Part 1

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

#define BAUDRATE 115200


IoT Engineering Education

volatile bool sleep_state = false;


Serial pc( SERIAL_TX, SERIAL_RX, BAUDRATE );

InterruptIn btn( PB_3 );


DigitalOut led1( PB_4 );
DigitalOut led2( PB_5 );

void irq_callback() {
btn.disable_irq();
sleep_state = !sleep_state;
}
// Code continues on the next page.
80
Mbed Coding Example 11 (Sleep & Wakeup) – Part 2

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


// Code continues from the previous page.
int main() {
btn.mode( PullUp ); // enable the internall pull-up resistor
btn.fall( &irq_callback ); // trigger on falling edge
btn.enable_irq();
IoT Engineering Education

while(1) {
if ( sleep_state ) { // enter sleep mode
led1 = led2 = 0; // turn off LED1 and LED2
btn.enable_irq();
sleep();
wait_ms(10);
btn.enable_irq();
pc.printf( "Woken up from sleep\r\n" );
} else {
led1 = 1; // turn on LED1
}
led2 = !led2; // toggle LED2
wait_ms( 100 );
}
}
81
Mbed Coding Example 12 (BH1750) – Part 1

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


#include "mbed.h"

#define SCL_PIN (PB_8)


#define SDA_PIN (PB_9)
IoT Engineering Education

#define I2C_ADDR (0x23)

const uint8_t addr = (I2C_ADDR << 1);


const uint8_t BH1750_CONT_HIGH_RES_MODE = (0x10);

Serial pc( SERIAL_TX, SERIAL_RX, 115200 );


I2C i2c( SDA_PIN, SCL_PIN );

// Code continues on the next page.

82
Mbed Coding Example 12 (BH1750) – Part 2

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


// Code continues from the previous page.
void i2c_scan() {
uint8_t data=0, found_devices=0;
pc.printf("Scan I2C devices....\r\n" );
IoT Engineering Education

for ( uint8_t addr=1; addr <= 0x7f; addr++ ) {


int ack = i2c.write( (addr << 1), (const char *)&data, 1 );
if (ack == 0) {
pc.printf("Found device @ 0x%02X\r\n", addr );
found_devices++;
}
}
if ( found_devices > 0 )
pc.printf( "Total number I2C devices found: %d\r\n", found_devices );
else
pc.printf( "No device found \r\n" );
}
// Code continues on the next page.
83
Mbed Coding Example 12 (BH1750) – Part 3

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


// Code continues from the previous page.

bool bh1750_init() {
int ack;
IoT Engineering Education

uint8_t buf[2];
buf[0] = BH1750_CONT_HIGH_RES_MODE;
ack = i2c.write( addr, (const char *)buf, 1 );
wait_ms(10);
if ( ack != 0 ) { // no ACK
return false;
}
return true;
}

// Code continues on the next page.

84
Mbed Coding Example 12 (BH1750) – Part 4

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


// Code continues from the previous page.

float bh1750_read() {
int ack;
IoT Engineering Education

uint8_t buf[2];

ack = i2c.read( addr, (char *)buf, 2 );


if ( ack != 0 ) {
return -1.0f;
}
uint16_t level = buf[0];
level = (level << 8) | buf[1];
return (level/1.2f); // Convert raw value to lux
}

// Code continues on the next page.

85
Mbed Coding Example 12 (BH1750) – Part 5

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


// Code continues from the previous page.

int main() {
i2c.frequency( 400000 );
IoT Engineering Education

i2c_scan();
bh1750_init(); // initialize the sensor
pc.printf( "Reading BH1750 light sensor...\r\n" );
while(1) {
float lux = bh1750_read();
if ( lux > 0 ) {
pc.printf( "Read: %d Lux\r\n", (int)lux );
} else {
pc.printf( "Sensor reading error !!!\r\n" );
}
wait(1.0); // 1 sec
}
}
86
IoT Engineering Education

STM32 Nucleo L053R8 + BH1750: Hardware Testing

87

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

STM32 Nucleo L053R8 + BH1750: Sample Output

88

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

VCC, DATA, NC, GND


STM32 Nucleo L053R8 + DHT22: Hardware Testing

89

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

STM32 Nucleo L053R8 + DHT22: Sample Output

90

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

STM32 Nucleo L053R8 + LCD16x2 + I2C Adapter

91

Copyright 2018 by Rawat Siripokarpirom @KMUTNB


IoT Engineering Education

To learn more
Please follow us
https://www.facebook.com/iot.kmutnb/

92

Copyright 2018 by Rawat Siripokarpirom @KMUTNB

You might also like