'Arduino'에 해당되는 글 104건

  1. 2017.06.28 Hardware | YF-S201 water flow sensor 가지고 놀기 4
  2. 2017.06.25 Hardware | Arduino 로 Photoresister 가지고 놀기 - 1
  3. 2017.05.07 Hardware | HC-SR501 PIR motion sensor
  4. 2017.05.07 Hardware | Arduino water level sensor
  5. 2017.04.16 Software | CH341SER driver 최신 업데이트 하기
  6. 2017.04.11 Software | Arduino IDE 실행시키기
  7. 2017.03.31 Hardware | Arduino nano 조립기
  8. 2017.03.09 Hardware | BME280 sensor
  9. 2017.03.06 Hardware | Arduino BMP280 고도/온도/기압 센서
  10. 2017.03.06 Software | Arduino IDE 에서 library 추가하기

Hardware | YF-S201 water flow sensor 가지고 놀기

|

1. 이런 센서도 있네?

향후 집도 짓고 배관 시설도 공사도 해야 해서 "Water Flow Sensor" 를 익힐 필요가 있습니다.


...라는건 뻥이구요 (집 짓는게 장래 희망은 사실), Arduino 로 할 수 있는 센서는 어떤게 있을까 찾아 봤습니다.

"Water Flow Sensor" 라는게 있네요.


쓰임새는 액체가 흐르는 파이프에 설치하여 흐르는 양을 검출할 수 있는 센서 입니다.

요런거죠.





2. 구입

역시 Aliexpress 에서 구입 했습니다.

없는게 없죠?


https://ko.aliexpress.com/item/Water-flow-sensor-flowmeter-Hall-flow-sensor-Water-control-1-30L-min-2-0MPa-YF-S201/32583680601.html



3천원 미만으로 무료 배송이면 괜찮츄?




3. 도착 및 분해

도착 기념 샷 입니다.

구성은 단순하네요.



뒷면을 보니 흐르는 방향이 표시되어 있습니다.



내부가 궁금해 졌습니다.

나사 4개가 너무 눈에 띄게 만들어 졌네요. 분리해 봅니다.



물이 들어갈까봐 고무 패킹에 잘 둘러쌓여 있습니다.



호스 부분은 프로펠러가 달려 있어서 회전하게 되어 있습니다.

회전축에 자석같은게 붙어 있어서, 이 부분이 상판 회로의 센서와 hall effect 를 검출하는 것 같습니다.



상판 회로는 잘 분리되어 있습니다.




4. Layout

Pin 연결은 다음과 같습니다.


  YF-S201 | Arduino Nano
-------------------------
  Red     |      5V
  Black   |      GND
  Yellow  |      D2
-------------------------



Hall effect 를 이용한 센서라고 하는데, 전자기를 이용한 방식인 듯 합니다.

그래서 그런지 digital 단자와 연결됩니다.


Hall effect 는 다음 Wikipedia 를 참고해 보세요.

https://en.wikipedia.org/wiki/Hall_effect




5. Source

Code 는 다음과 같습니다.


출처는 아래 link 입니다.

https://diyhacking.com/arduino-flow-rate-sensor/

Code 소스는 아래 link 입니다.

http://diyhacking.com/projects/FlowMeterDIY.ino


/*
Liquid flow rate sensor -DIYhacking.com Arvind Sanjeev

Measure the liquid/water flow rate using this code. 
Connect Vcc and Gnd of sensor to arduino, and the 
signal line to arduino digital pin 2.
 
 */

byte statusLed    = 13;

byte sensorInterrupt = 0;  // 0 = digital pin 2
byte sensorPin       = 2;

// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
// litre/minute of flow.
float calibrationFactor = 4.5;

volatile byte pulseCount;  

float flowRate;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;

unsigned long oldTime;

void setup()
{
  
  // Initialize a serial connection for reporting values to the host
  Serial.begin(38400);
   
  // Set up the status LED line as an output
  pinMode(statusLed, OUTPUT);
  digitalWrite(statusLed, HIGH);  // We have an active-low LED attached
  
  pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  pulseCount        = 0;
  flowRate          = 0.0;
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;
  oldTime           = 0;

  // The Hall-effect sensor is connected to pin 2 which uses interrupt 0.
  // Configured to trigger on a FALLING state change (transition from HIGH
  // state to LOW state)
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
}

/**
 * Main program loop
 */
void loop()
{
   
   if((millis() - oldTime) > 1000)    // Only process counters once per second
  { 
    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt);
        
    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;
    
    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();
    
    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.
    flowMilliLitres = (flowRate / 60) * 1000;
    
    // Add the millilitres passed in this second to the cumulative total
    totalMilliLitres += flowMilliLitres;
      
    unsigned int frac;
    
    // Print the flow rate for this second in litres / minute
    Serial.print("Flow rate: ");
    Serial.print(int(flowRate));  // Print the integer part of the variable
    Serial.print(".");             // Print the decimal point
    // Determine the fractional part. The 10 multiplier gives us 1 decimal place.
    frac = (flowRate - int(flowRate)) * 10;
    Serial.print(frac, DEC) ;      // Print the fractional part of the variable
    Serial.print("L/min");
    // Print the number of litres flowed in this second
    Serial.print("  Current Liquid Flowing: ");             // Output separator
    Serial.print(flowMilliLitres);
    Serial.print("mL/Sec");

    // Print the cumulative total of litres flowed since starting
    Serial.print("  Output Liquid Quantity: ");             // Output separator
    Serial.print(totalMilliLitres);
    Serial.println("mL"); 

    // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;
    
    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  }
}

/*
Insterrupt Service Routine
 */
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}



6. 측정

당장 물 호스를 연결할 수가 없어, 입으로 바람을 불어 봅니다.

잘 되네요 !!!



Serial Monitor 로 결과를 보면 아래와 같습니다.

신기하게 잘 잡힙니다.



Flow rate / 흐르는 양 / 총량을 계산해 줍니다.

원작자가 소스코드를 잘 짜신것 같습니다.




FIN

이제 집만 지으면 될 것 같습니다.

And

Hardware | Arduino 로 Photoresister 가지고 놀기 - 1

|

1. Photoresistor

광원을 받으면 저항값이 바뀌는 소자가 photo-resistor 입니다.

다른 말로는 Light Dependent Resisor (LDR) 이라고도 합니다.


빛을 받으면 저항값이 내려가고, 어두워지면 저항값이 올라가는 반응을 이용합니다.



보통, 어두워지면 자동으로 전기가 켜지는 가로등에 많이 쓰이고 있죠.



저번에 했던 motion sensor 에, 이 photoresistor 를 추가하여 개조하기 위해 구입해 봅니다.


http://chocoball.tistory.com/entry/Hardware-HCSR501-PIR-motion-sensor




2. 구입 및 도착

AliExpress 에서 "GL5528" 로 검색하면 보편적인 Photoresistor 가 검색됩니다.


https://ko.aliexpress.com/item/20Pcs-Photo-Light-Sensitive-Resistor-Photoresistor-5528-GL5528/1852500725.html



무료배송이 행복합니다.


배송까지 약 2주정도 걸렸습니다.

요즈음은 대략 2주정도 걸리는군요.



실물은 이렇게 생겼습니다.



구글에서 보던 줄이 더 촘촘하고 긴 모듈을 상상했으나,

조금 간단한 제품입니다.




3. Layout

Pin 연결은 다음과 같습니다.

특이한건, 저항과 Photoresistor 연결점을 A0 로 한다는 것 정도 입니다.


 Photoresistor | 
-------------------------------
      +        |      A0
      +        |   220 ohm (1)
      -        |      GND
-------------------------------

  220 ohm (1)  | 
-------------------------------
      +        | Photoresistor
      -        |      GND
-------------------------------

 
    LED    | 
----------------------------------
     +     |     D8
     -     |  220 ohm (2) -->  GND
----------------------------------




4. Code

Source code 입니다.


//photoresistor A Style Tech.

int Pr = 0; // will be used for analog 0.
int PrValue = 0; // value of output
int Pr_Input = 10; // value of when light is on

void setup() {
  Serial.begin(9600); //start serial Monitor
  pinMode(8, OUTPUT); // pin 8 as output
}

void loop() {
  PrValue = analogRead(Pr);
  Serial.println(PrValue); //prints photoresistor value
  delay(100); // value updated every 0.1 second.

  if (PrValue < Pr_Input) {
    digitalWrite(8, HIGH);
  } else {
    digitalWrite(8, LOW); }
}




5. 구동

구동 잘 되네요.



IDE의 Serial Monitor 로 확인해본 결과 입니다.

10 이하의 값이 나오는 경우는 손으로 photoresistor 를 막아서 빛을 못받게 하는 상황입니다.

이때 LED 가 켜지죠.



잘 되쥬?



나름 재미 있네요.




FIN

이제 뭘하지?

And

Hardware | HC-SR501 PIR motion sensor

|

1. 시작하기

Motion sensor 를 이용하여, 사람을 감지하는 모듈을 만들어 보고싶었습니다.

오늘은 기본 구동 확인만 해 봅니다.


역시 구입은 AliExpress 죠!

이게 어떻게 1000원정도로 구입할 수 있는지, 감사할 따름입니다.



원리는 이렇다고 합니다.



Datasheet 입니다.

HC-SR501-PIR-Sensor-Datasheet.pdf



2. 외관

도착한 센서를 찍어 봤습니다.



커버 안에 센서가 보입니다.

커버를 통하여 넓은 범위를 커버하기 위함이라 합니다.





뒷면




3. 참고

보드를 보면 부품 실장이 되지 않은 부분이 있습니다.



바로 Photoresistor socket 과 Thermistor socket 입니다.

Photoresistor 를 실장하면, 동작하는 조건을 낮/밤 구분해서도 할 수 있을것 같습니다.


좀더 찾아보니, Photoresistor 를 같이 파는 사이트도 있는걸 보니, 실 구동도 가능해 보입니다.



Photoresistor 는 GL5528 이라는 규격을 사용하면 되겠네요.

다른 규격들을 살펴 보면, Ligth Resistance 와 Dark Resistance 가 다르네요.

나중에 기회되면 Photoresistor 를 추가하여 구축해보겠습니다.



Photoresistor 의 datasheet 입니다.

GL55 Series Photoresistor.pdf


Thermistor 에 대한 정보는 찾을 수가 없었습니다.

뭔가 알게되면 update 할께요.


또한, jumper 를 이용하여 모드를 변경할 수 있습니다.

여러 회사에서 제조되는 관계로 이 jumber 부분에 pin 이 실장되지 않는 제품들도 있더군요.

다행히 제가 구매한 제품은 점퍼가 살장되어 있었습니다.



Sensitivity 와 Time Delay 조정은 다음과 같이 합니다.






4. Sketch

회로 구성 및 정보는 아래 사이트를 참고하였습니다.

http://henrysbench.capnfatz.com/henrys-bench/arduino-sensors-and-input/arduino-hc-sr501-motion-sensor-tutorial/


Pin 배열 정보 입니다.

HC-SR501 PIR sensor | Arduino Nano
----------------------------------
         S          |     D8
         +          |     5V
         -          |     GND
----------------------------------

    Piezo busser    | Arduino Nano
----------------------------------
         S          |     D11
         +          |     5V
         -          |     GND
----------------------------------

Sketch 정보입니다. 여기저기 source 보고 짜집기 했습니다.

/*******************************************************

Uses a PIR sensor to detect movement, sounds a buzzer

*******************************************************/
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 30;

int ledPin = 13; // choose the pin for the LED
int inputPin = 8; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0; // variable for reading the pin status
int pinSpeaker = 11; //Set up a speaker on a PWM pin (digital 9, 10, or 11)

void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
pinMode(pinSpeaker, OUTPUT);

//give the sensor some time to calibrate
Serial.begin(9600);
Serial.print("Calibrating sensor ");
  for(int i = 0; i < calibrationTime; i++) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println(" Done!");
  Serial.println("SENSOR is ACTIVE now");
  delay(50);
}

void loop() {
  val = digitalRead(inputPin); // read input value
  if (val == HIGH) { // check if the input is HIGH
    blinky(); // blink LED when motion haas been detected
    // digitalWrite(ledPin, HIGH); // turn LED ON
    playTone(300, 160);
    delay(150);
    
    if (pirState == LOW) {
    // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
    digitalWrite(ledPin, LOW); // turn LED OFF
    playTone(0, 0);
    delay(300);

    if (pirState == HIGH){
    // we have just turned off
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}

void playTone(long duration, int freq) {
  // duration in mSecs, frequency in hertz
  duration *= 1000;
  int period = (1.0 / freq) * 1000000;
  long elapsed_time = 0;

  while (elapsed_time < duration) {
    digitalWrite(pinSpeaker,HIGH);
    delayMicroseconds(period / 2);
    digitalWrite(pinSpeaker, LOW);
    delayMicroseconds(period / 2);
    elapsed_time += (period);
  }
}

void blinky() {
  for(int i=0; i<3; i++) {
    digitalWrite(13, HIGH);
    delay(200);
    digitalWrite(13, LOW);
    delay(200);
  }
}

빵판 구성입니다.



실제 구동하면서 Serial Monitor 입니다.



잘 동작합니다. 소리도 잘 나네요.



5. 실제 구성

실제 구성샷 입니다.




구동 동영상 입니다.





FIN

이제 뭘하지?


And

Hardware | Arduino water level sensor

|

1. 시작하기

어항을 시작하면서 물 수위에 대한 자도 조절 기능을 만들고 싶었습니다.

물론 부레가 달린 물탱크를 사용하면 수위가 내려가면 자동으로 물 충전을 시켜주기는 하지만,

뭔가 전자적으로 만들고 싶습니다.



또한, IoT 하면 수위 변동시 alert 등도 스마트폰으로 알람을 띄워 줄 수 있겠죠.


여기선, 우선 단순 구동 확인만 해보겠습니다.



2. 구입하기

AliExpress 에서 "water sensor" 를 검색하면 아래와 같은 센서가 보입니다.

구입합니다.



실제 사진입니다.



뒷면





3. layout

Pin은 다음과 같이 연결합니다.

Water Level Sensor | Arduino Nano
---------------------------------
         S         |     A0
         +         |    3.3V
         -         |     GND
---------------------------------


빵판 layout



실제 연결한 장면입니다.




4. sketch

/*Code for Liquid Level Sensor Circuit Built with an Arduino*/

const int sensorPin= 0; //sensor pin connected to analog pin A0
int liquid_level;

void setup() {
Serial.begin(9600); //sets the baud rate for data transfer in bits/second
pinMode(sensorPin, INPUT); //the liquid level sensor will be an input to the arduino
}

void loop() {
liquid_level= analogRead(sensorPin); //arduino reads the value from the liquid level sensor
Serial.println(liquid_level); //prints out liquid level sensor reading
delay(100); //delays 100ms
}


5. 측정

구동 잘 되고, 물컵 이용하여 측정해 봤습니다.



센서 끝부터 물에 담구면 수치가 변하는 것을 볼 수 있습니다.



센서 끝단은 측정치가 많이 올라가고 (0~200), 그 위에는 (200~400) 천천히 올라갑니다.

일정한 피치로 측정이 될려면 좀더 정확한 sensor 를 구입해야 할 듯 합니다.



한가지 좋은 점은 작은 LED 가 있어서, 구동중이라는 것을 보여주는 것 정도?



FIN

이제 뭘하지?


And

Software | CH341SER driver 최신 업데이트 하기

|

1. 시작하기

Chinese clone 인 arduino nano 를 이용하여 data 를 전송하는 프로그램을 돌려보면, 유난히 buffer 부족에 대한 에러가 많이 나옵니다.


아마 정품과 구성품이 다른 부품이 그 원인인 듯 하고,

또한 이를 제조한 WCH 사의 driver를 통해서만 arduino nano 에 접근이 가능하므로 driver 를 의심해 보기로 합니다.



2. 찾기

외국 친구들이 설명해 놓은 chinese clone driver 는 예전 버전이 많습니다.

WCH 가 만들었으니, "http://www.wch.cn/" 사이트에서 찾아보기로 합니다.


글은 까만색이요 흰색은 종이.... 레벨입니다. (중국어 모름)



다행이 검색란이 있으니, 찾고자 하는 driver 의 정확한 명칭인 "ch340ser" 을 칩니다.



오호이~ 나왔습니다.

여러 OS 별로도 연관 파일에 표시되어 있습니다.




3. Windows용

파일을 받고 실행해 봅니다.


역시 드라이버 버전이 바뀌어 있습니다!




혹시 몰라 장치관리자 > COM6 > 오른쪽 클릭하여 "드라이버 갱신" 에서 인터넷에서 갱신하면, 한번 더 하더군요.






FIN

뭐가 달라졌는지 여러가지로 해봐야겠습니다.

And

Software | Arduino IDE 실행시키기

|

1. 시작하기

Arduino 에 프로그램을 밀어 넣고 실행시키려면, arduino IDE 가 필요합니다.

Arduino IDE 를 실행시키려면, USB로 연결되는 arduino 본체를 인식해야 합니다.


여기에 더하여, 저는 Chinese clone 이므로, 일일히 driver 를 찾아서 설치해 줘야 합니다.


Arduino IDE 를 실행시키면 Happy Coding 의 세계가 열리는 것이죠.


자, 시작해 볼까요?



2. 파일 받기

다운로드 받는 곳은 아래와 같습니다.

http://www.arduined.eu/ch340g-converter-windows-7-driver-download/






3. 드라이버 인스톨

파일을 받고 압축을 풀면 SETUP 실행파일이 있습니다.

저는 Windows 7 64bit 이므로 "DRVSETUP64.exe" 파일을 실행시킵니다.



실행시키면 다음과 같은 화면이 뜹니다.



INSTALL 을 하면 완료 됩니다.



위의 과정을 거치기 전에는 USB를 꼽으면 아래 스샷처럼 인식할 수 없는 기기로 보입니다.



Driver 를 인스톨 하고 USB를 꼽으면 아래 스샷처럼 기기를 정식으로 등록하게 됩니다.



드라이버를 인식했습니닷 !!!

Port 정보를 잘 알아둬야 합니다. 여기서는 COM6 네요.





4. IDE 실행

이제 arduino 기기를 OS에서 인식했으니, 설치한 IDE 를 실행합니다.

IDE 다운로드는 다음 URL 에서 가능합니다.


https://www.arduino.cc/en/main/software


설치 후, 실행시킵니다.


작년 처음 시작할 때는 1.6 이었는데, 지금은 1.8 이네요.




5. 인식 시키기

IDE 를 실행시키면 바로 되는게 아니라, USB로 연결된 arduino nano 를 정식으로 등록해 줘야 합니다.

기기 등록은, Tools > Board, Processor 와 Port 정보 입니다.


Board 는 "Arduino Nano" 를 선택합니다.



Processor 는 "ATmega328" 을 선택합니다.



저의 경우의 Port 는, 아까 확인했던 "COM6" 를 선택합니다.



연결이 완료되면 beacon 신호를 보내는 것처럼 ready 상태를 나타내 줍니다.



이제 준비 완료 입니다!

이젠 Happy Coding 이지요.



FIN

이제 뭘하지?

And

Hardware | Arduino nano 조립기

|

1. 시작하기

Aliexpress 에서 판매되는 Arduino nano 는 2가지 버전이 있습니다.

조립되어 있고 USB cable 이 포함되어 있는 버전과, 케이블이 없고 다리들을 납땜해야 하는 버전.


한 700원 차이나지만, 궂이 cable 도 필요 없고 돈도 아낄 겸, 납땜해야 하는 버전도 하나 구입합니다.



납땜 연습에도 적격입니다.



2. 도착

물건 도착하자 마자 찍어놓은 사진입니다.



뒷모습



앞모습



MEGA328P 프로세서 입니다.



3. 완성

그냥 납땜 합니다.

빵판에 다리를 고정시켜 놓고 납땜하면 편합니다.



위에가 납땜한 버전입니다.

layout 상 다른 부분은 오실레이터가 수평이 아닌, 프로세서랑 나란이 위치하고 있는데 다릅니다.




4. 테스트

전원을 넣으면 빨간불이 켜지면서 ready 한 상태가 됩니다.



BME280 sketch 를 올리고 돌려보면 정상 작동하는 것을 확인하였습니다.

우훗!



성공입니다.



FIN

더 필요하면 납땜 버전을 계속 구입하겠습니다.


이제 뭘하지?

'Hardware' 카테고리의 다른 글

Hardware | BMR-C1 heatsink  (0) 2017.04.26
Hardware | Sharp GP2Y1010AU0F dust sensor  (0) 2017.03.31
Hardware | GeForce GTX 560 Ti 수리 실패기  (0) 2017.03.16
Hardware | BME280 sensor  (0) 2017.03.09
Hardware | DSO150 Oscilloscope  (0) 2017.03.07
And

Hardware | BME280 sensor

|

1. 시작하기

BMP280 을 구동시키면서 googling 해보면, "Humidity = 습도" 값을 표시해주는 글들이 심심치 않게 보였습니다.

그래서 열씸히 Humidity 를 표현하려고 이리저리 시도해 봤습니다.


또, Aliexpress 에서 구입한 BMP280 제품을 보면 GY-BME/P280 이라고 표시되어 있습니다.

할거 다 해봤습니다.


아니 그런뒈.... 그런뒈! (컬투 버전) 



2. 알아버렸다

그렇습니다. Humidity 를 하려면, 정확하게 BME280 이 있어야 합니다. BMP280 로는 안되는 것이였습니다.

아놔.




나를 깨우쳐준 글.



정말 되냐 안되냐를 확인할 수 있는 글.



3. 넌 누구냐

직접 확인해 봅니다.

SparkFun 이 제공하는 'I2C_ReadAllData.ino' sketch 를 통해서 0x58 이냐, 0x60 이냐를 확인해 봅니다.


SparkFun Library 를 아래 링크를 통해 다운받고 설치합니다.


 - https://github.com/sparkfun/SparkFun_BME280_Arduino_Library


마지막으로 I2C address 를 0x77 > 0x76 으로 바꾸고 실행해 봅니다.



아놔... 넌 BMP280 이구나...



4. BME280 구입

정말 정말 Humidity 수치를 알고 싶습니다.


한꺼번에 구입하지 못 한것을 탓하면서, 다시 주문을 넣습니다.

3주만에 오네요.



2개를 주문해서 앞뒤로 한 샷에 넣어 봅니다.



위의 부분이 센서군요. 보통 Bosch 에서 만든다고 하는데, Bosch 각인은 아닌것 같습니다.




이놈이 진짜 BME280 인지, 바로! 확인해 봅니닷!



오옷! 맞네요.
(정보를 알려준 외국인 친구 감사~!)



5. 구동해 보기

Library 를 다운받아 설치합니다.


 - https://github.com/adafruit/Adafruit_BME280_Library


I2C address 를 0x77 > 0x76 으로 꼭 변경해야 합니다.



이거 수정하지 않고 한참 해멨습니다.



이제 example sketch 를 로딩합니다.



소스는 다음과 같습니다.


/***************************************************************************
  This is a library for the BME280 humidity, temperature & pressure sensor

  Designed specifically to work with the Adafruit BME280 Breakout
  ----> http://www.adafruit.com/products/2650

  These sensors use I2C or SPI to communicate, 2 or 4 pins are required
  to interface. The device's I2C address is either 0x76 or 0x77.

  Adafruit invests time and resources providing this open source code,
  please support Adafruit andopen-source hardware by purchasing products
  from Adafruit!

  Written by Limor Fried & Kevin Townsend for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ***************************************************************************/

#include 
#include 
#include 
#include 

#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 10

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI

unsigned long delayTime;

void setup() {
    Serial.begin(9600);
    Serial.println(F("BME280 test"));

    bool status;
    
    // default settings
    status = bme.begin();
    if (!status) {
        Serial.println("Could not find a valid BME280 sensor, check wiring!");
        while (1);
    }
    
    Serial.println("-- Default Test --");
    delayTime = 1000;

    Serial.println();
}


void loop() { 
    printValues();
    delay(delayTime);
}


void printValues() {
    Serial.print("Temperature = ");
    Serial.print(bme.readTemperature());
    Serial.println(" *C");

    Serial.print("Pressure = ");

    Serial.print(bme.readPressure() / 100.0F);
    Serial.println(" hPa");

    Serial.print("Approx. Altitude = ");
    Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
    Serial.println(" m");

    Serial.print("Humidity = ");
    Serial.print(bme.readHumidity());
    Serial.println(" %");

    Serial.println();
}

layout 은 다음과 같고, pin 구성은 BMP280 과 같이 I2C 연결과 같습니다.


- VIN : 3.3V

- GND : GND

- SCL : A5

- SDA : A4



빵판에 연결합니다.




6. 결과

얏호~!!!

이제 Humidity 를 볼 수 있어요.



더 사용폭이 많은 BME280 만 만들지, 왜 BMP280 을 만드냐고 살짝 울분을 토해봅니다..



FIN

이제 뭘하지?

And

Hardware | Arduino BMP280 고도/온도/기압 센서

|

1. 시작하기

온도, 기압, 고도센서가 하나의 기판에 달려있는, 참 고마원 BMP280 을 가지고 놀아봅니다.

원래는 Adafruit 에서 나온 정식 발매품이 있는 듯 하나, Aliexpress 를 사랑하는 저로서는 clone 품을 가지고 놀아봅니다.





2. Library

2가지 library 를 설치해야 합니다.

- Adafruit Sensor

- Adafruit BMP280


먼저, Adafruit Sensor library 를 설치합니다.

- https://github.com/adafruit/Adafruit_Sensor




그리고, BMP280 용 library 를 다운로드 받아 설치합니다.

     - https://learn.adafruit.com/adafruit-bmp280-barometric-pressure-plus-temperature-sensor-breakout/wiring-and-test




맨 마지막으로, clone 부품을 구동시키기 위해,

"Adafruit_BMP280.h" 파일을, 아래처럼 I2C 어드레스에 대해 0x77 > 0x76 으로 수정해 줘야 합니다.





3. 소스코드

위의 library 를 추가하였으면, "File > Examples > Adafruit BMP280 Library > bmp280test" 를 선택할 수 있습니다.




/***************************************************************************
  This is a library for the BMP280 humidity, temperature & pressure sensor

  Designed specifically to work with the Adafruit BMEP280 Breakout 
  ----> http://www.adafruit.com/products/2651

  These sensors use I2C or SPI to communicate, 2 or 4 pins are required 
  to interface.

  Adafruit invests time and resources providing this open source code,
  please support Adafruit andopen-source hardware by purchasing products
  from Adafruit!

  Written by Limor Fried & Kevin Townsend for Adafruit Industries.  
  BSD license, all text above must be included in any redistribution
 ***************************************************************************/

#include 
#include 
#include 
#include 

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11 
#define BMP_CS 10

Adafruit_BMP280 bme; // I2C
//Adafruit_BMP280 bme(BMP_CS); // hardware SPI
//Adafruit_BMP280 bme(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

void setup() {
  Serial.begin(9600);
  Serial.println(F("BMP280 test"));
  
  if (!bme.begin()) {  
    Serial.println(F("Could not find a valid BMP280 sensor, check wiring!"));
    while (1);
  }
}

void loop() {
    Serial.print(F("Temperature = "));
    Serial.print(bme.readTemperature());
    Serial.println(" *C");
    
    Serial.print(F("Pressure = "));
    Serial.print(bme.readPressure());
    Serial.println(" Pa");

    Serial.print(F("Approx altitude = "));
    Serial.print(bme.readAltitude(1013.25)); // this should be adjusted to your local forcase
    Serial.println(" m");
    
    Serial.println();
    delay(2000);
}



4. Layout

PIN 배열은 다음과 같습니다.

- VCC : 3.3v

- GND : GND

- SCL : A5

- SDA : A4







5. 결과

잘 나오네요.

실재로 사용시에는 기준값을 조금 수정해야 할 것 같습니다만, 일단 성공입니다.




6. 확장

아래 링크에서는 OLED 를 사용한 방법을 소개하고 있습니다.


- http://www.instructables.com/id/Standalone-Arduino-Altimeter/


바로 따라해 봅니다.

우선 아래 용도로 사용될 BMP280 library 를 다운로드 받고, libraries 폴더에 위치시킵니다.


BMP280.zip





[BMP280]

----------------------

- VCC : +3.3V

- GND : GND

- SCL : A5

- SDA : A4

- CSB : +3.3V

- SDO : GND


[0.96" I2C IIC Series 128X64 OLED]

----------------------

- SCL : A5

- SDA : A4

- VCC : +3.3V

- GND : GND


#include "U8glib.h"
#include "BMP280.h"
#include "Wire.h"
#define P0 1021.97  //1013.25 
BMP280 bmp;

// OLED Type
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NO_ACK);

char sT[20];
char sP[9];
char sA[9];
char sA_MIN[9];
char sA_MAX[9];
double A_MIN = 0;
double A_MAX = 0;

void draw(double T, double P, double A) {
  u8g.setFont(u8g_font_unifont);

  dtostrf(T, 4, 2, sT);
  dtostrf(P, 4, 2, sP);
  dtostrf(A, 4, 2, sA);

  u8g.drawStr( 5, 10, "Temp: ");
  u8g.drawStr( 5, 30, "Bar : ");
  u8g.drawStr( 5, 50, "Alt : ");
  u8g.drawStr( 50, 10, sT);
  u8g.drawStr( 50, 30, sP);
  u8g.drawStr( 50, 50, sA);
}

void draw2(double A_MIN, double A_MAX) {
  u8g.setFont(u8g_font_unifont);

  dtostrf(A_MIN, 4, 2, sA_MIN);
  dtostrf(A_MAX, 4, 2, sA_MAX);
  u8g.drawStr( 5, 20, "A Min: ");
  u8g.drawStr( 60, 20, sA_MIN);
  u8g.drawStr( 5, 45, "A Max: ");
  u8g.drawStr( 60, 45, sA_MAX);
}

void setup() {
  Serial.begin(9600);
  if (!bmp.begin()) {
    Serial.println("BMP init failed!");
    while (1);
  }
  else Serial.println("BMP init success!");

  bmp.setOversampling(4);

  u8g.setColorIndex(1);
  u8g.setFont(u8g_font_unifont);
}

void loop(void) {
  double T, P;
  char result = bmp.startMeasurment();

  if (result != 0) {
    delay(result);
    result = bmp.getTemperatureAndPressure(T, P);

    if (result != 0) {
      double A = bmp.altitude(P, P0);

      if ( A > A_MAX) {
        A_MAX = A;
      }

      if ( A < A_MIN || A_MIN == 0) {
        A_MIN = A;
      }

      //      Serial.print("T = \t"); Serial.print(T, 2); Serial.print(" degC\t");
      //      Serial.print("P = \t"); Serial.print(P, 2); Serial.print(" mBar\t");
      //      Serial.print("A = \t"); Serial.print(A, 2); Serial.println(" m");

      u8g.firstPage();
      do {
        draw(T, P, A);
      } while ( u8g.nextPage() );
      u8g.firstPage();
      delay(1000);

      do {
        draw2(A_MIN, A_MAX);
      } while ( u8g.nextPage() );
      u8g.firstPage();
      delay(1000);
      
    }
    else {
      Serial.println("Error.");
    }
  }
  else {
    Serial.println("Error.");
  }

  delay(100);

}





값이 잘 바뀌고 있습니다.




FIN

이제 뭘하지?

And

Software | Arduino IDE 에서 library 추가하기

|

1. 시작하기

새로운 sensor 나 module 을 구매하여 구동시키려면,

제조 vendor 에서 제공한 library 가 필요합니다. (밑도 끝도 없이 혼자 파볼 수는 없는 일!)


- https://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use/installing-a-library


그래서, module 이 구해지면 자동으로 library 추가가 필요합니다.



2. ZIP 으로 추가하기

메뉴에서 Sketch > Include Library > Add .ZIP Library...

이렇게 하면 편하게 library 를 추가할 수 있습니다.



위에서처럼 추가하면, 아래처럼 추가한 library 가 보입니다.




다만, 정식 제품이 아닌,

clone 제품 등을 사용하거나, 비슷한 제품을 사용하게 되면, 이 library 소스를 조금 수정해야 하는 일이 발생합니다.

(완전히 같을 수는 없겠죵)



3. 직접 추가하기

메뉴로 추가하면 편하지만, 한가지 단점이 있습니다.

바로 위에서 이야기한, clone 제품일 경우 library 수정이 필요한 경우가 있습니다.


이럴때는 다음과 같은 순서로 작업을 합니다.


A) Library ZIP 파일을 다운로드

B) 개인이 관리하는 장소 (예: Windows OS 의 "내문서" 하위에 "Arduino" 폴더) 를 작성

C) 다운로드 받은 파일을, 새로 만든 폴더에 압축을 품

D) 압축 풀때 사용하는 folder 명을 수정

예) Adafruit_BMP280_Library_master --> Adafruit_BMP280


E) 수정한 파일 열어서 수정 후, 저장


위의 방식으로 하면, "File > Examples" 에서 등록된 것을 찾을 수 있습니다.





FIN

모두 Arduino 가지고 enjoy your life 하세요~!



And
prev | 1 | ··· | 7 | 8 | 9 | 10 | 11 | next