【软硬件通信】ESP32 Arduino 服务端 控制舵机

1、安装esp32开发环境

搭建ESP32开发环境

2、编写舵机驱动程序

#include <WiFi.h>
#include <Arduino.h>

int freq = 50;      // 频率(20ms周期)
int channel = 8;    // 通道(高速通道(0 ~ 7)由80MHz时钟驱动,低速通道(8 ~ 15)由 1MHz 时钟驱动。)
int resolution = 8; // 分辨率
const int led = 16;

const char *ssid = "wifi-name"; //wifi名
const char *password = "wifi-pwd";//wifi密码

const IPAddress serverIP(192,168,0,101); //欲访问的服务端IP地址
uint16_t serverPort = 9010;         //服务端口号

WiFiClient client; //声明一个ESP32客户端对象,用于与服务器进行连接

int calculatePWM(int degree)
{ //0-180度
 //20ms周期,高电平0.5-2.5ms,对应0-180度角度
  const float deadZone = 6.4;//对应0.5ms(0.5ms/(20ms/256))
  const float max = 32;//对应2.5ms
  if (degree < 0)
    degree = 0;
  if (degree > 180)
    degree = 180;
  return (int)(((max - deadZone) / 180) * degree + deadZone);
}

void setup()
{
    pinMode(2, OUTPUT);
    
    ledcSetup(channel, freq, resolution); // 设置通道
    ledcAttachPin(led, channel);          // 将通道与对应的引脚连接
    
    Serial.begin(115200);
    Serial.println();

    WiFi.mode(WIFI_STA);
    WiFi.setSleep(false); //关闭STA模式下wifi休眠,提高响应速度
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println("Connected");
    Serial.print("IP Address:");
    Serial.println(WiFi.localIP());
    Serial.println(String("MAC address = ")  + WiFi.softAPmacAddress().c_str());
}

void loop()
{
    Serial.println("尝试访问服务器");
    if (client.connect(serverIP, serverPort)) //尝试访问目标地址
    {
        Serial.println("访问成功");
        client.print("Hello world!");                    //向服务器发送数据
        while (client.connected() || client.available()) //如果已连接或有收到的未读取的数据
        {
            if (client.available()) //如果有数据可读取
            {
                String line = client.readStringUntil('\n'); //读取数据到换行符
                Serial.print("读取到数据:");
                Serial.println(line);
                client.write(line.c_str()); //将收到的数据回发
                if(line == "1")
                {
                    Serial.print("打开灯");
                    digitalWrite(2, HIGH);   // turn the LED on (HIGH is the voltage level)
                    for (int d = 0; d <= 180; d += 10)
                    {
                      ledcWrite(channel, calculatePWM(d)); // 输出PWM
                      Serial.printf("value=%d,calcu=%d\n", d, calculatePWM(d));
                      delay(500);
                    }  
                }
                else
                {
                    Serial.print("关闭灯");
                    digitalWrite(2, LOW);    // turn the LED off by making the voltage LOW    
                }
            }
        }
        Serial.println("关闭当前连接");
        client.stop(); //关闭客户端
    }
    else
    {
        Serial.println("访问失败");
        client.stop(); //关闭客户端
    }
    delay(5000);
}

3、服务端通讯

while(1)
 
    port = 9010;
 
	% 构造服务器端tcpip对象
	tcpipServer = tcpip('192,168,0,101',port,'NetWorkRole','Server');
	set(tcpipServer,'Timeout',10);
	N = 1024;
	set(tcpipServer,'InputBufferSize',8*N);
	set(tcpipServer,'OutputBufferSize',1024);
	 
	% 打开连接对象
	fopen(tcpipServer);
	 
	% 发送指令
	instruction = 'Please send back a signal.';
	fwrite(tcpipServer,instruction,'int8');
	disp('Instruction sending succeeds.');
	numSent = get(tcpipServer,'valuesSent');
	disp(strcat('Bytes of instruction is :',num2str(numSent)));
	 
	% 等待接收数据
	while(1)
		nBytes = get(tcpipServer,'BytesAvailable');
		if nBytes > 0
			break;
		end
	end
	 
	% 接收数据
	receivedInstruction = fread(tcpipServer,nBytes,'int8');
	disp(strcat('received instruction is: ',char(receivedInstruction')));
	% 关闭和删除连接对象
	fclose(tcpipServer);
	delete(tcpipServer);
end

换其他的任何高级编程语言均可,实现tcp通讯即可。

引用:

驱动舵机

matlab tcp server 持续通信

猜你喜欢

转载自blog.csdn.net/oqqHun123/article/details/124981964