Arduino笔记

September 16, 2019 访问: 47 次

已添加

  • DHT22 温湿度传感器
  • RGB三色LED模块
  • MQ-5 可燃气体传感器
  • MQ-135 TVOC传感器
  • GL5516/28/39光敏电阻

未完成

  • ESP8266串口WIFI(模块可能有问题,串口接收不到正确数据)

待添加

  • GY-2561 光强模块
  • GY-302 数字光强模块
  • 12864 显示模块
  • 雨滴传感器
  • 水位传感器

功能

雨滴传感器

无水:DO输出高电平,指示灯灭,数字信号1
有水:DO输出低电平,指示灯亮,数字信号0

传感器代码
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor

#include "DHT.h"

#define DHTPIN 2 // Digital pin connected to the DHT sensor
// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22 // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);


// RGB
int rPin = 7;
int gPin = 6;
int bPin = 5;

// MQ-5
// 数字信号
int MQFiveSensorDigital = 4;
int gasValueDigital;
//模拟信号
int MQFiveSensorAnalog = A0;
float gasValueAnalog;

// MQ-135
// 数字信号
int MQSensorDigital_135 = 8;
int gasValueDigital_135;
//模拟信号
int MQSensorAnalog_135 = A1;
float gasValueAnalog_135;

// 光敏电阻
int lightSensorPin = A2;
int lightValue = 0; // 光照度值

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

  dht.begin();

  // RGB
  pinMode(rPin, OUTPUT);
  pinMode(gPin, OUTPUT);
  pinMode(bPin, OUTPUT);

  // MQ-5
  pinMode(MQFiveSensorDigital, INPUT); //数字信号
  pinMode(MQFiveSensorAnalog, INPUT);  // 模拟信号
  // MQ-135
  pinMode(MQSensorDigital_135, INPUT); //数字信号
  pinMode(MQSensorAnalog_135, INPUT);  // 模拟信号

}

void loop()
{
  // Wait a few seconds between measurements.
  delay(2000);

  // rgb();

  dht_22();

  MQ_5();

  MQ_135();

  light_0();

  Serial.println();
  Serial.println(F("--------------------"));
  Serial.println();
}

void setColor(int red, int green, int blue)
{
  analogWrite(rPin, red);
  analogWrite(gPin, green);
  analogWrite(bPin, blue);
}

void rgb()
{
  // RGB
  // setColor(0, 255, 255);
  // delay(100);
  for (int i = 200; i > 0; i--)
  {
    setColor(i, i, 255);
    delay(10);
  }
  for (int i = 0; i < 200; i++)
  {
    setColor(255, i, i);
    delay(10);
  }
}

void MQ_135()
{
  gasValueDigital_135 = digitalRead(MQSensorDigital_135);
  gasValueAnalog_135 = analogRead(MQSensorAnalog_135);
  // Serial.print(gasValueDigital);
  if (gasValueDigital_135 == 1)
  {
    Serial.print(F("当前空气质量较好,TVOC指数为:"));
    Serial.println(gasValueAnalog_135);
  }
  else
  {
    Serial.print(F("当前空气质量较差!,TVOC指数为:"));
    Serial.println(gasValueAnalog_135);
    setColor(255, 0, 0);
    delay(100);
    setColor(0, 0, 0);
    delay(100);
  }
}

void MQ_5()
{
  gasValueDigital = digitalRead(MQFiveSensorDigital);
  gasValueAnalog = analogRead(MQFiveSensorAnalog);
  Serial.print(gasValueDigital);
  if (gasValueDigital == 1)
  {
    Serial.print(F("当前安全,气体浓度为:"));
    Serial.println(gasValueAnalog);
  }
  else
  {
    Serial.print(F("可燃气体发生泄漏!,气体浓度为:"));
    Serial.println(gasValueAnalog);
    setColor(255, 0, 0);
    delay(100);
    setColor(0, 0, 0);
    delay(100);
  }
}

void dht_22()
{
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  // float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  // if (isnan(h) || isnan(t) || isnan(f)) {
  if (isnan(h) || isnan(t))
  {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  // float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print(F("湿度: "));
  Serial.print(h);
  Serial.print(F("%  温度: "));
  Serial.print(t);
  Serial.print(F("°C "));
  // Serial.print(f);
  Serial.print(F("  体感温度: "));
  Serial.print(hic);
  Serial.println(F("°C "));
  // Serial.print(hif);
  // Serial.println(F("°F"));
}

void light_0()
{
  lightValue = analogRead(lightSensorPin);
  Serial.print(F("光照值:"));
  Serial.println(lightValue);
}
esp8266代码

该芯片为esp-01s优化版本
使用原厂arduino做软串口,测试多个波特率,该芯片均不能正确返回,等待usb-ttl连接测试

#include "SoftwareSerial.h"
 
SoftwareSerial mySerial(2, 3); // RX, TX
 
void setup() {
  Serial.begin(115200);
  
  // Open serial communications and wait for port to open:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
 
 
  Serial.println("Goodnight moon!");
 
  // set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
  mySerial.println("Hello, world?");
}
 
void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}
GY-302
#include <Wire.h> //IIC
#include <math.h> 

int BH1750address = 0x23; 
byte buff[2];

void setup()
{
  Wire.begin();
  Serial.begin(9600);
}

void loop()
{
 int i;

 uint16_t val=0;
 BH1750_Init(BH1750address);
 delay(200);

 if(2==BH1750_Read(BH1750address))
  {
   val=((buff[0]<<8)|buff[1])/1.2;
   Serial.print(val,DEC);     
   Serial.println("[lx]"); 
  }

 delay(150);
}

int BH1750_Read(int address) //
{
  int i=0;
  Wire.beginTransmission(address);
  Wire.requestFrom(address, 2);
  
  while(Wire.available()) //
  {
    buff[i] = Wire.receive();  // receive one byte
    i++;
  }

  Wire.endTransmission();  
  return i;
}

void BH1750_Init(int address) 
{
  Wire.beginTransmission(address);
  Wire.send(0x10);//1lx reolution 120ms
  Wire.endTransmission();
}
GY-2561
/* SFE_TSL2561 library example sketch

This sketch shows how to use the SFE_TSL2561
library to read the AMS/TAOS TSL2561
light sensor.

Product page: https://www.sparkfun.com/products/11824
Hook-up guide: https://learn.sparkfun.com/tutorials/getting-started-with-the-tsl2561-luminosity-sensor

Hardware connections:

3V3 to 3.3V
GND to GND

(WARNING: do not connect 3V3 to 5V
or the sensor will be damaged!)

You will also need to connect the I2C pins (SCL and SDA) to your Arduino.
The pins are different on different Arduinos:

                    SDA    SCL
Any Arduino         "SDA"  "SCL"
Uno, Redboard, Pro  A4     A5
Mega2560, Due       20     21
Leonardo            2      3

You do not need to connect the INT (interrupt) pin
for basic operation.

Operation:

Upload this sketch to your Arduino, and open the
Serial Monitor window to 9600 baud.

Have fun! -Your friends at SparkFun.

Our example code uses the "beerware" license.
You can do anything you like with this code.
No really, anything. If you find it useful,
buy me a beer someday.

V10 Mike Grusin, SparkFun Electronics 12/26/2013
*/

// Your sketch must #include this library, and the Wire library
// (Wire is a standard library included with Arduino):

#include <SFE_TSL2561.h>
#include <Wire.h>

// Create an SFE_TSL2561 object, here called "light":

SFE_TSL2561 light;

// Global variables:

boolean gain;     // Gain setting, 0 = X1, 1 = X16;
unsigned int ms;  // Integration ("shutter") time in milliseconds

void setup()
{
  // Initialize the Serial port:
  
  Serial.begin(9600);
  Serial.println("TSL2561 example sketch");

  // Initialize the SFE_TSL2561 library

  // You can pass nothing to light.begin() for the default I2C address (0x39),
  // or use one of the following presets if you have changed
  // the ADDR jumper on the board:
  
  // TSL2561_ADDR_0 address with '0' shorted on board (0x29)
  // TSL2561_ADDR   default address (0x39)
  // TSL2561_ADDR_1 address with '1' shorted on board (0x49)

  // For more information see the hookup guide at: https://learn.sparkfun.com/tutorials/getting-started-with-the-tsl2561-luminosity-sensor

  light.begin();

  // Get factory ID from sensor:
  // (Just for fun, you don't need to do this to operate the sensor)

  unsigned char ID;
  
  if (light.getID(ID))
  {
    Serial.print("Got factory ID: 0X");
    Serial.print(ID,HEX);
    Serial.println(", should be 0X5X");
  }
  // Most library commands will return true if communications was successful,
  // and false if there was a problem. You can ignore this returned value,
  // or check whether a command worked correctly and retrieve an error code:
  else
  {
    byte error = light.getError();
    printError(error);
  }

  // The light sensor has a default integration time of 402ms,
  // and a default gain of low (1X).
  
  // If you would like to change either of these, you can
  // do so using the setTiming() command.
  
  // If gain = false (0), device is set to low gain (1X)
  // If gain = high (1), device is set to high gain (16X)

  gain = 0;

  // If time = 0, integration will be 13.7ms
  // If time = 1, integration will be 101ms
  // If time = 2, integration will be 402ms
  // If time = 3, use manual start / stop to perform your own integration

  unsigned char time = 2;

  // setTiming() will set the third parameter (ms) to the
  // requested integration time in ms (this will be useful later):
  
  Serial.println("Set timing...");
  light.setTiming(gain,time,ms);

  // To start taking measurements, power up the sensor:
  
  Serial.println("Powerup...");
  light.setPowerUp();
  
  // The sensor will now gather light during the integration time.
  // After the specified time, you can retrieve the result from the sensor.
  // Once a measurement occurs, another integration period will start.
}

void loop()
{
  // Wait between measurements before retrieving the result
  // (You can also configure the sensor to issue an interrupt
  // when measurements are complete)
  
  // This sketch uses the TSL2561's built-in integration timer.
  // You can also perform your own manual integration timing
  // by setting "time" to 3 (manual) in setTiming(),
  // then performing a manualStart() and a manualStop() as in the below
  // commented statements:
  
  // ms = 1000;
  // light.manualStart();
  delay(ms);
  // light.manualStop();
  
  // Once integration is complete, we'll retrieve the data.
  
  // There are two light sensors on the device, one for visible light
  // and one for infrared. Both sensors are needed for lux calculations.
  
  // Retrieve the data from the device:

  unsigned int data0, data1;
  
  if (light.getData(data0,data1))
  {
    // getData() returned true, communication was successful
    
    Serial.print("data0: ");
    Serial.print(data0);
    Serial.print(" data1: ");
    Serial.print(data1);
  
    // To calculate lux, pass all your settings and readings
    // to the getLux() function.
    
    // The getLux() function will return 1 if the calculation
    // was successful, or 0 if one or both of the sensors was
    // saturated (too much light). If this happens, you can
    // reduce the integration time and/or gain.
    // For more information see the hookup guide at: https://learn.sparkfun.com/tutorials/getting-started-with-the-tsl2561-luminosity-sensor
  
    double lux;    // Resulting lux value
    boolean good;  // True if neither sensor is saturated
    
    // Perform lux calculation:

    good = light.getLux(gain,ms,data0,data1,lux);
    
    // Print out the results:
    
    Serial.print(" lux: ");
    Serial.print(lux);
    if (good) Serial.println(" (good)"); else Serial.println(" (BAD)");
  }
  else
  {
    // getData() returned false because of an I2C error, inform the user.

    byte error = light.getError();
    printError(error);
  }
}

void printError(byte error)
  // If there's an I2C error, this function will
  // print out an explanation.
{
  Serial.print("I2C error: ");
  Serial.print(error,DEC);
  Serial.print(", ");
  
  switch(error)
  {
    case 0:
      Serial.println("success");
      break;
    case 1:
      Serial.println("data too long for transmit buffer");
      break;
    case 2:
      Serial.println("received NACK on address (disconnected?)");
      break;
    case 3:
      Serial.println("received NACK on data");
      break;
    case 4:
      Serial.println("other error");
      break;
    default:
      Serial.println("unknown error");
  }
}


添加新评论