[研电赛技术支持] 用C++玩转MCU举例

[复制链接]
1015|2
 楼主| caizhiwei 发表于 2023-10-10 13:31 | 显示全部楼层 |阅读模式
1. 在头文件中定义基类,再定义父类
  1. class SerialFactory
  2. {
  3. public:
  4.     static SerialBase * creatRs485(void);
  5.     static SerialBase * creatRs232(void);
  6. };


2.
  1. class SerialGdRs485 : public SerialBase
  2. {
  3. public:
  4.     SerialGdRs485();
  5.     virtual ~SerialGdRs485();

  6.     virtual void close();
  7.     virtual bool open(uint8_t);

  8.     virtual void setParity(ParityType);
  9.     virtual void setDataBits(DataBitsType);
  10.     virtual void setStopBits(StopBitsType);
  11.     virtual void setBaudRate(BaudRateType);
  12.     virtual void setFlowControl(FlowType);

  13.     virtual int readBlock(char *data, unsigned int maxlen);
  14.     virtual int writeBlock(const char *data, unsigned int len);

  15. private:
  16.     u8 serialPort;
  17.     u8 parityType;
  18.     u8 stopBits;
  19.     u32 baudRates;
  20. };


当然这些驱动函数你需要在底层实现:
  1. //        BSP_RS485_Init( bsp_rs485_port2 );
  2. //        BSP_RS485_BaudRate_Set( bsp_rs485_port2, 115200);
  3. //        BSP_RS485_Parity_Set( bsp_rs485_port2, BSP_UART_PAR_NONE );
  4. //        BSP_RS485_StopBits_Set(bsp_rs485_port2, BSP_UART_STOP_1 );
  5. //        BSP_RS485_Open( bsp_rs485_port2 );


然后在C文件中new一个对象,功能是在一个task中收发rs485数据:
  1. static uint8_t recvBuf[64] = {0};
  2. static SerialBase *pComm[2];
  3.        
  4. /*!
  5.     \brief  主板LED控制任务
  6. */
  7. void led_task(void *pvParameters)
  8. {
  9.           uint8_t test[8] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x10, 0x44, 0x06};
  10.   
  11.           BSP_Led_init();
  12.        
  13.         pComm[0] = SerialFactory::creatRs485();
  14.        
  15.         pComm[0]->setBaudRate(BAUD9600);

  16.         pComm[0]->setParity(PAR_NONE);
  17.         /*数据位*/
  18.         pComm[0]->setDataBits(DATA_8);

  19.         pComm[0]->setStopBits(STOP_1); // 停止位

  20.         pComm[0]->open(1);

  21.     for(;;)
  22.     {
  23.         /* toggle LED */
  24.         MainBoard_LED_TOOGLE();   
  25.                 BSP_Feed_fwdgt();
  26.         vTaskDelay(500);
  27.                
  28.                 pComm[0]->writeBlock((const char *)test, 8);
  29.                 pComm[0]->readBlock((char *)recvBuf, 64 );
  30.                   
  31.                
  32.     }
  33. }





 楼主| caizhiwei 发表于 2023-10-10 13:32 | 显示全部楼层
小伙伴,你们学会了吗?
xia00 发表于 2023-10-22 10:15 | 显示全部楼层
如果一个团队用C开发,在搭建好的框架内,可能不需要每个人的水平都很高,有个别高手就能解决大部分BUG,但如果一个团队用C++开发,那就要求每个人都要精通C++,不然一个人就能搞死项目。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

100

主题

856

帖子

16

粉丝
快速回复 在线客服 返回列表 返回顶部