ESP8266의 Wi-Fi를 Arduino에서 사용하여 HTTP 클라이언트로 만들기
브레드 보드 배선
ESP8266의 3.3V RX와 TX를 Arduino Uno의 GPIO에 연결해도 작동했습니다. 로직 레벨 컨버터를 사용하는 것이 좋다고 생각합니다.

스케치
Arduino IDE에서 스케치를 작성합니다. AT 명령은 CoolTerm에서 실행한 것과 동일합니다. Arduino의 C++는 익숙하지 않으므로 쓰는 것이 어렵습니다. 개행 코드의 취급으로 끼워넣었습니다. ESP8266의 SoftwareSerial에서 HTTP 응답을 읽고 Serial로 출력하면
if(c == '\r') Serial.print('\n');
와 같이 CR 뒤에 LF를 추가하지 않으면 출력이 도중에 끊어집니다. 그래도 CoolTerm에서 출력한 내용보다 적기 때문에 코드는 재검토가 필요합니다.#include <SoftwareSerial.h>
#define SSID "xxx"
#define PASS "xxx"
#define BROKER_URL "xxx.xxx.xxx.x"
#define ESP_RX_PIN 2
#define ESP_TX_PIN 3
#define TIMEOUT 4000
SoftwareSerial esp8266Serial(ESP_RX_PIN, ESP_TX_PIN);
void setup()
{
if(connectWiFi())
{
getStatus();
sendCmd("AT+CIPCLOSE",0);
} else {
Serial.println("not connected");
}
Serial.println("finished");
}
void loop()
{
}
void getStatus()
{
String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += BROKER_URL;
cmd += "\",3000";
sendCmd(cmd,500);
String httpCmd = "GET /status HTTP/1.1\r\n";
httpCmd += "Host: ";
httpCmd += BROKER_URL;
httpCmd += "\r\n\r\n";
cmd = "AT+CIPSEND=";
cmd += httpCmd.length();
esp8266Serial.print(cmd);
esp8266Serial.print("\r\n");
Serial.println(cmd);
if(esp8266Serial.find(">"))
{
esp8266Serial.print(httpCmd);
delay(500);
if(esp8266Serial.available())
{
while(esp8266Serial.available())
{
char c = esp8266Serial.read();
Serial.write(c);
if(c == '\r') Serial.print('\n');
}
Serial.print("\r\n");
} else {
Serial.println("http failed");
}
} else {
Serial.println("not started");
}
}
bool connectWiFi() {
Serial.begin(9600);
esp8266Serial.begin(9600);
esp8266Serial.setTimeout(TIMEOUT);
if( sendCmd("AT+RST",3000))
{
String cmd = "AT+CWJAP=\"";
cmd += SSID;
cmd += "\",\"";
cmd += PASS;
cmd += "\"";
return sendCmd(cmd,5000);
} else {
return false;
}
}
bool sendCmd(String cmd, int wait) {
esp8266Serial.print(cmd);
esp8266Serial.print("\r\n");
Serial.println(cmd);
delay(wait);
if(esp8266Serial.find("OK")) {
Serial.println("OK");
return true;
} else {
Serial.println("NG");
return false;
}
}
스케치를 업로드하여 직렬 모니터에서 실행을 확인합니다. Arduino 단체에서도 인터넷에 연결하여 HTTP 요청을 발행할 수 있었습니다. 단지 C++로 AT명령을 쓰는 것도 힘들다. Arduino는 Raspberry Pi에서 Firmata 프로토콜을 사용하여 인터넷 연결을 Linux에 맡기는 것이 더 쉽습니다.
AT+RST
OK
AT+CWJAP="xxx","xxx"
OK
AT+CIPSTART="TCP","xxx.xxx.xxx.x",3000
OK
AT+CIPSEND=45
GET /status HTTP/1.1
Host: xxx.xxx.xxx.x
SEND OK
+IPD,54: restify
Request-Id: c641b1b0-dad9-11e4-9cf7-a53c7accdff6
Response-Time: 2
{"meshblu":"online"}
OK
AT+CIPCLOSE
OK
finished
Reference
이 문제에 관하여(ESP8266의 Wi-Fi를 Arduino에서 사용하여 HTTP 클라이언트로 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/masato/items/81d1eb298964c00f49c5텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)