Demo entry 6341688

Ball Beam Balance


Submitted by Abdullah on Jan 02, 2017 at 12:57
Language: Arduino. Code size: 3.4 kB.

#include<Servo.h>                                       //Including the library used to control the servo motor
#include <LiquidCrystal.h>                              //Including the library used to control the LCD
LiquidCrystal lcd(1, 0, 5, 4, 3, 2);                    //Stating the Arduino pins connected to the LCD for communication
#include<PID_v1.h>                                      //Including the PID library
int servoPin = 9;                                       //Stating the pin to which the servo is attached        
float Kp = 2;                                         //Defining the intitial values of the proportional, integral and derivative constants.                                              
float Ki = 0;                                                      
float Kd = 1;                                                    
double Setpoint, Input, Output, ServoOutput;                                      

Servo myServo;                                                       
void setup() {  
  lcd.begin(16, 2);                       //These lines set up the LCD, and the servo motor
  myServo.write(36);                      //The initial position of the servo is set to 36 degrees. In my system, the beam was horizontal at this angle.                                 

  Input = (4800 / (analogRead(0) - 20)) - 8;              //This formula turns the raw input from the IR Proximity Sensor into centimeters.                   
  myPID.SetOutputLimit                   //My system only allows the beam to rotate 30 degrees clockwise or anticlockwise from it's mean position                             
void loop()

  double a1 = analogRead(0);                //The raw input from the potentiometer is scaled from 1 to 10, 
  double a2 = analogRead(1);                //and is used to determine the proportional and derivative constants.
  float Kp = map(a1, 0, 1024, 0, 10);
  float Kd = map(a2, 0, 1024, 0, 10);
  float Ki = 0;
  lcd.setCursor(0, 0);                            //These lines display the constants on the LCD
  lcd.print("Kp = ");
  lcd.setCursor(6, 0);

  lcd.setCursor(0, 1);
  lcd.print("Kd = ");
  lcd.setCursor(6, 1);
  Setpoint = 18;                           //The setpoint is the distance from the sensor at which the ball will be balanced
if(Input >0 && Input <32)
  myPID.Compute();                     //The PID library takes the calculated distance in cm, and computes an output based on the constants we have set.                
  ServoOutput = 36 + Output;            //In this case, the output is in the form of the angle of the servo motor.                    
  delay(50);                                 //This small delay is necessary to allow the servo to turn to the specific angle.

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).