Created
October 26, 2025 06:33
-
-
Save vestige/63bd8d36b115e43006f28b8340c5ecac to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| from machine import Pin | |
| import network | |
| import time | |
| import socket | |
| #無線LANへの接続 | |
| def connect_to_wifi(ssid, password): | |
| wlan = network.WLAN(network.STA_IF) | |
| wlan.active(True) | |
| wlan.connect(ssid, password) | |
| max_wait = 10 | |
| while max_wait > 0: | |
| if wlan.status() < 0 or wlan.status() >= 3: | |
| break | |
| max_wait -= 1 | |
| print('接続待ち...') | |
| time.sleep(1) | |
| if wlan.status() != 3: | |
| raise RuntimeError('ネットワーク接続失敗') | |
| else: | |
| print('接続完了') | |
| status = wlan.ifconfig() | |
| print('IPアドレス = ' + status[0]) | |
| #自宅Wi-FiのSSIDとパスワードを入力 | |
| ssid = '' | |
| password = '' | |
| # Wi-Fiに接続 | |
| connect_to_wifi(ssid, password) | |
| port = 80 #ポート指定 | |
| listenSocket = None #初期化 | |
| wlan = network.WLAN(network.STA_IF) | |
| ip = wlan.ifconfig()[0] #自分のipアドレスを取得 | |
| listenSocket = socket.socket() #socketを作成 | |
| listenSocket.bind((ip, port)) # IPアドレスとポート番号をsocketに紐づける | |
| listenSocket.listen(5) # 接続の待受を開始 | |
| listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #指定されたソケットオプションの値を設定 | |
| while True: | |
| print("接続待機中...") | |
| conn, addr = listenSocket.accept() #接続を受信 | |
| print(addr, "が接続しました") #接続した相手のipアドレスを表示 | |
| while True: | |
| data = conn.recv(1024) # クライアントから最大1024バイトのデータを受け取る | |
| print(data) | |
| # 受け取ったデータが0バイト場合、ソケットを閉じる | |
| if len(data) == 0: | |
| print("ソケットを閉じます") | |
| conn.close() | |
| break | |
| else: | |
| # 受け取ったデータがb'1'の場合、LEDを点灯させる | |
| if data == b'1': | |
| Pin('LED', Pin.OUT).on() | |
| time.sleep(0.5) | |
| Pin('LED', Pin.OUT).off() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment