Emanuel Kuflik / Mbed OS HW05

Dependencies:   TextLCD

Revision:
0:f17da79e74c9
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HW05Code/AccCar.cpp	Wed Oct 09 16:29:06 2019 +0000
@@ -0,0 +1,67 @@
+#include "AccCar.h"
+#include <stdlib.h>
+#include <algorithm>
+
+#define TICK 1000
+#define MONITOR_DIST 17
+#define SAFETY_GAP 2
+
+AccCar::AccCar(int id, Road* road, int flag) {
+    this->id = id;
+    this->road = road;
+    this->flag = flag;
+    cycle = 0;
+    this->thread = NULL;
+}
+
+void AccCar::set_forward_car(AccCar* car) {
+    this->forward_car = car;   
+}
+
+void AccCar::update() {
+    while (true) {
+        ThisThread::sleep_for(TICK);
+        road->go_flags.wait_all(flag);
+        cycle++;
+        
+        position = position + speed;
+        
+        if (cycle % 5 == 0) {
+            speed = rand() % 11 + 5;
+        }
+        
+        if (forward_car->position - position < MONITOR_DIST) {
+            road->done_flags.wait_all(forward_car->flag, osWaitForever, false);
+            
+            int diff = forward_car->position - position;
+            int maxSafeSpeed = diff - SAFETY_GAP;
+            
+            speed = std::min(maxSafeSpeed, target_speed);
+        } else {
+            speed = target_speed;   
+        }
+        
+        road->done_flags.set(flag);   
+    }
+}
+
+void AccCar::reset() {
+    road->done_flags.clear(flag);
+    
+    if (thread != NULL) {
+        thread->terminate();   
+    }
+    
+    thread = new Thread();
+    thread->start( callback(this, &AccCar::update) );
+    
+    this->position = 0;
+    this->speed = rand() % 11 + 5;
+    this->target_speed = speed;
+}
+
+void AccCar::stop() {
+    if (thread != NULL) {
+        thread->terminate();   
+    }   
+}
\ No newline at end of file