1、机械臂控制
#include <allhead.h>
#define SER_IP "192.168.125.62"
#define SER_PORT 8888
#define CLI_IP "192.168.125.153"
#define CLI_PORT 9999
int main(int argc, const char *argv[])
{
//1、创建用于通信的套接字文件描述符
int cfd = socket(AF_INET,SOCK_STREAM,0);
if(cfd == -1)
{
perror("socket\n");
return -1;
}
int reuse = 1;
if(setsockopt(cfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1)
{
perror("setsocket\n");
return -1;
}
//2、绑定IP和端口号
//2.1填充地址信息结构体
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(CLI_PORT);
cin.sin_addr.s_addr = inet_addr(CLI_IP);
//2.2绑定工作
if(bind(cfd,(struct sockaddr*)&cin,sizeof(cin)) == -1)
{
perror("bind");
return -1;
}
printf("bind success\n");
//3、连接服务器
//3.1填充要连接的服务器地址信息结构体
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(SER_PORT);
sin.sin_addr.s_addr = inet_addr(SER_IP);
//3.2连接服务器
if(connect(cfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
{
perror("connect");
return -1;
}
printf("服务器连接成功\n");
char rbuf[5]={0xff,0x02,0x00,0x00,0xff};
unsigned char bbuf[5]={0xff,0x02,0x01,0x00,0xff};
int key = open("/dev/input/event1",O_RDONLY);
if(key == -1)
{
perror("open");
return -1;
}
//4、数据收发
while(1)
{
struct input_event kb;
read(key,&kb,sizeof(struct input_event));
printf("type =%d code=%d value =%d\n",kb.type,kb.code,kb.value);
switch(kb.value*kb.code)
{
case 30://a 蓝减
{if(bbuf[3]>0)
{
bbuf[3]-=3;
send(cfd,bbuf,sizeof(bbuf),0);
}
break;
}
case 31://s 红减
{if(rbuf[3]>-90)
{
rbuf[3]-=3;
send(cfd,rbuf,sizeof(rbuf),0);
}
break;
}
case 32://d 蓝加
{if(bbuf[3]<180)
{
bbuf[3]+=3;
send(cfd,bbuf,sizeof(bbuf),0);
}
break;
}
case 17://w 红加
{if(rbuf[3]<=90)
{
rbuf[3]+=3;
send(cfd,rbuf,sizeof(rbuf),0);
}
break;
}
}
}
close(key);
close(cfd);
return 0;
}