基本思想:随手记录一下树莓派的测试串口通信和超声波模块
第一步、测试树莓派的串口程序
可以通过桌面的设置,在Raspberry Pi Configuration中将Serial Port设置为Enable, 我全部打开了
引脚定义
第二步、根据pin引脚,引入usb转ttl引针,然后打开串口工具
第三步、先使用权限命令打开权限
pi@raspberrypi:~/sxj731533730 $ sudo chmod 777 /dev/ttyS0
测试代码
pi@raspberrypi:~/sxj731533730 $ cat a.py
import serial
ser = serial.Serial('/dev/ttyS0',9600)
ser.isOpen()
ser.write('Hello CSDN !!'.encode('utf-8'))
python测试结果
c++测试代码
#include#include #include #include #include #include #include #include #include #include #include using namespace std; int sendSerialPort(const unsigned char W_BUF[], int length) { int tty_fd = -1; int rv = -1; struct termios options; tty_fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY); //打开串口设备 fcntl(tty_fd, F_SETFL, 0); if (tty_fd < 0) { printf("open tty failed:%sn", strerror(errno)); close(tty_fd); return -1; } printf("open devices sucessful!n"); memset(&options, 0, sizeof(options)); rv = tcgetattr(tty_fd, &options); //获取原有的串口属性的配置 if (rv != 0) { printf("tcgetattr() failed:%sn", strerror(errno)); close(tty_fd); return -1; } options.c_cflag |= (CLOCAL | CREAD); // CREAD 开启串行数据接收,CLOCAL并打开本地连接模式 options.c_cflag &= ~CSIZE;// 先使用CSIZE做位屏蔽 options.c_cflag |= CS8; //设置8位数据位 options.c_cflag &= ~PARENB; //无校验位 cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); options.c_cflag &= ~CSTOPB; options.c_cc[VTIME] = 0; options.c_cc[VMIN] = 0; tcflush(tty_fd, TCIFLUSH); if ((tcsetattr(tty_fd, TCSANOW, &options)) != 0) { printf("tcsetattr failed:%sn", strerror(errno)); close(tty_fd); return -1; } std::cout << std::endl << "length= " << length << std::endl; rv = write(tty_fd, W_BUF, length); if(rv<=0) { if (errno == EINTR) { close(tty_fd); printf("[SeanSend]error errno==EINTR continuen"); } else if (errno == EAGAIN) { sleep(1);//等待一秒,希望发送缓冲区能得到释放 close(tty_fd); printf("[SeanSend]error errno==EAGAIN continuen"); } else { printf("[SeanSend]ERROR: errno = %d, strerror = %s n", errno, strerror(errno)); return (-1); } } if (rv < 0) { printf("Write() error:%sn", strerror(errno)); close(tty_fd); return -1; } for (int i = 0; i < length; i++) { std::cout << std::hex << (int) W_BUF[i] << " "; } close(tty_fd); printf("nWrite() successfullyn"); return 0; } int main(int argc, char **argv) { //0xFD 0x00 0x07 0x01 0x01 0xD6 0xB1 0xD0 0xD0 0x9D //直行 //0xFD 0x00 0x07 0x01 0x01 0xD7 0xF3 0xD7 0xAA 0xA3 //左转 //0xFD 0x00 0x07 0x01 0x01 0xD3 0xD2 0xD7 0xAA 0x86 //右转 const unsigned char data[][10] = {{0xFD, 0x00, 0x07, 0x01, 0x01, 0xD6, 0xB1, 0xD0, 0xD0, 0x9D}, {0xFD, 0x00, 0x07, 0x01, 0x01, 0xD7, 0xF3, 0xD7, 0xAA, 0xA3}, {0xFD, 0x00, 0x07, 0x01, 0x01, 0xD3, 0xD2, 0xD7, 0xAA, 0x86}}; sendSerialPort(data[0], sizeof(data[0]));//测试 return 0; }
测试方法
pi@raspberrypi:~/sxj731533730 $ g++ a.cpp pi@raspberrypi:~/sxj731533730 $ ./a.out open devices sucessful! length= 10 fd 0 7 1 1 d6 b1 d0 d0 9d Write() successfully
测试结果
第四步、测试超声波模块



