/
DetectedWall.java
129 lines (108 loc) · 2.83 KB
/
DetectedWall.java
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import lejos.nxt.*;
import lejos.robotics.subsumption.*;
import java.lang.Math;
public class DetectedWall implements Behavior {
private boolean suppressed;
private UltrasonicSensor sonar;
private TouchSensor sensor;
private int limSonarDistance = 18;
private int qoRotation = 222;
private short epsilon = 8;
private int DISTANCE_THRESHOLD = limSonarDistance+epsilon*4;
private int currentSonarDistance = 0;
private int diffDistance = 0;
private int absDiffDistance = 0;
private int frontDistance = 0;
private int rotationAngle = 0;
private boolean wallmode = false;
public DetectedWall(SensorPort _port1, SensorPort _port2)
{
sonar = new UltrasonicSensor(_port1);
sensor = new TouchSensor(_port2);
}
public boolean takeControl()
{
return (sonar.getDistance() < limSonarDistance && !sensor.isPressed());
}
public void suppress()
{
wallmode = false;
suppressed = true;
}
public void rotateAngle(int _angle, boolean _direction)
{
if(_direction) //left
{
Motor.C.rotate((-1)*qoRotation*_angle/90, true);
Motor.B.rotate(qoRotation*_angle/90, true);
}
else //right
{
Motor.B.rotate((-1)*qoRotation*_angle/90, true);
Motor.C.rotate(qoRotation*_angle/90, true);
}
while (Motor.B.isMoving() && Motor.C.isMoving() && !suppressed)
{
Thread.yield();
}
}
public void action()
{
suppressed = false;
//Saw a wall, turn left
if(!wallmode)
{
rotateAngle(90, true);
wallmode = true;
}
while(wallmode)
{
Motor.A.rotate(-90);
currentSonarDistance = sonar.getDistance();
Motor.A.rotate(90);
frontDistance = sonar.getDistance();
if(frontDistance <= limSonarDistance + epsilon/2)
{
rotateAngle(90, true);
continue;
}
else
{
diffDistance = currentSonarDistance - limSonarDistance;
absDiffDistance = Math.abs(diffDistance);
//Distance to obstacle is very big, turn right
if(absDiffDistance > DISTANCE_THRESHOLD)
{
//Turn left 90
LCD.drawString("Out to the right", 1, 1);
rotateAngle(90, false);
Motor.B.rotate(620, true);
Motor.C.rotate(620, true);
while (Motor.B.isMoving() && Motor.C.isMoving() && !suppressed)
{
Thread.yield();
}
}
else
{
rotationAngle = (Motor.B.getAcceleration()*absDiffDistance)%30;
if(diffDistance < 0)
{
//Robot turned against wall - turn away left
rotateAngle(rotationAngle, true);
}
else if(diffDistance > 0 && absDiffDistance >= epsilon)
{
//Robot turned away from the wall - turn towards it right
if(rotationAngle>10)
{
rotateAngle(rotationAngle, false);
}
}
Motor.B.forward();
Motor.C.forward();
}
}
}
}
}