Hi I'm trying to combine the Servo Knob example with Ultrasonic sensor.
Here's my sketch
#include "Ultrasonic.h"
Ultrasonic sonar(2,3);
int sonarPreviousMillis = 0;
unsigned long sonarCurrentMillis;
int sonarInterval = 500;
int range;
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int potpin = 0; // analog pin used to connect the potentiometer
int servoVal; // variable to read the value from the analog pin
int servoPreviousMillis = 0;
unsigned long servoCurrentMillis;
int servoInterval = 5;
void setup()
{
Serial.begin(9600);
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop()
{
head();
runSonar();
}
void head(){
servoCurrentMillis = millis();
if(servoCurrentMillis - servoPreviousMillis > servoInterval) {
servoPreviousMillis = servoCurrentMillis;
servoVal = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)
servoVal = map(servoVal, 0, 1023, 0, 179); // scale it to use it with the servo (value between 0 and 180)
myservo.write(servoVal);
}
}
void runSonar(){
sonarCurrentMillis = millis();
if(sonarCurrentMillis - sonarPreviousMillis > sonarInterval) {
sonarPreviousMillis = sonarCurrentMillis;
range = sonar.Ranging(CM);
if (range == 0){
Serial.println("too far");
}else{
Serial.print(sonar.Ranging(CM));
Serial.println("cm");
}
}
}
I would like to know if there is any better way to do such concurrent operations.
It seems the above sketch's Serial output got faster then 500ms when the sketch ran for a while, and the servo movement is a bit sloppy afterwards.