【飞凌RT1052】+ 06 ucLinux之TCP控制LED 1. 目的 新建一个TCP服务器,服务器端实现对板载LED的控制。采用电脑客户端连接上服务器,发送0或者1来控制LED亮与灭。 2. 测试准备工作 服务端源码如下: - #include <stdlib.h>
- #include <stdio.h>
- #include <errno.h>
- #include <string.h>
- #include <netinet/in.h>
- #include <sys/wait.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <arpa/inet.h>
- #include <fcntl.h>
- #define PORT 5000
- #define BACKLOG 10
- #define LENGTH 512
- int main()
- {
- int iR;
- int sockfd;
- int nsockfd;
- int num;
- int sin_size;
- int value;
- int pfd;
-
-
- struct sockaddr_in addr_local;
- struct sockaddr_in addr_remote;
- /*获取文件描述符*/
- if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
- {
- printf("ERROR:Failed to obtain socket Descriptor.\n");
- return 0;
- }
- else
- {
- printf("OK:Obtain socket descriptor successfully.\n");
- }
- /*本地地址初始化*/
- addr_local.sin_family=AF_INET;
- addr_local.sin_port=htons(PORT);
- addr_local.sin_addr.s_addr=htonl(INADDR_ANY);
- memset(addr_local.sin_zero,0,8);
- /*绑定端口*/
- if(bind(sockfd,(struct sockaddr*)&addr_local,sizeof(struct sockaddr))==-1)
- {
- printf("ERROR:Failed to bind Port %d.\n",PORT);
- return 0;
- }
- else
- {
- printf("OK:Bind the Port %d successfully.\n",PORT);
- }
- /*监听端口*/
- if(listen(sockfd,BACKLOG)==-1)
- {
- printf("ERROR:Failed to listen Port %d.\n",PORT);
- return 0;
- }
- else
- {
- printf("OK:Listening the Port %d successfully.\n",PORT);
- }
-
- /*一直等待连接*/
- sin_size=sizeof(struct sockaddr_in);
- nsockfd=accept(sockfd,(struct sockaddr*)&addr_remote,&sin_size);
-
-
- if(nsockfd==-1)
- {
- printf("ERROR:Obtain new socket Descriptor error.\n");
- return 0;
- }
- else
- {
- printf("OK:Server has got connected from %s.\n",inet_ntoa(addr_remote.sin_addr));
- }
- pfd=open("/sys/devices/platform/leds/leds/led1/brightness",O_RDWR); //打开LED驱动
- if(pfd<0)
- {
- printf("Open led failed.\n");
- return -1;
- }
- write(pfd,"1",1);
- while(1)
- {
- read(nsockfd,&value,4); //int 型
- if(value==1)
- {
- write(pfd,"1",1);
- }
- else
- {
- if(value==0)
- {
- write(pfd,"0",1);
- }
- else
- {
- printf("client quiting...\n");
- break;
- }
- }
- }
- close(pfd);
- close(nsockfd);
- close(sockfd);
- }
复制代码PC端设置 启动服务 3. 运行./led_server./led_client192.168.1.163测试
源码如下: |