Newer
Older
M5StickCPlus_FactoryTest2022 / wifi.ino
@motoki miura motoki miura on 19 Feb 2024 2 KB d
#include <M5StickCPlus.h>
#include <WiFi.h>

const char *ssid = "ics-ap"; // 802.11b/g (2.4GHz)only. 5GHz is not supported.
const char *password = "jikkenics";

// const char *ntpserver = "192.168.11.11"; //実験室ローカルNTPサーバ
const char *ntpserver = "ntp.nict.jp";

bool wifi_setup()
{
    M5.Lcd.fillScreen(ORANGE);
    M5.Lcd.setCursor(10, 50, 4);

    WiFi.begin(ssid, password); // 接続開始
    int count = 50;
    while (WiFi.status() != WL_CONNECTED)
    { // 接続中...
        M5.Beep.tone(2000);
        delay(200);
        M5.Beep.mute();
        delay(300);
        M5.Lcd.print(".");
        count--;
        if (count < 1)
            break;
    }
    if (count > 0)
    {
        // 接続完了!!
        M5.Beep.tone(4000);
        M5.Lcd.fillScreen(GREEN);
        M5.Lcd.setCursor(0, 8, 4);
        M5.Lcd.setTextColor(BLACK, GREEN);
        M5.Lcd.print("  Wifi Connected!\n  ");
        String gotip = WiFi.localIP().toString(); // m5デバイスのIPアドレス
        M5.Lcd.println(gotip);

        // MACアドレスを表示
        uint8_t mac[6];
        char macchar[100];
        esp_read_mac(mac, ESP_MAC_WIFI_STA);
        sprintf(macchar, "  %02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
        String macstr = macchar;
        M5.Lcd.println(macstr);

        delay(1500);
        M5.Beep.mute();
        return true;
    }
    return false;
}
void wifi_down()
{
    WiFi.disconnect();
    WiFi.mode(WIFI_OFF);
}

struct tm localTime;
void ntp_setup()
{
    configTime(9 * 3600, 0, ntpserver); // NTPサーバからLocalTimeへの時刻同期

    delay(1000);

    while (localTime.tm_year < 80)
    {
        getLocalTime(&localTime);
        M5.Beep.tone(1000);
        delay(200);
        M5.Beep.mute();
        delay(300);
        M5.Lcd.print(".");
    }
    M5.Beep.tone(2000);

    setRTCfromLT(localTime); // LocalTimeからRTCへの時刻同期
}

// LocalTimeからRTCへの時刻同期
void setRTCfromLT(struct tm lt)
{
    RTC_DateTypeDef DateStruct;
    DateStruct.Year = lt.tm_year + 1900;
    DateStruct.Month = lt.tm_mon + 1;
    DateStruct.Date = lt.tm_mday;
    DateStruct.WeekDay = lt.tm_wday;
    M5.Rtc.SetDate(&DateStruct);

    RTC_TimeTypeDef TimeStruct;
    TimeStruct.Hours = lt.tm_hour;
    TimeStruct.Minutes = lt.tm_min;
    TimeStruct.Seconds = lt.tm_sec + 1;
    M5.Rtc.SetTime(&TimeStruct);
    M5.Lcd.print("  RTC updated!\n  ");
    delay(1500);
    M5.Beep.mute();
}