From 2f22c1faf44d3d93bb3146ff605d20c9d38459b8 Mon Sep 17 00:00:00 2001 From: zofpolkowska Date: Tue, 5 Feb 2019 15:30:41 +0100 Subject: [PATCH] Add a module with reading temperature example --- src/rolnik_device.erl | 36 +++++++++++++++++++++++++++++++++ src/rolnik_example.erl | 46 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 src/rolnik_device.erl create mode 100644 src/rolnik_example.erl diff --git a/src/rolnik_device.erl b/src/rolnik_device.erl new file mode 100644 index 0000000..dffce6b --- /dev/null +++ b/src/rolnik_device.erl @@ -0,0 +1,36 @@ +% @doc +% @end +-module(rolnik_device). + +% API +% ds18b20 termometer - connected via one wire +-export([read_temperature_onewire/1, device_id_onewire/0]). +% pmod hygro - connected via i2c +-export([read_temperature_i2c/0, read_humidity_i2c/0]). + + +%--- API ----------------------------------------------------------------------- + +-spec device_id_onewire() -> [binary()]. +device_id_onewire() -> + grisp_onewire:transaction(fun() -> grisp_onewire:search() end). + +-spec read_temperature_onewire(ID :: binary()) -> float(). +read_temperature_onewire(ID) -> + %% ds18b20 is a digital thermomether + onewire_ds18b20:convert(ID, 500), + onewire_ds18b20:temp(ID). + +read_temperature_i2c() -> + grisp_i2c:msgs([16#40, {write, <<16#00>>}]), + timer:sleep(20), + T = grisp_i2c:msgs([16#40, {read, 2, 16#0800}]), + <> = T, + (Temp / 16384) * 165 - 40. + +read_humidity_i2c() -> + grisp_i2c:msgs([16#40, {write, <<16#01>>}]), + timer:sleep(20), + H = grisp_i2c:msgs([16#40, {read, 2, 16#0800}]), + <> = H, + (Hum / 16384) * 100. diff --git a/src/rolnik_example.erl b/src/rolnik_example.erl new file mode 100644 index 0000000..8dc58c2 --- /dev/null +++ b/src/rolnik_example.erl @@ -0,0 +1,46 @@ +% @doc +% @end +-module(rolnik_device). + +-import(rolnik_device, [device_id_onewire/0, + read_temperature_onewire/1]). + +% API +-export([init/0]). + + +%--- API ----------------------------------------------------------------------- + +init() -> + %% grisp_onewire:search/0 returns a list of IDs of devices connected via one wire, + %% provided example assumes there is only one slave connected + case device_id_onewire() of + [ID] -> + InitTemp = read_temperature_onewire(ID), + loop(ID, InitTemp); + _ -> + grisp_led:color(1, blue), + grisp_led:color(2, blue) + end. + + +%--- Internal ------------------------------------------------------------------ + +loop(ID, Temp) -> + timer:sleep(1000), + try read_temperature_onewire(ID) of + NewTemp -> + case abs(NewTemp - Temp) of + Dif when Dif < 0.5 -> + grisp_led:color(1, green), + grisp_led:color(2, green); + _ -> + grisp_led:color(1, red), + grisp_led:color(2, red) + end, + loop(ID, NewTemp) + catch + _:_ -> + grisp_led:flash(1, red, 500), + grisp_led:flash(2, yellow, 500) + end.