Hello, I am attempting to build a circuit which will allow me to control a servo motor using two push buttons for a simple robotic arm project. Based on my own troubleshooting, I suspect the problem lies within my code. However, just to include any details that may be necessary, I will also try to explain the wiring (unfortunately I do not know how to create a digital diagram).
I am using a pca9685 module to control the servo with two simple pushbuttons. The idea was to make the servo move in one direction when one button is pressed, and in the other when the other button is pressed. I currently have three buttons wired up (only using two at the moment for testing purposes) to one analog pin. I also have three 220-ohm resistors wired to each button, utilizing the voltage drop to differentiate between which button is being pressed. I also am using a physical 10k ohm pulldown resistor. I think the circuit itself is operational, as I was successfully able to make a servo jump between two specific positions using the following code:
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
#define SERVOMIN 130
#define SERVOMAX 550
uint8_t servonum = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println ("pca9685_TurnoutTest!");
pwm.begin();
pwm.setPWMFreq(60);
delay(50);
}
void loop() {
int temp = analogRead(A0);
Serial.println (temp);
if (temp <= 980 && temp > 0){
pwm.setPWM(0, 0, 550);
delay (1000);
}
else if (temp <= 1002 && temp > 0){
pwm.setPWM(0, 0, 130);
delay (1000);
}
}
However, when I attempted to alter the code to make the servo only move when the buttons were pressed in increments of 1, I could not make it work. I used the following code:
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
#define SERVOMIN 130
#define SERVOMAX 550
uint8_t servonum = 0;
int pos = 0;
int servostep = 10;
int startpos = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println ("pca9685_TurnoutTest!");
pwm.begin();
pwm.setPWMFreq(60);
delay(50);
}
void loop() {
int temp = analogRead(A0);
Serial.println (temp);
if (temp <= 975 && temp > 0){
pos++;
pwm.setPWM(0, 0, pos);
delay (500);
} else if (temp <= 1002 && temp > 0){
pos--;
pwm.setPWM(0, 0, pos);
delay (500);
}
}
The only time this code worked was when I changed both if statements to increase the pos integer, and even this only worked about 50% of the time. I did double check to be sure the temp ranges fit the data I received through the serial monitor, and I think it works. I also tried changing the delay values, going from 1 millisecond to 5 milliseconds, but this had little effect on the success rate. If anyone has any suggestions, I would greatly appreciate it. Also, if more information is needed, please let me know. Any advice would be helpful, thanks!