LoginSignup
6
8

More than 1 year has passed since last update.

Raspberry Pi Pico WでLINE通知をお試し

Last updated at Posted at 2023-04-02

Raspberry Pi Pico Wで、WiFiスキャンBluetooth通信は試してましたが、Http Clientは確認してなかったので、試しにLINE NotifyのAPIを使って、Raspberry Pi Pico WからLINEへの通知を試してみます。
開発環境はArduino IDE 2.0を使いました。Raspberry Pi Pico WのArduino環境の準備方法はRaspberry Pi Picoと同様です。ボードの選択でRaspberry Pi Pico Wを選べばOKです。

[参考]

LINE Noifyの登録

LINE通知を行うには、LINE Noifyにログインしてトークンを取得する必要があります。(LINEのアカウントを持っていることが前提)

以下のサイトが参考になります。

スケッチ

単純にRaspberry Pi Pico W上のBOOTSELボタンを押すと定型文をLINE通知するというスケッチです。
WiFiのSSID(ssid)とパスワード(password)、LINE通知のトークン(token)は自分の環境のものに変更して下さい

#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>

#define STASSID "ssid"
#define STAPSK "password"
#define LINE_ACCESS_TOKEN "token"
#define LINE_NOTIFY_MESSAGE "BOOTSELボタンが押されました"

const char *ssid = STASSID;
const char *pass = STAPSK;

HTTPClient httpClient;
String TOKEN = LINE_ACCESS_TOKEN;
String MESSAGE = LINE_NOTIFY_MESSAGE;

WiFiMulti multi;

void lineNotify(String body)
{ 
  String Url = "https://notify-api.line.me/api/notify";

  httpClient.setInsecure();
  httpClient.begin(Url);  
  httpClient.addHeader("Content-Type", "application/x-www-form-urlencoded");
  httpClient.addHeader("Authorization", "Bearer " + TOKEN);

  int status_code = httpClient.POST("message=" + body);
  Serial.println(httpClient.getString());
  if (status_code == 200){
    Serial.printf("[SUCCESS]");
  } else {
    Serial.printf("[ERROR]Code:%d", status_code);
  }
  httpClient.end();
}

void setup() {

  Serial.begin(115200);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  multi.addAP(ssid, pass);

  if (multi.run() != WL_CONNECTED) {
    Serial.println("Unable to connect to network, rebooting in 10 seconds...");
    delay(10000);
    rp2040.reboot();
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  bool bootSel = BOOTSEL;
  static bool beforeBootSel = BOOTSEL;

  if ((multi.run() == WL_CONNECTED)) {

    if(bootSel && !beforeBootSel) {
      lineNotify(MESSAGE);
    }
    beforeBootSel = bootSel;
  }
}

動作確認

SSIDとパスワードが間違っていなければシリアルモニタに以下のように表示されます。

12:01:29.906 -> WiFi connected
12:01:29.906 -> IP address: 
12:01:29.906 -> 192.168.2.182

BOOTSELボタンを押し、トークンが間違ってなければシリアルモニタに以下のように表示されます

12:01:34.259 -> {"status":200,"message":"ok"}
12:01:34.259 -> [SUCCESS]

LINEに通知も飛びました

image.png

最後に

サンプルやライブラリが準備されているので、Http Clientも5分ぐらいで試せました。
Arduino IDE向けのライブラリは豊富なので、センサー連動とかもあっという間にできそうですね。

6
8
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
6
8