Skip to content

Instantly share code, notes, and snippets.

@col
Created December 29, 2013 13:18
Show Gist options
  • Save col/8170414 to your computer and use it in GitHub Desktop.
Save col/8170414 to your computer and use it in GitHub Desktop.
A simple Arduino sketch that allows you to control a brushless motor via an ESC (or any servo really) using inputs from the Arduino IDE serial monitor.
#include <Servo.h>
Servo esc;
int escPin = 9;
int minPulseRate = 1000;
int maxPulseRate = 2000;
int throttleChangeDelay = 100;
void setup() {
Serial.begin(9600);
Serial.setTimeout(500);
// Attach the the servo to the correct pin and set the pulse range
esc.attach(escPin, minPulseRate, maxPulseRate);
// Write a minimum value (most ESCs require this correct startup)
esc.write(0);
}
void loop() {
// Wait for some input
if (Serial.available() > 0) {
// Read the new throttle value
int throttle = normalizeThrottle( Serial.parseInt() );
// Print it out
Serial.print("Setting throttle to: ");
Serial.println(throttle);
// Change throttle to the new value
changeThrottle(throttle);
}
}
void changeThrottle(int throttle) {
// Read the current throttle value
int currentThrottle = readThrottle();
// Are we going up or down?
int step = 1;
if( throttle < currentThrottle )
step = -1;
// Slowly move to the new throttle value
while( currentThrottle != throttle ) {
esc.write(currentThrottle + step);
currentThrottle = readThrottle();
delay(throttleChangeDelay);
}
}
int readThrottle() {
int throttle = esc.read();
Serial.print("Current throttle is: ");
Serial.println(throttle);
return throttle;
}
// Ensure the throttle value is between 0 - 180
int normalizeThrottle(int value) {
if( value < 0 )
return 0;
if( value > 180 )
return 180;
return value;
}
@Cartikey
Copy link

Genius.
Thank you :)

@solber
Copy link

solber commented Mar 26, 2017

willROV , just replace Serial.ParseInt() by your value !

@22th
Copy link

22th commented Aug 27, 2017

how to make it so it sends max 255 signal all the time when a button is pressed.

@jayanta-banik
Copy link

can you also help with the connection. also can you help me with an alternative power source and how to use them (preferably 9volt battery). thanks, any help is appreciated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment