【嵌入式学习】网络通信基础-Day2-TCP和UDP基础通信模型

本文介绍了如何使用UDP协议控制机械臂,包括发送16进制指令以及机械臂控制指令的结构,如W、S、A、D分别对应红蓝臂的角度增减。还提到服务器端口号和IP设置以及初始化步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思维导图&笔记

见原文:EmbeddedNote:TCP和UDP基础通信模型 - Jun (lingjun.life)

UDP机械臂测试

机械臂
通过w(红色臂角度增大)s(红色臂角度减小)d(蓝色臂角度增大)a(蓝色臂角度减小)按键控制机械臂
注意:关闭计算机的杀毒软件,电脑管家,防火墙
1)基于UDP服务器的机械臂,端口号是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:指定角度

在这里插入图片描述

/*
 * Filename: 02tcpClint.c
 * Author: linus
 * Date: 2024-01-12
 * Version: 1.0
 *
 * Description: The purpose of this code.
 */

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <pthread.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int cfd;
struct sockaddr_in cin;
char send_buf[5];

int RobArmCtl(char buf[128])
{
    static int x = 0, y = 0;

    switch (buf[0])
    {
    case 'W':
        x++;
        send_buf[2] = 0x00;
        send_buf[3] = x;
        break;
    case 'S':
        send_buf[2] = 0x00;
        send_buf[3] = x;
        x--;
        break;
    case 'A':
        y++;
        send_buf[2] = 0x01;
        send_buf[3] = y;
        break;
    case 'D':
        y--;
        send_buf[2] = 0x01;
        send_buf[3] = y;
        break;
    default:
        break;
    }

    send_buf[0] = 0xff;
    send_buf[1] = 0x02;

    send_buf[4] = 0xff;
    write(cfd, send_buf, sizeof(send_buf));
}

int init()
{
    send_buf[0] = 0xff;
    send_buf[1] = 0x02;
    send_buf[2] = 0x00;
    send_buf[3] = 0x00;
    send_buf[4] = 0xff;
    write(cfd, send_buf, sizeof(send_buf));

    send_buf[0] = 0xff;
    send_buf[1] = 0x02;
    send_buf[2] = 0x01;
    send_buf[3] = 90;
    send_buf[4] = 0xff;
    write(cfd, send_buf, sizeof(send_buf));
}

int main(int argc, const char *argv[])
{
    // 创建套接字
    cfd = socket(AF_INET, SOCK_STREAM, 0);

    cin.sin_family = AF_INET;
    cin.sin_port = htons(8888);
    cin.sin_addr.s_addr = inet_addr("192.168.125.27");

    // 连接服务器
    connect(cfd, (struct sockaddr *)&cin, sizeof(cin));
    init();

    char buf[128] = "";
    while (1)
    {
        printf("请输入指令:");
        fgets(buf, sizeof(buf), stdin);
        buf[strlen(buf) - 1] = '\0';
        RobArmCtl(buf);
        printf("指令发送成功\n");
    }

    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值