-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode 12 Onboard Arduino.cpp
More file actions
69 lines (62 loc) · 1.69 KB
/
Code 12 Onboard Arduino.cpp
File metadata and controls
69 lines (62 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
This code flips between two ultrasonic sensors
*/
#include <legopowerfunctions.h>
LEGOPowerFunctions lego(6); //PWM pin
#define trigPinFront 5
#define echoPinFront 4
#define trigPinBack 3
#define echoPinBack 2
byte trigPin = 5; //variable to hold which trigger pin is used - default front
byte echoPin = 4; //variable to hold which echo pin is used - default front
int counter = 0;
void setup() {
Serial.begin (9600);
pinMode(trigPinFront, OUTPUT);
pinMode(echoPinFront, INPUT);
pinMode(trigPinBack, OUTPUT);
pinMode(echoPinBack, INPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW); // Turn trigger off
delayMicroseconds(2); // wait a fraction of a second
digitalWrite(trigPin, HIGH); //send out ultrasonic pulse
delayMicroseconds(10); // pulse duration
digitalWrite(trigPin, LOW); //turn off ultrasonic pulse
duration = pulseIn(echoPin, HIGH); //receive input signal
distance = (duration/2) / 29.1; //calculate distance in centimetres
if (distance < 16) { // detection range
counter++; //increase the couter by one
changeDirection();
}
if (distance >= 200 || distance <= 0) {
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
Serial.print("counter=");
Serial.print(counter);
Serial.println();
}
if (counter % 2 ==0) {
trigPin = trigPinFront;
echoPin = echoPinFront;
}
else {
trigPin = trigPinBack;
echoPin = echoPinBack;
}
delay(100);
}
void changeDirection() {
lego.SingleOutput(0, PWM_FLT, BLUE, CH1); //stop the train
delay(1000);
if (counter % 2 ==0) {
lego.SingleOutput(0, PWM_FWD4, BLUE, CH1); //set direction forward
}
else {
lego.SingleOutput(0, PWM_REV4, BLUE, CH1); //set direction backward
}
}