Place to put your Basic demos and examples

Moderator: Mmiscool

User avatar
By cicciocb
#44743 Hi all,
this is another example, mainly aimed to show the communication between modules.
This is an example where one module acts like a "controller" and several other modules act as slaves.
The main module have a series of switches (2 in this example but can be more); each time a switch is pressed / released, the corresponding module change the state of the output pin.
This works based on broadcast address so it's not necessary to set IP address, the addressing is automatic.

let's see the main code :
Code: Select allmemclear

port = 5001
'variables used to store the previous state of the switches
sw1_p = 0
sw2_p = 0

'get the local IP
localIP = ip()
'convert to broadcast IP (.255 at the end)
'look for the last '.'; start from the end of the string
le = len(localIP)
for i = 0 to le
if mid(localIP, le - i, 1) <> "." then goto [cont]
p = le - i
i = 999
[cont]
next i
broadcastIP = mid(localIP, 1 , p) & "255"
print broadcastIP

timer 100, [loop]
wait
[loop]
pi 15 sw1
pi 2 sw2

if sw1 <> sw1_p then dummy else goto [else1]
serialprintln "changed sw1"
udpwrite broadcastIP, port, "SW1=" & sw1
[else1]
if sw2 <> sw2_p then dummy else goto [else2]
serialprintln "changed sw2"
udpwrite broadcastIP, port, "SW2=" & sw2
[else2]
sw1_p = sw1
sw2_p = sw2
wait

There are 2 switches connected on the main module (the controller), on the pin GPIO15 and GPIO2.
When the state of the switch sw1 changes, the message SW1=0 or SW1=1 is sent; the same for the switch2 (message SW2=0 or SW2=1 is sent)

Now let's see the receiver1 code
Code: Select allprint flashfree()
memclear

udpbegin 5001
udpbranch [udp]
wait

[udp]
'serialprintln "UDP received"
rec = udpread()
'serialprintln rec
if left(rec,4) <> "SW1=" then return
ou = mid(rec,5)
serialprintln ou
po 13 ou

return


And the receiver2 code
Code: Select allprint flashfree()
memclear

udpbegin 5001
udpbranch [udp]
wait

[udp]
'serialprintln "UDP received"
rec = udpread()
'serialprintln rec
if left(rec,4) <> "SW2=" then return
ou = mid(rec,5)
serialprintln ou
po 13 ou

return


As you can see, the receiver 1 accept only the message SW1= whereas the receiver 2 accept only the message SW2=
if the message is accepted, the corresponding output pin is activated (GPIO13 in this example).

This example can be extended in terms of switches, the only limit is the number of pins available on the ESP module.

Hoping this will permit to better understand how manage the ESP UDP communications

Regards
CiccioCB