Jan Kamidra
/
UDP_Echo
UDP echo with thread
Diff: main.cpp
- Revision:
- 0:9f56faada164
- Child:
- 1:9c712ebb90d3
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Sun May 05 14:58:32 2019 +0000 @@ -0,0 +1,59 @@ +#include "mbed.h" //MbedOS 5.12.2 +#include "EthernetInterface.h" + +#define ADDRESS "10.0.1.14" //Here place IP of your PC +#define PORT 20 + +Thread thread; +DigitalOut led1(LED1); +DigitalOut led2(LED2); + +void udpEcho(){ + EthernetInterface eth; + UDPSocket sock; + SocketAddress addr(0,PORT); + eth.connect(); + const char *ip = eth.get_ip_address(); + // Check ip + if(ip){ + printf("IP address is: %s\n", ip); + sock.open(ð); + sock.bind(PORT); + char buffer[] = "Hello World, UDP Echo server"; + printf("Sending message '%s' to server (%s)\n",buffer,ip); + sock.sendto(ADDRESS, PORT, buffer, sizeof(buffer)); + printf("Waiting for message...\n"); + + while(1) { + char in_buffer[80]; + int n = sock.recvfrom(&addr, &in_buffer, sizeof(in_buffer)); + in_buffer[n] = '\0'; + printf("Recieved: %s\n", in_buffer); + + char out_buffer[80]; + n = sprintf(out_buffer,"Echo - %s", in_buffer); + out_buffer[n] = '\0'; + printf("Send back: %s\n", out_buffer); + sock.sendto(addr.get_ip_address(),PORT , out_buffer, sizeof(out_buffer)); + led2 =! led2; + } + /*sock.close(); + eth.disconnect(); */ + }else{ + printf("No IP\n"); + //eth.disconnect(); + printf("Thread end\n"); + } +} + + +int main() { + printf("Mbed UDP socket starting...\n"); + thread.start(callback(udpEcho)); + wait(1); + + while(1) { + led1 =! led1; + wait(1); + } +} \ No newline at end of file