我认为将我的 BBC Microbit 变成一个数字时钟——特别是二进制数字时钟是一个有趣的想法。我在 Python 中敲了一些代码来做到这一点:
from microbit import *
def makeBinary(intValue,padding):
number = intValue
returnValue = ""
brightness = 4 #value 0 to 8
while number > 0:
bit = number % 2
if bit > 0:
bit = brightness
quotient = number / 2
returnValue = str(bit)+returnValue
number = quotient
for i in range(len(returnValue),padding):
returnValue = "0"+returnValue
return returnValue
timeAdvance = 0
minuteAdvance = 0
hourAdvance = 0
secondCounter = 0
while True:
if button_a.was_pressed():
#advance hours
hourAdvance = hourAdvance + 1
if hourAdvance > 23:
hourAdvance = 0
timeAdvance = (hourAdvance*60*60*1000)+(minuteAdvance*60*1000)
elif button_b.was_pressed():
#advance minutes
minuteAdvance = minuteAdvance + 1
if minuteAdvance > 59:
minuteAdvance = 0
timeAdvance = (hourAdvance*60*60*1000)+(minuteAdvance*60*1000)
else:
#calculate and display time
if (running_time()-secondCounter) > 1000:
secondCounter = running_time()
seconds = (running_time()/1000)%60
minutes = ((running_time()+timeAdvance)/1000/60)%60
hours = ((running_time()+timeAdvance)/1000/60/60)%24
pmString = "0"
addthirtyMString = "00000"
addthirtySString = "00000"
if hours>12:
pmString = "9"
hours = hours - 12
if minutes>29:
addthirtyMString = "00900"
minutes = minutes - 30
if seconds>29:
addthirtySString = "00900"
seconds = seconds - 30
hourString = makeBinary(hours,4)
minuteString = makeBinary(minutes,5)
secondString = makeBinary(seconds,5)
time = Image(pmString+hourString+":"+minuteString+":"+addthirtyMString+":"+secondString+":"+addthirtySString)
display.show(time)
问题是它不起作用!在 Microbit 上运行它会导致二进制字段全部返回 1,除非数字为 0。因此 10:48:01AM (错误地)显示为
****
*****
*****
它应该显示为
* *
* *
*
*
鉴于 am/pm led 和 add 30 seconds / add 30 minutes 标记工作正常,这显然只是格式化十进制数的二进制表示(makeBinary
函数)的问题。我最初尝试使用“格式”来执行此操作 - 但 microPython,至少在 microBit 上,显然不喜欢它。
当我makeBinary
在我的“真实”计算机上运行时,它运行良好。有谁知道这里可能有什么问题?或者对于其他将十进制转换为二进制字符串而不使用任何可能混淆 MicroBit 的函数的简单方法的任何建议?