Last active
November 15, 2023 10:17
-
-
Save ChinYikMing/504f42ffeca1c19874daf97292d284c3 to your computer and use it in GitHub Desktop.
python_gpio.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import RPi.GPIO as GPIO | |
import time | |
st = 1 # sleep time | |
def preamable(pin): | |
for _ in range(0,8): | |
blink(pin) # blink 0.5s | |
time.sleep(st) #dim 0.5s | |
return | |
def all_one(pin): | |
for _ in range(0,8): | |
blink(pin) | |
return | |
def decode(msg): | |
msg_list = [] | |
for c in msg: | |
a = bin(ord(c)) # change c to ASCII int ord and bin format str | |
a = a.replace('0b','') | |
while len(a) < 8: # append to 8-bits format | |
a = '0' + a | |
print(a) | |
msg_list.append(a) | |
return msg_list | |
# blink_msg in byte format | |
def blink_msg(msg_list,pin): | |
for msg in msg_list: | |
for i in msg : | |
if i == '0': | |
time.sleep(st) | |
else : | |
blink(pin) | |
return | |
# blinking one bit signal function | |
def blink(pin): | |
GPIO.output(pin,GPIO.HIGH) | |
time.sleep(st) #light 0.1 sec | |
GPIO.output(pin,GPIO.LOW) | |
#time.sleep(0.01) | |
# dim 0.01 sec | |
return | |
def main(): | |
GPIO.cleanup() | |
msg = input("Type the message: ") | |
#decode(msg) | |
# to use Raspberry Pi board pin numbers | |
GPIO.setmode(GPIO.BCM) # choose Bcm for convinent | |
# set up GPIO output channel, we set GPIO4 (Pin 22) to OUTPUT | |
GPIO.setup(22, GPIO.OUT) | |
preamable(22) | |
if len(bytearray(msg.encode(encoding='utf-8'))) < 10: | |
blink_msg(decode( '0' + str(len(bytearray(msg.encode(encoding='utf-8'))))),22) # exp : len(msg) = 2 send '02' | |
else : | |
blink_msg(decode(str(len(bytearray(msg.encode(encoding='utf-8'))))),22) # exp : len(msg) = 2 send '02' | |
bytes_arr = bytearray(msg.encode(encoding='utf-8')) | |
blink_msg([bin(v)[2:].zfill(8) for v in bytes_arr],22) | |
GPIO.cleanup() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment