633 solution updated for mbed os 54

Fork of Task633Solution-mbedos54 by Stage-1 Students SoCEM

main.cpp

Committer:
noutram
Date:
2016-03-09
Revision:
4:dae8898e55fe
Parent:
3:423191a375dc
Child:
5:31707531f715

File content as of revision 4:dae8898e55fe:

#include "mbed.h"
#include "rtos.h"
#include "string.h"
#include <stdio.h>
#include <ctype.h>

#define DELAY 200

//Digital outputs
DigitalOut onBoardLED(LED1);
DigitalOut redLED(D7);
DigitalOut yellowLED(D6);
DigitalOut greenLED(D5);

//Serial Interface
Serial pc(USBTX, USBRX);

//Digital inputs
DigitalIn  onBoardSwitch(USER_BUTTON);
DigitalIn  SW1(D4);
DigitalIn  SW2(D3);

//Thread ID for the Main function (CMSIS API)
osThreadId tidMain;

//Thread sychronisation primatives
Mutex lock1;
Mutex lock2;
unsigned long sw1Count = 0;
unsigned long sw2Count = 0;

void thread1( const void* arg ) 
{
    pc.printf("Entering thread 1\n");
    while (true) {
        
        //Start critical section
        lock1.lock();
 
        sw1Count++;
        printf("\nCount1 = %lu", sw1Count);
        
        //Thread::wait(1); //1ms
        
        if (SW1 == 1) {
            yellowLED = 1;
            lock2.lock();
            sw2Count--;
            lock2.unlock();  
            yellowLED = 0; 
        }
        
        //End critical section
        lock1.unlock();
        
        Thread::wait(DELAY);       
    }
}

void thread2( const void* arg ) 
{
    pc.printf("Entering thread 2\n");  
    while (true) {
        
        //Start critical section
        lock2.lock();
        
        sw2Count++;
        printf("\nCount2 = %lu", sw2Count);
        
        //Thread::wait(1);  //1ms
        
        if (SW2 == 1) {
            redLED = 1; 
            lock1.lock();
            sw1Count--;
            lock1.unlock();  
            redLED = 0;
        }  
        //End critical section
        lock2.unlock();
        
        Thread::wait(DELAY); 
    } 
}


//Main thread
int main() {
    redLED    = 0;
    yellowLED = 0;
    greenLED  = 0;
                
    //Main thread ID
    tidMain = Thread::gettid();  
    
    //Threads
    Thread t1(thread1);
    Thread t2(thread2);
    
    pc.printf("Main Thread\n");
    while (true) {
        Thread::wait(osWaitForever);
    }

}