Go Down

Topic: Ping-Pong with a DC motor & a pot (Read 2 times) previous topic - next topic

BazzaCAD

#5
Oct 08, 2012, 04:52 am Last Edit: Oct 08, 2012, 04:58 am by BazzaCAD Reason: 1
Yes, if I run the code below, the motor runs as expected.
In one direct for 4 sec. then in the other for 4 sec.....

Code: [Select]

//Motor A
int dir1PinA = 2;
int dir2PinA = 3;
int speedPinA = 5;

unsigned long time;
int speed;
int dir;

void setup ()
{
 pinMode (dir1PinA, OUTPUT);
 pinMode (dir2PinA, OUTPUT);
 pinMode (speedPinA, OUTPUT);
 time = millis ();
 speed = 200;
 dir = 1;
}

void loop ()
{
 analogWrite (speedPinA, speed);
 
 // set direction
 if (1 == dir)
 {
   digitalWrite (dir1PinA , LOW);
   digitalWrite (dir2PinA, HIGH);
 }
 else
 {
   digitalWrite (dir1PinA, HIGH);
   digitalWrite (dir2PinA, LOW);
 }
 
 delay(4000);
   if (1 == dir)
     {dir = 0;}
   else
     {dir = 1;}
}


It's just the logic with the pot code that I can't figure out.

Nick Gammon


The code does something. You want it to do something.


That's what happens with my code!

I want it to do something. It does something. But usually that is "something else". ;)

PeterH


It's just the logic with the pot code that I can't figure out.


Initially I assumed that MAX_LEFT was less than MAX_RIGHT, and with that assumption your code seemed to make sense. But in fact MAX_LEFT is greater than MAX_RIGHT. That means that the comparisons you're applying to your pot values are back to front.
I only provide help via the forum - please do not contact me for private consultancy.

BazzaCAD

OK I "think" I got it now. How does this look?
Will this have the over shooting issue & hit a mechanical limit & break?

Code: [Select]

#define  POT_PIN   A8
#define  MAX_LEFT  750
#define  MAX_RIGHT 300

int dir = 0; // 0 = Left, 1 = Right

void setup() {
  Serial.begin(9600);
}

void loop() {
  int headRot = analogRead(POT_PIN);
// Serial.println(headRot); // read-print pot
 
  if (headRot < MAX_LEFT)
  {
    if (headRot > MAX_RIGHT)
    {
     // Serial.println("Center");
    } else {
    //  Serial.println("Max Right");
      dir = 0;
    }
  } else {
   // Serial.println("Max Left");
    dir = 1;
  }
 
  if (dir == 0)
  {
    Serial.println("Turning Left");
  } else {
    Serial.println("Turning Right"); 
  }
}

PaulS

You never actually do anything with dir or motors...

If the potentiometer values represent limits, names like MIN_something and MAX_something make more sense than two MAX_somethings.

Go Up