@tigerpython/robotics-libraries 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG +68 -0
  2. package/LICENSE +373 -0
  3. package/README.md +81 -0
  4. package/calliope/README.md +15 -0
  5. package/calliope/callibot.py +176 -0
  6. package/calliope/callibotmot.py +46 -0
  7. package/calliope/callimk.py +143 -0
  8. package/calliope/cbalarm.py +14 -0
  9. package/calliope/cpglow.py +76 -0
  10. package/calliope/cpmike.py +16 -0
  11. package/calliope/cprover.py +33 -0
  12. package/calliope/cputils.py +23 -0
  13. package/calliope/libraries.json +10 -0
  14. package/calliope/libraries.raw.json +10 -0
  15. package/calliope/min/callibot.py +97 -0
  16. package/calliope/min/callibotmot.py +23 -0
  17. package/calliope/min/callimk.py +47 -0
  18. package/calliope/min/cbalarm.py +6 -0
  19. package/calliope/min/cpglow.py +29 -0
  20. package/calliope/min/cpmike.py +8 -0
  21. package/calliope/min/cprover.py +9 -0
  22. package/calliope/min/cputils.py +7 -0
  23. package/dist/index.d.mts +124 -0
  24. package/dist/index.d.ts +124 -0
  25. package/dist/index.js +2896 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/index.mjs +2862 -0
  28. package/dist/index.mjs.map +1 -0
  29. package/microbit/README.md +48 -0
  30. package/microbit/controller.py +212 -0
  31. package/microbit/huskylens.py +479 -0
  32. package/microbit/libraries.json +19 -0
  33. package/microbit/libraries.raw.json +19 -0
  34. package/microbit/mbalarm.py +15 -0
  35. package/microbit/mbbitbot.py +127 -0
  36. package/microbit/mbglow.py +77 -0
  37. package/microbit/mbled.py +56 -0
  38. package/microbit/mbmarsrover.py +216 -0
  39. package/microbit/mbminibit.py +139 -0
  40. package/microbit/mbrobot.py +401 -0
  41. package/microbit/mbrobot_legacy.py +90 -0
  42. package/microbit/mbrobot_plus.py +179 -0
  43. package/microbit/mbrobot_plusV2.py +490 -0
  44. package/microbit/mbrobot_plusV3.py +427 -0
  45. package/microbit/mbrobotmot.py +49 -0
  46. package/microbit/mbthetabot.py +167 -0
  47. package/microbit/mbwait.py +50 -0
  48. package/microbit/mbxgo.py +173 -0
  49. package/microbit/min/controller.py +42 -0
  50. package/microbit/min/huskylens.py +145 -0
  51. package/microbit/min/mbalarm.py +6 -0
  52. package/microbit/min/mbbitbot.py +40 -0
  53. package/microbit/min/mbglow.py +29 -0
  54. package/microbit/min/mbled.py +18 -0
  55. package/microbit/min/mbmarsrover.py +62 -0
  56. package/microbit/min/mbminibit.py +50 -0
  57. package/microbit/min/mbrobot.py +82 -0
  58. package/microbit/min/mbrobot_legacy.py +45 -0
  59. package/microbit/min/mbrobot_plus.py +75 -0
  60. package/microbit/min/mbrobot_plusV2.py +102 -0
  61. package/microbit/min/mbrobot_plusV3.py +194 -0
  62. package/microbit/min/mbrobotmot.py +25 -0
  63. package/microbit/min/mbthetabot.py +47 -0
  64. package/microbit/min/mbwait.py +23 -0
  65. package/microbit/min/mbxgo.py +37 -0
  66. package/package.json +54 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,2862 @@
1
+ // calliope/libraries.json
2
+ var libraries_default = {
3
+ cbalarm: "import music\n_g1=['c6:1','r','c6,1','r','r','r']\ndef setAlarm(on):\n if on:music.play(_g1,wait=False,loop=True)\n else:music.stop()\ndef beep():music.pitch(2000,200,wait=False)",
4
+ cprover: "from calliope_mini import pin28,pin29,pin30\ndef forward():pin28.write_analog(v);pin29.write_digital(1);pin30.write_digital(1)\ndef left():pin28.write_analog(v);pin29.write_digital(0);pin30.write_digital(1)\ndef right():pin28.write_analog(v);pin29.write_digital(1);pin30.write_digital(0)\ndef stop():pin28.write_digital(0)\ndef move():left()\ndef rewind():right()\ndef setSpeed(speed):global v;v=int(speed/100*1023)\nsetSpeed(100)",
5
+ callimk: "import gc\nfrom calliope_mini import i2c,sleep\ni2c.init()\n_g1=30\n_g2=.09\ndef w(d1,d2,s1,s2):i2c.write(16,bytearray([0,d1,s1]));i2c.write(16,bytearray([2,d2,s2]))\ndef forward():w(0,0,_g1,_g1)\ndef backward():w(1,1,_g1,_g1)\ndef stop():w(0,0,0,0)\ndef right():w(0 if _g1>0 else 1,1 if _g1>0 else 0,_g1,_g1)\ndef left():w(1 if _g1>0 else 0,0 if _g1>0 else 1,_g1,_g1)\ndef rightArc(r):\n A=abs(_g1)\n if r<_g2:B=0\n else:C=(r-_g2)/(r+_g2)*(1-A*A/200000);B=int(C*A)\n if _g1>0:w(0,0,A,B)\n else:w(1,1,B,A)\ndef leftArc(r):\n A=abs(_g1)\n if r<_g2:B=0\n else:C=(r-_g2)/(r+_g2)*(1-A*A/200000);B=int(C*A)\n if _g1>0:w(0,0,B,A)\n else:w(1,1,A,B)\ndef setSpeed(speed):\n A=speed;global _g1\n if A<15:_g1=15\n else:_g1=A\ndef motorL(dir,speed):i2c.write(16,bytearray([0,dir,speed]))\ndef motorR(dir,speed):i2c.write(16,bytearray([2,dir,speed]))\ndef led(right_left,on_off):\n A=bytearray(2)\n if right_left==0:A[0]=11\n else:A[0]=12\n A[1]=on_off;i2c.write(16,A)\ndef setLEDLeft(on):led(1,on)\ndef setLEDRight(on):led(0,on)\ndef setLED(on):led(1,on);led(0,on)\ndef rgbLED(red,green,blue):A=bytearray(2);A[0]=24;A[1]=red;B=bytearray(2);B[0]=25;B[1]=green;C=bytearray(2);C[0]=26;C[1]=blue;i2c.write(16,A);i2c.write(16,B);i2c.write(16,C)\ndef getDistance():i2c.write(16,bytearray([40]));sleep(20);A=i2c.read(16,2);B=A[0]<<8|A[1];return B\ndef irLeftValue():i2c.write(16,bytearray([29]));A=i2c.read(16,1)[0];return 0 if A&1!=0 else 1\ndef irRightValue():i2c.write(16,bytearray([29]));A=i2c.read(16,1)[0];return 0 if A&2!=0 else 1\ndef setServo(S,Angle):\n if S=='S1':A=20\n if S=='S2':A=21\n i2c.write(16,bytearray([A,Angle]))\nexit=stop\ndelay=sleep",
6
+ cpglow: `from calliope_mini import*
7
+ _g1=0
8
+ _g2=0
9
+ _g3=0
10
+ _g4=50
11
+ _g5=True
12
+ _g6=False
13
+ def makeGlow():global _g6;display.set_pixel(2,2,9);_g6=True
14
+ def clear():display.clear()
15
+ def forward():_f1(1)
16
+ def back():_f1(-1)
17
+ def right(angle):global _g3;_g3=(_g3+angle)%360
18
+ def left(angle):right(-angle)
19
+ def setPos(x,y):global _g1,_g2;_g1=x;_g2=y;_f2()
20
+ def getPos():return _g1,_g2
21
+ def setSpeed(speed):global _g4;_g4=speed
22
+ def showTrace(enable):global _g5;_g5=enable
23
+ def isLit():return display.get_pixel(_g1+2,4-(_g2+2))==9
24
+ def _f1(s):
25
+ global _g1,_g2;sleep(2000-_g4*20);d=_g3//45
26
+ if d in[1,2,3]:_g1+=s
27
+ if d in[5,6,7]:_g1-=s
28
+ if d in[0,1,7]:_g2+=s
29
+ if d in[3,4,5]:_g2-=s
30
+ _f2()
31
+ def _f2():
32
+ if not _g6:print('Use "makeGlow()" to create a Glow.');raise Exception('Glow not initialized.')
33
+ if not _g5:display.clear()
34
+ if-2<=_g1<=2 and-2<=_g2<=2:display.set_pixel(_g1+2,4-(_g2+2),9)`,
35
+ callibotmot: "import gc\nfrom calliope_mini import i2c,sleep\nimport machine\nclass Motor:\n def __init__(A,id):A._id=id\n def _f2(B,d,s):\n if B._id==0:A=0\n else:A=2\n try:i2c.write(32,bytearray([A,d,s]))\n except:\n print('Please switch on mbRobot!')\n while True:0\n def rotate(B,s):\n A=abs(s);A=A+50\n if s>0:B._f2(0,A)\n elif s<0:B._f2(1,A)\n else:B._f2(0,0)\ndelay=sleep\ndef setLED(on):\n if on==1:i2c.write(33,bytearray([0,3]))\n else:i2c.write(33,bytearray([0,0]))\nmotL=Motor(0)\nmotR=Motor(2)",
36
+ callibot: "_B=True\n_A='Please switch on Robot!'\nimport gc\nfrom calliope_mini import i2c,sleep\n_g1=.06\ndef w(d1,d2,s1,s2):\n try:i2c.write(32,bytearray([0,d1,s1]));i2c.write(32,bytearray([2,d2,s2]))\n except:\n print(_A)\n while _B:0\ndef setSpeed(speed):global _g2;_g2=speed+40\ndef forward():w(0,0,_g2,_g2)\ndef backward():w(1,1,_g2,_g2)\ndef stop():w(0,0,0,0)\ndef right():A=int(_g2*1.1);w(0 if _g2>0 else 1,1 if _g2>0 else 0,A,A)\ndef left():A=int(_g2*1.1);w(1 if _g2>0 else 0,0 if _g2>0 else 1,A,A)\ndef rightArc(r):\n A=abs(_g2)\n if r<_g1:B=0\n else:C=(r-_g1)/(r+_g1)*(1-A*A/200000);B=int(C*A)\n if _g2>0:w(0,0,A,B)\n else:w(1,1,B,A)\ndef leftArc(r):\n A=abs(_g2)\n if r<_g1:B=0\n else:C=(r-_g1)/(r+_g1)*(1-A*A/200000);B=int(C*A)\n if _g2>0:w(0,0,B,A)\n else:w(1,1,A,B)\ndef setLEDLeft(on):\n try:i2c.write(33,bytearray([0,0]))\n except:\n print(_A)\n while _B:0\n if on==1:i2c.write(33,bytearray([0,1]))\n else:i2c.write(33,bytearray([0,0]))\ndef setLEDRight(on):\n try:i2c.write(33,bytearray([0,0]))\n except:\n print(_A)\n while _B:0\n if on==1:i2c.write(33,bytearray([0,2]))\n else:i2c.write(33,bytearray([0,0]))\ndef setLED(on):\n try:i2c.write(33,bytearray([0,0]))\n except:\n print(_A)\n while _B:0\n if on==1:i2c.write(33,bytearray([0,3]))\n else:i2c.write(33,bytearray([0,0]))\ndef irLeftValue():\n try:\n A=i2c.read(33,1)\n if A[0]==130 or A[0]==131:return 1\n else:return 0\n except:\n print(_A)\n while _B:0\ndef irRightValue():\n try:\n A=i2c.read(33,1)\n if A[0]==129 or A[0]==131:return 1\n else:return 0\n except:\n print(_A)\n while _B:0\ndef getDistance():\n try:A=i2c.read(33,3);B=(256*A[1]+A[2])/10;return B\n except:\n print(_A)\n while _B:0\ndef tsValue():\n try:\n A=i2c.read(33,1)\n if A[0]==140 or A[0]==143:return 1\n else:return 0\n except:\n print(_A)\n while _B:0\ndef tsLeftValue():\n try:\n A=i2c.read(33,1)\n if A[0]==136 or A[0]==139:return 1\n else:return 0\n except:\n print(_A)\n while _B:0\ndef tsRightValue():\n try:\n A=i2c.read(33,1)\n if A[0]==132 or A[0]==135:return 1\n else:return 0\n except:\n print(_A)\n while _B:0\nexit=stop\ndelay=sleep\n_g2=90",
37
+ cputils: "def cat(filename):\n with open(filename)as B:\n A=B.readline()\n while A:print(A[:-1]);A=B.readline()\nfrom math import asin,atan2,sqrt,degrees\ndef getPitch(a):A=atan2(a[1],a[2]);return int(degrees(A))\ndef getRoll(a):A=sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]);B=asin(a[0]/A);return int(degrees(B))",
38
+ cpmike: "from calliope_mini import pin3,running_time,sleep\n_g1=running_time()\ndef isClicked(level=10,rearm_time=500):\n A=False;global _g1\n if running_time()-_g1<rearm_time:sleep(10);return A\n B=pin3.read_analog()\n if B<518-level:_g1=running_time();return True\n return A"
39
+ };
40
+
41
+ // calliope/libraries.raw.json
42
+ var libraries_raw_default = {
43
+ cbalarm: "# cbalarm.py\nimport music\n\n_m = ['c6:1', 'r', 'c6,1', 'r', 'r', 'r']\n\ndef setAlarm(on):\n if on:\n music.play(_m, wait = False, loop = True) \n else:\n music.stop()\n \n \ndef beep():\n music.pitch(2000, 200, wait = False)",
44
+ cprover: "# cprover.py\n \nfrom calliope_mini import pin28, pin29, pin30\n\ndef forward():\n pin28.write_analog(v)\n pin29.write_digital(1)\n pin30.write_digital(1)\n\ndef left():\n pin28.write_analog(v)\n pin29.write_digital(0)\n pin30.write_digital(1)\n\ndef right():\n pin28.write_analog(v)\n pin29.write_digital(1)\n pin30.write_digital(0)\n\ndef stop():\n pin28.write_digital(0)\n\ndef move():\n left()\n\ndef rewind(): \n right()\n\ndef setSpeed(speed):\n global v\n v = int(speed / 100 * 1023)\n\nsetSpeed(100)\n",
45
+ callimk: '# callimk.py (motionkit2)\nimport gc\nfrom calliope_mini import i2c, sleep\ni2c.init()\n_v = 30\n_axe = 0.09\n\n\ndef w(d1, d2, s1, s2):\n i2c.write(0x10, bytearray([0x00, d1, s1]))\n i2c.write(0x10, bytearray([0x02, d2, s2]))\n\n\ndef forward():\n w(0, 0, _v, _v)\n\n\ndef backward():\n w(1, 1, _v, _v)\n\n\ndef stop():\n w(0, 0, 0, 0)\n\n\ndef right():\n w(0 if _v > 0 else 1, 1 if _v > 0 else 0, _v, _v)\n\n\ndef left():\n w(1 if _v > 0 else 0, 0 if _v > 0 else 1, _v, _v)\n\n\ndef rightArc(r):\n v = abs(_v)\n if r < _axe:\n v1 = 0\n else:\n f = (r - _axe) / (r + _axe) * (1 - v * v / 200000)\n v1 = int(f * v)\n if _v > 0:\n w(0, 0, v, v1)\n else:\n w(1, 1, v1, v)\n\n\ndef leftArc(r):\n v = abs(_v)\n if r < _axe:\n v1 = 0\n else:\n f = (r - _axe) / (r + _axe) * (1 - v * v / 200000)\n v1 = int(f * v)\n if _v > 0:\n w(0, 0, v1, v)\n else:\n w(1, 1, v, v1)\n\n\ndef setSpeed(speed):\n global _v\n if speed < 15:\n _v = 15\n else:\n _v = speed\n\n\ndef motorL(dir, speed):\n i2c.write(0x10, bytearray([0x00, dir, speed]))\n\n\ndef motorR(dir, speed):\n i2c.write(0x10, bytearray([0x02, dir, speed]))\n\n\ndef led(right_left, on_off):\n buf_led = bytearray(2)\n if right_left == 0:\n buf_led[0] = 0x0B\n else:\n buf_led[0] = 0x0C\n buf_led[1] = on_off\n i2c.write(0x10, buf_led)\n\n\ndef setLEDLeft(on):\n led(1, on)\n\n\ndef setLEDRight(on):\n led(0, on)\n\n\ndef setLED(on):\n led(1, on)\n led(0, on)\n\n\ndef rgbLED(red, green, blue):\n buf_rgbLed_red = bytearray(2)\n buf_rgbLed_red[0] = 0x18\n buf_rgbLed_red[1] = red\n buf_rgbLed_green = bytearray(2)\n buf_rgbLed_green[0] = 0x19\n buf_rgbLed_green[1] = green\n buf_rgbLed_blue = bytearray(2)\n buf_rgbLed_blue[0] = 0x1A\n buf_rgbLed_blue[1] = blue\n i2c.write(0x10, buf_rgbLed_red)\n i2c.write(0x10, buf_rgbLed_green)\n i2c.write(0x10, buf_rgbLed_blue)\n\n\ndef getDistance():\n i2c.write(0x10, bytearray([0x28]))\n sleep(20)\n data = i2c.read(0x10, 2)\n distance = (data[0] << 8) | data[1]\n return distance\n\n\ndef irLeftValue():\n i2c.write(0x10, bytearray([0x1D]))\n data = i2c.read(0x10, 1)[0]\n return 0 if (data & 0x01) != 0 else 1\n\n\ndef irRightValue():\n i2c.write(0x10, bytearray([0x1D]))\n data = i2c.read(0x10, 1)[0]\n return 0 if (data & 0x02) != 0 else 1\n\n\ndef setServo(S, Angle):\n if S == "S1":\n Servo = 0x14\n if S == "S2":\n Servo = 0x15\n i2c.write(0x10, bytearray([Servo, Angle]))\n\n\nexit = stop\ndelay = sleep\n',
46
+ cpglow: '# cpglow.py\n# Version 1.0, Dec. 5, 2018\n\nfrom calliope_mini import *\n\n_x = 0\n_y = 0\n_dir = 0\n_speed = 50\n_trace = True\n_visible = False\n\ndef makeGlow():\n global _visible\n display.set_pixel(2, 2, 9)\n _visible = True\n\ndef clear():\n display.clear()\n \ndef forward(): \n _forward(1)\n\ndef back(): \n _forward(-1)\n \ndef right(angle):\n global _dir\n _dir = (_dir + angle) % 360\n\ndef left(angle):\n right(-angle)\n\ndef setPos(x, y):\n global _x, _y\n _x = x\n _y = y\n _render()\n\ndef getPos():\n return _x, _y\n\ndef setSpeed(speed):\n global _speed\n _speed = speed\n \ndef showTrace(enable):\n global _trace\n _trace = enable \n\ndef isLit():\n return (display.get_pixel(_x + 2, 4 - (_y + 2)) == 9)\n \ndef _forward(s):\n global _x, _y\n sleep(2000 - _speed * 20)\n d = _dir // 45\n if d in [1, 2, 3]: \n _x += s\n if d in [5, 6, 7]: \n _x -= s\n if d in [0, 1, 7]: \n _y += s\n if d in [3, 4, 5]: \n _y -= s\n _render()\n\ndef _render():\n if not _visible:\n print("Use \\"makeGlow()\\" to create a Glow.")\n raise Exception("Glow not initialized.")\n if not _trace:\n display.clear()\n if -2 <= _x <= 2 and -2 <= _y <= 2: \n display.set_pixel(_x + 2, 4 - (_y + 2), 9)\n\n',
47
+ callibotmot: '# callibotmot.py\n# Version 1.0, Apr 24, 2021 / AR\n\nimport gc\nfrom calliope_mini import i2c, sleep\nimport machine\n\nclass Motor:\n def __init__(self, id):\n self._id = id\n\n def _w(self, d, s):\n if self._id == 0:\n _self = 0x00\n else:\n _self = 0x02 \n try: \n i2c.write(0x20, bytearray([_self, d, s]))\n except:\n print("Please switch on mbRobot!")\n while True:\n pass\n \n def rotate(self, s):\n v = abs(s)\n v = v + 50 \n if s > 0: \n self._w(0, v) \n elif s < 0: \n self._w(1, v) \n else: \n self._w(0, 0) \n\n \ndelay = sleep\ndef setLED(on):\n if on == 1:\n i2c.write(0x21, bytearray([0,0x03])) \n else:\n i2c.write(0x21, bytearray([0,0])) \n\nmotL = Motor(0)\nmotR = Motor(2)\n\n\n\n',
48
+ callibot: '# callibot.py\n# Version 1.3, 17-Sept-2021 /JA\n# new: Touchsensors\n\nimport gc\nfrom calliope_mini import i2c, sleep\n\n_axe = 0.06\n\ndef w(d1, d2, s1, s2):\n try:\n i2c.write(0x20, bytearray([0x00, d1, s1]))\n i2c.write(0x20, bytearray([0x02, d2, s2]))\n except:\n print("Please switch on Robot!")\n while True:\n pass\n \ndef setSpeed(speed):\n global _v\n _v = speed + 40\n #_v = int(speed * 1.1) + 35 \n\ndef forward():\n w(0, 0, _v, _v)\n\ndef backward():\n w(1, 1, _v, _v)\n \ndef stop():\n w(0, 0, 0, 0)\n \ndef right():\n v = int(_v * 1.1)\n w(0 if _v > 0 else 1, 1 if _v > 0 else 0, v , v) \n\ndef left():\n v = int(_v * 1.1) \n w(1 if _v > 0 else 0, 0 if _v > 0 else 1, v, v)\n\ndef rightArc(r): \n v = abs(_v) \n if r < _axe:\n v1 = 0\n else: \n f = (r - _axe) / (r + _axe) * (1 - v * v / 200000) \n v1 = int(f * v)\n if _v > 0:\n w(0, 0, v, v1)\n else:\n w(1, 1, v1, v)\n\ndef leftArc(r): \n v = abs(_v) \n if r < _axe:\n v1 = 0\n else:\n f = (r - _axe) / (r + _axe) * (1 - v * v / 200000) \n v1 = int(f * v)\n if _v > 0:\n w(0, 0, v1, v)\n else:\n w(1, 1, v, v1)\n\ndef setLEDLeft(on):\n try:\n i2c.write(0x21, bytearray([0,0])) \n except:\n print("Please switch on Robot!")\n while True:\n pass \n if on == 1:\n i2c.write(0x21, bytearray([0,0x01])) \n else:\n i2c.write(0x21, bytearray([0,0])) \n \ndef setLEDRight(on):\n try:\n i2c.write(0x21, bytearray([0,0])) \n except:\n print("Please switch on Robot!")\n while True:\n pass \n if on == 1:\n i2c.write(0x21, bytearray([0,0x02])) \n else:\n i2c.write(0x21, bytearray([0,0])) \n\ndef setLED(on):\n try:\n i2c.write(0x21, bytearray([0,0])) \n except:\n print("Please switch on Robot!")\n while True:\n pass \n if on == 1:\n i2c.write(0x21, bytearray([0,0x03])) \n else:\n i2c.write(0x21, bytearray([0,0])) \n \ndef irLeftValue():\n try:\n buffer = i2c.read(0x21,1) \n if (buffer[0] == 130 or buffer[0] == 131):\n return 1\n else:\n return 0 \n except:\n print("Please switch on Robot!")\n while True:\n pass \n\ndef irRightValue():\n try:\n buffer = i2c.read(0x21,1) \n if (buffer[0] == 129 or buffer[0] == 131):\n return 1\n else:\n return 0 \n except:\n print("Please switch on Robot!")\n while True:\n pass \n \ndef getDistance():\n try:\n buffer = i2c.read(0x21,3)\n dist = (256 * buffer[1] + buffer[2])/10\n return dist\n except:\n print("Please switch on Robot!")\n while True:\n pass \n \ndef tsValue():\n try:\n buffer = i2c.read(0x21,1) \n if (buffer[0] == 0x8C or buffer[0] == 0x8F):\n return 1\n else:\n return 0 \n except:\n print("Please switch on Robot!")\n while True:\n pass \n\ndef tsLeftValue():\n try:\n buffer = i2c.read(0x21,1) \n if (buffer[0] == 0x88 or buffer[0] == 0x8B):\n return 1\n else:\n return 0 \n except:\n print("Please switch on Robot!")\n while True:\n pass \n \ndef tsRightValue():\n try:\n buffer = i2c.read(0x21,1) \n if (buffer[0] == 0x84 or buffer[0] == 0x87):\n return 1\n else:\n return 0 \n except:\n print("Please switch on Robot!")\n while True:\n pass \n \nexit = stop\ndelay = sleep\n_v = 90 # entspricht default Speed 50\n\n\n\n',
49
+ cputils: "# cputils.py\n# V1.1, Dec 5, 2018\n# Additional classes / global functions for Calliope\n\n\ndef cat(filename):\n with open(filename) as f:\n line = f.readline()\n while line:\n print(line[:-1])\n line = f.readline()\n\n\nfrom math import asin, atan2, sqrt, degrees\n\ndef getPitch(a):\n pitch = atan2(a[1], a[2])\n return int(degrees(pitch))\n\ndef getRoll(a):\n anorm = sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2])\n roll = asin(a[0] / anorm)\n return int(degrees(roll))",
50
+ cpmike: "# cpmike.py\n\nfrom calliope_mini import pin3, running_time, sleep\n\n_click_time = running_time()\n\ndef isClicked(level = 10, rearm_time = 500):\n global _click_time\n if running_time() - _click_time < rearm_time:\n sleep(10)\n return False\n v = pin3.read_analog()\n if v < 518 - level:\n _click_time = running_time()\n return True\n return False\n"
51
+ };
52
+
53
+ // microbit/libraries.json
54
+ var libraries_default2 = {
55
+ huskylens: `_E='Invalid model_id. Must be number in range [0,4]'
56
+ _D='Error: ID must be in range from 1 to 255.'
57
+ _C=None
58
+ _B=True
59
+ _A=False
60
+ from microbit import i2c,sleep,running_time
61
+ import math
62
+ _g1=['FaceRecognition','ObjectTracking','ObjectRecognition','LineTracking','ColorRecognition','TagRecognition','ObjectClassification','QRRecognition','BarcodeRecognition']
63
+ class Request_Command:KNOCK=44;ALGORITHM=45;ALL=32;BLOCKS=33;BLOCKS_LEARNED=36;BLOCKS_OF_ID=39;ARROWS=34;ARROWS_LEARNED=37;ARROWS_OF_ID=40;LEARNED=35;ALL_OF_ID=38;LEARN=54;FORGET=55;CUSTOM_LABEL=47;CUSTOM_TEXT=52;CLEAR_TEXT=53;SAVE_MODEL=50;LOAD_MODEL=51;SAVE_PHOTO=48;SAVE_SCREENSHOT=57;IS_PRO=59;VERSION=60
64
+ class Return_Code:ANY=1;OK=46;BUSY=61;INFO=41;BLOCK=42;ARROW=43;IS_PRO=59;NEED_PRO=62
65
+ class Algorithm:FACE_RECOGNITION=0;OBJECT_TRACKING=1;OBJECT_RECOGNITION=2;LINE_TRACKING=3;COLOR_RECOGNITION=4;TAG_RECOGNITION=5;OBJECT_CLASSIFICATION=6;QR_RECOGNITION=7;BARCODE_RECOGNITION=8
66
+ class Block:
67
+ def __init__(A,x,y,width,height,id):A.x=x;A.y=y;A.width=width;A.height=height;A.id=id
68
+ def _f2(A):return'Block: ID_'+str(A.id)+' Pos: ('+str(A.x)+' '+str(A.y)+') Size: ('+str(A.width)+' '+str(A.height)+')'
69
+ class Arrow:
70
+ def __init__(A,x_tail,y_tail,x_head,y_head,id):A.x_tail=x_tail;A.y_tail=y_tail;A.x_head=x_head;A.y_head=y_head;A.id=id
71
+ def get_direction(A):
72
+ C=A.x_head-A.x_tail;D=A.y_head-A.y_tail;B=90-math.degrees(math.atan2(D,C))
73
+ if B<0:B=B+360
74
+ return int(B)
75
+ def _f2(A):return'Arrow: ID_'+str(A.id)+' ('+str(A.x_tail)+' '+str(A.y_tail)+')->('+str(A.x_head)+' '+str(A.y_head)+')'
76
+ def byte_checksum(byte_list):return sum(byte_list)&255
77
+ def hexify(byte_array):
78
+ A=byte_array
79
+ if len(A)==0:return''
80
+ return'0x'+''.join('{:02x}'.format(A)for A in A)
81
+ class Huskylens:
82
+ I2C_ADDR=50
83
+ def __init__(A):A.learned_slot_count=0;A.id_slots={};A.id_names={};A.algorithm=Algorithm.OBJECT_TRACKING;A.clear_texts();A.pro_enabled=A.is_pro()
84
+ def initialize(A):
85
+ B=_A
86
+ for E in range(5):
87
+ A.knock();B,F=A.get_response(Return_Code.OK)
88
+ if B:break
89
+ if B>0:
90
+ C=A.clear_texts();D=A.set_algorithm(Algorithm.OBJECT_TRACKING)
91
+ if C and D:print('Initialization successful!');return _B
92
+ else:print("Initialization Failed. Couldn't change Algorithm");return _A
93
+ else:print('Initialization Failed. Please check connection to Huskylens.');return _A
94
+ def send_request(D,command,data=_C):
95
+ B=data;A=bytearray(b'U\\xaa\\x11\\x00\\x00');A[3]=0 if B is _C else len(B);A[4]=command
96
+ if B:
97
+ for C in B:A.append(C)
98
+ A.append(byte_checksum(A));i2c.write(Huskylens.I2C_ADDR,A);sleep(50)
99
+ def get_response(K,return_code=Return_Code.ANY,timeout=500):
100
+ C=return_code;A=bytearray(b'U\\x00\\x00\\x00\\x00');I=running_time()
101
+ while running_time()-I<timeout:
102
+ D=i2c.read(Huskylens.I2C_ADDR,1)[0]
103
+ if D==85:break
104
+ if D!=85:return-1,[]
105
+ for J in range(4):A[J+1]=i2c.read(Huskylens.I2C_ADDR,1)[0]
106
+ if A[0:3]!=b'U\\xaa\\x11':return-2,[]
107
+ E=A[3];F=A[4];B=[]
108
+ if E>0:G=i2c.read(Huskylens.I2C_ADDR,E+1);B=G[0:-1];H=G[-1]
109
+ else:H=ord(i2c.read(Huskylens.I2C_ADDR,1))
110
+ if H!=byte_checksum(list(A)+B):return-3,[]
111
+ if C==Return_Code.ANY or F==C:return F,B
112
+ else:return 0,B
113
+ def knock(A):A.send_request(Request_Command.KNOCK)
114
+ def set_algorithm(B,algorithm):
115
+ A=algorithm
116
+ if(A==Algorithm.QR_RECOGNITION or A==Algorithm.BARCODE_RECOGNITION)and not B.pro_enabled:raise RuntimeError('Error: Huskylens PRO version is required for algorithm ',_g1[A]);return _A
117
+ D=[A,0];B.send_request(Request_Command.ALGORITHM,D);C,E=B.get_response(Return_Code.OK)
118
+ if C>0:print('Current Algorithm:',_g1[A]);B.algorithm=A
119
+ return _B if C>0 else _A
120
+ def get_all(A):return A._f7(Request_Command.ALL)
121
+ def get_all_learned(A):return A._f7(Request_Command.LEARNED)
122
+ def get_all_with_id(A,id):
123
+ if id<=0 or id>255:raise RuntimeError(_D)
124
+ return A._f7(Request_Command.ALL_OF_ID,id)
125
+ def get_one(A):B=A._f7(Request_Command.ALL);return A._f8(B)
126
+ def get_one_learned(A):B=A._f7(Request_Command.LEARNED);return A._f8(B)
127
+ def get_one_with_id(A,id):
128
+ if id<=0 or id>255:raise RuntimeError(_D)
129
+ B=A._f7(Request_Command.ALL_OF_ID,id);return A._f8(B)
130
+ def attach_label(A,id,name):
131
+ B=name
132
+ if A.algorithm==Algorithm.OBJECT_TRACKING or A.algorithm==Algorithm.LINE_TRACKING:C=A._f6(1,B)
133
+ elif A.algorithm==Algorithm.FACE_RECOGNITION or A.algorithm==Algorithm.TAG_RECOGNITION or A.algorithm==Algorithm.OBJECT_CLASSIFICATION or A.algorithm==Algorithm.OBJECT_RECOGNITION:
134
+ D=A.id_slots.get(id)
135
+ if D==_C:raise RuntimeError("Can't attach a name to an unlearned ID number")
136
+ A.id_names[id]=B;C=_B
137
+ for E in D:F=A._f6(E,B);C=C and F>0
138
+ else:A.id_names[id]=B;C=A._f6(id,B)
139
+ return _B if C>0 else _A
140
+ def clear_labels(A):
141
+ A.id_names.clear()
142
+ for B in range(10):A._f6(B,'')
143
+ def add_text(E,text,position_x,position_y):
144
+ C=position_y;B=position_x;D=bytes(text,'utf-8')
145
+ if len(D)>19:raise RuntimeError('Custom Text must be less than 20 bytes long.')
146
+ if B>300 or B<0 or C<35 or C>240:raise RuntimeError("Custom Text can't be placed outside of screen pixel size.")
147
+ A=[len(D)];A.append(255 if B>255 else 0);A.append(B%255);A.append(240-C);A.extend(list(D));E.send_request(Request_Command.CUSTOM_TEXT,A);F,G=E.get_response(Return_Code.OK);return _B if F>0 else _A
148
+ def clear_texts(A):A.send_request(Request_Command.CLEAR_TEXT);B,C=A.get_response(Return_Code.OK);return _B if B>0 else _A
149
+ def learn(A,id,name=_C):
150
+ if id<=0 or id>255:raise RuntimeError('Parameter ID for learned item must be in range [0,255]')
151
+ if A.algorithm==Algorithm.OBJECT_TRACKING or A.algorithm==Algorithm.LINE_TRACKING:id=1
152
+ C=500
153
+ if A.algorithm==Algorithm.OBJECT_CLASSIFICATION:C=1000
154
+ A.send_request(Request_Command.LEARN,[id,0]);B,E=A.get_response(Return_Code.OK,C)
155
+ if B>0:
156
+ A.learned_slot_count+=1
157
+ if not id in A.id_slots:A.id_slots[id]=[A.learned_slot_count]
158
+ else:A.id_slots[id].append(A.learned_slot_count)
159
+ D=A.id_names.get(id)
160
+ if D!=_C:B=A.attach_label(A.learned_slot_count,D)
161
+ elif name!=_C:B=A.attach_label(id,name)
162
+ return _B if B>0 else _A
163
+ def forget(A):
164
+ A.send_request(Request_Command.FORGET);B,C=A.get_response(Return_Code.OK)
165
+ if B:A.learned_slot_count=0;A.id_slots.clear()
166
+ return _B if B else _A
167
+ def save_photo(A):A.send_request(Request_Command.SAVE_PHOTO);B,C=A.get_response(Return_Code.OK,1000);return _B if B>0 else _A
168
+ def save_screenshot(A):A.send_request(Request_Command.SAVE_SCREENSHOT);B,C=A.get_response(Return_Code.OK,1000);return _B if B>0 else _A
169
+ def save_model(B,model_id):
170
+ A=model_id
171
+ if A<0 or A>4:raise RuntimeError(_E)
172
+ B.send_request(Request_Command.SAVE_MODEL,[A,0]);C,D=B.get_response(Return_Code.OK,1000);print('Model saving: Check Huskylens screen for Result!\\n\\tModel name:',_g1[B.algorithm]+'_Backup_'+str(A)+'.conf');return _B if C>0 else _A
173
+ def load_model(B,model_id):
174
+ A=model_id
175
+ if A<0 or A>4:raise RuntimeError(_E)
176
+ B.send_request(Request_Command.LOAD_MODEL,[A,0]);C,D=B.get_response(Return_Code.OK,1000);print('Model Loading: Check Huskylens screen for Result!');return _B if C>0 else _A
177
+ def is_pro(A):A.send_request(Request_Command.IS_PRO);B,C=A.get_response(Return_Code.IS_PRO);return bool(C[0])if B>0 else _A
178
+ def _f6(C,id,name):
179
+ A=bytes(name,'utf-8')
180
+ if len(A)>19:raise RuntimeError('Custom Name must be less than 20 bytes long.')
181
+ B=[id,len(A)+1];B.extend(list(A));B.append(0);C.send_request(Request_Command.CUSTOM_LABEL,B);D,E=C.get_response(Return_Code.OK);return _B if D>0 else _A
182
+ def _f7(B,request_command,id=-1):
183
+ I=_C if id<0 else[id,0];B.send_request(request_command,I);G,H=B.get_response(Return_Code.INFO)
184
+ if not G:raise RuntimeError('Failed to request results. Got answer:'+str(G))
185
+ J=H[0]+H[1]*255;C=0;D=[]
186
+ while C<J:
187
+ E,A=B.get_response(Return_Code.ANY)
188
+ if E==Return_Code.BLOCK and B.algorithm!=3:K=A[0]+A[1]*255;L=240-A[2]+A[3]*255;M=A[4]+A[5]*255;N=A[6]+A[7]*255;F=A[8];O=Block(K,L,M,N,F);D.append(O);C+=1
189
+ elif E==Return_Code.ARROW:P=A[0]+A[1]*255;Q=240-A[2]+A[3]*255;R=A[4]+A[5]*255;S=240-A[6]+A[7]*255;F=A[8];T=Arrow(P,Q,R,S,F);D.append(T);C+=1
190
+ elif E==0:return[]
191
+ return D
192
+ def _f8(E,results):
193
+ C=_C;D=440
194
+ for A in results:
195
+ B=0
196
+ if E.algorithm==Algorithm.LINE_TRACKING:B=abs(A.x_tail+(A.x_tail-A.x_head)//2-160)+abs(A.y_tail+(A.y_tail-A.y_head)//2-120)
197
+ else:B=abs(A.x-160)+abs(A.y-120)
198
+ if B<D:C,D=A,B
199
+ return C`,
200
+ mbbitbot: "from microbit import*\nfrom neopixel import*\nfrom utime import ticks_us,sleep_us\n_g1=200\n_g2=12\n_g3=NeoPixel(pin13,_g2)\n_g4=0\n_g5=0\ndef w(leftforward,leftbackward,rightforward,rightbackward):\n if leftforward>0 or rightforward>0:pin16.write_analog(leftforward+_g4);pin8.write_analog(leftbackward);pin14.write_analog(rightforward-_g4);pin12.write_analog(rightbackward)\n elif leftbackward>0 or rightbackward>0:pin16.write_analog(leftforward);pin8.write_analog(leftbackward+_g4);pin14.write_analog(rightforward);pin12.write_analog(rightbackward-_g4)\n elif leftforward==0 and rightforward==0 and leftbackward==0 and rightbackward==0:pin16.write_analog(0);pin8.write_analog(0);pin14.write_analog(0);pin12.write_analog(0)\ndef forward():w(_g1,0,_g1,0)\ndef backward():w(0,_g1,0,_g1)\ndef stop():w(0,0,0,0)\ndef right():w(0,_g1,_g1,0)\ndef left():w(_g1,0,0,_g1)\ndef set_led(pos,red,green,blue):_g3[pos]=red,green,blue;_g3.show()\ndef fill(red,green,blue):\n for i in range(_g2):_g3[i]=red,green,blue\n _g3.show()\ndef getDistance():\n pin15.write_digital(1);sleep_us(10);pin15.write_digital(0);pin15.set_pull(pin15.NO_PULL)\n while pin15.read_digital()==0:0\n start=ticks_us()\n while pin15.read_digital()==1:0\n end=ticks_us();echo=end-start;distance=int(.01715*echo);return distance\ndef calibrate(offset,differential=0):global _g4;global _g5;global _g8;_g5=max(min(int(offset),50),-50);_g4=max(min(int(differential),50),-50);_g8=max(min(arcScaling,50),-50);setSpeed(_g1/1023*100)\ndef setSpeed(percent):global _g1;speed=percent/100*1023;speed+=_g5/100*1023;speed=min(max(speed,0),1023);_g1=speed\ndef getLine(bit):\n mask=1<<bit;value=0\n try:value=i2c.read(28,1)[0]\n except OSError:pass\n if value&mask>0:return 1\n else:return 0\ndef getLight(index):\n if index==0:return pin1.read_analog()\n elif index==1:return pin2.read_analog()\ndef leftArc(radius):speed=_g1;inner_wheel_speed=speed*(radius/(radius+1));w(inner_wheel_speed,0,speed,0)\ndef rightArc(radius):speed=_g1;inner_wheel_speed=speed*(radius/(radius+1));w(speed,0,inner_wheel_speed,0)",
201
+ mbwait: `from microbit import button_a,button_b,pin0,pin1,pin2,pin_logo,sleep
202
+ POLLING_DELAY=100
203
+ def wait_for_press(button='any'):
204
+ A=button;button_a.was_pressed();button_b.was_pressed()
205
+ if A=='a'or A=='A':
206
+ while not button_a.was_pressed():sleep(POLLING_DELAY)
207
+ elif A=='b'or A=='B':
208
+ while not button_b.was_pressed():sleep(POLLING_DELAY)
209
+ elif A=='any'or A=='ANY':
210
+ while not button_a.was_pressed()and not button_b.was_pressed():sleep(POLLING_DELAY)
211
+ elif A=='both'or A=='ab'or A=='AB':
212
+ while not(button_a.is_pressed()and button_b.is_pressed()):sleep(POLLING_DELAY)
213
+ while button_a.is_pressed()or button_b.is_pressed():sleep(POLLING_DELAY)
214
+ else:raise RuntimeError("Button to wait for must be either: 'a', 'b', 'any' or 'both'.")
215
+ def wait_for_touch(pin='logo'):
216
+ B=pin;A=pin_logo
217
+ if B=='pin0':A=pin0
218
+ elif B=='pin1':A=pin1
219
+ elif B=='pin2':A=pin2
220
+ elif B=='logo'or B=='pin_logo'or B=='pinLogo':A=pin_logo
221
+ else:raise RuntimeError("Argument 'pin' must be one of: 'pin_logo', 'pin0', 'pin1' or 'pin2'.")
222
+ A.set_touch_mode(A.CAPACITIVE)
223
+ while not A.is_touched():sleep(POLLING_DELAY)`,
224
+ mbled: `from neopixel import*
225
+ import gc
226
+ from microbit import pin2
227
+ _g1=24
228
+ _g2=NeoPixel(pin2,_g1)
229
+ def fill(red,green,blue):
230
+ for i in range(_g1):_g2[i]=red,green,blue
231
+ _g2.show()
232
+ def set_led(pos,red,green,blue):_g2[pos]=red,green,blue;_g2.show()
233
+ def clear():_g2.clear()
234
+ def shift_by(amount):
235
+ shifted_copy=[None]*_g1
236
+ for n in range(0,_g1):next_i=(n+amount)%_g1;shifted_copy[n]=_g2[next_i]
237
+ for n in range(0,_g1):_g2[n]=shifted_copy[n]
238
+ _g2.show()
239
+ def lerp_RGB(r1,g1,b1,r2,g2,b2,percent):
240
+ if percent<.0 or percent>1e2:raise RuntimeError("Argument 'percent' must be between 0 and 100.")
241
+ red=max(0,min(255,round(r1+(r2-r1)*(percent/1e2))));green=max(0,min(255,round(g1+(g2-g1)*(percent/1e2))));blue=max(0,min(255,round(b1+(b2-b1)*(percent/1e2))));return red,green,blue`,
242
+ mbrobot_plus: "_A='Please switch on mbRobot!'\nfrom microbit import i2c,pin0,pin1,pin2,sleep\nimport machine,gc,music\n_g1=50\n_g2=.082\ndef w(d1,d2,s1,s2):\n try:i2c.write(16,bytearray([0,d1,d2,s1,s2]))\n except:print(_A)\ndef setSpeed(speed):\n A=speed;global _g1\n if A<30 and A!=0:setPID(1);_g1=A+30\n elif A>=30 and A<32:setPID(0);_g1=A+2\n else:setPID(0);_g1=A\ndef setPID(pd):i2c.write(16,bytearray([10,pd]))\ndef stop():setPID(0);w(0,0,0,0)\ndef resetSpeed():setPID(0);A=50\ndef forward():w(1,_g1,1,_g1)\ndef backward():w(2,_g1,2,_g1)\ndef left():A=1.825-.0175*_g1;w(2,int(_g1*A),1,int(_g1*A))\ndef right():A=1.825-.0175*_g1;w(1,int(_g1*A),2,int(_g1*A))\ndef rightArc(r):\n A=abs(_g1)\n if r<_g2:B=0\n else:C=(r-_g2)/(r+_g2)*(1-A*A/200000);B=int(C*A)\n if _g1>0:w(1,A,1,B)\n else:w(2,B,2,A)\ndef leftArc(r):\n A=abs(_g1)\n if r<_g2:B=0\n else:C=(r-_g2)/(r+_g2)*(1-A*A/200000);B=int(C*A)\n if _g1>0:w(1,B,1,A)\n else:w(2,A,2,B)\ndef getDistance():pin1.write_digital(1);pin1.write_digital(0);B=machine.time_pulse_us(pin2,1,50000);A=int(B/58.2-.5);return A if A>0 else 255\nclass Motor:\n def __init__(A,id):A._id=2*id\n def _f2(A,d,s):\n try:i2c.write(16,bytearray([A._id,d,s]))\n except:\n print(_A)\n while True:0\n def rotate(A,s):\n B=abs(s)\n if s>0:A._f2(1,B)\n elif s<0:A._f2(2,B)\n else:A._f2(0,0)\nclass LEDState:OFF=0;RED=1;GREEN=2;YELLOW=3;BLUE=4;PINK=5;CYAN=6;WHITE=7\ndef setLED(state,stateR=None):B=state;A=stateR;A=A or B;i2c.write(16,bytearray([11,B,A]))\ndef setLEDLeft(state):i2c.write(16,bytearray([11,state]))\ndef setLEDRight(state):i2c.write(16,bytearray([12,state]))\ndef setAlarm(on):\n if on:music.play(_g3,wait=False,loop=True)\n else:music.stop()\ndef beep():music.pitch(2000,200,wait=False)\ndef ir_read_values_as_byte():i2c.write(16,bytearray([29]));A=i2c.read(16,1);return~A[0]\ndef setServo(S,Angle):\n if S=='S1':A=20\n if S=='S2':A=21\n B=A,Angle;i2c.write(16,bytes(B))\nclass IR:L3=0;L2=1;L1=2;R1=3;R2=4;R3=5;masks=[1,2,4,8,16,32]\nclass IRSensor:\n def __init__(A,index):A.index=index\n def read_digital(A):B=ir_read_values_as_byte();return(B&IR.masks[A.index])>>A.index\nirLeft=IRSensor(IR.L1)\nirRight=IRSensor(IR.R1)\nirL1=IRSensor(IR.L1)\nirR1=IRSensor(IR.R1)\nirL2=IRSensor(IR.L2)\nirR2=IRSensor(IR.R2)\nirL3=IRSensor(IR.L3)\nirR3=IRSensor(IR.R3)\npin2.set_pull(pin2.NO_PULL)\nmotL=Motor(0)\nmotR=Motor(1)\ndelay=sleep\n_g3=['c6:1','r','c6,1','r','r','r']",
243
+ mbrobot: `from microbit import i2c,pin1,pin2,pin8,pin12,pin13,pin14,pin15,sleep
244
+ import gc,machine,music,neopixel
245
+ _g1=50
246
+ _g2=40
247
+ _g3=40
248
+ _g4=bytearray(5)
249
+ _g5=bytearray(2)
250
+ _g6=bytes(b'\\x00\\x0b\\x0b\\x0c\\x0c\\r\\r\\r\\x0e\\x0e\\x0f\\x0f\\x0f\\x10\\x10\\x11\\x11\\x11\\x12\\x12\\x13\\x13\\x13\\x14\\x14\\x15\\x15\\x15\\x16\\x16\\x17\\x17\\x17\\x18\\x19\\x1a\\x1b\\x1b\\x1c\\x1d\\x1e\\x1f !"##$%&\\'()*++,-./0123468:<?ADFILOSVZ^bgkpu{\\x81\\x87\\x8d\\x94\\x9b\\xa3\\xab\\xb4\\xbd\\xc6\\xd0\\xdb\\xe6\\xf2\\xff')
251
+ _g7=0
252
+ _g8=0
253
+ _g9=0
254
+ _g10=neopixel.NeoPixel(pin15,4)
255
+ np_rgb_pixels=_g10
256
+ _g11=['c5:1','r','c5:1','r:3']
257
+ _g12='Please connect to Maqueen robot and switch it on.'
258
+ def _f1(dirL,powerL,dirR,powerR):
259
+ global _g4;_g4[1]=dirL;_g4[2]=powerL;_g4[3]=dirR;_g4[4]=powerR
260
+ try:i2c.write(16,_g4)
261
+ except:raise RuntimeError(_g12)
262
+ def _f2(side,dir,power):
263
+ global _g4;_g4[1+side]=dir;_g4[2+side]=power
264
+ try:i2c.write(16,_g4)
265
+ except:raise RuntimeError(_g12)
266
+ def _f3(speed,offset):return min(_g6[speed]+offset,255)
267
+ def _f4(r):
268
+ A=_g1;B=int(r*100);D=A-max(B+20,40)
269
+ if D<=0:A=min(max(B+40,40),100)
270
+ C=0
271
+ if B>=4:E=(100-A)//2;C=(B*10-35)/(B*(11+(_g9-4)/10)+90+E);C=C*A
272
+ F=_f3(int(C),0);G=_f3(int(A),0);return F,G
273
+ def calibrate(offset,differential=0,arcScaling=0):global _g8;global _g7;global _g9;_g7=max(min(int(offset),50),-10);_g8=max(min(int(differential),150),-150);_g9=max(min(arcScaling,50),-15);setSpeed(_g1)
274
+ def setSpeed(speed):
275
+ global _g1;global _g2;global _g3;_g1=int(min(max(speed,0),100));A=_f3(_g1,_g7);B=round((1-_g1/100)*abs(_g8))if _g1>0 else 0;C=round(_g1/100*abs(_g8))
276
+ if _g8>0:_g2=A-C;_g3=A+B
277
+ else:_g2=A+B;_g3=A-C
278
+ def resetSpeed():setSpeed(50)
279
+ def stop():_f1(0,0,0,0)
280
+ def forward():_f1(0,_g2,0,_g3)
281
+ def backward():_f1(1,_g2,1,_g3)
282
+ def left():_f1(1,_g2,0,_g3)
283
+ def right():_f1(0,_g2,1,_g3)
284
+ def rightArc(radius):A,B=_f4(radius);_f1(0,B,0,A)
285
+ def leftArc(radius):A,B=_f4(radius);_f1(0,A,0,B)
286
+ class Motor:
287
+ def __init__(A,side):A._side=side
288
+ def rotate(B,speed):A=speed;C=int(min(max(abs(A),0),100));D=_f3(C,_g7);E=0 if A>0 else 1;_f2(B._side,E,D)
289
+ def setServo(servo,angle):
290
+ B=angle;A=servo;global _g5
291
+ if A=='S1'or A=='P0':_g5[0]=20
292
+ elif A=='S2'or A=='P1':_g5[0]=21
293
+ else:raise ValueError("Unknown Servo. Please use 'S1' or 'S2'.")
294
+ if B<0 or B>180:raise ValueError('Invalid angle. Must be between 0 and 180')
295
+ _g5[1]=B
296
+ try:i2c.write(16,_g5)
297
+ except:raise RuntimeError(_g12)
298
+ class IRSensor:
299
+ def __init__(A,pin):A._pin=pin
300
+ def read_digital(A):return A._pin.read_digital()
301
+ def read_analog(A):raise NameError('Maqueen Lite does not support reading analog sensor values.')
302
+ def getDistance():pin1.write_digital(1);pin1.write_digital(0);A=machine.time_pulse_us(pin2,1,50000);B=(A>>6)+(A>>10)+(A>>11)+(A>>12)+1;return max(min(B,500),0)if B>0 else 255
303
+ def setLED(state,stateR=None):B=state;A=stateR;A=A if A!=None else B;pin8.write_digital(B);pin12.write_digital(A)
304
+ def setLEDLeft(state):pin8.write_digital(state)
305
+ def setLEDRight(state):pin12.write_digital(state)
306
+ def fillRGB(red,green,blue):
307
+ for A in range(4):_g10[A]=red,green,blue
308
+ _g10.show()
309
+ setRGB=fillRGB
310
+ def clearRGB():_g10.clear()
311
+ def posRGB(position,red,green,blue):
312
+ A=position
313
+ if A<0 or A>3:raise ValueError('invalid RGB-LED position. Must be 0,1,2 or 3.')
314
+ _g10[A]=red,green,blue;_g10.show()
315
+ def setAlarm(state):
316
+ if state:music.play(_g11,wait=False,loop=True)
317
+ else:music.stop()
318
+ def beep():music.pitch(440,200,wait=False)
319
+ pin2.set_pull(pin2.NO_PULL)
320
+ delay=sleep
321
+ irLeft=IRSensor(pin13)
322
+ irRight=IRSensor(pin14)
323
+ motL=Motor(0)
324
+ motR=Motor(2)`,
325
+ mbrobot_plusV3: `_B=True
326
+ _A=False
327
+ from microbit import i2c,sleep,running_time,pin0,pin1,pin2
328
+ import neopixel,music
329
+ _g1=bytearray(5)
330
+ _g2=50
331
+ _g3=50
332
+ _g4=50
333
+ _g5=bytes(b'\\x00\\x0f\\x10\\x10\\x11\\x12\\x12\\x13\\x13\\x14\\x15\\x15\\x16\\x16\\x17\\x18\\x18\\x19\\x19\\x1a\\x1b\\x1b\\x1c\\x1c\\x1d\\x1e\\x1e\\x1f\\x1f !!""#$$%%&\\')*+,-./0123456789:;;<>?ACEGIKMPRUX[^aeimquz\\x7f\\x84\\x89\\x8f\\x95\\x9b\\xa2\\xa9\\xb1\\xb9\\xc1\\xca\\xd3\\xdd\\xe8\\xf3\\xff')
334
+ _g6=0
335
+ _g7='Please connect to Maqueen robot and switch it on.'
336
+ _g8=neopixel.NeoPixel(pin1,4)
337
+ _g9=['c5:1','r','c5,1','r:3']
338
+ _g10=bytearray(1)
339
+ _g11=bytearray(2)
340
+ _g12=16
341
+ _g13=25
342
+ _g14=131
343
+ _g15=8
344
+ def _f1(reg):_g10[0]=reg;i2c.write(_g12,_g10)
345
+ def _f2(reg,val):_g11[0]=reg;_g11[1]=val;i2c.write(_g12,_g11)
346
+ def _f3(dirL,powerL,dirR,powerR):
347
+ global _g1;_g1[1]=dirL;_g1[2]=powerL;_g1[3]=dirR;_g1[4]=powerR
348
+ try:i2c.write(16,_g1)
349
+ except:raise RuntimeError(_g7)
350
+ def _f4(side,dir,power):
351
+ global _g1;_g1[1+side]=dir;_g1[2+side]=power
352
+ try:i2c.write(16,_g1)
353
+ except:raise RuntimeError(_g7)
354
+ def setSpeed(speed):A=speed;global _g2;global _g3;global _g4;_g2=int(min(max(A,0),100));_g3=int(round(2.4*A+14));_g4=int(round(2.4*A+14))
355
+ def resetSpeed():setSpeed(50)
356
+ def stop():_f3(0,0,0,0)
357
+ def forward():_f3(0,_g3,0,_g4)
358
+ def backward():_f3(1,_g3,1,_g4)
359
+ def left():_f3(1,_g3,0,_g4)
360
+ def right():_f3(0,_g3,1,_g4)
361
+ def _f5(speed,offset):return min(_g5[speed]+offset,255)
362
+ def _f6(r):
363
+ B=int(r*100);A=_g2
364
+ if A<25:A=25
365
+ C=0
366
+ if B>5:
367
+ D=A*(3*_g6-A-9*B+220);E=-14*_g6+A-200+3*A-10*B-290;C=int(D/E)
368
+ if C<2:C=2 if B>15 else 1
369
+ F=_f5(int(C),0);G=_f5(int(A),0);return F,G
370
+ def rightArc(radius):A,B=_f6(radius);_f3(0,B,0,A)
371
+ def leftArc(radius):A,B=_f6(radius);_f3(0,A,0,B)
372
+ class Motor:
373
+ def __init__(A,side):A._side=side
374
+ def rotate(B,speed):A=speed;C=int(min(max(abs(A),0),100));D=C;E=0 if A>0 else 1;_f4(B._side,E,D)
375
+ def setServo(servo,angle):
376
+ D=angle;C=servo
377
+ if D<0 or D>180:raise ValueError('Invalid angle. Must be between 0 and 180')
378
+ if C in['P0','S1']:A=pin0
379
+ elif C in['P1','S2']:A=pin1
380
+ elif C in['P2','S3']:A=pin2
381
+ else:raise ValueError('Valid servo names: S1, S2, S3 or P0, P1, P2')
382
+ B=(_g14-_g13)*int(D);E=(B>>8)+(B>>10)+(B>>11)+(B>>12);F=_g13+E;A.set_analog_period(20);A.write_analog(F)
383
+ class IRSensor:
384
+ _g19=bytes(b'\\x1d')
385
+ def __init__(A,index):A.index=index
386
+ def read_digital(A):
387
+ try:i2c.write(16,IRSensor._g19)
388
+ except:raise RuntimeError(_g7)
389
+ B=~i2c.read(16,1)[0];return(B&2**A.index)>>A.index
390
+ def read_analog(A):
391
+ try:_f1(29)
392
+ except:raise RuntimeError(_g7)
393
+ B=i2c.read(16,11);return B[2+2*A.index]<<8|B[1+2*A.index]
394
+ def setLEDs(rgbl,rgbr):_f2(11,rgbl);_f2(12,rgbr)
395
+ def setLED(state,stateR=None):B=state;A=stateR;A=A if A!=None else B;setLEDs(B,A)
396
+ def setLEDLeft(rgbl):_f2(11,rgbl)
397
+ def setLEDRight(rgbr):_f2(12,rgbr)
398
+ def fillRGB(red,green,blue):_g8.clear();_g8.fill((red,green,blue));_g8.show()
399
+ def setRGB(r,g,b):fillRGB(r,g,b)
400
+ def clearRGB():_g8.clear()
401
+ def posRGB(position,red,green,blue):
402
+ A=position
403
+ if A<0 or A>3:raise ValueError('invalid RGB-LED position. Must be 0,1,2 or 3.')
404
+ _g8[A]=red,green,blue;_g8.show()
405
+ def setAlarm(state):
406
+ if state:music.play(_g9,wait=_A,loop=_B)
407
+ else:music.stop()
408
+ def beep():music.pitch(440,200,wait=_A)
409
+ def readLightIntensity(side):
410
+ _f1(78);A=i2c.read(16,4,repeat=_A)
411
+ if side==1:return A[0]<<8|A[1]
412
+ else:return A[2]<<8|A[3]
413
+ def setPatrolSpeed(speed):_f2(63,speed)
414
+ def setIntersectionRunMode(mode):_f2(69,mode)
415
+ def setTRordRunMode(mode):_f2(70,mode)
416
+ def setLeftOrStraightRunMode(mode):_f2(71,mode)
417
+ def setRightOrStraightRunMode(mode):_f2(72,mode)
418
+ def patrolling(patrol):
419
+ if patrol==1:A=5
420
+ else:A=8
421
+ _f2(60,A)
422
+ def intersectionDetecting():_f1(61);A=i2c.read(16,1)[0];return A
423
+ def pidControlDistance(dir,distance,interruption):
424
+ A=distance;C=2
425
+ if A>=6000:A=60000
426
+ _f2(64,dir);_f2(85,C);_f2(65,A>>8);_f2(66,A);_f2(60,6)
427
+ if interruption==1:
428
+ _f1(87);B=i2c.read(16,1)
429
+ while B[0]==1:sleep(10);B=i2c.read(16,1)
430
+ def pidControlAngle(angle,interruption):
431
+ A=angle;D=2
432
+ if A>=0:B=1
433
+ else:B=2;A=-A
434
+ _f2(67,B);_f2(86,D);_f2(68,A);_f2(60,6)
435
+ if interruption==1:
436
+ _f1(87);C=i2c.read(16,1)
437
+ while C[0]==1:sleep(10);C=i2c.read(16,1)
438
+ def pidControlStop():_f2(60,16)
439
+ def readRealTimeSpeed(type):
440
+ _f2(76,1);A=i2c.read(16,2)
441
+ if type==1:return A[0]/5
442
+ else:return A[1]/5
443
+ def _f7(cmd,args=[]):
444
+ B=len(args);C=B+1;A=bytearray(4+B);A[0]=85;A[1]=C>>8&255;A[2]=C&255;A[3]=cmd
445
+ for(D,E)in enumerate(args):A[4+D]=E
446
+ i2c.write(51,A)
447
+ def _f8(expectedCommand):
448
+ F=1000;J=32;G=running_time();B=_A;A=None;C=_A
449
+ while running_time()-G<F and C==_A:
450
+ H=i2c.read(51,1)[0]
451
+ if H==83:C=_B
452
+ elif H==99:return B,A
453
+ sleep(16)
454
+ if C==_B:
455
+ D=i2c.read(51,3);K=D[0];L=D[1]|D[2]<<8
456
+ if K==expectedCommand:
457
+ B=_B;A=bytearray();E=L;M=min(E,J)
458
+ while running_time()-G<F and E>0:
459
+ try:I=i2c.read(51,M);A.extend(I);E-=len(I)
460
+ except:sleep(1)
461
+ return B,A
462
+ def setLidarMode(mode=8):
463
+ A=mode;global _g15
464
+ if A not in[4,8]:raise ValueError('Lidar mode must be 4 or 8')
465
+ C='4x4'if A==4 else'8x8';print('Switching Lidar Mode to '+C+'.\\nPlease wait up to 10 seconds.');B=_A
466
+ for D in range(10):
467
+ _f7(1,[0,0,0,A]);B,E=_f8(1)
468
+ if B==_B:break
469
+ sleep(17)
470
+ if B:_g15=A;sleep(5000)
471
+ else:raise RuntimeError('Failed to switch Lidar Mode')
472
+ def getDistanceAt(x_pos,y_pos):
473
+ _f7(3,[x_pos,y_pos]);B,A=_f8(3)
474
+ if B and len(A)>=2:C=(A[0]|A[1]<<8)//10;return C
475
+ else:return 1023
476
+ def getDistanceList():
477
+ _f7(2);D,A=_f8(2)
478
+ if D and len(A)>=32:
479
+ B=[]
480
+ for C in range(0,len(A),2):E=A[C]|A[C+1]<<8;B.append(E//10)
481
+ return B
482
+ else:return[]
483
+ def getDistance():global _g15;A=int(_g15/2);B=getDistanceAt(A-1,A-1);C=getDistanceAt(A,A-1);D=getDistanceAt(A-1,A);E=getDistanceAt(A,A);F=[B,C,D,E];return min(F)
484
+ def getDistanceGrid():
485
+ _f7(2);G,A=_f8(2)
486
+ if G and len(A)>=32:
487
+ B=[];C=16 if len(A)==128 else 8
488
+ for D in range(0,len(A),C):
489
+ E=[]
490
+ for F in range(0,C,2):H=A[D+F]|A[D+F+1]<<8;E.append(H//10)
491
+ B.append(E)
492
+ return B
493
+ else:return[]
494
+ def getDistanceColumn(index):
495
+ _f7(5,[index]);D,A=_f8(5)
496
+ if D and len(A)>=8:
497
+ B=[]
498
+ for C in range(0,len(A),2):E=A[C]|A[C+1]<<8;B.append(E//10)
499
+ return B
500
+ return[]
501
+ def getDistanceRow(index):
502
+ _f7(6,[index]);D,A=_f8(6)
503
+ if D and len(A)>=8:
504
+ B=[]
505
+ for C in range(0,len(A),2):E=A[C]|A[C+1]<<8;B.append(E//10)
506
+ return B
507
+ return[]
508
+ pin2.set_pull(pin2.NO_PULL)
509
+ delay=sleep
510
+ irR2=IRSensor(0)
511
+ irR1=IRSensor(1)
512
+ irRight=irR1
513
+ irM=IRSensor(2)
514
+ irL1=IRSensor(3)
515
+ irLeft=irL1
516
+ irL2=IRSensor(4)
517
+ motL=Motor(0)
518
+ motR=Motor(2)`,
519
+ mbmarsrover: "from microbit import*\nfrom neopixel import*\nimport utime\n_g1=[0,9,11,13,15]\n_g2=[0,0,0,0,0]\n_g3=False\n_g4=4\n_g5=NeoPixel(pin2,_g4)\n_g6=50\n_g7=40\n_g8=40\n_g9=0\n_g10=0\n_g11=0\n_g12=500\n_g13=29.1\ndef _f1(dirL,powerL,dirR,powerR):pinsL=pin1,pin12;pinsR=pin8,pin0;pinsL[dirL].write_analog(powerL);pinsL[1-dirL].write_analog(0);pinsR[dirR].write_analog(powerR);pinsR[1-dirR].write_analog(0)\ndef _f2(side,direction,power):\n if side==0:pins=pin1,pin12\n elif side==1:pins=pin8,pin0\n pins[direction].write_analog(power);pins[1-direction].write_analog(0)\ndef _f3(r):\n outerSpeed=_g6;rCm=int(r*100);threshold=outerSpeed-max(rCm+20,40)\n if threshold<=0:outerSpeed=min(max(rCm+40,40),100)\n reducedSpeed=0\n if rCm>=4:flattening=(100-outerSpeed)//2;reducedSpeed=(rCm*10-35)/(rCm*(11+(_g11-4)/10)+90+flattening);reducedSpeed=reducedSpeed*outerSpeed\n innerByte=_f6(int(reducedSpeed),0);outerByte=_f6(int(outerSpeed),0);return innerByte,outerByte\ndef _f4():global _g3;_g3=True;i2cData=bytearray(2);i2cData[0]=0;i2cData[1]=16;i2c.write(64,i2cData);i2cData[0]=254;i2cData[1]=101;i2c.write(64,i2cData);i2cData[0]=0;i2cData[1]=129;i2c.write(64,i2cData)\ndef _f5(pin,value,timeout):\n start_time=utime.ticks_us()\n while pin.read_digital()!=value:\n if utime.ticks_diff(utime.ticks_us(),start_time)>timeout:return 0\n start_time=utime.ticks_us()\n while pin.read_digital()==value:\n if utime.ticks_diff(utime.ticks_us(),start_time)>timeout:return 0\n return utime.ticks_diff(utime.ticks_us(),start_time)\ndef calibrate(offset,differential=0,arcScaling=0):global _g10;global _g9;global _g11;_g9=max(min(int(offset),500),-50);_g10=max(min(int(differential),150),-150);_g11=max(min(arcScaling,50),-15);setSpeed(_g6)\ndef setSpeed(speed):\n global _g6;global _g7;global _g8;_g6=int(min(max(speed,0),100));powerValue=_f6(_g6,_g9);boost=round((1-_g6/100)*abs(_g10))if _g6>0 else 0;reduction=round(_g6/100*abs(_g10))\n if _g10>0:_g7=powerValue-reduction;_g8=powerValue+boost\n else:_g7=powerValue+boost;_g8=powerValue-reduction\ndef _f6(speed,offset):analogValue=int(speed*1023/100)+offset;return min(max(analogValue,0),1023)\ndef stop():_f1(0,0,0,0)\ndef forward():_f1(0,_g7,0,_g8)\ndef backward():_f1(1,_g7,1,_g8)\ndef setServo(servoNum,angle):\n global _g1,_g3\n if _g3==False:_f4()\n offsetNum=servoNum;servoNum=_g1[servoNum];i2cData=bytearray(2);start=0;angle=max(min(angle,90),-90);stop=396+(angle+_g2[offsetNum])*223/90;i2cData[0]=6+servoNum*4+2;i2cData[1]=int(stop)+255;i2c.write(64,i2cData);i2cData[0]=6+servoNum*4+3;i2cData[1]=int(stop)>>8;i2c.write(64,i2cData)\ndef clearServos():setServo(0,0);setServo(1,0);setServo(2,0);setServo(3,0);setServo(4,0);sleep(500)\ndef steer(angle):angle=max(min(angle,45),-45);setServo(1,angle);setServo(2,-angle);setServo(3,-angle);setServo(4,angle);sleep(500)\ndef setLED(pos,red,green,blue):_g5[pos]=red,green,blue;_g5.show()\ndef fill(red,green,blue):\n for i in range(_g4):_g5[i]=red,green,blue\n _g5.show()\ndef getDistance():\n trig=pin13;echo=pin13;d=10;trig.set_pull(trig.NO_PULL)\n for _ in range(10):\n trig.write_digital(0);utime.sleep_us(2);trig.write_digital(1);utime.sleep_us(10);trig.write_digital(0);duration=_f5(echo,1,_g12*_g13)\n if duration>0:d=duration;break\n return round(d/_g13)\ndef calibrateServo(pos,angleDifferential):global _g2;angleDifferential=max(min(angleDifferential,90),-90);_g2[pos]=angleDifferential;clearServos()",
520
+ mbrobotmot: "import gc\nfrom microbit import i2c,pin1,pin2,pin8,pin12,pin13,pin14,sleep\nimport machine\nclass Motor:\n def __init__(A,id):A._id=2*id\n def rotate(A,s):\n B=abs(s)\n if s>0:A._f2(0,B)\n elif s<0:A._f2(1,B)\n else:A._f2(0,0)\n def _f2(A,d,s):\n try:i2c.write(16,bytearray([A._id,d,s]))\n except:\n print('Please switch on mbRobot!')\n while True:0\ndelay=sleep\ndef getDistance():pin1.write_digital(1);pin1.write_digital(0);B=machine.time_pulse_us(pin2,1,50000);A=int(B/58.2+.5);return A if A>0 else 255\ndef setLED(on):pin8.write_digital(on);pin12.write_digital(on)\npin2.set_pull(pin2.NO_PULL)\nirLeft=pin13\nirRight=pin14\nledLeft=pin8\nledRight=pin12\nmotL=Motor(0)\nmotR=Motor(1)",
521
+ controller: "_B=False\n_A=1.\nfrom microbit import run_every,pin13,pin14,pin15,pin16,pin8,pin1,pin2,pin12,button_a,button_b,sleep\nclass _Controller_Button:\n def __init__(A,pin):B=pin;A._pin=B;A.previous_state=0;A._press_count=0;A._pressed_before=_B;B.set_pull(B.PULL_UP)\n def _f3(A):\n B=1-A._pin.read_digital()\n if B==1 and A.previous_state==0:A._press_count+=1;A._pressed_before=True\n A.previous_state=B\n def is_pressed(A):return _B if A._pin.read_digital()else True\n def was_pressed(A):B=A._pressed_before;A._pressed_before=_B;return B\n def get_presses(A):B=A._press_count;A._press_count=0;return B\nclass _Controller_Analog_Stick:\n def __init__(A,pinX,pinY,pinZ):A.pin_x=pinX;A.pin_y=pinY;A.button_z=_Controller_Button(pinZ);A.dead_zone=.01;A.center_x=0;A.center_y=0;A.min_x=-1;A.max_x=1;A.min_y=-1;A.max_y=1\n def calibrate(A,dead_zone,center_x=.0,center_y=.0,x_min=-_A,x_max=_A,y_min=-_A,y_max=_A):A.dead_zone=min(.2,max(.01,dead_zone));A.center_x=min(.4,max(-.4,center_x));A.center_y=min(.5,max(-.5,center_y));A.min_x=min(-.5,max(-_A,x_min));A.max_x=min(_A,max(.5,x_max));A.min_y=min(-.5,max(-_A,y_min));A.max_y=min(_A,max(.5,y_max))\n def _f5(C,value,center,v_min,v_max):\n B=center;A=value-_A-B\n if abs(A)-C.dead_zone/2.>.0:\n if A<.0:A=A/abs(v_min-B)\n else:A=A/abs(v_max-B)\n A=min(_A,max(-_A,A));A=.0 if abs(A)<=C.dead_zone else A;return A\n def get_x(A):B=A.pin_x.read_analog()/512.;C=A._f5(B,A.center_x,A.min_x,A.max_x);return C\n def get_y(A):B=A.pin_y.read_analog()/512.;C=A._f5(B,A.center_y,A.min_y,A.max_y);return C\n def get_z(A):return 1 if A.button_z.is_pressed()else 0\n def is_pressed(A):return A.button_z.is_pressed()\n def was_pressed(A):return A.button_z.was_pressed()\n def get_presses(A):return A.button_z.get_presses()\ndef vibrate(state):pin12.write_digital(state)\njoystick=_Controller_Analog_Stick(pin1,pin2,pin8)\nbutton_z=joystick.button_z\nbutton_c=_Controller_Button(pin13)\nbutton_green=button_c\nbutton_d=_Controller_Button(pin14)\nbutton_yellow=button_d\nbutton_e=_Controller_Button(pin15)\nbutton_red=button_e\nbutton_f=_Controller_Button(pin16)\nbutton_blue=button_f\ntrigger_left=button_a\ntrigger_right=button_b\ndef _f1():global button_c;global button_d;global button_e;global button_f;global joystick;button_c._f3();button_d._f3();button_e._f3();button_f._f3();joystick.button_z._f3()\nrun_every(_f1,days=0,h=0,min=0,s=0,ms=33)",
522
+ mbxgo: "from microbit import*\n_g1=50\n_g2=False\n_g3=pin14\n_g4=pin13\ndef checkInit(func):\n def wrapper(*args,**kwargs):\n global _g2\n if not _g2:init_xgo_serial(_g3,_g4)\n return func(*args,**kwargs)\n return wrapper\ndef _f1(speed,in_min,in_max,out_min,out_max):return(speed-in_min)*(out_max-out_min)//(in_max-in_min)+out_min\n@checkInit\ndef _f2(direction,speed):\n move_buffer=bytearray(9);move_buffer[0]=85;move_buffer[1]=0;move_buffer[2]=9;move_buffer[3]=0;move_buffer[7]=0;move_buffer[8]=170;speed=max(0,min(100,speed))\n if direction==0:move_buffer[4]=48;move_buffer[5]=_f1(speed,0,100,128,255)\n elif direction==1:move_buffer[4]=48;move_buffer[5]=_f1(speed,0,100,128,0)\n elif direction==2:move_buffer[4]=49;move_buffer[5]=_f1(speed,0,100,128,0)\n elif direction==3:move_buffer[4]=49;move_buffer[5]=_f1(speed,0,100,128,255)\n move_buffer[6]=~(9+move_buffer[4]+move_buffer[5])&255;uart.write(move_buffer)\n@checkInit\ndef clampX(milimeters=50):clampBuffer=bytearray(9);clampBuffer[0]=85;clampBuffer[1]=0;clampBuffer[2]=9;clampBuffer[3]=0;clampBuffer[4]=115;clampBuffer[7]=0;clampBuffer[8]=170;clampBuffer[5]=milimeters;clampBuffer[6]=~(124+clampBuffer[5])&255;uart.write(clampBuffer);sleep(1000)\n@checkInit\ndef clampZ(milimeters=50):clampBuffer=bytearray(9);clampBuffer[0]=85;clampBuffer[1]=0;clampBuffer[2]=9;clampBuffer[3]=0;clampBuffer[4]=116;clampBuffer[7]=0;clampBuffer[8]=170;clampBuffer[5]=milimeters;clampBuffer[6]=~(125+clampBuffer[5])&255;uart.write(clampBuffer);sleep(1000)\n@checkInit\ndef clamp(force):clampBuffer=bytearray(9);clampBuffer[0]=85;clampBuffer[1]=0;clampBuffer[2]=9;clampBuffer[3]=0;clampBuffer[4]=113;clampBuffer[7]=0;clampBuffer[8]=170;clampBuffer[5]=force;clampBuffer[6]=~(122+clampBuffer[5])&255;uart.write(clampBuffer);sleep(1000)\ndef init_xgo_serial(tx_pin,rx_pin,baudrate=115200):global _g2;uart.init(baudrate=baudrate,tx=tx_pin,rx=rx_pin);init_action();_g2=True\ndef init_action():commands_buffer=bytearray(9);commands_buffer[0]=85;commands_buffer[1]=0;commands_buffer[2]=9;commands_buffer[3]=0;commands_buffer[4]=62;commands_buffer[5]=255;commands_buffer[6]=185;commands_buffer[7]=0;commands_buffer[8]=170;uart.write(commands_buffer);sleep(2000)\n@checkInit\ndef action(id):commands_buffer=bytearray(9);commands_buffer[0]=85;commands_buffer[1]=0;commands_buffer[2]=9;commands_buffer[3]=0;commands_buffer[4]=62;commands_buffer[5]=id;commands_buffer[6]=~(71+id)&255;commands_buffer[7]=0;commands_buffer[8]=170;uart.write(commands_buffer);sleep(2000)\ndef changeInit(tx,rx):global _g3;global _g4;_g3=tx;_g4=rx;init_xgo_serial(_g3,_g4)\n@checkInit\ndef setSpeed(speed):global _g1;_g1=speed\ndef forward():_f2(0,_g1)\ndef backward():_f2(1,_g1)\ndef left():_f2(2,_g1)\ndef right():_f2(3,_g1)",
523
+ mbglow: `from microbit import*
524
+ _g1=0
525
+ _g2=0
526
+ _g3=0
527
+ _g4=50
528
+ _g5=True
529
+ _g6=False
530
+ def makeGlow():global _g6;display.set_pixel(2,2,9);_g6=True
531
+ def clear():display.clear()
532
+ def forward():_f1(1)
533
+ def back():_f1(-1)
534
+ def right(angle):global _g3;_g3=(_g3+angle)%360
535
+ def left(angle):right(-angle)
536
+ def setPos(x,y):global _g1,_g2;_g1=x;_g2=y;_f2()
537
+ def getPos():return _g1,_g2
538
+ def setSpeed(speed):global _g4;_g4=speed
539
+ def showTrace(enable):global _g5;_g5=enable
540
+ def isLit():return display.get_pixel(_g1+2,4-(_g2+2))==9
541
+ def _f1(s):
542
+ global _g1,_g2;sleep(2000-_g4*20);d=_g3//45
543
+ if d in[1,2,3]:_g1+=s
544
+ if d in[5,6,7]:_g1-=s
545
+ if d in[0,1,7]:_g2+=s
546
+ if d in[3,4,5]:_g2-=s
547
+ _f2()
548
+ def _f2():
549
+ if not _g6:print('Use "makeGlow()" to create a Glow.');raise Exception('Glow not initialized.')
550
+ if not _g5:display.clear()
551
+ if-2<=_g1<=2 and-2<=_g2<=2:display.set_pixel(_g1+2,4-(_g2+2),9)`,
552
+ mbthetabot: `from microbit import*
553
+ from utime import ticks_us,sleep_us
554
+ from neopixel import*
555
+ _g1=50
556
+ _g2=40
557
+ _g3=40
558
+ _g4=bytes(b'\\x00\\x0b\\x0b\\x0c\\x0c\\r\\r\\r\\x0e\\x0e\\x0f\\x0f\\x0f\\x10\\x10\\x11\\x11\\x11\\x12\\x12\\x13\\x13\\x13\\x14\\x14\\x15\\x15\\x15\\x16\\x16\\x17\\x17\\x17\\x18\\x19\\x1a\\x1b\\x1b\\x1c\\x1d\\x1e\\x1f !"##$%&\\'()*++,-./0123468:<?ADFILOSVZ^bgkpu{\\x81\\x87\\x8d\\x94\\x9b\\xa3\\xab\\xb4\\xbd\\xc6\\xd0\\xdb\\xe6\\xf2\\xff')
559
+ _g5=0
560
+ _g6=0
561
+ _g7=0
562
+ _g8=34
563
+ _g9=14
564
+ def _f1(dirL,powerL,dirR,powerR):pinsL=pin14,pin13;pinsR=pin16,pin15;pinsL[dirL].write_analog(powerL);pinsL[1-dirL].write_analog(0);pinsR[dirR].write_analog(powerR);pinsR[1-dirR].write_analog(0)
565
+ def _f2(side,direction,power):
566
+ if side==0:pins=pin14,pin13
567
+ elif side==2:pins=pin16,pin15
568
+ pins[direction].write_analog(power);pins[1-direction].write_analog(0)
569
+ def _f3(r):
570
+ outerSpeed=_g1;rCm=int(r*100);threshold=outerSpeed-max(rCm+20,40)
571
+ if threshold<=0:outerSpeed=min(max(rCm+40,40),100)
572
+ reducedSpeed=0
573
+ if rCm>=4:flattening=(100-outerSpeed)//2;reducedSpeed=(rCm*10-35)/(rCm*(11+(_g7-4)/10)+90+flattening);reducedSpeed=reducedSpeed*outerSpeed
574
+ innerByte=_f4(int(reducedSpeed),0);outerByte=_f4(int(outerSpeed),0);return innerByte,outerByte
575
+ def calibrate(offset,differential=0,arcScaling=0):global _g6;global _g5;global _g7;_g5=max(min(int(offset),150),-10);_g6=max(min(int(differential),150),-150);_g7=max(min(arcScaling,50),-15);setSpeed(_g1)
576
+ def setSpeed(speed):
577
+ global _g1;global _g2;global _g3;_g1=int(min(max(speed,0),100));powerByte=_f4(_g1,_g5);boost=round((1-_g1/100)*abs(_g6))if _g1>0 else 0;reduction=round(_g1/100*abs(_g6))
578
+ if _g6>0:_g2=powerByte-reduction;_g3=powerByte+boost
579
+ else:_g2=powerByte+boost;_g3=powerByte-reduction
580
+ def _f4(speed,offset):speedIndex=int(speed*(len(_g4)-1)/100);return min(_g4[speedIndex]+offset,1023)
581
+ def stop():_f1(0,0,0,0)
582
+ def forward():_f1(0,_g2,0,_g3)
583
+ def backward():_f1(1,_g2,1,_g3)
584
+ def left():_f1(1,_g2,0,_g3)
585
+ def right():_f1(0,_g2,1,_g3)
586
+ def rightArc(radius):inner,outer=_f3(radius);_f1(0,outer,0,inner)
587
+ def leftArc(radius):inner,outer=_f3(radius);_f1(0,inner,0,outer)
588
+ def getDistance():
589
+ pin12.write_digital(1);sleep_us(10);pin12.write_digital(0);pin12.set_pull(pin15.NO_PULL)
590
+ while pin12.read_digital()==0:0
591
+ start=ticks_us()
592
+ while pin12.read_digital()==1:0
593
+ end=ticks_us();echo=end-start;distance=int(.01715*echo);return distance
594
+ def setLED(position,red,green,blue):global _g8;i2c_data=bytearray(5);i2c_data[0]=1;i2c_data[1]=position;i2c_data[2]=red;i2c_data[3]=green;i2c_data[4]=blue;i2c.write(_g8,i2c_data)
595
+ def fill(red,green,blue):
596
+ for position in range(_g9):setLED(position,red,green,blue)
597
+ def readLine(side):i2c.write(_g8,bytearray([side+1]),False);result=i2c.read(_g8,2);result=result[0]+(result[1]<<8);return result
598
+ def readLight(side):i2c.write(_g8,bytearray([side+3]),False);result=i2c.read(_g8,2);result=result[0]+(result[1]<<8);return result`,
599
+ mbrobot_legacy: "import gc\nfrom microbit import i2c,pin1,pin2,pin8,pin12,pin13,pin14,sleep\nimport machine\n_g1=.097\ndef w(d1,d2,s1,s2):\n try:i2c.write(16,bytearray([0,d1,s1]));i2c.write(16,bytearray([2,d2,s2]))\n except:\n print('Please switch on mbRobot!')\n while True:0\ndef setSpeed(speed):\n A=speed;global _g2\n if A<20:_g2=A+5\n else:_g2=A\ndef forward():w(0,0,_g2,_g2)\ndef backward():w(1,1,_g2,_g2)\ndef stop():w(0,0,0,0)\ndef right():w(0 if _g2>0 else 1,1 if _g2>0 else 0,int(_g2*.9),int(_g2*.9))\ndef left():w(1 if _g2>0 else 0,0 if _g2>0 else 1,int(_g2*.9),int(_g2*.9))\ndef rightArc(r):\n A=abs(_g2)\n if r<_g1:B=0\n else:C=(r-_g1)/(r+_g1)*(1-A*A/200000);B=int(C*A)\n if _g2>0:w(0,0,A,B)\n else:w(1,1,B,A)\ndef leftArc(r):\n A=abs(_g2)\n if r<_g1:B=0\n else:C=(r-_g1)/(r+_g1)*(1-A*A/200000);B=int(C*A)\n if _g2>0:w(0,0,B,A)\n else:w(1,1,A,B)\nexit=stop\ndelay=sleep\ndef getDistance():pin1.write_digital(1);pin1.write_digital(0);B=machine.time_pulse_us(pin2,1,50000);A=int(B/58.2+.5);return A if A>0 else 255\ndef setLED(on):pin8.write_digital(on);pin12.write_digital(on)\ndef setServo(S,Angle):\n if S=='S1':A=20\n if S=='S2':A=21\n B=A,Angle;i2c.write(16,bytes(B))\npin2.set_pull(pin2.NO_PULL)\n_g2=50\nirLeft=pin13\nirRight=pin14\nledLeft=pin8\nledRight=pin12\nforward()",
600
+ mbalarm: "import music\n_g1=['c6:1','r','c6,1','r','r','r']\ndef setAlarm(on):\n if on:music.play(_g1,wait=False,loop=True)\n else:music.stop()\ndef beep():music.pitch(2000,200,wait=False)",
601
+ mbminibit: "from microbit import*\nfrom neopixel import*\nimport utime\n_g1=4\n_g2=NeoPixel(pin13,_g1)\n_g3=50\n_g4=90\n_g5=90\n_g6=0\n_g7=0\n_g8=0\n_g9=500\n_g10=29.1\ndef _f1(dirL,powerL,dirR,powerR):pin8.write_analog(powerL if dirL==1 else 0);pin12.write_analog(0 if dirL==1 else powerL);pin16.write_analog(0 if dirR==1 else powerR);pin14.write_analog(powerR if dirR==1 else 0)\ndef _f2(pin,value,timeout):\n start_time=utime.ticks_us()\n while pin.read_digital()!=value:\n if utime.ticks_diff(utime.ticks_us(),start_time)>timeout:return 0\n start_time=utime.ticks_us()\n while pin.read_digital()==value:\n if utime.ticks_diff(utime.ticks_us(),start_time)>timeout:return 0\n return utime.ticks_diff(utime.ticks_us(),start_time)\ndef _f3(r):\n outerSpeed=_g3\n if r>0:innerSpeed=outerSpeed*max(.2,min(1,1-r/100))\n else:innerSpeed=0\n innerByte=_f4(int(innerSpeed),0);outerByte=_f4(int(outerSpeed),0);return innerByte,outerByte\ndef _f4(speed,offset):analogValue=int(speed*255/100)+offset;return min(max(analogValue,0),255)\ndef calibrate(offset,differential=0,arcScaling=0):global _g7;global _g6;global _g8;_g6=max(min(int(offset),100),-10);_g7=max(min(int(differential),150),-150);_g8=max(min(arcScaling,50),-15);setSpeed(_g3)\ndef setSpeed(speed):\n global _g3;global _g4;global _g5;_g3=int(min(max(speed,0),100));powerByte=_f4(_g3,_g6);boost=round((1-_g3/100)*abs(_g7))if _g3>0 else 0;reduction=round(_g3/100*abs(_g7))\n if _g7>0:_g4=powerByte-reduction;_g5=powerByte+boost\n else:_g4=powerByte+boost;_g5=powerByte-reduction\ndef stop():_f1(0,0,0,0)\ndef forward():_f1(0,_g4,0,_g5)\ndef backward():_f1(1,_g4,1,_g5)\ndef left():_f1(1,_g4,0,_g5)\ndef right():_f1(0,_g4,1,_g5)\ndef rightArc(radius):inner,outer=_f3(radius);_f1(0,outer,0,inner)\ndef leftArc(radius):inner,outer=_f3(radius);_f1(0,inner,0,outer)\ndef setLED(pos,red,green,blue):_g2[pos]=red,green,blue;_g2.show()\ndef fill(red,green,blue):\n for i in range(_g1):_g2[i]=red,green,blue\n _g2.show()\ndef getDistance():\n trig=pin15;echo=pin15;d=10;trig.set_pull(trig.NO_PULL)\n for _ in range(10):\n trig.write_digital(0);utime.sleep_us(2);trig.write_digital(1);utime.sleep_us(10);trig.write_digital(0);duration=_f2(echo,1,_g9*_g10)\n if duration>0:d=duration;break\n return round(d/_g10)",
602
+ mbrobot_plusV2: `from microbit import i2c,pin0,pin1,pin2,pin13,pin14,pin15,sleep
603
+ import gc,machine,music,neopixel
604
+ _g1=50
605
+ _g2=50
606
+ _g3=50
607
+ _g4=bytearray(5)
608
+ _g5=bytes(b'\\x00\\x0f\\x10\\x10\\x11\\x12\\x12\\x13\\x13\\x14\\x15\\x15\\x16\\x16\\x17\\x18\\x18\\x19\\x19\\x1a\\x1b\\x1b\\x1c\\x1c\\x1d\\x1e\\x1e\\x1f\\x1f !!""#$$%%&\\')*+,-./0123456789:;;<>?ACEGIKMPRUX[^aeimquz\\x7f\\x84\\x89\\x8f\\x95\\x9b\\xa2\\xa9\\xb1\\xb9\\xc1\\xca\\xd3\\xdd\\xe8\\xf3\\xff')
609
+ _g6=0
610
+ _g7=0
611
+ _g8=0
612
+ _g9=25
613
+ _g10=131
614
+ _g11=bytearray(b'\\x0b\\x00\\x00')
615
+ _g12=neopixel.NeoPixel(pin15,4)
616
+ np_rgb_pixels=_g12
617
+ _g13=['c5:1','r','c5,1','r:3']
618
+ _g14='Please connect to Maqueen robot and switch it on.'
619
+ def _f1(dirL,powerL,dirR,powerR):
620
+ global _g4;_g4[1]=dirL;_g4[2]=powerL;_g4[3]=dirR;_g4[4]=powerR
621
+ try:i2c.write(16,_g4)
622
+ except:raise RuntimeError(_g14)
623
+ def _f2(side,dir,power):
624
+ global _g4;_g4[1+side]=dir;_g4[2+side]=power
625
+ try:i2c.write(16,_g4)
626
+ except:raise RuntimeError(_g14)
627
+ def _f3(speed,offset):return min(_g5[speed]+offset,255)
628
+ def _f4(r):
629
+ B=int(r*100);A=_g1
630
+ if A<25:A=25
631
+ H=min(abs(A-70),20)/20;C=0
632
+ if B>5:
633
+ D=A*(3*_g8-A-9*B+220);E=-14*_g8+A-200+3*A-10*B-290;C=int(D/E)
634
+ if C<2:C=2 if B>15 else 1
635
+ F=_f3(int(C),0);G=_f3(int(A),0);return F,G
636
+ def calibrate(offset,differential=0,arcScaling=0):global _g7;global _g6;global _g8;_g6=max(min(int(offset),50),-14);_g7=max(min(int(differential),150),-150);_g8=max(min(arcScaling,50),-50);setSpeed(_g1)
637
+ def setSpeed(speed):
638
+ global _g1;global _g2;global _g3;_g1=int(min(max(speed,0),100));A=_f3(_g1,_g6);B=round((1-_g1/100)*abs(_g7))if _g1>0 else 0;C=round(_g1/100*abs(_g7))
639
+ if _g7>0:_g2=A-C;_g3=A+B
640
+ else:_g2=A+B;_g3=A-C
641
+ def resetSpeed():setSpeed(50)
642
+ def stop():_f1(0,0,0,0)
643
+ def forward():_f1(0,_g2,0,_g3)
644
+ def backward():_f1(1,_g2,1,_g3)
645
+ def left():_f1(1,_g2,0,_g3)
646
+ def right():_f1(0,_g2,1,_g3)
647
+ def rightArc(radius):A,B=_f4(radius);_f1(0,B,0,A)
648
+ def leftArc(radius):A,B=_f4(radius);_f1(0,A,0,B)
649
+ class Motor:
650
+ def __init__(A,side):A._side=side
651
+ def rotate(B,speed):A=speed;C=int(min(max(abs(A),0),100));D=_f3(C,_g6);E=0 if A>0 else 1;_f2(B._side,E,D)
652
+ def setServo(servo,angle):
653
+ D=angle;A=servo
654
+ if A=='P0'or A=='S1':B=pin0
655
+ elif A=='P1'or A=='S2':B=pin1
656
+ elif A=='P2':B=pin2
657
+ else:raise ValueError("Unknown Servo. Please use 'P0', 'P1' or 'P2'.")
658
+ if D<0 or D>180:raise ValueError('Invalid angle. Must be between 0 and 180')
659
+ C=(_g10-_g9)*int(D);E=(C>>8)+(C>>10)+(C>>11)+(C>>12);F=_g9+E;B.set_analog_period(20);B.write_analog(F)
660
+ def setMinAngleVal(duty):global _g9;_g9=int(duty)
661
+ def setMaxAngleVal(duty):global _g10;_g10=int(duty)
662
+ class IRSensor:
663
+ _g21=bytes(b'\\x1d')
664
+ def __init__(A,index):A._index=index
665
+ def read_digital(A):
666
+ try:i2c.write(16,IRSensor._g21)
667
+ except:raise RuntimeError(_g14)
668
+ B=~i2c.read(16,1)[0];return(B&2**A._index)>>A._index
669
+ def read_analog(A):
670
+ try:i2c.write(16,IRSensor._g21)
671
+ except:raise RuntimeError(_g14)
672
+ B=i2c.read(16,11);return B[1+A._index*2]
673
+ def ir_read_values_as_byte():i2c.write(16,bytearray([29]));A=i2c.read(16,1);return~A[0]
674
+ def getDistance():pin13.write_digital(1);pin13.write_digital(0);A=machine.time_pulse_us(pin14,1,50000);B=(A>>6)+(A>>10)+(A>>11)+(A>>12)+1;return max(min(B,500),0)if B>0 else 255
675
+ def setLED(state,stateR=None):B=state;A=stateR;global _g11;A=A if A!=None else B;_g11[1]=B;_g11[2]=A;i2c.write(16,_g11)
676
+ def setLEDLeft(state):global _g11;_g11[1]=state;i2c.write(16,_g11)
677
+ def setLEDRight(state):global _g11;_g11[2]=state;i2c.write(16,_g11)
678
+ def fillRGB(red,green,blue):
679
+ for A in range(4):_g12[A]=red,green,blue
680
+ _g12.show()
681
+ setRGB=fillRGB
682
+ def clearRGB():_g12.clear()
683
+ def posRGB(position,red,green,blue):
684
+ A=position
685
+ if A<0 or A>3:raise ValueError('invalid RGB-LED position. Must be 0,1,2 or 3.')
686
+ _g12[A]=red,green,blue;_g12.show()
687
+ def setAlarm(state):
688
+ if state:music.play(_g13,wait=False,loop=True)
689
+ else:music.stop()
690
+ def beep():music.pitch(440,200,wait=False)
691
+ class LEDState:ON=1;OFF=0;RED=1
692
+ class IR:R2=0;R1=1;M=2;L1=3;L2=4;masks=[1,2,4,8,16]
693
+ pin2.set_pull(pin2.NO_PULL)
694
+ delay=sleep
695
+ irR2=IRSensor(0)
696
+ irR1=IRSensor(1)
697
+ irRight=irR1
698
+ irM=IRSensor(2)
699
+ irL1=IRSensor(3)
700
+ irLeft=irL1
701
+ irL2=IRSensor(4)
702
+ motL=Motor(0)
703
+ motR=Motor(2)`
704
+ };
705
+
706
+ // microbit/libraries.raw.json
707
+ var libraries_raw_default2 = {
708
+ huskylens: `# For Huskylens (PRO inclusive) with Firmware version 0.5.1Norm or 0.5.3Alpha1.
709
+ from microbit import i2c, sleep, running_time
710
+ import math
711
+
712
+ _algorithm_names = ["FaceRecognition",
713
+ "ObjectTracking",
714
+ "ObjectRecognition",
715
+ "LineTracking",
716
+ "ColorRecognition",
717
+ "TagRecognition",
718
+ "ObjectClassification",
719
+ "QRRecognition",
720
+ "BarcodeRecognition"]
721
+
722
+ class Request_Command:
723
+ # """Command Codes that can be sent to the Huskylens.""""
724
+ KNOCK = 0x2C
725
+ ALGORITHM = 0x2D
726
+ ALL = 0x20
727
+ BLOCKS = 0x21
728
+ BLOCKS_LEARNED = 0x24
729
+ BLOCKS_OF_ID = 0x27
730
+ ARROWS = 0x22
731
+ ARROWS_LEARNED = 0x25
732
+ ARROWS_OF_ID = 0x28
733
+ LEARNED = 0x23
734
+ ALL_OF_ID = 0x26
735
+ LEARN = 0x36
736
+ FORGET = 0x37
737
+ CUSTOM_LABEL = 0x2F
738
+ CUSTOM_TEXT = 0x34
739
+ CLEAR_TEXT = 0x35
740
+ SAVE_MODEL = 0x32
741
+ LOAD_MODEL = 0x33
742
+ SAVE_PHOTO = 0x30
743
+ SAVE_SCREENSHOT = 0x39
744
+ IS_PRO = 0x3B
745
+ VERSION = 0x3C
746
+
747
+ class Return_Code:
748
+ # """Return codes that identify answer types, received from the Huskylens."""
749
+ ANY = 0x01 # custom command for "don't care", never returned by Huskylens
750
+ OK = 0x2E
751
+ BUSY = 0x3D
752
+ INFO = 0x29
753
+ BLOCK = 0x2A
754
+ ARROW = 0x2B
755
+ IS_PRO = 0x3B
756
+ NEED_PRO = 0x3E
757
+
758
+ class Algorithm:
759
+ FACE_RECOGNITION = 0
760
+ OBJECT_TRACKING = 1
761
+ OBJECT_RECOGNITION = 2
762
+ LINE_TRACKING = 3
763
+ COLOR_RECOGNITION = 4
764
+ TAG_RECOGNITION = 5
765
+ OBJECT_CLASSIFICATION = 6
766
+ QR_RECOGNITION = 7
767
+ BARCODE_RECOGNITION = 8
768
+
769
+ class Block:
770
+ # """Create a new Block with (x,y) as its center and (width,height) as its extent. Id is learned id on Huskylens.
771
+ # Blocks are returned by all Algorithms except for Line_Recognition. """
772
+ def __init__(self, x, y, width, height, id):
773
+ self.x = x
774
+ self.y = y
775
+ self.width = width
776
+ self.height = height
777
+ self.id = id
778
+
779
+ def __str__(self):
780
+ return "Block: ID_" + str(self.id) + " Pos: (" + str(self.x) + " " + str(self.y) + ") Size: (" + str(self.width) + " " + str(self.height) + ")"
781
+
782
+ class Arrow:
783
+ # """Create a new Arrow from (x,y)_tail to (x,y)_head. Id is learned id on Huskylens.
784
+ # Arrows are returned only for the Line Recognition Algorithm. """
785
+ def __init__(self, x_tail, y_tail, x_head, y_head, id):
786
+ self.x_tail = x_tail
787
+ self.y_tail = y_tail
788
+ self.x_head = x_head
789
+ self.y_head = y_head
790
+ self.id = id
791
+
792
+ def get_direction(self):
793
+ dx = self.x_head - self.x_tail
794
+ dy = self.y_head - self.y_tail
795
+ deg = 90 - math.degrees(math.atan2(dy, dx))
796
+ if deg < 0: deg = deg + 360
797
+ return int(deg)
798
+
799
+ def __str__(self):
800
+ return "Arrow: ID_" + str(self.id) + " (" + str(self.x_tail) + " " + str(self.y_tail) + ")->(" + str(self.x_head) + " " + str(self.y_head) + ")"
801
+
802
+ def byte_checksum(byte_list):
803
+ # """Computes the checksum and returns the low byte of the sum."""
804
+ return sum(byte_list) & 0xFF
805
+
806
+ def hexify(byte_array):
807
+ # """Takes arraylike of bytes and converts it to hex string for pretty-printing."""
808
+ if len(byte_array) == 0: return ""
809
+ return "0x" + "".join("{:02x}".format(i) for i in byte_array)
810
+
811
+ class Huskylens:
812
+
813
+ I2C_ADDR = 0x32
814
+
815
+ def __init__(self):
816
+ # """Create a new Huskylens instance.
817
+ #
818
+ # A Huskylens instance is necessary for further communication.
819
+ #
820
+ # The Huskylens has its own internal state that can't be known by this instance if
821
+ # a Huskylens is operated manually or has data stored in advance (names, learned id's).
822
+ # """
823
+ self.learned_slot_count = 0
824
+ self.id_slots = {} # id to learning-slots.
825
+ self.id_names = {} # id to string
826
+ self.algorithm = Algorithm.OBJECT_TRACKING
827
+ self.clear_texts()
828
+ self.pro_enabled = self.is_pro()
829
+
830
+ def initialize(self):
831
+ # """Establishes Connection to Huskylens. Then clears custom Texts and activates Algorithm Object Tracking.
832
+
833
+ # First, knocks at most 5 times to setup connection.
834
+ # If successful, clears custom text and changes Algorithm to OBJECT_TRACKING.
835
+ # Learned ids and labels are kept from previous uses if available.
836
+ #
837
+ # Returns:
838
+ # bool: Wheter initialization was successfull.
839
+ # """
840
+ success = False
841
+ for i in range(5):
842
+ self.knock()
843
+ success, _ = self.get_response(Return_Code.OK)
844
+ if success:
845
+ break
846
+
847
+ if success > 0:
848
+ s = self.clear_texts()
849
+ s2 = self.set_algorithm(Algorithm.OBJECT_TRACKING)
850
+ if s and s2:
851
+ print("Initialization successful!")
852
+ return True
853
+ else:
854
+ print("Initialization Failed. Couldn't change Algorithm")
855
+ return False
856
+ else:
857
+ print("Initialization Failed. Please check connection to Huskylens.")
858
+ return False
859
+
860
+ # Low Level communication commands (deal with byte-data yourself)
861
+
862
+ def send_request(self, command, data=None):
863
+ # """Request an action from the Huskylens through a command code and optional Data Bytes.
864
+ #
865
+ # Parameters:
866
+ # command (byte): a Request_Command byte to be sent.
867
+ # data (list of bytes | None): Optional data to attach to the request or None.
868
+ # """
869
+ buffer = bytearray(b'\\x55\\xAA\\x11\\x00\\x00')
870
+ buffer[3] = 0 if data is None else len(data)
871
+ buffer[4] = command
872
+ if data:
873
+ for b in data:
874
+ buffer.append(b)
875
+ buffer.append(byte_checksum(buffer))
876
+ # print("request:", hexify(buffer))
877
+ i2c.write(Huskylens.I2C_ADDR, buffer)
878
+ sleep(50)
879
+
880
+ def get_response(self, return_code=Return_Code.ANY, timeout=500):
881
+ # """Read a response from I2C. Returns after a timeout when no data available.
882
+ # If a specific return code is expected and given as a parameter, all other results will set the returned code to 0.
883
+ # If a timeout occured, the return code is set to -1. Other errors return -2.
884
+ # This way, the return code is positive upon success, and negative or 0 otherwise.
885
+ #
886
+ # Parameters:
887
+ # return_code (byte): Optional expected return code.
888
+ # timeout (int): milliseconds to wait for response before giving up
889
+ #
890
+ # Returns:
891
+ # (code | error, data list): A tuple containing the return code or the error code as a signed byte in the first part
892
+ # The data as a list of bytes in the second argument or an empty list if nothing was sent along.
893
+ # """
894
+ response_header = bytearray(b"\\x55\\0\\0\\0\\0")
895
+ start_time = running_time()
896
+
897
+ # bytewise polling, as there seem to be unpredictable 0 bytes between messages!
898
+ #response_header = i2c.read(Huskylens.I2C_ADDR, 5, True)
899
+ while running_time() - start_time < timeout:
900
+ byte = i2c.read(Huskylens.I2C_ADDR, 1)[0]
901
+ if byte == 0x55:
902
+ break
903
+ if byte != 0x55:
904
+ return -1, [] # Timeout error
905
+
906
+ # reading rest of header data
907
+ for i in range(4):
908
+ response_header[i+1] = i2c.read(Huskylens.I2C_ADDR, 1)[0]
909
+
910
+ if response_header[0:3] != b'\\x55\\xAA\\x11':
911
+ return -2, [] # Wrong header structure error
912
+
913
+ data_length = response_header[3]
914
+ response_type = response_header[4]
915
+
916
+ data = []
917
+ if data_length > 0:
918
+ response_body = i2c.read(Huskylens.I2C_ADDR, data_length+1)
919
+ data = response_body[0:-1]
920
+ response_checksum = response_body[-1]
921
+ else:
922
+ response_checksum = ord(i2c.read(Huskylens.I2C_ADDR, 1))
923
+ if response_checksum != byte_checksum(list(response_header) + data):
924
+ return -3, [] # Checksum Error
925
+
926
+ # print("response: " + hexify([response_type]) + " " + hexify(data))
927
+ if return_code == Return_Code.ANY or response_type == return_code:
928
+ return response_type, data
929
+ else:
930
+ return 0, data # not expected answer Hint
931
+
932
+ def knock(self):
933
+ self.send_request(Request_Command.KNOCK)
934
+
935
+ # High level commands for students
936
+
937
+ def set_algorithm(self, algorithm):
938
+ # """ Change the active algorithm on the Huskylens. Returns True on success."""
939
+ if (algorithm == Algorithm.QR_RECOGNITION or algorithm == Algorithm.BARCODE_RECOGNITION) and (not self.pro_enabled):
940
+ raise RuntimeError("Error: Huskylens PRO version is required for algorithm ", _algorithm_names[algorithm])
941
+ return False
942
+ data = [algorithm, 0x00]
943
+ self.send_request(Request_Command.ALGORITHM, data)
944
+ success, _ = self.get_response(Return_Code.OK)
945
+ if success > 0:
946
+ print("Current Algorithm:", _algorithm_names[algorithm])
947
+ self.algorithm = algorithm
948
+ return True if success > 0 else False
949
+
950
+ def get_all(self):
951
+ # """Get All detected objects, Blocks or Arrows as a list."""
952
+ return self._get_results(Request_Command.ALL)
953
+
954
+ def get_all_learned(self):
955
+ # """Get all detected objects that are learned as a list."""
956
+ return self._get_results(Request_Command.LEARNED)
957
+
958
+ def get_all_with_id(self, id):
959
+ # """Get all detected objects with specific id as a list."""
960
+ if id <= 0 or id > 255:
961
+ raise RuntimeError("Error: ID must be in range from 1 to 255.")
962
+ return self._get_results(Request_Command.ALL_OF_ID, id)
963
+
964
+ def get_one(self):
965
+ # """Get one instance of centermost detected object (Block or Arrow) else None."""
966
+ results = self._get_results(Request_Command.ALL)
967
+ return self._get_centermost(results)
968
+
969
+ def get_one_learned(self):
970
+ # """Get one instance of centermost detected object that has an id > 0. else None."""
971
+ results = self._get_results(Request_Command.LEARNED)
972
+ return self._get_centermost(results)
973
+
974
+ def get_one_with_id(self, id):
975
+ # """Get one instance of centermost detected object that has given id. else None."""
976
+ if id <= 0 or id > 255:
977
+ raise RuntimeError("Error: ID must be in range from 1 to 255.")
978
+ results = self._get_results(Request_Command.ALL_OF_ID, id)
979
+ return self._get_centermost(results)
980
+
981
+ def attach_label(self, id, name):
982
+ # """Attach the label "name" to a learned id of current Algorithm. Returns True on success."""
983
+ if self.algorithm == Algorithm.OBJECT_TRACKING or \\
984
+ self.algorithm == Algorithm.LINE_TRACKING: # single learn algorithms
985
+ success = self._set_name(1, name)
986
+ elif self.algorithm == Algorithm.FACE_RECOGNITION or \\
987
+ self.algorithm == Algorithm.TAG_RECOGNITION or \\
988
+ self.algorithm == Algorithm.OBJECT_CLASSIFICATION or \\
989
+ self.algorithm == Algorithm.OBJECT_RECOGNITION: # multi learn algorithms
990
+ # avoid naming unlearned id's to avert bugs.
991
+ slots = self.id_slots.get(id)
992
+ if slots == None:
993
+ raise RuntimeError("Can't attach a name to an unlearned ID number")
994
+
995
+ self.id_names[id] = name
996
+
997
+ success = True
998
+ for slot in slots:
999
+ s = self._set_name(slot, name)
1000
+ success = success and s > 0
1001
+ else: # For color recognition (where it works properly!)
1002
+ self.id_names[id] = name
1003
+ success = self._set_name(id, name)
1004
+ return True if success > 0 else False
1005
+
1006
+ def clear_labels(self):
1007
+ # """Deletes all learned label names on Huskylens for the current algorithm."""
1008
+ self.id_names.clear()
1009
+ for i in range(10):
1010
+ self._set_name(i, "")
1011
+
1012
+ def add_text(self, text, position_x, position_y):
1013
+ # """Add a custom text to the Huskylens screen at a certain screen pixel-position (top left starting point).
1014
+ # Text must be less than 20 bytes long and within pixel-borders.
1015
+ # Multiple texts at the same location get overwritten. Returns True on success."""
1016
+ text_bytes = bytes(text, "utf-8")
1017
+ if len(text_bytes) > 19:
1018
+ raise RuntimeError("Custom Text must be less than 20 bytes long.")
1019
+ if position_x > 300 or position_x < 0 or position_y < 35 or position_y > 240:
1020
+ raise RuntimeError("Custom Text can't be placed outside of screen pixel size.")
1021
+ data = [len(text_bytes)]
1022
+ data.append(0xFF if position_x > 255 else 0x00)
1023
+ data.append(position_x % 255)
1024
+ data.append(240 - position_y) # reverse flipped y axis
1025
+ data.extend(list(text_bytes))
1026
+ self.send_request(Request_Command.CUSTOM_TEXT, data)
1027
+ success, _ = self.get_response(Return_Code.OK)
1028
+ return True if success > 0 else False
1029
+
1030
+ def clear_texts(self):
1031
+ # """Deletes all text on the Huskylens screen."""
1032
+ self.send_request(Request_Command.CLEAR_TEXT)
1033
+ success, _ = self.get_response(Return_Code.OK)
1034
+ return True if success > 0 else False
1035
+
1036
+ def learn(self, id, name=None):
1037
+ # """Learn and assign an id to the object currently centered on the huskylens camera.
1038
+ # Optionally attach label to this learned id. Returns True on success."""
1039
+ if id <= 0 or id > 255:
1040
+ raise RuntimeError("Parameter ID for learned item must be in range [0,255]")
1041
+ if self.algorithm == Algorithm.OBJECT_TRACKING or self.algorithm == Algorithm.LINE_TRACKING:
1042
+ id = 1
1043
+ timeout = 500
1044
+ if self.algorithm == Algorithm.OBJECT_CLASSIFICATION:
1045
+ timeout = 1000
1046
+ self.send_request(Request_Command.LEARN, [id, 0x00])
1047
+ success, _ = self.get_response(Return_Code.OK, timeout)
1048
+ if success > 0:
1049
+ # 1. remember slot for id
1050
+ self.learned_slot_count += 1
1051
+ if (not (id in self.id_slots)):
1052
+ self.id_slots[id] = [self.learned_slot_count]
1053
+ else:
1054
+ self.id_slots[id].append(self.learned_slot_count)
1055
+ # 2. attach, name if available.
1056
+ known_by = self.id_names.get(id)
1057
+ if known_by != None:
1058
+ success = self.attach_label(self.learned_slot_count, known_by)
1059
+ elif name != None:
1060
+ success = self.attach_label(id, name)
1061
+ return True if success > 0 else False
1062
+
1063
+ def forget(self):
1064
+ # """Forget all learned objects (ids) of the current algorithm.
1065
+ # Labels are unaffected. Returns True on success."""
1066
+ self.send_request(Request_Command.FORGET)
1067
+ success, _ = self.get_response(Return_Code.OK)
1068
+ if success:
1069
+ self.learned_slot_count = 0
1070
+ self.id_slots.clear()
1071
+ return True if success else False
1072
+
1073
+
1074
+ def save_photo(self):
1075
+ # """Save a photo to the SD-Card. No Feedback, fails on Huskylens screen if no SD-Card is available."""
1076
+ self.send_request(Request_Command.SAVE_PHOTO)
1077
+ success, _ = self.get_response(Return_Code.OK, 1000)
1078
+ return True if success > 0 else False
1079
+
1080
+ def save_screenshot(self):
1081
+ # """Save a screenshot (including texts) to the SD-Card. No Feedback, fails on Huskylens screen if no SD-Card is available."""
1082
+ self.send_request(Request_Command.SAVE_SCREENSHOT)
1083
+ success, _ = self.get_response(Return_Code.OK, 1000)
1084
+ return True if success > 0 else False
1085
+
1086
+ def save_model(self, model_id):
1087
+ # """Save the learned ids and labels to the SD-Card. No Feedback, see Huskylens screen for Result.
1088
+ # There can be at most 5 models per Algorithm, indexed by model_id."""
1089
+ if model_id < 0 or model_id > 4:
1090
+ raise RuntimeError("Invalid model_id. Must be number in range [0,4]")
1091
+ self.send_request(Request_Command.SAVE_MODEL, [model_id, 0x00])
1092
+ success, _ = self.get_response(Return_Code.OK, 1000)
1093
+ print("Model saving: Check Huskylens screen for Result!\\n\\tModel name:", _algorithm_names[self.algorithm] + "_Backup_" + str(model_id) + ".conf")
1094
+ return True if success > 0 else False
1095
+
1096
+ def load_model(self, model_id):
1097
+ # """Load a previously saved model for the active Algorithm from the SD-Card. No Feedback, see Huskylens screen for Result."""
1098
+ if model_id < 0 or model_id > 4:
1099
+ raise RuntimeError("Invalid model_id. Must be number in range [0,4]")
1100
+ self.send_request(Request_Command.LOAD_MODEL, [model_id, 0x00])
1101
+ success, _ = self.get_response(Return_Code.OK, 1000)
1102
+ print("Model Loading: Check Huskylens screen for Result!")
1103
+ return True if success > 0 else False
1104
+
1105
+ def is_pro(self):
1106
+ # """Checks wheter the Huskylens is the PRO version, which supports QR_RECOGNITION and BARCODE_RECOGNITION.
1107
+ # Returns True/False on success, else 0."""
1108
+ self.send_request(Request_Command.IS_PRO)
1109
+ success, data = self.get_response(Return_Code.IS_PRO)
1110
+ return bool(data[0]) if success > 0 else False
1111
+
1112
+ # hidden Utility functions
1113
+
1114
+ def _set_name(self, id, name):
1115
+ # """Set the name of block "id" to the given "name". Name must be less than 20 characters long."""
1116
+ name_bytes = bytes(name, "utf-8")
1117
+ if len(name_bytes) > 19: raise RuntimeError("Custom Name must be less than 20 bytes long.")
1118
+ data = [id, len(name_bytes)+1]
1119
+ data.extend(list(name_bytes))
1120
+ data.append(0x00)
1121
+ self.send_request(Request_Command.CUSTOM_LABEL, data)
1122
+ success, _ = self.get_response(Return_Code.OK)
1123
+ return True if success > 0 else False
1124
+
1125
+ def _get_results(self, request_command, id=-1):
1126
+ # """Get all detected Blocks or Arrows from the Huskylens, specified by the request and id.
1127
+ # Possible Requests: BLOCKS, BLOCKS_LEARNED, BLOCKS_OF_ID, ARROWS, ...
1128
+ # Returns a list of all the detected Block or Arrow instances.
1129
+ # """
1130
+ request_data = None if id < 0 else [id, 0]
1131
+ self.send_request(request_command, request_data)
1132
+
1133
+ # 1. get info header
1134
+ success, info = self.get_response(Return_Code.INFO)
1135
+ if not success:
1136
+ raise RuntimeError("Failed to request results. Got answer:" + str(success))
1137
+
1138
+ # Ignoring number of detected id's and current frame number.
1139
+ n_elements = info[0] + info[1]*255
1140
+ #n_ids = info[2] + info[3]*255
1141
+ # frame = info[4] + info[5]*255
1142
+ #print("result info:", n_elements, n_ids, frame)
1143
+
1144
+ # 2. receive data
1145
+ el = 0
1146
+ objects = []
1147
+
1148
+ while el < n_elements:
1149
+ response_type, el_data = self.get_response(Return_Code.ANY)
1150
+ if response_type == Return_Code.BLOCK and self.algorithm != 3:
1151
+ x = el_data[0] + el_data[1]*255
1152
+ y = 240 - el_data[2] + el_data[3]*255 # flipped y axis
1153
+ width = el_data[4] + el_data[5]*255
1154
+ height = el_data[6] + el_data[7]*255
1155
+ el_id = el_data[8]
1156
+ block = Block(x, y, width, height, el_id)
1157
+ objects.append(block)
1158
+ el += 1
1159
+
1160
+ elif response_type == Return_Code.ARROW:
1161
+ xtail = el_data[0] + el_data[1]*255
1162
+ ytail = 240 - el_data[2] + el_data[3]*255 # flipped y axis
1163
+ xhead = el_data[4] + el_data[5]*255
1164
+ yhead = 240 - el_data[6] + el_data[7]*255 # flipped y axis
1165
+ el_id = el_data[8]
1166
+ arrow = Arrow(xtail,ytail,xhead,yhead,el_id)
1167
+ objects.append(arrow)
1168
+ el += 1
1169
+ elif response_type == 0:
1170
+ return [] # Error (couldn't read all detected elements) fail silently.
1171
+ return objects
1172
+
1173
+ def _get_centermost(self, results):
1174
+ # """Select and Return the most centered (L1-distance) instance of all detected Objects in "results". """
1175
+ centermost = None
1176
+ max_offset = 320+120
1177
+ for obj in results:
1178
+ center_offset = 0
1179
+ if self.algorithm == Algorithm.LINE_TRACKING:
1180
+ center_offset = abs((obj.x_tail + (obj.x_tail - obj.x_head) // 2) - 160) \\
1181
+ + abs((obj.y_tail + (obj.y_tail - obj.y_head) // 2) - 120)
1182
+ else:
1183
+ center_offset = abs(obj.x - 160) + abs(obj.y - 120)
1184
+ if center_offset < max_offset:
1185
+ centermost, max_offset = obj, center_offset
1186
+ return centermost
1187
+ `,
1188
+ mbbitbot: "from microbit import *\nfrom neopixel import *\nfrom utime import ticks_us, sleep_us\n\n\n_v = 200\n_nbLeds = 12\n_np = NeoPixel(pin13, _nbLeds)\n\n_powerDifferential = 0\n_powerOffset = 0\n\n\ndef w(leftforward, leftbackward, rightforward, rightbackward):\n if leftforward > 0 or rightforward > 0:\n pin16.write_analog(leftforward + _powerDifferential)\n pin8.write_analog(leftbackward)\n pin14.write_analog(rightforward - _powerDifferential)\n pin12.write_analog(rightbackward)\n elif leftbackward > 0 or rightbackward > 0:\n pin16.write_analog(leftforward)\n pin8.write_analog(leftbackward + _powerDifferential)\n pin14.write_analog(rightforward)\n pin12.write_analog(rightbackward - _powerDifferential)\n elif leftforward == 0 and rightforward == 0 and leftbackward == 0 and rightbackward == 0:\n pin16.write_analog(0)\n pin8.write_analog(0)\n pin14.write_analog(0)\n pin12.write_analog(0)\n\n\ndef forward():\n w(_v, 0, _v, 0)\n\n\ndef backward():\n w(0, _v, 0, _v)\n\n\ndef stop():\n w(0, 0, 0, 0)\n\n\ndef right():\n w(0, _v, _v, 0)\n\n\ndef left():\n w(_v, 0, 0, _v)\n\n\ndef set_led(pos, red, green, blue):\n _np[pos] = (red, green, blue)\n _np.show()\n\n\ndef fill(red, green, blue):\n for i in range(_nbLeds):\n _np[i] = (red, green, blue)\n _np.show()\n\n\ndef getDistance():\n pin15.write_digital(1)\n sleep_us(10)\n pin15.write_digital(0)\n pin15.set_pull(pin15.NO_PULL)\n while pin15.read_digital() == 0:\n pass\n start = ticks_us()\n while pin15.read_digital() == 1:\n pass\n end = ticks_us()\n echo = end-start\n distance = int(0.01715 * echo)\n return distance\n\n\ndef calibrate(offset, differential=0):\n global _powerDifferential\n global _powerOffset\n global _arcScaling\n\n _powerOffset = max(min(int(offset), 50), -50)\n _powerDifferential = max(min(int(differential), 50), -50)\n _arcScaling = max(min(arcScaling, 50), -50)\n setSpeed(_v / 1023 * 100)\n\n\ndef setSpeed(percent):\n global _v\n speed = percent / 100 * 1023\n speed += _powerOffset/100 * 1023\n speed = min(max(speed, 0), 1023)\n _v = speed\n\n\ndef getLine(bit):\n mask = 1 << bit\n value = 0\n try:\n value = i2c.read(0x1c, 1)[0]\n except OSError:\n pass\n if (value & mask) > 0:\n return 1\n else:\n return 0\n\n\ndef getLight(index):\n if index == 0:\n return pin1.read_analog()\n elif index == 1:\n return pin2.read_analog()\n\n\ndef leftArc(radius):\n speed = _v\n inner_wheel_speed = speed * (radius / (radius + 1))\n w(inner_wheel_speed, 0, speed, 0)\n\n\ndef rightArc(radius):\n speed = _v\n inner_wheel_speed = speed * (radius / (radius + 1))\n w(speed, 0, inner_wheel_speed, 0)\n",
1189
+ mbwait: `from microbit import button_a, button_b, pin0, pin1, pin2, pin_logo, sleep
1190
+
1191
+ # choose the reactivity of the press/touch sensing in ms. Default 100ms is 10 checks per second.
1192
+ POLLING_DELAY = 100
1193
+
1194
+ # Let the microbit wait until a certain button of choice was pressed (and released).
1195
+
1196
+
1197
+ def wait_for_press(button='any'):
1198
+ button_a.was_pressed()
1199
+ button_b.was_pressed()
1200
+ # busy wait until a chosen button was pressed.
1201
+ if button == 'a' or button == 'A':
1202
+ while not button_a.was_pressed():
1203
+ sleep(POLLING_DELAY)
1204
+ elif button == 'b' or button == 'B':
1205
+ while not button_b.was_pressed():
1206
+ sleep(POLLING_DELAY)
1207
+ elif button == 'any' or button == 'ANY':
1208
+ while (not button_a.was_pressed()) and (not button_b.was_pressed()):
1209
+ sleep(POLLING_DELAY)
1210
+ elif button == 'both' or button == 'ab' or button == 'AB':
1211
+ while not (button_a.is_pressed() and button_b.is_pressed()):
1212
+ sleep(POLLING_DELAY)
1213
+ while button_a.is_pressed() or button_b.is_pressed():
1214
+ sleep(POLLING_DELAY)
1215
+ else:
1216
+ raise RuntimeError(
1217
+ "Button to wait for must be either: 'a', 'b', 'any' or 'both'.")
1218
+
1219
+ # Let the microbit wait until a certain touch-sensitive pin of choice is touched.
1220
+
1221
+
1222
+ def wait_for_touch(pin='logo'):
1223
+ # busy wait until a given pin/logo is pressed.
1224
+ p = pin_logo
1225
+ if pin == 'pin0':
1226
+ p = pin0
1227
+ elif pin == 'pin1':
1228
+ p = pin1
1229
+ elif pin == 'pin2':
1230
+ p = pin2
1231
+ elif pin == 'logo' or pin == 'pin_logo' or pin == 'pinLogo':
1232
+ p = pin_logo
1233
+ else:
1234
+ raise RuntimeError(
1235
+ "Argument 'pin' must be one of: 'pin_logo', 'pin0', 'pin1' or 'pin2'.")
1236
+ p.set_touch_mode(p.CAPACITIVE)
1237
+ while not p.is_touched():
1238
+ sleep(POLLING_DELAY)
1239
+ `,
1240
+ mbled: `from neopixel import *
1241
+ import gc
1242
+ from microbit import pin2
1243
+
1244
+
1245
+ _nbLeds = 24
1246
+ _np = NeoPixel(pin2, _nbLeds)
1247
+
1248
+ # Fill all pixels with the same color.
1249
+ # The color is specified by giving values between 0 and 255 for red, green and blue
1250
+
1251
+
1252
+ def fill(red, green, blue):
1253
+ for i in range(_nbLeds):
1254
+ _np[i] = (red, green, blue)
1255
+ _np.show()
1256
+
1257
+ # Set the specified pixel to the specified color.
1258
+ # The pixel is specified by a number between 0 and 23.
1259
+ # The color is specified by giving values between 0 and 255 for red, green and blue
1260
+
1261
+
1262
+ def set_led(pos, red, green, blue):
1263
+ _np[pos] = (red, green, blue)
1264
+ _np.show()
1265
+
1266
+ # clears all LEDS by turning them off
1267
+
1268
+
1269
+ def clear():
1270
+ _np.clear()
1271
+
1272
+ # shift the displayed image by as many led-positions as specified in parameter "amount".
1273
+ # LED strip behaves like a cycle and wraps around when shifting across borders.
1274
+
1275
+
1276
+ def shift_by(amount):
1277
+ shifted_copy = [None]*_nbLeds
1278
+ for n in range(0, _nbLeds):
1279
+ next_i = (n + amount) % _nbLeds
1280
+ shifted_copy[n] = _np[next_i]
1281
+ for n in range(0, _nbLeds):
1282
+ _np[n] = shifted_copy[n]
1283
+ _np.show()
1284
+
1285
+ # get linearly interpolated colors in RGB space.
1286
+ # "percent" is the blending distance between the two colors. 0 is first color only, and 100 is second color only.
1287
+
1288
+
1289
+ def lerp_RGB(r1, g1, b1, r2, g2, b2, percent):
1290
+ if percent < 0.0 or percent > 100.0:
1291
+ raise RuntimeError("Argument 'percent' must be between 0 and 100.")
1292
+ red = max(0, min(255, round(r1 + (r2 - r1) * (percent/100.0))))
1293
+ green = max(0, min(255, round(g1 + (g2 - g1) * (percent/100.0))))
1294
+ blue = max(0, min(255, round(b1 + (b2 - b1) * (percent/100.0))))
1295
+ return red, green, blue
1296
+ `,
1297
+ mbrobot_plus: `# mbrobot_plus.py
1298
+ # Version 1.4 (1.10.2022)
1299
+
1300
+ from microbit import i2c,pin0,pin1,pin2,sleep
1301
+ import machine
1302
+ import gc
1303
+ import music
1304
+
1305
+ _v = 50
1306
+ _axe = 0.082
1307
+
1308
+ def w(d1, d2, s1, s2):
1309
+ try:
1310
+ i2c.write(0x10, bytearray([0x00,d1, d2, s1, s2]))
1311
+ except:
1312
+ print("Please switch on mbRobot!")
1313
+
1314
+ def setSpeed(speed):
1315
+ global _v
1316
+ if speed < 30 and speed != 0:
1317
+ setPID(1)
1318
+ _v = speed + 30
1319
+ elif speed >= 30 and speed < 32:
1320
+ setPID(0)
1321
+ _v = speed + 2
1322
+ else:
1323
+ setPID(0)
1324
+ _v = speed
1325
+
1326
+ def setPID(pd):
1327
+ i2c.write(0x10, bytearray([0x0A, pd]))
1328
+
1329
+ def stop():
1330
+ setPID(0)
1331
+ w(0, 0, 0, 0)
1332
+
1333
+ def resetSpeed():
1334
+ setPID(0)
1335
+ _v = 50
1336
+
1337
+ def forward():
1338
+ w(1, _v, 1, _v)
1339
+
1340
+ def backward():
1341
+ w(2, _v, 2, _v)
1342
+
1343
+ def left():
1344
+ m = 1.825 -0.0175 * _v
1345
+ w(2, int(_v * m), 1, int(_v * m))
1346
+
1347
+ def right():
1348
+ m = 1.825 -0.0175 * _v
1349
+ w(1, int(_v * m), 2, int(_v * m))
1350
+
1351
+ def rightArc(r):
1352
+ v = abs(_v)
1353
+ if r < _axe:
1354
+ v1 = 0
1355
+ else:
1356
+ f = (r - _axe) / (r + _axe) * (1 - v * v / 200000)
1357
+ v1 = int(f * v)
1358
+ if _v > 0:
1359
+ w(1, v, 1, v1)
1360
+ else:
1361
+ w(2, v1, 2, v)
1362
+
1363
+ def leftArc(r):
1364
+ v = abs(_v)
1365
+ if r < _axe:
1366
+ v1 = 0
1367
+ else:
1368
+ f = (r - _axe) / (r + _axe) * (1 - v * v / 200000)
1369
+ v1 = int(f * v)
1370
+ if _v > 0:
1371
+ w(1, v1, 1, v)
1372
+ else:
1373
+ w(2, v, 2, v1)
1374
+
1375
+ def getDistance():
1376
+ pin1.write_digital(1)
1377
+ pin1.write_digital(0)
1378
+ p = machine.time_pulse_us(pin2, 1, 50000)
1379
+ cm = int(p / 58.2 - 0.5)
1380
+ return cm if cm > 0 else 255
1381
+
1382
+ class Motor:
1383
+ def __init__(self, id):
1384
+ self._id = 2 * id
1385
+
1386
+ def _w(self, d, s):
1387
+ try:
1388
+ i2c.write(0x10, bytearray([self._id, d, s]))
1389
+ except:
1390
+ print("Please switch on mbRobot!")
1391
+ while True:
1392
+ pass
1393
+
1394
+ def rotate(self, s):
1395
+ p = abs(s)
1396
+ if s > 0:
1397
+ self._w(1, p)
1398
+ elif s < 0:
1399
+ self._w(2, p)
1400
+ else:
1401
+ self._w(0, 0)
1402
+
1403
+ class LEDState:
1404
+ OFF = 0
1405
+ RED = 1
1406
+ GREEN = 2
1407
+ YELLOW = 3
1408
+ BLUE = 4
1409
+ PINK = 5
1410
+ CYAN = 6
1411
+ WHITE = 7
1412
+
1413
+ def setLED(state, stateR=None):
1414
+ stateR = stateR or state
1415
+ i2c.write(0x10, bytearray([0x0B, state, stateR]))
1416
+
1417
+ def setLEDLeft(state):
1418
+ i2c.write(0x10, bytearray([0x0B, state]))
1419
+
1420
+ def setLEDRight(state):
1421
+ i2c.write(0x10, bytearray([0x0C, state]))
1422
+
1423
+ def setAlarm(on):
1424
+ if on:
1425
+ music.play(_m, wait = False, loop = True)
1426
+ else:
1427
+ music.stop()
1428
+
1429
+ def beep():
1430
+ music.pitch(2000, 200, wait = False)
1431
+
1432
+ def ir_read_values_as_byte():
1433
+ i2c.write(0x10, bytearray([0x1D]))
1434
+ buf = i2c.read(0x10, 1)
1435
+ return ~buf[0]
1436
+
1437
+ def setServo(S, Angle):
1438
+ if S == "S1":
1439
+ Servo = 0x14
1440
+ if S == "S2":
1441
+ Servo = 0x15
1442
+ buf = Servo, Angle
1443
+ i2c.write(0x10, bytes(buf))
1444
+
1445
+ class IR:
1446
+ L3 = 0
1447
+ L2 = 1
1448
+ L1 = 2
1449
+ R1 = 3
1450
+ R2 = 4
1451
+ R3 = 5
1452
+ masks = [0x01,0x02,0x04,0x08,0x10,0x20]
1453
+
1454
+ class IRSensor:
1455
+ def __init__(self, index):
1456
+ self.index = index
1457
+
1458
+ def read_digital(self):
1459
+ byte = ir_read_values_as_byte()
1460
+ return (byte & IR.masks[self.index]) >> self.index
1461
+
1462
+ irLeft = IRSensor(IR.L1)
1463
+ irRight = IRSensor(IR.R1)
1464
+ irL1 = IRSensor(IR.L1)
1465
+ irR1 = IRSensor(IR.R1)
1466
+ irL2 = IRSensor(IR.L2)
1467
+ irR2 = IRSensor(IR.R2)
1468
+ irL3 = IRSensor(IR.L3)
1469
+ irR3 = IRSensor(IR.R3)
1470
+ pin2.set_pull(pin2.NO_PULL)
1471
+ motL = Motor(0)
1472
+ motR = Motor(1)
1473
+ delay = sleep
1474
+ _m = ['c6:1', 'r', 'c6,1', 'r', 'r', 'r']
1475
+
1476
+ `,
1477
+ mbrobot: `# mbrobot.py
1478
+ # Date 10/09/24
1479
+
1480
+ from microbit import i2c, pin1, pin2, pin8, pin12, pin13, pin14, pin15, sleep
1481
+ import gc
1482
+ import machine
1483
+ import music
1484
+ import neopixel
1485
+
1486
+ # Motor state
1487
+ _speedPercent = 50
1488
+ _powerByteL = 40
1489
+ _powerByteR = 40
1490
+ _motorState = bytearray(5)
1491
+ _servoBytes = bytearray(2)
1492
+ _powerBytesLUT = bytes(b'\\x00\\x0b\\x0b\\x0c\\x0c\\x0d\\x0d\\x0d\\x0e\\x0e\\x0f\\x0f\\x0f\\x10\\x10\\x11\\x11\\x11\\x12\\x12\\x13\\x13\\x13\\x14\\x14\\x15\\x15\\x15\\x16\\x16\\x17\\x17\\x17\\x18\\x19\\x1a\\x1b\\x1b\\x1c\\x1d\\x1e\\x1f\\x20\\x21\\x22\\x23\\x23\\x24\\x25\\x26\\x27\\x28\\x29\\x2a\\x2b\\x2b\\x2c\\x2d\\x2e\\x2f\\x30\\x31\\x32\\x33\\x34\\x36\\x38\\x3a\\x3c\\x3f\\x41\\x44\\x46\\x49\\x4c\\x4f\\x53\\x56\\x5a\\x5e\\x62\\x67\\x6b\\x70\\x75\\x7b\\x81\\x87\\x8d\\x94\\x9b\\xa3\\xab\\xb4\\xbd\\xc6\\xd0\\xdb\\xe6\\xf2\\xff')
1493
+
1494
+ # Calibration data
1495
+ _powerOffset = 0
1496
+ _powerDifferential = 0
1497
+ _arcScaling = 0
1498
+
1499
+ # signaling objects
1500
+ _underglowNP = neopixel.NeoPixel(pin15, 4)
1501
+ np_rgb_pixels = _underglowNP
1502
+ _alarmSequence = ['c5:1', 'r', 'c5:1', 'r:3']
1503
+
1504
+ _UNCONNECTEDERRORMSG = "Please connect to Maqueen robot and switch it on."
1505
+
1506
+ # Utility functions
1507
+
1508
+
1509
+ def _setMotors(dirL, powerL, dirR, powerR):
1510
+ # """Write Motor State via i2c
1511
+
1512
+ # Parameters:
1513
+ # dirL (0/1): Direction of left Wheel. 0=forward, 1=backward
1514
+ # powerL (int): Power of left Wheel in range [0,255].
1515
+ # dirR (0/1): Direction of right Wheel. 0=forward, 1=backward
1516
+ # powerR (int): Power of right Wheel in range [0,255].
1517
+ #
1518
+ # raises:
1519
+ # RuntimeError: if Robot is switched off or unconnected. (replaces ENODEV error)
1520
+ # """
1521
+ global _motorState
1522
+ _motorState[1] = dirL
1523
+ _motorState[2] = powerL
1524
+ _motorState[3] = dirR
1525
+ _motorState[4] = powerR
1526
+ try:
1527
+ i2c.write(0x10, _motorState)
1528
+ except:
1529
+ raise RuntimeError(_UNCONNECTEDERRORMSG)
1530
+
1531
+
1532
+ def _setSingleMotor(side, dir, power):
1533
+ # """Write Motor State of a single Motor via i2c
1534
+
1535
+ # Parameters:
1536
+ # side (0/2): Selection of the Wheel. 0=left, 2=right
1537
+ # dir (0/1): Direction for that Wheel. 0=forward, 1=backward
1538
+ # power (int): Power for that Wheel in range [0,255].
1539
+ #
1540
+ # raises:
1541
+ # RuntimeError: if Robot is switched off or unconnected. (replaces ENODEV error)
1542
+ # """
1543
+ global _motorState
1544
+ _motorState[1 + side] = dir
1545
+ _motorState[2 + side] = power
1546
+ try:
1547
+ i2c.write(0x10, _motorState)
1548
+ except:
1549
+ raise RuntimeError(_UNCONNECTEDERRORMSG)
1550
+
1551
+ # _getPowerByte was used to create LookUpTable (_powerBytesLUT) used in _getPowerByteLUT to reduce Memory Leaks.
1552
+ # def _getPowerByte(speed, offset):
1553
+ # # """Computes the power value for a given speed in %.
1554
+ # # It accouts for the nonlinearity of motor strength.
1555
+ # # This is the original function that generates the LUT.
1556
+ #
1557
+ # # Parameter:
1558
+ # # speed (number): Desired speed of the Robot in %. Range [0,100].
1559
+ # # offset (number): basic power offset to add to the function.
1560
+ # # Returns:
1561
+ # # int: Power in range [0,255] to write to the motors via i2c.
1562
+ # # """
1563
+ # if speed <= 0:
1564
+ # return 0
1565
+ # if speed <= 33:
1566
+ # return int(0.4 * speed + 11 + offset)
1567
+ # elif speed <= 63:
1568
+ # return int(0.89 * speed - 5 + offset)
1569
+ # elif speed < 100:
1570
+ # return int(min(1.0561 ** speed + 20 + offset, 255))
1571
+ # else:
1572
+ # return 255
1573
+
1574
+
1575
+ def _getPowerByteLUT(speed, offset):
1576
+ # """Lookup Table version of _getPowerByte"""
1577
+ return min(_powerBytesLUT[speed] + offset, 255)
1578
+
1579
+
1580
+ def _getArcBytes(r):
1581
+ # """Computes the power bytes to drive an arc.
1582
+
1583
+ # Parameter:
1584
+ # r (float): Radius in meters of the desired Arc.
1585
+ # Measured from the center of the axle.
1586
+ # Returns:
1587
+ # (int, int): Power byte values for each motor.
1588
+ # First the outer Wheels byte [0,255],
1589
+ # then the inner Wheels byte [0,255].
1590
+ # """
1591
+ outerSpeed = _speedPercent
1592
+ rCm = int(r * 100) # r in cm instead of meters
1593
+ # adjust outer speed for unhealthy combinations
1594
+ # That is: too low speeds and big arcs.
1595
+ threshold = outerSpeed - max(rCm + 20, 40)
1596
+ if threshold <= 0:
1597
+ outerSpeed = min(max(rCm + 40, 40), 100)
1598
+ reducedSpeed = 0
1599
+ if rCm >= 4: # minimal radius is half the axle size: 3.5 cm rounded.
1600
+ flattening = (100 - outerSpeed) // 2
1601
+ reducedSpeed = (rCm * 10 - 35) / \\
1602
+ (rCm * (11 + (_arcScaling-4)/10) + 90 + flattening)
1603
+ reducedSpeed = reducedSpeed * outerSpeed
1604
+ innerByte = _getPowerByteLUT(int(reducedSpeed), 0)
1605
+ outerByte = _getPowerByteLUT(int(outerSpeed), 0)
1606
+ return (innerByte, outerByte)
1607
+
1608
+ # Movement Functions
1609
+
1610
+
1611
+ def calibrate(offset, differential=0, arcScaling=0):
1612
+ # """Adjust the driving behaviour of the robots
1613
+
1614
+ # Parameters:
1615
+ # offset (int): Offsets the minimal power of the motors.
1616
+ # Range [-10,50]. Highly affected by battery level.
1617
+ # Adjust this value until it starts moving at speed 1%.
1618
+ # differential (int, optional): Adjusts power difference
1619
+ # of left and right Wheel. Range [-150, 150].
1620
+ # Varies unpredictably with different speeds.
1621
+ # If a Robot steers left when driving forward: negative value
1622
+ # If a Robot steers right when driving forward: positive value
1623
+ # Perfectly straight driving Robots can leave this at 0.
1624
+ # arcScaling (int, optional): Adjusts the radius
1625
+ # driven by leftArc/rightArc. Valid range [-50, 50].
1626
+ # If the Robots radius is too large: positive value
1627
+ # If the Robots radius is too small: negative value
1628
+ # This then adjusts all radii for this Robot, by
1629
+ # scaling it's internal function to the new range.
1630
+ # """
1631
+ global _powerDifferential
1632
+ global _powerOffset
1633
+ global _arcScaling
1634
+ _powerOffset = max(min(int(offset), 50), -10)
1635
+ _powerDifferential = max(min(int(differential), 150), -150)
1636
+ _arcScaling = max(min(arcScaling, 50), -15)
1637
+ setSpeed(_speedPercent)
1638
+
1639
+
1640
+ def setSpeed(speed):
1641
+ # """sets the speed for future motion
1642
+
1643
+ # Parameter:
1644
+ # speed (int): in Range [0,100] as % of desired velocity.
1645
+ # """
1646
+ global _speedPercent
1647
+ global _powerByteL
1648
+ global _powerByteR
1649
+ _speedPercent = int(min(max(speed, 0), 100))
1650
+ powerByte = _getPowerByteLUT(_speedPercent, _powerOffset)
1651
+ boost = round((1 - _speedPercent / 100) *
1652
+ abs(_powerDifferential)) if _speedPercent > 0 else 0
1653
+ reduction = round((_speedPercent / 100) * abs(_powerDifferential))
1654
+ if _powerDifferential > 0:
1655
+ _powerByteL = powerByte - reduction
1656
+ _powerByteR = powerByte + boost
1657
+ else:
1658
+ _powerByteL = powerByte + boost
1659
+ _powerByteR = powerByte - reduction
1660
+
1661
+
1662
+ def resetSpeed():
1663
+ setSpeed(50)
1664
+
1665
+
1666
+ def stop():
1667
+ _setMotors(0, 0, 0, 0)
1668
+
1669
+
1670
+ def forward():
1671
+ _setMotors(0, _powerByteL, 0, _powerByteR)
1672
+
1673
+
1674
+ def backward():
1675
+ _setMotors(1, _powerByteL, 1, _powerByteR)
1676
+
1677
+
1678
+ def left():
1679
+ _setMotors(1, _powerByteL, 0, _powerByteR)
1680
+
1681
+
1682
+ def right():
1683
+ _setMotors(0, _powerByteL, 1, _powerByteR)
1684
+
1685
+
1686
+ def rightArc(radius):
1687
+ # """radius must be given in meters."""
1688
+ inner, outer = _getArcBytes(radius)
1689
+ _setMotors(0, outer, 0, inner)
1690
+
1691
+
1692
+ def leftArc(radius):
1693
+ # """radius must be given in meters."""
1694
+ inner, outer = _getArcBytes(radius)
1695
+ _setMotors(0, inner, 0, outer)
1696
+
1697
+
1698
+ class Motor:
1699
+ def __init__(self, side):
1700
+ # """Create a single motor.
1701
+
1702
+ # Parameter:
1703
+ # side (8/2): 0=left, 2=right
1704
+ # """
1705
+ self._side = side
1706
+
1707
+ def rotate(self, speed):
1708
+ # """Controls rotation of this motor.
1709
+
1710
+ # Parameters:
1711
+ # speed (int): Desired speed in %.
1712
+ # Valid range [-100,100].
1713
+ # Negative values are for backward turning.
1714
+ # """
1715
+ speedClamped = int(min(max(abs(speed), 0), 100))
1716
+ power = _getPowerByteLUT(speedClamped, _powerOffset)
1717
+ direction = 0 if speed > 0 else 1
1718
+ _setSingleMotor(self._side, direction, power)
1719
+
1720
+
1721
+ def setServo(servo, angle):
1722
+ # """Moves the Servo to position angle.
1723
+ # Servos must be connected to the Maqueen Lite's Servo connectors.
1724
+ # They are located in front of the left wheel.
1725
+
1726
+ # Parameters:
1727
+ # servo (str): Desired Servo Port. Either 'S1' or 'S2'.
1728
+ # angle (int): Desired angle in degrees. Range [0,180].
1729
+
1730
+ # raises:
1731
+ # ValueError: if arguments are out of valid range
1732
+ # RuntimeError: if Robot is switched off or unconnected.
1733
+ # """
1734
+ global _servoBytes
1735
+ # Acceptance of "P0" and "P1" is for compatibility with V2.
1736
+ if servo == 'S1' or servo == 'P0':
1737
+ _servoBytes[0] = 0x14
1738
+ elif servo == 'S2' or servo == 'P1':
1739
+ _servoBytes[0] = 0x15
1740
+ else:
1741
+ raise ValueError("Unknown Servo. Please use 'S1' or 'S2'.")
1742
+
1743
+ if angle < 0 or angle > 180:
1744
+ raise ValueError("Invalid angle. Must be between 0 and 180")
1745
+
1746
+ _servoBytes[1] = angle
1747
+ try:
1748
+ i2c.write(0x10, _servoBytes)
1749
+ except:
1750
+ raise RuntimeError(_UNCONNECTEDERRORMSG)
1751
+
1752
+ # Sensor functions
1753
+
1754
+
1755
+ class IRSensor():
1756
+ def __init__(self, pin):
1757
+ # """Create a new IR sensor.
1758
+
1759
+ # Parameter:
1760
+ # pin (object): pin13=left, pin14=right
1761
+ # """
1762
+ self._pin = pin
1763
+
1764
+ def read_digital(self):
1765
+ # """Returns if the surface below is dark or bright.
1766
+ # Result can be adjusted by putting the sensor on the dark
1767
+ # surface and pressing the LineKey calibration button on the
1768
+ # Robot for a few seconds, until the LED's blink.
1769
+
1770
+ # Returns:
1771
+ # 0 if the surface is dark. No light was reflected (in Air).
1772
+ # 1 if the surface is bright. A lot of light was reflected.
1773
+ # """
1774
+ return self._pin.read_digital()
1775
+
1776
+ def read_analog(self):
1777
+ raise NameError(
1778
+ "Maqueen Lite does not support reading analog sensor values.")
1779
+
1780
+
1781
+ def getDistance():
1782
+ # """uses the ultrasonic sensor to measure distance
1783
+
1784
+ # Returns:
1785
+ # int: valid Distance as cm in range [0,500].
1786
+ # For measurement errors or larger distances: 255.
1787
+ # """
1788
+ pin1.write_digital(1)
1789
+ pin1.write_digital(0)
1790
+ p = machine.time_pulse_us(pin2, 1, 50000)
1791
+ # approximate division: cm = p / 57.5
1792
+ cm = (p >> 6) + (p >> 10) + (p >> 11) + (p >> 12) + 1
1793
+ return max(min(cm, 500), 0) if cm > 0 else 255
1794
+
1795
+ # Signaling functions
1796
+
1797
+
1798
+ def setLED(state, stateR=None):
1799
+ # """Set the front red LED's.
1800
+
1801
+ # Parameters:
1802
+ # state (0/1): Sets the state of the left LED.
1803
+ # if stateR is omitted, then both LEDS.
1804
+ # 0=Off, 1=On
1805
+ # stateR (0/1/None, optional): Sets the right LED state.
1806
+ # 0=Off, 1=On, Default=None uses "state" for right LED.
1807
+ # """
1808
+ stateR = stateR if stateR != None else state
1809
+ pin8.write_digital(state)
1810
+ pin12.write_digital(stateR)
1811
+
1812
+
1813
+ def setLEDLeft(state):
1814
+ # """state: 0=Off, 1=On"""
1815
+ pin8.write_digital(state)
1816
+
1817
+
1818
+ def setLEDRight(state):
1819
+ # """state: 0=Off, 1=On"""
1820
+ pin12.write_digital(state)
1821
+
1822
+
1823
+ def fillRGB(red, green, blue):
1824
+ # """Uses Neopixel to set all 4 bottom RGB LEDs color.
1825
+ # Parameters (red,green,blue) are each a byte in Range [0,255].
1826
+ # """
1827
+ for i in range(4):
1828
+ _underglowNP[i] = (red, green, blue)
1829
+ _underglowNP.show()
1830
+ setRGB = fillRGB
1831
+
1832
+
1833
+ def clearRGB():
1834
+ _underglowNP.clear()
1835
+
1836
+
1837
+ def posRGB(position, red, green, blue):
1838
+ # """Uses Neopixel to set a single RGB LED of the robot.
1839
+
1840
+ # Parameters:
1841
+ # position (int): position of the targeted LED.
1842
+ # Numbers are visible at underside of Robot.
1843
+ # 0=front left
1844
+ # 1=back left
1845
+ # 2=back right
1846
+ # 3=front right
1847
+ # red, green, blue (int): color byte value.
1848
+ # each in range [0,255].
1849
+
1850
+ # raises:
1851
+ # ValueError: if position argument is out of valid range
1852
+ # """
1853
+ if position < 0 or position > 3:
1854
+ raise ValueError("invalid RGB-LED position. Must be 0,1,2 or 3.")
1855
+ _underglowNP[position] = (red, green, blue)
1856
+ _underglowNP.show()
1857
+
1858
+
1859
+ def setAlarm(state):
1860
+ # """state: 0=Off, 1=On"""
1861
+ if state:
1862
+ music.play(_alarmSequence, wait=False, loop=True)
1863
+ else:
1864
+ music.stop()
1865
+
1866
+
1867
+ def beep():
1868
+ music.pitch(440, 200, wait=False)
1869
+
1870
+
1871
+ # Default instances
1872
+ pin2.set_pull(pin2.NO_PULL)
1873
+ delay = sleep
1874
+ irLeft = IRSensor(pin13)
1875
+ irRight = IRSensor(pin14)
1876
+ motL = Motor(0)
1877
+ motR = Motor(2)
1878
+ `,
1879
+ mbrobot_plusV3: `# mbrobot_plusV3.py
1880
+ # Date 25/11/25
1881
+
1882
+ from microbit import i2c, sleep, running_time, pin0, pin1, pin2
1883
+ import neopixel
1884
+ import music
1885
+
1886
+ _motorState = bytearray(5)
1887
+ _speedPercent = 50
1888
+ _powerByteL = 50
1889
+ _powerByteR = 50
1890
+ _powerBytesLUT = bytes(b'\\x00\\x0f\\x10\\x10\\x11\\x12\\x12\\x13\\x13\\x14\\x15\\x15\\x16\\x16\\x17\\x18\\x18\\x19\\x19\\x1a\\x1b\\x1b\\x1c\\x1c\\x1d\\x1e\\x1e\\x1f\\x1f\\x20\\x21\\x21\\x22\\x22\\x23\\x24\\x24\\x25\\x25\\x26\\x27\\x29\\x2a\\x2b\\x2c\\x2d\\x2e\\x2f\\x30\\x31\\x32\\x33\\x34\\x35\\x36\\x37\\x38\\x39\\x3a\\x3b\\x3b\\x3c\\x3e\\x3f\\x41\\x43\\x45\\x47\\x49\\x4b\\x4d\\x50\\x52\\x55\\x58\\x5b\\x5e\\x61\\x65\\x69\\x6d\\x71\\x75\\x7a\\x7f\\x84\\x89\\x8f\\x95\\x9b\\xa2\\xa9\\xb1\\xb9\\xc1\\xca\\xd3\\xdd\\xe8\\xf3\\xff')
1891
+ _arcScaling = 0
1892
+ _UNCONNECTEDERRORMSG = "Please connect to Maqueen robot and switch it on."
1893
+ _underglowNP = neopixel.NeoPixel(pin1, 4)
1894
+ _alarmSequence = ['c5:1', 'r', 'c5,1', 'r:3']
1895
+ _buff1 = bytearray(1)
1896
+ _buff2 = bytearray(2)
1897
+ _add_mq = 0x10
1898
+ _servoMinPulse=25
1899
+ _servoMaxPulse=131
1900
+ _lidarMode=8
1901
+
1902
+ def _wr1(reg):
1903
+ _buff1[0] = reg
1904
+ i2c.write(_add_mq, _buff1)
1905
+
1906
+ def _wr2(reg, val):
1907
+ _buff2[0] = reg
1908
+ _buff2[1] = val
1909
+ i2c.write(_add_mq, _buff2)
1910
+
1911
+ def _setMotors(dirL, powerL, dirR, powerR):
1912
+ global _motorState
1913
+ _motorState[1] = dirL
1914
+ _motorState[2] = powerL
1915
+ _motorState[3] = dirR
1916
+ _motorState[4] = powerR
1917
+ try:
1918
+ i2c.write(0x10, _motorState)
1919
+ except:
1920
+ raise RuntimeError(_UNCONNECTEDERRORMSG)
1921
+
1922
+ def _setSingleMotor(side, dir, power):
1923
+ global _motorState
1924
+ _motorState[1 + side] = dir
1925
+ _motorState[2 + side] = power
1926
+ try:
1927
+ i2c.write(0x10, _motorState)
1928
+ except:
1929
+ raise RuntimeError(_UNCONNECTEDERRORMSG)
1930
+
1931
+ def setSpeed(speed):
1932
+ global _speedPercent
1933
+ global _powerByteL
1934
+ global _powerByteR
1935
+ _speedPercent = int(min(max(speed,0),100))
1936
+ _powerByteL = int(round(2.4*speed+14))
1937
+ _powerByteR = int(round(2.4*speed+14))
1938
+
1939
+ def resetSpeed():
1940
+ setSpeed(50)
1941
+
1942
+ def stop():
1943
+ _setMotors(0,0,0,0)
1944
+
1945
+ def forward():
1946
+ _setMotors(0, _powerByteL, 0, _powerByteR)
1947
+
1948
+ def backward():
1949
+ _setMotors(1, _powerByteL, 1, _powerByteR)
1950
+
1951
+ def left():
1952
+ _setMotors(1, _powerByteL, 0, _powerByteR)
1953
+
1954
+ def right():
1955
+ _setMotors(0, _powerByteL, 1, _powerByteR)
1956
+
1957
+ def _getPowerByteLUT(speed, offset):
1958
+ return min(_powerBytesLUT[speed] + offset, 255)
1959
+
1960
+ def _getArcBytes(r):
1961
+ rmm = int(r * 100)
1962
+ outerSpeed = _speedPercent
1963
+ if outerSpeed < 25:
1964
+ outerSpeed = 25
1965
+ reducedSpeed = 0
1966
+ if rmm > 5:
1967
+ n = outerSpeed * (3 * _arcScaling - outerSpeed - 9 * rmm + 220)
1968
+ d = -14 * _arcScaling + outerSpeed - 200 + 3 * outerSpeed - 10 * rmm - 290
1969
+ reducedSpeed = int(n/d)
1970
+ if reducedSpeed < 2:
1971
+ reducedSpeed = 2 if rmm > 15 else 1
1972
+ innerByte = _getPowerByteLUT(int(reducedSpeed), 0)
1973
+ outerByte = _getPowerByteLUT(int(outerSpeed), 0)
1974
+ return (innerByte, outerByte)
1975
+
1976
+ def rightArc(radius):
1977
+ inner, outer = _getArcBytes(radius)
1978
+ _setMotors(0, outer, 0, inner)
1979
+
1980
+
1981
+ def leftArc(radius):
1982
+ inner, outer = _getArcBytes(radius)
1983
+ _setMotors(0, inner, 0, outer)
1984
+
1985
+ class Motor:
1986
+ def __init__(self, side):
1987
+ self._side = side
1988
+
1989
+ def rotate(self, speed):
1990
+ speedClamped = int(min(max(abs(speed), 0), 100))
1991
+ power = speedClamped
1992
+ direction = 0 if speed > 0 else 1
1993
+ _setSingleMotor(self._side, direction, power)
1994
+
1995
+ def setServo(servo,angle):
1996
+ if angle < 0 or angle >180:
1997
+ raise ValueError("Invalid angle. Must be between 0 and 180")
1998
+ if servo in ["P0", "S1"]:
1999
+ pin = pin0
2000
+ elif servo in ["P1", "S2"]:
2001
+ pin = pin1
2002
+ elif servo in ["P2", "S3"]:
2003
+ pin = pin2
2004
+ else:
2005
+ raise ValueError("Valid servo names: S1, S2, S3 or P0, P1, P2")
2006
+ frac = (_servoMaxPulse - _servoMinPulse) * int(angle)
2007
+ offset = (frac >> 8)+ (frac >> 10) + (frac >> 11)+ (frac >> 12) # / 180
2008
+ usPulseTime = _servoMinPulse + offset
2009
+ pin.set_analog_period(20)
2010
+ pin.write_analog(usPulseTime)
2011
+
2012
+ class IRSensor:
2013
+ _address = bytes(b'\\x1D')
2014
+
2015
+ def __init__(self, index):
2016
+ self.index = index
2017
+
2018
+ def read_digital(self):
2019
+ try:
2020
+ i2c.write(0x10, IRSensor._address)
2021
+ except:
2022
+ raise RuntimeError(_UNCONNECTEDERRORMSG)
2023
+ byte = ~i2c.read(0x10, 1)[0]
2024
+ return (byte & (2 ** self.index)) >> self.index
2025
+
2026
+ def read_analog(self):
2027
+ try:
2028
+ _wr1(0x1D)
2029
+ except:
2030
+ raise RuntimeError(_UNCONNECTEDERRORMSG)
2031
+ buffer = i2c.read(0x10,11)
2032
+ return buffer[2+2*self.index] << 8 | buffer[1+2*self.index]
2033
+
2034
+ def setLEDs(rgbl, rgbr):
2035
+ _wr2(11, rgbl)
2036
+ _wr2(12, rgbr)
2037
+
2038
+ def setLED(state, stateR=None):
2039
+ stateR = stateR if stateR != None else state
2040
+ setLEDs(state, stateR)
2041
+
2042
+ def setLEDLeft(rgbl):
2043
+ _wr2(11, rgbl)
2044
+
2045
+ def setLEDRight(rgbr):
2046
+ _wr2(12, rgbr)
2047
+
2048
+ def fillRGB(red, green, blue):
2049
+ _underglowNP.clear()
2050
+ _underglowNP.fill((red,green,blue))
2051
+ _underglowNP.show()
2052
+
2053
+ def setRGB(r,g,b):
2054
+ fillRGB(r,g,b)
2055
+
2056
+ def clearRGB():
2057
+ _underglowNP.clear()
2058
+
2059
+ def posRGB(position, red, green, blue):
2060
+ if position < 0 or position > 3:
2061
+ raise ValueError("invalid RGB-LED position. Must be 0,1,2 or 3.")
2062
+ _underglowNP[position] = (red, green, blue)
2063
+ _underglowNP.show()
2064
+
2065
+ def setAlarm(state):
2066
+ if state:
2067
+ music.play(_alarmSequence, wait=False, loop=True)
2068
+ else:
2069
+ music.stop()
2070
+
2071
+ def beep():
2072
+ music.pitch(440, 200, wait=False)
2073
+
2074
+ def readLightIntensity(side):
2075
+ _wr1(78)
2076
+ LightBuffer = i2c.read(0x10, 4, repeat=False)
2077
+ if side == 1:
2078
+
2079
+ return LightBuffer[0] << 8 | LightBuffer[1]
2080
+ else:
2081
+ return LightBuffer[2] << 8 | LightBuffer[3]
2082
+
2083
+ def setPatrolSpeed(speed):
2084
+ _wr2(63, speed)
2085
+
2086
+ def setIntersectionRunMode(mode):
2087
+ _wr2(69, mode)
2088
+
2089
+ def setTRordRunMode(mode):
2090
+ _wr2(70, mode)
2091
+
2092
+ def setLeftOrStraightRunMode(mode):
2093
+ _wr2(71, mode)
2094
+
2095
+ def setRightOrStraightRunMode(mode):
2096
+ _wr2(72, mode)
2097
+
2098
+ def patrolling(patrol):
2099
+ if patrol == 1:
2100
+ val = 0x04 | 0x01
2101
+ else:
2102
+ val = 0x08
2103
+ _wr2(60, val)
2104
+
2105
+ def intersectionDetecting():
2106
+ _wr1(61)
2107
+ data = i2c.read(0x10, 1)[0]
2108
+ return data
2109
+
2110
+ def pidControlDistance(dir, distance, interruption):
2111
+ speed = 2
2112
+ if distance >= 6000:
2113
+ distance = 60000
2114
+ _wr2(64, dir)
2115
+ _wr2(85, speed)
2116
+ _wr2(65, distance >> 8)
2117
+ _wr2(66, distance)
2118
+ _wr2(60, 0x04 | 0x02)
2119
+ if (interruption == 1):
2120
+ _wr1(0x57)
2121
+ flagBuffer = i2c.read(0x10, 1)
2122
+ while flagBuffer[0] == 1:
2123
+ sleep(10)
2124
+ flagBuffer = i2c.read(0x10, 1)
2125
+
2126
+ def pidControlAngle(angle, interruption):
2127
+ speed = 2
2128
+ if angle >= 0:
2129
+ buf = 1
2130
+ else:
2131
+ buf = 2
2132
+ angle = -angle
2133
+ _wr2(67, buf)
2134
+ _wr2(86, speed)
2135
+ _wr2(68, angle)
2136
+ _wr2(60, 0x04 | 0x02)
2137
+ if interruption == 1:
2138
+ _wr1(0x57)
2139
+ buff = i2c.read(0x10, 1)
2140
+ while buff[0] == 1:
2141
+ sleep(10)
2142
+ buff = i2c.read(0x10, 1)
2143
+
2144
+ def pidControlStop():
2145
+ _wr2(60, 0x10)
2146
+
2147
+ def readRealTimeSpeed(type):
2148
+ _wr2(76, 1)
2149
+ buff = i2c.read(0x10, 2)
2150
+ if type == 1:
2151
+ return buff[0] / 5
2152
+ else:
2153
+ return buff[1] / 5
2154
+
2155
+ def _sendLidarCommand(cmd, args=[]):
2156
+ args_len = len(args)
2157
+ packet_len = args_len + 1
2158
+ packet = bytearray(4 + args_len)
2159
+ packet[0] = 0x55
2160
+ packet[1] = (packet_len >> 8) & 0xFF
2161
+ packet[2] = packet_len & 0xFF
2162
+ packet[3] = cmd
2163
+ for i, arg in enumerate(args):
2164
+ packet[4 + i] = arg
2165
+ # chunkwise sending? TODO
2166
+ i2c.write(0x33, packet)
2167
+
2168
+ def _receiveLidarData(expectedCommand):
2169
+ TIMEOUT = 1000
2170
+ MAX_SIZE = 32
2171
+ start_time = running_time()
2172
+ success = False
2173
+ data = None
2174
+ started = False
2175
+
2176
+ while running_time() - start_time < TIMEOUT and started == False:
2177
+ status = i2c.read(0x33, 1)[0]
2178
+ if status == 0x53:
2179
+ started = True
2180
+ elif status == 0x63:
2181
+ return success, data
2182
+ sleep(16)
2183
+
2184
+ if started == True:
2185
+ header = i2c.read(0x33, 3)
2186
+ cmd = header[0]
2187
+ data_length = header[1] | (header[2] << 8)
2188
+
2189
+ if cmd == expectedCommand:
2190
+ success = True
2191
+ data = bytearray()
2192
+ remaining_bytes = data_length
2193
+ chunk_size = min(remaining_bytes, MAX_SIZE)
2194
+ while running_time() - start_time < TIMEOUT and remaining_bytes > 0:
2195
+ try:
2196
+ chunk = i2c.read(0x33, chunk_size)
2197
+ data.extend(chunk)
2198
+ remaining_bytes -= len(chunk)
2199
+ except:
2200
+ sleep(1)
2201
+ return success, data
2202
+
2203
+ def setLidarMode(mode=8):
2204
+ global _lidarMode
2205
+ if mode not in [4, 8]:
2206
+ raise ValueError("Lidar mode must be 4 or 8")
2207
+ mode_text = "4x4" if mode == 4 else "8x8"
2208
+ print("Switching Lidar Mode to " + mode_text + ".\\nPlease wait up to 10 seconds.")
2209
+ success = False
2210
+
2211
+ for i in range(10):
2212
+ _sendLidarCommand(1, [0, 0, 0, mode])
2213
+ success, _ = _receiveLidarData(1)
2214
+
2215
+ if success == True: break
2216
+ sleep(17)
2217
+
2218
+ if success:
2219
+ _lidarMode = mode
2220
+ sleep(5000)
2221
+ else:
2222
+ raise RuntimeError("Failed to switch Lidar Mode")
2223
+
2224
+ def getDistanceAt(x_pos, y_pos):
2225
+ _sendLidarCommand(0x3, [x_pos, y_pos])
2226
+ success, data = _receiveLidarData(0x3)
2227
+ if success and len(data) >= 2:
2228
+ distance = (data[0] | (data[1] << 8)) // 10
2229
+ return distance
2230
+ else:
2231
+ return 1023
2232
+
2233
+ def getDistanceList():
2234
+ _sendLidarCommand(0x2)
2235
+ success, data = _receiveLidarData(0x2)
2236
+ if success and len(data) >= 32:
2237
+ distList = []
2238
+ for i in range(0,len(data),2):
2239
+ d = data[i] | (data[i+1] << 8)
2240
+ distList.append(d // 10)
2241
+ return distList
2242
+ else:
2243
+ return []
2244
+
2245
+ def getDistance():
2246
+ global _lidarMode
2247
+ mid = int(_lidarMode/2)
2248
+ topLeft = getDistanceAt(mid-1, mid-1)
2249
+ topRight = getDistanceAt(mid, mid-1)
2250
+ bottomLeft = getDistanceAt(mid-1, mid)
2251
+ bottomRight = getDistanceAt(mid, mid)
2252
+ distanceList = [topLeft, topRight, bottomLeft, bottomRight]
2253
+ return min(distanceList)
2254
+
2255
+
2256
+ def getDistanceGrid():
2257
+ _sendLidarCommand(0x2)
2258
+ success, data = _receiveLidarData(0x2)
2259
+ if success and len(data) >= 32:
2260
+ distGrid = []
2261
+ stride = 16 if len(data) == 128 else 8
2262
+ for i in range(0,len(data),stride):
2263
+ row = []
2264
+ for j in range(0,stride,2):
2265
+ d = data[i+j] | (data[i+j+1] << 8)
2266
+ row.append(d // 10)
2267
+ distGrid.append(row)
2268
+ return distGrid
2269
+ else:
2270
+ return []
2271
+
2272
+ def getDistanceColumn(index):
2273
+ _sendLidarCommand(0x5, [index])
2274
+ success, data = _receiveLidarData(0x5)
2275
+ if success and len(data) >= 8:
2276
+ row = []
2277
+ for i in range(0, len(data), 2):
2278
+ distance = data[i] | (data[i+1] << 8)
2279
+ row.append(distance // 10)
2280
+ return row
2281
+ return []
2282
+
2283
+ def getDistanceRow(index):
2284
+ _sendLidarCommand(0x6, [index])
2285
+ success, data = _receiveLidarData(0x6)
2286
+ if success and len(data) >= 8:
2287
+ col = []
2288
+ for i in range(0, len(data), 2):
2289
+ distance = data[i] | (data[i+1] << 8)
2290
+ col.append(distance // 10)
2291
+ return col
2292
+ return []
2293
+
2294
+
2295
+ pin2.set_pull(pin2.NO_PULL)
2296
+ delay = sleep
2297
+ irR2 = IRSensor(0)
2298
+ irR1 = IRSensor(1)
2299
+ irRight = irR1
2300
+ irM = IRSensor(2)
2301
+ irL1 = IRSensor(3)
2302
+ irLeft = irL1
2303
+ irL2 = IRSensor(4)
2304
+ motL = Motor(0)
2305
+ motR = Motor(2)`,
2306
+ mbmarsrover: "from microbit import *\nfrom neopixel import *\nimport utime\n\n_servoArray = [0, 9, 11, 13, 15]\n_servoOffset = [0, 0, 0, 0, 0]\n_initI2C = False\n\n_nbLeds = 4\n_np = NeoPixel(pin2, _nbLeds)\n\n_speedPercent = 50\n_powerByteL = 40\n_powerByteR = 40\n\n_powerOffset = 0\n_powerDifferential = 0\n_arcScaling = 0\n\n_MAX_CM_DISTANCE = 500\n_CM_PER_MICROSECOND = 29.1\n\n\ndef _setMotors(dirL, powerL, dirR, powerR):\n pinsL = (pin1, pin12)\n pinsR = (pin8, pin0)\n\n pinsL[dirL].write_analog(powerL)\n pinsL[1 - dirL].write_analog(0)\n\n pinsR[dirR].write_analog(powerR)\n pinsR[1 - dirR].write_analog(0)\n\n\ndef _setSingleMotor(side, direction, power):\n if side == 0:\n pins = (pin1, pin12)\n elif side == 1:\n pins = (pin8, pin0)\n\n pins[direction].write_analog(power)\n pins[1 - direction].write_analog(0)\n\n\ndef _getArcBytes(r):\n outerSpeed = _speedPercent\n rCm = int(r * 100)\n threshold = outerSpeed - max(rCm + 20, 40)\n if (threshold <= 0):\n outerSpeed = min(max(rCm + 40, 40), 100)\n reducedSpeed = 0\n if rCm >= 4:\n flattening = (100 - outerSpeed) // 2\n reducedSpeed = (rCm * 10 - 35) / \\\n (rCm * (11 + (_arcScaling - 4) / 10) + 90 + flattening)\n reducedSpeed = reducedSpeed * outerSpeed\n innerByte = _convertSpeedToAnalogValue(int(reducedSpeed), 0)\n outerByte = _convertSpeedToAnalogValue(int(outerSpeed), 0)\n return (innerByte, outerByte)\n\n\ndef _initPCA():\n global _initI2C\n _initI2C = True\n i2cData = bytearray(2)\n i2cData[0] = 0\n i2cData[1] = 0x10\n i2c.write(0x40, i2cData)\n\n i2cData[0] = 0xFE\n i2cData[1] = 101\n i2c.write(0x40, i2cData)\n\n i2cData[0] = 0\n i2cData[1] = 0x81\n i2c.write(0x40, i2cData)\n\n\ndef _pulse_in(pin, value, timeout):\n start_time = utime.ticks_us()\n\n while pin.read_digital() != value:\n if utime.ticks_diff(utime.ticks_us(), start_time) > timeout:\n return 0\n\n start_time = utime.ticks_us()\n while pin.read_digital() == value:\n if utime.ticks_diff(utime.ticks_us(), start_time) > timeout:\n return 0\n\n return utime.ticks_diff(utime.ticks_us(), start_time)\n\n\ndef calibrate(offset, differential=0, arcScaling=0):\n global _powerDifferential\n global _powerOffset\n global _arcScaling\n\n _powerOffset = max(min(int(offset), 500), -50)\n _powerDifferential = max(min(int(differential), 150), -150)\n _arcScaling = max(min(arcScaling, 50), -15)\n setSpeed(_speedPercent)\n\n\ndef setSpeed(speed):\n global _speedPercent\n global _powerByteL\n global _powerByteR\n\n _speedPercent = int(min(max(speed, 0), 100))\n powerValue = _convertSpeedToAnalogValue(_speedPercent, _powerOffset)\n boost = round((1 - _speedPercent / 100) *\n abs(_powerDifferential)) if _speedPercent > 0 else 0\n reduction = round((_speedPercent / 100) * abs(_powerDifferential))\n if _powerDifferential > 0:\n _powerByteL = powerValue - reduction\n _powerByteR = powerValue + boost\n else:\n _powerByteL = powerValue + boost\n _powerByteR = powerValue - reduction\n\n\ndef _convertSpeedToAnalogValue(speed, offset):\n analogValue = int(speed * 1023 / 100) + offset\n return min(max(analogValue, 0), 1023)\n\n\ndef stop():\n _setMotors(0, 0, 0, 0)\n\n\ndef forward():\n _setMotors(0, _powerByteL, 0, _powerByteR)\n\n\ndef backward():\n _setMotors(1, _powerByteL, 1, _powerByteR)\n\n\ndef setServo(servoNum, angle):\n global _servoArray, _initI2C\n if _initI2C == False:\n _initPCA()\n offsetNum = servoNum\n servoNum = _servoArray[servoNum]\n i2cData = bytearray(2)\n start = 0\n angle = max(min(angle, 90), -90)\n stop = 396 + (angle + _servoOffset[offsetNum]) * 223 / 90\n i2cData[0] = 0x06 + servoNum * 4 + 2\n i2cData[1] = int(stop) + 0xff\n i2c.write(0x40, i2cData)\n\n i2cData[0] = 0x06 + servoNum*4 + 3\n i2cData[1] = int(stop) >> 8\n i2c.write(0x40, i2cData)\n\n\ndef clearServos():\n setServo(0, 0)\n setServo(1, 0)\n setServo(2, 0)\n setServo(3, 0)\n setServo(4, 0)\n sleep(500)\n\n\ndef steer(angle):\n angle = max(min(angle, 45), -45)\n setServo(1, angle)\n setServo(2, -angle)\n setServo(3, -angle)\n setServo(4, angle)\n sleep(500)\n\n\ndef setLED(pos, red, green, blue):\n _np[pos] = (red, green, blue)\n _np.show()\n\n\ndef fill(red, green, blue):\n for i in range(_nbLeds):\n _np[i] = (red, green, blue)\n _np.show()\n\n\ndef getDistance():\n trig = pin13\n echo = pin13\n\n d = 10\n\n trig.set_pull(trig.NO_PULL)\n\n for _ in range(10):\n trig.write_digital(0)\n utime.sleep_us(2)\n trig.write_digital(1)\n utime.sleep_us(10)\n trig.write_digital(0)\n\n duration = _pulse_in(echo, 1, _MAX_CM_DISTANCE * _CM_PER_MICROSECOND)\n if duration > 0:\n d = duration\n break\n\n return round(d / _CM_PER_MICROSECOND)\n\n\ndef calibrateServo(pos, angleDifferential):\n global _servoOffset\n\n angleDifferential = max(min(angleDifferential, 90), -90)\n _servoOffset[pos] = angleDifferential\n clearServos()\n",
2307
+ mbrobotmot: '# mbrobotmot.py\n# Version 1.2, Aug 9, 2019\n\nimport gc\nfrom microbit import i2c, pin1, pin2, pin8, pin12, pin13, pin14, sleep\nimport machine\n\nclass Motor:\n def __init__(self, id):\n self._id = 2 * id\n\n def rotate(self, s):\n v = abs(s)\n if s > 0:\n self._w(0, v) \n elif s < 0:\n self._w(1, v) \n else: \n self._w(0, 0) \n \n\n def _w(self, d, s):\n try:\n i2c.write(0x10, bytearray([self._id, d, s]))\n except:\n print("Please switch on mbRobot!")\n while True:\n pass\n\ndelay = sleep\n\ndef getDistance():\n pin1.write_digital(1)\n pin1.write_digital(0)\n p = machine.time_pulse_us(pin2, 1, 50000)\n cm = int(p / 58.2 + 0.5)\n return cm if cm > 0 else 255\n\ndef setLED(on):\n pin8.write_digital(on)\n pin12.write_digital(on)\n\npin2.set_pull(pin2.NO_PULL)\nirLeft = pin13\nirRight = pin14\nledLeft = pin8\nledRight = pin12\nmotL = Motor(0)\nmotR = Motor(1)',
2308
+ controller: '# Controller v1.0, Date 21.06.24\n# Enables easy use of the DFRobot Micro:bit GamePad by simulating buttons the same way as the microbit internal ones.\nfrom microbit import run_every, pin13, pin14, pin15, pin16, pin8, pin1, pin2, pin12, button_a, button_b, sleep\n\nclass _Controller_Button:\n #""" Simulated Button for regular pins with same functionality as the micro:bit buttons a and b."""\n \n def __init__(self, pin):\n # """create a new simulated button from a digital pin\n\n # Parameter:\n # pin (MicroBitDigitalPin): pin to use as button\n # """\n self._pin = pin\n self.previous_state = 0\n self._press_count = 0\n self._pressed_before = False\n pin.set_pull(pin.PULL_UP)\n \n def _update_state(self):\n # """ internally update the buttons state."""\n current_state = 1 - self._pin.read_digital()\n \n if current_state == 1 and self.previous_state == 0: # Low -> High\n self._press_count += 1\n self._pressed_before = True\n \n self.previous_state = current_state\n\n def is_pressed(self):\n # """ check if the button is currently pressed.\n\n # Returns:\n # bool: if button is currently pressed.\n # """\n return False if self._pin.read_digital() else True\n \n def was_pressed(self):\n # """ check if button was pressed down before. Resets upon call. \n\n # Returns:\n # bool: True if button was pressed down after last call of this function.\n # """\n state = self._pressed_before\n self._pressed_before = False\n return state\n \n def get_presses(self):\n # """ get the amount of button presses since last call.\n \n # Returns:\n # int: number of button (down) presses since last call of this function.\n # """\n count = self._press_count\n self._press_count = 0\n return count\n\nclass _Controller_Analog_Stick:\n # """ class that encapsulates the right analog stick of the controller. \n # This includes the turning in an xy-plane and the pressing (z-button)."""\n\n def __init__(self, pinX, pinY, pinZ):\n # """ creates a new analog-stick given its input pins.\n \n # Parameters:\n # pinX (MicroBitAnalogDigitalPin): The pin to use for the x-axis (left-right).\n # pinY (MicroBitAnalogDigitalPin): The pin to use for the y-axis (up-down).\n # pinZ (MicroBitDigitalPin): The pin to use for the z-button.\n # """\n self.pin_x = pinX\n self.pin_y = pinY\n self.button_z = _Controller_Button(pinZ)\n self.dead_zone = 0.01\n self.center_x = 0\n self.center_y = 0\n self.min_x = -1\n self.max_x = 1\n self.min_y = -1\n self.max_y = 1\n \n def calibrate(self, dead_zone, \n center_x=0.0, center_y=0.0, \n x_min=-1.0, x_max=1.0, \n y_min=-1.0, y_max=1.0):\n # """ calibrate the analog-stick to remove drift (nonzero values even in resting position) \n # and rescale to full [-1,1] range for the xy-inputs.\n \n # After calibration, the analog-stick \n # - does not react (returns 0) until it exceeds a value above the "dead_zone" range.\n # - returns values in the range [-1, 1] when pushed to the extremes and 0 at rest.\n \n # Parameters:\n # dead_zone (int): range of xy-values (negative too) that should be mapped to 0. \n # Default: 0.01 \n # center_x (int): returned value for get_x, when the stick is not moved (before calibration). \n # Default: 0.0\n # center_y (int): returned value for get_y, when the stick is not moved (before calibration). \n # Default: 0.0\n # x_min (int): minimal possible value for x (before calibration). Default: -1.0\n # x_max (int): maximal possible value for x (before calibration). Default: 1.0\n # y_min (int): minimal possible value for y (before calibration). Default: -1.0\n # y_max (int): maximal possible value for y (before calibration). Default: 1.0\n # """\n self.dead_zone = min(0.2, max(0.01,dead_zone))\n self.center_x = min(0.4, max(-0.4,center_x))\n self.center_y = min(0.5, max(-0.5,center_y))\n self.min_x = min(-0.5, max(-1.0,x_min))\n self.max_x = min(1.0, max(0.5,x_max))\n self.min_y = min(-0.5, max(-1.0,y_min))\n self.max_y = min(1.0, max(0.5,y_max))\n\n def _remap(self, value, center, v_min, v_max):\n # """ internal function that applies remapping of the values according to the calibration.\n # The returned value will live in a possible space from [-1,1] with center at 0.\n \n # Parameters:\n # value (float): the input value to remap to the desired range.\n # center (float): the resting value before calibration.\n # v_min (float): the minimally attainable value before calibration.\n # v_max (float): the maximally attainable value before calibration.\n\n # Returns:\n # v (float): remapped parameter value according to calibration.\n # """\n v = value - 1.0 - center\n if abs(v) - self.dead_zone/2.0 > 0.0:\n if v < 0.0:\n v = v / abs(v_min - center)\n else:\n v = v / abs(v_max - center)\n v = min(1.0, max(-1.0, v))\n v = 0.0 if abs(v) <= self.dead_zone else v\n return v\n\n def get_x(self):\n # """ get the current x-axis value of the analog stick.\n \n # Returns:\n # (float): position of x-axis in range [-1,1] (left to right). 0 is resting position. (after calibration)\n # """\n v_raw = (self.pin_x.read_analog() / 512.0)\n v = self._remap(v_raw, self.center_x, self.min_x, self.max_x)\n return v\n\n def get_y(self):\n # """ get the current y-axis value of the analog stick.\n \n # Returns:\n # (float): position of y-axis in range [-1,1] (down to up). 0 is resting position. (after calibration)\n # """\n v_raw = (self.pin_y.read_analog() / 512.0)\n v = self._remap(v_raw, self.center_y, self.min_y, self.max_y)\n return v\n\n def get_z(self):\n # """ get the current z-button state as an int. 1 = pressed, 0 = not pressed. """\n return 1 if self.button_z.is_pressed() else 0\n\n def is_pressed(self):\n # """ returns if the z-button is currently pressed as a bool."""\n return self.button_z.is_pressed()\n \n def was_pressed(self):\n # """ returns if the z-button was pressed (down) before the last call to this function."""\n return self.button_z.was_pressed()\n \n def get_presses(self):\n # """ returns how often the z-button was pressed (down) before the last call to this function."""\n return self.button_z.get_presses()\n\n# Controller LED and vibration motor\ndef vibrate(state):\n # """ Set the state of the controllers vibration motor. 0=Off, 1=On.\n # Also affects the controllers blue LED next to the motor. """\n pin12.write_digital(state)\n\n# Left side of controller (black joystick)\njoystick = _Controller_Analog_Stick(pin1, pin2, pin8)\n# also make the joystick button accessible independently.\nbutton_z = joystick.button_z\n\n# Right side of controller (4 colored buttons)\nbutton_c = _Controller_Button(pin13)\nbutton_green = button_c\nbutton_d = _Controller_Button(pin14)\nbutton_yellow = button_d\nbutton_e = _Controller_Button(pin15)\nbutton_red = button_e\nbutton_f = _Controller_Button(pin16)\nbutton_blue = button_f\n\n# Back side of controller (2 white buttons, same as default buttons)\ntrigger_left = button_a\ntrigger_right = button_b\n\n\ndef _update_controller_buttons():\n # """ function to be called repeatedly that updates the state of all the controllers buttons. \n # It is necessary to run this function regularly to simulate the standard microbit button behaviour. """\n global button_c\n global button_d\n global button_e\n global button_f\n global joystick\n\n button_c._update_state()\n button_d._update_state()\n button_e._update_state()\n button_f._update_state()\n joystick.button_z._update_state()\n\nrun_every(_update_controller_buttons, days=0, h=0, min=0, s=0, ms=33) # ~30 Updates per Second\n',
2309
+ mbxgo: "from microbit import *\n\n_speed = 50\n_XGOInit = False\n_TX = pin14\n_RX = pin13\n\n\ndef checkInit(func):\n def wrapper(*args, **kwargs):\n global _XGOInit\n if not _XGOInit:\n init_xgo_serial(_TX, _RX)\n return func(*args, **kwargs)\n return wrapper\n\n\ndef _map(speed, in_min, in_max, out_min, out_max):\n return (speed - in_min) * (out_max - out_min) // (in_max - in_min) + out_min\n\n\n@checkInit\ndef _move(direction, speed):\n move_buffer = bytearray(9)\n move_buffer[0] = 0x55\n move_buffer[1] = 0x00\n move_buffer[2] = 0x09\n move_buffer[3] = 0x00\n move_buffer[7] = 0x00\n move_buffer[8] = 0xAA\n\n speed = max(0, min(100, speed))\n\n if direction == 0:\n move_buffer[4] = 0x30\n move_buffer[5] = _map(speed, 0, 100, 128, 255)\n elif direction == 1:\n move_buffer[4] = 0x30\n move_buffer[5] = _map(speed, 0, 100, 128, 0)\n elif direction == 2:\n move_buffer[4] = 0x31\n move_buffer[5] = _map(speed, 0, 100, 128, 0)\n elif direction == 3:\n move_buffer[4] = 0x31\n move_buffer[5] = _map(speed, 0, 100, 128, 255)\n\n move_buffer[6] = ~(0x09 + 0x00 + move_buffer[4] + move_buffer[5]) & 0xFF\n\n uart.write(move_buffer)\n\n\n@checkInit\ndef clampX(milimeters=50):\n clampBuffer = bytearray(9)\n clampBuffer[0] = 0x55\n clampBuffer[1] = 0x00\n clampBuffer[2] = 0x09\n clampBuffer[3] = 0x00\n clampBuffer[4] = 0x73\n clampBuffer[7] = 0x00\n clampBuffer[8] = 0xAA\n\n clampBuffer[5] = milimeters\n clampBuffer[6] = ~(0x09 + 0x00 + 0x73 + clampBuffer[5]) & 0xFF\n\n uart.write(clampBuffer)\n sleep(1000)\n\n\n@checkInit\ndef clampZ(milimeters=50):\n clampBuffer = bytearray(9)\n clampBuffer[0] = 0x55\n clampBuffer[1] = 0x00\n clampBuffer[2] = 0x09\n clampBuffer[3] = 0x00\n clampBuffer[4] = 0x74\n clampBuffer[7] = 0x00\n clampBuffer[8] = 0xAA\n\n clampBuffer[5] = milimeters\n clampBuffer[6] = ~(0x09 + 0x00 + 0x74 + clampBuffer[5]) & 0xFF\n\n uart.write(clampBuffer)\n sleep(1000)\n\n\n@checkInit\ndef clamp(force):\n clampBuffer = bytearray(9)\n clampBuffer[0] = 0x55\n clampBuffer[1] = 0x00\n clampBuffer[2] = 0x09\n clampBuffer[3] = 0x00\n clampBuffer[4] = 0x71\n clampBuffer[7] = 0x00\n clampBuffer[8] = 0xAA\n\n clampBuffer[5] = force\n clampBuffer[6] = ~(0x09 + 0x00 + 0x71 + clampBuffer[5]) & 0xFF\n\n uart.write(clampBuffer)\n sleep(1000)\n\n\ndef init_xgo_serial(tx_pin, rx_pin, baudrate=115200):\n global _XGOInit\n uart.init(baudrate=baudrate, tx=tx_pin, rx=rx_pin)\n init_action()\n _XGOInit = True\n\n\ndef init_action():\n commands_buffer = bytearray(9)\n commands_buffer[0] = 0x55\n commands_buffer[1] = 0x00\n commands_buffer[2] = 0x09\n commands_buffer[3] = 0x00\n commands_buffer[4] = 0x3E\n commands_buffer[5] = 0xFF\n commands_buffer[6] = ~(0x09 + 0x00 + 0x3E + 0xFF) & 0xFF\n commands_buffer[7] = 0x00\n commands_buffer[8] = 0xAA\n\n uart.write(commands_buffer)\n sleep(2000)\n\n\n@checkInit\ndef action(id):\n commands_buffer = bytearray(9)\n commands_buffer[0] = 0x55\n commands_buffer[1] = 0x00\n commands_buffer[2] = 0x09\n commands_buffer[3] = 0x00\n commands_buffer[4] = 0x3E\n commands_buffer[5] = id\n commands_buffer[6] = ~(0x09 + 0x00 + 0x3E + id) & 0xFF\n commands_buffer[7] = 0x00\n commands_buffer[8] = 0xAA\n\n uart.write(commands_buffer)\n sleep(2000)\n\n\ndef changeInit(tx, rx):\n global _TX\n global _RX\n _TX = tx\n _RX = rx\n init_xgo_serial(_TX, _RX)\n\n\n@checkInit\ndef setSpeed(speed):\n global _speed\n _speed = speed\n\n\ndef forward():\n _move(0, _speed)\n\n\ndef backward():\n _move(1, _speed)\n\n\ndef left():\n _move(2, _speed)\n\n\ndef right():\n _move(3, _speed)\n",
2310
+ mbglow: '# mbglow.py\n# V1.5, June 30, 2018\n# Module for a crash course in Python\n# An implementation of a glowbug, firefly (Leuchtkaefer)\n\nfrom microbit import *\n\n_x = 0\n_y = 0\n_dir = 0\n_speed = 50\n_trace = True\n_visible = False\n\ndef makeGlow():\n global _visible\n display.set_pixel(2, 2, 9)\n _visible = True\n\ndef clear():\n display.clear()\n \ndef forward(): \n _forward(1)\n\ndef back(): \n _forward(-1)\n \ndef right(angle):\n global _dir\n _dir = (_dir + angle) % 360\n\ndef left(angle):\n right(-angle)\n\ndef setPos(x, y):\n global _x, _y\n _x = x\n _y = y\n _render()\n\ndef getPos():\n return _x, _y\n\ndef setSpeed(speed):\n global _speed\n _speed = speed\n \ndef showTrace(enable):\n global _trace\n _trace = enable \n\ndef isLit():\n return (display.get_pixel(_x + 2, 4 - (_y + 2)) == 9)\n \ndef _forward(s):\n global _x, _y\n sleep(2000 - _speed * 20)\n d = _dir // 45\n if d in [1, 2, 3]: \n _x += s\n if d in [5, 6, 7]: \n _x -= s\n if d in [0, 1, 7]: \n _y += s\n if d in [3, 4, 5]: \n _y -= s\n _render()\n\ndef _render():\n if not _visible:\n print("Use \\"makeGlow()\\" to create a Glow.")\n raise Exception("Glow not initialized.")\n if not _trace:\n display.clear()\n if -2 <= _x <= 2 and -2 <= _y <= 2: \n display.set_pixel(_x + 2, 4 - (_y + 2), 9)',
2311
+ mbthetabot: "from microbit import *\nfrom utime import ticks_us, sleep_us\nfrom neopixel import *\n\n_speedPercent = 50\n_powerByteL = 40\n_powerByteR = 40\n_powerBytesLUT = bytes(b'\\x00\\x0b\\x0b\\x0c\\x0c\\x0d\\x0d\\x0d\\x0e\\x0e\\x0f\\x0f\\x0f\\x10\\x10\\x11\\x11\\x11\\x12\\x12\\x13\\x13\\x13\\x14\\x14\\x15\\x15\\x15\\x16\\x16\\x17\\x17\\x17\\x18\\x19\\x1a\\x1b\\x1b\\x1c\\x1d\\x1e\\x1f\\x20\\x21\\x22\\x23\\x23\\x24\\x25\\x26\\x27\\x28\\x29\\x2a\\x2b\\x2b\\x2c\\x2d\\x2e\\x2f\\x30\\x31\\x32\\x33\\x34\\x36\\x38\\x3a\\x3c\\x3f\\x41\\x44\\x46\\x49\\x4c\\x4f\\x53\\x56\\x5a\\x5e\\x62\\x67\\x6b\\x70\\x75\\x7b\\x81\\x87\\x8d\\x94\\x9b\\xa3\\xab\\xb4\\xbd\\xc6\\xd0\\xdb\\xe6\\xf2\\xff')\n\n_powerOffset = 0\n_powerDifferential = 0\n_arcScaling = 0\n\n_ADDR_ATM = 0x22\n_nbLeds = 14\n\n\ndef _setMotors(dirL, powerL, dirR, powerR):\n pinsL = (pin14, pin13)\n pinsR = (pin16, pin15)\n\n pinsL[dirL].write_analog(powerL)\n pinsL[1 - dirL].write_analog(0)\n\n pinsR[dirR].write_analog(powerR)\n pinsR[1 - dirR].write_analog(0)\n\n\ndef _setSingleMotor(side, direction, power):\n if side == 0:\n pins = (pin14, pin13)\n elif side == 2:\n pins = (pin16, pin15)\n\n pins[direction].write_analog(power)\n pins[1 - direction].write_analog(0)\n\n\ndef _getArcBytes(r):\n outerSpeed = _speedPercent\n rCm = int(r * 100)\n threshold = outerSpeed - max(rCm + 20, 40)\n if threshold <= 0:\n outerSpeed = min(max(rCm + 40, 40), 100)\n reducedSpeed = 0\n if rCm >= 4:\n flattening = (100 - outerSpeed) // 2\n reducedSpeed = (rCm * 10 - 35) / \\\n (rCm * (11 + (_arcScaling-4)/10) + 90 + flattening)\n reducedSpeed = reducedSpeed * outerSpeed\n innerByte = _getPowerByteLUT(int(reducedSpeed), 0)\n outerByte = _getPowerByteLUT(int(outerSpeed), 0)\n return (innerByte, outerByte)\n\n\ndef calibrate(offset, differential=0, arcScaling=0):\n global _powerDifferential\n global _powerOffset\n global _arcScaling\n\n _powerOffset = max(min(int(offset), 150), -10)\n _powerDifferential = max(min(int(differential), 150), -150)\n _arcScaling = max(min(arcScaling, 50), -15)\n setSpeed(_speedPercent)\n\n\ndef setSpeed(speed):\n global _speedPercent\n global _powerByteL\n global _powerByteR\n\n _speedPercent = int(min(max(speed, 0), 100))\n powerByte = _getPowerByteLUT(_speedPercent, _powerOffset)\n boost = round((1 - _speedPercent / 100) *\n abs(_powerDifferential)) if _speedPercent > 0 else 0\n reduction = round((_speedPercent / 100) * abs(_powerDifferential))\n if _powerDifferential > 0:\n _powerByteL = powerByte - reduction\n _powerByteR = powerByte + boost\n else:\n _powerByteL = powerByte + boost\n _powerByteR = powerByte - reduction\n\n\ndef _getPowerByteLUT(speed, offset):\n speedIndex = int(speed * (len(_powerBytesLUT) - 1) / 100)\n return min(_powerBytesLUT[speedIndex] + offset, 1023)\n\n\ndef stop():\n _setMotors(0, 0, 0, 0)\n\n\ndef forward():\n _setMotors(0, _powerByteL, 0, _powerByteR)\n\n\ndef backward():\n _setMotors(1, _powerByteL, 1, _powerByteR)\n\n\ndef left():\n _setMotors(1, _powerByteL, 0, _powerByteR)\n\n\ndef right():\n _setMotors(0, _powerByteL, 1, _powerByteR)\n\n\ndef rightArc(radius):\n inner, outer = _getArcBytes(radius)\n _setMotors(0, outer, 0, inner)\n\n\ndef leftArc(radius):\n inner, outer = _getArcBytes(radius)\n _setMotors(0, inner, 0, outer)\n\n\ndef getDistance():\n pin12.write_digital(1)\n sleep_us(10)\n pin12.write_digital(0)\n pin12.set_pull(pin15.NO_PULL)\n while pin12.read_digital() == 0:\n pass\n start = ticks_us()\n while pin12.read_digital() == 1:\n pass\n end = ticks_us()\n echo = end-start\n distance = int(0.01715 * echo)\n return distance\n\n\ndef setLED(position, red, green, blue):\n global _ADDR_ATM\n i2c_data = bytearray(5)\n\n i2c_data[0] = 1\n\n i2c_data[1] = position\n\n i2c_data[2] = red\n i2c_data[3] = green\n i2c_data[4] = blue\n\n i2c.write(_ADDR_ATM, i2c_data)\n\n\ndef fill(red, green, blue):\n for position in range(_nbLeds):\n setLED(position, red, green, blue)\n\n\ndef readLine(side): # 0=left 1=right\n i2c.write(_ADDR_ATM, bytearray([side + 1]), False)\n result = i2c.read(_ADDR_ATM, 2)\n result = result[0] + (result[1] << 8)\n return result\n\n\ndef readLight(side): # 0=left 1=right\n i2c.write(_ADDR_ATM, bytearray([side + 3]), False)\n result = i2c.read(_ADDR_ATM, 2)\n result = result[0] + (result[1] << 8)\n return result\n",
2312
+ mbrobot_legacy: 'import gc\nfrom microbit import i2c, pin1, pin2, pin8, pin12, pin13, pin14, sleep\nimport machine\n\n_axe = 0.097\ndef w(d1, d2, s1, s2):\n try:\n i2c.write(0x10, bytearray([0, d1, s1]))\n i2c.write(0x10, bytearray([2, d2, s2]))\n except:\n print("Please switch on mbRobot!")\n while True:\n pass\n \ndef setSpeed(speed):\n global _v\n if speed < 20:\n _v = speed + 5\n else:\n _v = speed \n\ndef forward():\n w(0, 0, _v, _v)\n\ndef backward():\n w(1, 1, _v, _v)\n \ndef stop():\n w(0, 0, 0, 0)\n \ndef right():\n w(0 if _v > 0 else 1, 1 if _v > 0 else 0, int(_v * 0.9), int(_v * 0.9)) \n\ndef left():\n w(1 if _v > 0 else 0, 0 if _v > 0 else 1, int(_v * 0.9) , int(_v * 0.9))\n\ndef rightArc(r):\n v = abs(_v)\n if r < _axe:\n v1 = 0\n else: \n f = (r - _axe) / (r + _axe) * (1 - v * v / 200000) \n v1 = int(f * v)\n if _v > 0:\n w(0, 0, v, v1)\n else:\n w(1, 1, v1, v)\n\ndef leftArc(r):\n v = abs(_v)\n if r < _axe:\n v1 = 0\n else:\n f = (r - _axe) / (r + _axe) * (1 - v * v / 200000) \n v1 = int(f * v)\n if _v > 0:\n w(0, 0, v1, v)\n else:\n w(1, 1, v, v1)\n\nexit = stop\ndelay = sleep\n\ndef getDistance():\n pin1.write_digital(1)\n pin1.write_digital(0)\n p = machine.time_pulse_us(pin2, 1, 50000)\n cm = int(p / 58.2 + 0.5)\n return cm if cm > 0 else 255\n\ndef setLED(on):\n pin8.write_digital(on)\n pin12.write_digital(on)\n \ndef setServo(S, Angle):\n if S == "S1":\n Servo = 0x14\n if S == "S2":\n Servo = 0x15\n buf = Servo, Angle\n i2c.write(0x10, bytes(buf)) \n\npin2.set_pull(pin2.NO_PULL)\n_v = 50 # entspricht default 50\nirLeft = pin13\nirRight = pin14\nledLeft = pin8\nledRight = pin12\n\nforward()',
2313
+ mbalarm: "# mbalarm.py\n\nimport music\n\n_m = ['c6:1', 'r', 'c6,1', 'r', 'r', 'r']\n\ndef setAlarm(on):\n if on:\n music.play(_m, wait = False, loop = True) \n else:\n music.stop()\n \n \ndef beep():\n music.pitch(2000, 200, wait = False)",
2314
+ mbminibit: "from microbit import *\nfrom neopixel import *\nimport utime\n\n_nbLeds = 4\n_np = NeoPixel(pin13, _nbLeds)\n\n_speedPercent = 50\n_powerLeft = 90\n_powerRight = 90\n\n_powerOffset = 0\n_powerDifferential = 0\n_arcScaling = 0\n\n_MAX_CM_DISTANCE = 500\n_CM_PER_MICROSECOND = 29.1\n\n\ndef _setMotors(dirL, powerL, dirR, powerR):\n pin8.write_analog(powerL if dirL == 1 else 0)\n pin12.write_analog(0 if dirL == 1 else powerL)\n pin16.write_analog(0 if dirR == 1 else powerR)\n pin14.write_analog(powerR if dirR == 1 else 0)\n\n\ndef _pulse_in(pin, value, timeout):\n start_time = utime.ticks_us()\n while pin.read_digital() != value:\n if utime.ticks_diff(utime.ticks_us(), start_time) > timeout:\n return 0\n start_time = utime.ticks_us()\n while pin.read_digital() == value:\n if utime.ticks_diff(utime.ticks_us(), start_time) > timeout:\n return 0\n return utime.ticks_diff(utime.ticks_us(), start_time)\n\n\ndef _getArcBytes(r):\n outerSpeed = _speedPercent\n if r > 0:\n innerSpeed = outerSpeed * max(0.2, min(1, 1 - r / 100))\n else:\n innerSpeed = 0\n\n innerByte = _convertSpeedToAnalogValue(int(innerSpeed), 0)\n outerByte = _convertSpeedToAnalogValue(int(outerSpeed), 0)\n return (innerByte, outerByte)\n\n\ndef _convertSpeedToAnalogValue(speed, offset):\n analogValue = int(speed * 255 / 100) + offset\n return min(max(analogValue, 0), 255)\n\n\ndef calibrate(offset, differential=0, arcScaling=0):\n global _powerDifferential\n global _powerOffset\n global _arcScaling\n _powerOffset = max(min(int(offset), 100), -10)\n _powerDifferential = max(min(int(differential), 150), -150)\n _arcScaling = max(min(arcScaling, 50), -15)\n setSpeed(_speedPercent)\n\n\ndef setSpeed(speed):\n global _speedPercent\n global _powerLeft\n global _powerRight\n _speedPercent = int(min(max(speed, 0), 100))\n powerByte = _convertSpeedToAnalogValue(_speedPercent, _powerOffset)\n boost = round((1 - _speedPercent / 100) *\n abs(_powerDifferential)) if _speedPercent > 0 else 0\n reduction = round((_speedPercent / 100) * abs(_powerDifferential))\n if _powerDifferential > 0:\n _powerLeft = powerByte - reduction\n _powerRight = powerByte + boost\n else:\n _powerLeft = powerByte + boost\n _powerRight = powerByte - reduction\n\n\ndef stop():\n _setMotors(0, 0, 0, 0)\n\n\ndef forward():\n _setMotors(0, _powerLeft, 0, _powerRight)\n\n\ndef backward():\n _setMotors(1, _powerLeft, 1, _powerRight)\n\n\ndef left():\n _setMotors(1, _powerLeft, 0, _powerRight)\n\n\ndef right():\n _setMotors(0, _powerLeft, 1, _powerRight)\n\n\ndef rightArc(radius):\n inner, outer = _getArcBytes(radius)\n _setMotors(0, outer, 0, inner)\n\n\ndef leftArc(radius):\n inner, outer = _getArcBytes(radius)\n _setMotors(0, inner, 0, outer)\n\n\ndef setLED(pos, red, green, blue):\n _np[pos] = (red, green, blue)\n _np.show()\n\n\ndef fill(red, green, blue):\n for i in range(_nbLeds):\n _np[i] = (red, green, blue)\n _np.show()\n\n\ndef getDistance():\n trig = pin15\n echo = pin15\n d = 10\n trig.set_pull(trig.NO_PULL)\n for _ in range(10):\n trig.write_digital(0)\n utime.sleep_us(2)\n trig.write_digital(1)\n utime.sleep_us(10)\n trig.write_digital(0)\n duration = _pulse_in(echo, 1, _MAX_CM_DISTANCE * _CM_PER_MICROSECOND)\n if duration > 0:\n d = duration\n break\n return round(d / _CM_PER_MICROSECOND)\n",
2315
+ mbrobot_plusV2: `# mbrobot_plusV2.py
2316
+ # Date 10/09/24
2317
+
2318
+ from microbit import i2c, pin0, pin1, pin2, pin13, pin14, pin15, sleep
2319
+ import gc
2320
+ import machine
2321
+ import music
2322
+ import neopixel
2323
+
2324
+ # Motor state
2325
+ _speedPercent = 50
2326
+ _powerByteL = 50
2327
+ _powerByteR = 50
2328
+ _motorState = bytearray(5)
2329
+ _powerBytesLUT = bytes(b'\\x00\\x0f\\x10\\x10\\x11\\x12\\x12\\x13\\x13\\x14\\x15\\x15\\x16\\x16\\x17\\x18\\x18\\x19\\x19\\x1a\\x1b\\x1b\\x1c\\x1c\\x1d\\x1e\\x1e\\x1f\\x1f\\x20\\x21\\x21\\x22\\x22\\x23\\x24\\x24\\x25\\x25\\x26\\x27\\x29\\x2a\\x2b\\x2c\\x2d\\x2e\\x2f\\x30\\x31\\x32\\x33\\x34\\x35\\x36\\x37\\x38\\x39\\x3a\\x3b\\x3b\\x3c\\x3e\\x3f\\x41\\x43\\x45\\x47\\x49\\x4b\\x4d\\x50\\x52\\x55\\x58\\x5b\\x5e\\x61\\x65\\x69\\x6d\\x71\\x75\\x7a\\x7f\\x84\\x89\\x8f\\x95\\x9b\\xa2\\xa9\\xb1\\xb9\\xc1\\xca\\xd3\\xdd\\xe8\\xf3\\xff')
2330
+
2331
+ # Calibration data
2332
+ _powerOffset = 0
2333
+ _powerDifferential = 0
2334
+ _arcScaling = 0
2335
+ _servoMinPulse = 25
2336
+ _servoMaxPulse = 131
2337
+
2338
+ # Signaling objects and buffers
2339
+ _ledState = bytearray(b'\\x0B\\0\\0')
2340
+ _underglowNP = neopixel.NeoPixel(pin15, 4)
2341
+ np_rgb_pixels = _underglowNP
2342
+ _alarmSequence = ['c5:1', 'r', 'c5,1', 'r:3']
2343
+
2344
+ _UNCONNECTEDERRORMSG = "Please connect to Maqueen robot and switch it on."
2345
+
2346
+ # Utility functions
2347
+
2348
+
2349
+ def _setMotors(dirL, powerL, dirR, powerR):
2350
+ # """Write Motor State via i2c
2351
+
2352
+ # Parameters:
2353
+ # dirL (0/1): Direction of left Wheel. 0=forward, 1=backward
2354
+ # powerL (int): Power of left Wheel in range [0,255].
2355
+ # dirR (0/1): Direction of right Wheel. 0=forward, 1=backward
2356
+ # powerR (int): Power of right Wheel in range [0,255].
2357
+ #
2358
+ # raises:
2359
+ # RuntimeError: if Robot is switched off or unconnected. (replaces ENODEV error)
2360
+ # """
2361
+ global _motorState
2362
+ _motorState[1] = dirL
2363
+ _motorState[2] = powerL
2364
+ _motorState[3] = dirR
2365
+ _motorState[4] = powerR
2366
+ try:
2367
+ i2c.write(0x10, _motorState)
2368
+ except:
2369
+ raise RuntimeError(_UNCONNECTEDERRORMSG)
2370
+
2371
+
2372
+ def _setSingleMotor(side, dir, power):
2373
+ # """Write Motor State of a single Motor via i2c
2374
+
2375
+ # Parameters:
2376
+ # side (0/2): Selection of the Wheel. 0=left, 2=right
2377
+ # dir (0/1): Direction for that Wheel. 0=forward, 1=backward
2378
+ # power (int): Power for that Wheel in range [0,255].
2379
+ #
2380
+ # raises:
2381
+ # RuntimeError: if Robot is switched off or unconnected. (replaces ENODEV error)
2382
+ # """
2383
+ global _motorState
2384
+ _motorState[1 + side] = dir
2385
+ _motorState[2 + side] = power
2386
+ try:
2387
+ i2c.write(0x10, _motorState)
2388
+ except:
2389
+ raise RuntimeError(_UNCONNECTEDERRORMSG)
2390
+
2391
+ # _getPowerByte was used to create LookUpTable (_powerBytesLUT) used in _getPowerByteLUT to reduce Memory Leaks.
2392
+ # def _getPowerByte(speed, offset):
2393
+ # # """Computes the power value for a given speed in %.
2394
+ # # It accouts for the nonlinearity of motor strength.
2395
+ # # This is the original function that generates the LUT.
2396
+ #
2397
+ # # Parameter:
2398
+ # # speed (number): Desired speed of the Robot in %. Range [0,100].
2399
+ # # offset (int): basic power offset to add to the function.
2400
+ # # Returns:
2401
+ # # int: Power in range [0,255] to write to the motors via i2c.
2402
+ # # """
2403
+ # if speed <= 0:
2404
+ # return 0
2405
+ # elif speed < 40:
2406
+ # return int(0.6 * speed + 15 + offset)
2407
+ # elif speed < 60:
2408
+ # return int(speed + offset)
2409
+ # elif speed < 100:
2410
+ # return int(min(1.05546 ** speed + 34 + offset, 255))
2411
+ # else:
2412
+ # return 255
2413
+
2414
+
2415
+ def _getPowerByteLUT(speed, offset):
2416
+ # """Lookup Table version of _getPowerByte"""
2417
+ return min(_powerBytesLUT[speed] + offset, 255)
2418
+
2419
+
2420
+ def _getArcBytes(r):
2421
+ # """Computes the power bytes to drive an arc.
2422
+
2423
+ # Parameter:
2424
+ # r (float): Radius in meters of the desired Arc.
2425
+ # Measured from the center of the axle.
2426
+ # Returns:
2427
+ # (int, int): Power byte values for each motor.
2428
+ # First the outer Wheels byte [0,255],
2429
+ # then the inner Wheels byte [0,255].
2430
+ # """
2431
+ rmm = int(r * 100) # radius in mm
2432
+ outerSpeed = _speedPercent
2433
+ # adjust outer speed for unhealthy values
2434
+ if outerSpeed < 25:
2435
+ outerSpeed = 25
2436
+ speedFix = min(abs(outerSpeed - 70), 20) / 20
2437
+ reducedSpeed = 0
2438
+ if rmm > 5:
2439
+ # formula derived from data and simplified
2440
+ n = outerSpeed * (3 * _arcScaling - outerSpeed - 9 * rmm + 220)
2441
+ d = -14 * _arcScaling + outerSpeed - 200 + 3 * outerSpeed - 10 * rmm - 290
2442
+ reducedSpeed = int(n/d)
2443
+ if reducedSpeed < 2: # fix values at low radii (negative values too)
2444
+ reducedSpeed = 2 if rmm > 15 else 1
2445
+ innerByte = _getPowerByteLUT(int(reducedSpeed), 0)
2446
+ outerByte = _getPowerByteLUT(int(outerSpeed), 0)
2447
+ return (innerByte, outerByte)
2448
+
2449
+ # Movement functions
2450
+
2451
+
2452
+ def calibrate(offset, differential=0, arcScaling=0):
2453
+ # """Adjust the driving behaviour of the robots
2454
+
2455
+ # Parameters:
2456
+ # offset (int): Offsets the minimal power of the motors.
2457
+ # Range [-10,50]. Highly affected by battery level.
2458
+ # Adjust this value until it starts moving at speed 1%.
2459
+ # differential (int, optional): Adjusts power difference
2460
+ # of left and right Wheel. Range [-150, 150].
2461
+ # Varies unpredictably with different speeds.
2462
+ # If a Robot steers left when driving forward: negative value
2463
+ # If a Robot steers right when driving forward: positive value
2464
+ # Perfectly straight driving Robots can leave this at 0.
2465
+ # arcScaling (int, optional): Adjusts the radius
2466
+ # driven by leftArc/rightArc. Valid range [-50, 50].
2467
+ # If the Robots radius is too large: positive value
2468
+ # If the Robots radius is too small: negative value
2469
+ # This then adjusts all radii for this Robot, by
2470
+ # scaling it's internal function to the new range.
2471
+ # """
2472
+ global _powerDifferential
2473
+ global _powerOffset
2474
+ global _arcScaling
2475
+ _powerOffset = max(min(int(offset), 50), -14)
2476
+ _powerDifferential = max(min(int(differential), 150), -150)
2477
+ _arcScaling = max(min(arcScaling, 50), -50)
2478
+ setSpeed(_speedPercent)
2479
+
2480
+
2481
+ def setSpeed(speed):
2482
+ # """sets the speed for future motion
2483
+
2484
+ # Parameter:
2485
+ # speed (int): in Range [0,100] as % of desired velocity.
2486
+ # """
2487
+ global _speedPercent
2488
+ global _powerByteL
2489
+ global _powerByteR
2490
+ _speedPercent = int(min(max(speed, 0), 100))
2491
+ powerByte = _getPowerByteLUT(_speedPercent, _powerOffset)
2492
+ boost = round((1 - _speedPercent / 100) *
2493
+ abs(_powerDifferential)) if _speedPercent > 0 else 0
2494
+ reduction = round((_speedPercent / 100) * abs(_powerDifferential))
2495
+ if _powerDifferential > 0:
2496
+ _powerByteL = powerByte - reduction
2497
+ _powerByteR = powerByte + boost
2498
+ else:
2499
+ _powerByteL = powerByte + boost
2500
+ _powerByteR = powerByte - reduction
2501
+
2502
+
2503
+ def resetSpeed():
2504
+ setSpeed(50)
2505
+
2506
+
2507
+ def stop():
2508
+ _setMotors(0, 0, 0, 0)
2509
+
2510
+
2511
+ def forward():
2512
+ _setMotors(0, _powerByteL, 0, _powerByteR)
2513
+
2514
+
2515
+ def backward():
2516
+ _setMotors(1, _powerByteL, 1, _powerByteR)
2517
+
2518
+
2519
+ def left():
2520
+ _setMotors(1, _powerByteL, 0, _powerByteR)
2521
+
2522
+
2523
+ def right():
2524
+ _setMotors(0, _powerByteL, 1, _powerByteR)
2525
+
2526
+
2527
+ def rightArc(radius):
2528
+ # """radius must be given in meters."""
2529
+ inner, outer = _getArcBytes(radius)
2530
+ _setMotors(0, outer, 0, inner)
2531
+
2532
+
2533
+ def leftArc(radius):
2534
+ # """radius must be given in meters."""
2535
+ inner, outer = _getArcBytes(radius)
2536
+ _setMotors(0, inner, 0, outer)
2537
+
2538
+
2539
+ class Motor:
2540
+ def __init__(self, side):
2541
+ # """Create a single motor.
2542
+
2543
+ # Parameter:
2544
+ # side (0/2): 0=left, 2=right
2545
+ # """
2546
+ self._side = side
2547
+
2548
+ def rotate(self, speed):
2549
+ # """Controls rotation of this motor.
2550
+
2551
+ # Parameters:
2552
+ # speed (int): Desired speed in %.
2553
+ # Valid range [-100,100].
2554
+ # Negative values are for backward turning.
2555
+ # """
2556
+ speedClamped = int(min(max(abs(speed), 0), 100))
2557
+ power = _getPowerByteLUT(speedClamped, _powerOffset)
2558
+ direction = 0 if speed > 0 else 1
2559
+ _setSingleMotor(self._side, direction, power)
2560
+
2561
+
2562
+ def setServo(servo, angle):
2563
+ # """Moves the Servo to position angle.
2564
+ # Servos must be connected to the Maqueen Plus V2's "P" connectors.
2565
+ # They are located at the back of the robot.
2566
+
2567
+ # Parameters:
2568
+ # servo (str): Desired Servo Port. Either 'P0', 'P1' or 'P2'.
2569
+ # angle (int): Desired angle in degrees. Range [0,180].
2570
+
2571
+ # raises:
2572
+ # ValueError: if arguments are out of valid range
2573
+ # """
2574
+ if servo == "P0" or servo == 'S1':
2575
+ pin = pin0
2576
+ elif servo == "P1" or servo == 'S2':
2577
+ pin = pin1
2578
+ elif servo == "P2":
2579
+ pin = pin2
2580
+ else:
2581
+ raise ValueError("Unknown Servo. Please use 'P0', 'P1' or 'P2'.")
2582
+
2583
+ if angle < 0 or angle > 180:
2584
+ raise ValueError("Invalid angle. Must be between 0 and 180")
2585
+
2586
+ frac = (_servoMaxPulse - _servoMinPulse) * int(angle)
2587
+ offset = (frac >> 8) + (frac >> 10) + (frac >> 11) + (frac >> 12) # / 180
2588
+ usPulseTime = _servoMinPulse + offset # min + (max-min) * (angle / 180)
2589
+ pin.set_analog_period(20)
2590
+ pin.write_analog(usPulseTime)
2591
+
2592
+
2593
+ def setMinAngleVal(duty):
2594
+ # """ Sets the minimal pulse duty cycle for the servo.
2595
+ # It should match 1ms of a 20ms period, where the duty is in range [0,1024].
2596
+ # Theoretically: 1/20*1024 = 51. Practically: Default is 25. adjust carefully in steps of 1.
2597
+ #
2598
+ # Parameter:
2599
+ # duty (int): The minimal duty amount for a write_analog signal with 20ms pulse.
2600
+ # It should approximate 1ms. 1ms/20ms*1024 = min duty = 0-degree position for the servo.
2601
+ # """
2602
+ global _servoMinPulse
2603
+ _servoMinPulse = int(duty)
2604
+
2605
+
2606
+ def setMaxAngleVal(duty):
2607
+ # """ Sets the maximal pulse duty cycle for the servo.
2608
+ # It should match 2ms of a 20ms period, where the duty is in range [0,1024].
2609
+ # Theoretically: 2/20*1024 = 102. Practically: Default is 131. adjust carefully to increase range of the servo.
2610
+ #
2611
+ # Parameter:
2612
+ # duty (int): The maximal duty amount for a write_analog signal with 20ms pulse.
2613
+ # It should approximate 2ms. 2ms/20ms*1024 = max duty = 180-degree position for the servo.
2614
+ # """
2615
+ global _servoMaxPulse
2616
+ _servoMaxPulse = int(duty)
2617
+
2618
+ # Sensor functions
2619
+
2620
+
2621
+ class IRSensor:
2622
+ _address = bytes(b'\\x1D')
2623
+
2624
+ def __init__(self, index):
2625
+ # """Create a new IR sensor.
2626
+
2627
+ # Parameter:
2628
+ # index (int): 0=R2, 1=R1, 2=M, 3=L1, 4=L2
2629
+ # """
2630
+ self._index = index
2631
+
2632
+ def read_digital(self):
2633
+ # """Returns if the surface below is dark or bright.
2634
+ # Result can be adjusted by putting the sensor on the dark
2635
+ # surface and pressing the LineKey calibration button on the
2636
+ # Robot for a few seconds, until the LED's blink.
2637
+
2638
+ # Returns:
2639
+ # 0 if the surface is dark. No light was reflected (in Air).
2640
+ # 1 if the surface is bright. A lot of light was reflected.
2641
+ #
2642
+ # raises:
2643
+ # RuntimeError: if Robot is switched off or unconnected. (replaces ENODEV error)
2644
+ # """
2645
+ try:
2646
+ i2c.write(0x10, IRSensor._address)
2647
+ except:
2648
+ raise RuntimeError(_UNCONNECTEDERRORMSG)
2649
+ byte = ~i2c.read(0x10, 1)[0]
2650
+ # mask out corresponding bit, from returned byte.
2651
+ return (byte & (2 ** self._index)) >> self._index
2652
+
2653
+ def read_analog(self):
2654
+ # """Returns the brightness of the surface as a byte.
2655
+
2656
+ # Returns:
2657
+ # int: amount of reflection of light in range [0,255].
2658
+ #
2659
+ # raises:
2660
+ # RuntimeError: if Robot is switched off or unconnected. (replaces ENODEV error)
2661
+ # """
2662
+ try:
2663
+ i2c.write(0x10, IRSensor._address)
2664
+ except:
2665
+ raise RuntimeError(_UNCONNECTEDERRORMSG)
2666
+ # Buffer structure:
2667
+ # 1 Byte Bitmask (for digital redout),
2668
+ # then 10 Bytes analog byte values (every second entry is a value).
2669
+ buffer = i2c.read(0x10, 11)
2670
+ return buffer[1 + self._index * 2]
2671
+
2672
+
2673
+ def ir_read_values_as_byte():
2674
+ # """get single byte with bit encoding of each Infrared sensor state
2675
+ # Bits: 0=R2, 1=R1, 2=M, 3=L1, 4=L2
2676
+ # """
2677
+ i2c.write(0x10, bytearray([0x1D]))
2678
+ buf = i2c.read(0x10, 1)
2679
+ return ~buf[0]
2680
+
2681
+
2682
+ def getDistance():
2683
+ # """uses the ultrasonic sensor to measure distance
2684
+
2685
+ # Returns:
2686
+ # int: valid Distance as cm in range [0,500].
2687
+ # For measurement errors or larger distances: 255.
2688
+ # """
2689
+ pin13.write_digital(1)
2690
+ pin13.write_digital(0)
2691
+ p = machine.time_pulse_us(pin14, 1, 50000)
2692
+ # approximate division: p / 58.2 - 0.5
2693
+ cm = (p >> 6) + (p >> 10) + (p >> 11) + (p >> 12) + 1
2694
+ return max(min(cm, 500), 0) if cm > 0 else 255
2695
+
2696
+ # Signaling functions
2697
+
2698
+
2699
+ def setLED(state, stateR=None):
2700
+ # """Set the front red LED's.
2701
+
2702
+ # Parameters:
2703
+ # state (0/1): Sets the state of the left LED.
2704
+ # if stateR is omitted, then both LEDS.
2705
+ # 0=Off, 1=On
2706
+ # stateR (0/1/None, optional): Sets the right LED state.
2707
+ # 0=Off, 1=On, Default=None uses "state" for right LED.
2708
+ # """
2709
+ global _ledState
2710
+ stateR = stateR if stateR != None else state
2711
+ _ledState[1] = state
2712
+ _ledState[2] = stateR
2713
+ i2c.write(0x10, _ledState)
2714
+
2715
+
2716
+ def setLEDLeft(state):
2717
+ # """state: 0=Off, 1=On"""
2718
+ global _ledState
2719
+ _ledState[1] = state
2720
+ i2c.write(0x10, _ledState)
2721
+
2722
+
2723
+ def setLEDRight(state):
2724
+ # """state: 0=Off, 1=On"""
2725
+ global _ledState
2726
+ _ledState[2] = state
2727
+ i2c.write(0x10, _ledState)
2728
+
2729
+
2730
+ def fillRGB(red, green, blue):
2731
+ # """Uses Neopixel to set all 4 bottom RGB LEDs color.
2732
+ # Parameters (red,green,blue) are each a byte in Range [0,255].
2733
+ # """
2734
+ for i in range(4):
2735
+ _underglowNP[i] = (red, green, blue)
2736
+ _underglowNP.show()
2737
+ setRGB=fillRGB
2738
+
2739
+
2740
+ def clearRGB():
2741
+ _underglowNP.clear()
2742
+
2743
+ def posRGB(position, red, green, blue):
2744
+ # """Uses Neopixel to set a single RGB LED of the robot.
2745
+
2746
+ # Parameters:
2747
+ # position (int): position of the targeted LED.
2748
+ # Numbers are visible at underside of Robot.
2749
+ # 0=front left
2750
+ # 1=back left
2751
+ # 2=back right
2752
+ # 3=front right
2753
+ # red, green, blue (int): color byte value.
2754
+ # each in range [0,255].
2755
+
2756
+ # raises:
2757
+ # ValueError: if position argument is out of valid range
2758
+ # """
2759
+ if position < 0 or position > 3:
2760
+ raise ValueError("invalid RGB-LED position. Must be 0,1,2 or 3.")
2761
+ _underglowNP[position] = (red, green, blue)
2762
+ _underglowNP.show()
2763
+
2764
+
2765
+ def setAlarm(state):
2766
+ if state:
2767
+ music.play(_alarmSequence, wait=False, loop=True)
2768
+ else:
2769
+ music.stop()
2770
+
2771
+
2772
+ def beep():
2773
+ music.pitch(440, 200, wait=False)
2774
+
2775
+ # Class constants (for compatibilty)
2776
+
2777
+
2778
+ class LEDState:
2779
+ ON = 1
2780
+ OFF = 0
2781
+ RED = 1
2782
+
2783
+
2784
+ class IR:
2785
+ R2 = 0
2786
+ R1 = 1
2787
+ M = 2
2788
+ L1 = 3
2789
+ L2 = 4
2790
+ masks = [0x01, 0x02, 0x04, 0x08, 0x10]
2791
+
2792
+
2793
+ # Default instances
2794
+ pin2.set_pull(pin2.NO_PULL)
2795
+ delay = sleep
2796
+ irR2 = IRSensor(0)
2797
+ irR1 = IRSensor(1)
2798
+ irRight = irR1
2799
+ irM = IRSensor(2)
2800
+ irL1 = IRSensor(3)
2801
+ irLeft = irL1
2802
+ irL2 = IRSensor(4)
2803
+ motL = Motor(0)
2804
+ motR = Motor(2)
2805
+ `
2806
+ };
2807
+
2808
+ // src/index.ts
2809
+ var minified = {
2810
+ calliope: libraries_default,
2811
+ microbit: libraries_default2
2812
+ };
2813
+ var raw = {
2814
+ calliope: libraries_raw_default,
2815
+ microbit: libraries_raw_default2
2816
+ };
2817
+ var DEVICES = Object.keys(minified);
2818
+ function assertDevice(device) {
2819
+ if (!(device in minified)) {
2820
+ throw new Error(
2821
+ `Unknown device: ${device}. Valid devices are: ${DEVICES.join(", ")}`
2822
+ );
2823
+ }
2824
+ }
2825
+ function listDevices() {
2826
+ return [...DEVICES];
2827
+ }
2828
+ function listLibraries(device) {
2829
+ assertDevice(device);
2830
+ return Object.keys(minified[device]);
2831
+ }
2832
+ function getLibrary(device, name) {
2833
+ assertDevice(device);
2834
+ const source = minified[device][name];
2835
+ if (source === void 0) {
2836
+ throw new Error(
2837
+ `Unknown ${device} library: ${name}. Valid libraries are: ${listLibraries(device).join(", ")}`
2838
+ );
2839
+ }
2840
+ return source;
2841
+ }
2842
+ function getRawLibrary(device, name) {
2843
+ assertDevice(device);
2844
+ const source = raw[device][name];
2845
+ if (source === void 0) {
2846
+ throw new Error(
2847
+ `Unknown ${device} raw library: ${name}. Valid libraries are: ${listLibraries(device).join(", ")}`
2848
+ );
2849
+ }
2850
+ return source;
2851
+ }
2852
+ export {
2853
+ libraries_default as calliopeLibraries,
2854
+ libraries_raw_default as calliopeRawLibraries,
2855
+ getLibrary,
2856
+ getRawLibrary,
2857
+ listDevices,
2858
+ listLibraries,
2859
+ libraries_default2 as microbitLibraries,
2860
+ libraries_raw_default2 as microbitRawLibraries
2861
+ };
2862
+ //# sourceMappingURL=index.mjs.map