* BUGGY SAMPLE CODE
--------------------------------------------------------------
//SETUP LIBRARY
#include <Servo.h>
Servo motor_Left; // setup left motor
Servo motor_Right; // setup right motor
--------------------------------------------------------------
// DEFINE PINS
const in motor_Left_PIN = 10;
const in motor_Right_PIN = 9;
const in greenLed_PIN = 2;
const in Pot_PIN = A0;
---------------------------------------------------------------
// PID CONTROLS VARIABLES
float kp = 1; // Proportional gain
float Ki =1; // Integral gain
float kd = 1; // Derivative gain
float previousError = 0;
float integralError = 0;
---------------------------------------------------------------
// DEFINE VARIABLES FOR POT ANGLE MEASURMENT
const int angleSensorPin = A0;
const float zeroAngleVoltage = 2.5; // Voltage when the buggy is level
const float angleConversionFactor = 180.0 / 5.0; // Conversion factor from voltage to degrees
----------------------------------------------------------------
// DEFINE VARIABLES FOR SCANNING TIMER
bool scanning = false;
unsigned long scanStartTime = 0;
const unsigned long scanDuration = 5000; // 5 seconds in milliseconds
-----------------------------------------------------------------
void setup() {
// START SERIAL COMMUNICATION
Serial.begin(9600);
// SETUP PIN MODES
pinMode(motor_Left_PIN, OUTPUT);
pinMode(motor_Right_PIN, OUTPUT);
pinMode(greenLed_PIN, OUTPUT);
// SETUP MOTORS
motor_Left.attach(motor_Left_PIN); //Attach the left motor controller
motor_Right.attach(motor_Right_PIN); //Attach the right motor controller
// INTIALIZE MOTORS
motor_Left.writeMicroseconds(1000);
motor_Right.writeMicroseconds(1000);
// START LED
digitalWrite(greenLed_PIN, HIGH);
analogWrite(motor_Left_PIN, 60); // sending zero signal.
analogWrite(motor_Right_PIN, 60); // sending zero signal.
}
void loop() {
motor_Left.write(180); //MOTOR OFF (use 180 for full power)
motor_Right.write(180); //MOTOR OFF (use 180 for full power)
------------------------------------------------------------------
// READ CURRENT ANGLE FRON POT SENSOR
float voltage = analogRead(angleSensorPin) * (5.0 / 1023.0);
float angle = (voltage - zeroAngleVoltage) * angleConversionFactor;
------------------------------------------------------------------
// CALCULATE ERROR AND PID SIGNAL
float error = -angle; // set target angle to zero
integralError += error;
float derivativeError = error - previousError;
previousError = error;
float motorControlSignal = kp * error + ki * integralError + kd * derivativeError;
--------------------------------------------------------------------
// CONTROL MOTOR SIGNAL INTO MOTOR VALUES
motor_Left.writeMicroseconds(1500 - motorControlSignal); //Control the left motor
motor_Right.writeMicroseconds(1500 + motorControlSignal); //Control the right motor
---------------------------------------------------------------------
// SEND ZERO POWER TO MOTORS AFTER 11 METERS
motor_Left.write(60); //MOTOR OFF
motor_Right.write(60); //MOTOR OFF
}