Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Diff: HW05Code/AccCar.cpp
- 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