Hello guyz I am trying to control the direction of the motor using my analog pot. Actually i want to try this thing with analog thumb joystick but i haven't bought it yet so I am trying with the usual analog pots. Now analog pots can read up to a resolution of 0-1023 so I used a simple algorithm, when the post reads 512 motor will stop, if it reads greater than 512 it will move clockwise and if it reads less than 512 it will move anti-clockwise. But my motor only rotates in one direction and I don't know why. I am posting my whole code see if there is coding related problem.
int pot = 0;
int val = 0;
int motor[2] = {2,3};
int pwmPin = 9;
void setup()
{
Serial.begin(9600);
pinMode(pwmPin, OUTPUT);
//analogWrite(pwmnPin, 45);
int i;
for(i = 0; i < 2; i++)
{
pinMode(motor[i], OUTPUT);
}
}
void loop()
{
val = analogRead(pot);
Serial.println(val);
delay(1000);
if(val > 512)
{
int val1 = map(val1, 513, 1023, 0 ,45);
analogWrite(pwmPin, val1);
digitalWrite(motor[1], HIGH);
digitalWrite(motor[0], LOW);
}
else if( val < 512)
{
int val2 = map(val2, 0, 511, 0 ,45);
analogWrite(pwmPin, val2);
digitalWrite(motor[1], LOW);
digitalWrite(motor[0], HIGH);
}
else if(val = 512)
{
digitalWrite(motor[1], LOW);
digitalWrite(motor[0], LOW);
}
}
Servo/pot test code. For a DIY type continuous rotation servo, it might be better to use microseconds and map the command value between 1400us and 1600us, with 1500us being the calibrated no rotation value.
//zoomkat dual pot/servo test 12-29-12
//view output using the serial monitor
#include <Servo.h>
Servo myservo1;
Servo myservo2;
int potpin1 = 0; //analog input pin A0
int potpin2 = 1;
int newval1, oldval1;
int newval2, oldval2;
void setup()
{
Serial.begin(9600);
myservo1.attach(2);
myservo2.attach(3);
Serial.println("testing dual pot servo");
}
void loop()
{
newval1 = analogRead(potpin1);
newval1 = map(newval1, 0, 1023, 0, 179);
if (newval1 < (oldval1-2) || newval1 > (oldval1+2)){
myservo1.write(newval1);
Serial.print("1- ");
Serial.println(newval1);
oldval1=newval1;
}
newval2 = analogRead(potpin2);
newval2 = map(newval2, 0, 1023, 0, 179);
if (newval2 < (oldval2-2) || newval2 > (oldval2+2)){
myservo2.write(newval2);
Serial.print("2- ");
Serial.println(newval2);
oldval2=newval2;
}
delay(50);
}