아두이노에서 I2C 통신을 구현하기에 앞 서서 I2C 통신의 기본원리를 살펴 보면 아래와 같다.

 

□ 동기식 통신방식, I2C 개요

- 기존 1:1 통신방식인 시리얼(RS232C) 통신의 단점을 개선하여 Master/Slave 기반 1:N 통신이 가능하도록 고안된
  프로토콜

- Philips에서 개발

 

 

 

 

 

 

□ RS232C 대비 I2C 통신 특성

I2C 통신 방식은 RS232C의 단점을 개선한 것으로 두 방식의 특성을 비교하면 아래와 같다. 

 

 I2C

 RS232C 

 통신 방식

 1:N

 1:1

 통신 구조

 - SCL(클록), SDA(데이터) 이용 

 - RX, TX 이용  

 타이밍 처리

 - 클록신호를 이용한 동기식 통신

 - 유연한 타이밍 관리가 가능 

 - 보레이트(전송속도) 엄수 필요 

 

□ I2C통신 구성 시 주의 사항

I2C 통신은 오픈 컬렉터 구성이므로 구성 시 반드시 풀업 저항이 필요하다.

 

 

 

 

 

□ 아두이노 I2C통신

 

 

 

반응형

 

 

 

 

 

 

 MPU6050

 0x68 

 

 

 BMP180

 0x77

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형

'아두이노 > 센서' 카테고리의 다른 글

스위치 : 푸시형 NON-LOCK DJP2213  (0) 2014.11.26
HC-SR04 : 초음파 거리측정 센서  (0) 2014.11.24
801s : 진동센서  (0) 2014.11.20
BMP180 : 고도센서, 기압센서, 온도센서  (0) 2014.11.20
복합 센서  (0) 2014.11.19

 

 

 

 

 

 

 

 

 

GENERAL SPECIFICATIONS 
Size: 41 * 15 * 12.5mm
 
The main chip: LM393, vibrating probe
 
Operating Voltage: DC 3-5V
 
Main features:
 
1, having a signal output instruction;
2, with a TTL level signal, and the analog output signal;
3, the output valid signal is high, the light goes out;
4, the sensitivity is adjustable (fine-tuning);
5, wide detection range of vibration, no direction;
6, with mounting holes, firmware installation flexible and convenient.
Applications: can be used in anti-theft devices, electronic locks, mechanical equipment vibration detection, detection range bull's-eye counts vibration testing occasions;

 

 

CIRCUIT:SPST
CURRENT RATING:12mA
VOLTAGE RATING:24VDC
CONTACT RESISTANCE:50mΩ Max.(inital)
INSULATION RESISTANCE:100MΩ Min
OPERATING FORCE:170gf±50g
TOTAL TRAVEL:2.8mm±0.4mm a , long : measurement 10mm x wide 30mm x high 20mm
2 , main chip : lm393 , vibration probe
 three , working voltage : dc 3-5v
 four , features :
1 , possesses the signal output indication
2 , with analogue and ttl level signal output signal output
3 , output signal for high effective dbm0 , indicator lamp quellers .
4 , sensitivity adjustable ( adjusting ) .
5 , vibration wide range detection , directionality none .
6 , belt mounting hole , firmware flexible and convenient installation .
OPERATING LIFE:50,000 CYCLES Min
SOLDER SPECIFICATIONS:256°C for 3 seconds
FUNCTION:Momentary
OPERATING TEMPERATURE:+10°C ~ +60°C
 

 

 

 

 

801s 진동센서 001 specification.pdf

 

 

 

 

 

반응형

'아두이노 > 센서' 카테고리의 다른 글

HC-SR04 : 초음파 거리측정 센서  (0) 2014.11.24
I2C Address  (0) 2014.11.21
BMP180 : 고도센서, 기압센서, 온도센서  (0) 2014.11.20
복합 센서  (0) 2014.11.19
GP2Y1010AU0F : 먼지 센서  (0) 2014.11.18

BMP180은 BMP085의 상위모델로 기압센서입니다. 기압 측정값을 이용해서 고도로 변환이 가능합니다.

 

□ BMP180 

 4 pin

 5 pin 

 

 

 

BMP180 특징(Specification) 

항목

범위

 분해능력

 오차

 압력 (Pressure range)

 300 ~ 1100 hPa

 0.01 hPa 

 ± 0.02 hPa ( 약 0.17 m 고도 오차 )

 온도

 -40 ~ 85 도(C)

 0.1 도  

 

□ BMP180 아두이노 회로 구성도( BMP180 Arduino circuit diagram )



 

□ BMP180 와 아두이노 Pin 배열( BMP180 Arduino PIN Mapping )

BMP180 4 pin

BMP180 5 pin

 비고(Remark)

Pin 배열

 Arduino

Pin 배열

 Arduino

 SCL

 A5(SCL)

 SDA

 A4(SDA)

 

 SDA

 A4(SDA)

 SCL

 A5(SCL)

 

 VIN

 +5V  GND  GND  

 GND

 GND

 VDD

 +3.3V (Only)

 

   

 VDDIO

 N/A

 I/O voltage

※ VDD    : 5 pin의 경우 3.3V 연결 

    VDDIO : 특수 저전력 microprocessor용으로, 아두이노의 경우 별도 연결 필요없음

  ( VDD    : Connect the power pins (+ and -) ONLY to a 3.3V supply.

    VDDIO : Leave disconnected unless you're connecting to a lower-voltage microprocessor )

 

BMP180 통신 프로토콜

 

 

BMP180 Sample Source 

  - 기본 라이브러리(Basic Library)

    

 


  - Sample 1

#include <Wire.h>

#include <Adafruit_BMP085.h>


void setup() {

  Serial.begin(9600);

  BMP180init();

}

  

void loop() {

 BMP180exec();

 delay(1000); 

}


Adafruit_BMP085 bmp;

void BMP180init() {

    if (!bmp.begin(BMP085_ULTRAHIGHRES)) {

        Serial.println("BMP180 센서를 찾을 수 없습니다. 연결을 확인해 주세요!");

    }

}

  

void BMP180exec() {

    float Ftemperature = 0.0;    // 온도 측정 값

    float Fpressure    = 0.0;    // 기압 측정 값

    float Faltitude    = 0.0;    // 고도 측정 값

    

    Ftemperature =  bmp.readTemperature();

    Fpressure    =  bmp.readPressure();

    Faltitude    =  bmp.readAltitude( 100560 );     // 101560 : 서울 해면기압, 101325 : 표준기압



    char CAtemperature [20] = ""; 

    char CApressure    [20] = ""; 

    char CAaltitude    [20] = ""; 

    char CAbuffer      [254] = "";

    dtostrf( Ftemperature, 10, 2, CAtemperature );

    dtostrf( Fpressure   , 10, 2, CApressure    );

    dtostrf( Faltitude   , 10, 2, CAaltitude    );

    

    // 온도 압력 고도

    sprintf( CAbuffer, "Temp(C): %s\tPres(PA): %s\tAlt(M): %s", CAtemperature, CApressure, CAaltitude );

    Serial.println( CAbuffer );


    // TEST

    //Serial.print( "temp(C): "    ); Serial.print  ( Ftemperature );

    //Serial.print( "\tpres(Pa): " ); Serial.print  ( Fpressure    );

    //Serial.print( "\talti(M) : " ); Serial.println( Faltitude    );

}

 



  - Sample 2

 

#include <Wire.h>
#include <Adafruit_BMP085.h>


void setup() {
  Serial.begin(9600);
  BMP180init();
}
 
void loop() {
 BMP180exec();
 delay(1000);
}


Adafruit_BMP085 bmp;

void BMP180init() {
 if (!bmp.begin(BMP085_ULTRAHIGHRES)) {
  Serial.println("BMP180 센서를 찾을 수 없습니다. 연결을 확인해 주세요!");
 }
}
 
void BMP180exec() {
 float temperature = 0.0;  // 온도 측정 값들
 float pressure    = 0.0;     // 기압 측정 값들
 float altitude    = 0.0;     // 고도 측정 값들

    temperature =  bmp.readTemperature();
    pressure    =  bmp.readPressure();
    altitude =  bmp.readAltitude(101340);
 
    Serial.print("temperature(℃): "); Serial.print(temperature);
    Serial.print("\tpressure(Pa): "); Serial.print(pressure);
    Serial.print("\taltitude(M): ");  Serial.print(altitude);

    /*
     * 고도 계산을 표준 기압 1013.25 millibar를 사용하여 계산합니다.
     * 1013.25 mbar = 101325 Pa(Pascal)입니다.
     */
    Serial.print("\tbase altitude(M): ");   Serial.print(bmp.readAltitude());
    Serial.print("\tSea Level(Pa - X): "); Serial.print(bmp.readSealevelPressure());
    Serial.println( " " );
 
/*
 * 기상청 지역별상세관측자료(AWS)에 들어가면 해면 기압 정보를 얻을 수
 * 있습니다. 이 mbar(millibar)값에 100을 곱하면 Pa(Pascal) 값을 얻을
 * 수 있습니다.
 *
 * 1 hPa =  100 Pa =  1 mbar
 * 1 kPa = 1000 Pa = 10 mbar
 *
 * http://www.kma.go.kr/weather/observation/aws_table_popup.jsp
 *
 * 2014/09/11/22:21 - 1013.4 mbar
 *
 */

 

 

  - Sample 3 

 

/***************************************************
  This is an example for the BMP085 Barometric Pressure & Temp Sensor
 
  Designed specifically to work with the Adafruit BMP085 Breakout
  ----> https://www.adafruit.com/products/391
 
  These displays use I2C to communicate, 2 pins are required to 
  interface
  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!
 
  Written by Limor Fried/Ladyada for Adafruit Industries. 
  BSD license, all text above must be included in any redistribution
 ****************************************************/
 
#include <Wire.h>
#include <Adafruit_BMP085.h>
 
const int CIrowSize = 20;

int index = 0;                    // 현재 센서값을 넣어야 할 인덱스
float temperatures[CIrowSize];  // 온도 측정 값들
float pressures[CIrowSize];     // 기압 측정 값들
float altitudes[CIrowSize];     // 고도 측정 값들
float totalTemperature = 0.0;     // 온도 총합
float totalPressure = 0.0;        // 기압 총합
float totalAltitude = 0.0;        // 고도 총합
 
/*
 * mode :
 *        BMP085_ULTRALOWPOWER 0
 *        BMP085_STANDARD      1
 *        BMP085_HIGHRES       2
 *        BMP085_ULTRAHIGHRES  3
 *
 */
void setup() {
  Serial.begin(9600);
  BMP180init();
}
 
void loop() {
 BMP180exec();
 delay(1000); 
}


Adafruit_BMP085 bmp;

void BMP180init() {
 if (!bmp.begin(BMP085_ULTRAHIGHRES)) {
  Serial.println("BMP180 센서를 찾을 수 없습니다. 연결을 확인해 주세요!");
 }
 
 for(int i = 0; i < CIrowSize; i++) {
  temperatures[i] = 0.0;
  pressures[i] = 0.0;
 }
}
 
void BMP180exec() {
 

    totalTemperature    =  totalTemperature - temperatures[index];
    temperatures[index] =  bmp.readTemperature();
    totalTemperature    += temperatures[index];
  
    totalPressure   =  totalPressure - pressures[index];
    pressures[index]  =  bmp.readPressure();
    totalPressure   += pressures[index];


    totalAltitude   =  totalAltitude - altitudes[index];
    altitudes[index]  =  bmp.readAltitude(101340);
    totalAltitude   += altitudes[index];

 
    Serial.print("측정 온도(℃): "); Serial.print(totalTemperature / CIrowSize);
    Serial.print("측정 압력(Pa): "); Serial.print(totalPressure / CIrowSize);
    Serial.print("측정 고도(M): ");  Serial.print(totalAltitude / CIrowSize);

    /*
     * 고도 계산을 표준 기압 1013.25 millibar를 사용하여 계산합니다.
     * 1013.25 mbar = 101325 Pa(Pascal)입니다.
     */
    Serial.print("표준 고도(M): ");  Serial.print(bmp.readAltitude());
    Serial.print("해면 기압(Pa - X): ");  Serial.print(bmp.readSealevelPressure());
    Serial.println( " " );
 
/*
 * 기상청 지역별상세관측자료(AWS)에 들어가면 해면 기압 정보를 얻을 수
 * 있습니다. 이 mbar(millibar)값에 100을 곱하면 Pa(Pascal) 값을 얻을
 * 수 있습니다.
 *
 * 1 hPa =  100 Pa =  1 mbar
 * 1 kPa = 1000 Pa = 10 mbar
 *
 * http://www.kma.go.kr/weather/observation/aws_table_popup.jsp
 *
 * 2014/09/11/22:21 - 1013.4 mbar
 *
 */

 
 
    ++index;
   
  // 만약 배열의 끝에 있다면...
  if (index >= CIrowSize)             
    // ...배열의 처음으로 돌아가게 합니다:
    index = 0;
     

}

 


 

반응형

'아두이노 > 센서' 카테고리의 다른 글

I2C Address  (0) 2014.11.21
801s : 진동센서  (0) 2014.11.20
복합 센서  (0) 2014.11.19
GP2Y1010AU0F : 먼지 센서  (0) 2014.11.18
Piezo Disk Sensor  (0) 2014.11.18

 

 

 구분

센서유형

센서 

단가

구입가

 

 

 센서

 진동센서

 801s

10,980

13,480 

 

 

 

 DC 컨트롤러

 

3,500 

20,000 

 

 

 센서 

 진동

피에조 

6,600 

 

 

 

 센서

 먼지센서

 

15,400

 

 

 

 소모품

 리드전선

 

1,500 

9,000 

 

 

 

 충전기

 

45,000 

47,500 

 

 

 센서

온습도센서

DHT22 AM2302 

13,000 

 

 

 

 소모품

 PCB 5*7

 

1,900 

5,100 

 

 

 소모품

 PCB 7*9

 

2,500 

7,500 

 

 

 센서 마이크로폰   5,200       
 

WiFi

  14,900       
 센서

자이로

MPU6050  

       

 센서

고도센서

BPM180  

       

 센서 

 고도센서 BPM180   4,000 14,500     

 센서

 복합센서  MPU6050 HMC5883 BMP180  4,000 14,500     
             
             
             

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형

'아두이노 > 센서' 카테고리의 다른 글

801s : 진동센서  (0) 2014.11.20
BMP180 : 고도센서, 기압센서, 온도센서  (0) 2014.11.20
GP2Y1010AU0F : 먼지 센서  (0) 2014.11.18
Piezo Disk Sensor  (0) 2014.11.18
DHT22-AM2302 : 디지털 온습도 센서  (0) 2014.11.17

 

□ GP2Y1010AU0F : 먼지 센서 

 

 

 

 

□ GP2Y1010AU0F 특징(Specification)

 항목

 내용

 비고(Remark)

 공급전원(Supply Voltage)

 5 ~ 7 V

 Vcc 

 동작온도(Operating Temperature)

 -10 ~ 56 도(Celsius)

 

 납땜허용온도(Soldering Temperature)

 -20 ~ 80 도(Celsius)

 

 전류소모(Comsumption current)

 MAX 20 mA

 

 터미널전원(Input Terminal Voltage)

 -0.3 to Vcc

 V-Led

 

 

□ GP2Y1010AU0F와 아두이노 핀 배열(Arduino pin map)

 

 

* 1번 ~ 3번은 LED 신호와 관계된 것으로 LED확인이 필요하지 않을 경우 연결 필요 없음

 

 

 

□ GP2Y1010AU0F 핀 구성도(Pin Design) 

 핀 구성도

 (Pin Design)

 

 

 설명

 (Detail)

GP2Y1010AU0F 

 Arduino

 비고(Remark)

 ① V-Led

5V (150ohm resistor) 

 LED 신호용

 ② LED-GND

 GND

 ③ LED

 Digital pin 2

 ④ S-GND

 GND

 Data 출력용

 ⑤ Vo

 Analog pin 0

 ⑥ Vcc

 5V

* V-Led, LED-GND, LED(1번~3번)는 LED 신호와 관계된 것으로 LED확인이 필요하지 않을 경우 연결 필요 없음

 

 

□ GP2Y1010AU0F 샘플(Sample Source) 

 

/*
 Standalone Sketch to use with a Arduino UNO and a
 Sharp Optical Dust Sensor GP2Y1010AU0F
*/
  
int measurePin = 0; //Connect dust sensor to Arduino A0 pin
int ledPower = 2;   //Connect 3 led driver pins of dust sensor to Arduino D2
  
int samplingTime = 280;
int deltaTime = 40;
int sleepTime = 9680;
  
float voMeasured = 0;
float calcVoltage = 0;
float dustDensity = 0;
  
void setup(){
  Serial.begin(9600);
  pinMode(ledPower,OUTPUT);
}
  
void loop(){
  digitalWrite(ledPower,LOW); // power on the LED
  delayMicroseconds(samplingTime);
  
  voMeasured = analogRead(measurePin); // read the dust value
  
  delayMicroseconds(deltaTime);
  digitalWrite(ledPower,HIGH); // turn the LED off
  delayMicroseconds(sleepTime);
  
  // 0 - 5V mapped to 0 - 1023 integer values
  // recover voltage
  calcVoltage = voMeasured * (5.0 / 1024.0);
  
  // linear eqaution taken from http://www.howmuchsnow.com/arduino/airquality/
  // Chris Nafis (c) 2012
  dustDensity = 0.17 * calcVoltage - 0.1;
  
  Serial.print("Raw Signal Value (0-1023): ");
  Serial.print(voMeasured);
  
  Serial.print(" - Voltage: ");
  Serial.print(calcVoltage);
  
  Serial.print(" - Dust Density: ");
  Serial.println(dustDensity); // unit: mg/m3
  
  delay(1000);
}

 

 

□ GP2Y1010AU0F 참고자료

 - Datasheet         먼지센서 001 gp2y1010au_e.pdf

 

 

 

반응형

'아두이노 > 센서' 카테고리의 다른 글

BMP180 : 고도센서, 기압센서, 온도센서  (0) 2014.11.20
복합 센서  (0) 2014.11.19
Piezo Disk Sensor  (0) 2014.11.18
DHT22-AM2302 : 디지털 온습도 센서  (0) 2014.11.17
사운드 감지 센서  (0) 2014.11.17

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Specification

  • Power supply:5V
  • Interface:Analog

 

 

//Arduino Sample code
void setup()
{
  Serial.begin(9600); //
}

void loop()
{
      int val;
      val=analogRead(0);//Connect the sensor to analog pin 0
      Serial.println(val,DEC);//
      delay(100);
}

 

 

 

 

반응형

'아두이노 > 센서' 카테고리의 다른 글

복합 센서  (0) 2014.11.19
GP2Y1010AU0F : 먼지 센서  (0) 2014.11.18
DHT22-AM2302 : 디지털 온습도 센서  (0) 2014.11.17
사운드 감지 센서  (0) 2014.11.17
MPU-6050 : 6축 센서 ( 가속도, 자이로 )  (0) 2014.11.12

 

□ 실물사진


□ 센서 특징

 특징

 내용

 모델

 DHT22 / AM2302

 정밀도

 0.1

 습도 측정 범위

 0 ~ 100% RH ( +- 2% RH)

 온도 측정 범위

 섭씨 -40 ~ 80 도 ( +- 0.5 도 )

 기타

 저전력, 부가회로 불필요

 사용 전압

 3.3 ~ 5V DC 

 응답시간

 2s 

 

□ 회로구성도



□ 연결방법

DHT PIN1 → Arduino 5V

DHT PIN2 → 10K Resistor Arduino 5V (Full up Resistance)
DHT PIN2 → Arduino Digital Pin 2
DHT PIN3 → Not Used
DHT PIN4 → Arduino GND

 

□ 구현 시 주의사항

마이크로 컨트롤러의 I/O 포트와 DHT22 온습도 센서의 출력과 연결하여 풀업저항을 하나 설치

1. 센서와의 길이는 가급적 짧게 하여 전압강하로 인한 오류  예방

2. 센서로 부터 데이터 리딩 시에는 최소 5초 간격 필요

 

□ 전송 데이터 포맷

습도 정수 데이터( 8bit ) + 습도 소수점 데이터( 8bit ) + 온도 정수 데이터( 8bit ) + 온도 소수점 데이터( 8bit )
+ 패리티 비트( 8bit )


□ Sample


#include <DHT22.h> 

// Only used for sprintf 

#include <stdio.h>


// Data wire is plugged into port 7 on the Arduino 

// Connect a 4.7K resistor between VCC and the data pin (strong pullup) 

#define DHT22_PIN 7


// Setup a DHT22 instance 

DHT22 myDHT22(DHT22_PIN); 

 

void setup(void) { 

    // start serial port 

    Serial.begin(9600); 

    Serial.println("DHT22 Library Demo"); 

 

void loop(void) {  

    DHT22_ERROR_t errorCode; 

    

    // The sensor can only be read from every 1-2s, and requires a minimum 

    // 2s warm-up after power-on. 

    delay(2000); 

    

    Serial.print("Requesting data..."); 

    errorCode = myDHT22.readData(); 

    switch(errorCode) { 

        case DHT_ERROR_NONE: 

            Serial.print("Got Data "); 

            Serial.print(myDHT22.getTemperatureC()); 

            Serial.print("C "); 

            Serial.print(myDHT22.getHumidity()); 

            Serial.println("%"); 

            // Alternately, with integer formatting which is clumsier but more compact to store and 

            // can be compared reliably for equality: 


            char buf[128]; 

            sprintf(buf, "Integer-only reading: Temperature %hi.%01hi C, Humidity %i.%01i %% RH", 

                         myDHT22.getTemperatureCInt()/10, abs(myDHT22.getTemperatureCInt()%10), 

                         myDHT22.getHumidityInt()/10, myDHT22.getHumidityInt()%10); 

            Serial.println(buf); 

            break; 

        case DHT_ERROR_CHECKSUM: 

            Serial.print("check sum error "); 

            Serial.print(myDHT22.getTemperatureC()); 

            Serial.print("C "); 

            Serial.print(myDHT22.getHumidity()); 

            Serial.println("%"); 

            break; 

        case DHT_BUS_HUNG: 

            Serial.println("BUS Hung "); 

            break; 

        case DHT_ERROR_NOT_PRESENT: 

            Serial.println("Not Present "); 

            break; 

        case DHT_ERROR_ACK_TOO_LONG: 

            Serial.println("ACK time out "); 

            break; 

        case DHT_ERROR_SYNC_TIMEOUT: 

            Serial.println("Sync Timeout "); 

            break; 

        case DHT_ERROR_DATA_TIMEOUT: 

            Serial.println("Data Timeout "); 

            break; 

        case DHT_ERROR_TOOQUICK: 

            Serial.println("Polled to quick "); 

            break; 

    } 

}


□ 라이브러리 파일 

Arduino-DHT22-master.zip

 

  

반응형

'아두이노 > 센서' 카테고리의 다른 글

복합 센서  (0) 2014.11.19
GP2Y1010AU0F : 먼지 센서  (0) 2014.11.18
Piezo Disk Sensor  (0) 2014.11.18
사운드 감지 센서  (0) 2014.11.17
MPU-6050 : 6축 센서 ( 가속도, 자이로 )  (0) 2014.11.12

 

 

 

 

- 기본 정보


 * 고감도 사운드 감지 센서
 * 아날로그(AO)와 디지털(DO) 신호 모두 검출 가능

 


 

- 핀 연결 

 센서

 아두이노핀

 D0

 D2

VCC

 5V

 GND

 GND

 A0

 A0

 

핀 연결 (3PIN)

 센서

 아두이노핀

 D0

 D2

VCC

 5V

 GND

 GND

 

 

1) 센서의 그라운드 – 5k옴 – 아두이노 그라운드
2) 센서의 signal output – 아두이노아날로그0번핀 – 2k옴 – 아두이노그라운드(2번은 있으니 1번만)

   내 경우 2K옴으로 실험함

몇옴을 달아야 하는지는 정확하지 않으니까 10k 가변저항 두개를 달고 조절해보면서 해보삼..

 

 

- Arduino 소스 코드 (센서 핀 A0 사용)

 

const int S = 0;
const int ledPin = 13;
int sensorstate = 0;

 

void setup() {

  pinMode(ledPin, OUTPUT);
  pinMode(S, INPUT);

  Serial.begin(9600);

void loop() {
  sensorstate = analogRead(S);

  Serial.println( sensorstate, DEC);
  if (sensorstate > 50) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
  delay(500);
}

 

 

 

 

 

- Arduino 소스 코드 (센서 핀 D2 사용)

 

const int S = 2;
const int ledPin = 13;
int sensorstate = 0;


void setup() {

  pinMode(ledPin, OUTPUT);
  pinMode(S, INPUT);
}

 

void loop() {
  sensorstate = digitalRead(S);
  if (sensorstate == HIGH) {
    digitalWrite(ledPin, HIGH);
  } else {

    digitalWrite(ledPin, LOW);
  }
}

 

 

 

[참조 사이트]

 

1. 아두이노 + 사운드 센서 : http://blog.naver.com/PostView.nhn?blogId=knexkorea&jumpingVid=E4998EC56EA103ED9EB6AB971E9D64454F30&logNo=184782761


2. 아날로그 사운드 센서로 LED 밝기 제어 : http://makewhatever.wordpress.com/2013/03/06/%EC%95%84%EB%82%A0%EB%A1%9C%EA%B7%B8-%EC%82%AC%EC%9A%B4%EB%93%9C-%EC%84%BC%EC%84%9C%EB%A1%9C-led-%EB%B0%9D%EA%B8%B0-%EC%A0%9C%EC%96%B4/

 

http://kocoafab.cc/view/tutorials/77

 

 

http://seeedstudio.com/wiki/index.php?title=Twig_-_Sound_Sensor#Introduction

반응형

'아두이노 > 센서' 카테고리의 다른 글

복합 센서  (0) 2014.11.19
GP2Y1010AU0F : 먼지 센서  (0) 2014.11.18
Piezo Disk Sensor  (0) 2014.11.18
DHT22-AM2302 : 디지털 온습도 센서  (0) 2014.11.17
MPU-6050 : 6축 센서 ( 가속도, 자이로 )  (0) 2014.11.12

 

□ 사용자 라이브러리 구성 방법

스케치 파일(ino)에 소스를 작성하는 것은 비효율적인 경우가 많다.

한 예로, ino 파일을 다른 Editor (Visual Studio, eclipse 등 )에서 사용하는데 확장자로 인해서 번거롭고 별도 헤더파일 정의도 없어 라이브러리로 사용이 불편하거나 하는 등 여러 단점이 존재한다.

특히, 복잡한 프로그램을 개발하는 경우 다양한 사용자 라이브러리들을 별도의 파일로 만들어 사용하는 것은 불가결하다.

 

이런 이유로, 복잡한 프로그램은 두말할 것도 없고 단순 기능도 스케치 파일(ino)와 사용자 라이브러리(별도 소스파일)을 분리해서 개발하는 것은 좋은 방법이다.

아두이노에서 사용자 라이브러리를 사용하는 것은 간단하며 아래와 같은 형태로 쉽게 구성이 가능하다.

 

그림) 아두이노 사용자 라이브러리 구성도 

 

  Sample.ino

 프로그램 Sample에 대한 스케치

  Sample.h

 Sample.cpp 소스에 대한 헤더파일

  Sample.cpp

 실제 기능/클래스를 이용한 실행 소스 

- 실제 소스는 Sample.h와 Sample.cpp에서 작성하여 재사용성을 높이고 ino 파일은 스케치 역할과 프로그램 설명,
   저작권 설명 등 부수적인 역할만 수행

 

 

사용자 라이브러리를 위한 별도 소스파일에서 가장 먼저 지정해야하는 것은 #include “Arduino.h” 구문을 사용하는 것이다.

#include "Arduino.h"    

- 아두이노 표준 타입, 사전 정의된 상수, 함수들에 대한 헤더파일

- 아두이노 표준 제공 기능을 사용할 수 있도록 해준다.

 

해당 파일은 일반 스케치(ino 파일)에서는 암묵적으로 자동 추가되지만, 사용자 라이브러리 파일에서는 자동 추가되지 않아서 직접 지정해 주어야 한다.

주의해야할 사항으로는스케치 파일에서는 Arduino.h와 IDE에서 "새탭"으로 정의한 소스 및 헤더파일 들만 자동 추가된다.

따라서, 소스 내에서 Serial 클래스와 같은 #include <Wire.h> 등을 사용할 때나 다른 라이브러리 등을 사용할 경우에는 스케치 파일에도 반드시 명시적으로 기재해 주어야 한다.

또한, 사용되는 라이브러리들의 구성관계를 파악하기에 용이하므로 새탭 메뉴를 통해 정의된 사용자 라이브러리의 헤더파일도 명시적으로 선언(#include로 기재)해 주는 것이 좋다.

 

 Sample.ino

 

Sample.h 

 

 Sample.cpp

 

 // 프로그램 개요

 // 저작권 : ... ...

 // ... ...

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 // 전처리 상수 선언

 #define PORT_NO 12

 #define TIME        1000

            ... ...

 

 // 함수 or 클래스 선언

 void userfunction1();

 void userfunction2();

            ... ...

 

 

 

 

 

 

 

 

 

 // 필수 추가

 #include "Arduino.h"

 #include "Sample.h"

            ... ...

 

 void setup() {

            ... ...

 }

 

 void loop() {

            ... ...

 }

 

 void userfunction1() {

            ... ...

 }

 

 - 주석을 이용해서 프로그램

    설명, 저작권 표기 등 가능

 

 - 헤더 파일

 - 상수선언, 함수, 클래스 선언

 

 

 - 실제 소스 구성 부문

 - 사용자 라이브러리

 

 

 

□ 예제를 통한 확인

아래 예제는 아두이노 IDE에서 제공되는 Basic 예제인 Blink를 이용한 사용자 라이브러리 사용방법이다.

충분한 확인을 위해  고의로 기존 Blink.ino 단일 파일을 복잡한 여러 파일로 분리했다.

 

 그림) Blink.ino 의 분리 

- 단일 스케치 파일을 여러  라이브러리로 구성하여 사용성을 높임

 

 

1) 원본 소스 Blink.ino 확인

   - "파일 메뉴 - 예제"를 통해서 Blink.ino를 불러 온다.

 

 

2) Test.ino 생성 

   - Blink.ino를 다른이름으로 저장하여 Test.ino를 생성한다.

   - 저장한 후 Test.ino의 내용은 맨 마지막에 삭제해도 되고 이 단계에서 삭제해도 된다.

   - 해당 예제에서는 맨 마지막에 삭제하는 것으로 설정했다.

 

 

3) 새탭 메뉴를 이용, 신규  파일 생성 

  - 스케치를 통한 파일의 연결은 새탭을 통해서 가능하다.

 

 

4) 신규 파일명 부여 후 저장 

  - 하단 입력창을 통해서 이름부여 후 저장한다.

 

 

5) 반복해서 필요한 파일 전체 생성 

  - 예제를 통해 확인해 필요한 모든 파일을 생성한다.

  - Test.h, Test.cpp, Blink.h, Blink.cpp

 

 

6) blink.ino에서 원본 소스 복사

아두이노 IDE에서 제공되는 Basic 예제 "Blink" 소스 - blink.ino에서 복사해서 수정을 시작한다.

편의 상 복사한 것으로 내용을 수기 입력해도 당연히 된다.

}
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

 

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                // wait for a second
  digitalWrite(13, LOW);   // turn the LED off by making the voltage LOW
  delay(1000);                // wait for a second

 

7) 원본 소스에서 Blink.h, Blink.cpp 구성

  - 테스트를 위해 Blink 소스를 아래와 같이 수정해서 Blink.cpp로 저장한다.

  - 해당 작업으로 좀 더 유연하게 사용가능한 blinkInit, LEDon, LEDoff 함수를 만들 수 있다.

void setup() {
  pinMode(13, OUTPUT);

void blinkInit() {
  pinMode(13, OUTPUT);
}

 

 

void loop() {
  digitalWrite(13, HIGH);   
  delay(1000);            

    
  digitalWrite(13, LOW);   
  delay(1000);               
}

 

 

 

 

 

void LEDon() {
  digitalWrite(13, HIGH);   
}

 

void LEDoff {

  digitalWrite(13, LOW);   
}

 

  - Blink.h와 Blink.cpp의 최종소스는 아래와 같다.

Blink.h

 Blink.cpp

void blinkInit();
void LEDon();
void LEDoff();

 

 

 

 

 

 

 

 

 

#include "Arduino.h"
#include "Blink.h"
 
void blinkInit() {
  pinMode(13, OUTPUT);
}

void LEDon() {
  digitalWrite(13, HIGH); 
}

 

void LEDoff() {
  digitalWrite(13, LOW);  
}

 

8) 원본소스에서 Test.h, Test.cpp 구성

  - 원소스인 Blink.ino에서 아래와 수정해서 메인 프로세스에 해당하는 Test.cpp도 생성한다. 

  - test.cpp는 Main 프로세스(C의 Main함수)에 해당하는 것으로 아래처럼 보다 직관적으로 구성이 가능해졌다.

void setup() {
  pinMode(13, OUTPUT);

void setup() {
  blinkInit(); 
}

 

void loop() {
  digitalWrite(13, HIGH);   
  delay(1000);            

    
  digitalWrite(13, LOW);   
  delay(1000);               
}

 

 

 

 

 

void loop() {
  LEDon();
  delay(1000);              

 

  LEDoff();
  delay(1000);             
}

 

  - Test.h와 Test.cpp의 최종소스는 아래와 같다.

Test.h

 Test.cpp

// Test.cpp에 사용자 함수가 없으므로

// Test.h에는 아무 것도 선언할 내용이 없다.

 

 

 

 

 

 

 

 

 

  

 

 

#include "Arduino.h"
#include "Test.h"
#include "Blink.h"

 

void setup() {
  blinkInit(); 
}

 

void loop() {
  LEDon();
  delay(1000); 


  LEDoff();
  delay(1000); 
}

 

10) 분리 완료(사용자 라이브러리 생성 완료 및 Test.ino 내용 삭제)

  - 최종적으로 Test.ino 의 모든 내용을 지운다. Test.ino는 어떠한 코드도 사용할 필요가 없게 된다.

  - 이후 Test.ino 파일의 용도는 프로그램 설명, 저작권 등에 대한 내용을 기재하는데 사용하면 된다.

 

11) 컴파일 및 확인

  - 컴파일이 성공적으로 끝난 것을 확인이 가능하며, 업로드하여 테스트해도 기존 Blink.ino와 동일한 내용 확인이

    가능하다.

 

 

 

 

12) 결론

  - Blink.ino 파일은 스케치파일(ino)와 메인파트(Test.cpp)와 사용자 라이브러리(Blink.cpp)로 분리가 되어

    보다 유연한 구조를 가지게 되었음을 알 수 있다.

  - 해당 예제는 고의로 복잡한 구성을 만들었다. 다만, 예제에서 알 수 있듯이 간단한 소스도 스케치 파일과

     소스파일을 분리하는 것이 구조 상 활용시 장점이 많게 된다.

 

끝으로, 이미 위에서 언급한 바와 같이 스케치 파일에서는 Arduino.h와 IDE에서 "새탭"으로 정의한 소스 및 헤더파일 들만 자동 추가된다. 따라서,

 

1. 소스 내에서 Serial 클래스와 같은 #include <Wire.h> 등을 사용할 때나 다른 라이브러리 등을 사용할 경우에는 

   스케치 파일에도 반드시 명시적으로 선언(#include로 기재)해 주어야 한다.

 

2. 사용되는 라이브러리들의 구성관계를 파악하기에 용이하므로 새탭 메뉴를 통해 정의된 사용자 라이브러리의

    헤더파일도 명시적으로 선언해 주는 것이 좋다.

 

를 유의해서 작성하는 것이 필요하다. 

 

즉, ino 파일은 프로그램의 전체 구조에 대한 맵과 같아서 사용되는 모든 라이브러리들을 명시적 선언해 주는 것이 좋은 방법이다.

 

 

샘플소스 :Test.zip

 

 

 

반응형

+ Recent posts