Hi. I have been trying to correlate the movement of my robot based on a PIR Sensor. Specifically, I just want my robot to move randomly (forward, left and right) whilst stopping on a regular interval (say every 5 seconds) to activate the PIR Sensor to check if anything's moving. However, I can't seem to make anything move and even the PIR is not checking on anything on my code.
Here's a list of what I am using
- A standard Parallax PIR Sensor
- Generic Motor Shield that drives 2 DC Motors. Uses pins 8,9,10,11.
- Arduino Uno R3
Since I have yet to gather enough understanding on how to make time intervals on code, I am only trying at the moment to make the motors move once the PIR detects something. Here is my (non-working) code so far. (I only mixed and modified some tutorial codes I've found and added some of mine. Credits to their owners.)
int ledPin = 13; // choose the pin for the LED
int inputPin = 2; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0; // variable for reading the pin status
int speed;
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
Serial.begin(9600);
}
void loop(){
val = digitalRead(inputPin);
if (val == HIGH) {
digitalWrite(ledPin, HIGH);
digitalWrite(8, LOW);
digitalWrite(11, LOW);
for (speed=0; speed<256; speed++){
analogWrite(9, speed);
analogWrite(10, speed);
delay(10);
}
for (speed=255; speed>0; speed--){
analogWrite(9, speed);
analogWrite(10, speed);
delay(10);
}
digitalWrite(8, HIGH);
digitalWrite(11, HIGH);
for (speed=0; speed<256; speed++){
analogWrite(9, speed);
analogWrite(10, speed);
delay(10);
}
for (speed=255; speed>0; speed--){
analogWrite(9, speed);
analogWrite(10, speed);
delay(10);
}
if (pirState == LOW) {
Serial.println("Motion detected!");
pirState = HIGH;
}
}
else {
digitalWrite(ledPin, LOW); // turn LED OFF
if (pirState == HIGH){
Serial.println("Motion ended!");
pirState = LOW;
}
}
}
If somebody could shed me some light on this I would be very much thankful!
EDIT: Okay so I tried the code and made some corrections and now it works. The car now runs for a short while whenever a motion is detected on the PIR sensor. That's basically how I programmed it to be for the meantime just to see if the shield and PIR Sensor work. However, how do I go into making the car to do these things:
- Run randomly for 5 seconds (forward, left and right)
- Activate the PIR once the wheels have stopped. Then run another DC motor once motion is detected.
- If no motion is detected on Step 2, Run step 1 again.
Thank you!
Schematic.pdf (19.9 KB)