Thread example

Committer:
noutram
Date:
Tue Oct 31 13:45:19 2017 +0000
Revision:
1:20f8dc1354d0
Parent:
0:e48f4ddb9393
Child:
2:47c9c24b49fc
Updated for 2017 FX429

Who changed what in which revision?

UserRevisionLine numberNew contents of line
noutram 0:e48f4ddb9393 1 #include "mbed.h"
noutram 0:e48f4ddb9393 2
noutram 0:e48f4ddb9393 3
noutram 0:e48f4ddb9393 4 //Function declarations
noutram 0:e48f4ddb9393 5 void Function1();
noutram 0:e48f4ddb9393 6 void Function2();
noutram 0:e48f4ddb9393 7
noutram 0:e48f4ddb9393 8 //I/O
noutram 0:e48f4ddb9393 9 DigitalOut onBoardLED(LED1);
noutram 1:20f8dc1354d0 10 DigitalOut redLED(PE_15);
noutram 1:20f8dc1354d0 11 DigitalOut yellowLED(PB_10);
noutram 1:20f8dc1354d0 12 DigitalOut greenLED(PB_11);
noutram 0:e48f4ddb9393 13
noutram 0:e48f4ddb9393 14 DigitalIn onBoardSwitch(USER_BUTTON);
noutram 1:20f8dc1354d0 15 DigitalIn SW1(PE_12);
noutram 1:20f8dc1354d0 16 DigitalIn SW2(PE_14);
noutram 0:e48f4ddb9393 17
noutram 1:20f8dc1354d0 18 //Create thread objects
noutram 0:e48f4ddb9393 19 Thread t1, t2;
noutram 0:e48f4ddb9393 20
noutram 1:20f8dc1354d0 21 //Thread
noutram 0:e48f4ddb9393 22 void Function1()
noutram 0:e48f4ddb9393 23 {
noutram 0:e48f4ddb9393 24 while (true) {
noutram 0:e48f4ddb9393 25 redLED = !redLED;
noutram 0:e48f4ddb9393 26 Thread::wait(2000);
noutram 0:e48f4ddb9393 27 }
noutram 0:e48f4ddb9393 28 }
noutram 0:e48f4ddb9393 29
noutram 1:20f8dc1354d0 30 //Thread
noutram 0:e48f4ddb9393 31 void Function2()
noutram 0:e48f4ddb9393 32 {
noutram 0:e48f4ddb9393 33 while (true) {
noutram 0:e48f4ddb9393 34 yellowLED = !yellowLED;
noutram 0:e48f4ddb9393 35 Thread::wait(1000);
noutram 0:e48f4ddb9393 36 }
noutram 0:e48f4ddb9393 37 }
noutram 0:e48f4ddb9393 38
noutram 0:e48f4ddb9393 39 //Main thread
noutram 0:e48f4ddb9393 40 int main() {
noutram 1:20f8dc1354d0 41 //Initial state
noutram 0:e48f4ddb9393 42 redLED = 0;
noutram 0:e48f4ddb9393 43 yellowLED = 0;
noutram 1:20f8dc1354d0 44 greenLED = 0;
noutram 0:e48f4ddb9393 45
noutram 1:20f8dc1354d0 46 //Create and run threads (C function pointers)
noutram 0:e48f4ddb9393 47 t1.start(Function1);
noutram 0:e48f4ddb9393 48 t2.start(Function2);
noutram 0:e48f4ddb9393 49
noutram 1:20f8dc1354d0 50 //Main thread loop
noutram 0:e48f4ddb9393 51 while(1) {
noutram 0:e48f4ddb9393 52 //Thread::wait(osWaitForever);
noutram 0:e48f4ddb9393 53 Thread::wait(5000);
noutram 1:20f8dc1354d0 54 greenLED = !greenLED;
noutram 1:20f8dc1354d0 55 printf("Main is Awake\n"); //Should not happen when osWaitForever is used
noutram 0:e48f4ddb9393 56 }
noutram 0:e48f4ddb9393 57 }