Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

NodeMCU v1 ESP8266 - LittleFS를 이용한 와이파이 접속 정보 업데이트

이전 글에서,

NodeMCU v1 ESP8266 - 펌웨어 내 파일 시스템(SPIFFS, LittleFS) 및 EEPROM 활용
; https://www.sysnet.pe.kr/2/0/12638

ESP8266은 Sketch 영역을 제외한 공간에 대해 파일 시스템처럼 사용할 수 있다고 언급했는데요, 이런 목적에 잘 부합하는 것 중의 하나가 바로 와이파이 접속 정보를 업데이트하는 것입니다.

예를 들어, 개발자 환경의 와이파이 정보로 초기화된 IoT 장치를 엔지니어가 가지고 나가 방문 설치를 하는 중에 단지 와이파이 접속 정보를 업데이트하기 위해 Sketch 프로그램까지 수정하는 것은 너무 원시적인 ^^ 대처 방법입니다. 즉, 그런 경우라면 Sketch는 건드리지 않고 별도 저장된 파일만 수정하는 식이 더 바람직합니다.

"NodeMCU v1 ESP8266 - 펌웨어 내 파일 시스템(SPIFFS, LittleFS) 및 EEPROM 활용" 글에서 설명했듯이 기본적으로 4MB 중 2MB 영역을 파일 시스템으로 할당이 되어 있다고 했습니다.

그럼, 그 영역에 파일을 업로드해볼 텐데요, 이에 대해서는 다음의 글에서 이미 잘 설명하고 있습니다.

Install ESP8266 NodeMCU LittleFS Filesystem Uploader in Arduino IDE
; https://randomnerdtutorials.com/install-esp8266-nodemcu-littlefs-arduino/

이를 위해 별도로 Arduino IDE에 플러그인으로 설치하는 것이 있는데요,

earlephilhower/arduino-esp8266littlefs-plugin
; https://github.com/earlephilhower/arduino-esp8266littlefs-plugin

ESP8266LittleFS-2.6.0.zip
; https://github.com/earlephilhower/arduino-esp8266littlefs-plugin/releases

ESP8266LittleFS-2.6.0.zip 파일을 다운로드해 압축을 풀면 나오는 "ESP8266LittleFS\tool\esp8266littlefs.jar" 파일을 디렉터리까지 포함해서 Arduino IDE의 설치 디렉터리 하위에 있는 "\tools"에 복사합니다. 예를 들어 제 경우에는 다음과 같은 식으로 구성을 했습니다.

아두이노 설치 경로: C:\Program Files (x86)\Arduino
플러그인 복사 경로: C:\Program Files (x86)\Arduino\tools\ESP8266LittleFS\tool\esp8266littlefs.jar

이후 다시 Arduino IDE를 실행하면 다음과 같은 식으로 "Tools"에 파일 업로드를 할 수 있는 "ESP8266 LittleFS Data Upload" 메뉴가 추가됩니다.

esp8266_file_upload_1.png

업로드 파일은 지정하는 방식이 아니고, 현재 열려 있는 Arduino IDE 프로젝트의 ino 파일과 동일한 위치의 "data" 디렉터리를 선택하게 되어 있습니다. 예를 들어,

INO 파일 위치:      C:\sample\WiFiUpdate\WiFiUpdate.ino
data 디렉터리 위치: C:\sample\WiFiUpdate\data

위와 같이 구성해 주고, 와이파이 정보를 담은 wifi_info.txt를 "C:\sample\WiFiUpdate\data" 디렉터리에 복사해 주면 됩니다. 이후 "ESP8266 LittleFS Data Upload" 메뉴를 선택하면 자동으로 data 디렉터리의 내용을 ESP8266 기기에 복사합니다. 그럼 다음과 같은 식으로 복사 과정이 출력되는데,

[LittleFS] data    : C:\sample\WiFiUpdate\data
[LittleFS] size    : 2024
[LittleFS] page    : 256
[LittleFS] block   : 8192
/wifi_info.txt
[LittleFS] upload  : %USERPROFILE%\AppData\Local\Temp\arduino_build_819929/WiFiUpdate.mklittlefs.bin
[LittleFS] address : 0x200000
[LittleFS] reset   : --before default_reset --after hard_reset
[LittleFS] port    : COM4
[LittleFS] speed   : 115200
[LittleFS] python   : %USERPROFILE%\AppData\Local\Arduino15\packages\esp8266\tools\python3\3.7.2-post1\python3.exe
[LittleFS] uploader : %USERPROFILE%\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\tools\upload.py

esptool.py v2.8
Serial port COM4
Connecting....
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: 80:7d:3a:32:cd:33
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 4MB
Compressed 2072576 bytes to 2223...
Wrote 2072576 bytes (2223 compressed) at 0x00200000 in 0.2 seconds (effective 81315.5 kbit/s)...
Hash of data verified.

0x00200000에 썼다고 하니, 2,097,152 바이트의 위치니까 대략 2MB 정도가 됩니다. 이에 기반을 둬 아마도 다음과 같은 식으로 Flash 메모리가 구획되는 것을 예측할 수 있습니다. (혹시 정확한 메모리 레이아웃을 아시는 분은 덧글 부탁드립니다. ^^)

0       ~   1097KB: Sketch 프로그램
1,097KB ~   2,194KB: (Sketch 예비 영역)
2,194KB ~   4,096KB: 파일 시스템 영역

그리고, "reset" 출력을 보면 "--after hard_reset"으로 설정이 되었는데 그런 이유로 인해 파일 업로드 후 프로그램이 자동으로 재시작합니다. 아마도 이것은 esp8266littlefs.jar 플러그인이 그렇게 reset 옵션을 설정하고 업로드하는 듯한데 어쨌든 이로 인해 업로드 완료 후 기존의 Sketch 프로그램은 setup 함수부터 다시 실행해 변경 사항이 반영됩니다.




자, 그럼 이제 지난번 조도 센서 데이터를 ThinkSpeak에 올리던 예제를 꺼내 볼까요? ^^

ThingSpeak 사물인터넷 플랫폼에 ESP8266 NodeMCU v1 + 조도 센서 장비 연동
; https://www.sysnet.pe.kr/2/0/12631

위의 예제 코드에서 WiFi 정보만 파일로부터 업데이트하는 코드를 추가해 볼 수 있습니다.

#include "ThingSpeak.h"
#include "secrets.h"
#include "LittleFS.h"

unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;

#include <ESP8266WiFi.h>

int _photoSensorPin = A0;

String ssid = SECRET_SSID;
String pass = SECRET_PASS;

WiFiClient  client;

void readWifiInfo()
{
  if (!LittleFS.begin())
  {
    Serial.println("An error has occurred while mounting LittleFS");
    return;
  }

  File file = LittleFS.open("/wifi_info.txt", "r");
  if (!file)
  {
    Serial.println("Failed to open file for reading");
    return;
  }

  if (file.available())
  {
    ssid = file.readStringUntil('\n');
  }

  if (file.available())
  {
    pass = file.readStringUntil('\n');
  }

  file.close();
}


void setup() {
  Serial.begin(115200);

  WiFi.mode(WIFI_STA);
  readWifiInfo();

  delay(1000);
  ThingSpeak.begin(client);    
}

void loop() {

  if (WiFi.status() != WL_CONNECTED)
  {
    WiFi.begin(ssid, pass);
    Serial.print(".");    
    delay(5000);
  }

  if (WiFi.status() != WL_CONNECTED)
  {
    return;
  }
  
  int cdsValue = analogRead(_photoSensorPin);
  long rssi = WiFi.RSSI();

  ThingSpeak.setField(1, (float)cdsValue);
  ThingSpeak.setField(2, (float)rssi);
  int httpCode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);

  if (httpCode == 200) {
    Serial.println("Channel write successful.");
  }
  else {
    Serial.println("Problem writing to channel. HTTP error code " + String(httpCode));
  }
  
  delay(1000 * 20);
}

위와 같은 Sketch를 업로드한 다음 "data\wifi_info.txt" 파일의 내용을 오류가 있는 정보로 채운 다음 Arduino IDE에서 "ESP8266 LittleFS Data Upload" 메뉴를 선택해 파일을 올려 봅니다.

결국 부정확한 WiFi 정보를 업데이트했기 때문에 이제는 ThinkSpeak 사이트에 데이터 업로드가 안 될 것입니다. 그리고 다시 정확한 WiFi 정보를 채운 후 파일을 업로드하면 정상적으로 센서 데이터가 ThinkSpeak 사이트로 전달이 될 것이고!

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 9/8/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 106  107  108  [109]  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11231정성태6/28/201719518디버깅 기술: 86. windbg의 mscordacwks DLL 로드 문제 - 세 번째 이야기 [1]
11230정성태6/28/201718917제니퍼 .NET: 26. 제니퍼 닷넷 적용 사례 (6) - 잦은 Recycle 문제
11229정성태6/27/201720297오류 유형: 402. Windows Server Backup 관리 콘솔이 없어진 경우
11228정성태6/26/201717461개발 환경 구성: 320. Visual Basic .NET 프로젝트에서 내장 Manifest 자원을 EXE 파일로부터 제거하는 방법파일 다운로드1
11227정성태6/19/201725877개발 환경 구성: 319. windbg에서 python 스크립트 실행하는 방법 - pykd [6]
11226정성태6/19/201717014오류 유형: 401. Microsoft Edge를 실행했는데 입력 반응이 없는 경우
11225정성태6/19/201716247오류 유형: 400. Outlook - The required file ExSec32.dll cannot be found in your path. Install Microsoft Outlook again.
11224정성태6/13/201718745.NET Framework: 661. Json.NET의 DeserializeObject 수행 시 속성 이름을 동적으로 바꾸는 방법파일 다운로드1
11223정성태6/12/201717683개발 환경 구성: 318. WCF Service Application과 WCFTestClient.exe
11222정성태6/10/201721827오류 유형: 399. WCF - A property with the name 'UriTemplateMatchResults' already exists.파일 다운로드1
11221정성태6/10/201718884오류 유형: 398. Fakes - Assembly 'Jennifer5.Fakes' with identity '[...].Fakes, [...]' uses '[...]' which has a higher version than referenced assembly '[...]' with identity '[...]'
11220정성태6/10/201723697.NET Framework: 660. Shallow Copy와 Deep Copy [1]파일 다운로드2
11219정성태6/7/201718825.NET Framework: 659. 닷넷 - TypeForwardedFrom / TypeForwardedTo 특성의 사용법
11218정성태6/1/201721759개발 환경 구성: 317. Hyper-V 내의 VM에서 다시 Hyper-V를 설치: Nested Virtualization
11217정성태6/1/201717909오류 유형: 397. initerrlog: Could not open error log file 'C:\...\MSSQL12.MSSQLSERVER\MSSQL\Log\ERRORLOG'
11216정성태6/1/201719602오류 유형: 396. Activation context generation failed
11215정성태6/1/201721249오류 유형: 395. 관리 콘솔을 실행하면 "This app has been blocked for your protection" 오류 발생 [1]
11214정성태6/1/201718632오류 유형: 394. MSDTC 서비스 시작 시 -1073737712(0xC0001010) 오류와 함께 종료되는 문제 [1]
11213정성태5/26/201724017오류 유형: 393. TFS - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
11212정성태5/26/201723274오류 유형: 392. Windows Server 2016에 KB4019472 업데이트가 실패하는 경우
11211정성태5/26/201722124오류 유형: 391. BeginInvoke에 전달한 람다 함수에 CS1660 에러가 발생하는 경우
11210정성태5/25/201722453기타: 65. ActiveX 없는 전자 메일에 사용된 "개인정보 보호를 위해 암호화된 보안메일"의 암호화 방법
11209정성태5/25/201770072Windows: 143. Windows 10의 Recovery 파티션을 삭제 및 새로 생성하는 방법 [16]
11208정성태5/25/201728834오류 유형: 390. diskpart의 set id 명령어에서 "The specified type is not in the correct format." 오류 발생
11207정성태5/24/201729676Windows: 142. Windows 10의 복구 콘솔로 부팅하는 방법
11206정성태5/24/201722889오류 유형: 389. DISM.exe - The specified image in the specified wim is already mounted for read/write access.
... 106  107  108  [109]  110  111  112  113  114  115  116  117  118  119  120  ...