밑에 꺼 저희 코드인데 서버랑 http get을 코드를 어떻게 추가해야 하나요?
#include "SPI.h"
#include "WiFi.h"
#include "Adafruit_WS2801.h"
#ifdef __AVR_ATtiny85__
#include
#endif
char ssid[] = "와이파이"; //와이파이 SSID
char pass[] = "비번"; //와이파이 password
//인스턴스 변수 초기화
WiFiServer server(80);
WiFiClient client;
const unsigned long requestInterval = 60000; // 요구 시간 딜레이(1 min)
IPAddress hostIp;
uint8_t ret;
unsigned long lastAttemptTime = 0; // 마지막으로 서버에서 데이터를 전송받은 시간
String currentLine = "";
String weatherString = "";
String timeString = "";
String location = "kiev";
boolean readingWeather = false;
boolean readingTime = false;
boolean stringComplete = false;
int weather;
int temp = 0;
uint8_t dataPin = 2; // Yellow wire on Adafruit Pixels
uint8_t clockPin = 3; // Green wire on Adafruit Pixels
int lednum = 30;
Adafruit_WS2801 strip = Adafruit_WS2801(25, dataPin, clockPin);
void setup() {
//각 변수에 정해진 공간 할당
Serial.begin(115200);
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
clock_prescale_set(clock_div_1); //clock을 16Mhz로 사용
#endif
strip.begin();
strip.show();
delay(10);
//WiFi연결 시도
Serial.println("Connecting to WiFi....");
WiFi.begin(ssid, pass); //WiFi가 패스워드를 사용한다면 매개변수에 password도 작성
server.begin();
Serial.println("Connect success!");
Serial.println("Waiting for DHCP address");
//DHCP주소를 기다린다
while(WiFi.localIP() == INADDR_NONE) {
Serial.print(".");
delay(300);
}
Serial.println("\n");
printWifiData();
connectToServer();
}
void loop()
{
if (client.connected()) {
while (client.available()) {
//전송된 데이터가 있을 경우 데이터를 읽어들인다.
char inChar = client.read();
// 읽어온 데이터를 inChar에 저장한다.
currentLine += inChar;
//inChar에 저장된 Char변수는 currentLine이라는 String변수에 쌓이게 된다.
//라인피드(줄바꿈)문자열이 전송되면 데이터를 보내지 않는다.
if (inChar == '\n') {
//Serial.print("clientReadLine = ");
//Serial.println(currentLine);
currentLine = "";
}
if ( currentLine.endsWith(" readingWeather = true")
){weatherString = " ";}
if (readingWeather) {
if (inChar != 'v') { //다음 전송될 문자가 'v'가 아니라면 계속 날씨 데이터(코드)를 받는다.
weatherString += inChar;
}
else { //다음 전송된 문자가 'v'라면 날씨 데이터(코드)를 출력한다.
readingWeather = false;
weather = getInt(weatherString);
weatherpixel();
Serial.print("weather code: ");
Serial.println(weather);
}
}
if ( currentLine.endsWith(" " ))
if (readingTime) {
if (inChar != '/') { //다음 전송될 문자가 '/'가 아니라면 계속적으로 시간데이터를 받는다
timeString += inChar;
}
else {
readingTime = false;
Serial.print("last update: ");
Serial.println(timeString.substring(2,timeString.length()-1));
}
}
if ( currentLine.endsWith("")) { //현재 스트링이 로 끝났다면 연결을 끊고 다시 서버와 연결을 준비한다.
delay(100); //10초뒤에 서버와 연결을 끊고 재연결을 시도한다.
client.stop();
// serialEvent();
// if (stringComplete) {
// Serial.println(location);
// // clear the string:
// stringComplete = false;
// }
connectToServer();
//Serial.println("Disconnected from Server.\n");
}
}
}
else if (millis() - lastAttemptTime > requestInterval) {
//연결을 실패했다면 requestInterval(60초)이후에 다시 연결을 시도한다.
connectToServer();
}
}
//서버와 연결
void connectToServer() {
Serial.println("");
Serial.println("connecting to server...");
String content = "";
if (client.connect(hostIp, 80)) {
Serial.println("Connected! Making HTTP request to api.openweathermap.org for "+location+"...");
//Serial.println("GET /data/2.5/weather?q="+location+"&mode=xml");
client.println("GET /data/2.5/weather?q="+location+"&mode=xml");
//위에 지정된 주소와 연결한다.
client.print("HOST: api.openweathermap.org\n");
client.println("User-Agent: launchpad-wifi");
client.println("Connection: close");
client.println();
Serial.println("Weather information for "+location);
}
//마지막으로 연결에 성공한 시간을 기록
lastAttemptTime = millis();
}
void printHex(int num, int precision) {
char tmp[16];
char format[128];
sprintf(format, "%%.%dX", precision);
sprintf(tmp, format, num);
Serial.print(tmp);
}
void printWifiData() {
// Wifi쉴드의 IP주소를 출력
Serial.println();
Serial.println("IP Address Information:");
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
//MAC address출력
byte mac[6];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
printHex(mac[5], 2);
Serial.print(":");
printHex(mac[4], 2);
Serial.print(":");
printHex(mac[3], 2);
Serial.print(":");
printHex(mac[2], 2);
Serial.print(":");
printHex(mac[1], 2);
Serial.print(":");
printHex(mac[0], 2);
Serial.println();
//서브넷 마스크 출력
IPAddress subnet = WiFi.subnetMask();
Serial.print("NetMask: ");
Serial.println(subnet);
//게이트웨이 주소 출력
IPAddress gateway = WiFi.gatewayIP();
Serial.print("Gateway: ");
Serial.println(gateway);
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
ret = WiFi.hostByName("api.openweathermap.org", hostIp);
Serial.print("ret: ");
Serial.println(ret);
Serial.print("Host IP: ");
Serial.println(hostIp);
Serial.println("");
}
int getInt(String input){ //String데이터를 intger형으로 변환하는 함수
int i = 2;
while(input[i] != '"'){
i++;
}
input = input.substring(2,i);
char carray[20];
//Serial.println(input);
input.toCharArray(carray, sizeof(carray));
//Serial.println(carray);
temp = atoi(carray);
//Serial.println(temp);
return temp;
}
void weatherpixel(){
float rantime = random(20,50);
//날씨 코드가 200부터 531까지 범위 안에 있다면 type3 패턴으로 led를 제어한다.
//비, 눈, 우박
if(weather>199 && weather<532){
type3();
}
else ;
//날씨 코드가 701부터 781, 또는 802부터 804까지 범위 안에 있다면 type2 패턴으로 led를 제어한다.
//흐림
if(weather>700 && weather <782){
type2();
}
else ;
if(weather>801 && weather<805){
type2();
}
else ;
//날씨 코드가 800부터 801
//흐림
if(weather>799 && weather<802){
type1();
}
else ;
}
void type1(){
rainbow(60);
}
void type2(){
uint16_t i, j;
for(j=0; j<256; j+=1) {
for(i=0; i ; int sum = i+j;)
map(sum,0,300,120,190);
strip.setPixelColor(i, Wheel(sum),Wheel(sum),Wheel(sum));
}
strip.show();
delay(10);
}
}
void type3(){
uint16_t i, j,q;
for(q=0; q for(j=0; j<256; j+=1) {
for(i=0; i int sum = i+j;
map(sum,0,300,120,190);
strip.setPixelColor(i, Wheel(sum),Wheel(sum),0);
}
strip.show();
delay(10);
}
}
theaterChase(strip.Color(255, 255, 0), 60); //흰색 출력
}
//모든 LED를 출력가능한 모든색으로 한번씩 보여주는 동작을 한번하는 함수
void rainbow(uint8_t wait) {
uint16_t i, j;
for(j=0; j<256; j++) {
for(i=0; i strip.setPixelColor(i, Wheel((i+j) & 255));
}
strip.show();
delay(wait);
}
}
//입력한 색으로 LED를 깜빡거리며 표현한다void theaterChase(uint32_t c, uint8_t wait) {
for (int j=0; j<10; j++) {
for (int q=0; q < 3; q++) {
for (int i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, c);
}
strip.show();
delay(wait);
for (int i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, 0);
}
}
}
}
uint32_t Color(byte r, byte g, byte b)
{
uint32_t c;
c = r;
c <<= 8;
c |= g;
c <<= 8;
c |= b;
return c;
}
//255가지의 색을 나타내는 함수
uint32_t Wheel(byte WheelPos)
{
if (WheelPos < 85) {
return Color(WheelPos * 3, 255 - WheelPos * 3, 0);
} else if (WheelPos < 170) {
WheelPos -= 85;
return Color(255 - WheelPos * 3, 0, WheelPos * 3);
} else {
WheelPos -= 170;
return Color(0, WheelPos * 3, 255 - WheelPos * 3);
}
}
원기옥 2015-09-02 20:54:24
구성은 아래와 같이 하면 될 것 같습니다.
1. 아두이노 (서버, HTTP GET을 받을 수 있도록) 설정
2. 스마트폰에서 아두이노가 붙은 동일 WiFi AP에 붙이신 후, 아두이노 로컬 아이피로 HTTP GET 요청
3. 아두이노에서 받은 HTTP GET요청에서 location 파라메터를 확인하고 값 변경
또는, 아두이노(클라이언트) -> AP -> 인터넷 서버(보유하신 서버) <- 스마트폰
과 같이 설정하셔서, 아두이노에서는 주기적으로 인터넷상의 서버에 값을 조회하여 변경하고
스마트폰에서도 필요시 인터넷 서버에 접속하여 값을 변경하는 방식입니다. 통신은 동일하게 HTTP를 사용하시면 되고요