主页 > 硬件 > 修正I2C通讯程序

修正I2C通讯程序

2014年5月30日 修正I2C通讯程序无评论 阅读: 11,214 次

#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

参考:

12

12

发表评论

新用户的评论需审核后才会显示;

电子邮件地址不会被公开;
必填项已用*标注