micro:bit是否能连外接的温度测量模块测水温?
2018-01-081万
AI 快速预览详细
本文介绍了如何使用micro:bit连接外接温度测量模块来测量水温。文章详细说明了使用DS18B20数字温度传感器的具体步骤和代码设置方法,解决了热敏电阻无法准确测量水温的问题。通过这种方法,用户可以轻松实现水温的精确测量,适用于STEM教育和儿童科学实验。
创作许可协议
本项目采用 None(不开放任何权利,保留所有权利) 进行许可。
创作许可协议
本项目采用 None(不开放任何权利,保留所有权利) 进行许可。
https://www.iot-programmer.com/index.php/books/27-micro-bit-iot-in-c/chapters-micro-bit-iot-in-c/24-micro-bit-and-ds18b20-1-wire-temperature-sensor
连线图
[mw_shl_code=python,true]#include "MicroBit.h"
int init();
void sendskip();
void writeBit(int);
void sendOne();
void sendZero();
void writeByte(int);
int readBit();
int convert();
int readByte();MicroBit uBit;
MicroBitPin P0 = uBit.io.P0;
MicroBitPin P1 = uBit.io.P1;
uBit.init();
P0.setDigitalValue(1);
P0.setPull(PullUp);
P1.getDigitalValue();
uBit.sleep(1);
while (1) {
init();
writeByte(0xCC);
int r = convert();
init();
writeByte(0xCC);
writeByte(0xBE);
int b1 = readByte();
int b2 = readByte();
int16_t temp = (b2 << 8 | b1);
temp = temp * 100 / 16;char buff[10];
sprintf(buff, "%d.%d", temp / 100, abs(temp % 100));
uBit.display.scroll(buff, 200);
uBit.sleep(1000);
}
release_fiber();
}
int init() {
volatile int i;P0.setDigitalValue(0);
for (i = 0; i < 600; i++) {
};
P0.setDigitalValue(1);
for (i = 0; i < 30; i++) {
};
int b = P1.getDigitalValue();
for (i = 0; i < 600; i++) {
};
return b;
}
void sendZero() {
volatile int i;
P0.setDigitalValue(0);
for (i = 1; i < 75; i++) {
};
P0.setDigitalValue(1);
for (i = 1; i < 6; i++) {
};
}
void sendOne() {
volatile int i;
P0.setDigitalValue(0);
for (i = 1; i < 1; i++) {
};
P0.setDigitalValue(1);
for (i = 1; i < 80; i++) {
};
}
void writeBit(int b) {
volatile int i;
int delay1, delay2;
if (b == 1) {
delay1 = 1;
delay2 = 80;
} else {
delay1 = 75;
delay2 = 6;
}
P0.setDigitalValue(0);
for (i = 1; i < delay1; i++) {
};
P0.setDigitalValue(1);
for (i = 1; i < delay2; i++) {
};
}
void sendskip() {
writeBit(0);
writeBit(0);
writeBit(1);
writeBit(1);
writeBit(0);
writeBit(0);
writeBit(1);
writeBit(1);
}
void writeByte(int byte) {
int i;
for (i = 0; i < 8; i++) {
if (byte & 1) {
writeBit(1);
} else {
writeBit(0);
}
byte = byte >> 1;
}
}
int readBit() {
volatile int i;
P0.setDigitalValue(0);
P0.setDigitalValue(1);
for (i = 1; i < 20; i++) {
};
int b = P1.getDigitalValue();
for (i = 1; i < 60; i++) {
};
return b;
}
int convert() {
volatile int i;
int j;
writeByte(0x44);
for (j = 1; j < 1000; j++) {
for (i = 1; i < 900; i++) {
};
if (readBit() == 1)break;
};
return (j);
}
int readByte() {
int byte = 0;
int i;
for (i = 0; i < 8; i++) {
byte = byte | readBit() << i;
};
return byte;
} [/mw_shl_code]