2015年7月28日 星期二

Arduino 網路遠端遙控家電

源自於

http://swf.com.tw/?p=630

http://swf.com.tw/?p=634

本文旨在補充《超圖解Arduino互動設計入門》第十六章「網路家電控制」單元,增加另一個網頁控制範例。



Arduino網路遠端遙控家電開關(一)

Arduino網路遠端遙控家電開關(二)



Arduino官方的Ethernet以太網路控制板,當中的數位腳位編號4,保留給SD記憶卡的晶片選擇線使用,請不要挪做他用。
數位10~13腳是SPI介面的預設腳位,用於控制以太網路晶片,也請不要使用。

2015年7月27日 星期一

Arduino Read a card using a mfrc522 reader

Arduino Read a card using a mfrc522 reader 


參考

1) http://playground.arduino.cc/Learning/MFRC522

2) http://blog.davidou.org/archives/684

3) http://www.dotblogs.com.tw/aliceyeh/archive/2014/11/12/147272.aspx


MFRC-522 RC522 RFID射频 IC卡感应模块 11/11 ¥12.8 资料下载1 资料下载2  Philips MFRC522
非接触式通信中高集成度的读写卡芯片。支持14443A兼容应答器信号。数字部分处理 ISO14443A 帧和错误检测。支持快速 CRYPTO1 加密算法,用语验证MIFARE系列产品。支持 MIFARE 系列更高速的非接触式通信,双向数据传输速率高达 424 kb/s。 与MF RC500 和 MF RC530 有不少相似之处,同时也具备许多特点和差异。它与主机间通信采用SPI模式,有利于减少连线,缩小PCB板体积,降低成本。

◦ Module Name: MF522-ED
◦ Working current:13—26mA/ DC 3.3V
◦ Working frequency:13.56MHz
◦ Card reading distance :0~60mm(mifare1 card)
◦ Protocol:SPI
◦ Data communication speed:Maximum 10Mbit/s
◦ Card types supported:mifare1 S50、mifare1 S70、mifare UltraLight、mifare Pro、mifare Desfire
◦ NXP RC522 Datasheet


然後板上有VCC、RST、GND、MISO、MOSI、SCK、NSS、IRQ這八個腳位
VCC要插到ARDUINO的3V腳位 (注意!不是5V)
然後RST接 數位接腳5(DIGITAL 5)
GND就是接GND
MISO->數位12
MOSI->數位11
SCK->數位13
NSS->數位10
IRQ-> 我沒接




※ MFRC522
◆ GitHub -- miguelbalboa/rfid (Arduino for MRFC522)  ★★★★★ 偶比較喜歡這個封包, 不過原始來源都素一樣滴~~~141123 DL
Mifare 1K=1024bytes, 4K=4096bytes, Mini(S20)=320bytes, Ultralight=64bytes
◎ ElectroDragon -- RFID Card Reader/Detector Module ★★★★141202 DL
◎ Arduino Playground -- Mifare MFRC522 RFID Reader/Writer
▪ Dumping Mifare's TAGs




/**
* Read a card using a mfrc522 reader on your SPI interface
* Pin layout should be as follows (on Arduino Uno):
* MOSI: Pin 11 / ICSP-4
* MISO: Pin 12 / ICSP-1
* SCK: Pin 13 / ISCP-3
* SS: Pin 10
* RST: Pin 9
*
* Script is based on the script of Miguel Balboa.
* Serial number is shown on a HD44780 compatible display
*
* The circuit:
* LCD RS pin to digital pin (7)
* LCD Enable pin to digital pin (6)
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
*
* @version 0.1
* @author Henri de Jong
* @since 27-01-2013
*/

#include <SPI.h>
#include <RFID.h>

//I2C + I2C LCD Library
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display
/*==========================================
SDA – 接 Arduino 的 Analog Pin 4 (Arduino Mega 為 Pin 20)
SCL – 接 Arduino 的 Analog Pin 5 (Arduino Mega 為 Pin 21)
GND – 接 GND
VCC – 接 +5V
==========================================*/

#define RFID_OUT 7

#define SS_PIN 10
#define RST_PIN 9

RFID rfid(SS_PIN, RST_PIN);

// Setup variables:
    int serNum0;
    int serNum1;
    int serNum2;
    int serNum3;
    int serNum4;

void setup()
{
  Serial.begin(9600);
  SPI.begin();
  rfid.init();

  lcd.init();                       // initialize the lcd
                                    // Print a message to the LCD.
  lcd.backlight();
                                    // 輸出初始化文字
  lcd.setCursor(0, 0);              // 設定游標位置在第1行行首
  lcd.print("RFIDReader RC522");    //RFID Reader RC522 + Access Control System
  Serial.println("RFID Reader RC522 + Access Control System");

  pinMode(RFID_OUT, OUTPUT);      // sets the digital pin as output
  digitalWrite(RFID_OUT, HIGH);   //Set RFID OUT OFF

}

void loop()
{
 
    if (rfid.isCard()) {
        if (rfid.readCardSerial()) {
            if (rfid.serNum[0] != serNum0
                && rfid.serNum[1] != serNum1
                && rfid.serNum[2] != serNum2
                && rfid.serNum[3] != serNum3
                && rfid.serNum[4] != serNum4
            ) {
                /* With a new cardnumber, show it. */
                Serial.println(" ");
                Serial.println("Card found");
                serNum0 = rfid.serNum[0];
                serNum1 = rfid.serNum[1];
                serNum2 = rfid.serNum[2];
                serNum3 = rfid.serNum[3];
                serNum4 = rfid.serNum[4];
             
                //Serial.println(" ");
                Serial.println("Cardnumber:");
                Serial.print("Dec: ");
                Serial.print(rfid.serNum[0],DEC);
                Serial.print(", ");
                Serial.print(rfid.serNum[1],DEC);
                Serial.print(", ");
                Serial.print(rfid.serNum[2],DEC);
                Serial.print(", ");
                Serial.print(rfid.serNum[3],DEC);
                Serial.print(", ");
                Serial.print(rfid.serNum[4],DEC);
                Serial.println(" ");
                     
                Serial.print("Hex: ");
                Serial.print(rfid.serNum[0],HEX);
                Serial.print(", ");
                Serial.print(rfid.serNum[1],HEX);
                Serial.print(", ");
                Serial.print(rfid.serNum[2],HEX);
                Serial.print(", ");
                Serial.print(rfid.serNum[3],HEX);
                Serial.print(", ");
                Serial.print(rfid.serNum[4],HEX);
                Serial.println(" ");

                /* Write the HEX code to the display */
                lcd.clear();              
               // lcd.setCursor(0, 0);
               // lcd.print("Cardno (hex):");
                lcd.setCursor(0,1);
                lcd.print(rfid.serNum[0], HEX);
                lcd.print(',');
                lcd.print(rfid.serNum[1], HEX);
                lcd.print(',');
                lcd.print(rfid.serNum[2], HEX);
                lcd.print(',');
                lcd.print(rfid.serNum[3], HEX);
                lcd.print(',');
                lcd.print(rfid.serNum[4], HEX);

                if (rfid.serNum[0]==68 &&           //RFID Code Correct Set OUT ON
                    rfid.serNum[1]==81 &&           // Card found Cardnumber:
                    rfid.serNum[2]==187 &&          //Dec: 68, 81, 187, 150, 56
                    rfid.serNum[3]==150 &&          //Hex: 44, 51, BB, 96, 38
                    rfid.serNum[4]==56 ) {
                          digitalWrite(RFID_OUT, LOW);
                          lcd.setCursor(0, 0);          // 設定游標位置在第1行行首
                          lcd.print("RFID SET ON  ");   //Set RFID OUT ON
                    }

                if (rfid.serNum[0]==112 &&             //RFID Code Correct Set OUT OFF
                    rfid.serNum[1]==33 &&             // Card found  Cardnumber:
                                                      // Dec: 112, 33, 237, 16, 172
                                                      // Hex: 70, 21, ED, 10, AC

                    rfid.serNum[2]==237 &&
                    rfid.serNum[3]==16 &&
                    rfid.serNum[4]==172 ) {
                          digitalWrite(RFID_OUT, HIGH);  //Set RFID OUT OFF
                          lcd.setCursor(0, 0);          // 設定游標位置在第1行行首
                          lcd.print("RFID SET OFF  ");
                    }
             
             } else {
               /* If we have the same ID, just write a dot. */
               Serial.print(".");
             }
          }
    }
 
    rfid.halt();
}




Arduino IR Remote 程式-2

-2

1) 利用上一篇的 Arduino IR Remote 程式抓取遙控器的10進制接收內碼


results value is  HEX=807F00FF  DEC= 2155806975, bits is 32, decode_type is 1
---Key "0"
results value is  HEX=FFFFFFFF  DEC= 4294967295, bits is 0, decode_type is 1
---Key  release

results value is  HEX=807F906F  DEC= 2155843695, bits is 32, decode_type is 1
---Key "1"
results value is  HEX=FFFFFFFF  DEC= 4294967295, bits is 0, decode_type is 1
---Key  release

2) 控制 "0" , "1" 設定輸出 ON/OFF 


#include <IRremote.h>

//I2C + I2C LCD Library
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display
/*==========================================
SDA – 接 Arduino 的 Analog Pin 4 (Arduino Mega 為 Pin 20)
SCL – 接 Arduino 的 Analog Pin 5 (Arduino Mega 為 Pin 21)
GND – 接 GND
VCC – 接 +5V
==========================================*/

int RECV_PIN = 2; // 使用數位腳位2接收紅外線訊號
int RECV_OUT = 12; // 使用數位腳位12 控制ON/OFF

IRrecv irrecv(RECV_PIN); // 初始化紅外線訊號輸入
decode_results results; // 儲存訊號的結構

void setup()
{
  Serial.begin(9600);
  irrecv.blink13(true); // 設為true的話,當收到訊號時,腳位13的LED便會閃爍
  irrecv.enableIRIn(); // 啟動接收
  pinMode(RECV_OUT, OUTPUT);      // sets the digital pin as output
  digitalWrite(RECV_OUT, HIGH);   //Set RECV_OUT  HIGH = OFF   LOW=ON 
  //**************************************
  lcd.init();                   // initialize the lcd
                                // Print a message to the LCD.
  lcd.backlight();              // 輸出初始化文字
  lcd.setCursor(0, 0);          // 設定游標位置在第1行行首
  lcd.print("IR Remote Contro");
}

void loop() {
  if (irrecv.decode(&results)) { // 接收紅外線訊號並解碼
    Serial.print("results value is  HEX="); // 輸出解碼後的資料
    Serial.print(results.value, HEX);
    Serial.print("  DEC= ");
    Serial.print(results.value); 
    Serial.print(", bits is ");
    Serial.print(results.bits);
    Serial.print(", decode_type is ");
    Serial.println(results.decode_type);
    irrecv.resume(); // 準備接收下一個訊號
  

  if (results.value==2155806975) {   // KEY "1" HEX=807F00FF  DEC= 2155806975
      digitalWrite(RECV_OUT, LOW);    //Set RECV_OUT 
      lcd.setCursor(0, 1);          // 設定游標位置在第2行行首
      lcd.print("IR SET ON  ");
  } 
  
  if (results.value==2155843695){    //KEY "0"  HEX=807F906F  DEC= 2155843695
      digitalWrite(RECV_OUT, HIGH);    //Set RECV_OUT 
      lcd.setCursor(0, 1);          // 設定游標位置在第2行行首
      lcd.print("IR SET OFF ");
  }
  
  } 
}

Arduino IR Remote 程式-1

Arduino IR Remote 程式-1

參考   http://yehnan.blogspot.tw/2014/09/arduinoerror-tkd2-was-not-declared.html

1) 編譯錯誤 錯誤問題

#include <IRremote.h>
void setup() {
}
void loop() {
}

就會出現底下的編譯錯誤訊息(若選擇「Arduino Robot Control」以外的板子):

D:\arduino-1.6.5-r2-windows\libraries\RobotIRremote\IRremoteTools.cpp:5:16: error: 'TKD2' was not declared in this scope
 int RECV_PIN = TKD2; // the pin the IR receiver is connected to
  
原因在於,Arduino IDE 1.5.5 r2開始加入一套縮減版的IRremote程式庫,名為RobotIRremote,更動了不少東西,但有些地方卻沒變(譬如檔名),以至於起衝突。

此錯誤的詳細情況,大致如此:想使用自行安裝的IRremote,但Arduino IDE卻以內建的RobotIRremote為優先;RobotIRremote的檔案IRremoteTools.cpp需要TKD2的腳位定義,而只有「Arduino Robot Control」板子的腳位定義檔裡才有TKD2這玩意兒,如此一來,就會發生上述的錯誤訊息。

2) 移除 D:\arduino-1.6.5-r2-windows\libraries\RobotIRremote 相關的Robot目錄檔案


IRremote.h 程式

/*
 * IRremote
 * Version 0.1 July, 2009
 * Copyright 2009 Ken Shirriff
 * For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.htm http://arcfn.com
 *
 * Interrupt code based on NECIRrcv by Joe Knapp
 * http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556
 * Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/
 */

#ifndef IRremote_h
#define IRremote_h

// The following are compile-time library options.
// If you change them, recompile the library.
// If DEBUG is defined, a lot of debugging output will be printed during decoding.
// TEST must be defined for the IRtest unittests to work.  It will make some
// methods virtual, which will be slightly slower, which is why it is optional.
// #define DEBUG
// #define TEST

// Results returned from the decoder
class decode_results {
public:
  int decode_type; // NEC, SONY, RC5, UNKNOWN
  unsigned long value; // Decoded value
  int bits; // Number of bits in decoded value
  volatile unsigned int *rawbuf; // Raw intervals in .5 us ticks
  int rawlen; // Number of records in rawbuf.
};

// Values for decode_type
#define NEC 1
#define SONY 2
#define RC5 3
#define RC6 4
#define DISH 5
#define SHARP 6
#define UNKNOWN -1

// Decoded value for NEC when a repeat code is received
#define REPEAT 0xffffffff

// main class for receiving IR
class IRrecv
{
public:
  IRrecv(int recvpin);
  void blink13(int blinkflag);
  int decode(decode_results *results);
  void enableIRIn();
  void resume();
private:
  // These are called by decode
  int getRClevel(decode_results *results, int *offset, int *used, int t1);
  long decodeNEC(decode_results *results);
  long decodeSony(decode_results *results);
  long decodeRC5(decode_results *results);
  long decodeRC6(decode_results *results);
  long decodeHash(decode_results *results);
  int compare(unsigned int oldval, unsigned int newval);

}
;

// Only used for testing; can remove virtual for shorter code
#ifdef TEST
#define VIRTUAL virtual
#else
#define VIRTUAL
#endif

class IRsend
{
public:
  IRsend() {}
  void sendNEC(unsigned long data, int nbits);
  void sendSony(unsigned long data, int nbits);
  void sendRaw(unsigned int buf[], int len, int hz);
  void sendRC5(unsigned long data, int nbits);
  void sendRC6(unsigned long data, int nbits);
  void sendDISH(unsigned long data, int nbits);
  void sendSharp(unsigned long data, int nbits);
  // private:
  void enableIROut(int khz);
  VIRTUAL void mark(int usec);
  VIRTUAL void space(int usec);
}
;

// Some useful constants

#define USECPERTICK 50  // microseconds per clock interrupt tick
#define RAWBUF 76 // Length of raw duration buffer

// Marks tend to be 100us too long, and spaces 100us too short
// when received due to sensor lag.
#define MARK_EXCESS 100

#endif



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

#include <IRremote.h>

int RECV_PIN = 2; 

// 使用數位腳位2接收紅外線訊號  Timer2
//預設是 Timer2,發射器要接 pin 3,假如你不想用 pin 3 當作紅外線發射的腳位,
//你有一個選擇,可以換成 Timer1,這樣就可以改用 pin 9 來接紅外線發射器


IRrecv irrecv(RECV_PIN); // 初始化紅外線訊號輸入
decode_results results; // 儲存訊號的結構

void setup()
{
  Serial.begin(9600);
  irrecv.blink13(true); // 設為true的話,當收到訊號時,腳位13的LED便會閃爍
  irrecv.enableIRIn(); // 啟動接收
}

void loop() {
  if (irrecv.decode(&results)) { // 接收紅外線訊號並解碼
    Serial.print("results value is "); // 輸出解碼後的資料
    Serial.print(results.value, HEX);
    Serial.print(", bits is ");
    Serial.print(results.bits);
    Serial.print(", decode_type is ");
    Serial.println(results.decode_type);
    irrecv.resume(); // 準備接收下一個訊號
  }
}



2015年7月26日 星期日

Arduino TimeAlarms Library


TimeAlarms Library

源自於
http://www.pjrc.com/teensy/td_libs_TimeAlarms.html


TimeAlarms, by Michael Margolis, runs functions at specific times. It is means to be used together with the Time libraryDownloadTimeAlarms.zip

Hardware Requirements

TimeAlarms does not require any special hardware, because it uses the time and date provided by the Time library.

Creating Alarms

Alarms are used to call a function at a specific time of the day.
Alarm.alarmRepeat(hours, minutes, seconds, function);
Create an alarm that will call a function every day at a particular time.
Alarm.alarmRepeat(dayofweek, hours, minutes, seconds, function);
Create an alarm that will call a function every week on a specific day at a particular time.
"dayofweek" can be dowSunday, dowMonday, dowTuesday, dowWednesday, dowThursday, dowFriday, or dowSaturday.
Alarm.alarmOnce(hours, minutes, seconds, function);
Create an alarm that will call a function tomorrow at a particular time.
Alarm.alarmOnce(dayofweek, hours, minutes, seconds, function);
Create an alarm that will call a function once, at specific day and time.

Creating Timers

Timers call a function at regular intervals.
Alarm.timerRepeat(seconds, function);
Create a timer that will call a function every at an interval of "seconds".
Alarm.timerOnce(seconds, function);
Create a timer that will call a function once in "seconds".

Normal Running Usage

Alarm.delay(milliseconds);
Alarms and Timers are only checks and their functions called when you use this delay function. You can pass 0 for minimal delay. This delay should be used instead of the normal Arduino delay(), for timely processing of alarms and timers.

Example Program

You can open this example from File > Examples > TimeAlarms > TimeAlarmExample.
/*
 * TimeAlarmExample.pde
 *
 * This example calls alarm functions at 8:30 am and at 5:45 pm (17:45)
 * and simulates turning lights on at night and off in the morning
 * A weekly timer is set for Saturdays at 8:30:30
 *
 * A timer is called every 15 seconds
 * Another timer is called once only after 10 seconds
 *
 * At startup the time is set to Jan 1 2011  8:29 am
 */
 
#include <Time.h>
#include <TimeAlarms.h>

void setup()
{
  Serial.begin(9600);
  setTime(8,29,0,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011
  // create the alarms 
  Alarm.alarmRepeat(8,30,0, MorningAlarm);  // 8:30am every day
  Alarm.alarmRepeat(17,45,0,EveningAlarm);  // 5:45pm every day 
  Alarm.alarmRepeat(dowSaturday,8,30,30,WeeklyAlarm);  // 8:30:30 every Saturday 

 
  Alarm.timerRepeat(15, Repeats);            // timer for every 15 seconds    
  Alarm.timerOnce(10, OnceOnly);             // called once after 10 seconds 
}

void  loop(){  
  digitalClockDisplay();
  Alarm.delay(1000); // wait one second between clock display
}

// functions to be called when an alarm triggers:
void MorningAlarm(){
  Serial.println("Alarm: - turn lights off");    
}

void EveningAlarm(){
  Serial.println("Alarm: - turn lights on");           
}

void WeeklyAlarm(){
  Serial.println("Alarm: - its Monday Morning");      
}

void ExplicitAlarm(){
  Serial.println("Alarm: - this triggers only at the given date and time");       
}

void Repeats(){
  Serial.println("15 second timer");         
}

void OnceOnly(){
  Serial.println("This timer only triggers once");  
}

void digitalClockDisplay()
{
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println(); 
}

void printDigits(int digits)
{
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

2015年7月25日 星期六

Arduino Keyboards-MultipleButtons

Keyboards-MultipleButtons
源自於 
https://arduino-info.wikispaces.com/Keyboards-MultipleButtons

5-Button Keyboard: Uses series resistors and switches to decide a variety of voltages to send to an Arduino Analog Input. 
You can use this same technique for multiple buttons you mount in other ways or orientations.
Diagram (right):



Below: Example code of a 5-button keyboard that uses resistors to connect to a single Analog Input Pin:

/* YourDuino Example 5 Button Analog Keyboard 
 5-button keyboard connected to Analog Input 0
 terry@yourduino.com */

/*-----( Import needed libraries )-----*/
/*-----( Declare Constants and Pin Numbers )-----*/

#define keyboard_AnalogInput 0

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnENTER 4
#define btnNONE   5
/*-----( Declare objects )-----*/
/*-----( Declare Variables )-----*/

int adc_key_in = 0;
int buttonPressed;

void setup()   /****** SETUP: RUNS ONCE ******/
{
  Serial.begin(9600);
  Serial.println("Test 5-button keyboard");
 }   //--(end setup )---


void loop()   /****** LOOP: RUNS CONSTANTLY ******/
{
  buttonPressed = read_keyboard();
  if (buttonPressed != btnNONE)
  {
    Serial.print("OK - That looks like you pressed ");
    Serial.println(buttonPressed, DEC);
  } 
  delay(500);

}  //--(end main loop )---

/*-----( Declare User-written Functions )-----*/
// read the buttons
int read_keyboard()
{
  adc_key_in = analogRead(keyboard_AnalogInput); 
  // read the value from the sensor
  // buttons when read are centered at these values: 0, 144, 329, 504, 741
  // add approx 50 to those values and check to see if we are close
  if (adc_key_in > 1000) return btnNONE; 
  if (adc_key_in < 50) return btnRIGHT;
  if (adc_key_in < 195) return btnUP;
  if (adc_key_in < 380) return btnDOWN;
  if (adc_key_in < 555) return btnLEFT;
  if (adc_key_in < 790) return btnENTER;
  return btnNONE; // when all others fail, return this...
}


//*********( THE END )***********




2015年7月24日 星期五

Arduino 溫濕度計DHT 11

Arduino  溫濕度計DHT 11


DHT-11 是一個結合濕度計和測溫元件量測週遭空氣環境,並與一個高性能8位元單晶片相連接,將所量測到的溫、濕度資料拆解成為數位訊號,再由 data pin腳將資料送出。使用上很簡單,但是抓取資料時必須要特別注意時間的掌控,而且每筆資料的抓取時間間隔要1~2秒鐘,不能太快。與 DHT-22 比較,DHT-11 較不精密與準確且溫濕度量測範圍不大,雖然如此,但對於學習與熟悉溫、濕度感測卻是綽綽有餘,傳輸的距離又可長達20m以上,而且比 DHT-22 較小且便宜許多,是十分方便的簡易測試元件。

其規格如下:
1、濕度測量範圍:20~90%RH;
2、濕度測量精度:±5%RH;
3、溫度測量範圍:0~50℃
4、溫度測量精度:±2℃
5、電源供應範圍: 3~5V
6、頻率不可超過:0.5Hz (每2秒一次)



接線的方法十分簡單,"+"接5V,"-"接GND,data pin接上要輸入的Pin腳。有人說因為數位訊號要接高data電位,所以把data pin外接4.7歐姆電阻至Vcc。不過我曾嘗試不接那4.7k 歐姆,試出來的效果看起來沒有太大的差別。

先下載 library ,丟到Arduino的libraries裡面,然後再開Arduino IDE,去叫<dht.h>


//溫濕度計DHT 11。
#include <dht.h>  
#define dht_dpin 2 //定義訊號要從Pin A0 進來
//I2C + I2C LCD Library
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display
/*==========================================
SDA – 接 Arduino 的 Analog Pin 4 (Arduino Mega 為 Pin 20)
SCL – 接 Arduino 的 Analog Pin 5 (Arduino Mega 為 Pin 21)
GND – 接 GND
VCC – 接 +5V
==========================================*/

dht DHT;

void setup(){
    lcd.init();                      // initialize the lcd
    // Print a message to the LCD.
     lcd.backlight();
    // 輸出初始化文字
    lcd.setCursor(0, 0);                   // 設定游標位置在第1行行首
    lcd.print("Humidity and");
    lcd.setCursor(0, 1);                   // 設定游標位置在第2行行首
    lcd.print("temperature");

    Serial.begin(9600);
    delay(300);             //Let system settle
    Serial.println("Humidity and temperature\n\n");
    delay(700);             //Wait rest of 1000ms recommended delay before
                            //accessing sensor
}

void loop(){
    DHT.read11(dht_dpin);                 //去library裡面找DHT.read11
 
    lcd.setCursor(0, 0);                   // 設定游標位置在第1行行首
    lcd.print("Humidity =");
    lcd.print(DHT.humidity);
    lcd.print("%");
    lcd.setCursor(0, 1);                   // 設定游標位置在第2行行首
    lcd.print("Temp = ");
    lcd.print(DHT.temperature);
    lcd.print("C   ");


    Serial.print("Humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("% ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C ");
    delay(1000);            //每1000ms更新一次
}



參考來源 :

http://ming-shian.blogspot.tw/2014/05/arduino19dht11.html

Arduino Weigand 26bit Decoder ---2

Arduino Weigand 26bit Decoder ---2

In Wiegand 26 / Wiegand 34 / Wiegand 36 and all other Wiegand protocols used 2 wires (D0 and D1) to connect reader to MCU.
In standby D0 and D1 connected to VCC(+5V). All data from reader goes in binary format - If reader transmitting 0, it connecting D0 wire to ground for 20-50mks then connecting back to VCC and waits for 2ms before sending next bit. If goes '1' - D1 will be connected to ground fo 20-50mks and so on.
If no change in lines for more than 2ms - transfer complete.
Picture: 



Wiegand protocol — logic level
In logic level wiegand26 have 26 bit of data, 8 for — facility code, 16 for card number, and 2 for parity control.
Facility code – number of building or company where card is used.
Card number – card number 



/*
 * https://github.com/monkeyboard/Wiegand-Protocol-Library-for-Arduino
 */

#include <Wiegand.h>
//I2C + I2C LCD Library 
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display
/*==========================================
SDA – 接 Arduino 的 Analog Pin 4 (Arduino Mega 為 Pin 20)
SCL – 接 Arduino 的 Analog Pin 5 (Arduino Mega 為 Pin 21)
GND – 接 GND
VCC – 接 +5V
==========================================*/

WIEGAND wg;

void setup() {
    Serial.begin(9600);  
    
    wg.begin();
    lcd.init();                      // initialize the lcd
    // Print a message to the LCD.
     lcd.backlight();
    // 輸出初始化文字
    lcd.setCursor(0, 0); // 設定游標位置在第一行行首
    lcd.clear();
    lcd.setCursor(0, 0);                   // 設定游標位置在第1行行首
    lcd.print("Reading RFID....");
    lcd.setCursor(0, 1);                   // 設定游標位置在第2行行首
    lcd.print("Wiegand 26 bit..");
 }

void loop() {
    if(wg.available())
    {   
        lcd.clear();
        lcd.setCursor(0, 0);                   // 設定游標位置在第1行行首
        lcd.print("DEC Code=");
        lcd.print(wg.getCode()); 
        lcd.setCursor(0, 1);                   // 設定游標位置在第2行行首
        lcd.print("HEX Code=");
        lcd.print(wg.getCode(),HEX); 
         
        Serial.print("Wiegand HEX = ");
        Serial.print(wg.getCode(),HEX);
        Serial.print(", DECIMAL = ");
        Serial.print(wg.getCode());
        Serial.print(", Type W");
        Serial.println(wg.getWiegandType());    
    }
}










參考文件: 


4) 程式庫 

   Wiegand 24 and Wiegand 36 Protocol Library for Arduino


char dat[26]; // 26 bit for data
unsigned char fcode; // for facility code (0..255)
unsigned int code; // for card number (0..65535)

while(){

if(PIND.3==0){ // D1 on ground?
 dat[i]=1; //    bit = 1
 i++;
 while(PIND.3==0){};//waiting for release
}

if(PIND.4==0){// D0 on ground?
 dat[i]=0; //  bit = 0
 i++;
    while(PIND.4==0){}; //waiting for release
}

if(i==27) { // i=27, 26 bits collected
 //now parsing
 b=0;
 for(a=9;a>1;a--){ //first 8bit in revers order
  if(dat[a]==1) fcode=fcode+stepen(b); //if bit =1,
             //adding position^2
         //(2^0 , 2^1 , 2^2 and etc)
  b++; // inc position
 }

 b=0; // reset bit counter

 for(a=25;a>9;a--){//same for next 16 bit (card number)
  if(dat[a]==1) code=code+stepen(b);
  b++;
 }
}


//If all OK, we have
//facility code — in var fcode
//card number – in var code

//Now searching...
//all numbers in 2 arrays in eeprom
//unsigned char fcode[MAX];  - facility code
//unsigned int code[MAX];  - card number
//MAX – number of "lines" in memory
// for attiny2313 - 40 code numbers


for(i=0;i<MAX;i++){//going thru array
 // cheching only  facility code in this step
 if(fcode == fcodedb[i]){ //if code found
  //checking number in same position
  if(code==codedb[i]){ //number found...
              //...we have exact numbers
   card_found=1; // flag = card found
   break;  //breaking - no need to check next lines
  }
    }
}

//card found?
if(card_found){//yes!
 PORTD.5=1;//opening lock
 PORTD.6=0;//GREEN LED
 delay_ms(5000); //5 second to enter
 PORTD.5=0;//locking back
 PORTD.6=1;//turning off LED
} else{ //NO! card not found
 PORTB,0=0;//RED led
 delay_ms(3000); //delay for 3 seconds
 PORTB.0=1;//turn of red led
}

//now clear all data
fcode=0; // facility code
code=0; // card number
i=0; // bit counter
card_found=0; // flag

}
//go to first line... and wait for signal on D0 or D1
}



2024_113_RFID 作業2 ESP32 Arduino程式

2024_113_RFID 作業2 ESP32 Arduino程式  const char broker[] = "test.mosquitto.org"; //const char broker[] = "broker.mqtt-dashboard...