读取空气检测器程序
#include <OneWire.h>
#include <Wire.h>
int dustPin=0;
int dustVal=0;
String dust=”";
int ledPower=2;
int delayTime=280;
int delayTime2=40;
float offTime=9680;
void setup(){
Wire.begin(5);
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
Serial.begin(9600);
pinMode(ledPower,OUTPUT);
}
void loop(){
getDust();
}
void requestEvent()
{
char charBuf[dust.length()+1];
dust.toCharArray(charBuf, dust.length()+1);
Wire.write(charBuf);
}
void receiveEvent(int howMany)
{
while (1 < Wire.available()) // loop through all but the last
{
char c = Wire.read(); // receive byte as a character
Serial.print(c); // print the character
}
int x = Wire.read(); // receive byte as an integer
Serial.print(x); // print the integer
}
void getDust(){
digitalWrite(ledPower,LOW); // power on the LED
delayMicroseconds(delayTime);
dustVal=analogRead(dustPin);
if(dustVal<10){
dust=”000″+String(dustVal);
}else if(dustVal<100){
dust=”00″+String(dustVal);
}else if(dustVal<1000){
dust=”0″+String(dustVal);
}else{
dust=String(dustVal);
}
delayMicroseconds(delayTime2);
digitalWrite(ledPower,HIGH); // turn the LED off
delayMicroseconds(offTime);
delay(3000);
Serial.println(dust);
}
需要先下载OneWire
发表评论