//Definición de pines
#define UH_PIN 5
#define UL_PIN 6
#define VH_PIN 7
#define VL_PIN 8
#define WH_PIN 9
#define WL_PIN 10
// Definición de las constantes
const int MAX_SPEED = 255;
const int MIN_SPEED = 0;
// Variables globales
int motor_speed = 0;
int motor_direction = 1;
// Función de inicialización del PWM
void init_pwm() {
TCCR1A = 0;
TCCR1B = 0;
TCCR1A |= (1 << COM1A1) | (1 << COM1B1) | (1 << COM1C1) | (1 << WGM11);
TCCR1B |= (1 << WGM13) | (1 << WGM12) | (1 << CS10);
ICR1 = 255;
}
// Función de configuración de los pines
void setup() {
pinMode(UH_PIN, OUTPUT);
pinMode(UL_PIN, OUTPUT);
pinMode(VH_PIN, OUTPUT);
pinMode(VL_PIN, OUTPUT);
pinMode(WH_PIN, OUTPUT);
pinMode(WL_PIN, OUTPUT);
init_pwm();
}
// Función de control de velocidad
void control_speed() {
if (motor_speed > MAX_SPEED) {
motor_speed = MAX_SPEED;
} else if (motor_speed < MIN_SPEED) {
motor_speed = MIN_SPEED;
}
OCR1A = motor_speed;
OCR1B = motor_speed;
OCR1C = motor_speed;
}
// Función de control de dirección
void control_direction() {
if (motor_direction == 1) {
digitalWrite(UH_PIN, HIGH);
digitalWrite(UL_PIN, LOW);
digitalWrite(VH_PIN, HIGH);
digitalWrite(VL_PIN, LOW);
digitalWrite(WH_PIN, HIGH);
digitalWrite(WL_PIN, LOW);
} else {
digitalWrite(UH_PIN, LOW);
digitalWrite(UL_PIN, HIGH);
digitalWrite(VH_PIN, LOW);
digitalWrite(VL_PIN, HIGH);
digitalWrite(WH_PIN, LOW);
digitalWrite(WL_PIN, HIGH);
}
}
// Función de loop principal
void loop() {
// Se lee la velocidad del motor desde el sensor
int sensor_speed = analogRead(A0);
// Se mapea la velocidad del sensor a la velocidad del motor
motor_speed = map(sensor_speed, 0, 1023, 0, MAX_SPEED);
// Se lee la dirección del motor desde un botón o interruptor
int direction_button = digitalRead(2);
if (direction_button == LOW) {
motor_direction = 1;
} else {
motor_direction = -1;
}
// Se controla la velocidad y la dirección del motor
control_speed();
control_direction();
}