雄介 太田 / Mbed 2 deprecated UDPSocket_Sample

Dependencies:   EthernetInterface mbed-rtos mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /*UDP通信サンプルコード
00002  自分:mbedAから相手:mbedBへのデータ送信方法、相手:mbedBから自分:mbedAへのデータ受信方法*/
00003 #include "mbed.h"
00004 #include "EthernetInterface.h" 
00005 
00006 Serial pc(USBTX, USBRX); // tx, rx
00007 
00008 const char* A_ADDRESS = "192.168.1.1"; 
00009 const int A_PORT = 1000;
00010 
00011 const char* B_ADDRESS = "192.168.1.2";
00012 const int B_PORT = 2000;
00013 
00014 int main() {
00015        
00016     char u_packet[2]; 
00017     u_packet[0]=0x41; u_packet[1]=0x42; //ex.
00018     char u_buff[10];
00019 
00020     EthernetInterface eth; 
00021     eth.init(A_ADDRESS, "255.255.255.0", ""); //    Use hard IP
00022     pc.printf("IP : %s\n", eth.getIPAddress());
00023     if (eth.connect() < 0) {
00024         pc.printf("Failed to connect\n\r");
00025         return -1;
00026     }
00027     
00028     UDPSocket sockA; 
00029     if (sockA.bind(A_PORT) < 0) {
00030         pc.printf("Failed to bind UDP Socket to PORT : %d\n\r", A_PORT);
00031         return -1;
00032     }
00033     else pc.printf("Bind UDP Socket to PORT : %d\n\r", A_PORT);
00034     sockA.set_blocking(false);
00035     
00036     Endpoint EndpointA; 
00037     EndpointA.set_address(A_ADDRESS, A_PORT);
00038     
00039     Endpoint EndpointB;
00040     EndpointB.set_address(B_ADDRESS, B_PORT);
00041 
00042     /*-----------
00043       MAIN ROOP
00044      -----------*/    
00045     while(1) { 
00046     /*--send--*/
00047         pc.printf("Send : %s\n", u_packet);
00048         int n_send=sockA.sendTo(EndpointB, (char*)u_packet, sizeof(u_packet));
00049         wait_ms(1);            
00050         
00051         if(n_send < 0){
00052             pc.printf("Sent unsuccessfully\n");
00053             return 0;
00054         }
00055         else pc.printf("Sent %d bytes Successfully!\n",n_send);
00056     /*-receive--*/
00057         int n_receive=sockA.receiveFrom(EndpointB, (char*)u_buff, sizeof(u_buff));
00058         wait_ms(1);            
00059 
00060         if(n_receive < 0){
00061             pc.printf("Received unsuccessfully\n");        
00062             return 0;
00063         }
00064         else {
00065              pc.printf("Received %d byte Successfully!\n",n_receive);
00066              pc.printf("Received : %s\n",u_buff);
00067         }
00068     } 
00069     
00070     sockA.close(false);
00071     eth.disconnect(); 
00072     return 0;
00073 }