본문 바로가기

개발자/Arduino

HTTP를 통해 Arduino Nano 33 IoT와 Ubidots 데이터 보내기 3 Oled에 데이터 표시하기

반응형

 

 

HTTP를 통해 Arduino Nano 33 IoT와 Ubidots 데이터 보내기 3 Oled에 데이터 표시하기 

 

 

 

관련 포스팅을 참고하세요.

 

HTTP를 통해 Arduino Nano 33 IoT와 Ubidots 연결 1

HTTP를 통해 Arduino Nano 33 IoT와 Ubidots 데이터 보내기 2

HTTP를 통해 Arduino Nano 33 IoT와 Ubidots 데이터 보내기 3 Oled에 데이터 표시하기

 

 

 

 

 

코드

 

 

/********************************
 * Libraries included
 *******************************/

#include <SPI.h>
#include <WiFiNINA.h>
#include <avr/dtostrf.h>
#include <SimpleDHT.h>

#include <Wire.h>              // include Arduino wire library (required for I2C devices)
#include <Adafruit_GFX.h>      // include Adafruit graphics library
#include <Adafruit_SSD1306.h>  // include Adafruit SSD1306 OLED display driver
#define OLED_RESET  4    // define display reset pin
Adafruit_SSD1306 display(OLED_RESET);

/********************************
 * Constants and objects
 *******************************/

#define DEVICE_LABEL "arduino-nano-33"
#define TOKEN "USER TOKEN"

//define DHT11 pin connection
int pinDHT11 = 9;
SimpleDHT11 dht11;

String tempVarId = "5f9943df1d847246587273cc";
String humVarId = "5f995f571d847213c58177d3";

char const * VARIABLE_LABEL_1 = "humidity_forcm";
char const * VARIABLE_LABEL_2 = "temparature_forcm";
char const *SERVER="things.ubidots.com";
//char const *SERVER="industrial.api.ubidots.com";
//Replace the above line if you are an Educational user char const *SERVER="things.ubidots.com";

const int HTTPPORT= 443;
char const *AGENT="Arduino Nano 33 IoT";
char const *HTTP_VERSION = " HTTP/1.1\r\n";
char const *VERSION ="1.0";
char const *PATH= "/api/v1.6/devices/";


//char const * SSID_NAME = "PISnet_032AC8"; // Put here your SSID name
//char const * SSID_PASS = "82988298"; // Put here your password

//#define SECRET_SSID "PISnet_032AC8"
//#define SECRET_PASS "82988298"

char const * SSID_NAME = "SK_WiFiGIGAA988"; // Put here your SSID name
char const * SSID_PASS = "1806026356"; // Put here your password

//char const * SSID_NAME = "FORCM"; // Put here your SSID name
//char const * SSID_PASS = "16610350"; // Put here your password

//#define SECRET_SSID "SK_WiFiGIGAA988"
//#define SECRET_PASS "1806026356"


int status = WL_IDLE_STATUS;

WiFiSSLClient client;

/********************************
 * Auxiliar Functions
 *******************************/

void printWiFiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  // print your board'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");
}

void getResponseServer() {
  Serial.println(F("\nUbidots' Server response:\n"));
  while (client.available()) {
    char c = client.read();
    Serial.print(c); // Uncomment this line to visualize the response on the Serial Monitor
  }
}

void waitServer() {
  int timeout = 0;
  while (!client.available() && timeout < 5000) {
    timeout++;
    delay(1);
    if (timeout >= 5000) {
      Serial.println(F("Error, max timeout reached"));
      break;
    }
  }
}

void sendData(char* payload) {
  int contentLength = strlen(payload);

  /* Connecting the client */
  if (client.connect(SERVER, HTTPPORT)) {
    Serial.println("connected to server");
   
    client.print(F("POST "));
    client.print(PATH);    
    client.print(DEVICE_LABEL);
    client.print(F("/"));
    client.print(HTTP_VERSION);
    client.print(F("Host: "));
    client.print(SERVER);
    client.print(F("\r\n"));  
    client.print(F("User-Agent: "));
    client.print(AGENT);
    client.print(F("\r\n"));
    client.print(F("X-Auth-Token: "));
    client.print(TOKEN);
    client.print(F("\r\n"));
    client.print(F("Connection: close\r\n"));
    client.print(F("Content-Type: application/json\r\n"));
    client.print(F("Content-Length: "));
    client.print(contentLength);
    client.print(F("\r\n\r\n"));
    client.print(payload);
    client.print(F("\r\n"));
   
    Serial.print(F("POST "));
    Serial.print(PATH);    
    Serial.print(DEVICE_LABEL);
    Serial.print(F("/"));
    Serial.print(HTTP_VERSION);
    Serial.print(F("Host: "));
    Serial.print(SERVER);
    Serial.print(F("\r\n"));
    Serial.print(F("User-Agent: "));
    Serial.print(AGENT);
    Serial.print(F("\r\n"));
    Serial.print(F("X-Auth-Token: "));
    Serial.print(TOKEN);
    Serial.print(F("\r\n"));
    Serial.print(F("Connection: close\r\n"));
    Serial.print(F("Content-Type: application/json\r\n"));
    Serial.print(F("Content-Length: "));
    Serial.print(contentLength);
    Serial.print(F("\r\n\r\n"));
    Serial.print(payload);
    Serial.print(F("\r\n"));
   
    waitServer();
    getResponseServer();
  }

    /* Disconnecting the client */
  client.stop();
}

void initial_oled()
{
    //initialize the SSD1306 OLED display with I2C address = 0x3D
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

  // clear the display buffer.
  display.clearDisplay();
 
  display.setTextSize(1);   // text size = 1
  display.setTextColor(WHITE, BLACK);  // set text color to white and black background
  display.setCursor(15, 0);            // move cursor to position (15, 0) pixel
  display.print("Device Status");
  display.display();        // update the display
  display.setTextSize(2);   // text size = 2
}

/********************************
 * Main Functions
 *******************************/

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
 
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only

  initial_oled();
}
 
  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }
 
  // attempt to connect to WiFi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(SSID_NAME);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(SSID_NAME, SSID_PASS);
    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWiFiStatus();
}

void loop(){

  char payload[200];
  char str_val_1[30];
  char str_val_2[30];
 
  float value;

  to_oled_temphumidata();
  
  /*4 is the total lenght of number,maximun number accepted is 99.99*/
  value = analogRead(A0);
  dtostrf(get_humi(), 4, 2, str_val_1);
  sprintf(payload, "%s","");
  sprintf(payload, "{\"");
  sprintf(payload, "%s%s\":%s", payload, VARIABLE_LABEL_1, str_val_1);
  //sprintf(payload, "%s}", payload);

  value = analogRead(A1);
  dtostrf(get_temp(), 4, 2, str_val_2);
  sprintf(payload, "%s,",payload);
  //sprintf(payload, "%s{\"", payload);
  sprintf(payload, "%s\"""%s\":%s", payload, VARIABLE_LABEL_2, str_val_2);
  sprintf(payload, "%s}", payload);

  Serial.println(payload);

  //Send the payload to Ubidots
  sendData(payload);
  delay(60000);
} 

char _buffer[8];

void to_oled_temphumidata()
{
  byte temperature = 0;
  byte humidity = 0;
  
  if (dht11.read(pinDHT11, &temperature, &humidity, NULL)) {
    Serial.print("Read DHT11 failed.");
    return;
  }

  display.setCursor(23, 10); 
  sprintf(_buffer, "%d C", (int)temperature);
  display.print(_buffer);
  
  display.setCursor(23, 30); 
  sprintf(_buffer, "%d ", (int)humidity);
  display.print(_buffer);

  display.setCursor(60, 30); 
  sprintf(_buffer, "/", (int)humidity);
  display.print(_buffer);
  
  display.setCursor(23, 50);
    
  display.print(_buffer);
  
  display.drawCircle(54, 12, 2, WHITE);
  display.drawCircle(60, 32, 2, WHITE); 
  display.drawCircle(70, 42, 2, WHITE); 
  
  // update the display 
  display.display();
    
  // DHT11 sampling rate is 1HZ.
  delay(2000);
}

int get_temp()
{
  delay(2000);
  byte temperature = 0;
  byte humidity = 0;
  
  if (dht11.read(pinDHT11, &temperature, &humidity, NULL)) {
    Serial.print("Read DHT11 temp failed.");
    return 0;
  }
  else{
    return (int)temperature;  
  }
}

int get_humi()
{
  delay(2000);
  byte temperature = 0;
  byte humidity = 0;
  
  if (dht11.read(pinDHT11, &temperature, &humidity, NULL)) {
    Serial.print("Read DHT11 humi failed.");
    return 0;
  }else{
    return (int)humidity;
  }
}

 

 

데이터 OLED에 표시하고 Ubidots 에 전송

 

 

 

 

반응형

캐어랩 고객 지원

취업, 창업의 막막함, 외주 관리, 제품 부재!

당신의 고민은 무엇입니까? 현실과 동떨어진 교육, 실패만 반복하는 외주 계약, 아이디어는 있지만 구현할 기술이 없는 막막함.

우리는 알고 있습니다. 문제의 원인은 '명확한 학습, 실전 경험과 신뢰할 수 있는 기술력의 부재'에서 시작됩니다.

이제 고민을 멈추고, 캐어랩을 만나세요!

코딩(펌웨어), 전자부품과 디지털 회로설계, PCB 설계 제작, 고객(시장/수출) 발굴과 마케팅 전략으로 당신을 지원합니다.

제품 설계의 고수는 성공이 만든 게 아니라 실패가 만듭니다. 아이디어를 양산 가능한 제품으로!

귀사의 제품을 만드세요. 교육과 개발 실적으로 신뢰할 수 있는 파트너를 확보하세요.

지난 30년 여정, 캐어랩이 얻은 모든 것을 함께 나누고 싶습니다.

카카오 채널 추가하기

카톡 채팅방에서 무엇이든 물어보세요

당신의 성공을 위해 캐어랩과 함께 하세요.

캐어랩 온라인 채널 바로가기

캐어랩