okay so i've been working on a project with other group members and we've ran into a plateau in the arduino code. the project involves a HCSR04 sensor (ultrasonic) and a DC motor. we are trying to make the motor move faster when the sensor reads an object farther away and slower as the objects gets closer to the sensor.
we have been able to get independent codes to work on the sensor and DC motor but I'm unable to control the motor speed using the sensor's values.
things used: HCSR04 sensor, Motor shield, DC motor, LED light bulb, breadboard, 12V battery, jumper wires.
(arduino code attachments below)
For those who don't wanna download the attachment
SENSOR CODE:
int trigPin = 9;
int echoPin = 10;
int led = 7;
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// put your setup code here, to run once:
}
void loop() {
long duration, distance;
digitalWrite(trigPin,HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration=pulseIn(echoPin, HIGH);
distance =(duration/2)/29.1;
Serial.print(distance);
Serial.println("CM");
delay(10);
if((distance<=10))
{
digitalWrite(led, HIGH);
}
else if(distance>10)
{
digitalWrite(led, LOW);
}
}
DC MOTOR CODE:
#include<AFMotor.h>
AF_DCMotor motor1(1);
void setup() {
// put your setup code here, to run once:
motor1.setSpeed(255);
}
void loop() {
// put your main code here, to run repeatedly:
motor1.run(FORWARD);
delay(1000);
motor1.run(RELEASE);
delay(1000);
motor1.run(BACKWARD);
delay(1000);
}
COMBINED CODE TRIAL:
int trigPin = 9;
int echoPin = 10;
int led = 7;
#include<AFMotor.h>
AF_DCMotor motor1(1);
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
//motor1.setSpeed(255);
// put your setup code here, to run once:
}
void loop() {
long duration, distance;
digitalWrite(trigPin,HIGH);
delayMicroseconds(10000);
digitalWrite(trigPin, LOW);
duration=pulseIn(echoPin, HIGH);
distance =(duration/2)/29.1;
Serial.print(distance);
Serial.println("CM");
delay(1000);
if((distance<=10))
{
digitalWrite(led, HIGH);
motor1.setSpeed(10);
}
else if(distance>10)
{
digitalWrite(led, LOW);
motor1.setSpeed(300);
}
}
MOTOR.ino (308 Bytes)
SENSOR.ino (598 Bytes)
COMBINED.ino (724 Bytes)