Skip to content

Instantly share code, notes, and snippets.

@biacz
Forked from col/servo_test.ino
Created July 25, 2018 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biacz/41ad15c51182ec2f40fcb6cb8a9e5db3 to your computer and use it in GitHub Desktop.
Save biacz/41ad15c51182ec2f40fcb6cb8a9e5db3 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment