I don't understand I am getting the error message "'i' is not declared in this scope" even though it should be.
It is originating from the line if ((i)==1){
Here is my code:
#include <AFMotor.h>
//setting pin numbers
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor3(3);
AF_DCMotor motor4(4);
const int trigpin = 53;
const int echopin = 51;
//setting up other variables
int range;
long duration;
int distance;
int start_turn=-15001;
//defining threshold distance in cm
const int t_d=20;
void setup() {
Serial.begin(9600); // set up Serial library at 9600 bps
//set up sensor input, output
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
Serial.println("Start");
// turn on motors and set the speed of motors
motor1.setSpeed(255);
motor2.setSpeed(255);
motor3.setSpeed(255);
motor4.setSpeed(255);
motor1.run(RELEASE);
motor2.run(RELEASE);
motor3.run(RELEASE);
motor4.run(RELEASE);
}
//defining the function for getting the range to nearest obstacle in cm
int get_range() {
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(5);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
distance = duration*0.034/2;
return distance;
}
void loop() {
range=get_range();
while ((range)>=(t_d)){
//Serial.print("forward");
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
range=get_range();
}
Serial.println(range);
while ((range)<(t_d)){
if (abs((millis()-(start_turn)))>10000){
randomSeed(analogRead(9));
const int i = (random(1, 256))%2;
}
if ((i)==1){
Serial.print("right");
motor1.run(BACKWARD);
motor2.run(BACKWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
range=get_range();
start_turn=millis();
}
else{
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(BACKWARD);
motor4.run(BACKWARD);
range=get_range();
start_turn=millis();
}
if (range>t_d){
delay(3000);
}
}
}