超声波连线:
TrigPin连4号数字口; EchoPin连5号数字口;
温湿度传感器连线:
datapin连3号数字口;
编写如下代码
humiture.c
//定义引脚 #define PIN_humiture 3 uint8_t bits[5]; //40bit信息 uint8_t cnt = 7; uint8_t idx = 0; int humidity; int temperature; // const int TrigPin = 4; const int EchoPin = 5; float distance; bool Distance() { // 产生一个10us的高脉冲去触发TrigPin digitalWrite(TrigPin, LOW); delayMicroseconds(2); digitalWrite(TrigPin, HIGH); delayMicroseconds(10); digitalWrite(TrigPin, LOW); // 检测脉冲宽度,并计算出距离 distance = pulseIn(EchoPin, HIGH) / 58.00; if(distance > 25.0) return false; //为了方便突显结果,我们使用25cm else { Serial.println("Hello"); Serial.println(distance); return true; } } // int read() { //主机开始信号 pinMode(PIN_humiture, OUTPUT); digitalWrite(PIN_humiture, LOW); delay(18);//主机至少拉低18ms digitalWrite(PIN_humiture, HIGH); delayMicroseconds(40);//主机拉高40us //DHT11发送信号,引脚作为输入 pinMode(PIN_humiture, INPUT); //检查电平是否变化响应80us,拉高80us unsigned int loopCnt = 10000; while(digitalRead(PIN_humiture) == LOW) if (loopCnt-- == 0) return 0; loopCnt = 10000; while(digitalRead(PIN_humiture) == HIGH) if (loopCnt-- == 0) return 0; //读出数据并处理 for (int i=0; i<40; i++) { //检测时序 loopCnt = 10000; while(digitalRead(PIN_humiture) == LOW) if (loopCnt-- == 0) return 0; unsigned long t = micros(); loopCnt = 10000; while(digitalRead(PIN_humiture) == HIGH) if (loopCnt-- == 0) return 0; //循环移位写入 if ((micros() - t) > 40) bits[idx] |= (1 << cnt);//数据位写入 if (cnt == 0) // next byte? { cnt = 7; // restart at MSB idx++; // next byte! } else cnt--; } /*** 数据格式 8bit湿度整数数据+8bit湿度小数数据(为0,便于拓展) 8bit温度整数数据+8bit温度小数数据(为0,便于拓展) +8bit校验和 ***/ humidity = bits[0]; temperature = bits[2]; uint8_t sum = bits[0] + bits[2]; //检验位不符合就报错 if (bits[4] != sum) return 0; } void setup() { Serial.begin(9600); pinMode(TrigPin, OUTPUT); // 要检测引脚上输入的脉冲宽度,需要先设置为输入状态 pinMode(EchoPin, INPUT); //初始化 for (int i=0; i< 5; i++) bits[i] = 0; } void loop() { if(Distance() == true) { read(); Serial.print("Humidity (%): "); Serial.print((float)humidity, 2); Serial.print(" "); Serial.print("Temperature (oC): "); Serial.println((float)temperature, 2); delay(500); } }