活动介绍
file-type

PID控制策略比较研究:传统、模糊、神经网络PID

RAR文件

5星 · 超过95%的资源 | 下载需积分: 50 | 358KB | 更新于2025-05-23 | 167 浏览量 | 142 下载量 举报 28 收藏
download 立即下载
在当今的控制系统设计领域,PID(比例-积分-微分)控制是一种广泛使用的经典控制方法。随着技术的进步,对控制系统的性能要求越来越高,传统的PID控制方法在处理非线性、大滞后和不确定性动态系统时,可能会遇到一些局限性。为了解决这些问题,研究者们提出了模糊PID和神经网络PID等先进控制策略。本篇文档详细分析了常规PID、模糊PID和神经网络PID控制方法在控制效果上的比较,并提供了相应的仿真和编程实现文件。 ### 常规PID控制 PID控制器的核心思想是根据系统的误差(即设定值与实际输出之间的差异)来调整控制量。PID控制器包含三个主要参数:比例(P)、积分(I)和微分(D)。比例作用可以迅速减少误差,但通常会引起稳态误差;积分作用可以消除稳态误差,但可能导致系统响应缓慢;微分作用可以改善系统的动态响应,增加系统的稳定性。常规PID控制方法在控制系统设计中非常基础,适用于许多线性和线性化后的非线性系统。 ### 模糊PID控制 模糊PID控制是将传统PID控制与模糊逻辑控制相结合的产物。模糊控制不依赖于被控对象精确的数学模型,而是通过模拟人的决策思维,利用模糊规则来处理不确定性问题。在模糊PID控制器中,PID的三个参数(P、I、D)是可变的,它们根据输入误差和误差变化率的模糊集合,通过模糊逻辑推理得到相应的调整。这种控制方式在处理具有模糊性、不确定性和非线性特点的系统时,通常比传统的PID控制更为有效。 ### 神经网络PID控制 神经网络PID控制将神经网络的自学习和自适应能力引入PID控制结构中。神经网络通过学习控制对象的历史数据来调整PID参数,使得控制器能够适应环境的变化并提高控制精度。神经网络PID控制通常需要大量的数据来训练网络,以期达到良好的控制效果。其优势在于能够处理复杂的、非线性的、高维度的控制问题。 ### 控制效果比较 在本毕设项目中,研究者通过建立一个三阶模型来模拟系统的动态行为,并对常规PID、模糊PID和神经网络PID这三种控制策略进行了比较研究。在仿真实现中,常规PID和模糊PID控制器利用Matlab/Simulink中的GUI和mdl文件进行设计和调试。而神经网络PID控制则需要通过Matlab编程实现,这可能涉及神经网络工具箱的使用和深度学习算法的实现。 在效果比较中,可以考虑以下几个方面: 1. 系统的快速响应能力:哪一种控制方法能够使系统更快地达到稳定状态。 2. 控制精度:各控制方法在达到稳定状态后的控制精度如何。 3. 抗干扰能力:在面对系统参数变化或外部干扰时,各种控制方法的稳定性和鲁棒性。 4. 控制器设计的复杂性:不同控制方法在控制器设计上的难度和计算复杂度。 ### 结论 通过比较分析,我们可以得出不同控制策略在特定应用条件下的优劣。传统PID控制在一些线性或近似线性的系统中表现出色,但在处理复杂和不确定性问题时可能力不从心。模糊PID控制在应对复杂环境和非线性问题时,通过模糊规则对PID参数进行调整,表现出较好的鲁棒性和适应性。神经网络PID控制则在系统非常复杂、非线性特征明显或参数不确定性较大的情况下,提供了更为先进的控制方法,但实现过程复杂,需要大量的数据进行训练,且模型的解释性可能较差。 本项目的成功实施与分享,为智能控制系统的设计和研究提供了宝贵的经验和数据支持,对推动控制理论的发展和实际应用具有重要意义。对于从事控制系统设计的研究者和工程师来说,这些内容无疑是具有高度参考价值的。

相关推荐

filetype

rosroot@ubuntu:~# ros2 launch origincar_bringup usb_websocket_display.launch.py [INFO] [launch]: All log files can be found below /root/.ros/log/2025-07-25-00-30-32-000127-ubuntu-10457 [INFO] [launch]: Default logging verbosity is set to INFO launch webserver pwd_path is /root webserver_path is /opt/tros/lib/websocket/webservice launch webserver cmd is ./sbin/nginx -p . [INFO] [hobot_usb_cam-1]: process started with pid [10730] [INFO] [hobot_codec_republish-2]: process started with pid [10732] [INFO] [example-3]: process started with pid [10734] [INFO] [websocket-4]: process started with pid [10736] [example-3] [WARN] [1753374633.587285650] [example]: This is dnn node example! [example-3] [WARN] [1753374633.763922258] [example]: Parameter: [example-3] feed_type(0:local, 1:sub): 1 [example-3] image: config/test.jpg [example-3] image_type: 0 [example-3] dump_render_img: 0 [example-3] is_shared_mem_sub: 1 [example-3] config_file: config/fcosworkconfig.json [example-3] msg_pub_topic_name_: hobot_dnn_detection [example-3] [ERROR] [1753374633.765273884] [fcos_detection_parser]: class_names length 2 is not equal to class_num 80 [example-3] [ERROR] [1753374633.772209015] [example]: Load fcos Parser config file fail [example-3] [ERROR] [1753374633.772677390] [example]: Load config fail! [example-3] terminate called after throwing an instance of 'rclcpp::exceptions::RCLError' [example-3] what(): Failed to create interrupt guard condition in Executor constructor: the given context is not valid, either rcl_init() was not called or rcl_shutdown() was called., at /mnt/disk1/zhuo.wang/build_deb/cc_ws_x3/tros_ws/src/tros/rcl/rcl/src/rcl/guard_condition.c:67 [ERROR] [example-3]: process has died [pid 10734, exit code -6, cmd '/opt/tros/lib/dnn_node_example/example --ros-args --log-level warn --ros-args --params-file /tmp/launch_params__qq5sikn --params-file /tmp/launch_params_kuzvkrxa --params-file /tmp/launch_params_tng3_8d8 --params-file /tmp/launch_params_tit1364h --params-file /tmp/launch_params_g37rwcrp']. [hobot_usb_cam-1] [WARN] [1753374633.815094676] [hobot_usb_cam]: Camera calibration file: [/opt/tros/lib/hobot_usb_cam/config/usb_camera_calibration.yaml] does not exist! [hobot_usb_cam-1] If you need calibration msg, please make sure the calibration file path is correct and the calibration file exists! [hobot_usb_cam-1] [WARN] [1753374633.816883511] [hobot_usb_cam]: get camera calibration parameters failed [hobot_usb_cam-1] [WARN] [1753374633.817144553] [hobot_usb_cam]: Start to open device /dev/video8. [hobot_usb_cam-1] [WARN] [1753374633.894102243] [hobot_usb_cam]: Open & Init device /dev/video8 success.

filetype

01-01 00:08:12.495 1711 1711 I AEE_AEDV: $** *** *** *** *** *** *** *** Exception *** *** *** *** *** *** *** **$ 01-01 00:08:12.496 1711 1711 D AEE_AEDV: /vendor/bin/aee_dumpstatev_v2: filepath /data/vendor/aee_exp/temp/db.qHk3oU, pid -1360007168, tid -1360007168, exp_class 6, db_opt 0 01-01 00:08:12.498 1717 1717 E AEE_DUMPSTATEV: execute /vendor/bin/aee_dumpstatev_v2 01-01 00:08:12.507 1036 1036 E SpeechMessengerNormal: openCcciDriver(), open(/dev/ccci_aud) fail!! mCcciDeviceHandler: -1, errno: 2 01-01 00:08:12.507 1036 1036 W SpeechMessengerNormal: checkCcciStatusAndRecovery(), #20, sleep 10 ms & retry openCcciDriver 01-01 00:08:12.528 1717 1717 W libc : Access denied finding property "ro.version.confidential" 01-01 00:08:12.528 1717 1717 I AEE_DUMPSTATEV: begin 01-01 00:08:12.528 1717 1717 I AEE_DUMPSTATEV: Built commit 7c708b4421ea60f803088d5c00a634c95909c17c 01-01 00:08:12.529 1717 1717 E AEE_DUMPSTATEV: start set_signal_for_dumpstate 01-01 00:08:12.529 1717 1717 D AEE_DUMPSTATEV: cpu cores:8, online:8 01-01 00:08:12.530 1717 1717 I AEE_DUMPSTATEV: aee_opt=0x0 01-01 00:08:12.531 1717 1717 I AEE_DUMPSTATEV: archive_file_to_db: current dumped file is /data/vendor/aee_exp/temp/db.qHk3oU/__exp_main.txt 01-01 00:08:12.531 1717 1717 D AEE_DUMPSTATEV: archive_file_to_db: Collect file /data/vendor/aee_exp/temp/db.qHk3oU/__exp_main.txt to __exp_main.txt successfully, size 1296 01-01 00:08:12.532 1717 1717 I AEE_DUMPSTATEV: archive_file_to_db: current dumped file is /data/vendor/aee_exp/temp/db.qHk3oU/SYS_PROPERTIES 01-01 00:08:12.533 1046 1046 E sensors-hal-HfManager: try 19 times to wait device ready... 01-01 00:08:12.534 1717 1717 D AEE_DUMPSTATEV: archive_file_to_db: Collect file /data/vendor/aee_exp/temp/db.qHk3oU/SYS_PROPERTIES to SYS_PROPERTIES successfully, size 36992 01-01 00:08:12.534 1717 1717 I AEE_DUMPSTATEV: archive_file_to_db: current dumped file is /data/vendor/aee_exp/temp/db.qHk3oU/_exp_detail.txt 01-01 00:08:12.535 1717 1717 D AEE_DUMPSTATEV: archive_file_to_db: Collect file /data/vendor/aee_exp/temp/db.qHk3oU/_exp_detail.txt to _exp_detail.txt successfully, size 92 01-01 00:08:12.542 1717 1717 E AEE_DUMPSTATEV: archive_file_to_db: Failed to dump SYS_BLOCKIO, can not open file /sys/kernel/debug/blockio, No such file or directory 01-01 00:08:12.543 1717 1717 I AEE_DUMPSTATEV: archive_file_to_db: current dumped file is /proc/blocktag/blockio 01-01 00:08:12.544 1090 1124 I UAH_HAL : (1124)[wait_boot_init_completed] Waiting for 1st Boot 0.1 sec... errno: 0, value: 0 01-01 00:08:12.547 1717 1717 D AEE_DUMPSTATEV: archive_file_to_db: Collect file /proc/blocktag/blockio to SYS_BLOCKIO successfully, size 18709 01-01 00:08:12.547 1717 1717 I AEE_DUMPSTATEV: archive_file_to_db: current dumped file is /proc/ufs_debug 01-01 00:08:12.550 1012 1332 E TetherController: addInterface p2p0->20 succ 01-01 00:08:12.550 1012 1333 E TetherController: addInterface p2p0->20 succ 01-01 00:08:12.552 1717 1717 D AEE_DUMPSTATEV: archive_file_to_db: Collect file /proc/ufs_debug to SYS_STORAGE_DEBUG_UFS successfully, size 50558 01-01 00:08:12.554 1717 1717 E AEE_DUMPSTATEV: archive_file_to_db: Failed to dump SYS_STORAGE_DEBUG_MSDC, can not open file /proc/msdc_debug, No such file or directory 01-01 00:08:12.555 1717 1717 I AEE_DUMPSTATEV: archive_file_to_db: current dumped file is /sys/kernel/debug/mmprofile/buffer 01-01 00:08:12.556 1012 1332 E TetherController: addInterface p2p1->21 succ 01-01 00:08:12.559 1012 1333 E TetherController: addInterface p2p1->21 succ 01-01 00:08:12.571 1720 1720 I AEE_AED : Built commit 1fe4561f177e76c5c927d9204bc9c10c0df47204 01-01 00:08:12.571 1720 1720 D AEE_AED : Rtt command(type:0, string: arg0:1) 01-01 00:08:12.571 1720 1720 E aee_v2 : client connect socket fail: Connection refused 01-01 00:08:12.571 1720 1720 E AEE_AED : aee:rttdRtt command connect socket fail: Connection refused 01-01 00:08:12.572 1720 1720 D AEE_AED : aee:rttd_64Rtt waiting 64_daemon finish the job... 01-01 00:08:12.572 580 580 D AEE_AED : $===AEE===AEE===AEE===$ 01-01 00:08:12.572 580 580 D AEE_AED : p 0 poll events 1 revents 1 01-01 00:08:12.573 580 580 D AEE_AED : requesting from: pid=1720 cmd=23 01-01 00:08:12.581 1720 1720 E AEE_AED : Rtt command read 64_socket fail: Not a data message 01-01 00:08:12.586 1717 1717 D AEE_DUMPSTATEV: archive_file_to_db: Collect file /sys/kernel/debug/mmprofile/buffer to SYS_MMPROFILE successfully, size 3169936 01-01 00:08:12.608 1068 1068 E sensors-hal-HfManager: try 20 times to wait device ready... 01-01 00:08:12.614 1014 1023 D bspFwUpdate: [bspFwUpdate][ufs] ufs fw move succ! 01-01 00:08:12.614 1014 1023 D bspFwUpdate: [bspFwUpdate](null):fw_update success 01-01 00:08:12.614 1014 1023 D bspFwUpdate: [bspFwUpdate]Going to detect /data/oplus/fw_update/ufs 01-01 00:08:12.614 1014 1023 D bspFwUpdate: [bspFwUpdate]Going to create 01-01 00:08:12.614 1014 1023 D bspFwUpdate: [bspFwUpdate](null),monitor read begin

filetype

root@ubuntu:~# ros2 launch origincar_bringup usb_websocket_display.launch.py [INFO] [launch]: All log files can be found below /root/.ros/log/2025-07-25-17-31-52-966571-ubuntu-10912 [INFO] [launch]: Default logging verbosity is set to INFO launch webserver pwd_path is /root webserver_path is /opt/tros/lib/websocket/webservice launch webserver cmd is ./sbin/nginx -p . [INFO] [hobot_usb_cam-1]: process started with pid [11053] [INFO] [hobot_codec_republish-2]: process started with pid [11055] [INFO] [example-3]: process started with pid [11057] [INFO] [websocket-4]: process started with pid [11059] [example-3] [WARN] [1753435914.613104062] [example]: This is dnn node example! [example-3] [WARN] [1753435914.893210332] [example]: Parameter: [example-3] feed_type(0:local, 1:sub): 1 [example-3] image: config/test.jpg [example-3] image_type: 0 [example-3] dump_render_img: 0 [example-3] is_shared_mem_sub: 1 [example-3] config_file: config/fcosworkconfig.json [example-3] msg_pub_topic_name_: hobot_dnn_detection [example-3] [ERROR] [1753435914.894555902] [fcos_detection_parser]: class_names length 2 is not equal to class_num 80 [example-3] [ERROR] [1753435914.894755225] [example]: Load fcos Parser config file fail [example-3] [ERROR] [1753435914.894825766] [example]: Load config fail! [example-3] terminate called after throwing an instance of 'rclcpp::exceptions::RCLError' [example-3] what(): Failed to create interrupt guard condition in Executor constructor: the given context is not valid, either rcl_init() was not called or rcl_shutdown() was called., at /mnt/disk1/zhuo.wang/build_deb/cc_ws_x3/tros_ws/src/tros/rcl/rcl/src/rcl/guard_condition.c:67 [ERROR] [example-3]: process has died [pid 11057, exit code -6, cmd '/opt/tros/lib/dnn_node_example/example --ros-args --log-level warn --ros-args --params-file /tmp/launch_params_cwgh5fz1 --params-file /tmp/launch_params_6ec69pce --params-file /tmp/launch_params_khbqjyev --params-file /tmp/launch_params_iuziozp8 --params-file /tmp/launch_params_w5leczsi']. [hobot_usb_cam-1] [WARN] [1753435914.987403273] [hobot_usb_cam]: Camera calibration file: [/opt/tros/lib/hobot_usb_cam/config/usb_camera_calibration.yaml] does not exist! [hobot_usb_cam-1] If you need calibration msg, please make sure the calibration file path is correct and the calibration file exists! [hobot_usb_cam-1] [WARN] [1753435914.994379308] [hobot_usb_cam]: get camera calibration parameters failed [hobot_usb_cam-1] [WARN] [1753435914.994661096] [hobot_usb_cam]: Start to open device /dev/video8. [hobot_usb_cam-1] [WARN] [1753435915.086700377] [hobot_usb_cam]: Open & Init device /dev/video8 success. [websocket-4] [ERROR] [1753435919.856381991] [websocket]: Websocket did not receive AI data! Please check whether the AI data publisher still exists by 'ros2 topic info hobot_dnn_detection'! [websocket-4] [ERROR] [1753435924.857349055] [websocket]: Websocket did not receive AI data! Please check whether the AI data publisher still exists by 'ros2 topic info hobot_dnn_detection'! [websocket-4] [ERROR] [1753435929.855952188] [websocket]: Websocket did not receive AI data! Please check whether the AI data publisher still exists by 'ros2 topic info hobot_dnn_detection'! [websocket-4] [ERROR] [1753435934.854875773] [websocket]: Websocket did not receive AI data! Please check whether the AI data publisher still exists by 'ros2 topic info hobot_dnn_detection'! [websocket-4] [ERROR] [1753435939.854077154] [websocket]: Websocket did not receive AI data! Please check whether the AI data publisher still exists by 'ros2 topic info hobot_dnn_detection'! [websocket-4] [ERROR] [1753435944.853378754] [websocket]: Websocket did not receive AI data! Please check whether the AI data publisher still exists by 'ros2 topic info hobot_dnn_detection'! [websocket-4] [ERROR] [1753435949.852848457] [websocket]: Websocket did not receive AI data! Please check whether the AI data publisher still exists by 'ros2 topic info hobot_dnn_detection'! [websocket-4] [ERROR] [1753435954.852420186] [websocket]: Websocket did not receive AI data! Please check whether the AI data publisher still exists by 'ros2 topic info hobot_dnn_detection'! [websocket-4] [ERROR] [1753435959.852054268] [websocket]: Websocket did not receive AI data! Please check whether the AI data publisher still exists by 'ros2 topic info hobot_dnn_detection'! [websocket-4] [ERROR] [1753435964.851760481] [websocket]: Websocket did not receive AI data! Please check whether the AI data publisher still exists by 'ros2 topic info hobot_dnn_detection'! ^A[websocket-4] [ERROR] [1753435969.851507130] [websocket]: Websocket did not receive AI data! Please check whether the AI data publisher still exists by 'ros2 topic info hobot_dnn_detection'!

filetype

设备服务器 #include "serial.h" /*********************串口 start******************************/ #define FALSE -1 #define TRUE 0 int serial_Open(char *devpath) { /*分别为com1,com2, com3对应 ttyUSB0 ttyUSB1 ttyUSB2 */ int fd = open( devpath, O_RDWR|O_NOCTTY|O_NDELAY); if (FALSE == fd){ perror("Can't Open Serial Port"); return(FALSE); } //恢复串口为阻塞状态 if(fcntl(fd, F_SETFL, 0) < 0){ printf("fcntl failed!\n"); return(FALSE); } else{ printf("fcntl=%d\n",fcntl(fd, F_SETFL,0)); } //测试是否为终端设备 if(0 == isatty(fd)){ printf("standard input is not a terminal device\n"); return(FALSE); } else{ printf("isatty success!\n"); } printf("fd->open=%d\n",fd); return fd; } //fd串口号;speed传输波特率;databits数据位;flow_ctrl数据流;parity奇偶校验;stopbits停止位 int serial_Set(int fd,int speed,int flow_ctrl,int databits,int stopbits,int parity) { int i; int speed_arr[] = { B115200, B19200, B9600, B4800, B2400, B1200, B300}; int name_arr[] = {115200, 19200, 9600, 4800, 2400, 1200, 300}; struct termios options; /*tcgetattr(fd,&options)得到与fd指向对象的相关参数,并将它们保存于options,该函数还可以测试配置是否正确,该串口是否可用等。若调用成功,函数返回值为0,若调用失败,函数返回值为1. */ if ( tcgetattr( fd,&options) != 0) { perror("SetupSerial 1"); return(FALSE); } //设置串口输入波特率和输出波特率 for ( i= 0; i < sizeof(speed_arr) / sizeof(int); i++) { if (speed == name_arr[i]) { cfsetispeed(&options, speed_arr[i]); cfsetospeed(&options, speed_arr[i]); } } //修改控制模式,保证程序不会占用串口 options.c_cflag |= CLOCAL; //修改控制模式,使得能够从串口中读取输入数据 options.c_cflag |= CREAD; options.c_oflag &= ~(ONLCR | OCRNL); options.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); options.c_iflag &= ~(ICRNL | INLCR); options.c_iflag &= ~(IXON | IXOFF | IXANY); //设置数据流控制 switch(flow_ctrl) { case 0 ://不使用流控制 options.c_cflag &= ~CRTSCTS; break; case 1 ://使用硬件流控制 options.c_cflag |= CRTSCTS; break; case 2 ://使用软件流控制 options.c_cflag |= IXON | IXOFF | IXANY; break; } //设置数据位 //屏蔽其他标志位 options.c_cflag &= ~CSIZE; switch (databits) { case 5 : options.c_cflag |= CS5; break; case 6 : options.c_cflag |= CS6; break; case 7 : options.c_cflag |= CS7; break; case 8: options.c_cflag |= CS8; break; default: fprintf(stderr,"Unsupported data size\n"); return (FALSE); } //设置校验位 switch (parity) { case 'n': case 'N': //无奇偶校验位。 options.c_cflag &= ~PARENB; options.c_iflag &= ~INPCK; break; case 'o': case 'O'://设置为奇校验 options.c_cflag |= (PARODD | PARENB); options.c_iflag |= INPCK; break; case 'e': case 'E'://设置为偶校验 options.c_cflag |= PARENB; options.c_cflag &= ~PARODD; options.c_iflag |= INPCK; break; case 's': case 'S': //设置为空格 options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; break; default: fprintf(stderr,"Unsupported parity\n"); return (FALSE); } // 设置停止位 switch (stopbits) { case 1: options.c_cflag &= ~CSTOPB; break; case 2: options.c_cflag |= CSTOPB; break; default: fprintf(stderr,"Unsupported stop bits\n"); return (FALSE); } //修改输出模式,原始数据输出 options.c_oflag &= ~OPOST; options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);//我加的 //options.c_lflag &= ~(ISIG | ICANON); //设置等待时间和最小接收字符 options.c_cc[VTIME] = 1; /* 读取一个字符等待0*(0/10)s */ options.c_cc[VMIN] = 1; /* 读取字符的最少个数为0 */ //如果发生数据溢出,接收数据,但是不再读取 刷新收到的数据但是不读 tcflush(fd,TCIFLUSH); //激活配置 (将修改后的termios数据设置到串口中) if (tcsetattr(fd,TCSANOW,&options) != 0) { perror("com set error!\n"); return (FALSE); } printf("serial set success\n"); return (TRUE); } int serial_init(char *devpath, int baudrate) { int fd_comport = FALSE; //打开串口 if((fd_comport=serial_Open(devpath))<0){ perror("serial_Open"); return FALSE; } //设置串口数据帧格式 if (serial_Set(fd_comport,baudrate,0,8,1,'N')<0) { perror("serial_Set"); return FALSE; } return fd_comport; } ssize_t serial_recv_exact_nbytes(int fd, void *buf, size_t count) { ssize_t ret; ssize_t total = 0; assert(buf != NULL); while (total != count) { ret = read(fd, buf + total, count - total); if (ret == -1) { perror("serial->recv"); break; } else if (ret == 0) { fprintf(stdout, "serial->recv: timeout or end-of-file\n"); break; } else total += ret; } return total; } ssize_t serial_send_exact_nbytes(int fd, unsigned char *buf, size_t count) { ssize_t ret; ssize_t total = 0; assert(buf != NULL); #if 0 int i = 0; for (i = 0; i < 36; i++){ printf("%.2x ", buf[i]); } printf("\n"); #endif while (total != count) { ret = write(fd, buf + total, count - total); if (ret == -1) { perror("serial->send"); break; } else total += ret; } return total; } int serial_exit(int fd) { if (close(fd)) { perror("serial->exit"); return -1; } return 0; } /*********************串口 end ******************************/ Serial.h #ifndef __LIB_H__ #define __LIB_H__ #include <stdio.h> /*标准输入输出定义*/ #include <stdlib.h> /*标准函数库定义*/ #include <unistd.h> /*Unix 标准函数定义*/ #include <string.h> #include <fcntl.h> /*文件控制定义*/ #include <termios.h> /*PPSIX 终端控制定义*/ #include <errno.h> /*错误号定义*/ #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/wait.h> #include <arpa/inet.h> #include <assert.h> #include <poll.h> int serial_init(char *devpath, int baudrate); ssize_t serial_recv_exact_nbytes(int fd, void *buf, size_t count); ssize_t serial_send_exact_nbytes(int fd, unsigned char *buf, size_t count); int serial_exit(int fd); #endif Server.c #include <stdio.h> #include <string.h> //socket,bind,listen #include <sys/types.h> #include <sys/socket.h> //struct sockaddr_in #include <netinet/in.h> #include <netinet/ip.h> //htons,htonl #include <arpa/inet.h> //read,write #include <unistd.h> #include <pthread.h> #include "serial.h" //服务器初始化 int server_init(short port) { //1.创建监听套接字 int listenfd = -1; listenfd = socket(AF_INET,SOCK_STREAM,0); if(-1 == listenfd){ perror("socket"); return -1; } //2.绑定IP及其端口号 //2.1.创建专用地址结构体存储IP和端口号信息 struct sockaddr_in server_addr; memset(&server_addr,0,sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port);//5000+ server_addr.sin_addr.s_addr = htonl(INADDR_ANY); //2.2.完成绑定过程 int ret = -1; ret = bind(listenfd,(const struct sockaddr *)&server_addr,sizeof(server_addr)); if(-1 == ret){ perror("bind"); return -1; } //3.开启监听 ret = listen(listenfd,16); if(-1 == ret){ perror("listen"); return -1; } printf("server_init success\n"); return listenfd; } //服务器处理客户端连接请求 int server_wait_connect(int listenfd) { //4.处理连接请求 //关心客户端的连接信息 struct sockaddr_in client_addr; memset(&client_addr,0,sizeof(client_addr)); socklen_t len = sizeof(client_addr); int connfd = accept(listenfd,(struct sockaddr *)&client_addr,&len); if(-1 == connfd){ perror("accept"); return -1; } printf("connect success,client IP:%s,PORT:%d\n",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port)); return connfd; } int serial_fd = -1; int connfd = -1; pthread_mutex_t lock; //通信 void * server_exchange_data_pthread(void * arg) { int ret = -1; char buf[1024] = {0}; while(1){ memset(buf,0,sizeof(buf)); //pthread_mutex_lock(&lock); //接受客户端发送的数据 ret = read(connfd,buf,sizeof(buf)); if(-1 == ret){ perror("read"); return NULL; }else if(0 == ret){ printf("client exit\n"); return NULL; } ret = serial_send_exact_nbytes(serial_fd,buf,ret); //pthread_mutex_unlock(&lock); } } void * serial_recv_data_pthread(void * arg) { char buf[10]; int ret = -1; while(1){ memset(buf,0,10); if(connfd >= 0){ //pthread_mutex_lock(&lock); ret = serial_recv_exact_nbytes(serial_fd,buf,1); //printf("serial buf = %s\n",buf); write(connfd,buf,ret); //pthread_mutex_unlock(&lock); } } } int main() { signal(SIGPIPE,SIG_IGN); pthread_mutex_init(&lock,NULL); serial_fd = serial_init("/dev/rfcomm0",115200); pthread_t pid_serial; pthread_create(&pid_serial,NULL,serial_recv_data_pthread,NULL); //初始化服务器 int listenfd = server_init(8888); pthread_t pid; while(1){ connfd = server_wait_connect(listenfd); printf("connfd = %d\n",connfd); pthread_create(&pid,NULL,server_exchange_data_pthread,NULL); } } 详细解释代码,包括每一个函数的作用

weixin_39840588
  • 粉丝: 451
上传资源 快速赚钱