I am trying to control a servo motor with the following code:
#include <Servo.h>
Servo servo;
int const inputPin = 3;
void setup() {
Serial.begin(9600);
servo.attach(9);
pinMode(inputPin, INPUT);
servo.write(0);
}
void loop() {
if (digitalRead(inputPin)) {
Serial.println("HIGH");
servo.write(40);
} else {
Serial.println("LOW");
servo.write(0);
}
}
It takes input from pin 3 and controls the servo with pin 9. When pin 3 is connected to a pushbutton, as shown in the following image, it works exactly as expected; for as long as the button is held down, the servo stays at 40° and when the button is released the servo returns to 0°.
It's a little difficult to see in the images, but the resistor on row 24 is connected to ground, not power.
However, if I replace the button with an Adafruit RF M4 Receiver, as shown in the following image, the servo behaves differently. When I hold the button on the remote down, the servo attempts to move to 40°, but returns to 0° before trying again. From the serial output, I can see that the pin is in fact oscillating between HIGH and LOW.
If I remove the commands to the servo and just use the buttons to control the serial output, the code behaves correctly. With both the pushbutton and the RF M4 Receiver, the output says HIGH when the button is held down and LOW when it is released. So the issue only occurs when I use both the receiver and a servo motor, but not one or the other.
int const inputPin = 3;
void setup() {
Serial.begin(9600);
pinMode(inputPin, INPUT);
}
void loop() {
if (digitalRead(inputPin)) {
Serial.println("HIGH");
} else {
Serial.println("LOW");
}
}
I am using an Arduino Uno R3, this receiver, and this remote.
Edit: The schematic, as requested. I'm new to Arduino, so I apologize if the schematic is a little sloppy.
simulate this circuit – Schematic created using CircuitLab