使用c++代码实现舵机
c#include <iostream> #include <fcntl.h> #include <termios.h> #include <unistd.h> #include <cstring> #include <chrono> #include <thread> #include <errno.h> const int PULSE_MIN = 500; // 最小脉冲宽度 (微秒,0度) const int PULSE_MAX = 2500; // 最大脉冲宽度 (微秒,180度) int main() { // 打开串口,USB转TTL适配器通常为/dev/ttyUSBx,替换为实际设备路径 int serial_port = open("/dev/ttyUSB1", O_RDWR); // 替换为实际的串口 if (serial_port < 0) { std::cerr << "无法打开串口!" << std::endl; return 1; } std::cout << "串口已打开!" << std::endl; // 配置串口设置 struct termios tty; memset(&tty, 0, sizeof(tty)); // 获取当前串口设置 if (tcgetattr(serial_port, &tty) != 0) { std::cerr << "获取串口设置失败!" << std::endl; close(serial_port); return 1; } std::cout << "串口设置成功!" << std::endl; // 设置波特率 cfsetispeed(&tty, B9600); // 输入波特率 cfsetospeed(&tty, B9600); // 输出波特率 // 设置其他串口参数 tty.c_cflag &= ~PARENB; // 无奇偶校验 tty.c_cflag &= ~CSTOPB; // 1个停止位 tty.c_cflag &= ~CSIZE; tty.c_cflag |= CS8; // 8个数据位 tty.c_cflag |= CREAD | CLOCAL; // 启用接收,忽略控制线路 tty.c_iflag &= ~(IXON | IXOFF | IXANY); // 禁用软件流控 tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // 原始模式 tty.c_oflag &= ~OPOST; // 原始输出模式 // 应用设置 tcflush(serial_port, TCIFLUSH); if (tcsetattr(serial_port, TCSANOW, &tty) != 0) { std::cerr << "设置串口失败!" << std::endl; close(serial_port); return 1; } std::cout << "串口设置成功!!!" << std::endl; std::cout << "程序已启动,发送 PWM 信号控制 SG90 舵机。" << std::endl; while (true) { // 移动到 0 度 std::cout << "移动到 0 度" << std::endl; write(serial_port, "1", 1); // 发送信号开启舵机 std::this_thread::sleep_for(std::chrono::microseconds(PULSE_MIN)); write(serial_port, "0", 1); // 发送信号关闭舵机 std::this_thread::sleep_for(std::chrono::milliseconds(200)); // 稍作延时 // 移动到 90 度 std::cout << "移动到 90 度" << std::endl; write(serial_port, "1", 1); // 发送信号开启舵机 std::this_thread::sleep_for(std::chrono::microseconds((PULSE_MIN + PULSE_MAX) / 2)); write(serial_port, "0", 1); // 发送信号关闭舵机 std::this_thread::sleep_for(std::chrono::milliseconds(200)); // 稍作延时 // 移动到 180 度 std::cout << "移动到 180 度" << std::endl; write(serial_port, "1", 1); // 发送信号开启舵机 std::this_thread::sleep_for(std::chrono::microseconds(PULSE_MAX)); write(serial_port, "0", 1); // 发送信号关闭舵机 std::this_thread::sleep_for(std::chrono::milliseconds(200)); // 稍作延时 // 等待 1 秒后再继续 std::this_thread::sleep_for(std::chrono::seconds(3)); } // 关闭串口 close(serial_port); std::cout << "串口已关闭!" << std::endl; return 0; }
接线方式
-
usb转ttl分别有五个针脚
- 3.3v
- 5v
- GND
- RX 接收数据的
- TX 发送数据的
-
蜂鸣器
- GND
- I/O
- VCC
5v -> VCC GND -> GND TX -> I/O
sg90有三个引脚,分别是红线(VCC),棕线(GND)和橙线(信号线)t通常使用5v
最好还是使用io口进行控制