Newer
Older
m5scp2_exp / FactoryTest / wifi.ino
#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.Display.fillScreen(ORANGE);
    M5.Display.setCursor(10, 50, 4);

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

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

        return true;
    } else {
        // 一旦、Wifiを切断
        wifi_down();
    }
    return false;
}
void wifi_down()
{
    WiFi.disconnect();
    WiFi.mode(WIFI_OFF);
}

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

    M5.delay(2500);
    for(int i = 0; i < 3; i++)
    {
        M5.Speaker.tone(1000, 200);
        M5.delay(500);
    }
    struct tm localTime;
    getLocalTime(&localTime);
    while (localTime.tm_hour == 0)
    {
        getLocalTime(&localTime);
        // Serial.printf("%2d %2d %2d\n", localTime.tm_hour, localTime.tm_min, localTime.tm_sec);
        M5.Speaker.tone(1000, 200);
        M5.delay(500);
        M5.Display.print(".");
    }
    M5.Speaker.tone(2000, 1500);

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

// LocalTimeからRTCへの時刻同期
void setRTCfromLT(struct tm lt)
{
    m5::rtc_date_t 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);

    m5::rtc_time_t TimeStruct;
    TimeStruct.hours = lt.tm_hour;
    TimeStruct.minutes = lt.tm_min;
    TimeStruct.seconds = lt.tm_sec + 1;
    M5.Rtc.setTime(&TimeStruct);
    M5.Display.print("  RTC updated!\n  ");
    M5.delay(1500);
}