Hello people! As part of my highschool science fair project I am running a simple RC car with an arduino. I am using a light sensor which can display in terms of voltage the light intensity and an ultrasonic sensor. My only problem is that my code doesn't work. Now, I tested the code individually, each separate segment for the code works. The car motor with a PWM works. The light sensor works, the sonar sensor works. However, when I put them all together in a single code, both the sensor work because I connected them to an LED to check, but the motor doesn't move. Could any of you please help me because it's my first time using arduino and I don't know if my code logic is good, I just used the samples and examples for reference.
int echo=9; //sonar sensor
int trig=8; //sonar sensor
int led=7;
int enb=2; //enables the motor
int forward=10; // + on this side makes motor go forward
int back=11;
void setup()
{
pinMode(echo, INPUT);
pinMode(led, OUTPUT);
Serial.begin (9600);
pinMode(trig, OUTPUT);
pinMode(enb, OUTPUT);
pinMode(forward, OUTPUT);
pinMode(back, OUTPUT);
}
void loop()
{
digitalWrite(enb, HIGH);
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
int sensorVal=analogRead(A0);
float voltage= sensorVal*(5.0/1023.0);
int duration = pulseIn(echo, HIGH);
int distance = (duration/2) / 29.1;
if (distance <25 || voltage >3) // This is where the LED On/Off happens
{
analogWrite(forward, 0);
digitalWrite(led,HIGH);
delayMicroseconds(1000);
digitalWrite(led,LOW);
}
else
{
analogWrite(forward, 200);
digitalWrite(back, LOW);
}
if (distance >= 200 || distance <= 0)
{
Serial.println("Out of range");
Serial.print("Color voltage =");
Serial.print(voltage);
Serial.println("V");
}
else
{
Serial.print("Distance ahead ");
Serial.print(distance);
Serial.println(" cm");
Serial.print("Color voltage =");
Serial.print(voltage);
Serial.println("V");
}
delay(1000);
}