I am struggling to build a communication bridge between Arduino and Python. Arduino should send an integer value to python. To enable the Udp communication I am using Ethernet shield 2 on Arduino and have to connect to IP "192.168.137.30". Now when I try to connect to bind with this Ip address, an error occurs because "192.168.137.30" is an external Ip address.
Below is my Arduino and python code :
#include <SPI.h>
#include <SD.h>
#include <Ethernet2.h>
#include <EthernetUdp2.h> // UDP library from: [email protected] 12/30/2008
byte mac[] = {
0xA8, 0x61, 0x0A, 0xAE, 0x2A, 0x12
};
IPAddress ip(192.168.137.30);
unsigned int localPort = 8880; // local port to listen on
// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;
void setup()
{
Ethernet.begin(mac, ip);
Udp.begin(localPort);
Serial.begin(115200);
}
void loop()
{
char ReplyBuffer[] = "acknowledged";
Udp.beginPacket(ip, localPort);
Udp.write(ReplyBuffer);
Udp.endPacket();
}
Python :
import serial
import time
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('192.168.137.30', 8880))
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
sock.close()
I still can not send data from Arduino to Python. However, it is possible to send data from Python to Arduino.
IPAddress ip(169, 254, 114, 130);
IPAddress my_PC_ip(169, 254, 94, 133);
unsigned int localPort = 7476;
unsigned int pythonPort= 7000;
void setup()
{
Ethernet.begin(mac, ip);
Udp.begin(localPort);
Serial.begin(115200);
}
void loop()
{
Udp.beginPacket(my_PC_ip,pythonPort);
Udp.print("hello");
Udp.endPacket();
}
Python : import serial import time import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('169.254.94.133', 7000))
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
sock.close()