-
-
Save kristiankristensen/f725ce91faa66eeffcc9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(simple_temp). | |
-export([start/0, get_temp/0]). | |
init() -> | |
gpio_sup:start_link([{18, output}, {23, output}]). | |
set(Val) -> | |
gpio:write(18, lists:nth(1, Val)), | |
gpio:write(23, lists:nth(2, Val)). | |
blink() -> | |
set([1,1]), | |
io:format("LED on~n"), | |
timer:sleep(1000), | |
set([0,0]), | |
io:format("LED off~n"), | |
timer:sleep(1000). | |
%% Temperature reading inspired from https://github.com/mokele/onewire_therm | |
-record(therm, { | |
message, | |
crc, | |
temperature, | |
timestamp | |
}). | |
read(Binary) when is_binary(Binary) -> | |
read(Binary, #therm{ | |
timestamp = erlang:now() | |
}). | |
read(<<A1:16,_,A2:16,_,A3:16,_,A4:16,_,A5:16,_,A6:16,_,A7:16,_,A8:16,_,CRC:16,_,$:,_,"crc=",CRC:16,_,"YES",Rest0/binary>>, | |
#therm{ | |
message = undefined | |
} = OneWire) -> | |
[_, Rest] = to_nl(Rest0), | |
read(Rest, OneWire#therm{ | |
message = <<A1:16,A2:16,A3:16,A4:16,A5:16,A6:16,A7:16,A8:16>>, | |
crc = <<CRC:16>> | |
}); | |
read(<<A1:16,_,A2:16,_,A3:16,_,A4:16,_,A5:16,_,A6:16,_,A7:16,_,A8:16,_,CRC:16," t=",Rest/binary>>, | |
#therm{ | |
message = <<A1:16,A2:16,A3:16,A4:16,A5:16,A6:16,A7:16,A8:16>>, | |
crc = <<CRC:16>> | |
} = OneWire) -> | |
[TemperatureBinary|_] = to_nl(Rest), | |
read(Rest, OneWire#therm{ | |
temperature = list_to_integer(binary_to_list(TemperatureBinary)) / 1000 | |
}); | |
read(_, #therm{ | |
message = Message, | |
crc = CRC, | |
temperature = Temperature | |
}) when Message =:= undefined; CRC =:= undefined; Temperature =:= undefined -> | |
{error, temperature_not_found}; | |
read(_, #therm{ | |
temperature = Temperature, | |
timestamp = Timestamp | |
}) -> | |
{ok, Temperature, Timestamp}. | |
to_nl(Binary) -> | |
binary:split(Binary, <<10>>). | |
path(Wire, Device) -> | |
filename:join(["", "sys", "bus", Wire, "devices", Device, Wire ++ "_slave"]). | |
get_temp() -> | |
%% You'll need the devide id of your sensor as the second param | |
Path = path("w1","28-0000044719d7"), | |
Temp = case file:read_file(Path) of | |
{ok, Binary} -> | |
read(Binary); | |
Else -> | |
Else | |
end, | |
Temp. | |
start() -> | |
init(), | |
io:format("blink test~n"), | |
blink(), | |
io:format("fetch temperature"), | |
Temp = get_temp(), | |
io:format("Temperature: ~p~n", [Temp]), | |
%% Temp might not be correct - the YES/NO word in the first line. In which case you'll run it again | |
%% io:format("fetch temperature"), | |
%% Temp = get_temp(), | |
%% io:format("Temperature: ~p~n", [Temp]), |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment