Hi everyone, i'm trying to control multiple servo motors with buttons. For example, 2 motor with 2 buttons. It somehow works but sometimes the servos goes haywire. i'm new to Arduino so please explain in the most simplest term. Thanks..
Code:
// Button from pin 4 to ground
// Servo connected to pin 7
// LED from pin 6 to ground
#include <Servo.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x27 // <<----- Add your address here. Find it from I2C Scanner
#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7
int n = 1;
int button1 = 4; //button pin, connect to ground to move servo
int press1 = 0;
int led = 6;
int button2 = 9;
int led2 = 10;
Servo servo1;
Servo servo2;
LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);
void setup()
{
pinMode(led, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(button2, INPUT);
pinMode(button1, INPUT);
servo1.attach(7); //first motor
servo2.attach(8); //second motor
digitalWrite(4, HIGH); //enable pullups to make pin high
digitalWrite(9, HIGH);
lcd.begin (16,2); // <<----- My LCD was 16x2
lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
lcd.setBacklight(HIGH);
lcd.home (); // go home
lcd.clear();
lcd.write("Ready to dispense");
}
void loop()
{
press1 = digitalRead(button1);
if (press1 == LOW)
{
digitalWrite(led, HIGH);
servo1.write(160);
lcd.clear();
lcd.print("Dispensing");
delay (1000);
servo1.write(20);
delay(100);
lcd.clear();
lcd.print("Ready 2 dispense");
delay(500);
digitalWrite(led, LOW);
}
if (digitalRead(9) == LOW)
{
digitalWrite(led2, HIGH);
servo2.write(160);
lcd.clear();
lcd.print("Dispensing");
delay (1000);
}
servo2.write(20);
delay(100);
lcd.clear();
lcd.print("Ready 2 dispense");
delay(500);
digitalWrite(led2, LOW);
}