I'm trying to make it so that when we hold the button for three seconds the servo will switch position. (we are designing a braking system for a wheelchair for a class and we need to make sure that the wheels don't lock while they are moving if someone accidentally hits the button hence why we need the three second hold) Here is the code as we currently have it. I'm not sure what is wrong with it but the servo will not move at all.
#include <Servo.h>
#define KEY_PRESSED HIGH //state of key being pressed
#define KEY_NO_PRESS 0 //key not pressed
#define KEY_SHORT_PRESS 1 //key pressed short
#define KEY_LONG_PRESS 2 //key pressed long
#define KEY_DURATION 3000 //cycle count, minimum threshold to test for long presses
const int buttonPin = 8;
const int servoPin = 9;
int buttonState = 0;
int directionState = 0;
Servo servoOne;
int pos = 0;
int count = 0;
void setup() {
servoOne.attach(9);
servoOne.write(directionState);
pinMode(buttonPin, INPUT);
unsigned char key_read(unsigned char pin);
unsigned char count = 0;
}
void loop() {
if (digitalRead(8) != KEY_PRESSED) return KEY_NO_PRESS; //key not pressed
//key is pressed
while (digitalRead(8) == KEY_PRESSED) count+=1; //increment count if key is continuously pressed
if (count > KEY_DURATION) return KEY_LONG_PRESS;
else return KEY_SHORT_PRESS;
if (KEY_LONG_PRESS) {
if (buttonState == HIGH) {
directionState = 1;
for (pos = 0; pos < 180; pos = pos + 1) {
servoOne.write(pos);
delay(5);
}
}
} else if (KEY_LONG_PRESS) {
if (buttonState == HIGH) {
directionState = 0;
for (pos = 180; pos > 1; pos = pos - 1) {
servoOne.write(pos);
delay(5);
}
}
}
}
Does anyone know what we are doing wrong or how we could write this code in a different way to accomplish the same purpose? Some of the code in there might be irrelevant because I am trying to combine two sets of code that I found online that serves to make the servo move and serves to make a button held for a certain amount of time before it does something and I'm not sure it is all necessary. Thank you for any help!