Just started with electronics and duino a few months ago. What a hoot! Was beating my brains out trying to find a way to sweep a servo for a bot head and still be able to do other functions like read the IR sensor and move wheels. Learned real fast that delay is the enemy of this goal. Fianlly, by the beg, borrow and steal method, pieced together some code that seems to work well. There must be a less "codely" way to do this but I thought I would post it anyway for those like me who are learning. Hope it helps someone.
#include <Servo.h>
Servo head; //servo IR detector (eyeball) is mounted to
int poshead = 0; //variable for head (eyeball) position
int value = 0; //variable to store eyeball reading
long timerVal = 50; // Variable to hold the timer for servo head
int countupdown = 4; // Variable to hold the positive or negative change in angle
void setup()
{
Serial.begin (9600); //start serial comms
head.attach (3); // head servo attached here
}
void loop() {
if ((timerVal + 50) <= millis()) { // Timer loop
head.write(poshead); // move head servo
poshead = poshead + countupdown; // increment or decrement value depending on countupdown value
if (poshead == 160) { // If poshead reaches this position, change
countupdown = -10; // directon by making countupdown negative
}
if (poshead == 30) { // If headpos reaches this position, change direction
countupdown = 10; // making countupdown positive
}
timerVal = millis(); // Reset the timer
}
Readeyeball();
}
void Readeyeball () {
value = analogRead(0); //Sharp IR sensor (eyeball) attached here
Serial.println (value);
}