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

비밀번호

댓글 작성자
 




1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13483정성태12/14/20232314닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232907닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232285개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232659개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232339개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232531닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232268닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232333닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232177개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232387닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232196C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232276Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232570닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232296닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232232닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232329오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232497닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232244개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232389닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232302오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232343오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232379닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232332닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232310닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232318닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232258VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...