1089 views|0 replies

1662

Posts

0

Resources
The OP
 

MCU serial port sends data frame [Copy link]

It is rare to see information about how to send a frame of data in an interrupt mode. If you send a data frame in a waiting mode, it will waste time for a high-speed microcontroller. The following is a method of sending a data frame in an interrupt mode. The operating platform uses 51 MCU.

  First, define a data frame structure, which can be used as a global variable. All transmissions must pass through this structure:

  //Structure

  struct {

  char busy_falg; //Busy flag, if set to 1 when sending data, that is, set to 1 at the beginning of sending and set to 0 at the end of sending

  int index; //Index, pointing to the location where the array needs to be sent

  int length; //The length of the entire data frame

  char *buf; //Points to the data frame to be sent. It is recommended to be a global variable. Otherwise, once the sending starts, you must wait until the sending is completed, that is, judge that busy_flag is 0

  } send_buf;

  The function for sending data has a disadvantage, that is, it still needs to use while to detect whether the serial port is busy, but this is much better than taking up system time to send:

  //Send a frame

  void SendBuf(char *buf,int length)

  {

  while(busy_falg); //Check if the sending is busy, otherwise wait in a loop

  send_buf.length = length;

  send_buf.index = 0;

  send_buf.buf = buf;

  send_buf.busy_flag = 1;

  SBUF = send_buf.buf[0]; //Write to SBUF, start sending, and then automatically enter interrupt sending

  }

  Serial port interrupt sending function, pay attention to setting the idle flag to avoid calling the same structure for multiple sending frames during multi-tasking:

  void SerialInt() interrupt 4 //Serial port interrupt

  {

  if(RI == 1) //Serial port receiving

  {

  RI = 0;

  }

  else if(TI == 1) //Serial port sends

  {

  TI = 0;

  send_buf.index++;

  if(send_buf.index == send_buf.length)

  {

  send_buf.busy_falg = 0; //Sending is finished

  return;

  }

  SBUF = send_buf.buf[send_buf.index]; //Continue to send the next

  }

  }

  Serial port interrupt sending is as simple as this. Pay attention to the use of busy_flag and index.

This post is from Microcontroller MCU
 

Guess Your Favourite
Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list