정보나눔

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

아두이노와 esp8266
모던디어 | 2018-01-25

안녕하세요 아두이노로 졸업작품을 하고 있는 학생들입니다.

 

로드셀(무게센서)에서 받아온 값을 esp8266을 통해서 wifi로 PHP로 된 서버에 전달해 주고 싶은데 자꾸 AP가 끊깁니

 

다.. 한 번 연결, 다음 번에 끊기고, 다시 연결, 다시 끊기고... 왜 이런지 해결책을 알 수 있을까요?

 

#include<CountUpDownTimer.h>
#include <SoftwareSerial.h>

#include <LiquidCrystal.h>
#include <Stepper.h>
#include "HX711.h"
#include "ESP8266.h"


#define SSID "KGC"
#define PASS "20171108"
#define DST_IP "183.111.183.6"

#define DOUT  A0
#define CLK  A1
#define MAX 550
#define DOWN 0
#define UP 1
#define STEPS 64      // 스텝모터의 스텝수를 선언한다.


Stepper stepper(STEPS, 0 , 9, 10, 11);  // 스텝모터의 스텝수, 제어핀을 설정한다.
SoftwareSerial esp8266Serial = SoftwareSerial(6,7); //tx rx 주황색 노란색
ESP8266 wifi = ESP8266(esp8266Serial);

 

unsigned long Watch, _micro, time = micros();
unsigned int Clock = 0, R_clock;
boolean Reset = false, Stop = false, Paused = false, _type;
volatile boolean timeFlag = false;

 

int a=8;

unsigned long H;
unsigned long M;
unsigned long S;
unsigned int n=1;
int avg=0;


unsigned long time1=0;
unsigned long time2=0;
unsigned long sremain;
unsigned long c;
unsigned long percentage_sum;
unsigned long count;


float value=0;
int percentage=0;

LiquidCrystal lcd(13,12,5,4,3,2);
HX711 scale(DOUT, CLK);

float calibration_factor = -150000; //-7050 worked for my 440lb maxscale setup
//-210000 is the best calibration factor of the domain gram.

void setup()
{
  
  Serial.begin(9600);
  
  lcd.begin(20,4);
  
  SetTimer(0,0,1); // 10 seconds
  StartTimer();


    // ESP8266
    esp8266Serial.begin(9600);
 
    wifi.begin();
    
    wifi.setTimeout(1000);
 
  pinMode(A3, INPUT);
  pinMode(A2, INPUT);
  stepper.setSpeed(300);    // 스텝모터의 회전수를 설정한다.

  
  scale.set_scale();
  scale.tare();   //Reset the scale to 0
  
  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
  
  
}

void loop()
{
  int value1 = digitalRead(A2);
  int value2 = digitalRead(A3);
  unsigned int id;
  int length;
  int totalRead;
  char buffer[11] = {};
  
  if(value1 == HIGH) {
    stepper.step(500);   // 스텝모터를 100만큼 회전 시킨다.
    delay(10); // 1초간 딜레이  
  } else if(value2 == HIGH){
    stepper.step(-500);
    delay(10);
  } 
  scale.set_scale(calibration_factor); //Adjust to this calibration factor

//로드쉘 lcd에 띄우기
  
  value=scale.get_units()*0.45359*1000;
  if(value<0)
    value=-value;
  percentage=(int)((value/MAX)*100);    
  
  if (count ==  10)
  {
    avg  = percentage_sum / 20;
    percentage_sum = 0;
    count = 0;
  }
  else {
    percentage_sum = percentage_sum + percentage ;
    count++;
  }

  
  //lcd.clear();0.
  lcd.setCursor(0,1);
  lcd.print(percentage);
  lcd.print("%   " );
  
  if(percentage == 97 && n == 1)
  {
     time2=millis();
    
    sremain=((time2-time1)/3000)*100;
    SetTimer(0,0,sremain); // 10 seconds
    StartTimer();  
    lcd.setCursor(0,1);
    n=0;
     //lcd.print("remain");
  }
  

 


//카운터 lcd에 띄우기 소스

  CountUpDownTimer(DOWN); // run the timer

  
  // this prevents the time from being constantly shown.
  if (TimeHasChanged() ) 
  {
    Serial.print(ShowHours());
    Serial.print(":");
    Serial.print(ShowMinutes());
    Serial.print(":");
    Serial.print(ShowSeconds());

    //lcd.clear();
    lcd.setCursor(3,0);
    lcd.print(H);
    lcd.setCursor(5,0);
    lcd.print(":");
    lcd.setCursor(7,0);
    lcd.print(M);
    lcd.setCursor(9,0);
    lcd.print(":");
    lcd.print(S);
  }

      // test
    Serial.print("test: ");
    Serial.println(getStatus(wifi.test()));

    // restart
    Serial.print("restart: ");
    Serial.println(getStatus(wifi.restart()));

    // getVersion
    char version[16] = {};
    Serial.print("getVersion: ");
    Serial.print(getStatus(wifi.getVersion(version, 16)));
    Serial.print(" : ");
    Serial.println(version);

    // getWifiMode
    ///*
   ESP8266WifiMode mode;
   Serial.print("getWifiMode: ");
   Serial.println(getStatus(wifi.getMode(&mode)));//*/
   Serial.print("Wifi mode>>:"); Serial.println(mode);
   if(mode !=ESP8266_WIFI_STATION)
   {
    //setWifiMode
    Serial.print("setWifiMode:");
    //
    Serial.println(getStatus(wifi.setMode(ESP8266_WIFI_ACCESSPOINT)));
    Serial.println(getStatus(wifi.setMode(ESP8266_WIFI_STATION)));
   }
   else
   Serial.println("already ESP8266_WIFI_STATION mode");
    // joinAP
    Serial.print("joinAP: ");
    Serial.println(getStatus(wifi.joinAP(SSID, PASS)));

    
    // connect
    Serial.print("connect: ");
    Serial.println(getStatus(wifi.connect(ESP8266_PROTOCOL_TCP, DST_IP, 80)));
     getConnectionStatue(wifi);
    
    // send
    String cmd = "GET http://ksghj.cafe24.com/test?a=";
    cmd += percentage;
    cmd += " HTTP/1.0\r\n\r\n";
    Serial.print("send: ");
    Serial.println(getStatus(wifi.send((cmd))));

 if ((length = wifi.available()) > 0) {
    id = wifi.getId();
    totalRead = wifi.read(buffer, 1000);
    if (length > 0) {
      Serial.println((char*)buffer);
    }
  }
}

boolean CountUpDownTimer(boolean Type)
{
  _type = Type;
  static unsigned long duration = 1000000; // 1 second
  timeFlag = false;

  if (!Stop && !Paused) // if not Stopped or Paused, run timer
  {
    // check the time difference and see if 1 second has elapsed
    if ((_micro = micros()) - time > duration ) 
    {
      _type == UP? Clock++ : Clock--;
      timeFlag = true;

      if (_type == DOWN && Clock == 0) // check to see if the clock is 0
        Stop = true; // If so, stop the timer

     // check to see if micros() has rolled over, if not,
     // then increment "time" by duration
      _micro < time ? time = _micro : time += duration; 
    }
  }
  return !Stop; // return the state of the timer
}


void ResetTimer()
{
  if(_type) 
    Clock = 0;
  else
    SetTimer(R_clock);

  Stop = false;
}

void StartTimer()
{
  Watch = micros(); // get the initial microseconds at the start of the timer
  Stop = false;
  Paused = false;
  if(_type == UP) 
    Clock = 0;
}

void StopTimer()
{
  Stop = true;
}

void StopTimerAt(unsigned int hours, unsigned int minutes, unsigned int seconds)
{
  if (TimeCheck(hours, minutes, seconds) )
    Stop = true;
}

void PauseTimer()
{
  Paused = true;
}

void ResumeTimer() // You can resume the timer if you ever stop it.
{
  Paused = false;
}

void SetTimer(unsigned int hours, unsigned int minutes, unsigned int seconds)
{
  // This handles invalid time overflow ie 1(H), 0(M), 120(S) -> 1, 2, 0
  unsigned int _S = (seconds / 60), _M = (minutes / 60);
  if(_S) minutes += _S;
  if(_M) hours += _M;

  Clock = (hours * 3600) + (minutes * 60) + (seconds % 60);
  R_clock = Clock;
  Stop = false;
}

void SetTimer(unsigned int seconds)
{
 // StartTimer(seconds / 3600, (seconds / 3600) / 60, seconds % 60);
 Clock = seconds;
 R_clock = Clock;
 Stop = false;
}

int ShowHours()
{
  H = Clock / 3600;
  return  H;
}

int ShowMinutes()
{
  M = (Clock / 60) % 60;
  return  M;
}

int ShowSeconds()
{
  S = Clock % 60;
  return  S;
}

/*
unsigned long ShowMilliSeconds()
{
  return (_micro - Watch)/ 1000.0;
}*/


/*
unsigned long ShowMicroSeconds()
{
  return _micro - Watch;
}*/

boolean TimeHasChanged()
{
  return timeFlag;
}

// output true if timer equals requested time
boolean TimeCheck(unsigned int hours, unsigned int minutes, unsigned int seconds) 
{
  return (hours == ShowHours() && minutes == ShowMinutes() && seconds == ShowSeconds());
}

void getConnectionStatue(ESP8266 wifi) {
  // getConnectionStatus
  ESP8266ConnectionStatus connectionStatus;
  ESP8266Connection connections[5];
  unsigned int connectionCount;
  Serial.print("getConnectionStatus: ");
  Serial.print(getStatus(wifi.getConnectionStatus(connectionStatus, connections, connectionCount)));
  Serial.print(" : ");
  Serial.println(connectionCount);
  for (int i = 0; i < connectionCount; i++) {
    Serial.print(" - Connection: ");
    Serial.print(connections[i].id);
    Serial.print(" - ");
    Serial.print(getProtocol(connections[i].protocol));
    Serial.print(" - ");
    Serial.print(connections[i].ip);
    Serial.print(":");
    Serial.print(connections[i].port);
    Serial.print(" - ");
    Serial.println(getRole(connections[i].role));
  }
}
    


    
//}
    /****************************************/
    /******        WiFi commands       ******/
    /****************************************/
    // getConnectedStations
    /*ESP8266Station stations[5];
    unsigned int stationCount;
    Serial.print("getConnectedStations: ");
    Serial.print(getStatus(wifi.getConnectedStations(stations, stationCount, 5)));
    Serial.print(" : ");
    Serial.println(stationCount);
    for (uint8_t i = 0; i < stationCount; i++) {
      Serial.print(" - ");
      Serial.print(stations[i].ip);
      Serial.print(" - ");
      for (uint8_t j = 0; j < 6; j++) {
        Serial.print(stations[i].mac[j], HEX);
        if (j < 5)
          Serial.print(":");
      }
      Serial.println();
    }
    delay(5000);*/

    /****************************************/
    /******       TCP/IP commands      ******/
    /****************************************/
    // getConnectionStatus
    /*ESP8266ConnectionStatus connectionStatus;
    ESP8266Connection connections[5];
    unsigned int connectionCount;
    Serial.print("getConnectionStatus: ");
    Serial.print(getStatus(wifi.getConnectionStatus(connectionStatus, connections, connectionCount)));
    Serial.print(" : ");
    Serial.println(connectionCount);
    for (int i = 0; i < connectionCount; i++) {
      Serial.print(" - Connection: ");
      Serial.print(connections[i].id);
      Serial.print(" - ");
      Serial.print(getProtocol(connections[i].protocol));
      Serial.print(" - ");
      Serial.print(connections[i].ip);
      Serial.print(":");
      Serial.print(connections[i].port);
      Serial.print(" - ");
      Serial.println(getRole(connections[i].role));
    }
    delay(5000);*/


    // read data
    /*unsigned int id;
    int length;
    int totalRead;
    char buffer[11] = {};

    if ((length = wifi.available()) > 0) {
      id = wifi.getId();
      totalRead = wifi.read(buffer, 10);

      if (length > 0) {
        Serial.print("Received ");
        Serial.print(totalRead);
        Serial.print("/");
        Serial.print(length);
        Serial.print(" bytes from client ");
        Serial.print(id);
        Serial.print(": ");
        Serial.println((char*)buffer);
      }
    }*/


String getStatus(bool status)
{
    if (status)
        return "OK";

    return "KO";
}

String getStatus(ESP8266CommandStatus status)
{
    switch (status) {
    case ESP8266_COMMAND_INVALID:
        return "INVALID";
        break;

    case ESP8266_COMMAND_TIMEOUT:
        return "TIMEOUT";
        break;

    case ESP8266_COMMAND_OK:
        return "OK";
        break;

    case ESP8266_COMMAND_NO_CHANGE:
        return "NO CHANGE";
        break;

    case ESP8266_COMMAND_ERROR:
        return "ERROR";
        break;

    case ESP8266_COMMAND_NO_LINK:
        return "NO LINK";
        break;

    case ESP8266_COMMAND_TOO_LONG:
        return "TOO LONG";
        break;

    case ESP8266_COMMAND_FAIL:
        return "FAIL";
        break;

    default:
        return "UNKNOWN COMMAND STATUS";
        break;
    }
}

String getRole(ESP8266Role role)
{
    switch (role) {
    case ESP8266_ROLE_CLIENT:
        return "CLIENT";
        break;

    case ESP8266_ROLE_SERVER:
        return "SERVER";
        break;

    default:
        return "UNKNOWN ROLE";
        break;
    }
}

String getProtocol(ESP8266Protocol protocol)
{
    switch (protocol) {
    case ESP8266_PROTOCOL_TCP:
        return "TCP";
        break;

    case ESP8266_PROTOCOL_UDP:
        return "UDP";
        break;

    default:
        return "UNKNOWN PROTOCOL";
        break;
    }
}

이전글   |    포인트 충전은 어떻게 하나요 2018-01-24
다음글   |    위치와 방향을 화면으로 표시하는 방법 질문이요!!... 2018-01-29