Microsoft Small Basic

Program Listing: WMF008-1
' Robot Control thru micro:bit
' Version 0.3
' Copyright © 2019 Nonki Takahashi. The MIT License.
' Last update 2019-04-30
' Program ID WMF008-1

GraphicsWindow.Title = "Robot Control thru micro:bit"
distance = 20
angle = 90
Init()
For i = 1 To 4
Move()
Turn()
EndFor

Sub Move
' param distance
log = log + "Move " + distance + LF
Controls.SetTextBoxText(tboxLog, log)
If 0 < distance Then
time = Math.Floor(distance * dx)
LDCommPort.TXString("F" + time + LF)
Program.Delay(time + wait)
ElseIf distance < 0 Then
time = Math.Floor(-distance * dx)
LDCommPort.TXString("B" + time + LF)
Program.Delay(time + wait)
EndIf
EndSub

Sub Turn
' param angle
log = log + "Turn " + angle + LF
Controls.SetTextBoxText(tboxLog, log)
If 0 < angle Then
time = Math.Floor(angle * ax)
LDCommPort.TXString("R" + time + LF)
Program.Delay(time + wait)
ElseIf angle < 0 Then
time = Math.Floor(-angle * ax)
LDCommPort.TXString("L" + time + LF)
Program.Delay(time + wait)
EndIf
EndSub

Sub Init
LF = Text.GetCharacter(10)
ax = 14
dx = 40
wait = 300
gw = GraphicsWindow.Width
gh = GraphicsWindow.Height
GraphicsWindow.BackgroundColor = "LightGray"
GraphicsWindow.BrushColor = "Black"
btnFore = Controls.AddButton("Foreward", 10, 10)
btnBack = Controls.AddButton("Back", 85, 10)
tboxDistance = Controls.AddTextBox(130, 12)
Controls.SetTextBoxText(tboxDistance, distance)
btnRight = Controls.AddButton("Right", 10, 40)
btnLeft = Controls.AddButton("Left", 85, 40)
tboxAngle = Controls.AddTextBox(130, 42)
Controls.SetTextBoxText(tboxAngle, angle)
Controls.ButtonClicked = OnButtonClicked
tboxLog = Controls.AddMultiLineTextBox(10, 70)
Controls.SetSize(tboxLog, gw - 20, gh - 80)
status = LDCommPort.OpenPort("COM3", 115200)
LDCommPort.SetEncoding("Ascii")
EndSub

Sub OnButtonClicked
If Controls.LastClickedButton = btnFore Then
distance = Controls.GetTextBoxText(tboxDistance)
Move()
ElseIf Controls.LastClickedButton = btnBack Then
distance = -Controls.GetTextBoxText(tboxDistance)
Move()
ElseIf Controls.LastClickedButton = btnRight Then
angle = Controls.GetTextBoxText(tboxAngle)
Turn()
ElseIf Controls.LastClickedButton = btnLeft Then
angle = -Controls.GetTextBoxText(tboxAngle)
Turn()
EndIf
EndSub