0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【MicroPython】ESP32で入力フォームを作成

Last updated at Posted at 2020-12-18

はじめに

ESP32 MicroPythonでWi-FiアクセスポイントとWebサーバーを立ち上げ入力フォームページを作成してみました.
↓こんな感じ
esp32.png

前提条件

  • ESP32-WROOM-32
  • MicroPython v1.13

プログラム

main.py
import socket
import network
import ssl
import re

ESSID = "ESP32"
PASSWORD = "ESPWROOM32"
IP = "192.168.5.1"

def wifi(essid, pwd, ip, mask, gw, dns):
    ap = network.WLAN(network.AP_IF)
    ap.config(essid = essid, authmode = 3, password = pwd)
    ap.ifconfig((ip,mask,gw,dns))
    # print("(ip,netmask,gw,dns)=" + str(ap.ifconfig()))
    ap.active(True)
    return ap

wifi(ESSID, PASSWORD, IP, '255.255.255.0', IP, '8.8.8.8')

def web_page():
    html = """
    <html lang = "ja">
    <head>
    <title>test</title>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="data:,">
    <style>
    </style>
    </head>
    <body>
    <h1>test page</h1>
    <h2>入力フォーム</h2>
    <form action = "" method = "GET">
    <p><input type="text" name="test" size="40"></p>
    <p><input class="button" type="submit" value="送信"></p> 
    </form>
    </body>
    </html>
   """
    return html

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)

while True:
    conn, addr = s.accept()
    response = web_page()
    conn.send('HTTP/1.1 200 OK\n')
    conn.send('Content-Type: text/html\n')
    conn.send('Connection: close\n\n')
    conn.sendall(response)
    request = str(conn.recv(1024)).lower()
    # print("request : "+  request)
    m = re.search(r'test=(\w+)', request)
    if m != None :
        word = m.group(0)
        print(word[5:])
    conn.close()

コード解説

  • def wifi(essid, pwd, ip, mask, gw, dns)

    Wi-Fiアクセスポイントを立ち上げ
  • s.bind(('', 80))

    HTTPポート80番で接続を待機
  • m = re.search(r'test=(\w+)', request)

    クライアントの入力データを取得
  • word = m.group(0)

    入力データを変数に入れる

実行

スマホなどからESP32のアクセスポイントに接続しブラウザで192.168.5.1にアクセスしてください.

おわりに

おわりです.

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?