实验程序:水流量传感器控制5V继电器和LCD1602 I2C模块 (1)Arduino参考开源代码
- /*
- 【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
- 程序十二:用LCD1602A屏显示水流量传感器输出
- 实验说明:D2处接10K上拉电阻(另一端接VCC)
- 实验接线:Uno D2接流量传感器OUT,继电器接D4
- Arduino------LCD1602
- 5V-------------VCC
- GND-----------GND
- A4-----------SDA IIC 数据线
- A5-----------SCL IIC 时钟线
- */
- #include <LiquidCrystal_I2C.h> //包括 LiquidCrystal 库
- LiquidCrystal_I2C lcd(0x27, 16, 2);
- #define FLOWSENSORPIN 2 //连接到 Arduino 数字引脚 2 的水流传感器
- #define relayPin 4 // 连接到 Arduino 数字引脚 4 的 5v 继电器模块
- volatile uint16_t pulses = 0; // 计算多少个脉冲
- volatile uint8_t lastflowpinstate; // 跟踪脉冲引脚的状态
- volatile uint32_t lastflowratetimer = 0; //您可以尝试保持脉冲之间的时间间隔
- volatile float flowrate; // 并使用它来计算流量
- // 每毫秒调用一次中断,寻找来自传感器的任何脉冲!
- SIGNAL(TIMER0_COMPA_vect) {
- uint8_t x = digitalRead(FLOWSENSORPIN);
- if (x == lastflowpinstate) {
- lastflowratetimer++;
- return; // 没有改变!
-
- if (x == HIGH) //从低到高的过渡!
- pulses++;
- }
- lastflowpinstate = x;
- flowrate = 1000.0;
- flowrate /= lastflowratetimer; // 以赫兹为单位
- lastflowratetimer = 0;
- }
- void useInterrupt(boolean v) {
- if (v) { // Timer0 已经用于 millis() - 我们将在某处中断
- // 在中间并调用上面的“比较A”函数
- OCR0A = 0xAF;
- TIMSK0 |= _BV(OCIE0A);
- } else { // 不再调用中断函数 COMPA
- TIMSK0 &= ~_BV(OCIE0A);
- }
- }
- void setup() {
- Serial.begin(9600);
- Serial.println("---水流量传感器准备就绪---");
- lcd.init(); // 初始化液晶显示器
- lcd.backlight();
- lcd.begin(16, 2); //16X2液晶显示器
- lcd.setBacklight(HIGH);
- lcd.setCursor(0, 0); //设置显示位置
- lcd.print("Aqua counter");
- pinMode(FLOWSENSORPIN, INPUT); //将水流量传感器设置为输入
- pinMode(relayPin, OUTPUT); //将继电器模块设置为输出
- digitalWrite(relayPin, LOW);
- digitalWrite(FLOWSENSORPIN, HIGH);//可选的内部上拉
- lastflowpinstate = digitalRead(FLOWSENSORPIN);
- useInterrupt(true);
- delay(2000);
- lcd.clear();
- }
- void loop(){
- lcd.setCursor(0, 0);
- lcd.print("Pulses:");
- lcd.print(pulses, DEC);
- lcd.print(" Hz:");
- lcd.print(flowrate);
- //lcd.print(flowrate);
- Serial.print("频率:");
- Serial.println(flowrate);
- Serial.print("脉冲:");
- Serial.println(pulses, DEC);
- // if a plastic sensor use the following calculation
- // Sensor Frequency (Hz) = 7.5 * Q (Liters/min)
- // Liters = Q * time elapsed (seconds) / 60 (seconds/minute)
- // Liters = (Frequency (Pulses/second) / 7.5) * time elapsed (seconds) / 60
- // Liters = Pulses / (7.5 * 60)
- float liters = pulses;
- liters /= 7.5;
- liters /= 60.0;
- /*
- // if a brass sensor use the following calculation
- float liters = pulses;
- liters /= 8.1;
- liters -= 6;
- liters /= 60.0;
- */
- Serial.print(liters);
- Serial.println(" 升");
- lcd.setCursor(0, 1);
- lcd.print(liters);
- lcd.print(" Litres ");
- if (liters >= 0.15) //限水设置
- {
- digitalWrite(relayPin, HIGH);
- }
- else {
- digitalWrite(relayPin, LOW);
- }
- delay(2000);
- lcd.clear();
- }
复制代码
|