Hi, fairly new to Arduino, attended a beginners course few years back
i want to make a useless box
the servo keeps running, serial monitor shows switch pin low so it must detect the switch.
Why doesnt the servo stop?
// Board: Mega2560
#include <Servo.h> //includes servo library
Servo myservo; //names the servo
#define fullstop 90 //since i have a continous rotation servo, here i define the speeds
#define fullcounter 180
#define fullclock 0
#define lowcounter 97
#define lowclock 85
int switch_pin = 30; //i have a tumbler on digital 30 and 5V
void setup() {
// put your setup code here, to run once:
pinMode (9,OUTPUT); //defining inputs and outputs
pinMode (30, INPUT);
myservo.attach (9); //attach servo to PWM output 9
Serial.begin (9600); //start serial to see if i connected stuff right
}
void loop() {
// put your main code here, to run repeatedly:
if (digitalRead(switch_pin) == HIGH) { //is this correct? if switch on continue...
myservo.write (60); //speed 60, hand moves out, clockwize
delay (350); //for 350ms
myservo.write (fullstop); //stops
delay (500); //delays before hand moves in
myservo.write (117); //speed for retracting, counterclockwize
delay (325); //does that for 325ms
myservo.write (fullstop); //hand moved in, full stop
}
else if (digitalRead(switch_pin) == LOW){ //if switch off, continue here
Serial.println ("Switch pin low");
myservo.write (fullstop); //incase it still moves, here it stops
}
else {
myservo.write (fullstop);
}
}
EDIT: made a new code that prints to serial monitor when switch is HIGH/LOW, turns out that when switch is high, it says HIGH, but when switch is low is says HIGH and LOW
a button switch is typically connected between an input pin and ground. The input is configured as INPUT_PULLUP so that when the switch is not pressed, the input is "pulled" HIGH and when the button is pressed it makes the pin LOW
how is your switch wired? should it be configured INPUT_PULLUP? should your code do things when the input is LOW instead of HIGH?
unzboz:
EDIT: made a new code that prints to serial monitor when switch is HIGH/LOW, turns out that when switch is high, it says HIGH, but when switch is low is says HIGH and LOW
If you mean that when the switch is open/not pressed it reading it varies randomly between HIGH and LOW then I'd say you don't have the necessary pull-down resistor fitted. A 10K resistor between the pin and GND should sort you out.
Or as suggested you could rewire the switch between the pin and GND and set pinMode(pin, INPUT_PULLUP). It will then be LOW when pressed and HIGH when not pressed.
Which part of "A 10K resistor between the pin and GND should sort you out" is proving too difficult to understand? That's what I said and that's what a pull-down resistor is.