Skip to content

Instantly share code, notes, and snippets.

@codergautam
Created February 21, 2025 10:16
Show Gist options
  • Save codergautam/687fc3cc30dd2d6f9213de29f60c88cc to your computer and use it in GitHub Desktop.
Save codergautam/687fc3cc30dd2d6f9213de29f60c88cc to your computer and use it in GitHub Desktop.
Code for science olympiad electric vehicle in Arduino
#include <Servo.h>
// pin defs
#define EncoderPinA 2 // (green)
#define EncoderPinB 3 // (white)
#define ButtonPin 12 // (start btn SW)
const int pwmPin = 5; // motor white wire
const int ledPin = 13; // onboard LED
Servo motor;
volatile long encoderPosition = 0;
const float cmTarget = 900-(100);
// overshot calculations (approx)
// 3m - 70cm overshot
const float rotationsTarget = (cmTarget / 8); // 1rot = approx 8cm
const int motorSpeed = 1200; // Constant speed PWM value
bool motorStarted = false; // track buttonpress
void setup() {
// Encoder setup
pinMode(EncoderPinA, INPUT_PULLUP);
pinMode(EncoderPinB, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(EncoderPinA), EncoderA, FALLING);
attachInterrupt(digitalPinToInterrupt(EncoderPinB), EncoderB, FALLING);
motor.attach(pwmPin);
motor.writeMicroseconds(800); // initialize motor to minimum PWM
pinMode(ButtonPin, INPUT_PULLUP); // track the button
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
Serial.begin(9600);
delay(2000); // let esc get ready
}
void loop() {
// start pressed
if (digitalRead(ButtonPin) == LOW && !motorStarted) {
motor.writeMicroseconds(motorSpeed);
motorStarted = true;
digitalWrite(ledPin, HIGH);
}
// Run motor at constant speed or stop it based on encoder position
if (motorStarted) {
float rotations = (float)encoderPosition / 720.0;
if (rotations < rotationsTarget) {
motor.writeMicroseconds(motorSpeed);
} else {
// stop motor when target rotations reached
motor.writeMicroseconds(800);
digitalWrite(ledPin, LOW);
}
static unsigned long lastPrintTime = 0;
if (millis() - lastPrintTime >= 100) {
Serial.print("Rotations: ");
Serial.print(rotations, 2);
Serial.print(", Dist: ");
Serial.println(rotations/8, 2);
lastPrintTime = millis();
}
}
}
void EncoderA() {
encoderPosition += (digitalRead(EncoderPinA) == digitalRead(EncoderPinB)) ? -1 : 1;
}
void EncoderB() {
encoderPosition += (digitalRead(EncoderPinA) != digitalRead(EncoderPinB)) ? -1 : 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment