#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#define SER_PORT 8888 //端口号
#define SER_IP "192.168.117.47" //IP地址
int main()
{
// 1.定义套接字
int cfd = -1;
cfd = socket(AF_INET,SOCK_STREAM,0);
if(cfd == -1)
{
perror("socket");
return 1;
}
//2.绑定端口号和ip(非必须)
//3.链接到服务器
//填充要连接的服务器信息
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(SER_PORT);
sin.sin_addr.s_addr = inet_addr(SER_IP);
//连接
if(connect(cfd,(struct sockaddr *)&sin,sizeof(sin)) == -1)
{
perror("connect");
return 1;
}
//蓝色机械臂 帧头 功能字 帧尾
unsigned char str1[5] = {0xff,0x02,0x01,0x00,0xff}; //0x00 - 0xb4
//红色机械臂
unsigned char str2[5] = {0xff,0x02,0x00,0x00,0xff}; //红色 0x00 - 0x60 0-90度
//0xff - 0xa6 0 ~ -90 度
// 0xa6 0xff 0x00 0x60
// -90 0 90
//取消标准输入流的行缓冲,实现实时读入数据
struct termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= (~ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
//设置标准输入流为非阻塞状态(非必须)
// int flags;
// flags = fcntl(STDIN_FILENO,F_GETFL,0);
// fcntl(STDIN_FILENO,F_SETFL,flags|O_NONBLOCK);
//机械臂控制逻辑
while(1)
{
char c = getchar();
if(c == 'w')
{
str1[3]++;
if(str1[3]>=0xb3)
str1[3]=0xb3;
//usleep(5000);
write(cfd,str1,5);
printf("-w-\n%#x",str1[3]);
}
else if(c == 's')
{
str1[3]--;
if(str1[3]<=0x01)
str1[3] = 0x01;
//usleep(5000);
write(cfd,str1,5);
printf("-s-\n%#x",str1[3]);
}
else if(c == 'a')
{
str2[3]++;
if(str2[3]>=0x60 && str2[3] <0xa6 )
str2[3]=0x60;
//usleep(5000);
write(cfd,str2,5);
printf("-a-\n%#x",str2[3]);
}
else if (c== 'd')
{
str2[3]--;
if(str2[3]<=0xa6 && str2[3] > 0x60)
str2[3]=0xa6;
//usleep(5000);
write(cfd,str2,5);
printf("-d-\n%#x",str2[3]);
}
//printf("已发送\n");
}
clode(cdf);
return 0;
}
3.15作业
本文详细描述了一个C语言编写的程序,使用套接字技术,通过指定的IP地址和端口与服务器连接,实现实时控制两个机械臂(蓝色和红色)的动作,通过键盘输入w/s/a/d控制机械臂的运动角度。
摘要由CSDN通过智能技术生成