Blog Arşivleri

Servo Motor Control via Joystick on Arduino Mega

Servo Control via Joystick

Servo Control via Joystick

Hi, my this program will be an improvement of “Usage of Joystick With Arduino Mega” post.

I controlled my servo motor via my joystick’s one axis. At the position of rest my analogue
input has the value of (Vcc / 2) about 512 that is approximately equals to 1023 / 2 .

Logic of my programme is like this. When i turn my joystick throuht right, my servo will turn as
clockwise and also if i turn my joystick throuht left, my servo will turn as counter-clockwise.
For able to get certain limits i choose 525 and 510. If my analog input’s digitalized value is
greater than 525 turns CCV if it is less than 510 it turns CW.

Servo motor is attached to the Arduino Mega’s A7 pin.

Also there is one more important point that I did not mentioned my earlier post is I delayed a little
the after one degree movement. ( delay(15); ) The point is if I do not use this delay, my analog
input will be at same value.

I hope it helps you.

 

#include <Servo.h> 
 
 Servo myservo;
 int joyPin1 = A1; // First analog input for Jostick
 int joyPin2 = A2; // Second analog input for Jostick
 int value1 = 0; // variable to read the value from the analog pin 0
 int value2 = 0; // variable to read the value from the analog pin 1
 int pos = 0; // variable to store the servo position 

 void setup() {
 pinMode(joyPin1, INPUT); 
 pinMode(joyPin2, INPUT); 
 myservo.attach(A7); // attaches the servo on pin A7 to the servo object 
 Serial.begin(9600);
 }


 void loop() {
 value1 = analogRead(joyPin1); 
 if (value1 > 525){ 
 if ( pos < 181 )
 pos++;
 }
 else if (value1 < 510){ 
 if ( -1 < pos )
 pos--;
 }
 
 delay(15);
 myservo.write(pos); 
 
 
 // delay(10); 
 // value2 = analogRead(joyPin2); 
 // delay(10); 


 Serial.print("first value : ");
 Serial.println(value1);
 Serial.print("second value : ");
 Serial.println(value2);
 Serial.println("---------------------");

 }