Template project for University of York ELE00032C Lab 4

Dependencies:   UoY-serial

Files at this revision

API Documentation at this revision

Comitter:
ajp109
Date:
Sat Jan 16 21:58:06 2021 +0000
Parent:
0:77209603a6fe
Child:
2:00b981e6c241
Commit message:
Initial commit

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
--- a/main.cpp	Mon Jan 11 11:28:11 2021 +0000
+++ b/main.cpp	Sat Jan 16 21:58:06 2021 +0000
@@ -1,15 +1,60 @@
 #include "mbed.h"
 
-int main()
-{
-    int x = 4;
-    x = 6;
-    int y;
-    y = 2*x;
-    x = 7;
-    
-    printf("x:%d y:%d\n", x, y);
-    
-    // Do nothing, forever...
-    while (true);
+class BoundedInt {
+
+  int min_;
+  int max_;
+  int value_;
+
+public:
+  
+  /* Constructor: takes a minimum and maximum value, and an initial value.
+    Enforces min <= max and calls setValue() to enforce min <= value <= max. */
+  BoundedInt(int min, int max, int value) {
+    if (max < min) {
+        max = min;
+    }
+    min_ = min;
+    max_ = max;
+    setValue(value);
+  }
+  
+  /* Sets a new value for this BoundedInt.  If the supplied value is outside
+    the range [min, max] it will be set to the closest valid value instead. */
+  void setValue(int value) {
+      if (value < min_) {
+          value = min_;
+      }
+      if (value > max_) {
+          value = max_;
+      }
+      value_ = value;
+  }
+  
+  /* Returns the value of this BoundedInt as an int */
+  int getValue() {
+      return value_;
+  }
+  
+  /* Shorthand for .setValue() */
+  BoundedInt & operator=(int value) {
+    setValue(value);
+    return *this;
+  }
+
+};
+
+int main() {
+  printf("ok\r\n");
+
+  BoundedInt test(0, 10, 0); // Minimum, maximum, initial value
+  
+  printf("Value is %d\r\n", test.getValue());
+  test = 4;
+  printf("Value is %d\r\n", test.getValue());
+  test = 25;
+  printf("Value is %d\r\n", test.getValue());
+  
+  // Do nothing, forever...
+  while (true);
 }