通过w(红色臂角度增大)s(红色臂角度减小)d(蓝色臂角度增大)a(蓝色臂角度减小)按键控制机械臂
注意:关闭计算机的杀毒软件,电脑管家,防火墙
1)基于TCP服务器的机械臂,端口号是8888, ip是Windows的ip;
查看Windows的IP:按住Windows+r 按键,输入cmd , 输入ipconfig
2)点击软件中的开启监听;
3)机械臂需要发送16进制数,共5个字节,协议如下
0xff 0x02 x y 0xff
0xff:起始结束协议,固定的;
0x02:控制机械手臂协议,固定的;
x:指定要操作的机械臂
0x00 红色摆臂
0x01 蓝色摆臂
y:指定角度
#include <myhead.h>
#include <linux/input.h>
#define S_IP "192.168.125.195"
#define S_PORT 8888
#define C_IP "192.168.125.105"
#define C_PORT 7777
int main(int argc, const char *argv[])
{
int cfd = socket(AF_INET, SOCK_STREAM, 0);
if(cfd == -1){
perror("socket");
return -1;
}
//调用端口号快速重用函数
int reuse = 1;
if(setsockopt(cfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) == -1){
perror("setsockopt");
return -1;
}
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(C_PORT);
cin.sin_addr.s_addr = inet_addr(C_IP);
socklen_t cinlen = sizeof(cin);
if(bind(cfd, (struct sockaddr *)&cin, cinlen) == -1){
perror("bind");
return -1;
}
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(S_PORT);
sin.sin_addr.s_addr = inet_addr(S_IP);
socklen_t sinlen = sizeof(sin);
if(connect(cfd, (struct sockaddr *)&sin, sinlen) == -1){
perror("connect");
return -1;
}
printf("connect success\n");
char rbuf[5] = {0xff, 0x02, 0x00, 0x00, 0xff};
unsigned char bbuf[5] = {0xff, 0x02, 0x01, 0x00, 0xff};
send(cfd, rbuf, sizeof(rbuf), 0);
send(cfd, bbuf, sizeof(bbuf), 0);
int fd = open("/dev/input/event1", O_RDONLY);
if(fd == -1){
perror("open");
return -1;
}
struct input_event input;
while(1){
read(fd, &input, sizeof(input));
switch(input.value * input.code){
case 17:
rbuf[3] += 2;
if(rbuf[3] >= 90){rbuf[3] = 90;}
send(cfd, rbuf, sizeof(rbuf), 0);
break;
case 31:
rbuf[3] -= 2;
if(rbuf[3] <= -90){rbuf[3] = -90;}
send(cfd, rbuf, sizeof(rbuf), 0);
break;
case 30:
bbuf[3] -= 2;
if(bbuf[3] >180 && bbuf[3] <= 255){bbuf[3] = 0;}
send(cfd, bbuf, sizeof(bbuf), 0);
break;
case 32:
bbuf[3] += 2;
if(bbuf[3] >= 180){bbuf[3] = 180;}
send(cfd, bbuf, sizeof(bbuf), 0);
break;
default:break;
}
}
close(fd);
close(cfd);
return 0;
}