Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
#include "mbed.h"
DigitalOut errorLed(LED3);
DigitalOut produceLed(LED1);
DigitalOut consumeLed(LED2);
Thread prodThread;
Thread consThread;
//Again Moving this to a Libary is left as an exersise
class TheStack{
private:
int maxSize;
int itemCount;
int data[5];
public:
TheStack(){
maxSize = 5;
itemCount = 0;
}
int addItem(int item)
/* Add an Item to the stack,
Returns:
0 if Successful
-1 On Error
*/
{
if (itemCount < maxSize){
data[itemCount] = item;
itemCount +=1;
return 0;
}
else{
errorLed = 1;
return -1;
}
}
int removeItem()
/* Remove an Item from the Stack
Return -1 on error
*/
{
if (itemCount < 0){
errorLed = 1;
return -1;
}
else{
itemCount -= 1;
int tmp = data[itemCount];
return tmp;
}
}
int numItems(){
return itemCount;
}
};
//Function to simulate busywait Data processing
//Accepts a time in MS
void fakeWait(int time){
Timer t;
t.start();
while (t.read_ms() < time){
//Simulate Processing
}
t.stop();
}
//Global Stack
TheStack myStack;
/* Function to produce items. You will need to make this safe*/
void produce(){
int counter = 0; //For the Item we are producing
while(1){
produceLed = !produceLed;
int data = counter;
fakeWait(200); //Fake Procesing
counter +=1;
printf("Produced %d\n", data);
myStack.addItem(data);
//And ask the theread to sleep
wait(0.5);
}
}
/* Function to Consume Items. This also needs to be safe */
void consume(){
int value;
while(1){
consumeLed = !consumeLed;
value = myStack.removeItem();
printf("--> Consumed %d\n", value);
fakeWait(200);
wait(0.5);
}
}
int main(){
errorLed = 0;
prodThread.start(produce);
consThread.start(consume);
while(1){
printf("Tick %d in Stack\n", myStack.numItems());
wait(5);
}
}