Simple code for comunication via TCP between the mbed and PC.

Dependencies:   EthernetInterface SimpleSocket mbed-rtos mbed

Fork of SimpleSocketExamples by Hiroshi Yamaguchi

Committer:
numeral369
Date:
Wed Dec 17 16:06:00 2014 +0000
Revision:
1:016774025718
Parent:
0:6dc3cfd058c6
A simple code for comunication via TCP between the Mbed and a PC

Who changed what in which revision?

UserRevisionLine numberNew contents of line
yamaguch 0:6dc3cfd058c6 1 #include "SimpleSocket.h"
yamaguch 0:6dc3cfd058c6 2
yamaguch 0:6dc3cfd058c6 3 void findbuddy()
yamaguch 0:6dc3cfd058c6 4 {
yamaguch 0:6dc3cfd058c6 5 int myIP[4];
yamaguch 0:6dc3cfd058c6 6 sscanf(EthernetInterface::getIPAddress(), "%d.%d.%d.%d", myIP, myIP + 1, myIP + 2, myIP + 3);
yamaguch 0:6dc3cfd058c6 7
yamaguch 0:6dc3cfd058c6 8 DatagramSocket datagram(7777);
yamaguch 0:6dc3cfd058c6 9
yamaguch 0:6dc3cfd058c6 10 char buddy[32] = {};
yamaguch 0:6dc3cfd058c6 11 int port;
yamaguch 0:6dc3cfd058c6 12 for (int i = myIP[3] + 1;; i = (i - myIP[3] + 260) % 10 + myIP[3] + 1) {
yamaguch 0:6dc3cfd058c6 13 sprintf(buddy, "%d.%d.%d.%d", myIP[0], myIP[1], myIP[2], i);
yamaguch 0:6dc3cfd058c6 14 printf("sending message to %s\n", buddy);
yamaguch 0:6dc3cfd058c6 15 datagram.printf("Hello World\n");
yamaguch 0:6dc3cfd058c6 16
yamaguch 0:6dc3cfd058c6 17 datagram.send(buddy, 7777);
yamaguch 0:6dc3cfd058c6 18 // this will not reach target during the first round,
yamaguch 0:6dc3cfd058c6 19 // and in order to receive successfully,
yamaguch 0:6dc3cfd058c6 20 // timeout must be at least 4 seconds (default = 5.0 seconds)
yamaguch 0:6dc3cfd058c6 21 datagram.setTimeout(4.0);
yamaguch 0:6dc3cfd058c6 22 if (datagram.receive(buddy, &port) > 0) {
yamaguch 0:6dc3cfd058c6 23 char buf[80] = {};
yamaguch 0:6dc3cfd058c6 24 int len = datagram.read(buf, sizeof(buf) - 1);
yamaguch 0:6dc3cfd058c6 25 printf("received from %s: %s", buddy, buf);
yamaguch 0:6dc3cfd058c6 26 break;
yamaguch 0:6dc3cfd058c6 27 }
yamaguch 0:6dc3cfd058c6 28 }
yamaguch 0:6dc3cfd058c6 29
yamaguch 0:6dc3cfd058c6 30 for (int i = 0; i < 2; i++) {
yamaguch 0:6dc3cfd058c6 31 datagram.printf("There you are!\n");
yamaguch 0:6dc3cfd058c6 32 datagram.send(buddy, 7777);
yamaguch 0:6dc3cfd058c6 33
yamaguch 0:6dc3cfd058c6 34 if (datagram.receive() > 0) {
yamaguch 0:6dc3cfd058c6 35 char buf[80] = {};
yamaguch 0:6dc3cfd058c6 36 int len = datagram.read(buf, sizeof(buf) - 1);
yamaguch 0:6dc3cfd058c6 37 printf("received: %s", buf);
yamaguch 0:6dc3cfd058c6 38 }
yamaguch 0:6dc3cfd058c6 39 }
yamaguch 0:6dc3cfd058c6 40 }