#include <Button.h>
#include <ezButton.h>
//--- button pins
Button btn_left(2);
Button btn_right(3);
Button btn_play(4);
Button btn_switch_left(13);
Button btn_switch_right(12);
//--- motor pins
const int drv_pull = 6;
const int drv_dir = 7;
const int drv_enb = 8;
//--- leds
const int led_left = 11;
const int led_right = 10;
//--- states
bool play_state = false;
int motor_direction = 1; // switch 13-left, 12-right / <-0 1 2->
//--- motor values
int pulse_delay = 500;
void setup() {
//-serial
while (!Serial) { };
Serial.begin(9600);
//-buttons
btn_left.begin();
// btn_left.setDebounceTime(50);
btn_right.begin();
btn_play.begin();
btn_switch_left.begin();
btn_switch_right.begin();
//-driver
pinMode(drv_pull, OUTPUT);
pinMode(drv_dir, OUTPUT);
pinMode(drv_enb, OUTPUT);
//-leds
pinMode(led_left, OUTPUT);
pinMode(led_right, OUTPUT);
digitalWrite(led_left, LOW);
digitalWrite(led_right, LOW);
// pinMode(btn_switch_left, INPUT);
// pinMode(btn_switch_right, INPUT);
// digitalWrite(drv_dir, LOW);
// digitalWrite(drv_pull, LOW);
// digitalWrite(drv_enb, LOW);
}
void loop() {
// btn_left.loop();
//-map potentiometer values to driver speed
pulse_delay = map(analogRead(A0),0,1023,2000,50);
//-switch the direction of movement and turn on leds
if(btn_switch_left.read() == 1 && btn_switch_right.read() == 0){
// Serial.println("right switch");
motor_direction = 2;
digitalWrite(led_left, LOW);
digitalWrite(led_right, HIGH);
}else if(btn_switch_left.read() == 0 && btn_switch_right.read() == 1){
// Serial.println("left switch");
motor_direction = 0;
digitalWrite(led_left, HIGH);
digitalWrite(led_right, LOW);
}else{
motor_direction = 1;
digitalWrite(led_left, LOW);
digitalWrite(led_right, LOW);
}
//-play | pause
if(btn_play.pressed()){
Serial.println("play");
play_state = !play_state;
}
//-if play toggled drive motor in direction determined by switch and speed of pot
if(play_state == true){
driveMotor(motor_direction, pulse_delay);
}else{
digitalWrite(drv_enb, LOW); //disable stepper
}
//-check play state before pushing left|right buttons
if(play_state == false){
if(btn_left.pressed() || btn_left.read() == 0) {
driveMotor(0, pulse_delay);
Serial.println("left");
}
if(btn_right.pressed() || btn_right.read() == 0) {
Serial.println("right");
driveMotor(2, pulse_delay);
}
}
delay(10);
}
void driveMotor(int direction, int speed){
// digitalWrite(drv_enb, HIGH);
digitalWrite(drv_dir, direction);
digitalWrite(drv_pull, HIGH);
delayMicroseconds(speed);
digitalWrite(drv_pull, LOW);
delayMicroseconds(speed);
Serial.print("Drive to the: ");
Serial.print(direction);
Serial.print(" With pulse width: ");
Serial.println(speed);
}