First Draft, serial print change based on distance

Revision:
7:7464fbb0f3e1
Parent:
6:18a4dd77057e
Child:
8:7e48229d678c
--- a/main.cpp	Mon Jan 24 22:35:08 2022 +0000
+++ b/main.cpp	Wed Jan 26 23:08:24 2022 +0000
@@ -30,10 +30,6 @@
         
     }
         
-void dist(int distance){
-
-    printf("Safe Distance %dmm\r\n", distance);
-    }
     
 void main_menu(){
     
@@ -201,21 +197,12 @@
         
 void calibrate_object(){
      
-     int distance; 
-     
      while(1)
     {
-      lcd.clear();
-      mu.checkDistance();     //call checkDistance() as much as possible, as this is where
+        
+        mu.checkDistance();     //call checkDistance() as much as possible, as this is where
                                 //the class checks if dist needs to be called.
-      printf("Safe Distance %dmm\r\n", distance);
-    
-        char displaydist[14];
-        sprintf(displaydist,"%dmm", distance); // print formatted data to buffer
-        lcd.printString("set object to xxx",0,0);
-        lcd.printString(displaydist,0,3); // display on screen
-        lcd.refresh();
-        
+     
         if (Back_flag == 1) {
             Back_flag = 0;
             main_menu();}
@@ -224,6 +211,25 @@
         }
         }
         
+void dist(int distance)
+
+{
+    printf("Distance changed to %dmm\r\n", distance);
+
+     lcd.clear();
+     
+     char buffer[14]; // each character is 6 pixels wide, screen is 84 pixels (84/6 = 14)
+    // so can display a string of a maximum 14 characters in length
+    // or create formatted strings - ensure they aren't more than 14 characters long
+    int length = sprintf(buffer,"%dmm", distance); // print formatted data to buffer
+    // it is important the format specifier ensures the length will fit in the buffer
+    if (length <= 14) // if string will fit on display (assuming printing at x=0)
+    
+        lcd.printString("set object to xxx",0,0);
+        lcd.printString(buffer,0,3); // display on screen
+        lcd.refresh();
+    }
+        
 void Start_isr()
     {
     Start_flag = 1;