-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgigglebot.ts
1070 lines (982 loc) · 35.7 KB
/
gigglebot.ts
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Use this file to define custom functions and blocks.
* Read more at https://makecode.microbit.org/blocks/custom
*/
enum gigglebotWhichUniqueMotor {
//% block="right motor"
Right,
//% block="left motor"
Left
}
enum gigglebotWhichMotor {
//% block="both motors"
Both,
//% block="right motor"
Right,
//% block="left motor"
Left
}
enum gigglebotWhichDriveDirection {
//% block="forward"
Forward,
//% block="backward"
Backward
}
enum gigglebotWhichTurnDirection {
//% block="right"
Right,
//% block="left"
Left
}
enum gigglebotWhichUnitSystem {
//% block="mm"
mm,
//% block="inches"
inches
}
enum gigglebotWhichSpeed {
//% block="slowest"
Slowest = 30,
//% block="slower"
Slower = 45,
//% block="normal"
Normal = 60,
//% block="faster"
Faster = 75,
//% block="fastest"
Fastest = 90
}
enum gigglebotI2CCommands {
GET_FIRMWARE_VERSION = 1,
GET_MANUFACTURER,
GET_BOARD,
GET_VOLTAGE_BATTERY,
GET_LINE_SENSORS,
GET_LIGHT_SENSORS,
GET_MOTOR_STATUS_RIGHT,
GET_MOTOR_STATUS_LEFT,
SET_MOTOR_POWER,
SET_MOTOR_POWERS
}
enum gigglebotLineType {
//% block="thick"
Thick,
//% block="thin"
Thin
}
enum gigglebotLineColor {
//% block="black"
Black,
//% block="white"
White
}
enum gigglebotLightLevel {
//% block="brightness"
Brightness,
//% block="darkness"
Darkness
}
enum gigglebotTowardsAway {
//% block="towards"
Towards,
//% block="away from"
Away
}
enum gigglebotServoAction {
//% block="right"
Right,
//% block="left"
Left,
//% block="both in synchro"
Both,
//% block="both in mirror"
Mirror
}
enum gigglebotInequality {
//% block="closer than"
Closer,
//% block="farther than"
Farther
}
enum gigglebotLightFollowMode {
//% block="follow"
Follow,
//% block="avoid"
Avoid
}
enum gigglebotTempScale {
//% block="Celsius"
Celsius,
//% block="Farhenheit",
Farhenheit
}
enum gigglebotPressureScale {
//% block="Pascal"
Pascal,
//% block="inches"
inches
}
/**
* Custom blocks
*/
//% weight=99 color=#46BFB1 icon="\uf0d1"
//% groups='["other", "Line Follower", "Light Sensors", "Servo", "Distance Sensor (Add-On)", "Temperature Humidity Pressure (Add-On)", "On Board Sensors", "Voltage", "Firmware"]'
namespace gigglebot {
/**
* Basic drive and sensor functionalities for GiggleBot
* No radio, no neopixels functionalities here in order to be compatible with Bluetooth.
* Load pxt-giggle for radio and neopixels
*/
let ADDR = 0x04
let line_follower_threshold = 175
let light_level_threshold = 850
let currentMotorPower = gigglebotWhichSpeed.Normal;
let trimLeft = 0
let trimRight = 0
let motorPowerLeft = currentMotorPower
let motorPowerRight = currentMotorPower
let distanceSensorInitDone = false;
let thpSensorInitDone = false;
let line_follow_in_action = false;
let light_follow_in_action = false;
let lineSensors = [0, 0]
let lightSensors = [0, 0]
let reverse_motor = 1
// turn motor power off
// stop()
/**
* return current power setting of the left motor
*/
export function leftPower() {
return motorPowerLeft
}
/**
* return current power setting of the right motor
*/
export function rightPower() {
return motorPowerRight
}
/**
* Reads left or right motor power
* @param which left or right
*/
//% blockId="gigglebot_read_motor_power" block="%which| power"
//% advanced=true
//% weight=80
export function readMotorPower(which: gigglebotWhichUniqueMotor): number {
if (which == gigglebotWhichUniqueMotor.Left)
return motorPowerLeft
if (which == gigglebotWhichUniqueMotor.Right)
return motorPowerRight
return 0
}
/**
* Assigns a new power value to the left motor
* Values from 101 through 127, and -128 through -101 are used to float the motor.
* @param leftpower new value for the power setting of the left motor (-100 < leftpower < 100)
*/
export function setLeftPower(leftpower: number){
motorPowerLeft = leftpower * reverse_motor
}
/**
* Assigns a new power value to the right motor
* Values from 101 through 127, and -128 through -101 are used to float the motor.
* @param rightpower new value for the power setting of the right motor. (-100 < rightpower < 100)
*/
//% rightpower.min= -100 rightpower.max = 100
export function setRightPower(rightpower: number) {
motorPowerRight = rightpower * reverse_motor
}
/**
* Follows a line that is thicker than the space between the two sensors
* The robot will stop when both of its sensors will detect white
*/
function followLine(type_of_line: gigglebotLineType, max_attempts: number = 3) {
let all_white = false
let attempt = 0
driveStraight(gigglebotWhichDriveDirection.Forward)
while (!(all_white) && line_follow_in_action) {
lineSensors = lineSensorsRaw()
// test if robot is over white
if (lineTest(gigglebotLineColor.White)) {
attempt = attempt + 1
if (attempt >= max_attempts) {
all_white = true // gets us out of the loop
stop() // stops and sets line_follow_in_action to false
} else {
// serial.writeLine("move around a bit")
// attempt to get out of bright spot
driveStraight(gigglebotWhichDriveDirection.Forward)
basic.pause(5)
}
// robot is seeing at least one black reading
} else {
attempt = 0
// test if two black readings
if (lineTest(gigglebotLineColor.Black)) {
driveStraight(gigglebotWhichDriveDirection.Forward)
} else if (lineSensors[0] < line_follower_threshold) {
/* left sensor reads black, right sensor reads white */
if (type_of_line == gigglebotLineType.Thick){
turn(gigglebotWhichTurnDirection.Right)
} else {
turn(gigglebotWhichTurnDirection.Left)
}
} else if (lineSensors[1] < line_follower_threshold) {
/* right sensor reads black, left sensor reads white */
if (type_of_line == gigglebotLineType.Thick){
turn(gigglebotWhichTurnDirection.Left)
} else {
turn(gigglebotWhichTurnDirection.Right)
}
}
// play well with others
basic.pause(20)
}
}
}
/**
* Configures the Distance Sensor.
* must be called before doing any distance sensor readings.
* Called automatically when calling the distance sensor blocks
*/
function distanceSensorConfigure() {
distanceSensor.init()
// set to long range (about 2.3 meters)
// set final range signal rate limit to 0.1 MCPS (million counts per second)
distanceSensor.setSignalRateLimitRaw(12) // 0.1 * (1 << 7) = 12.8
distanceSensor.setVcselPulsePeriod(distanceSensor.vcselPeriodPreRange(), 18)
distanceSensor.setVcselPulsePeriod(distanceSensor.vcselPeriodFinalRange(), 14)
distanceSensor.startContinuous(0)
distanceSensorInitDone = true
}
////////////////////////////////////////////////////////////////////////
////////// BLOCKS
///////////////////////////////////////////////////////////////////////
/**
* Will invert the power sent to the motors to get a different behavior.
* Call this block once in the OnStart block.
*/
//% blockId="gigglebotInvert" block="invert motors"
//% weight=100
export function invertMotors() {
reverse_motor = -1 * reverse_motor
}
/**
* Will let GiggleBot move forward or backward for a number of milliseconds.
* Distance covered during that time is related to the freshness of the batteries.
* @param dir forward or backward;
* @param delay for how many milliseconds; eg: 1000
*/
//% blockId="gigglebotDriveMillisec" block="drive %dir|for %delay|ms"
//% weight=98
//% delay.min=0
export function driveMillisec(dir: gigglebotWhichDriveDirection, delay: number) {
if (delay < 0) delay = 0
driveStraight(dir)
basic.pause(delay)
stop()
}
/**
* Will make GiggleBot turn left and right for a number of milliseconds. How far it turns depends on the freshness of the batteries.
* @param turn_dir turning left or right
* @param delay for how many milliseconds; eg: 1000
*/
//% blockId="gigglebotTurnMillisec" block="turn %turn_dir|for %delay|ms"
//% weight=96
//% delay.min=0
export function turnMillisec(turn_dir: gigglebotWhichTurnDirection, delay: number) {
if (delay < 0) delay = 0
turn(turn_dir)
basic.pause(delay)
stop()
}
/**
* GiggleBot will spin on itself for the provided number of milliseconds, like a turn but staying in the same spot. Especially useful when drawing
* @param turn_dir turning left or right
* @param delay how many milliseconds; eg: 1000
*/
//% blockId="gigglebotSpinMillisec" block="spin %turn_dir|for %delay|ms"
//% weight=94
//% delay.min=0
export function spinMillisec(turn_dir: gigglebotWhichTurnDirection, delay: number) {
if (delay < 0) delay = 0
gigglebotSpin(turn_dir)
basic.pause(delay)
stop()
}
/**
* GiggleBot will drive forward while steering to one side for the provided number of milliseconds.
* Useful when it needs to go around an obstacle, or orbit around an object.
* 0% means no steering, the same as the 'drive' block. 100% is the same as the 'turn' block.
* @param percent the variation in power between left and right; eg: 0, 20, 50, 100
* @param dir which direction to steer, left or right
* @param delay for how many milliseconds; eg: 1000
* */
//% blockId="gigglebotSteerMillisec" block="steer %percent| towards the %dir| for %delay| ms"
//% percent.min=0 percent.max=100
//% weight=92
export function steerMillisec(percent: number, dir: gigglebotWhichTurnDirection, delay: number) {
if (delay < 0) delay = 0
if (percent < 0) percent = 0
if (percent > 100) percent = 100
steer(percent, dir)
basic.pause(delay)
stop()
}
/**
* Will let GiggleBot move forward or backward until told otherwise (either by a stop block or a turn block).
* @param dir forward or backward
*/
//% blockId="gigglebot_drive_straight" block="drive %dir"
//% weight=89
export function driveStraight(dir: gigglebotWhichDriveDirection) {
let dir_factor = 1
if (dir == gigglebotWhichDriveDirection.Backward) {
dir_factor = -1
}
if (dir == gigglebotWhichDriveDirection.Forward) {
dir_factor = 1
}
motorPowerAssignBoth(motorPowerLeft * dir_factor, motorPowerRight * dir_factor)
}
/**
* Will make GiggleBot turn left or right until told otherwise (by a stop block or a drive block).
*/
//% blockId="gigglebotTurn" block="turn %turn_dir"
//% weight=88
export function turn(turn_dir: gigglebotWhichTurnDirection) {
if (turn_dir == gigglebotWhichTurnDirection.Left) {
motorPowerAssignBoth(0, motorPowerRight)
}
else {
motorPowerAssignBoth(motorPowerLeft, 0)
}
}
/**
* GiggleBot will spin on itself until told otherwise, like a turn but staying in the same spot. Especially useful when drawing.
* @param turn_dir left or right;
*/
//% blockId="gigglebotSpin" block="spin %turn_dir"
//% weight=87
export function gigglebotSpin(turn_dir: gigglebotWhichTurnDirection) {
if (turn_dir == gigglebotWhichTurnDirection.Left) {
motorPowerAssignBoth(-1 * motorPowerLeft, motorPowerRight)
}
else {
motorPowerAssignBoth(motorPowerLeft, -1 * motorPowerRight)
}
}
/**
* GiggleBot will drive forward while steering to one side.
* Useful when it needs to go around an obstacle, or orbit around an object.
* 0% means no steering, the same as the 'drive' block. 100% is the same as the 'turn' block.
* @param percent value between 0 and 100 to control the amount of steering
* @param dir to the left or to the right
*/
//% blockId="gigglebotSteer" block="steer %percent| towards the %dir"
//% percent.min=0 percent.max=100
//% weight=86
export function steer(percent: number, dir: gigglebotWhichTurnDirection) {
percent = Math.min(Math.max(percent, 0), 100)
let correctedMotorPowerLeft = motorPowerLeft
let correctedMotorPowerRight = motorPowerRight
if (dir == gigglebotWhichTurnDirection.Left) {
correctedMotorPowerLeft = motorPowerLeft - Math.idiv(motorPowerLeft * percent, 100)
correctedMotorPowerRight = motorPowerRight + Math.idiv(motorPowerRight * percent, 100)
} else {
correctedMotorPowerLeft = motorPowerLeft + Math.idiv(motorPowerLeft * percent, 100)
correctedMotorPowerRight = motorPowerRight - Math.idiv(motorPowerRight * percent, 100)
}
motorPowerAssignBoth(correctedMotorPowerLeft, correctedMotorPowerRight)
}
/**
* stops the robot.
*/
//% blockId="gigglebot_stop" block="stop"
//% weight=70
export function stop() {
motorPowerAssign(gigglebotWhichMotor.Both, 0)
light_follow_in_action = false
line_follow_in_action = false
}
/**
* This allows the user to correct the motors on the GiggleBot if it's not driving straight
* @param dir: if the GiggleBot drives to the left, then correct to the right. Vice versa.
* @param trim_value: a correction value between 0 and 100, but most likely below 10
*/
//% blockId="gigglebot_trim_main" block="correct towards %dir|by %trim_value"
//% weight=60
export function motorTrimSetMain(dir: gigglebotWhichTurnDirection, trim_value: number) {
motorTrimSet(dir, trim_value)
}
/**
* You can set the speed for each individual motor or both together. The higher the speed the less control the robot has.
* You may need to correct the robot (see block in "more..." section). A faster robot needs more correction than a slower one.
* Note that any drive correction done previously gets applied here.
* If you want to follow a line, it will work best at a lower speed.
* Actual speed is dependent on the freshness of the batteries.
* @param motor: left, right or both motors
* @param speed: how fast the robot goes.
*/
//% blockId="gigglebot_set_speed" block="set %motor | speed to %speed"
//% speed.min=-100 speed.max=100
//% weight=60
export function setSpeed(motor: gigglebotWhichMotor, speed: gigglebotWhichSpeed) {
speed = Math.min(Math.max(speed, -100), 100)
currentMotorPower = speed
motorPowerLeft = currentMotorPower
motorPowerRight = currentMotorPower
// apply trim
if (trimRight != 0 && motor != gigglebotWhichMotor.Left) {
if (speed > 0) {
motorPowerRight = currentMotorPower - Math.idiv(trimRight * currentMotorPower, 100);
} else {
motorPowerRight = currentMotorPower + Math.idiv(trimRight * currentMotorPower, 100);
}
}
if (trimLeft != 0 && motor != gigglebotWhichMotor.Right) {
if (speed > 0) {
motorPowerLeft = currentMotorPower - Math.idiv(trimLeft * currentMotorPower, 100);
} else {
motorPowerLeft = currentMotorPower + Math.idiv(trimLeft * currentMotorPower, 100);
}
}
}
///////////////////////////////////////////////////////////////////////
/////////// LINE FOLLOWER BLOCKS
///////////////////////////////////////////////////////////////////////
/**
* A javascript method to change the line follower threshold.
* Not exposed as a block
*/
export function setLineFollowerThreshold(newThreshold: number) {
line_follower_threshold = newThreshold
}
/**
* A thin black line would fall between the two sensors. The GiggleBot will stop when both sensors are reading black.
* A thick black line would have the two sensors on top of it at all times. The GiggleBot will stop when both sensors are reading white.
* Calling this block puts the GiggleBot into "Line Follower Mode". To exit "Line Follower Mode" you need to call the "stop" block.
* @param type_of_line thin line or thick line
* @param specific_line_threshold overwrite the default line threshold to adapt to your particular tape and lighting condition. Default is 175.
*/
//% group="Line Follower"
//% blockId="gigglebot_follow_line" block="follow a %type_of_line| black line"
//% weight=50
export function lineFollow(type_of_line: gigglebotLineType, specific_line_threshold: number = 200) {
// test if the line follower is already in action in case this was put
// in a loop. Only launch one in background
if (!line_follow_in_action) {
line_follow_in_action = true
light_follow_in_action = false // mutually exclusive
line_follower_threshold = specific_line_threshold
control.inBackground( () => {
followLine(type_of_line)
if (line_follow_in_action){
stop()
}
})
}
}
/**
* True if robot is currently following a line.
* False otherwise
*/
//% group="Line Follower"
//% blockId="gigglebot_follow_line_status" block="following line"
//% weight= 47
export function lineFollowStatus() : boolean {
return (line_follow_in_action)
}
/**
* Will return true if the whole line sensor is reading either black or white.
* @param color: black or white
*/
//% blockId="gigglebot_test_line" block="%which|line is detected"
//% advanced=true
//% weight=90
//% group="Line Follower"
export function lineTest(color: gigglebotLineColor): boolean {
lineSensorsRaw()
for (let _i = 0; _i < lineSensors.length; _i++) {
if (color == gigglebotLineColor.Black && lineSensors[_i] > line_follower_threshold) {
return false
}
if (color == gigglebotLineColor.White && lineSensors[_i] < line_follower_threshold) {
return false
}
}
return true
}
/**
* Reads left or right line sensor
* @param which left or right
*/
//% blockId="gigglebot_read_line_sensors" block="%which|line sensor"
//% advanced=true
//% weight=80
//% group="Line Follower"
export function lineReadSensor(which: gigglebotWhichTurnDirection): number {
lineSensorsRaw()
return lineSensors[which]
}
///////////////////////////////////////////////////////////////////////
/////////// LIGHT SENSOR BLOCKS
///////////////////////////////////////////////////////////////////////
/**
* Will follow a spotlight shone on its eyes. The GiggleBot will stop following
* a light when it detects it is in darkness. It will not automatically
* restart following a light once it leaves darkness
* Using javascript, you can switch to light avoiding mode by changing the first
* parameter to "gigglebotLightFollowMode.Avoid"
* @param mode either follow or avoid light
* @param sensitivity how much of a difference between the two sides is needed for GiggleBot to react; eg: 20
* @param light_threshold how much light is needed to consider the loop needs to end. This can happen when a light following robot is covered with a box; eg: 10
*/
//% blockId="gigglebot_follow_light" block="follow light"
//% group="Light Sensors"
//% weight=80
export function lightFollow(mode: gigglebotLightFollowMode = gigglebotLightFollowMode.Follow,
sensitivity: number = 20,
light_threshold: number = 10) {
// test if the light follower is already in action in case this was put
// in a loop. Only launch one in background
if ( ! light_follow_in_action) {
light_follow_in_action = true
line_follow_in_action = false // mutually exclusive
let giveup_count = 0;
control.inBackground( () => {
while ( light_follow_in_action && giveup_count < 5) {
lightSensors = lightSensorsRaw()
if (lightSensors[0] > lightSensors[1] + sensitivity) {
// it's brighter to the right
if (mode == gigglebotLightFollowMode.Follow){
turn(gigglebotWhichTurnDirection.Right)
} else {
turn(gigglebotWhichTurnDirection.Left)
}
} else if (lightSensors[1] > lightSensors[0] + sensitivity) {
// it's brighter to the left
if (mode == gigglebotLightFollowMode.Follow){
turn(gigglebotWhichTurnDirection.Left)
} else {
turn(gigglebotWhichTurnDirection.Right)
}
} else {
driveStraight(gigglebotWhichDriveDirection.Forward)
}
if (mode == gigglebotLightFollowMode.Follow &&
lightSensors[0] < light_threshold &&
lightSensors[1] < light_threshold) {
giveup_count = giveup_count + 1
}
else if (mode == gigglebotLightFollowMode.Avoid &&
lightSensors[0] > 1000 - light_threshold &&
lightSensors[1] > 1000 - light_threshold) {
giveup_count = giveup_count + 1
}
else {
// must have consecutive readings before giving up
giveup_count = 0
}
// play well with others
basic.pause(20);
}
// If we're still in light following mode, then stop
// It's possible that stop() was called elsewhere
if (light_follow_in_action){
stop()
}
})
}
}
/**
* Will orient the GiggleBot towards a light, just once.
* To do a light following robot, this block needs to be inserted in a loop.
* You control when the loop ends.
* @param diff the difference between the two sensors that will trigger a reaction; eg: 50
* @param delay how long in milliseconds to turn for before stopping; eg: 200
*
*/
//% blockId="gigglebot_orient_light" block="turn %dir light"
//% group="Light Sensors"
//% weight=80
export function lightOrient(dir: gigglebotTowardsAway = gigglebotTowardsAway.Towards, diff: number = 50, delay: number = 200) {
let current_lights = lightSensorsRaw()
if (current_lights[0] > current_lights[1] + diff) {
// it's brighter to the right
if (dir == gigglebotTowardsAway.Towards){
turn(gigglebotWhichTurnDirection.Right)
}
else{
turn(gigglebotWhichTurnDirection.Left)
}
}
else if (current_lights[1] > current_lights[0] + diff) {
// it's brighter to the left
if (dir == gigglebotTowardsAway.Towards){
turn(gigglebotWhichTurnDirection.Left)
}
else {
turn(gigglebotWhichTurnDirection.Right)
}
}
else {
stop()
}
basic.pause(delay)
stop()
}
/**
* True if robot is currently following light.
* False otherwise
*/
//% group="Light Sensors"
//% blockId="gigglebot_follow_light_status" block="following light"
//% weight= 70
export function lightFollowStatus() : boolean {
return (light_follow_in_action)
}
/**
* Will return true if both light sensors are detecting bright light, or darkness.
* @param level: bright or darness
* @param threshold: how sensitive the detection will be. The smaller the number, the less sensitive it will be.
*/
//% blockId="gigglebot_test_light" block="%level| is detected"
//% advanced=true
//% weight=90
//% group="Light Sensors"
export function lightTest(level: gigglebotLightLevel, threshold: number = 10 ): boolean {
lightSensorsRaw()
for (let _i = 0; _i < lightSensors.length; _i++) {
// if we're lookin for darkness and one of the sensor is above the threshold,
// then we don't have darkness
if (level == gigglebotLightLevel.Darkness && lightSensors[_i] > threshold) {
return false
}
// if we're looking for brightness and one of the sensors is below the threshold,
// then we don't have brightness
// while the sensor reads theoretically up to 1023, in practice a bright environment is over 900
if (level == gigglebotLightLevel.Brightness && lightSensors[_i] < (900-threshold)) {
return false
}
}
return true
}
/**
* Reads left or right light sensor.
* The light sensors are placed in front of each eye neopixel, they're tiny!
* The range is 0 through 1023, although in reality rarely above ~950.
* @param which left or right
*/
//% blockId="gigglebot_read_light_sensors" block="%which|light sensor"
//% advanced=true
//% weight=80
//% group="Light Sensors"
export function lightReadSensor(which: gigglebotWhichTurnDirection): number {
lightSensorsRaw()
return lightSensors[which]
}
////////////////////////////////////////////////////////////////////////
/////////// DISTANCE SENSOR
////////////////////////////////////////////////////////////////////////
/**
* Get a reading of how far an obstacle is from the distanse sensor.
*/
//% blockId="distanceSensorReadRangeContinuous" block="distance to obstacle (mm)"
//% advanced=true
//% group="Distance Sensor (Add-On)"
export function distanceSensorReadRangeContinuous(): number {
if (distanceSensorInitDone == false) {
distanceSensorConfigure()
}
return distanceSensor.readRangeContinuousMillimeters()
}
/**
* Test for the presence of an obstacle.
* @param inequality less than or more than, closer than or farther than
* @param dist how many millimeters; eg: 100
*/
//% blockId="distanceSensorTestForObstacle" block="obstacle is %inequality| %dist| mm"
//% group="Distance Sensor (Add-On)"
//% weight=30
export function distanceSensorTestForObstacle(inequality: gigglebotInequality, dist: number): boolean {
if (distanceSensorInitDone == false) {
distanceSensorConfigure()
}
if (inequality == gigglebotInequality.Closer) {
if (distanceSensor.readRangeContinuousMillimeters() < dist) {
return true
}
else {
return false
}
}
else if (inequality == gigglebotInequality.Farther) {
if (distanceSensor.readRangeContinuousMillimeters() > dist) {
return true
}
else {
return false
}
}
return false
}
/**
* Distance Sensor: takes a single reading.
*/
export function distanceSensorReadRangeSingle(): number {
if (distanceSensorInitDone == false) {
distanceSensorConfigure()
}
return distanceSensor.readRangeSingleMillimeters()
}
/////////// SERVO BLOCKS
/**
* Positions a servo motor to a specified position
* @param which left or right servo
* @param degree which position, from 0 to 180
*/
//% blockId="gigglebot_servo" block="set %which|servo to |%degree"
//% group="Servo"
//% degree.min=0 degree.max=180
export function servoMove(which: gigglebotServoAction, degree: number) {
if (which == gigglebotServoAction.Right) {
pins.servoWritePin(AnalogPin.P13, degree)
}
else if (which == gigglebotServoAction.Left) {
pins.servoWritePin(AnalogPin.P14, degree)
}
else if (which == gigglebotServoAction.Both) {
pins.servoWritePin(AnalogPin.P13, degree)
pins.servoWritePin(AnalogPin.P14, degree)
}
else if (which == gigglebotServoAction.Mirror) {
pins.servoWritePin(AnalogPin.P13, degree)
pins.servoWritePin(AnalogPin.P14, 180 - degree)
}
}
///////////////////////////////////////////////////////////////////////
/////////// THP SENSOR
///////////////////////////////////////////////////////////////////////
/**
* Get a temperature reading from the Temp/Humidity/Pressure sensor
*/
//% group="Temperature Humidity Pressure (Add-On)"
//% blockId="gigglebot_temperature" block="temperature in %scale"
export function temperature(scale: gigglebotTempScale): number {
if (thpSensorInitDone == false)
{
TempHumPressSensor.initialize()
thpSensorInitDone = true
}
let temp = TempHumPressSensor.read_temperature()
if (scale == gigglebotTempScale.Celsius) {
return (Math.round(temp))
}
else {
return (Math.round((temp * 1.8)+32))
}
}
/**
* Get an atmospheric humidity reading from the Temp/Humidity/Pressure sensor
*/
//% group="Temperature Humidity Pressure (Add-On)"
//% blockId="gigglebot_humidity" block="humidity"
export function humidity(): number {
if (thpSensorInitDone == false)
{
TempHumPressSensor.initialize()
thpSensorInitDone = true
}
return Math.round(TempHumPressSensor.read_humidity())
}
/**
* Get an atmospheric pressure reading from the Temp/Humidity/Pressure sensor
*/
//% group="Temperature Humidity Pressure (Add-On)"
//% blockId="gigglebot_pressure" block="pressure in %pressureScale"
export function pressure(pressureScale: gigglebotPressureScale): number {
// call to read_temperature() to udpate temperature compensation
TempHumPressSensor.read_temperature()
if (thpSensorInitDone == false)
{
TempHumPressSensor.initialize()
thpSensorInitDone = true
}
let p = TempHumPressSensor.read_pressure()
if (pressureScale == gigglebotPressureScale.Pascal) {
return Math.round(p)
}
else {
return Math.round(p * 0.0002953)
}
}
/**
* Read Dew Point
*/
//% group="Temperature Humidity Pressure (Add-On)"
//% blockId="gigglebot_dewpoint" block="dew point in %scale"
//% advanced=true
export function dewPoint(scale: gigglebotTempScale): number {
if (thpSensorInitDone == false)
{
TempHumPressSensor.initialize()
thpSensorInitDone = true
}
if (scale == gigglebotTempScale.Celsius) {
return Math.round(TempHumPressSensor.read_dewpoint())
}
else {
return Math.round(TempHumPressSensor.read_dewpoint() * 1.8 + 32)
}
}
///////////////////////////////////////////////////////////////////////
/////////// MORE BLOCKS
///////////////////////////////////////////////////////////////////////
/**
* This allows the user to correct the motors on the GiggleBot if it's not driving straight
* @param dir: if the GiggleBot drives to the left, then correct to the right. Vice versa.
* @param trim_value: a correction value between 0 and 100, but most likely below 10
*/
//% blockId="gigglebot_trim" block="correct towards %dir|by %trim_value"
//% weight=100
//% advanced=true
export function motorTrimSet(dir: gigglebotWhichTurnDirection, trim_value: number) {
if (trim_value < 0) {
trim_value = 0
}
if (dir == gigglebotWhichTurnDirection.Left) {
trimLeft = trim_value
trimRight = 0
}
if (dir == gigglebotWhichTurnDirection.Right) {
trimRight = trim_value
trimLeft = 0
}
if (motorPowerLeft > 0){
motorPowerLeft = currentMotorPower - Math.idiv(trimLeft * currentMotorPower, 100)
} else {
motorPowerLeft = currentMotorPower + Math.idiv(trimLeft * currentMotorPower, 100)
}
if (motorPowerRight > 0) {
motorPowerRight = currentMotorPower - Math.idiv(trimRight * currentMotorPower, 100)
} else {
motorPowerRight = currentMotorPower + Math.idiv(trimRight * currentMotorPower, 100)
}
}
/**
* Assigns power to a motor, or the same power to both motors
* Values from 101 through 127, and -128 through -101 are used to float the motor.
* @param motor: left or right motor, or both
* @param power: a value between -100 and 100
*/
//% blockId="gigglebot_set_motor" block="set power on %motor| to | %power"
//% advanced=true
//% weight=90
export function motorPowerAssign(motor: gigglebotWhichMotor, power: number) {
let buf = pins.createBuffer(3)
buf.setNumber(NumberFormat.UInt8BE, 0, gigglebotI2CCommands.SET_MOTOR_POWER)
buf.setNumber(NumberFormat.UInt8BE, 2, power * reverse_motor)
// activate right motor
if (motor == gigglebotWhichMotor.Right) {
buf.setNumber(NumberFormat.UInt8BE, 1, 0x01)
}
// activate left motor
else if (motor == gigglebotWhichMotor.Left) {
buf.setNumber(NumberFormat.UInt8BE, 1, 0x02)
}
// activate both motors
else if (motor == gigglebotWhichMotor.Both) {
buf.setNumber(NumberFormat.UInt8BE, 1, 0x03)
}
pins.i2cWriteBuffer(ADDR, buf, false);
}
/**
* Assigns potentially different powers to both motors in one call.
* Values from 101 through 127, and -128 through -101 are used to float the motor.
* @param left_power: the power to assign to the left motor (between -100 and 100)
* @param right_power: the power to assign to the right motor (between -100 and 100)
*/
//% blockId="gigglebot_set_motors" block="set left power to %left_power|and right to | %right_power"
//% advanced=true
//% weight=90
export function motorPowerAssignBoth(left_power: number, right_power: number) {
let buf = pins.createBuffer(3)
buf.setNumber(NumberFormat.UInt8BE, 0, gigglebotI2CCommands.SET_MOTOR_POWERS)
buf.setNumber(NumberFormat.UInt8BE, 1, right_power * reverse_motor)
buf.setNumber(NumberFormat.UInt8BE, 2, left_power * reverse_motor)
pins.i2cWriteBuffer(ADDR, buf, false);
}
//% blockId="gigglebot_get_firmware" block="firmware version number"
//% advanced=true
//% weight=10
//% group="Firmware"
export function firmwareVersion(): number {
/**
* returns the firmware version that is installed.