2017년 8월 8일 화요일

RTC 모듈로 릴레이 작동시키기

http://cafe.naver.com/diymaker/11 에 사용한 RTC 모듈을 간단하게 릴레이를 작동시키는 타이머로 사용하는 방법입니다.

Blynk 앱으로는 간단하게 되는데 웹으로 지원하는 IoT 사이트에서는 원격으로 타이머처리를 할려니 안되는 곳도 있고 

설정이 복잡하더군요.


#include <Wire.h>
#include "RTClib.h"

// PIN definitions
#define RELAY_PIN 2

// FSM states
#define STATE_OFF  0
#define STATE_ON   1

// Timer settings
#define START_TIME  2144
#define END_TIME    2146

// variables
RTC_DS1307 RTC;
int fsm_state;

void setup() {
  
  Serial.begin(57600);
  Serial.println("SimpleTimer running...");
  Serial.println();

  Wire.begin();
  RTC.begin();  

  pinMode(RELAY_PIN, OUTPUT);
  digitalWrite(RELAY_PIN, LOW);
  fsm_state = STATE_OFF;
}

void loop() {

  DateTime now = RTC.now();
  int nowHourMinute = now.hour() * 100 + now.minute();

  // FSM states
  switch(fsm_state) {
    
    case STATE_OFF:
      if(nowHourMinute > START_TIME && nowHourMinute < END_TIME) {
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);
        Serial.println(", it's time to wake up!");
        digitalWrite(RELAY_PIN, HIGH);
        fsm_state = STATE_ON;
      }
      break;
    
    case STATE_ON:
      if(nowHourMinute > END_TIME) {
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);        
        Serial.println(", it's time to go to sleep!");
        digitalWrite(RELAY_PIN, LOW);
        fsm_state = STATE_OFF;
      }    
      break;
  }
}


유량센서 사용하기 - 인터럽트 이용

유량센서 작동방식이 홀센서가 내부에 있어서 1회전에 할때마다 트리거가 발생하는 원리이므로

트리거 신호를 인터럽트에 연결시켜서 회전수를 카운트 해서 유량을 계산하는 코드입니다.

신호선에는 10K 저항을 연결해서 풀업저항으로 만들어 줍니다. 

1회전시 유량은 유량센서 용량에 따라 다르므로 스펙에 맞게 공식을 수정해야 할 것 같습니다.

제가 구한 유량센서는 The frequency calculation = constant flow rate (L/min) 7.5 * unit time (in seconds)

분당 7.5 리터니깐 초당 계산하니깐 60을 더 곱해줍니다.

인터럽트를 사용하니 SoftSerial은 사용할 수 없을것 같네요. 같이 인터럽트를 사용하니 WiFi을 연결하려면

하드웨어 시리얼을  이용해야 할 듯 합니다.

flow meter arduino

아래 사이트를 코드를 참고하였습니다.


// Reading liquid flow rate using an Arduino 
// Code adapted by Charles Gantt from PC Fan RPM code written by Crenn@thebestcasescenario.com
// http:/themakersworkbench.com http://thebestcasescenario.com 

volatile int NbTopsFan;            //measuring the rising edges of the signal
int Calc; 
int hallsensor = 2;                //The pin location of the sensor

void rpm ()                        //This is the function that the interupt calls
{
  NbTopsFan++;                     //This function measures the rising and falling edge of signal
}                                  //The setup() method runs once, when the sketch starts

void setup() 

{
 pinMode(hallsensor, INPUT);       //initializes digital pin 2 as an input
 Serial.begin(9600);               //This is the setup function where the serial port is initialised
 attachInterrupt(0, rpm, RISING);  //and the interrupt is attached
}
                                   // the loop() method runs over and over again
                                   // as long as the Arduino has power
void loop () 
{
 NbTopsFan = 0;                    //Set NbTops to 0 ready for calculations
 sei();                            //Enables interrupts
 delay (1000);                     //Wait 1 second
 cli();                            //Disable interrupts
 Calc = (NbTopsFan * 60 / 7.5);    //(Pulse frequency x 60) / 7.5Q = flow rate in L/hour
 Serial.print (Calc, DEC);         //Prints the number calculated above
 Serial.print (" L/hour\r\n");     //Prints "L/hour" and returns a new line
}

초음파 센서 이용하기

초음파 센서로 간단하게 거리를 측정하는 코드입니다.

Trig핀으로 신호를 보내고 Echo핀으로 측정값을 받습니다.

측정된 값을 왕복이니깐 2로 나누고, 소리는 초당 343m를 이동하므로, 1cm를 이동하는데 29.155ms가 소요되므로 29.1을

나누어 줍니다.

/*
HC-SR04 Ping distance sensor]
VCC to arduino 5v GND to arduino GND
Echo to Arduino pin 13 Trig to Arduino pin 12
Red POS to Arduino pin 11
Green POS to Arduino pin 10
560 ohm resistor to both LED NEG and GRD power rail
More info at: http://goo.gl/kJ8Gl
Original code improvements to the Ping sketch sourced from Trollmaker.com
Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar
*/

#define trigPin 13
#define echoPin 12
#define led 11
#define led2 10

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(1000); - Removed this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1; // 소리는 초당 343m를 이동하므로, 1cm를 이동하는데 29.155ms가 소요됨
  if (distance < 4) {  // This is where the LED On/Off happens
    digitalWrite(led,HIGH); // When the Red condition is met, the Green LED should turn off
  digitalWrite(led2,LOW);
}
  else {
    digitalWrite(led,LOW);
    digitalWrite(led2,HIGH);
  }
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}