我目前正在攻读嵌入式硕士学位,对于我的论文,我必须研究 Erlang 对机器人编程的有效性。AFAIK Erlang 的声明性和并发性是有效的,所以我为“自适应巡航控制”制作了一个 Erlang 代码,它从 C 程序中获取传感器值(因为 Erlang 不能直接读取传感器)然后执行计算并将控制信号发送回 C 程序。但是代码的大小(行)看起来很大。为什么我不能使用声明性或存在其他问题?这是我的代码片段。
start() ->
spawn( cr, read_sensor, []),
spawn(cr, take_decision, []),
sleep_infinite().
% this will make it to run infinitely
sleep_infinite() ->
receive
after infinity ->
true
end.
read_sensor() ->
register(read, self()),
Port = open_port({spawn , "./cr_cpgm" }, [{packet, 2}]),
Port ! {self(),{command, [49]}},% for executing read sensor fun in C pgm
read_reply(Port).
read_reply(Port) ->
receive
read_sensor ->
Port ! { self(), { command, [49]}};
{Port, {data, Data}} ->
[Left,Center,Right,Distance] = Data, % stored values of sensors into variables for further computation
io:format("value of Left: ~w and Center: ~w and Right: ~w and Distance: ~w~n",[Left,Center,Right,Distance]),
if Distance =< 100 -> decision ! {1, out}; % Distance shows the value returned by front sharp sensor
((Left > 25) and (Center > 25) and (Right > 25)) -> decision ! {2, out}; % stop robot
Center < 25 -> decision ! {3, out}; % move forward
((Left > 25) and (Center > 25)) -> decision ! {4, out}; % turn right
((Right > 25) and (Center > 25)) -> decision ! {5, out}; % turn left
true -> decision ! {6, out} % no match stop robot
end
end,
read_reply(Port).
take_decision() ->
register(decision, self()),
Port = open_port({spawn , "./cr_cpgm" }, [{packet, 2}]),
decision_reply(Port).
decision_reply(Port) ->
receive
{A, out} ->
Port ! {self(), {command, [50,A]}};
{Port,{data, Data}} ->
if
Data == [102] -> read ! read_sensor %
end
end,
decision_reply(Port).
此代码看起来更像 C 代码。
- 我的实现方式是否错误?(尤其是 IF...end)或问题本身很小(只有 2 个进程)
请建议我如何展示 Erlang 在机器人编程中的有效性。欢迎所有建议。
谢谢..
好吧,我同意@cthulahoops 的观点,这个问题不足以证明 Erlang 的有效性。任何人都可以推荐一些我可以在 Erlang 中实现的机器人应用程序吗?