Code for a Servo + Encoder pulses?

Howdy,

I hve made the hardware and that checks out ok. I have a servo driving a wheel with an encoder on it.

int LeftOpto = 0; int RightOpto = 1; int LeftLED = 12; int RightLED = 11; int lval = 0; int rval = 0;

void setup() { pinMode(LeftLED, OUTPUT); pinMode(RightLED, OUTPUT); }

void loop() { lval = analogRead(LeftOpto); if (lval > 1000) { digitalWrite(LeftLED, LOW); } else { digitalWrite(LeftLED, HIGH); }

rval = analogRead(RightOpto); if (rval > 600) { digitalWrite(RightLED, LOW); } else { digitalWrite(RightLED, HIGH); } }

This simply turns an LED on or off indicating that the encoder is counting.

What I would like to do is have a function that allows me to turn a servo on for a number of encoder pulses. eg: LeftServo(12) 12 being the pulses. The servo will then turn untill it reaches the 12th encoder pulse.

I am using continuious rotation servos, and drive them using Servo.write(110) for full one way and (50) for full reverse.

I guess I need to use interrupts for this, but have no idea where to start.

Anyone done anything similar? I have serached the forum and seen a few examples, but none specific to this app.

Cheers!

Are you sure that analogRead is the correct way to read your encoder? What kind of encoder are you using?

Anyway, why not add in the code to count the pulses and light the LED when it reaches the desired number. When you have that working you can add in the servo code:

Write the value that rotates the servo Monitor the pin connected to the encoder and count pulses until you get to 12 Write the value to stop the servo

I am using a QRB1134 photoreflective sensor.

I did think about having a simple function that you pass an interger to for pulses, then count them.

I have been told interrupts would work better, but I have never used them before...

If you're using analogRead to read your counters, I can't really see any way interrupts (except, perhaps from timer interrupts) are going to help you. Normally, you'd use interrupts to automatically count either edges or levels, but since your readings are analogue and not digital, this isn't really feasible.

Maybe you could get creative with comparator interrupts, but really, for the sort of rates you're looking at here, you may as well stick with simply doing it all in "loop"

I have now modified my hardware to use the digital I/O so I can now use interrupts.

void setup(){
attachInterrupt(leftPin, pulsedLeft, RISING);
}

void pulsedLeft(){
movedLeft++;
}

void leftServo(int clicks){
movedLeft = 0;
leftServo.write(90);
while(movedLeft < clicks){
delay(50);
}
}

Make sure you declare "movedLeft" with the qualifier "volatile".