人类历史上最早的计算机是帕斯卡的加法机,纯机械式的,十进制,有不少视频可以看到,极精妙。最简单的加法机应该用二进制,象周易里的八卦那样,111→110→101→011……分别对应“连连连”、“断连连”、“连断连”、“连连断”……明显是移位再按位或运算。
在STC89C51的流水灯里也是如此。先是给led一个最低位亮灯。经典51是低位亮起的。
led = 0b11111110;
P1= led;
接着把低位0移动7次,同时按位或0b00000001
for (i=0; i<7; i++) {
led = led << 1 | 0b00000001;
P1 = led;
}
这样就把脑子里的计算soft思维过程,放在电子的hardware电路过程里面了。这种软硬之间的切换和对应,实在神奇。
使用MicroPython也能模拟二进制运算,把数字和LED的亮暗对应到一起,如果有按钮,也是可以输入任意数字的。以下示例摘自Raspberry Pi Pico Essentials(Program, Build, and Master Over 50 Projects with MicroPython and the RP2040 Microprocessor)一书。代码中对LED引脚的list化和二进制串位的补齐,值得学习。
from machine import Pin
import utime
PORT = [7, 6, 5, 4, 3, 2, 1, 0] # port connections
DIR = ["0","0","0","0","0","0","0","0"] # port directons
L = [0]*8
def Configure_Port():
for i in range(0, 8):
if DIR[i] == "0":
L[i] = Pin(PORT[i], Pin.OUT)
else:
L[i] = Pin(PORT[i], Pin.IN)
return
def Port_Output(x):
print('dec b:',x)
b = bin(x) # convert into binary
print('bin b:',b)
b = b.replace("0b", "") # remove leading "0b"
diff = 8 - len(b) # find the length
for i in range (0, diff):
b = "0" + b # insert leading os
for i in range (0, 8):
if b[i] == "1":
L[i].value(1)
else:
L[i].value(0)
print(b[i],end='')
print('\n--------------------')
return
#
# Configure PORT to all outputs
#
Configure_Port()
#
# Main program loop. Count up in binary every second
#
cnt = 0
while True:
Port_Output(cnt) # send cnt to port
utime.sleep(1) # wait 1 second
cnt = cnt + 5 if cnt < 255 else 0
结果:
联系客服