-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathROB301_Project_2018_Student-Full.java
669 lines (564 loc) · 18.8 KB
/
ROB301_Project_2018_Student-Full.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
package ROB301_Project_2018;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.concurrent.TimeUnit;
import lejos.hardware.Button;
import lejos.hardware.lcd.LCD;
import lejos.hardware.motor.Motor;
import lejos.hardware.port.SensorPort;
import lejos.hardware.sensor.EV3GyroSensor;
import lejos.hardware.sensor.EV3UltrasonicSensor;
public class ROB301_Project_2018_Student_Simulation {
static int asci_count = 0; // ASCII counter
static int[] coord = new int [2]; // Keep track of coordinates
static Map<Character, int[]> char_to_position; // Hash map maps node with given name to coordinate on map
static char[][] my_map; // Stores maze map
static char[] listHead = {'U', 'R', 'D', 'L'}; // List of 4 possible Headings
static char nextHead = 'Z'; // Initialize nextHead which later gets updated
static robot_reading reading = new robot_reading();
static robot_control control = new robot_control();
static run_robot run = new run_robot();
public static void main(String[] args) {
int sizeMapX = 11; int sizeMapY = 11;
char curPos = 'A'; // Start position of robot (to be updated)
char curHead = 'R'; // Start orientation of robot (either 'U', 'D', 'L', 'R') (to be updated)
int[] curCoord = new int [2];
char nextPos;
int[] nextCoord = new int [2];
char goalPos = 'Y'; // Final position the robot needs to reach
char goalHead = 'U'; // Final orientation the robot needs to reach (either 'U', 'D', 'L', 'R')
List<Character> optPath; // Optimal path
double wall_dist;
initializeMap(); // Initialize map with no walls
Graph g = getGraph(my_map, sizeMapX, sizeMapY, char_to_position); // Create graph out of initialized map
optPath = g.getShortestPath(curPos, goalPos); // Get optimal path from current position to goal
System.out.println("Optimal Path: " + optPath);
printMap(my_map); // Print map to see structure of map (can choose to print for debugging purposes)
Button.waitForAnyPress();
while(!Button.ENTER.isDown()){
while (ifGoal(curPos, curHead, goalPos, goalHead) == false){
//
/*my_map[1][6] = '1'; // Add a wall to the map (for demo)
g = getGraph(my_map, sizeMapX, sizeMapY, char_to_position); // Create graph out of initialized map
optPath = g.getShortestPath(curPos, goalPos); // Get optimal path from current position to goal
System.out.println("Optimal Path: " + optPath);
printMap(my_map); // Print map to see structure of map (can choose to print for debugging purposes)
//Insert your code here...
*/
g = getGraph(my_map, sizeMapX, sizeMapY, char_to_position); // Create graph out of updated map
optPath = g.getShortestPath(curPos, goalPos); // Get optimal path from current position to goal
System.out.println("Optimal Path: " + optPath);
curCoord = char_to_position.get(curPos);
nextPos = optPath.get(optPath.size()-1);//suppose the robot is able to follow the shortest path
nextCoord = char_to_position.get(nextPos);
turnHead(curHead, curCoord, nextCoord); // updates the nextHead and turnd it
// Move (i.e. from currPos to nextPos)
wall_dist = reading.get_sonic_reading();
if (wall_dist < 15){
updateMap(nextPos, nextHead, my_map, char_to_position);
} else if (wall_dist <= 45){
control.move_until_wall();
updateMap(nextPos, nextHead, my_map, char_to_position);
curPos = nextPos;
} else {
control.move_1_grid();
curPos = nextPos;
}
curHead = nextHead;
}
printMap(my_map); // Print map to see structure of map (can choose to print for debugging purposes)
}
}
public static boolean ifGoal(char curPos,char curHead, char goalPos,char goalHead){
/* return true and execute the turning if goal is reached
return false if not
*/
if(curPos != goalPos){
return false;
}
else{
System.out.println("Goal is reached!");
int curHeadIndex = Arrays.asList(listHead).indexOf(curHead);
int goalHeadIndex = Arrays.asList(listHead).indexOf(goalHead);
int direction = goalHeadIndex - curHeadIndex;
switch (direction) {
case 1: case -3: control.turn_90(); control.turn_90(); control.turn_90(); break;
case 2: case -2: control.turn_90(); control.turn_90(); break;
case 3: case -1: control.turn_90(); break;
default: break;
}
return true;
}
}
public static void turnHead(char curHead, int[] curCoord, int[] nextCoord){
/* Use the difference between the current position and desired position (must be adjacent)
to determine the heading and turn it. Return nextHead
Examples:
* cur: (0,0) --> next: (0,1): nextHead = R
* cur: (0,0) --> next: (1,0): nextHead = D
* cur: (0,1) --> next: (0,0): nextHead = L
* cur: (1,0) --> next: (0,0): nextHead = U
*/
// determine which direction it should be heading
if(curCoord[0] == nextCoord[0]){
if (curCoord[1] == nextCoord[1]+2){
nextHead = 'L';
}
else if (curCoord[1] == nextCoord[1]-2){
nextHead = 'R';
}
}
else if(curCoord[1] == nextCoord[1]){
if (curCoord[0] == nextCoord[0]+2){
nextHead = 'U';
}
else if (curCoord[0] == nextCoord[0]-2){
nextHead = 'D';
}
}
// determine how it should turn to that direction and execute the turn
int curHeadIndex = Arrays.asList(listHead).indexOf(curHead);
int nextHeadIndex = Arrays.asList(listHead).indexOf(nextHead);
int direction = nextHeadIndex - curHeadIndex;
switch (direction) {
case 1: case -3: control.turn_90(); control.turn_90(); control.turn_90(); break;
case 2: case -2: control.turn_90(); control.turn_90(); break;
case 3: case -1: control.turn_90(); break;
default: break;
}
}
public static void initializeMap(){
/* Map should look like:
* ZZZZZZZZZZZ
ZA0B0C0D0EZ
Z0Z0Z0Z0Z0Z
ZF0G0H0I0JZ
Z0Z0Z0Z0Z0Z
ZK0L0M0N0OZ
Z0Z0Z0Z0Z0Z
ZP0Q0R0S0TZ
Z0Z0Z0Z0Z0Z
ZU0V0W0X0YZ
ZZZZZZZZZZZ
Hash map char_to_position is like a dictionary relating characters (e.g. 'A') to coordinates (e.g. [1,1]) in my_map
Note that positive X is right and positive Y is down
Z character is a null entry of the map
Alphabetical characters from A to Y are potential positions the robot can be in
Numerical characters can hold either 0 or 1 (to signify empty space or wall respectively between its neighbouring positions)
*/
char_to_position = new HashMap<Character, int[]>(); // Create hash from character to position in map
my_map = new char[11][11]; // Create map from position to character (i.e. regular map)
char letter; // Holds character corresponding to a position in the map
// Populate entire array with Z
for(int i = 0; i < 11; i++){
for(int j =0; j < 11; j ++){
my_map[i][j] = 'Z';
}
}
// Populate inner map area with 0's to signify free path between robot positions
for(int i = 1; i < 10; i++){
for(int j =1; j < 10; j ++){
my_map[i][j] = '0';
}
}
// Populate cells from A-Y where robot will go
for(int i = 1; i < 10; i+=2){
for(int j =1; j < 10; j +=2){
int[] coord = new int [2]; // Must create new array object so since hash map points all keys to same
letter = (char)(65+asci_count);
my_map[i][j] = letter;
coord [0] = i; coord[1] = j;
char_to_position.put(letter, coord);
asci_count++;
}
}
//Rest of map is padded with Z character to make parsing the map easier to implement
for(int i = 2; i < 10; i+=2){
for(int j =2; j < 10; j +=2){
my_map[i][j] = 'Z';
}
}
}
public static void updateMap(char curPos, char curHead, char[][] map, Map<Character, int[]> char_to_position){
/***
* Inputs: current Position, current Heading
* Outputs: None
* Function: Use current position and heading to correctly add a wall to the map my_map
***/
// Insert your code here...
int[] curCoord = new int[2];
curCoord = char_to_position.get(curPos);
int wall_x = 0;
int wall_y = 0;
if(curHead == 'U'){
wall_x = curCoord[0]-1;
wall_y = curCoord[1];
}
else if(curHead == 'D'){
wall_x = curCoord[0]+1;
wall_y = curCoord[1];
}
else if(curHead == 'L'){
wall_x = curCoord[0];
wall_y = curCoord[1]-1;
}
else if(curHead == 'R'){
wall_x = curCoord[0];
wall_y = curCoord[1]+1;
}
if(map[wall_x][wall_y] != 'Z'){
map[wall_x][wall_y] = '1';
}
}
public static Graph getGraph(char[][] map, int sizeX, int sizeY, Map<Character, int[]> char_to_position){
// Iterate through each robot position of the map
char[] neighbours;
Graph g = new Graph();
char letter;
for(int i = 1; i < sizeX-1; i+=2){
for(int j =1; j < sizeY-1; j +=2){
letter = map[i][j]; // Get current letter we're on and create edges from this on the graph
neighbours = getNeighbours(letter, map, char_to_position);
ArrayList<Vertex> vertices = new ArrayList<Vertex>();
for(int k=0; k < 4; k++){ // Iterate over all neighbours of current position in map
if(neighbours[k] != 'Z'){
vertices.add(new Vertex(neighbours[k],1));
}else{
break;
}
}
g.addVertex(letter, vertices); // Add list of neighbouring vertices to graph
}
}
return g;
}
public static char[] getNeighbours(char letter, char[][] map, Map<Character, int[]> char_to_position){
/***
* Inputs: position (char identifier of position in map we want to get the neighbours of)
* map (my_map variable above)
* char_to_position (hash map, see explanation in initializaMap() )
* Outputs: character array size between 1 and 4 of the neighbours (e.g. if we query H, return char will be 'C','I','M','G')
* Function: Return neighbors to queried node
***/
char[] neighbours = {'Z','Z','Z','Z'}; // Initialize neighbours to null type
int[] coord = new int[2];
coord = char_to_position.get(letter);
int n_index = 0;
//Check if any of the four neighbouring positions are free for the robot to travel to
if(map[coord[0]-1][coord[1]] == '0'){
neighbours[n_index] = map[coord[0]-2][coord[1]];
n_index++;
}
if(map[coord[0]+1][coord[1]] == '0'){
neighbours[n_index] = map[coord[0]+2][coord[1]];
n_index++;
}
if(map[coord[0]][coord[1]-1] == '0'){
neighbours[n_index] = map[coord[0]][coord[1]-2];
n_index++;
}
if(map[coord[0]][coord[1]+1] == '0'){
neighbours[n_index] = map[coord[0]][coord[1]+2];
}
return neighbours;
}
public static void printMap(char[][] map){
for(int i = 0; i < 11; i++){
for(int j =0; j < 11; j ++){
System.out.print(map[i][j]);
}
System.out.println("");
}
}
}
class robot_control{
double sensor_data; //this is the value returned by sensor
long time_start;
long time_end;
long d_t;
double robot_distance = 0;
boolean start_flag = false;
double magic_number = 0.8;
double grid_length = 17.5;
pidcontroller pid = new pidcontroller();
robot_reading robotreading = new robot_reading();
double turn_sensitivity_thresh = 0.15;
double speed = 0;
double magic_number_sonic = 6.5;
public void reset_flags(){
robot_distance = 0;
start_flag = true;
}
public double run(double speed) throws InterruptedException{
time_start = System.nanoTime();
//sensor_data = robot_reading.get_sonic_reading();
System.out.println(robot_distance);
//robot_reading.turn(motor_speed, motor_speed);
time_end = System.nanoTime();
d_t = time_end - time_start;
if (start_flag == false){
start_flag = true;
d_t = 0;
}
robot_distance += ((speed)*0.0275)*d_t*2*magic_number/1000000000;
return robot_distance;
}
public void turn_90() throws InterruptedException{
turn_45(-1);
while(robotreading.get_color_reading() >= turn_sensitivity_thresh){
robot_control.turn_increment(-1);
}
}
public void move_1_grid() throws InterruptedException{
while (run(100) < grid_length){
/*
if(Button.ESCAPE.isDown()){
break;
}
*/
speed = pid.run();
}
reset_flags();
pid.resetpid();
}
//We want this to output a distance (?)
public static void turn_increment(int direction) throws InterruptedException{
Motor.B.setSpeed(90);
Motor.C.setSpeed(90);
if (direction == -1){
Motor.B.backward();
Motor.C.forward();
} else if (direction == 1){
Motor.B.forward();
Motor.C.backward();
}
Thread.sleep((long) (10));
}
public void turn_45(int direction) throws InterruptedException{
Motor.B.setSpeed(90);
Motor.C.setSpeed(90);
Motor.B.rotate(direction*92, true);
Motor.C.rotate(direction*(-92));
Thread.sleep((long) (184.090909090*1000/90));
}
public void move_until_wall(){
while(robotreading.get_sonic_reading() >= magic_number_sonic){
/*
if(Button.ESCAPE.isDown()){
break;
}
*/
speed = pid.run();
//control_run = control.run(grid_length, speed);
}
}
public static void turn(double lspeed, double rspeed) {
int left_speed_round = (int) lspeed;
int right_speed_round = (int) rspeed;
Motor.B.setSpeed(Math.abs(left_speed_round));
if(lspeed > 0){
Motor.B.forward();
} else if(lspeed < 0) {
Motor.B.backward();
} else {
Motor.B.stop(true);
}
Motor.C.setSpeed(Math.abs(right_speed_round));
if(rspeed > 0){
Motor.C.forward();
} else if(rspeed < 0) {
Motor.C.backward();
} else {
Motor.C.stop(true);
}
}
}
// DO NOT CHANGE FOLLOWING CODE. Path planning implementation
class Vertex implements Comparable<Vertex> {
private Character id;
private Integer distance;
public Vertex(Character id, Integer distance) {
super();
this.id = id;
this.distance = distance;
}
public Character getId() {
return id;
}
public Integer getDistance() {
return distance;
}
public void setId(Character id) {
this.id = id;
}
public void setDistance(Integer distance) {
this.distance = distance;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((distance == null) ? 0 : distance.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vertex other = (Vertex) obj;
if (distance == null) {
if (other.distance != null)
return false;
} else if (!distance.equals(other.distance))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "Vertex [id=" + id + ", distance=" + distance + "]";
}
@Override
public int compareTo(Vertex o) {
if (this.distance < o.distance)
return -1;
else if (this.distance > o.distance)
return 1;
else
return this.getId().compareTo(o.getId());
}
}
class Graph {
public final Map<Character, List<Vertex>> vertices;
public Graph() {
this.vertices = new HashMap<Character, List<Vertex>>();
}
public void addVertex(Character character, List<Vertex> vertex) {
this.vertices.put(character, vertex);
}
public void createHashMap(){
}
public List<Character> getShortestPath(Character start, Character finish) {
final Map<Character, Integer> distances = new HashMap<Character, Integer>();
final Map<Character, Vertex> previous = new HashMap<Character, Vertex>();
PriorityQueue<Vertex> nodes = new PriorityQueue<Vertex>();
for(Character vertex : vertices.keySet()) {
if (vertex == start) {
distances.put(vertex, 0);
nodes.add(new Vertex(vertex, 0));
} else {
distances.put(vertex, Integer.MAX_VALUE);
nodes.add(new Vertex(vertex, Integer.MAX_VALUE));
}
previous.put(vertex, null);
}
while (!nodes.isEmpty()) {
Vertex smallest = nodes.poll();
if (smallest.getId() == finish) {
final List<Character> path = new ArrayList<Character>();
while (previous.get(smallest.getId()) != null) {
path.add(smallest.getId());
smallest = previous.get(smallest.getId());
}
return path;
}
if (distances.get(smallest.getId()) == Integer.MAX_VALUE) {
break;
}
for (Vertex neighbor : vertices.get(smallest.getId())) {
Integer alt = distances.get(smallest.getId()) + neighbor.getDistance();
if (alt < distances.get(neighbor.getId())) {
distances.put(neighbor.getId(), alt);
previous.put(neighbor.getId(), smallest);
forloop:
for(Vertex n : nodes) {
if (n.getId() == neighbor.getId()) {
nodes.remove(n);
n.setDistance(alt);
nodes.add(n);
break forloop;
}
}
}
}
}
return new ArrayList<Character>(distances.keySet());
}
}
class robot_reading{
//public static final EV3ColorSensor color = new EV3ColorSensor(SensorPort.S3);
//public static final EV3UltrasonicSensor sonic = new EV3UltrasonicSensor(SensorPort.S2);
public float get_color_reading() {
//int sampleSize = color.sampleSize();
float[] idsample = new float[sampleSize];
//color.getRedMode().fetchSample(idsample, 0);
LCD.clear();
return idsample[0];
}
public float get_sonic_reading() {
int sampleSize = sonic.sampleSize();
float[] sonicsample = new float[sampleSize];
sonic.fetchSample(sonicsample, 0);
LCD.clear();
return sonicsample[0]*100;
}
public void turn_90() {
Motor.B.rotate(92);
Motor.C.rotate(-92);
}
public void turn(double lspeed, double rspeed) {
int left_speed_round = (int) lspeed;
int right_speed_round = (int) rspeed;
Motor.B.setSpeed(left_speed_round);
Motor.B.forward();
Motor.C.setSpeed(right_speed_round);
Motor.C.forward();
}
}
}
class pidcontroller{
double k_p = 250;
double k_i = 5;
double k_d = 500;
double derivative = 0;
double lasterror = 0;
double integral= 0;
double floor = 0.35;
double line = 0.09;
double mid = 0.21;
double target = 0.21; //set target value
int direction;
double speed;
double sensor_data; //this is the vlaue returnd by sensor
public void resetpid(){
integral = 0;
}
public double run(){
sensor_data = robot_reading.get_color_reading();
double error = target - sensor_data; //if positive - target is larger - turn left
derivative = error - lasterror;
lasterror = error;
integral *= 0.98;
integral += error;
//if negative - target is smaller - turn right
double rightspeed = 90 + k_p*error + k_d*derivative + k_i*integral;
double leftspeed = 90 - k_p*error - k_d*derivative - k_i*integral;
robot_control.turn(leftspeed, rightspeed);
return (leftspeed + rightspeed)/2;
}
}