Skip to content

Instantly share code, notes, and snippets.

@nathanic
Created February 14, 2017 16:01
Show Gist options
  • Save nathanic/cef1684fd52875922164cdc900a66ef5 to your computer and use it in GitHub Desktop.
Save nathanic/cef1684fd52875922164cdc900a66ef5 to your computer and use it in GitHub Desktop.
#include <Servo.h>
// CONSTANTS
const byte MAX_POS = 180;
const byte SERVO_PIN = 9;
const byte STEP_PIN = 2;
const byte DIR_PIN = 3;
const byte NEG_LIMIT_PIN = 11;
const byte POS_LIMIT_PIN = 12;
// TODO: see if these are backwards if that matters at some point
const byte DIR_CW = HIGH;
const byte DIR_CCW = LOW;
// GLOBAL VARIABLES >:-O
Servo g_servo;
volatile byte g_pos = 90; // count step pulses to update the servo
// Interrupt service routine - saturated inc/dec of position counter
void handle_step_pulse() {
if (digitalRead(DIR_PIN) == DIR_CW) {
if (g_pos < MAX_POS) {
g_pos++;
}
} else {
if (g_pos > 0) {
g_pos--;
}
}
}
void setup() {
g_servo.attach(SERVO_PIN);
pinMode(STEP_PIN, INPUT);
pinMode(DIR_PIN, INPUT);
pinMode(NEG_LIMIT_PIN, OUTPUT);
pinMode(POS_LIMIT_PIN, OUTPUT);
attachInterrupt(digitalPinToInterrupt(STEP_PIN), handle_step_pulse, RISING);
}
void loop() {
// set the servo position to match the current counter
// TODO: scaling? settable MIN_POS?
g_servo.write( g_pos );
digitalWrite(NEG_LIMIT_PIN, g_pos == 0 ? HIGH : LOW);
digitalWrite(POS_LIMIT_PIN, g_pos == MAX_POS ? HIGH : LOW);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment