Hey, I wanted to know how I can use millis() and if statement to run an ultrasonic sensor and 2 servo motors?
You need to be a little more specific about what it is you want to do.
What decision is the if meant to make?
What have you tried ?
Where are you stuck ?
Take a look at Using millis() for timing. A beginners guide, Several things at the same time and the BlinkWithoutDelay example in the IDE
I want the ultrasonic sensor to trigger the servo motors to go backward, left, and right to avoid objects.
So where are you stuck ?
`I'm stuck on getting everything to working together. I can't get the sensor to trigger the servos.
Post your best effort but read this topic first and follow the advice to use code tags when posting code How to get the best out of this forum
#include "SR04.h"
#include <Servo.h>
#define TRIG_PIN 2
#define ECHO_PIN 3
SR04 sr04 = SR04(ECHO_PIN,TRIG_PIN);
long a;
long distance;
long duration;
unsigned long prevTime = millis();
Servo myservo1; //Left leg
Servo myservo2; //Right leg
int pos = 0;
void setup() {
Serial.begin(9600);
delay(1000);
myservo1.attach(7);
myservo2.attach(8);
pinMode(TRIG_PIN,OUTPUT);
pinMode(ECHO_PIN,INPUT);
}
void loop() {
a=sr04.Distance();
Serial.print(a);
Serial.println("cm");
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration*0.034/2;
unsigned long currentTime = millis();
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo1.write(pos); // tell servo to go to position in variable 'pos'
}
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo2.write(pos); // tell servo to go to position in variable 'pos'
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo1.write(pos); // tell servo to go to position in variable 'pos'
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo2.write(pos); // tell servo to go to position in variable 'pos'
if(currentTime - prevTime > 1000) {
}
}
}
The servo sweeps don't appear to achieve very much.
What are they supposed to do?
Servos make the robot walk. I need to change the positions.
The positions of what?
That for loop could be replaced by
myservo1.write (180);
The positions of the servo, like if I made them go 80 - 90 degrees they will walk and ok I'll change to myservo1.write (180);. Any other changes?
This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.