본문 바로가기

개발자/Arduino

스마트 팩토리 연결도와 소스코드 20201018

반응형

 

가끔은 일도 하는 게 맞다. 아침 저녁으로 국화에 물을 주고, 달리기로 정해진 날에 비록 재미가 없더라도 달리고, 가을이 가득 차는 나무와 하늘과 바람을 아주 많이 쐬고 나서 그래도 시간이 남으면 일을 하기 바란다. 사람은 어떤 일이든 할 일을 가져야 한다. 그래야 잡념에 빠지지 않는다.

현재 되어 있는 곳까지 정리는 하고 간다. 며칠 내로 마무리해야 하기 때문이다. 아래는 연결도면이다. 거리센서와 사운드 센서는 코드에 없다. 회로 연결도는 그려야 하고, 여기서는 표로 나타내었다. 표를 참고한 곳은 'Introduction to the Nano 33 IoT' 에서 카피해 수정하였다.

 

Left side Board Image Right side
Extra function Analog Pin Number Digital pin number   Digital pin number Extra function
SCK D13


Drawing of Arduino Nano 33 IoT
D12~ SDO
3.3V D11~ SDI
ARef D10~ CS
DAC0 A0 D14 D9~
A1 D15 D8
A2 D16~ D7
A3 D17~ D6~
SDA, OLED SDA A4 D18 D5~
SCL, OLED SCL A5 D19~ D4
A6 D20 D3~
A7 D21 D2
Vusb GND
reset reset
GND D0 RX
Vin (21V max.) D1 TX

Nano 33 IoT pin functions.

 

헤더파일은 여러군데 옮기며 하다보니 공유기 WiFi 연결을 위해 적어둔다. 아래 코드는 WiFi 관련 프로그램에 항상 포함하는 헤더파일 arduino_secrets.h 파일이다.

 

//#define SECRET_SSID "PIS******"
//#define SECRET_PASS ""

//#define SECRET_SSID "PISnet_032AC8"
//#define SECRET_PASS "829******8"

//#define SECRET_SSID "SK_Wi******AA988"
//#define SECRET_PASS "180******356"


//#define SECRET_SSID "KT_G******_D652"
//#define SECRET_PASS "6ch******758"

#define SECRET_SSID "F******RCM"
#define SECRET_PASS "1******10350"

 

소스코드-그냥 평이한 코드를 수정해야 한다. data_logger.ino 파일이다.

 

/*
 * Arduino with LM35 analog temperature sensor and SSD1306 OLED display.
 * This is a free software with NO WARRANTY.
 * https://simple-circuit.com/
 */
 
#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
#include <SimpleDHT.h>


#include <SPI.h>
#include <WiFiNINA.h>
 
#define OLED_RESET  4    // define display reset pin
Adafruit_SSD1306 display(OLED_RESET);

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

#include "arduino_secrets.h" 
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;
//char server[]="www.google.com";  
char server[]="jarvis.wepnp.com";
//== IPAddress servernaeme(117,16,231,212);  

//WiFiClient client;
WiFiClient client;

const char* host = "jarvis.wepnp.com";  // --> "openapi.airkorea.or.kr"
const uint16_t port = 80;     // --> 80

void setup(void)
{
  initial_oled();
  
  pinMode(LED_BUILTIN, OUTPUT);
 
  Serial.begin(9600);
  /*while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }*/

  // attempt to connect to Wifi network:
  
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    //delay(10000);
    Serial.print(".");
  }
  Serial.println("Connected to wifi");
  printWifiStatus();
}

String url = "https://jarvis.wepnp.com/API/v2/kpi/data/insert";
String key = "YmVsbGFuZWxsYTplU21aNmJvMjFjVGt1dnA3bXM2ZFI0Snlabw==";

String Company_Name; //company name
String machine_type; //machine type code 01, 01, 03...
String machine_number; //machine number 1, 2, 3...

char buf_temp[5];
char buf_humi[5];
char buf_booloperation[5];
char buf_count[5];
String power;
String print_count;

void loop()
{
  to_oled_temphumidata();
  
  Serial.print("connecting to ");
  Serial.print(host);
  Serial.print(':');
  Serial.println(port);

  //Use WiFiClient class to create TCP connections
  WiFiClient client;
  
  if (!client.connect(host, port)) 
  {
    Serial.println("connection failed");
    delay(5000);
    return;
  }
  else
  {
    Serial.println("connect server!");  
  }

  digitalWrite(LED_BUILTIN, HIGH);

  if(client.connected()) //Check WiFi connection status
  {
     //POST data Set
    client.print("GET /API/v2/kpi/data/insert?data={%22machine%22:%22");
    client.print("printer-02");
    client.print("%22,%22temperature%22:");
    client.print(get_temp());
    client.print(",%22humidity%22:");
    client.print(get_humi());
    client.print(",%22power%22:");
    client.print(get_operation_state());
    client.print(",%22count%22:");
    client.print(get_operation_count());
    client.println("} HTTP/1.1");
    //root.printTo(client);
    //client.print(" HTTP/1.1");
    client.println("Host: jarvis.wepnp.com");
    client.println("Authorization: Basic YmVsbGFuZWxsYTplU21aNmJvMjFjVGt1dnA3bXM2ZFI0Snlabw==");
    //client.println("Content-Type: application/x-www-form-urlencoded");
    //client.println("Connection: close");
    client.println();

    // wait for data to be available
    unsigned long timeout = millis();
    while (client.available() == 0) {
      if (millis() - timeout > 5000) {
        Serial.println(">>> Client Timeout !");
        client.stop();
        delay(60000);
        return;
      }
    }

    // Read all the lines of the reply from server and print them to Serial
    Serial.println("receiving from remote server");
    // not testing 'client.connected()' since we do not need to send data here
    while (client.available()) {
      char ch = static_cast<char>(client.read());
      Serial.print(ch);
    }

    // Close the connection
    Serial.println();
    Serial.println("closing connection");
    client.stop();
    
    Serial.println("Complete");
   
  }

  digitalWrite(LED_BUILTIN, LOW);
  delay(20000);  //Send a request every 10 seconds
}


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 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
}
 

char _buffer[8];

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;
  }
}

boolean running = false;

boolean get_operation_state()
{
  running = !running;

  return running;
}

int operation_count=0;

int get_operation_count()
{
  
  operation_count++;

  return operation_count;
}



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(23, 50);
  //printf(_buffer, "On/Off");
  //display.print("On/Off");
  
  display.drawCircle(88, 12, 2, WHITE); 
  
  // update the display 
  display.display();
    
  // DHT11 sampling rate is 1HZ.
  delay(2000);
}

void to_oled_temphumidata_test()
{
  byte temperature = 0;
  byte humidity = 0;
  if (dht11.read(pinDHT11, &temperature, &humidity, NULL)) {
    Serial.print("Read DHT11 failed.");
    return;
  }
  
  Serial.print("Sample OK: ");
  Serial.print((int)temperature); Serial.print(" *C, "); 
  Serial.print((int)humidity); Serial.println(" %");
  
  // DHT11 sampling rate is 1HZ.
  delay(2000);
  
}

 
// end of code.

 

 

 

 

반응형

캐어랩 고객 지원

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

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

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

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

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

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

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

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

카카오 채널 추가하기

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

귀사가 성공하기까지의 긴 고난의 시간을 캐어랩과 함께 하세요.

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

캐어랩