정보나눔

오픈소스하드웨어 프로젝트에 대한 다양한 정보를 나누는 공간입니다.

날씨 받아오기
진이 | 2019-03-10

1. 프로젝트 사용한 보드 종류

   오렌지보드 wifi

 

 

2. 사용한 개발 프로그램명

아두이노 ide

 

 

3. 사용한 센서 모델명

 

 

 

4. 연결한 회로 설명 (또는 이미지)

 

 

5. 소스코드 (주석 필수)

  엄청 긴데,,,, 확인 가능하시면 읽어주시고 ㅠㅠ 않읽어 주셔도 무방

 

 

#include <SPI.h>
#include <WizFi250.h>
#include <SoftwareSerial.h>
#include <Adafruit_NeoPixel.h>
#include <Servo.h>
#include <DFPlayer_Mini_Mp3.h>

///////////////////////강수확률//////////////////////////////

int getInt(String input);

char ssid[] = "sejongB1409";       // wifi ID
char pass[] = "sejongB1409@";        // your network password
int status = WL_IDLE_STATUS;       // the Wifi radio's status

char server[] = "www.kma.go.kr"; // 접속 서버 주소

unsigned long lastConnectionTime = 0;         // 제일 마지막에 접속한 시간, in milliseconds
boolean getIsConnected = false;

int temp = 0;
int popVal, sum; // popVal : 입력받은 강수확률 중 제일 큰 값 , sum : seq 값 ( 지금시점으로부터 받는 시간 정보 갯수 ex)sum=2 이고
      //                                                                   현재시각 15시 이면 18시,21시 정보 추출           )

String wt_hour=""; //시간
String wt_pop=""; //강수확률
String wt_seq=""; //seq

//////////////////////미세먼지///////////////////////////////////////////////////////

#define APIKEY    "sXKJr0AZeY9qvfO%2F2e7o7VcLfbdG6ZVE%2F8oFGhrBp5ToCtNNINcRtREVJCAznd8ccIWysV7PJ5ed8qf5TY4I8A%3D%3D"
#define CITY    "대연동"
#define VERSION    "1.3"

char server2[] = "openapi.airkorea.or.kr";
char lastConnectionTime2 = 0;
const unsigned long postingInterval2 = 900000L; // 900초 마다 서버에 접속하여 데이터를 받아 온다.
String rcvbuf;

String wt_datatime=""; //시간
String wt_datatime2="";
String wt_pm10grade=""; //미세먼지등급
String wt_pm10grade2="";

boolean getIsConnected2;
boolean reading10grade;
boolean readingTime;
boolean twice=true;
String rcvbuf2;

WiFiClient client;

void httpRequest();
void httpRequest2();
void printWifiStatus();

//////////////////////////////네오픽셀 및 압력센서//////////////////////////////////////////////////

Adafruit_NeoPixel strip = Adafruit_NeoPixel(2, 5, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip2 = Adafruit_NeoPixel(2, 6, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip3 = Adafruit_NeoPixel(2, 9, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip4 = Adafruit_NeoPixel(2, 10, NEO_GRB + NEO_KHZ800);

int psensor1 = A0; //analog pin 0
int psensor2 = A1;
int psensor3 = A2;
int led1 = 5;
int led2 = 6;
int led3 = 9;
int led4 = 10;
boolean start = false;

/////////////////////////////////초음파 센서//////////////////////////////////////////////////////////

#define TRIG 7
#define ECHO 8
/////////////////// 모터 //////////////////////////////////////////

Servo myservo; 

int pos = 0;    // 서보모터 각도 초기값 0

///////////////////스피커/////////////////////////////

boolean domp3=true;
boolean domp3_02 = true;

///////ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ//////////////////////

void setup()
{
////////////스피커///////////////

 mp3_set_serial (Serial);    
    delay(1);                  
    mp3_set_volume (30); 

 
//////////초음파/////////////////////
 
pinMode(TRIG,OUTPUT);
pinMode(ECHO,INPUT);

//////////LED/////////////////////
  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
  pinMode(led3,OUTPUT);
  pinMode(led4,OUTPUT);
  Serial.println("SLEEP MODE");
  strip.begin(); //네오픽셀을 초기화하기 위해 모든LED를 off시킨다
  strip.show();

/////////////모터//////////////////////////

  myservo.attach(12);  // 핀번호 12번

//////////wifi/////////////////////////
 
  Serial.begin(250000);
  Serial.println(F("\r\nSerial Init"));

  WiFi.init();
 
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");

  printWifiStatus();
  httpRequest();
}

//ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ//

void loop() {

 if(getIsConnected){
 
  if (client.connected()) {
   
    while (client.available()) {


      String line = client.readStringUntil('\n');
 
  if(sum < 5 ){
      //seq
      int seq= line.indexOf("\">");
      if(seq>0) {
        String tmp_str="<data seq=\"";
        String wt_seq = line.substring(line.indexOf(tmp_str)+tmp_str.length(),seq);
        if((wt_seq != "on=\"2.0") & (wt_seq.toInt() < 5)){
         Serial.print("seq is ");
        Serial.println(wt_seq);
        }
        if(sum < wt_seq.toInt()){
          sum = wt_seq.toInt(); 
        }
       
      }
  
    
      //시간
      int temp11= line.indexOf("</hour>");
      if(temp11>0) {
        String tmp_str="<hour>";
        String wt_hour = line.substring(line.indexOf(tmp_str)+tmp_str.length(),temp11);  
        Serial.print("hour is ");
        Serial.println(wt_hour); 
      }
     

        //강수확률   
       int pop= line.indexOf("</pop>");
      if(pop>0) {
        String tmp_str="<pop>";
        String wt_pop = line.substring(line.indexOf(tmp_str)+tmp_str.length(),pop);
        Serial.print("pop is ");
        Serial.println(wt_pop);
         if(popVal < wt_pop.toInt()){
            popVal=wt_pop.toInt();
         }
           
            Serial.println("===================================");
      } 
        
     }
   
   else {
    Serial.println(popVal);
    client.stop();
    httpRequest2();
    line = "";
   }
    }     
    }  
  }
  if(getIsConnected2){
  
    if (client.connected()) {
   
    while (client.available()) {

    char c = client.read();
      
      rcvbuf += c; 
     
      if (c == '\n') {
       
        rcvbuf = "";
      } 
     
      if ( rcvbuf.endsWith("<dataTime>")) {
       
        readingTime = true;
        wt_datatime2 = "";
      }     

      if (readingTime) {
        if (c != '<') {
         
          wt_datatime2 += c;
       
        }
        else { //전송된 문자가 'm'이라면 온도데이터를 그만 저장하고 온도값 출력
          readingTime = false;
          wt_datatime = wt_datatime2.substring(1);
          Serial.println("dataTime  ");
          Serial.println(wt_datatime);
        
        }
      }


           if ( rcvbuf.endsWith("<pm10Grade1h>")) {
           
        reading10grade = true;
        wt_pm10grade2 = "";
      }

      if (reading10grade) {
        if (c != '<') {
          wt_pm10grade2 += c;
        }
        else { 
          reading10grade = false;
          wt_pm10grade = wt_pm10grade2.substring(1);
          Serial.println("10grade is  ");
          Serial.println(wt_pm10grade);
          twice = false;
        }
      }

}

}
  if(millis()-lastConnectionTime <= postingInterval2){
   if(twice){
   start=false;
   }
   else{
    start=true;
   }
  }
 
  if(millis()-lastConnectionTime > postingInterval2){
  start=false; 
 pinMode(ECHO,OUTPUT);
  colorWipe(strip.Color(0, 0, 0), 0);
  colorWipe2(strip2.Color(0, 0, 0), 0);
  colorWipe3(strip3.Color(0, 0, 0), 0);
  colorWipe4(strip4.Color(0, 0, 0), 0);
  httpRequest();
 }
}
///// 초음파 ////////////////


if(start){
  float duration, distance;
  digitalWrite(TRIG, HIGH);
  delay(10);
  digitalWrite(TRIG, LOW);
  duration = pulseIn(ECHO, HIGH);
  distance = ((float)(340 * duration) / 10000) / 2;
Serial.println(distance);

 
  if((distance < 100) & (distance > 0)){
   
int x = analogRead(psensor1);
Serial.println(x);
  if(x > 50){
    if(popVal >= 50)                {  colorWipe(strip.Color(255, 0, 0), 0);  }
    else if(popVal >= 25 & popVal < 50){ colorWipe(strip.Color(252, 196, 3), 0); }
    else if(popVal < 25)            { colorWipe(strip.Color(54, 163, 46), 0); }
  }
 
  else if (x<50){  colorWipe(strip.Color(0, 0, 0), 0);}
 
 int y = analogRead(psensor2);
  if(y > 50){
    if(popVal >= 50)                { colorWipe2(strip2.Color(255, 0, 0), 0);  }
    else if(popVal >= 25 & popVal < 50){ colorWipe2(strip2.Color(252, 196, 3), 0); }
    else if(popVal < 25)            { colorWipe2(strip2.Color(54, 163, 46), 0); }
  }
   else if (y<50){  colorWipe2(strip2.Color(0, 0, 0), 0);}

 int z = analogRead(psensor3);
  if(z > 50){
    if(popVal >= 50)                { colorWipe3(strip3.Color(255, 0, 0), 0);  }
    else if(popVal >= 25 & popVal < 50){ colorWipe3(strip3.Color(252, 196, 3), 0); }
    else if(popVal < 25)            { colorWipe3(strip3.Color(54, 163, 46), 0); }
  }
   else if (z<50){  colorWipe3(strip3.Color(0, 0, 0), 0);}

  delay(50);

if(wt_pm10grade.toInt() >=3)
  {

    colorWipe4(strip4.Color(199, 183, 71), 0);
    if(domp3){
     mp3_play01();
    }
}

if((popVal >= 50) & ((x > 30) | (y > 30) | (z > 30)) ){
  if(domp3_02){
  mp3_play02();
  }
}

  }

else{
  delay(4000);
  domp3 = true;
  domp3_02 = true;
  colorWipe(strip.Color(0, 0, 0), 0);
  colorWipe2(strip2.Color(0, 0, 0), 0);
  colorWipe3(strip3.Color(0, 0, 0), 0);
  colorWipe4(strip4.Color(0, 0, 0), 0);
}
}


}

void mp3_play01(){
  mp3_play(01);
  delay(7000);
  domp3 = false;
}

void mp3_play02(){
  mp3_play(02);
  delay(7000);
  domp3_02 = false;
}

 void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
  }
}
 void colorWipe2(uint32_t c2, uint8_t wait2) {
  for(uint16_t i2=0; i2 < strip2.numPixels(); i2++) {
      strip2.setPixelColor(i2, c2);
      strip2.show();
      delay(wait2);
  }
}

 void colorWipe3(uint32_t c3, uint8_t wait3) {
  for(uint16_t i3=0; i3<strip3.numPixels(); i3++) {
      strip3.setPixelColor(i3, c3);
      strip3.show();
      delay(wait3);
  }
}

 void colorWipe4(uint32_t c4, uint8_t wait4) {
  for(uint16_t i4=0; i4<strip4.numPixels(); i4++) {
      strip4.setPixelColor(i4, c4);
      strip4.show();
      delay(wait4);
  }
}

 


void httpRequest() {
  Serial.println();
  client.stop(); 

 
 
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");

    client.println("GET /wid/queryDFSRSS.jsp?zone=2629053000&mode=xml HTTP/1.1");

    client.println("Host:www.kma.go.kr ");

    client.println("User-Agent:launchpad-wifi");

    client.println("Connection:close");

    client.println();
   
    lastConnectionTime = millis();
   
   Serial.println("===================================");
   getIsConnected = true;
   getIsConnected2 = false;
  }
  else {
    // if you couldn't make a connection
    Serial.println("Connection failed");
    getIsConnected = false;

  }
}

void httpRequest2() {
  Serial.println();
  client.stop();
  start=false;

  if (client.connect(server2, 80)) {
    Serial.println("Connecting mungee...");
 client.print(F("GET /openapi/services/rest/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty?stationName="));
    client.print(CITY);
    client.print(F("&dataTerm=daily&pageNo=1&numOfRows=1&ServiceKey="));
    client.print(APIKEY);
    client.print(F("&ver="));
    client.print(VERSION);
    client.print(F("&returnType=xml"));
    client.print(F(" HTTP/1.1 \r\n"));
    client.print(F("Host: openapi.airkorea.or.kr\r\n"));
    client.print(F("Connection: close\r\n"));
    client.print(F("\r\n\r\n"));

    client.println();
   
   Serial.println("===================================");
   getIsConnected = false;
   getIsConnected2 = true;
   twice = true;
   sum=0;
  }
  else {
    // if you couldn't make a connection
    Serial.println("Connection failed");
  
    getIsConnected2 = false;

  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

int getInt(String input) {
  char carray[20];
  //Serial.println(input);
  input.toCharArray(carray, sizeof(carray));
  //Serial.println(carray);
  temp = atoi(carray);
  return temp;
}

 

6. 문제점 및 에러 내용

 

오렌지 wifi 를 사용하고 있구요.

네오픽셀 led 15씩 4줄 사용합니다.

Adafruit_NeoPixel strip = Adafruit_NeoPixel(15, 5, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip2 = Adafruit_NeoPixel(15, 6, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip3 = Adafruit_NeoPixel(15, 9, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip4 = Adafruit_NeoPixel(15, 10, NEO_GRB + NEO_KHZ800);
 

그리고 기상청에서 강수확률을 받아오고

서버 끊고 다시 airkorea 에 접속하여 미세먼지 등급을 받아오려고 합니다.

그런데 값이 않읽혀 집니다. 또 네오픽셀 갯수를 2개,2개,2개,2개 씩으로 조정하면

값을 받아옵니다........

왜그런 거죠??

 

그리고 wifi 를 연결을 끊었다가 다시  연결하는 함수가 있을까요??

이전글   |    blink 관련 질문드립니다. 2019-03-09
다음글   |    초음파 센서 간섭 현상 2019-03-13