DNS, DHCPClient, Http Client, TCP Client, GET
Dependencies: WIZnetInterface mbed
main.cpp
00001 #include "mbed.h" 00002 #include "EthernetInterface.h" 00003 00004 #define ECHO_SERVER_PORT 80 // HTTP defaults to port 80 00005 char serverName[] = "openweathermap.org"; 00006 #define BUFFER_SIZE 2048 00007 00008 DigitalOut myled(LED1); 00009 00010 // Initialize the Ethernet client library 00011 EthernetInterface eth; 00012 00013 int main() { 00014 char http_cmd[]= "GET / HTTP/1.0\r\n\r\n"; 00015 char buffer[BUFFER_SIZE]; 00016 00017 // Enter a MAC address for your controller below. 00018 uint8_t mac_addr[6] = {0x00, 0x08, 0xDC, 0x1D, 0x62, 0x11}; 00019 00020 // initializing MAC address 00021 eth.init(mac_addr); 00022 00023 // Check Ethenret Link 00024 if(eth.link() == true) 00025 printf("- Ethernet PHY Link-Done \r\n"); 00026 else 00027 printf("- Ethernet PHY Link- Fail\r\n"); 00028 00029 // Start Ethernet connecting: Trying to get an IP address using DHCP 00030 if ( eth.connect() < 0 ){ 00031 printf("Fail - Ethernet Connecing"); 00032 }else{ 00033 // Print your local IP address: 00034 printf("IP=%s\n\r",eth.getIPAddress()); 00035 printf("MASK=%s\n\r",eth.getNetworkMask()); 00036 printf("GW=%s\n\r",eth.getGateway()); 00037 } 00038 00039 // Initialize the TCPSocketConnection 00040 // with the IP address and port of the server 00041 // that you want to connect to (port 80 is default for HTTP): 00042 TCPSocketConnection sock; 00043 if(sock.connect(serverName, ECHO_SERVER_PORT)<0){ 00044 //you didn't get a connection to the server: 00045 printf("- connection failed\r\n"); 00046 }else{ 00047 printf("- connected\r\n"); 00048 wait(3); 00049 while( sock.is_connected()==false) 00050 { 00051 printf("."); 00052 } 00053 // Make & Send a HTTP request: 00054 sock.send_all(http_cmd, sizeof(http_cmd)); 00055 } 00056 00057 while(true) { 00058 00059 int n = sock.receive_all(buffer, BUFFER_SIZE); 00060 if(n<0) 00061 { 00062 break; 00063 } 00064 else 00065 { 00066 for(int i=0; i<n; i++) printf("%c",buffer[i]); 00067 } 00068 00069 if(sock.is_connected()==false){ 00070 sock.close(); 00071 while(true) 00072 { 00073 //led blinky 00074 myled = 1; 00075 wait(0.2); 00076 myled = 0; 00077 wait(0.2); 00078 } 00079 } 00080 } 00081 sock.close(); 00082 }
Generated on Tue Jul 19 2022 20:55:35 by 1.7.2