Created
August 24, 2017 21:40
-
-
Save jaydlawrence/d8d53cba2dce5365ae068e79e5cf5bf0 to your computer and use it in GitHub Desktop.
An Arduino sketch to control an ESC via PWM, including initial handshake and reading input from a potentiometer to modulate the speed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Servo.h> | |
// create motor handler of the Servo class type | |
Servo motor; | |
// The On/Off button will be on pin 6 | |
const int buttonPin = 6; | |
// The Potentiometer to adjust speed will be on pin 7 | |
const int potPin = 7; | |
// Motor signal is on pin 3 | |
const int motorPin = 3; | |
// store the current state of the button | |
int buttonState = 0; | |
// store the signal level from the potentiometer | |
int signalLevel; | |
void setup() { | |
// attach motor pin to the motor handler | |
motor.attach(motorPin); | |
// register buttonPin as an input | |
pinMode(buttonPin, INPUT); | |
// For debugging, start a serial connection | |
Serial.begin(9600); | |
// Start the complicated handshake with the ESC | |
motor.writeMicroseconds(1000); | |
delay(100); | |
motor.writeMicroseconds(2000); | |
delay(100); | |
motor.writeMicroseconds(1200); | |
delay(100); | |
motor.writeMicroseconds(0); | |
} | |
void loop() { | |
// get the current state of the button | |
buttonState = digitalRead(buttonPin); | |
// do the following if the button is pushed | |
if (buttonState == HIGH) { | |
// reads the value of the potentiometer (value between 0 and 1023) | |
signalLevel = analogRead(potPin); | |
// output potentiometer value to serial for debugging | |
Serial.println(signalLevel); | |
// scale the potentiometer value to within the minimum and maximum values of the ESC (between 1200 and 2000 in microseconds for PWM) | |
signalLevel = map(signalLevel, 0, 1023, 1200, 2000); | |
// Sends new signal value to the ESC | |
motor.writeMicroseconds(signalLevel); | |
// output the scaled value to serial for debugging | |
Serial.println(signalLevel); | |
} else { | |
// if the button is not pushed, set the ESC to not run the motor | |
motor.writeMicroseconds(1200); | |
} | |
// wait a bit between loops | |
delay(45); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment