ESP8266 UDP to/from Raspberry Pi running Lazaraus / Free Pascal

(click here to see index of all ESP8266 posts)

This is a variation on the theme of the prior post, except in this case, the ESP8266 sends a UDP packet to the RPI which processes it using Lazarus / Free Pascal.

For details, please see the prior post

ESP8266 UDP to/from Raspberry Pi running LUA

I’ll repeat the ESP8266 NodeMCU/LUA code here without comment as it is the same code used in the prior example:

-- interrupt called when button is pressed
function btnINT(level)
    if inInt then                   -- don't allow interrupt in interrupt
        return
    else 
        inInt = true
    end
    tmr.delay(100000)               -- 100ms debounce
    cu:send('1234')
    gpio.write(4, gpio.LOW)
    inInt = false
    end -- btnINT

-- function called when UDP packet received
function rxPkt(cu,c)
    if c == '1234' then
        print('correct response')
        gpio.write(4, gpio.HIGH)
    else
        print('incorrect response')
        end
    end -- rxPkt

-- setup gpio pins
gpio.mode(3, gpio.INT, gpio.PULLUP)
gpio.trig(3, 'down', btnINT)
gpio.mode(4, gpio.OUTPUT)
gpio.write(4, gpio.LOW)

-- setup UDP port
cu=net.createConnection(net.UDP)
cu:on('receive',rxPkt)
cu:connect(9999,'192.8.50.106')

inInt = false

So the ESP8266 will send a UDP packet to the RPI when the button is pressed and the RPI should echo it back. Here is the Free Pascal code to run on the RPI. It is very straight forward, I don’t think any additional comment is necessary:

program esp8266RPIviaUDP;

{$mode objfpc}{$H+}

uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
    base64,
  blcksock,
  Classes,
    math,
    sysutils;

{$R *.res}

var

    s                           : string;
    udp                         : TUDPBlockSocket;

begin

udp := TUDPBlockSocket.create;

try
    udp.bind('0.0.0.0', '9999');
except
    writeln('bind failed');
    end;

while true do begin
    while (udp.WaitingData = 0) do begin
        sleep(500);
        end;

    s := udp.RecvPacket(1000);
    if udp.LastError = 0 then begin
        writeln('s    = ', s);
        writeln('ip   = ', udp.GetRemoteSinIP);
        writeln('port = ', udp.GetRemoteSinPort);
        udp.SendString(s);
        end;
    end; // while

end.

 

Advertisements
This entry was posted in c-esp8266, c-lazarus, c-rpi. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s