通过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>
#define SER_PORT 8888 //与服务器保持一致
#define SER_IP "192.168.0.111" //服务器ip地址
#define CLI_PORT 6666 //客户端端口号
#define CLI_IP "192.168.0.152" //客户端ip地址
int main(int argc, const char *argv[])
{
//1、创建用于通信的套接字文件描述符
int cfd = socket(AF_INET, SOCK_STREAM, 0);
if (cfd == -1)
{
perror("socket error");
return -1;
}
printf("cfd = %d\n", cfd); //3
/*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); //ip地址
//2.2 绑定工作
if(bind(cfd, (struct sockaddr*)&cin, sizeof(cin)) == -1)
{
perror("bind error");
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); //服务器ip地址
//3.2 连接服务器
if (connect(cfd, (struct sockaddr *)&sin, sizeof(sin)) == -1)
{
perror("connect error");
return -1;
}
printf("连接服务器成功\n");
int red = 0;
int blue = 90;
//准备数据
char rbuf[5] = {0xff, 0x02, 0x00, red, 0xff};
char bbuf[5] = {0xff, 0x02, 0x01, blue, 0xff};
//发送给服务器,以初始化机械臂
send(cfd, rbuf, sizeof(rbuf), 0);
sleep(1);
send(cfd, bbuf, sizeof(bbuf), 0);
// 用户输入控制命令
char buf[128];
while (1)
{
printf("请输入控制命令>>>");
if (fgets(buf, sizeof(buf), stdin) == NULL)
{
break; // 处理EOF或其他错误
}
size_t len = strlen(buf);
if (len > 0 && buf[len - 1] == '\n')
{
buf[len - 1] = '\0'; // 移除换行符
}
if (buf[0] == 'w')
{
red = red + 5;
char qbuf[5] = {0xff, 0x02, 0x00, red, 0xff};
if (send(cfd, qbuf, sizeof(qbuf), 0) == -1)
{
perror("send command error");
break;
}
}
if (buf[0] == 's')
{
red = red - 5;
char wbuf[5] = {0xff, 0x02, 0x00, red, 0xff};
if (send(cfd, wbuf, sizeof(wbuf), 0) == -1)
{
perror("send command error");
break;
}
}
if (buf[0] == 'a')
{
blue = blue - 5;
char ebuf[5] = {0xff, 0x02, 0x01, blue, 0xff};
if (send(cfd, ebuf, sizeof(ebuf), 0) == -1)
{
perror("send command error");
break;
}
}
if (buf[0] == 'd')
{
blue = blue + 5;
char rbuf[5] = {0xff, 0x02, 0x01, blue, 0xff};
if (send(cfd, rbuf, sizeof(rbuf), 0) == -1)
{
perror("send command error");
break;
}
}
}
//5、关闭套接字
close(cfd);
return 0;
}