아두이노와 친구들
arduino plus
Wemos D1 R1 - API 데이터로 서보모터 제어하기 (풍향)
입력 | 출력 | 실습내용 |
API 데이터 | 서보모터 | API 데이터가 표시하는 바람의 방향에 따라 서보모터가 움직임 |
준비물 | 수량 |
Wemos D1 R1 보드 | 1 |
서보모터 | 1 |
점퍼케이블 | 3 |
결선도
코딩
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>
#include <Servo.h>
Servo myservo;
const char* ssid = "Wifi ID";
const char* password = "Wifi PW";
//StaticJsonDocument<2048> doc;
DynamicJsonDocument doc(1000);
String serverName = "http://yongdo.azurewebsites.net/api/v1/weather/real-time?weather_station=school";
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;
String payload = "";
int wind_deg_index = 0;
int wind_speed = 0;
int wind_direction = 0;
long mytime=0;
int servo_position = 0;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
myservo.attach(D5, 700, 2800);
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}
void loop() {
// Send an HTTP POST request depending on timerDelay
if ((millis() - lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;
String serverPath = serverName;
http.begin(client, serverPath.c_str());
// Send HTTP GET request
int httpResponseCode = http.GET();
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
// Serial.println(payload);
char buf[1000];
payload.toCharArray(buf, payload.length()+1);
Serial.println(payload.length());
Serial.println(buf);
DeserializationError error = deserializeJson(doc, buf);
if (error) {
Serial.print("deserializeMsgPack() failed: ");
Serial.println(error.f_str());
return;
}
wind_deg_index = doc["wind_deg_index"];
wind_direction = doc["wind_direction"];
wind_speed = doc["wind_speed"];
Serial.print("wind_deg_index = " + String(wind_deg_index)); Serial.print('t');
Serial.print("wind_direction = " + String(wind_direction)); Serial.println("");
Serial.print("wind_speed = " + String(wind_speed)); Serial.println("");
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
servo_position = 0;
servo_position= int(map(wind_direction, 0, 360, 0, 180));
servo_position = int(constrain(servo_position, 0, 180));
myservo.write(servo_position);
}