0

Control a brushless motor through a ESC with Arduino

#include “Servo.h”

#define MOTOR_PIN 10
#define MOTOR_MAX_SPEED 180
#define MOTOR_START_SPEED 80

int motor_current_speed = 0;
int motor_increment = 1;
int max_reached = 0;

Servo motor;

// Wrapper function for Servo’s “.write(*speed*)” function
void motorSetSpeed(int speed)
{
// Don’t let the motor go above or below pre-determined max and min
if (speed > MOTOR_MAX_SPEED)
speed = MOTOR_MAX_SPEED;
else if (speed < MOTOR_START_SPEED)
speed = MOTOR_START_SPEED;

motor.write(speed);
motor_current_speed = speed;

Serial.print(“current motor speed = “);
Serial.println(motor_current_speed);
}

void motorSpeedUp()
{
/*
Speed up quicker than normal if speed is less than 100.
Motor’s thrust to current relation is not linear – the motor needs a certain
minimum amount of current to generate sufficient thrust to initially lift the ball.
From observation, that minimum current is around speed 100.
*/
int increment = (motor_current_speed < 100) ? motor_increment + 3: motor_increment
motorSetSpeed(motor_current_speed + increment);
}

void motorSlowDown()
{
motorSetSpeed(motor_current_speed – increment);
}

void motorStop()
{
motor.write(0);
}

/*
!!! Very important! Motor has to start at 0 and reach desired speed gradually.
It will NOT work if you go directly to speed 60 or 100, etc.
If this isn’t working for you, try increasing the delay.
*/
void motorStartAt(int start_speed)
{
int i;
for (i=0; i < start_speed; i+=5) {
motorSetSpeed(i);
Serial.println(i);
delay(100);
}
}

void setup()
{

// Setup deb
Serial.begin(9600);

// Motor
delay(1000);
motor.attach(MOTOR_PIN);
motorStartAt(motor_start_speed);
delay(1500);
}

/*
Speeds the motor up until it hits 170,
then slows it down to the start speed again.
Repeats.
*/
void loop()
{

if (!max_reached) {
motorSpeedUp();
} else {
motorSlowDown();
}
if (motor_current_speed < MOTOR_START_SPEED) {
max_reached = 0;
} else if (motor_current_speed > MOTOR_MAX_SPEED) {
max_reached = 1;
}
delay(500);
}