mirror of
https://github.com/okalachev/flix.git
synced 2025-07-30 21:08:49 +00:00
62 lines
1.6 KiB
C++
62 lines
1.6 KiB
C++
// Copyright (c) 2023 Oleg Kalachev <okalachev@gmail.com>
|
|
// Repository: https://github.com/okalachev/flix
|
|
|
|
// Motors output control using MOSFETs
|
|
|
|
#include "util.h"
|
|
|
|
#define MOTOR_0_PIN 12 // rear left
|
|
#define MOTOR_1_PIN 13 // rear right
|
|
#define MOTOR_2_PIN 14 // front right
|
|
#define MOTOR_3_PIN 15 // front left
|
|
|
|
#define PWM_FREQUENCY 1000
|
|
#define PWM_RESOLUTION 12
|
|
|
|
// Motors array indexes:
|
|
const int MOTOR_REAR_LEFT = 0;
|
|
const int MOTOR_REAR_RIGHT = 1;
|
|
const int MOTOR_FRONT_RIGHT = 2;
|
|
const int MOTOR_FRONT_LEFT = 3;
|
|
|
|
void setupMotors() {
|
|
Serial.println("Setup Motors");
|
|
|
|
// configure pins
|
|
ledcAttach(MOTOR_0_PIN, PWM_FREQUENCY, PWM_RESOLUTION);
|
|
ledcAttach(MOTOR_1_PIN, PWM_FREQUENCY, PWM_RESOLUTION);
|
|
ledcAttach(MOTOR_2_PIN, PWM_FREQUENCY, PWM_RESOLUTION);
|
|
ledcAttach(MOTOR_3_PIN, PWM_FREQUENCY, PWM_RESOLUTION);
|
|
|
|
sendMotors();
|
|
Serial.println("Motors initialized");
|
|
}
|
|
|
|
int getDutyCycle(float value) {
|
|
value = constrain(value, 0, 1);
|
|
float duty = mapff(value, 0, 1, 0, (1 << PWM_RESOLUTION) - 1);
|
|
return round(duty);
|
|
}
|
|
|
|
void sendMotors() {
|
|
ledcWrite(MOTOR_0_PIN, getDutyCycle(motors[0]));
|
|
ledcWrite(MOTOR_1_PIN, getDutyCycle(motors[1]));
|
|
ledcWrite(MOTOR_2_PIN, getDutyCycle(motors[2]));
|
|
ledcWrite(MOTOR_3_PIN, getDutyCycle(motors[3]));
|
|
}
|
|
|
|
bool motorsActive() {
|
|
return motors[0] != 0 || motors[1] != 0 || motors[2] != 0 || motors[3] != 0;
|
|
}
|
|
|
|
void testMotor(uint8_t n) {
|
|
Serial.printf("Testing motor %d\n", n);
|
|
motors[n] = 1;
|
|
delay(50); // ESP32 may need to wait until the end of the current cycle to change duty https://github.com/espressif/arduino-esp32/issues/5306
|
|
sendMotors();
|
|
delay(3000);
|
|
motors[n] = 0;
|
|
sendMotors();
|
|
Serial.printf("Done\n");
|
|
}
|