I don't know how to use regular expression in a pile of code and I'm not sure how to code it correctly either. I tried to lookup for tutorial, guides, everything. But I'm still not understand about it, so please help me to fix my stupid code.
Summary of the working, I'm trying to code a small program that controls my computer keyboard through pyserial and with the help of microbit. For example, when button A is pressed, the microbit sends data to my computer through uart and my python shell at the end receiving the message, try to match it and execute the respective command.
This is the code of microbit
from microbit import *
uart.init(baudrate=57600, bits=8, parity=None, stop=1, tx=None, rx=None)
while True:
if button_a.is_pressed():
uart.write("Up")
display.show(Image.ARROW_NW)
if button_b.is_pressed():
uart.write("Down")
display.show(Image.ARROW_S)
else:
display.show(Image.ASLEEP)
This is the code of my python end
import re
import serial
import keyboard
serialPort = serial.Serial(port = "COM5", baudrate=57600,
bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
serialString = ""
while(1):
(serialPort.in_waiting > 0)
serialString = serialPort.readline()
wordsa = ("up")
wordsb = ("down")
if():
words = [word.lower() for word in wordsa if re.match('^[a-zA-Z]+', word)]
keyboard.press_and_release('up')
The problem is I want to have re to match the string or data received from microbit through uart at serialString = serial.Port.readline(), if the microbit sends UP, I would want python to match the data received is UP or Down, then press the keyboard key UP or DOWN respectively. Upon running this shitty code of mine, there are no errors showing up and it won't work at all. I think this is a very stupid question to ask, but please help me. This problem has burned a hole at my brain already.
if():doing? Does that always return false?if():is actuallyif ():which is the same asif []:, so always returns false so never gets into the other code.if serialString =="Up": keyboard.press_and_release('up'), since the Microbit sends "Up". Don't understand why you need a regular expression to check for "Up" vs "Down".if serialString == "Up\n": keyboard.press_and_release('up')