Pico Wの温度をWebサーバ(WordPress)に送信して表示させた結果です。
現在のPico温度: 31.3 ℃(2025-06-11T23:40)プログラムは次です
Pico W 側のコード(HTTPで温度データをwordpressに送る)
Pico Wの内蔵温度センサで取得した温度をWebサーバー(WordPress等)に3分ごとに送信します。
import network
import urequests
import machine
import time
import ntptime
# ====== Wi-Fi設定 ======
SSID = "Raspi_Pico_W"
PASSWORD = "qwertyuiop"
# ====== 送信先URL(温度 + 日時付き)& 認証 ======
POST_URL = "https://yourdomain.com/?pico_temp={}&datetime={}&token=your_secure_token"
# ====== 温度を取得 ======
def read_temp():
sensor_temp = machine.ADC(4)
conversion_factor = 3.3 / 65535
reading = sensor_temp.read_u16() * conversion_factor
temperature = 27 - (reading - 0.706) / 0.001721
return round(temperature, 1)
# ====== 時刻同期(NTP) ======
def sync_time():
try:
ntptime.settime()
print("時刻同期成功")
except:
print("時刻同期失敗")
# ====== 現在の日時を文字列で取得(UTC→JST補正) ======
def get_datetime():
t = time.localtime(time.time() + 9 * 3600) # JST = UTC+9
return "{:04}-{:02}-{:02}T{:02}:{:02}".format(t[0], t[1], t[2], t[3], t[4])
# ====== Wi-Fi接続 ======
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
for _ in range(10):
if wlan.isconnected():
print("接続成功:", wlan.ifconfig())
return True
time.sleep(1)
print("Wi-Fi接続失敗")
return False
# ====== メインループ ======
def main():
if not connect_wifi():
return
sync_time()
while True:
temp = read_temp()
dt = get_datetime()
url = POST_URL.format(temp, dt)
print(f"[{dt}] 送信: {url}")
try:
res = urequests.get(url)
print("応答:", res.text)
res.close()
except Exception as e:
print("送信失敗:", e)
time.sleep(180) # 3分ごと
main()
WordPress 側の処理(プラグインで次コードを設定)
add_action('init', function () {
if (isset($_GET['pico_temp'], $_GET['token']) && $_GET['token'] === 'your_secure_token') {
$temp = floatval($_GET['pico_temp']);
update_option('pico_current_temp', $temp);
if (isset($_GET['datetime'])) {
update_option('pico_temp_time', sanitize_text_field($_GET['datetime']));
}
echo 'OK';
exit;
}
});
add_shortcode('pico_temp', function () {
$temp = get_option('pico_current_temp', 'データ未取得');
$time = get_option('pico_temp_time', '時刻不明');
return "現在のPico温度: " . esc_html($temp) . " ℃(" . esc_html($time) . ")";
});
WordPressの投稿、固定ページ、ウィジェットなどどこでも”pico_temp
” で表示可能。
コメント