ardunio nano对各种传感器的使用

 1.MQ-2烟雾传感器的使用

#include 



#define Sensor_AO A0

#define Sensor_DO 4



unsigned int sensorValue = 0;



void setup()

{

 pinMode(Sensor_DO, INPUT);

 Serial.begin(9600);

}



void loop()

{

 sensorValue = analogRead(Sensor_AO);// 读取传感器的模拟值并赋值给val,函数的返回值范围是0 到1023

 Serial.print("Sensor AD Value = ");

 Serial.println(sensorValue);



 if (digitalRead(Sensor_DO) == LOW)

 {

  Serial.println("Alarm!");

 }

 delay(1000);

}

2.ardunio对JSON解析

#include //jSON

String comdata;

void setup()

{

 Serial.begin(115200);   

}

void loop()

{

  while (Serial.available() > 0){

    comdata += char(Serial.read()); //每次读一个char字符,并相加

    delay(2);

  }

  if (comdata.length() > 0){

    DynamicJsonDocument jsonBuffer(200);  

    DeserializationError error =deserializeJson(jsonBuffer,comdata);

    Serial.println(comdata);

    if (error) {   

       // Serial.println(comdata);

       return;

    }else{

     if(jsonBuffer["deviceType"]=="RFID" || jsonBuffer["deviceType"]=="addRFID"){

       Serial.println(comdata);

     }

    }

    comdata="";

  }

}

3.使用温湿度传感器dht11

#include 



//定义针脚

#define DHTPIN 5

//定义类型,DHT11或者其它

#define DHTTYPE DHT11

//进行初始设置 

DHT dht(DHTPIN, DHTTYPE);



void setup() {

 Serial.begin(115200);

 dht.begin(); //DHT开始工作

}



void loop() {

 // 两次检测之间,要等几秒钟,这个传感器有点慢。

 delay(2000);

 // 读温度或湿度要用250毫秒

 int h = dht.readHumidity();//读湿度

 int t = dht.readTemperature();//读温度,默认为摄氏度

 Serial.print("Humidity: ");//湿度

 Serial.println(h);

 Serial.print("Temperature: ");//温度

 Serial.print(t);

 Serial.println(" ℃ ");

}

4.使用co2传感器ccs811

#include



Adafruit_CCS811 ccs;



void setup() {

 Serial.begin(115200);

 ccs.begin();

 Serial.println("CCS811 test");

 if(!ccs.begin()){

 Serial.println("Couldn’t find sensor!");

 }

 while(!ccs.available());

 }



void loop() {

 if(ccs.available()){

    if(!ccs.readData()){

      Serial.print("CO2: ");

      Serial.println(ccs.geteCO2());

      Serial.print(" TVOC: ");

      Serial.println(ccs.getTVOC());

     }else{

      Serial.println("ERROR!");

     }

 }

 delay(500);

}

5.使用的是0.96寸的四脚OLED,芯片为ESP-WROOM-32。

#include 

U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);

void setup(void) {

 u8g2.begin();

}



void loop(void) {

 u8g2.setFont(u8g2_font_ncenB10_tr);  

 u8g2.setFontDirection(0);

 u8g2.firstPage();

 do {

  u8g2.setCursor(0, 15);

  u8g2.print("Hello World!");

 } while ( u8g2.nextPage());

 delay(1000);

}

6.使用风扇

//A

const int AA=8;

const int AB=9;

//B

const int BA=6;

const int BB=7;

//byte speed=255;

String comdata = "";

void setup() {

 Serial.begin(115200);

 pinMode(AA,OUTPUT);

 pinMode(AB,OUTPUT);

 pinMode(BA,OUTPUT);

 pinMode(BB,OUTPUT);

}

void loop() {

  

   while (Serial.available() > 0){

    comdata += char(Serial.read()); //每次读一个char字符,并相加

    delay(2);

  }

  if (comdata.length() > 0){

    

    //Serial.print(comdata);

     if(comdata=="1z")

     {//电机风扇正转

      digitalWrite(AA,HIGH);

      digitalWrite(AB,LOW);

     }

     if(comdata=="1f"){  

      digitalWrite(AA,LOW);

      digitalWrite(AB,HIGH);

     }

     if(comdata=="1t"){

      digitalWrite(AA,LOW);

      digitalWrite(AB,LOW);

     }

     if(comdata=="2z")

     {//电机风扇正转

      digitalWrite(BA,HIGH);

      digitalWrite(BB,LOW);

     }

     if(comdata=="2f"){  

      digitalWrite(BA,LOW);

      digitalWrite(BB,HIGH);

     }

     if(comdata=="2t"){

      digitalWrite(BA,LOW);

      digitalWrite(BB,LOW);

     }

    comdata = "";      

  }

}

7.使用光照传感器

#include  //IIC库

#include  

 //VCC,GND,SCL,SDA和ADDR。五个引脚分别接上Arduino UNO的3.3V,GND,A5与A4接口,ADDR引脚悬空不接。

int BH1750address = 0x23;//芯片地址为16位23

byte buff[2];

void setup(){

 pinMode(13,OUTPUT);

 Wire.begin();

 Serial.begin(9600);

}



void loop(){

 int i;

 uint16_t val=0;

 BH1750_Init(BH1750address);

 delay(100);

 if(2==BH1750_Read(BH1750address)) {

  val=((buff[0]<<8)|buff[1])/1.2;

  Serial.print(val,DEC);   

  Serial.println("[lx]"); 

 }

 delay(150);

 if (val<100) {

  digitalWrite(13,HIGH);

 }

 else {

  digitalWrite(13,LOW);

 }

}

int BH1750_Read(int address) {

 int i=0;

 Wire.beginTransmission(address);

 Wire.requestFrom(address, 2);

 while(Wire.available()) {

  buff[i] = Wire.read(); // read one byte

  i++;

 }

 Wire.endTransmission();  



 return i;

}

void BH1750_Init(int address) {

 Wire.beginTransmission(address);

 Wire.write(0x10);//1lx reolution 120ms

 Wire.endTransmission();

}

8.利用EEPROM实现控制存储

#include 

#include 

int a;

int value;

String comdata;

void setup()

{

 Serial.begin(115200);

 //EEPROM.write(0,12);

}



void loop()

{

 value = EEPROM.read(0);

 Serial.println(value);

  while (Serial.available() > 0)  

  { 

    comdata+= char(Serial.read());   

  }

  if(comdata.length() > 0){

    DynamicJsonDocument jsonBuffer(200);  //解析json

    // 反序列化JSON

    DeserializationError error =deserializeJson(jsonBuffer,comdata);

    if(error){

     Serial.println(comdata);

    }else{

     if(jsonBuffer["deviceType"]=="B"){

      a=jsonBuffer["mesValue"];

      EEPROM.write(0,a);

       delay(3);

     }   

    }   

    comdata="";  

  }

 delay(1500);

}

9.使用JSON来控制RFID进行写入和读取

#include 

#include 

#include

#include 

typedef struct{

 byte bookId[32];    

 byte bookName[64];    

 byte bookLocation[64];  

}Library;

#define pinBuzzer 4

#define RST_PIN     9      // Configurable, see typical pin layout above

#define SS_PIN     10     // Configurable, see typical pin layout above



MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

MFRC522::MIFARE_Key key;

MFRC522::StatusCode status;



Library library;   //实例化一个结构体变量



byte block;

byte len;

String comdata;

String bookId;

String bookName;

String bookLocation;

const int bookNameBlockAddr[3] = {48,28,30};  //名称的存储地址

void setup() {

 Serial.begin(115200);    // Initialize serial communications with the PC

 SPI.begin();        // Init SPI bus

 mfrc522.PCD_Init();    // Init MFRC522 card

 for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;   

}

void loop(){

 while (Serial.available() > 0){

    comdata = Serial.readString();  

 }

 if (comdata.length() > 0){  

    

      if(comdata=="1")

      {

       // 寻找新卡

       while ( ! mfrc522.PICC_IsNewCardPresent()) 

       {

        delay(1000);   

       }     

       // 选择一张卡

       if ( ! mfrc522.PICC_ReadCardSerial()) {

        return;

       }      

       // mfrc522.PICC_DumpDetailsToSerial(&(mfrc522.uid)); //转储有关卡的一些详细信息     

       len = 18;

       for(int i = 0; i < 3;i++)

       {

        //在uid为mfrc522.uid的卡的trailerBlock块(此块为扇区控制块)验证key是否与A密码相同

        status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, bookNameBlockAddr[i], &key, &(mfrc522.uid)); 

        if (status != MFRC522::STATUS_OK) {

         break;

        }

        //读取len个第bookNameBlockAddr[i]块的数据到library.bookId[i*16]

        if(i==0){

         status = mfrc522.MIFARE_Read(bookNameBlockAddr[i], &library.bookId[32], &len);

        }else if(i==1){

         status = mfrc522.MIFARE_Read(bookNameBlockAddr[i], &library.bookName[64], &len);

        }else{

         status = mfrc522.MIFARE_Read(bookNameBlockAddr[i], &library.bookLocation[64], &len);

        }

        if (status != MFRC522::STATUS_OK) {

         break;

        }

       }     

       //发送读到的数据给串口

        

       for (uint8_t i = 0; i < sizeof(library.bookId)&& library.bookId[i]; i++)

       { 

         bookId+=char(library.bookId[i]);

       }

       for (uint8_t i = 0; i < sizeof(library.bookName) && library.bookName[i]; i++)

       {

        bookName+=char(library.bookName[i]);

       }

       for (uint8_t i = 0; i < sizeof(library.bookLocation) && library.bookLocation[i]; i++)

       {

        bookLocation+=char(library.bookLocation[i]);

       }

       //此处将三个数据用json格式发送  =====================      

       Serial.print("{\"deviceType\":\"bookRFID\",\"bookId\":\""+bookId+"\"");

       //Serial.print(bookId);

       //Serial.print("1");

       Serial.print(",\"bookName\":\""+bookName+"\"");

       // Serial.print(bookName);

       // Serial.print(",\"bookLocation\":");

       //Serial.print(bookLocation);

        Serial.print(",\"bookLocation\":\""+bookLocation+"\"");  

       Serial.println("}");     

       //蜂鸣器发出声音1s可以用delay

       digitalWrite(pinBuzzer, HIGH); //有障碍时

        delay(50); 

        digitalWrite(pinBuzzer,LOW);

       mfrc522.PICC_HaltA();

       mfrc522.PCD_StopCrypto1();

       bookId="";

       bookName="";

       bookLocation="";

      }

      //写标签

     else if(comdata=="2")

      {

       // 寻找一张新卡

       while( ! mfrc522.PICC_IsNewCardPresent())

       {

        delay(1000);

       }

       // 选择一张卡

       if ( ! mfrc522.PICC_ReadCardSerial()) {

        return;

       }

       String mes1="meilinsen";

       String mes2="meilinsen";

       String mes3="meilinsen";

       if(mes1){

        mes1.getBytes(library.bookId,-1);

        mes2.getBytes(library.bookName,-1);

        mes3.getBytes(library.bookLocation,-1);

       }     

       for(int i = 0; i < 3; i++)

       {

        status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, bookNameBlockAddr[i], &key, &(mfrc522.uid));

        if (status != MFRC522::STATUS_OK) {

         break;

        }    

        // Write block

        if(i==0){

          status = mfrc522.MIFARE_Write(bookNameBlockAddr[i], &library.bookId[32], 16);

        }

        else if(i==1){

         status = mfrc522.MIFARE_Write(bookNameBlockAddr[i], &library.bookName[64], 16);

        }else{

         status = mfrc522.MIFARE_Write(bookNameBlockAddr[i], &library.bookLocation[64], 16);

        }

        if (status != MFRC522::STATUS_OK) {

         break;

        }

       }

       //蜂鸣器发出声音1s可以用delay

       digitalWrite(pinBuzzer, HIGH); //有障碍时

        delay(50); 

        digitalWrite(pinBuzzer,LOW);

       //================================

       mfrc522.PICC_HaltA(); // 使放置在读卡区的IC卡进入休眠状态,不再重复读卡,Halt(停止)

       mfrc522.PCD_StopCrypto1(); // 停止读卡模块编码

      }



     }

   comdata = "";   

}



10.(综合)使用JSON来控制步进电机和风扇正反转,使用红外对射,LED灯,EEPROM存储等

#include 

#include

#include //存储

#include 

#include 

const byte IRPin = 12;  //红外对射,管脚D12

const byte ledPin = 7;  //LED,管脚D9

int pinBuzzer = 6;    //蜂鸣器,管脚D5 

//A

const int AA=2;

const int AB=3;

//B

const int BA=4;

const int BB=5;

//byte speed=255;

String comdata = "";

//红外对射

int flag=0;

//状态:0表示自动,1表示手动

int type=0;



//温度值和阈值

int t;

int t1;

int t2;



//光照

int l;

int L1;

// 定义电机控制用常量

int d=1;

// 电机内部输出轴旋转一周步数

const int STEPS_PER_ROTOR_REV = 32; 

// 减速比

const int GEAR_REDUCTION = 64;

const float STEPS_PER_OUT_REV = STEPS_PER_ROTOR_REV * GEAR_REDUCTION;

Stepper steppermotor(STEPS_PER_ROTOR_REV, 8, 10, 9, 11); 

int StepsRequired;

void sendMes(){

  Serial.print("{\"myName\":\"XiaoLiTongXue\",\"deviceType\":\"B\",\"flag\":");

  Serial.print(flag);   

  Serial.println("}");

}

void autoController(){//自动控制

 if(type==0){

  if(t>=t1){//风扇1打开

    digitalWrite(AA,LOW);

    digitalWrite(AB,HIGH);

  }else{//风扇1关闭

   digitalWrite(AA,LOW);

   digitalWrite(AB,LOW);

  }

  if(t>=t2){//风扇都打开

    digitalWrite(BA,LOW);

    digitalWrite(BB,HIGH);

  }else{//风扇关闭

   digitalWrite(BA,LOW);

   digitalWrite(BB,LOW);

  }

  if(lL1 && d==0){//步进电机反转5秒

   StepsRequired = - STEPS_PER_OUT_REV;  

   steppermotor.setSpeed(400);  

   steppermotor.step(StepsRequired);

   d=1;

    digitalWrite(ledPin, LOW);   //设置LED灯

   }

  }

}

void setup() {

 Serial.begin(115200);

 pinMode(AA,OUTPUT);

 pinMode(AB,OUTPUT);

 pinMode(BA,OUTPUT);

 pinMode(BB,OUTPUT);

 pinMode(IRPin, INPUT);   //红外对射开关

 pinMode(ledPin, OUTPUT);  //LED端口设定成“输出”

 pinMode(pinBuzzer,OUTPUT); //设置pinBuzzer脚为输出状态

 digitalWrite(pinBuzzer,LOW);//设置蜂鸣器灯初始状态为0

 digitalWrite(ledPin, LOW); //设置LED灯初始状态为0

 MsTimer2::set(1000,sendMes);

 MsTimer2::start();

}

void loop() {

  t1=EEPROM.read(0);

  t2=EEPROM.read(1);

  L1=EEPROM.read(2);

  while (Serial.available() > 0){

    comdata += char(Serial.read()); //每次读一个char字符,并相加

    delay(2);

    //Serial.print(comdata);  

  }

  if (comdata.length() > 0){  

    DynamicJsonDocument jsonBuffer(200);  //解析json

    // 反序列化JSON

    DeserializationError error =deserializeJson(jsonBuffer,comdata);

    //delay(20);

    if (error) {   

       Serial.println(comdata);

       return;

     } 

    else{ 

     //Serial.println(comdata);

     if(jsonBuffer["deviceType"]=="autoController"){

      type=0;

      d=0;

      }

     if(jsonBuffer["deviceType"]=="quitController"){

      type=1;

     }

     if(jsonBuffer["deviceType"]=="A"){//得到温度值

      t=jsonBuffer["temperature"]; 

      l=jsonBuffer["luminosity"];

     }

     if(type==1){//手动

      if(jsonBuffer["mesValue"]=="df"){//步进电机正转

         // 顺时针一次旋转

       StepsRequired = STEPS_PER_OUT_REV; 

       steppermotor.setSpeed(1000);  

       steppermotor.step(StepsRequired);

       }

       if(jsonBuffer["mesValue"]=="dz"){//步进电机反转

        // 逆时针一次旋转

        StepsRequired = - STEPS_PER_OUT_REV;  

        steppermotor.setSpeed(1000);  

        steppermotor.step(StepsRequired);

       }

       if(jsonBuffer["mesValue"]=="1z"){//电机风扇正转        

         digitalWrite(AA,HIGH);

         digitalWrite(AB,LOW);

        }

       if(jsonBuffer["mesValue"]=="1f"){  

         digitalWrite(AA,LOW);

         digitalWrite(AB,HIGH);

       }

       if(jsonBuffer["mesValue"]=="1t"){

         digitalWrite(AA,LOW);

         digitalWrite(AB,LOW);

       }

       if(jsonBuffer["mesValue"]=="2z"){//电机风扇正转

         digitalWrite(BA,HIGH);

         digitalWrite(BB,LOW);

       }

       if(jsonBuffer["mesValue"]=="2f"){  

         digitalWrite(BA,LOW);

         digitalWrite(BB,HIGH);

       }

       if(jsonBuffer["mesValue"]=="2t"){

         digitalWrite(BA,LOW);

         digitalWrite(BB,LOW);

       } 

       if(jsonBuffer["mesValue"]=="open"){

         digitalWrite(ledPin, HIGH);  

       }

       if(jsonBuffer["mesValue"]=="close"){

         digitalWrite(ledPin, LOW);  

       }  

      }

     else{

       if(jsonBuffer["deviceType"]=="setT1"){//设置温度阈值1

        t1=jsonBuffer["mesValue"];

        EEPROM.write(0,t1);

        delay(5);

       }

       if(jsonBuffer["deviceType"]=="setT2"){

        t2=jsonBuffer["mesValue"];

        EEPROM.write(1,t2);

        delay(5);

       }

       if(jsonBuffer["deviceType"]=="setL1"){

        L1=jsonBuffer["mesValue"];

        d=0;

        EEPROM.write(2,L1);

        delay(5);

       }

      }

    }        

    comdata = "";      

  } 

  //自动

  autoController();

   //红外设备断开,蜂鸣器响,LED灯闪烁8秒

  boolean IR = digitalRead(IRPin); //要不要放函数前面

  if (IR) {

   digitalWrite(pinBuzzer, LOW); //没有阻拦时

   digitalWrite(ledPin, LOW);  

   flag=0;  

  } else {

   flag=1;

   digitalWrite(pinBuzzer, HIGH); //有障碍时

   //digitalWrite(ledPin, HIGH);   //设置LED灯

   //delay(3000);

  }

}

你可能感兴趣的:(ardunio,nano,c语言,物联网,嵌入式硬件)