stm32 串口发送一帧数据(字符串版本和结构体版本)

使用stm32串口发送一帧数据,具体程序如下,相关知识点请自行脑补。

1、串口发送字符串

/*****************  发送一个字节 **********************/
//myUSARTx:具体串口
//ch: 一个8位的字节
void Debug_SendByte( USART_TypeDef * myUSARTx, uint8_t ch)
{
	/* 发送一个字节数据到USART */
	USART_SendData(myUSARTx,ch);
		
	/* 等待发送数据寄存器为空 */
	while (USART_GetFlagStatus(myUSARTx, USART_FLAG_TXE) == RESET);	
}

/*****************  发送字符串 **********************/
//myUSARTx:具体串口
//str:字符串
void Debug_SendString( USART_TypeDef * myUSARTx, char *str)
{
    uint8_t next=0; //指向下一个字节的变量
    do 
    {
       Usart_SendByte( myUSARTx, *(str + next) );
       next++;
    }  while(*(str + next!=);
  
  /* 等待发送完成 */
  while(USART_GetFlagStatus(myUSARTx,USART_FLAG_TC)==RESET)
  {}
}


//实际使用
Debug_SendString(DEBUG_USARTx,"AA A1 A2 A3 A4 A5 A6 A7 A8 BB");

2、串口发送结构体数据

typedef struct My_Test
{
  uint8_t head;   //帧头
  uint8_t length;
  uint8_t type;
  uint8_t command;
  uint8_t work;
  uint8_t fre;
  uint8_t chan;
  uint8_t check;
  uint8_t num;
  uint8_t end;    //帧尾
}My_Test;

//实际使用
My_Test mytest;

void My_Struct_Test(My_Test *mytest)
{
  mytest->head = 0xAA;  //帧头数据
  mytest->length = 0xA1;
  mytest->type = 0xA2;
  mytest->command = 0xA3;
  mytest->work = 0xA4;
  mytest->fre = 0xA5;
  mytest->chan = 0xA6;
  mytest->check = 0xA7;
  mytest->num = 0XA8;
  mytest->end = 0xBB;  //帧尾数据
}

void send_data(My_Test*mytest,uint8_t len)
{
  static uint8_t date=0,i=0;
  for(i=0;i<len;i++) //使用sizeof计算结构体
  {
    date = *(((uint8_t *)&mytest->head)+i); //从帧头开始 然后依次向下指向
    USART_SendData(DEBUG_USARTx,date); //发送一个字节
    while(USART_GetFlagStatus(DEBUG_USARTx,USART_FLAG_TC)!= SET);
  }
}

//具体调用
My_Struct_Test(&mytest);           //赋值
Debug("sizeof:%d
",sizeof(mytest));  //sizeof:10
send_data(&mytest,sizeof(mytest)); //发送一帧数据
经验分享 程序员 微信小程序 职场和发展