UDP通信のサンプルプログラム
Dependencies: EthernetInterface mbed-rtos mbed
main.cpp
- Committer:
- yusuke_kyo
- Date:
- 2015-04-06
- Revision:
- 1:617727625d66
- Parent:
- 0:e0ec056e8895
File content as of revision 1:617727625d66:
/*UDP通信サンプルコード 自分:mbedAから相手:mbedBへのデータ送信方法、相手:mbedBから自分:mbedAへのデータ受信方法*/ #include "mbed.h" #include "EthernetInterface.h" Serial pc(USBTX, USBRX); // tx, rx const char* A_ADDRESS = "192.168.1.1"; const int A_PORT = 1000; const char* B_ADDRESS = "192.168.1.2"; const int B_PORT = 2000; int main() { char u_packet[2]; u_packet[0]=0x41; u_packet[1]=0x42; //ex. char u_buff[10]; EthernetInterface eth; eth.init(A_ADDRESS, "255.255.255.0", ""); // Use hard IP pc.printf("IP : %s\n", eth.getIPAddress()); if (eth.connect() < 0) { pc.printf("Failed to connect\n\r"); return -1; } UDPSocket sockA; if (sockA.bind(A_PORT) < 0) { pc.printf("Failed to bind UDP Socket to PORT : %d\n\r", A_PORT); return -1; } else pc.printf("Bind UDP Socket to PORT : %d\n\r", A_PORT); sockA.set_blocking(false); Endpoint EndpointA; EndpointA.set_address(A_ADDRESS, A_PORT); Endpoint EndpointB; EndpointB.set_address(B_ADDRESS, B_PORT); /*----------- MAIN ROOP -----------*/ while(1) { /*--send--*/ pc.printf("Send : %s\n", u_packet); int n_send=sockA.sendTo(EndpointB, (char*)u_packet, sizeof(u_packet)); wait_ms(1); if(n_send < 0){ pc.printf("Sent unsuccessfully\n"); return 0; } else pc.printf("Sent %d bytes Successfully!\n",n_send); /*-receive--*/ int n_receive=sockA.receiveFrom(EndpointB, (char*)u_buff, sizeof(u_buff)); wait_ms(1); if(n_receive < 0){ pc.printf("Received unsuccessfully\n"); return 0; } else { pc.printf("Received %d byte Successfully!\n",n_receive); pc.printf("Received : %s\n",u_buff); } } sockA.close(false); eth.disconnect(); return 0; }