LINEダッシュボタンを少し改善しました。ボタン単体での動作を想定して、PCのシリアルモニタでの状態確認ではなく、ブレッドボードに載せたLEDで状態を表示するようにしました。また、ボタンが押されてからWiFiに接続し、メッセージのポストが終わったらWiFi接続を切るようにして省電力化しました。このため、ポストに少し時間がかかります。
緑のLED点滅はWiFi接続中、赤のLED点灯はメッセージのポスト中です。
VIDEO
今後やりたいこと
アクセスポイント情報やLINE Notifyのトークン、メッセージなどをmicroSDカードに格納して汎用化する ESP32をSleepさせて省電力化 スケッチです。無保証です。元スケッチはネットにある色々な情報を参考にさせて頂きました。感謝。
//---------------------------------------------------------------
// 2022.1.28 naka
// LINE Dash Button
//
//---------------------------------------------------------------
#include <WiFi.h>
#include <WiFiClientSecure.h>
#define SW 25
#define LED_G 33
#define LED_R 32
#define ON 1
#define OFF 0
// WiFi Access Point
const char * ssid = "AccessPointName" ;
const char * password = "Himitsu" ;
// LINE Notify
const char * host = "notify-api.line.me" ;
const char * token = "LINE Notifyから取得したトークン" ;
const char * message = "押されたヨ" ;
void setup ()
{
pinMode ( SW , INPUT_PULLUP );
pinMode ( LED_G , OUTPUT );
pinMode ( LED_R , OUTPUT );
led_green ( OFF );
led_red ( OFF );
}
void loop (){
if (! digitalRead ( SW )) {
wifi_connect ();
send_msg2line ();
wifi_disconnect ();
while (! digitalRead ( SW ));
}
}
void led_green ( int onoff ) {
if ( onoff == ON ) digitalWrite ( LED_G , LOW );
else digitalWrite ( LED_G , HIGH );
}
void led_red ( int onoff ) {
if ( onoff == ON ) digitalWrite ( LED_R , LOW );
else digitalWrite ( LED_R , HIGH );
}
void wifi_connect () {
WiFi . begin ( ssid , password );
int onoff = 0 ;
while ( WiFi . status () != WL_CONNECTED ) {
delay ( 500 );
if ( onoff == 0 ) led_green ( ON );
else led_green ( OFF );
onoff ^= 1 ;
}
// 以下の5行は普通は不要のはず。
IPAddress gateway ( 192 , 168 , 0 , 1 );
IPAddress subnet ( 255 , 255 , 255 , 0 );
IPAddress dns1 ( 8 , 8 , 8 , 8 ); // Google DNS primery server
IPAddress dns2 ( 8 , 8 , 4 , 4 ); // Google DNS secondary server
WiFi . config ( WiFi . localIP (), gateway , subnet , dns1 , dns2 );
led_green ( ON );
}
void wifi_disconnect () {
WiFi . disconnect ( true );
led_green ( OFF );
}
void send_msg2line () {
WiFiClientSecure client ;
led_red ( ON );
client . setInsecure ();
if (! client . connect ( host , 443 )) {
int onoff = 1 ;
int i ;
for ( i = 0 ; i < 10 ; i ++) { // blink 5 times
delay ( 100 );
if ( onoff == 0 ) led_red ( ON );
else led_red ( OFF );
onoff ^= 1 ;
}
led_red ( OFF );
return ;
}
String query = String ( "message=" ) + String ( message );
String request = String ( "" ) +
"POST /api/notify HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Authorization: Bearer " + token + "\r\n" +
"Content-Length: " + String ( query . length ()) + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" +
query + "\r\n" ;
client . print ( request );
while ( client . connected ()) {
String line = client . readStringUntil ( '\n' );
if ( line == "\r" ) {
break ;
}
}
String line = client . readStringUntil ( '\n' );
led_red ( OFF );
}