Hello all,
I am in the process of learning the program language of Arduino.
I have no programming experience nor a programming knack.
Find it quite complicated, and therefore challenging.
My project is a robot car with 3 ultrasonic sensors to drive it around autonomously.
Now I can't manage to get the "loop" right.
Can anyone give a little advice?
Sorry for my english, using a translator.
Greetings,
Robert
Here is my program:
//* Robotcar with Arduino Mega (3x ultra soon en 2 motors)
#include <AFMotor.h>
#define TRIG A1 //Trigger pin
#define ECHOL A4 //Echo Left sensor
#define ECHOM A3 //Echo Middle sensor
#define ECHOR A2 //Echo Right sensor
AF_DCMotor motor1(1); // create motor #1
AF_DCMotor motor4(4); // create motor #2
int distance[3]; // integer for distance sensor
void setup() {
Serial.begin(9600); //Serial monitor 9600 Baud
// Pins for ultrasoon sensor
pinMode(TRIG, OUTPUT); // Trigger output
pinMode(ECHOL, INPUT); // Echo Left sensor input
pinMode(ECHOM, INPUT); // Echo Middle sensor input
pinMode(ECHOR, INPUT); // Echo Right sensor input
// setup for 2 motors
motor1.setSpeed(150); // speed 150/255
motor4.setSpeed(150); // speed 150/255
delay (2500); // starts program after 2,5 seconds
}
void loop() {
ultrasoon(); // starts ultrsoon
if(distance[0] > 20); aandrijving(1); //if distance 0 > 20cm drive, case 1
if(distance[0] < 20); aandrijving(0); //if distance 0 < 20cm drive, case 0
if(distance[1] < 20); aandrijving(3); //if distance 1 < 20cm drive, case 3
if(distance[2] < 20); aandrijving(2); //if distance 2 < 20cm drive, case 2
delay (200);
}
void ultrasoon() {
//Middle sensor
digitalWrite(TRIG, HIGH); delayMicroseconds(8); digitalWrite(TRIG, LOW); delayMicroseconds(3); distance[0] = pulseIn(ECHOM, HIGH) / 58; delay(7);
//Right sensor
digitalWrite(TRIG, HIGH); delayMicroseconds(8); digitalWrite(TRIG, LOW); delayMicroseconds(3); distance[1] = pulseIn(ECHOR, HIGH) / 58; delay(7);
//Left sensor
digitalWrite(TRIG, HIGH); delayMicroseconds(8); digitalWrite(TRIG, LOW); delayMicroseconds(3); distance[2] = pulseIn(ECHOL, HIGH) / 58; delay(7);
}
void aandrijving(int wiel) {
//wiel
//0 = stop
//1 = forward
//2 = clockwise
//3 = left
//4 = backward
switch (wiel) {
case 0: //stop
motor1.run(RELEASE); // Motor 1 stop
motor4.run(RELEASE); // Motor 2 stop
Serial.print("stoppen");
break;
case 1: //forward
motor1.run(FORWARD); // Motor 1 forward
motor4.run(FORWARD); // Motor 2 forward
Serial.print("vooruit");
break;
case 2: //clockwise
motor1.run(RELEASE); // Motor 1 stop
motor4.run(FORWARD); // Motor 2 run
Serial.print("rechtsom");
break;
case 3: //left
motor1.run(FORWARD); // Motor 1 run
motor4.run(RELEASE); // Motor 2 stop
Serial.print("linksom");
break;
case 4: //backward
motor1.run(BACKWARD); // Motor 1 backward
motor4.run(BACKWARD); // Motor 2 backward
Serial.print("achteruit");
break;
}
}