Stap 2: Code
<p>dint pwm_speed //trig of ultrasonic sensor int trig = 12; //echo of ultrasonic sensor int echo = 13; </p><p>//int red = 2; //int blue = 4; //int green = 7;</p><p>int potpin = A0;</p><p>void setup() { //pins for motor controller pinMode(11, OUTPUT); pinMode(10, OUTPUT); pinMode(9, OUTPUT); pinMode(6, OUTPUT);</p><p>//pinMode(red,OUTPUT); //pinMode(blue,OUTPUT); //pinMode(green,OUTPUT);</p><p>//set trig as output and echo as input for ultrasonic sensor pinMode(trig, OUTPUT); pinMode(echo,INPUT); }</p><p>void loop() { pwm_speed = analogRead(potpin); pwm_speed = map(pwm_speed, 0, 1028, 0, 225);</p><p>scan();</p><p>int duration = pulseIn(echo, HIGH); int distance = duration / 29 / 2;</p><p>if(distance > 15){ forward(100); }else if(distance < 15){ backward(700); left(500); }</p><p>}</p><p>// function for driving straight void forward(int delay_time){ analogWrite(11, pwm_speed); analogWrite(10, 0); analogWrite(9, 0); analogWrite(6, pwm_speed); delay(delay_time); }</p><p>//function for reversing void backward(int delay_time){ analogWrite(11, 0); analogWrite(10, pwm_speed); analogWrite(9, pwm_speed); analogWrite(6, 0); delay(delay_time); }</p><p>//function for turning left void left(int delay_time){ analogWrite(11, 0); analogWrite(10, pwm_speed); analogWrite(9, 0); analogWrite(6, pwm_speed); delay(delay_time); }</p><p>//function for turning right void right(int delay_time){ analogWrite(11, pwm_speed); analogWrite(10, 0); analogWrite(9, pwm_speed); analogWrite(6, 0); delay(delay_time); }</p><p>//function for stopping motors void motors_stop(int delay_time){ analogWrite(11, 0); analogWrite(10, 0); analogWrite(9, 0); analogWrite(6, 0); delay(delay_time); } void scan(){ digitalWrite(trig, LOW); delayMicroseconds(2); digitalWrite(trig, HIGH); delayMicroseconds(5); digitalWrite(trig, LOW); }</p>