UDP echo with thread

Committer:
JohnnyK
Date:
Sun May 05 16:17:26 2019 +0000
Revision:
1:9c712ebb90d3
Parent:
0:9f56faada164
Child:
2:01b03970605d
Start

Who changed what in which revision?

UserRevisionLine numberNew contents of line
JohnnyK 0:9f56faada164 1 #include "mbed.h" //MbedOS 5.12.2
JohnnyK 0:9f56faada164 2 #include "EthernetInterface.h"
JohnnyK 0:9f56faada164 3
JohnnyK 0:9f56faada164 4 #define ADDRESS "10.0.1.14" //Here place IP of your PC
JohnnyK 0:9f56faada164 5 #define PORT 20
JohnnyK 0:9f56faada164 6
JohnnyK 0:9f56faada164 7 Thread thread;
JohnnyK 0:9f56faada164 8 DigitalOut led1(LED1);
JohnnyK 0:9f56faada164 9 DigitalOut led2(LED2);
JohnnyK 0:9f56faada164 10
JohnnyK 0:9f56faada164 11 void udpEcho(){
JohnnyK 0:9f56faada164 12 EthernetInterface eth;
JohnnyK 0:9f56faada164 13 UDPSocket sock;
JohnnyK 0:9f56faada164 14 SocketAddress addr(0,PORT);
JohnnyK 0:9f56faada164 15 eth.connect();
JohnnyK 0:9f56faada164 16 const char *ip = eth.get_ip_address();
JohnnyK 0:9f56faada164 17 // Check ip
JohnnyK 0:9f56faada164 18 if(ip){
JohnnyK 0:9f56faada164 19 printf("IP address is: %s\n", ip);
JohnnyK 0:9f56faada164 20 sock.open(&eth);
JohnnyK 0:9f56faada164 21 sock.bind(PORT);
JohnnyK 0:9f56faada164 22 char buffer[] = "Hello World, UDP Echo server";
JohnnyK 0:9f56faada164 23 printf("Sending message '%s' to server (%s)\n",buffer,ip);
JohnnyK 0:9f56faada164 24 sock.sendto(ADDRESS, PORT, buffer, sizeof(buffer));
JohnnyK 0:9f56faada164 25 printf("Waiting for message...\n");
JohnnyK 0:9f56faada164 26
JohnnyK 0:9f56faada164 27 while(1) {
JohnnyK 0:9f56faada164 28 char in_buffer[80];
JohnnyK 0:9f56faada164 29 int n = sock.recvfrom(&addr, &in_buffer, sizeof(in_buffer));
JohnnyK 0:9f56faada164 30 in_buffer[n] = '\0';
JohnnyK 0:9f56faada164 31 printf("Recieved: %s\n", in_buffer);
JohnnyK 0:9f56faada164 32
JohnnyK 0:9f56faada164 33 char out_buffer[80];
JohnnyK 0:9f56faada164 34 n = sprintf(out_buffer,"Echo - %s", in_buffer);
JohnnyK 0:9f56faada164 35 out_buffer[n] = '\0';
JohnnyK 0:9f56faada164 36 printf("Send back: %s\n", out_buffer);
JohnnyK 0:9f56faada164 37 sock.sendto(addr.get_ip_address(),PORT , out_buffer, sizeof(out_buffer));
JohnnyK 0:9f56faada164 38 led2 =! led2;
JohnnyK 0:9f56faada164 39 }
JohnnyK 0:9f56faada164 40 /*sock.close();
JohnnyK 0:9f56faada164 41 eth.disconnect(); */
JohnnyK 0:9f56faada164 42 }else{
JohnnyK 0:9f56faada164 43 printf("No IP\n");
JohnnyK 0:9f56faada164 44 //eth.disconnect();
JohnnyK 0:9f56faada164 45 printf("Thread end\n");
JohnnyK 0:9f56faada164 46 }
JohnnyK 0:9f56faada164 47 }
JohnnyK 0:9f56faada164 48
JohnnyK 0:9f56faada164 49
JohnnyK 0:9f56faada164 50 int main() {
JohnnyK 1:9c712ebb90d3 51 printf("UDP echo starting...\n");
JohnnyK 0:9f56faada164 52 thread.start(callback(udpEcho));
JohnnyK 0:9f56faada164 53 wait(1);
JohnnyK 0:9f56faada164 54
JohnnyK 0:9f56faada164 55 while(1) {
JohnnyK 0:9f56faada164 56 led1 =! led1;
JohnnyK 0:9f56faada164 57 wait(1);
JohnnyK 0:9f56faada164 58 }
JohnnyK 0:9f56faada164 59 }