Hello, I am doing a project with an Arduino and a gobilda motor, I am wanting to use a button to start the motor and when I press it again, it will stop the motor. Well what happens is that when you connect the battery to the motor it automatically starts the motor, also when you press the button what it does is make the movement rotate to the opposite side when what I want to do is start it when you click.
Motor: 5203 Series Yellow Jacket Planetary Gear Motor (50.9:1 Ratio, 24mm Length 8mm REX™ Shaft, 117 RPM, 3.3 - 5V Encoder) - goBILDA®
Diagram Wiring : https://www.gobilda.com/content/videos/m1/wiring_diagram.pdf
#include <Servo.h>
Servo esc_1;
int botonPin = 2;
int estadoBoton = 0;
int ultimoEstadoBoton = HIGH;
bool motorEncendido = false;
unsigned long tiempoUltimoCambio = 0;
unsigned long debounceDelay = 200;
void setup() {
esc_1.attach(9);
pinMode(botonPin, INPUT_PULLUP);
set_esc_power(esc_1, 0);
Serial.begin(9600);
Serial.println("Sistema iniciado");
}
void loop() {
int lecturaBoton = digitalRead(botonPin);
// Comprobar si ha pasado el tiempo de debounce
if (lecturaBoton != ultimoEstadoBoton) {
tiempoUltimoCambio = millis();
}
// Solo actuamos si ha pasado suficiente tiempo desde el último cambio
if ((millis() - tiempoUltimoCambio) > debounceDelay) {
// Si el botón se presionó (transición de HIGH a LOW)
if (lecturaBoton == LOW && ultimoEstadoBoton == HIGH) {
motorEncendido = !motorEncendido;
if (motorEncendido) {
set_esc_power(esc_1, 100);
Serial.println("Motor encendido");
} else {
set_esc_power(esc_1, 0);
Serial.println("Motor apagado");
}
delay(50);
}
}
ultimoEstadoBoton = lecturaBoton;
}
void set_esc_power(Servo esc, int power) {
power = constrain(power, 0, 100);
int signal_min = 1050;
int signal_max = 1950;
int signal_output = map(power, 0, 100, signal_min, signal_max);
esc.writeMicroseconds(signal_output); // Enviar la señal al ESC
}