Skip to content
This repository has been archived by the owner on Sep 22, 2024. It is now read-only.

Commit

Permalink
Add a module with reading temperature example
Browse files Browse the repository at this point in the history
  • Loading branch information
zofpolkowska committed Mar 11, 2019
1 parent eac6ce4 commit 2f22c1f
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/rolnik_device.erl
Original file line number Diff line number Diff line change
@@ -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}]),
<<Temp:14/unsigned-big,_:2>> = 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}]),
<<Hum:14/unsigned-big,_:2>> = H,
(Hum / 16384) * 100.
46 changes: 46 additions & 0 deletions src/rolnik_example.erl
Original file line number Diff line number Diff line change
@@ -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.

0 comments on commit 2f22c1f

Please sign in to comment.