ADC_Init(); // ADC初始化
LPC_GPIO2->FIODIR = 0x000000ff; // LED配置
LPC_GPIO0->FIODIR = 0x00200000;
LPC_GPIO0->FIOPIN |= 0x00200000;
while(1)
{
tcpclient("42.96.164.52",80 ,1); //AD转换值上传
tcpclient("42.96.164.52",80 ,2); //获取LED状态并改变开发板LED状态
rt_thread_delay(RT_TICK_PER_SECOND * 4); //延时4s
}
//TCP客户端实验
int tcpclient(const char* url, int port,int num)
{
char *recv_data;
struct hostent *host;
int sock, bytes_received;
struct sockaddr_in server_addr;
int Buf = 0;
/* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */
host = gethostbyname(url);
/* 分配用于存放接收数据的缓冲 */
recv_data = rt_malloc(BUFSZ);
if (recv_data == RT_NULL)
{
rt_kprintf("No memoryn");
return;
}
/* 创建一个socket,类型是SOCKET_STREAM,TCP类型 */
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
/* 创建socket失败 */
rt_kprintf("Socket errorn");
/* 释放接收缓冲 */
rt_free(recv_data);
return 1;
}
if(num == 1) /
{
Buf = ADC_Get();
Buf = (Buf * 3300)/4096;
INT_CHAR(Buf);
send_data1[234] = dis[0]; //更改上传数据内容即AD值
send_data1[234+1] = '.';
send_data1[234+2] = dis[0+1];
send_data1[234+3] = dis[0+2];
}
/* 初始化预连接的服务端地址 */
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr = *((struct in_addr *)host->h_addr);
rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
/* 连接到服务端 */
while (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
{
/* 连接失败 */
rt_kprintf("Connect fail!n");
lwip_close(sock);
/*释放接收缓冲 */
rt_free(recv_data);
return 1;
}
rt_kprintf("Connect OK!n");
if(num == 1)
{
/* 发送数据到sock连接 */
if(send(sock,send_data1,strlen(send_data1), 0) < 0)
{
/* 发送失败,关闭这个连接 */
rt_kprintf("nSend error ");
lwip_close(sock);
/* 释放接收缓冲 */
rt_free(recv_data);
}
else
{
rt_kprintf("nSend OK ");
bytes_received = recv(sock, recv_data, BUFSZ – 1, 0);
lwip_close(sock);
/* 释放接收缓冲 */
rt_free(recv_data);
}
}
else if(num == 2)
{
/* 发送数据到sock连接 */
if(send(sock,send_data2,strlen(send_data2), 0) < 0)
{
/* 发送失败,关闭这个连接 */
rt_kprintf("nSend error ");
lwip_close(sock);
/* 释放接收缓冲 */
rt_free(recv_data);
}
else
{
rt_kprintf("nSend OK ");
/* 从sock连接中接收最大BUFSZ – 1字节数据 */
bytes_received = recv(sock, recv_data, BUFSZ – 1, 0);
Buf = Search_str(recv_data,""value":");
if(recv_data[Buf] == '0')
LPC_GPIO2->FIOPIN &= ~0xff; //关闭LED
else
LPC_GPIO2->FIOPIN |= 0xff; //打开LED
rt_kprintf("n%s ",recv_data+Buf);
lwip_close(sock);
/* 释放接收缓冲 */
rt_free(recv_data);
}
}
return 1;
}