pyserialモジュールでシリアル通信をする。webbrowserモジュールでWebページを開く。

f:id:ti-nspire:20190528143427p:plain:h250

import serial
import webbrowser

sp = serial.Serial("COM4", 9600, timeout=2) # serial.Serialクラスを実体化する。timeoutは秒単位。
sp.flush() # シリアルバッファーをクリアする。しなくてもよい。

while(1):
    # .read(1)でシリアルポートから1バイトをバイトデータとして読み出す。
    # response = sp.read(1).decode() # .decode()を適用すれば文字列型へ変換される。
    response = sp.read(1)

    if response == b'0':
        print("Got OK Byte. Waiting for button press.")
    elif response == b'a': # aが押されたら横浜のアメダスのページを開く。
        print("%s received." % response)
        webbrowser.open("http://www.jma.go.jp/jp/amedas_h/today-46106.html?areaCode=000&groupCode=32")
    elif response == b's': # sが押されたら辻堂のアメダスのページを開く。
        print("%s received." % response)
        webbrowser.open("http://www.jma.go.jp/jp/amedas_h/today-46141.html?areaCode=000&groupCode=32")
    else:
        print("Got nothing. Still waiting.")