用 gasp 开发DS18B20 智能温度传感器

406 阅读2分钟

今天我们用 gasp 编程语言来设计一个基于 DS18B20 智能温度传感器。 功能描述如下: 实时监控温度(每隔 6 秒一次),发现温度变化超过 1 摄氏度时向服务端汇报,如果温度不变的情况下,每隔半个小时汇报一次。

如果没有安装 gasp 的话请参考 gasp 物联网编程语言快速入门 安装部分。

我们新建一个项目:

gasp new DS18B20
cd DS18B20

我先用 git 安装依赖库,到 Arduino 的 libraries 目录,执行以下命令安装

git clone https://github.com/PaulStoffregen/OneWire.git
git clone https://github.com/matmunk/DS18B20.git

我们在 main.gasp 添加初始化代码,如下:

init {=code
#include <DS18B20.h>
DS18B20 ds(2);
code=}

我们初始化一个 DS18B20 对象,并将 DS18B20 数据管脚接到 arduino 的2号管脚。

找到 read_DS18B20 函数,将代码改为:

func read_DS18B20 {=code
    while (ds.selectNext()) {
        temperature = ds.getTempC();
    }
code=}

将读到的温度放在 temperature 这个变量, 到这里 DS18B20 智能温度传感器以完成。

完整代码如下:

app DS18B20 {
  key: "DS18B20",
  token: "DS18B20"
}

init {=code
#define GL_SERIAL Serial
#define DEBUG_SERIAL Serial
#define METRIC_DELAY_MS metric_delay_ms
code=}

setup {=code
    GL_SERIAL.begin(115200);
    while (!GL_SERIAL) {;}
code=}

attr delay {
  var: metric_delay_ms,
  type: "unsigned long",
  default: 1800,
  min: 60,
  max: 86400,
  scale: 1000
}

metric temperature {
  var: temperature,
  type: "float",
  max: 100,
  min: 0,
  threshold: 1,
  prec: 2
}

func read_DS18B20 {=code
    while (ds.selectNext()) {
        temperature = ds.getTempC();
    }
code=}

every read_DS18B20 6000

上传到设备

Giveyun 上申请一个设备,并复制 keytoken

然后修改 app DS18B20, 如下:

app DS18B20 {
  key: "product_key",
  token: "device_token"
}

最后用 gasp compile, 并用 Arduino IDE 编译后上传到 arduino 板子上面 就大功告成。