개발자

스마트 팩토리(Smart Factory) 센서 데이터 수집 전송 장치

지구빵집 2020. 9. 10. 10:11
반응형

 

스마트 팩토리 과제 사업으로 장비에 센서를 달아 동작 상태, 제품 생산 횟수, 온도와 습도, 진동센서, 광센서 등으로부터 데이터를 수집하여 클라우드 서버로 전송하는 장치를 개발할 예정입니다. 여기서는 가상으로 모든 센서와 데이터 처리가 완벽하게 동작하도록 예측하여 구성하려고 합니다. 말하자면 시뮬레이션?

 

이미 설치된 장비는 약간이라도 손을 대지 않고 작업합니다. 장비에서 나오는 신호, 예를 들면 소리, 진동, 이동하는 물체로부터 센싱 데이터를 뽑아내고 실내의 온도와 습도를 클라우드로 전송합니다. 서버단에서 데이터를 받는 부분은 구현하지 않고 여기서는 마이크로 프로세서 기능만 구현합니다.

 

그림으로 표현한 개념도는 아래와 같아요.

 

센서 데이터 수집 장치 개념도

 

 

Visio를 사용하여 그린 블록도를 첨부합니다. 구성품 상세 기능이나 전원 규격 부분, 센서 파트 넘버와 같은 상세 설명은 아직 적지 않았습니다. 나중에 구현하며 추가할 생각입니다.

 

센서 데이터 수집 장치 블럭도(Block Diagram)

 

온도 습도 센서 DHT11 혹은 DHT22 사용

 

사용할 마이크로 컨트롤러(MCU)는 Nano 33 IoT 보드를 사용하려고 한다. 무엇보다 WiFi가 지원되기 때문. 

온도, 습도 센서를 연결할 때는 아래와 같이 연결합니다.

 

  • DHT22 Pin 1 (power) ---> Nano Pin 3.3v
  • DHT22 Pin 2 (data) ---> Nano Pin D2
  • DHT22 Pin 3 (NC) ---> not connected
  • DHT22 Pin 4 (ground) ---> Nano GND

Nano 33 IoT는 3.3V를 안정적으로 지원합니다. Nano 33 IoT 보드의 'VUSB' 접점에 솔더 브리지를 생성하면 센서에 3.3V 이상을 출력할 수 있다고 나온다. DHT22 센서가 Nano의 5v 핀으로 전원이 공급되는 경우에도 'DHT_Sensor_Library' 라이브러리는 여전히 Nano 33 IoT에서 작동하지 않는 경우가 있어요. 라이브러리 'SimpleDHT22' (https://github.com/winlinvip/SimpleDHT)는 센서가 5v 핀으로 전원을 공급받을 때 아주 잘 동작한다고 하니 검증할 필요가 있어요. 

 

제 생각엔 5V를 직접 핀에 연결해 사용해도 상관없지 않을까 하는 데 다음을 참고하세요. 신중한 IO로 Nano 33을 테스트하지는 않았지만 기술 사양에 따르면 보드는 3.3V IO 만 지원하고 5V는 허용하지 않습니다. 3.3V를 5V로 작동하는 일부 주변 장치에 높은 신호로 밀어 넣는 것은 피할 수 있지만 해당 전압을 33으로 다시 보드에 입력으로 받으면 심각한 문제가 발생합니다. 보드가 튀겨지지 않도록 하려면 레벨 시프터를 사용하십시오. 저항기 설정 또는 3.3V 센서를 연결해야 합니다. 

 

참고 코드를 올려둡니다. 시험은 하지 않아서 확인하지 않았습니다. 참고용이고 출처는 How to use DHT11 and DHT22 Sensors with Arduino 입니다.

 

/* Arduino example code for DHT11, DHT22/AM2302 and DHT21/AM2301 temperature and humidity sensors. More info: www.makerguides.com */
// Include the libraries:
#include <Adafruit_Sensor.h>
#include <DHT.h>
// Set DHT pin:
#define DHTPIN 2
// Set DHT type, uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11 
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
// Initialize DHT sensor for normal 16mhz Arduino:
DHT dht = DHT(DHTPIN, DHTTYPE);
void setup() {
  // Begin serial communication at a baud rate of 9600:
  Serial.begin(9600);
  // Setup sensor:
  dht.begin();
}
void loop() {
  // Wait a few seconds between measurements:
  delay(2000);
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  // Read the humidity in %:
  float h = dht.readHumidity();
  // Read the temperature as Celsius:
  float t = dht.readTemperature();
  // Read the temperature as Fahrenheit:
  float f = dht.readTemperature(true);
  // Check if any reads failed and exit early (to try again):
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  // Compute heat index in Fahrenheit (default):
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius:
  float hic = dht.computeHeatIndex(t, h, false);
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" % ");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" \xC2\xB0");
  Serial.print("C | ");
  Serial.print(f);
  Serial.print(" \xC2\xB0");
  Serial.print("F ");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" \xC2\xB0");
  Serial.print("C | ");
  Serial.print(hif);
  Serial.print(" \xC2\xB0");
  Serial.println("F");
}

 

20*4줄 LCD를 연결해서 사용하려면 아래 코드를 참고한다. 주석에 소스코드 출처가 나와있다. 예제 코드가 잘 동작한다면 라이브러리로 사용한 LiquidCrystal_I2C 라이브러리에 유용한 함수들을 알아보면 되는데 다음 링크를 참고한다. Other useful functions of the LiquidCrystal_I2C library 

 

 

이미지 출처: https://www.makerguides.com/character-i2c-lcd-arduino-tutorial/

I2C 부품을 사용하려면 일단 스캔을 통해 부품의 주소를 찾아야 한다. 다음 코드는 I2C 스캐너 코드이다.

 

/*I2C_scanner
  This sketch tests standard 7-bit addresses.
  Devices with higher bit address might not be seen properly.*/
  
#include <Wire.h>
void setup() {
  Wire.begin();
  Serial.begin(9600);
  while (!Serial);
  Serial.println("\nI2C Scanner");
}
void loop() {
  byte error, address;
  int nDevices;
  Serial.println("Scanning...");
  nDevices = 0;
  for (address = 1; address < 127; address++ ) {
    Wire.beginTransmission(address);
    error = Wire.endTransmission();
    if (error == 0) {
      Serial.print("I2C device found at address 0x");
      if (address < 16)
        Serial.print("0");
      Serial.print(address, HEX);
      Serial.println("  !");
      nDevices++;
    }
    else if (error == 4) {
      Serial.print("Unknown error at address 0x");
      if (address < 16)
        Serial.print("0");
      Serial.println(address, HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");
  delay(5000);
}

 

20*4줄 캐릭터 LCD 샘플코드를 참고한다.

 

/*
  I2C LCD
  LCD 에 텍스트 출력하고 1초마다 백라이트를 ON/OFF 하는 예제
 
  출처: http://whiteat.com/Arduino
  
  부품
  . Arduino UNO R3 : http://kit128.com/goods/view?no=337
  . I2C LCD2004 : http://kit128.com/goods/view?no=171  
 
  연결
    Arduino UNO R3   I2C LCD2004
    -------------------------------------------------
    SCL				I2C SCL
    SDA				I2C SDA
 
*/  
 
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
 
// I2C LCD 기본 어드레스는 0x27
LiquidCrystal_I2C lcd(0x27);
 
// 프로그램 시작 - 초기화 작업
void setup()
{
	// 자동으로 I2C address 설정
	lcd = LiquidCrystal_I2C(GetAddress());
    lcd.begin (20,4);   // 20 x 4
}
 
// 계속 실행할 무한 루프
void loop()
{
	lcd.setBacklight(HIGH);
	lcd.setCursor(0, 0);
	lcd.print("HI____________! 20x4");
	lcd.setCursor(0, 1);
	lcd.print("Good Day******* 20x4");
	lcd.setCursor(0, 2);
	lcd.print("KIT128.com    ! 20x4");
	lcd.setCursor(0, 3);
	lcd.print("LCD I2C Module  20x4");
	delay(1000);
	lcd.setBacklight(LOW);
	delay(1000);
}
 
// I2C address 찾기
byte GetAddress()
{
	Wire.begin();
	for (byte i = 1; i < 120; i++)
	{
		Wire.beginTransmission(i);
		if (Wire.endTransmission() == 0)
		{
			Serial.print("Found address: ");
			Serial.print(i, DEC);
			Serial.print(" (0x");
			Serial.print(i, HEX);
			Serial.println(")");
			return i;
			delay(10);
		}
	}
}

 

적외선 거리측정센서(SHARP 2Y0A02) 

 

거리 측정 센서는 센서와 물체 사이에 거리를 측정하는 센서입니다. 측정하려는 물체로 적외선을 송신하고 물체에 반사되어 돌아오는 시간을 계산하고 이를 통해 거리를 알 수 있는 센서입니다. 적외선 거리 측정 센서는 수신부로 측정되는 적외선의 아날로그 세기를 측정하여 출력하기 때문에 VCC, GND, VOUT로 총 3개의 핀으로 구성되어 있습니다. 

 

적외선 거리측정센서(SHARP 2Y0A02) https://m.blog.naver.com/eduino/221146048122

 

거리 측정 센서는 적외선을 송신하는 발광부와 물체에 반사된 적외선이 수신되는 수광부로 구성되어 있습니다. 발광부는 적외선을 송신할 수 있는 다이오드 LED로 만들어져 있고 수광부는 트렌지스터로 만들어져 있습니다. 트랜지스터는 반도체로 전류가 흐를 수도 흐르지 못하게 할 수 도 있는 스위치 역할을 하는 소자입니다. 이 소자를 활용하여 거리를 측정할 수 있습니다. 적외선이 수광부에 수신되면 트랜지스터는 전류가 흐를 수 있게 됩니다. 이때 수신된 적외선의 양에 따라 흐르는 전류의 양도 달라지고 출력되는 전압이 다르게 보입니다.  

 

실습 코드는 아래 소스를 참고하세요. 코드 출처는 소스 상단에 있습니다. 

 

/* 소스코드 설명과 출처는 https://m.blog.naver.com/eduino/221146048122 */

int readPin0 = A0; // 적외선 센서 데이터 핀 선언
int i; // 모집군 순서
int num = 1; //모집군 수
int total = 0; //모집군 합
int average = 0; //모집군 평균

int LedPin1 = 7;  // 1번 LED의 핀 번호
int LedPin2 = 6;  // 2번 LED의 핀 번호
int LedPin3 = 5;  // 3번 LED의 핀 번호
int LedPin4 = 4;  // 4번 LED의 핀 번호
int LedPin5 = 3;  // 5번 LED의 핀 번호
int LedPin6 = 2;  // 6번 LED의 핀 번호

void setup() {
  
  pinMode(readPin0,INPUT); //핀 모드 설정
  pinMode(LedPin1,OUTPUT);
  pinMode(LedPin2,OUTPUT);
  pinMode(LedPin3,OUTPUT);
  pinMode(LedPin4,OUTPUT);
  pinMode(LedPin5,OUTPUT);
  pinMode(LedPin6,OUTPUT);
   digitalWrite( LedPin1, LOW);digitalWrite( LedPin2, LOW);digitalWrite( LedPin3, LOW); 
   digitalWrite( LedPin4, LOW);digitalWrite( LedPin5, LOW);digitalWrite( LedPin6, LOW);
  Serial.begin(9600); // 시리얼 포트 개방
}
void loop() {

   for(i = 0;i <= num;i++) // 센싱 횟수 
   {
    float v = analogRead(readPin0)*(5.0/1023.0); // 측정 전압 변환
    float di = 60.495*pow(v,-1.1904);  // 거리 계산
    total = total + di; 
  delay(10);
   }
  average = (int)total/num; // 평균
  if( i >= num){ // 초기화 
    i = 0;
    total = 0;
  }

 if(average < 35){  // average에 저장된 데이터값이 35미만 일때 동작 , 모든 LED소등
        digitalWrite( LedPin1, LOW);digitalWrite( LedPin2, LOW);digitalWrite( LedPin3, LOW);
            digitalWrite( LedPin4, LOW);digitalWrite( LedPin5, LOW);digitalWrite( LedPin6, LOW);
     delay(50);}
if( average >= 35 && average <40){  // average에 저장된 데이터값이 35 이상 40 미만 일때 동작 , 1번 LED점등 나머지 소등
      digitalWrite( LedPin1,HIGH);digitalWrite( LedPin2, LOW);digitalWrite( LedPin3, LOW);
      digitalWrite( LedPin4, LOW);digitalWrite( LedPin5, LOW);digitalWrite( LedPin6, LOW);
     delay(50);}
if( average >= 40 && average < 45){ // average에 저장된 데이터값이 40 이상 45 미만 일때 동작 , 1,2번 LED점등 나머지 소등
      digitalWrite( LedPin1,HIGH);digitalWrite( LedPin2,HIGH);digitalWrite( LedPin3, LOW);
      digitalWrite( LedPin4, LOW);digitalWrite( LedPin5, LOW);digitalWrite( LedPin6, LOW);
     delay(50);}
if( average >= 45 && average < 50){ // average에 저장된 데이터값이 45 이상 50 미만 일때 동작 , 1~3번 LED점등 나머지 소등 
      digitalWrite( LedPin1,HIGH);digitalWrite( LedPin2,HIGH);digitalWrite( LedPin3,HIGH);
      digitalWrite( LedPin4, LOW);digitalWrite( LedPin5, LOW);digitalWrite( LedPin6, LOW);
     delay(50);}
if( average >= 50 && average < 55){ // average에 저장된 데이터값이 50 이상 55 미만 일때 동작 , 1~4번 LED점등 나머지 소등
      digitalWrite( LedPin1,HIGH);digitalWrite( LedPin2,HIGH);digitalWrite( LedPin3,HIGH);
      digitalWrite( LedPin4,HIGH);digitalWrite( LedPin5, LOW);digitalWrite( LedPin6, LOW);
     delay(50);}
if( average >= 55 && average < 60){ // average에 저장된 데이터값이 55 이상 60 미만 일때 동작 , 1~5번 LED점등 나머지 소등
      digitalWrite( LedPin1,HIGH);digitalWrite( LedPin2,HIGH);digitalWrite( LedPin3,HIGH);
      digitalWrite( LedPin4,HIGH);digitalWrite( LedPin5,HIGH);digitalWrite( LedPin6, LOW);
     delay(50);}
if( average >= 60){ // average에 저장된 데이터값이 60 이상 일때 동작 , 전체 LED점등 점등
      digitalWrite( LedPin1,HIGH);digitalWrite( LedPin2,HIGH);digitalWrite( LedPin3,HIGH);
      digitalWrite( LedPin4,HIGH);digitalWrite( LedPin5,HIGH);digitalWrite( LedPin6,HIGH);
     delay(50);}

 Serial.print("range : ");Serial.println(average-20); // 적외선 값 출력, -20은 시리얼 모니터로 보이는 내용과 실제 자에 표시된는 내용이 같도록 수정
}

 

일단 여기까지 완성하고 놀러 나간다. 놀러 갈데도 없다. 사회적 거리두기가 일주일 더 강도 높게 실행하기로 했고, 태풍 마이삭이 올라오고 있다. 정신적으로 피폐해지는 나날이다. 내일은 청주로 가서 아버님 입원하신 병원에 들러야 한다. 사는 게 참 엉망이다.

 

스마트 팩토리(Smart Factory)란 공장 내 설비와 기계에 센서(IoT)가 설치되어 데이터가 실시간으로 수집, 분석되어 공장 내 모든 상황들이 일목요연하게 보이고(Observability), 이를 분석해 목적된 바에 따라 스스로 제어(Controllability)되는 공장을 말합니다. 

과거에는 숙련된 작업자가 원료의 색깔을 보고, 혹은 설비의 소리만 들어도 경험적으로 무엇이 문제인지 알고 손쉽게 문제를 해결했습니다. 하지만 고령화에 따라 숙련공들은 점점 줄어들어 문제가 발생할 때 제대로 대응하기가 점점 어려워지고 있는 실정이죠! 또한 제품의 라이프 사이클이 단축되고 있고, 맞춤형 대량생산으로 변화하면서 가볍고 유연한 생산 체계가 요구되고 있습니다. 이러한 상황에서 제조업 혁신을 위한 새로운 방안으로 부상하고 있는 것이 바로 “스마트 팩토리”입니다. 출처: https://smartfuture-poscoict.co.kr/306 [포스코ICT] 

 

 

 

 

 

반응형