Working code with button bug

Dependencies:   mbed

Files at this revision

API Documentation at this revision

Comitter:
michael_antonucci
Date:
Wed Nov 16 04:52:35 2022 +0000
Commit message:
Working servo code. Has a bug where the button needs to be pressed twice at first. Not sure how to resolve

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Wed Nov 16 04:52:35 2022 +0000
@@ -0,0 +1,69 @@
+//Assignment 5 Exercise 2
+//Author: Michael Antonucci
+//Last Modified: 11/15/2022
+
+#include "mbed.h"
+
+DigitalOut myled(LED1);   //Specify inputs and variables
+DigitalIn button(p17);
+Serial pc(USBTX,USBRX);
+PwmOut servo(p21); 
+Timer timePressed;
+
+
+void servo_angle(float angle) //declare the angle function
+{
+    float pulseCoeff = 10.0;
+    float pulseOffset = 400;
+    float pulseWidth;
+
+    //Make sure angles are within bounds
+    if (angle < 0) {
+        angle = 0;
+    } else if (angle > 180) {
+        angle = 180.0;
+    }
+
+    //Calculate the pulsewidth for the desired angle and issue command:
+    pulseWidth = pulseCoeff * angle + pulseOffset;
+    servo.pulsewidth(pulseWidth/1000000.000);
+}
+
+int main()
+{
+    wait(3);
+    float angle; //store angle data
+    angle = 0; //set to zero
+    servo_angle(angle);
+    pc.printf("The servo angle is: %5.2f\r\n",angle);
+    while(1) {
+
+        while(button.read()==0) { //while button is not pressed
+            wait(0.1);
+            if (button.read()==1) { //if pressed
+                angle=angle+30;
+                servo_angle(angle);
+                timePressed.start(); //Start button timer
+                pc.printf("The servo angle is: %5.2f\r\n",angle);
+            }
+        }
+        while(button.read()==1) { //while button is pressed
+            wait(0.1);
+            if (button.read()==0) { //if released
+                timePressed.stop(); //Stop button timer
+            }
+        }
+        if (angle >= 180) { //Reset Servo if angle is greater than 180
+            angle = 0;
+            servo_angle(angle);
+            pc.printf("The servo angle is: %5.2f\r\n",angle);
+        }
+        if (timePressed.read_ms()>= 3000) { //Reset servo if timer is greater than 3 seconds
+            angle = 0;
+            servo_angle(angle);
+            pc.printf("The servo angle is: %5.2f\r\n",angle);
+        }
+        timePressed.reset(); //Reset button timer
+
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Wed Nov 16 04:52:35 2022 +0000
@@ -0,0 +1,1 @@
+https://os.mbed.com/users/mbed_official/code/mbed/builds/65be27845400
\ No newline at end of file