NUCLEO-F042K6 Simple demo with buttons intterupt changing PWM DC - with autoincrement when button pressed longer than 1s

Dependencies:   mbed

Revision:
0:602adf33625c
Child:
1:127786980842
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Sun Feb 11 23:55:14 2018 +0000
@@ -0,0 +1,87 @@
+#include "mbed.h"
+// pull up
+
+InterruptIn buttonPlus(PA_0); // deffition of interrupt
+InterruptIn buttonMinus(PA_1); // deffition of interrupt
+
+PwmOut PWM(PA_8); // definition of PWM pin
+
+Timer tim; // Timer definition
+
+Ticker tick;
+
+bool autoIncrement=false;
+bool plus=true;
+
+void pressedPlus() {
+    tim.start(); // start Timer
+    plus=true;
+    if (PWM.read()+0.01 <= 1) {
+        PWM.write(PWM.read()+0.01);
+        printf("Presed plus button. DC: %f.\n",PWM.read());
+    }else{
+        PWM.write(1);
+        printf("Presed plus button. Already maximum DC.\n");
+    }
+}
+
+void releasedPlus(){
+    tim.stop();
+    tim.reset();
+    autoIncrement=false;
+    printf("Plus button released.\n");
+}
+
+void pressedMinus() {
+    tim.start(); // start Timer
+    plus=false;
+    if (PWM.read()-0.01 >= 0) {
+        PWM.write(PWM.read()-0.01);
+        printf("Presed minus button. DC: %f\n",PWM.read());
+    }else{
+        PWM.write(0);
+        printf("Presed minus button. Already minimum DC.\n");
+    }
+}
+
+void releasedMinus(){
+    tim.stop();
+    tim.reset();
+    autoIncrement=false;
+    printf("Minus button released.\n");
+}
+
+void checkTimer(){
+    if(tim.read_ms()>1000){
+        tim.stop();
+        autoIncrement=true;
+    }    
+}
+
+int main()
+{
+        
+    // Set PWM
+    PWM.period_ms(2); // 500 Hz
+    PWM.write(0); // duration of active pulse
+    
+    // Set button interrupt
+    buttonPlus.fall(&pressedPlus);
+    buttonMinus.fall(&pressedMinus);
+    buttonPlus.rise(&releasedPlus);
+    buttonMinus.rise(&releasedMinus);
+    
+    tick.attach(&checkTimer,0.01);
+    
+    while (1) {
+        if(autoIncrement && plus && PWM.read()+0.01 <= 1){
+            PWM.write(PWM.read()+0.01);
+            printf("Autoincrement. DC: %f.\n",PWM.read());
+        }
+        else if(autoIncrement && !plus && PWM.read()-0.01 >= 0){
+            PWM.write(PWM.read()-0.01);
+            printf("Autodecrement. DC: %f.\n",PWM.read());
+        }
+        wait_ms(500);
+    }
+}