Why do I get twice the same message? - printing

I'm quite new in Erlang, and I'm developing a little program to simulate a robot which collect cans:
-export([start/0]).
start()->
Believes=#{bin_position=>0, num_cans=>1, can_position=>4, my_position=>1},
PID=spawn(fun()-> believes(Believes) end),
action(PID,Believes).
believes(NewBelieves)->
receive
{add,Key,Value}->
N1=maps:put(Key,Value,NewBelieves),
print(N1),
action(self(),N1),
believes(N1);
{remove, Key}->
N2=maps:remove(Key, NewBelieves),
print(N2),
action(self(),N2),
believes(N2);
{update, Key, Value}->
N3=NewBelieves#{Key => Value},
print(N3),
action(self(),N3),
believes(N3);
{get}->
action(self(),NewBelieves),
believes(NewBelieves)
end.
print(Map)->
List=maps:to_list(Map),
io:format("Believes: ~p~n",[List]).
action(PID, Map)->
case {is_holding(Map),is_over_bin(PID,Map)} of
{false,false}->
%io:format("Is not holding and is not over the bin ~n"),
%timer:sleep(1000),
case is_over_can(PID,Map) of
false->move(PID,right,Map);
% timer:sleep(1000);
_->hold(PID)
%timer:sleep(1000)
end;
{_,false}->
%io:format("Is holding but is not over the bin ~n"),
%timer:sleep(1000),
move(PID, left, Map);
%timer:sleep(1000);
{_,_}->
%io:format("Is holding and is over the bin ~n"),
%timer:sleep(1000),
drop(PID),
timer:sleep(10000),
exit(self(),kill)
end.
is_over_can(PID, Map)->
case same_position(maps:find(my_position,Map),maps:find(can_position, Map)) of
equal->hold(PID);
_->false
end.
is_over_bin(PID, Map)->
case same_position(maps:find(my_position,Map),maps:find(bin_position, Map)) of
equal->drop(PID);
_->false
end.
is_holding(Map)->
maps:is_key(holding,Map).
%is_gripper_on(Map)->
% map:is_key(gripper_on,Map).
%is_touching(Map)->
% map:is_key(touching,Map).
same_position({ok,A},{ok,B}) when A=:=B -> equal;
same_position(_, _) -> not_equal.
move(PID, Dir, Map)->
{ok,MyPosition}=maps:find(my_position,Map),
case Dir of
right->PID ! {update, my_position, MyPosition+1};
left->PID ! {update, my_position, MyPosition-1}
end.
hold(PID)->
PID ! {add, holding, []},
PID ! {update, can_position, nil}.
drop(PID)->
PID ! {remove, holding},
PID ! {update, num_cans, 0},
PID ! {add, cans_collected, 1},
timer:sleep(10000),
io:format("Todas las latas han sido recogidas.~n"),
timer:sleep(10000),
exit(PID,kill).
And when I run the code, I get the print twice in some cases (and I don't get the last 3 prints, from the drop function):
prueba2:start().
Believes: [{bin_position,0},{can_position,4},{my_position,2},{num_cans,1}]
Believes:
[{bin_position,0},{can_position,4},{my_position,3},{num_cans,1}]
{update,my_position,2}
Believes:
[{bin_position,0},{can_position,4},{my_position,4},{num_cans,1}]
(Prueba#Usuario)2>
Believes: [{bin_position,0},
{can_position,4},
{holding,[]},
{my_position,4},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,4},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,4},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,4},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,3},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,3},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,3},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,3},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,2},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,2},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,2},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,2},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,1},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,1},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,1},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,1},
{num_cans,1}]
Believes: [{bin_position,0},
{can_position,nil},
{holding,[]},
{my_position,0},
{num_cans,1}]
Todas las latas han sido recogidas.
Am I doing something wrong? Is it related with the time that each process need to execute it? I also don't know if there is a way to implement it with OTP, I mean, using gen_server or something.
Thank you so much!

Try running this code:
-module(so1).
-export([start/0]).
start()->
Believes = #{bin_position=>0, num_cans=>1, can_position=>4, my_position=>1},
PID = spawn(fun()-> believes(Believes) end),
action(PID,Believes).
believes(NewBelieves)->
receive
{add,Key,Value}->
N1=maps:put(Key,Value,NewBelieves),
io:format("add clause:~n"),
print(N1),
action(self(),N1),
believes(N1);
{remove, Key}->
N2=maps:remove(Key, NewBelieves),
io:format("remove clause:~n"),
print(N2),
action(self(),N2),
believes(N2);
{update, Key, Value}->
N3=NewBelieves#{Key => Value},
io:format("update clause:~n"),
print(N3),
action(self(),N3),
believes(N3);
{get}->
action(self(),NewBelieves),
believes(NewBelieves)
end.
print(Map)->
List=maps:to_list(Map),
io:format("Believes: ~p~n",[List]).
action(PID, Map)->
case {is_holding(Map),is_over_bin(PID,Map)} of
{false,false}->
%io:format("Is not holding and is not over the bin ~n"),
%timer:sleep(1000),
case is_over_can(PID,Map) of
false->
io:format("action() is calling move()~n"),
move(PID,right,Map);
% timer:sleep(1000);
_->hold(PID)
%timer:sleep(1000)
end;
{_,false}->
%io:format("Is holding but is not over the bin ~n"),
%timer:sleep(1000),
move(PID, left, Map);
%timer:sleep(1000);
{_,_}->
%io:format("Is holding and is over the bin ~n"),
%timer:sleep(1000),
drop(PID),
timer:sleep(10000),
exit(self(),kill)
end.
is_over_can(PID, Map)->
case same_position(maps:find(my_position,Map),maps:find(can_position, Map)) of
equal->hold(PID);
_->false
end.
is_over_bin(PID, Map)->
case same_position(maps:find(my_position,Map),maps:find(bin_position, Map)) of
equal->drop(PID);
_->false
end.
is_holding(Map)->
maps:is_key(holding,Map).
%is_gripper_on(Map)->
% map:is_key(gripper_on,Map).
%is_touching(Map)->
% map:is_key(touching,Map).
same_position({ok,A},{ok,B}) when A=:=B -> equal;
same_position(_, _) -> not_equal.
move(PID, Dir, Map)->
{ok,MyPosition}=maps:find(my_position,Map),
io:format("move() is going to send update message~n"),
case Dir of
right-> PID ! {update, my_position, MyPosition+1};
left -> PID ! {update, my_position, MyPosition-1}
end.
hold(PID)->
io:format("hold() is sending add, update messages,~n"),
io:format("which will result in two prints:~n"),
PID ! {add, holding, []},
PID ! {update, can_position, nil}.
drop(PID)->
io:format("drop() is sending remove, update, add messages,~n"),
io:format("which will result in three prints:~n"),
PID ! {remove, holding},
PID ! {update, num_cans, 0},
PID ! {add, cans_collected, 1},
timer:sleep(10000),
io:format("Todas las latas han sido recogidas.~n"),
timer:sleep(10000),
exit(PID,kill).
The output will show that your code is a convoluted mess. Also, when you create more than one process the output can be interleaved and come in a different order than written.
I'm quite new in Erlang,
You can only code programs that are as long as your debugging skills can handle. Stick to 20 lines or less for now. You also might want to try using the erlang debugger to step through your code.
I also don't know if there is a way to implement it with OTP, I mean,
using gen_server or something.
Any infinite loop with a receive clause and a loop variable that holds state can be considered a server, so believes() could be implemented as a gen_server.

Related

TSL237 sensor on ESP8266 Wemos D1 Mini

I'm trying to read a TSL237 light sensor using my ESP8266 Wemos D1 Mini board. I have got code for an Arduino Uno from here (see copied below) and loaded it on my board. I first tried pin D0 on my board (GPIO 16) for the sensor data input, then pin D1 (GPIO5). In both cases I get the same useless output; I've copied one loop of this output below. Any ideas what I'm doing wrong?
CODE:
#define TSL237 2
volatile unsigned long pulse_cnt = 0;
void setup() {
attachInterrupt(0, add_pulse, RISING);
pinMode(TSL237, INPUT);
Serial.begin(9600);
}
void add_pulse(){
pulse_cnt++;
return;
}
unsigned long Frequency() {
pulse_cnt = 0;
delay(10000);// this delay controlls pulse_cnt read out. longer delay == higher number
// DO NOT change this delay; it will void calibration.
unsigned long frequency = pulse_cnt;
return (frequency);
pulse_cnt = 0;
}
void loop() {
unsigned long frequency = Frequency();
Serial.println(frequency);
delay(5000);
}
OUTPUT:
14:26:59.605 -> ets Jan 8 2013,rst cause:2, boot mode:(3,6)
14:26:59.605 ->
14:26:59.605 -> load 0x4010f000, len 3460, room 16
14:26:59.605 -> tail 4
14:26:59.605 -> chksum 0xcc
14:26:59.605 -> load 0x3fff20b8, len 40, room 4
14:26:59.605 -> tail 4
14:26:59.605 -> chksum 0xc9
14:26:59.605 -> csum 0xc9
14:26:59.605 -> v00041fe0
14:26:59.605 -> ~ld

esp8266 RTOS blink example doesn't work

I have a problem with the RTOS firmware on the esp8266 (I have a esp12e), after flashing the firmware, reading from uart, it keeps stuck with those lines:
ets Jan 8 2013,rst cause:2, boot mode:(3,0)
load 0x40100000, len 31584, room 16
tail 0
chksum 0x24
load 0x3ffe8000, len 944, room 8
tail 8
chksum 0x9e
load 0x3ffe83b0, len 1080, room 0
tail 8
chksum 0x60
csum 0x60
Now I will explain my HW setup:
GPIO15 -> Gnd
EN -> Vcc
GPIO0 -> Gnd (when flashing)
GPIO0 -> Vcc (normal mode)
For the toolchain I've followed this tutorial and it works well:
http://microcontrollerkits.blogspot.it/2015/12/esp8266-eclipse-development.html
Then I started doing my RTOS blink example, I post my user_main.c code here:
#include "esp_common.h"
#include "gpio.h"
void task2(void *pvParameters)
{
printf("Hello, welcome to client!\r\n");
while(1)
{
// Delay and turn on
vTaskDelay (300/portTICK_RATE_MS);
GPIO_OUTPUT_SET (5, 1);
// Delay and LED off
vTaskDelay (300/portTICK_RATE_MS);
GPIO_OUTPUT_SET (5, 0);
}
}
/******************************************************************************
* FunctionName : user_rf_cal_sector_set
* Description : SDK just reversed 4 sectors, used for rf init data and paramters.
* We add this function to force users to set rf cal sector, since
* we don't know which sector is free in user's application.
* sector map for last several sectors : ABCCC
* A : rf cal
* B : rf init data
* C : sdk parameters
* Parameters : none
* Returns : rf cal sector
*******************************************************************************/
uint32 user_rf_cal_sector_set(void)
{
flash_size_map size_map = system_get_flash_size_map();
uint32 rf_cal_sec = 0;
switch (size_map) {
case FLASH_SIZE_4M_MAP_256_256:
rf_cal_sec = 128 - 5;
break;
case FLASH_SIZE_8M_MAP_512_512:
rf_cal_sec = 256 - 5;
break;
case FLASH_SIZE_16M_MAP_512_512:
case FLASH_SIZE_16M_MAP_1024_1024:
rf_cal_sec = 512 - 5;
break;
case FLASH_SIZE_32M_MAP_512_512:
case FLASH_SIZE_32M_MAP_1024_1024:
rf_cal_sec = 1024 - 5;
break;
default:
rf_cal_sec = 0;
break;
}
return rf_cal_sec;
}
/******************************************************************************
* FunctionName : user_init
* Description : entry of user application, init user function here
* Parameters : none
* Returns : none
*******************************************************************************/
void user_init(void)
{
uart_init_new();
printf("SDK version:%s\n", system_get_sdk_version());
// Config pin as GPIO5
PIN_FUNC_SELECT (PERIPHS_IO_MUX_GPIO5_U, FUNC_GPIO5);
xTaskCreate(task2, "tsk2", 256, NULL, 2, NULL);
}
I also post the flash command, the first executed one time, the second every time I modify the code:
c:/Espressif/utils/ESP8266/esptool.exe -p COM3 write_flash -ff 40m -fm qio -fs 32m 0x3FC000 c:/Espressif/ESP8266_RTOS_SDK/bin/esp_init_data_default.bin 0x3FE000 c:/Espressif/ESP8266_RTOS_SDK/bin/blank.bin 0x7E000 c:/Espressif/ESP8266_RTOS_SDK/bin/blank.bin
c:/Espressif/utils/ESP8266/esptool.exe -p COM3 -b 256000 write_flash -ff 40m -fm qio -fs 32m 0x00000 firmware/eagle.flash.bin 0x40000 firmware/eagle.irom0text.bin
There is something wrong? I really don't understand why it doesn't work.
When I try the NON-OS example they works very well.
I had the same problem as you. This issue is caused by the incorrect address of the eagle.irom0text.bin .
So I changed the address of the eagle.irom0text.bin from 0x40000 (0x10000) to 0x20000 and it worked well for me.
[RTOS SDK version: 1.4.2(f57d61a)]
The correct flash codes in the common_rtos.mk (ESP-12E)
for flashinit
flashinit:
$(vecho) "Flash init data default and blank data."
$(ESPTOOL) -p $(ESPPORT) write_flash $(flashimageoptions) 0x3fc000 $(SDK_BASE)/bin/esp_init_data_default.bin
$(ESPTOOL) -p $(ESPPORT) write_flash $(flashimageoptions) 0x3fe000 $(SDK_BASE)/bin/blank.bin
for flash:
flash: all
#ifeq ($(app), 0)
$(ESPTOOL) -p $(ESPPORT) -b $(ESPBAUD) write_flash $(flashimageoptions) 0x00000 $(FW_BASE)/eagle.flash.bin 0x20000 $(FW_BASE)/eagle.irom0text.bin
else
ifeq ($(boot), none)
$(ESPTOOL) -p $(ESPPORT) -b $(ESPBAUD) write_flash $(flashimageoptions) 0x00000 $(FW_BASE)/eagle.flash.bin 0x20000 $(FW_BASE)/eagle.irom0text.bin
else
$(ESPTOOL) -p $(ESPPORT) -b $(ESPBAUD) write_flash $(flashimageoptions) $(addr) $(FW_BASE)/upgrade/$(BIN_NAME).bin
endif
endif

Printing memory accesses in GDB

I am new to gdb. I want to print the memory addresses used with the actual sequence during execution of a c program. Let’s explain my question with an example. Let’s assume that we have the following c code with two functions main() and test(). I know that, inside gdb, I can use "disassemble main" to disassemble main() function, or "disassemble test" to disassemble test() function separately. My question is, how can I disassemble these two functions as a single code; so that, I can see all the memory addresses used during execution and their sequence of accesses? To be specific, as main() is calling test() and test() is also calling itself multiple times, I want to see something like example 2. I am also wandering, the addresses shown in gdb disassembler, are they virtual or physical memory addresses? Any help or guidance will be appreciated.
Example 1:
#include "stdio.h"
int test(int q)
{
if(q<16)
test(q+5);
return q;
}
void main()
{
unsigned int a=5;
unsigned int b=5;
unsigned int c=5;
test(a);
}
Example 2:
<Memory Address> <assembly instruction> <c instructions>
0x12546a mov //for unsigned int a=5;
0x12546b mov //for unsigned int b=5;
0x12546c mov //for unsigned int c=5;
0x12546d jmp //for test(q=a=5);
0x12546e cmpl //for if(q<16)
0x12546f jmp //for test(q+5);
0x12546d jmp //for test(q=10);
0x12546e cmpl //for if(q<16)
0x12546f jmp //for test(q+5);
0x12547a jmp //for test(q=15);
0x12547b cmpl //for if(q<16)
0x12547c jmp //for test(q+5);
0x12547d jmp //for test(q=20);
0x12547e cmpl //for if(q<16)
0x12547f jmp //return q);
0x12548a jmp //return q);
0x12548b jmp //return q);
0x12548c jmp //return q);
There's really no pretty way to do this. You're just going to have to step through the code:
(gdb) stepi
(gdb) x/i $pc
(gdb) info registers
(gdb) stepi
(gdb) x/i $pc
(gdb) info registers
.....
You could script that up so that it does it quickly and dumps the data to a file, but that's about all.
I suppose you may have more luck with valgrind. If there's no existing tool to do so, it is possible to add your own instrumentation to report memory accesses (and not only that), or alter an existing one.
E.g. see http://valgrind.org/docs/manual/lk-manual.html
--trace-mem= [default: no]
When enabled, Lackey prints the size and address of almost every memory access made by the program.

How do you get the ICC compiler to generate SSE instructions within an inner loop?

I have an inner loop such as this
for(i=0 ;i<n;i++){
x[0] += A[i] * z[0];
x[1] += A[i] * z[1];
x[2] += A[i] * z[2];
x[3] += A[i] * z[3];
}
The inner 4 instructions can be easily converted to SSE instructions by a compiler. Do current compilers do this ? If they do what do I have to do to force this on the compiler?
From what you've provided, this can't be vectorized, because the pointers could alias each other, i.e. the x array could overlap with A or z.
A simple way to help the compiler out would be to declare x as __restrict. Another way would be to rewrite it like so:
for(i=0 ;i<n;i++)
{
float Ai=A[i];
float z0=z[0], z1=z[1], z2=z[2], z3=z[3];
x[0] += Ai * z0;
x[1] += Ai * z1;
x[2] += Ai * z2;
x[3] += Ai * z3;
}
I've never actually tried to get a compiler to auto-vectorize code, so I don't know if that will do it or not. Even if it doesn't get vectorized, it should be faster since the loads and stores can be ordered more efficiently and without causing a load-hit-store.
If you have more information than the compiler does, (e.g. whether or not your pointers are 16-byte aligned), and should be able to use that to your advantage (e.g. using aligned loads). Note that I'm not saying you should always try to beat the compiler, only when you know more than it does.
Further reading:
Load-hit-stores and the __restrict keyword
Memory Optimization (aliasing starts around slide 35)
ICC auto-vectorizes the below code snippet for SSE2 by default:
void foo(float *__restrict__ x, float *__restrict__ A, float *__restrict__ z, int n){
for(int i=0;i<n;i++){
x[0] += A[i] * z[0];
x[1] += A[i] * z[1];
x[2] += A[i] * z[2];
x[3] += A[i] * z[3];
}
return;
}
By using restrict keyword, the memory aliasing assumption is ignored. The vectorization report generated is:
$ icpc test.cc -c -vec-report2 -S
test.cc(2): (col. 1) remark: PERMUTED LOOP WAS VECTORIZED
test.cc(3): (col. 2) remark: loop was not vectorized: not inner loop
To confirm if SSE instructions are generated, open the ASM generated (test.s) and you will find the following instructions:
..B1.13: # Preds ..B1.13 ..B1.12
movaps (%rsi,%r15,4), %xmm10 #3.10
movaps 16(%rsi,%r15,4), %xmm11 #3.10
mulps %xmm0, %xmm10 #3.17
mulps %xmm0, %xmm11 #3.17
addps %xmm10, %xmm9 #3.2
addps %xmm11, %xmm6 #3.2
movaps 32(%rsi,%r15,4), %xmm12 #3.10
movaps 48(%rsi,%r15,4), %xmm13 #3.10
movaps 64(%rsi,%r15,4), %xmm14 #3.10
movaps 80(%rsi,%r15,4), %xmm15 #3.10
movaps 96(%rsi,%r15,4), %xmm10 #3.10
movaps 112(%rsi,%r15,4), %xmm11 #3.10
addq $32, %r15 #2.1
mulps %xmm0, %xmm12 #3.17
cmpq %r13, %r15 #2.1
mulps %xmm0, %xmm13 #3.17
mulps %xmm0, %xmm14 #3.17
addps %xmm12, %xmm5 #3.2
mulps %xmm0, %xmm15 #3.17
addps %xmm13, %xmm4 #3.2
mulps %xmm0, %xmm10 #3.17
addps %xmm14, %xmm7 #3.2
mulps %xmm0, %xmm11 #3.17
addps %xmm15, %xmm3 #3.2
addps %xmm10, %xmm2 #3.2
addps %xmm11, %xmm1 #3.2
jb ..B1.13 # Prob 75% #2.1
# LOE rax rdx rsi r8 r9 r10 r13 r15 ecx ebp edi r11d r14d bl xmm0 xmm1 xmm2 xmm3 xmm4 xmm5 xmm6 xmm7 xmm8 xmm9
..B1.14: # Preds ..B1.13
addps %xmm6, %xmm9 #3.2
addps %xmm4, %xmm5 #3.2
addps %xmm3, %xmm7 #3.2
addps %xmm1, %xmm2 #3.2
addps %xmm5, %xmm9 #3.2
addps %xmm2, %xmm7 #3.2
lea 1(%r14), %r12d #2.1
cmpl %r12d, %ecx #2.1
addps %xmm7, %xmm9 #3.2
jb ..B1.25 # Prob 50% #2.1

SSE2: How to reduce a _m128 to a word

What's the best way ( sse2 ) to reduce a _m128 ( 4 words a b c d) to one word?
I want the low part of each _m128 components:
int result = ( _m128.a & 0x000000ff ) << 24
| ( _m128.b & 0x000000ff ) << 16
| ( _m128.c & 0x000000ff ) << 8
| ( _m128.d & 0x000000ff ) << 0
Is there an intrinsics for that ? thanks !
FYI, the sse3 intrinsics _mm_shuffle_epi8 do the job: (with the mask 0x0004080c in this case )
The SSE2 answer takes more than one instructions:
unsigned benoit(__m128i x)
{
__m128i zero = _mm_setzero_si128(), mask = _mm_set1_epi32(255);
return _mm_cvtsi128_si32(
_mm_packus_epi16(
_mm_packus_epi16(
_mm_and_si128(x, mask), zero), zero));
}
The above amounts to 5 machine ops, given the input in %xmm1 and output in %rax:
pxor %xmm0, %xmm0
pand MASK, %xmm1
packuswb %xmm0, %xmm1
packuswb %xmm0, %xmm1
movd %xmm1, %rax
If you want to see some unusual uses of SSE2, including high-speed bit-matrix transpose, string search and bitonic (GPGPU-style) sort, you might want to check my blog, Coding on the edges.
Anyway, hope that helps.

Resources