6.2 - UART串口数据发送之轮询
文章目录
- 1 实验任务
- 2 系统框图
- 3 软件实现
1 实验任务
本实验使用轮询方式实现UART串口数据的连续发送。
2 系统框图
参见6.1。
3 软件实现
注意事项:
- XUartPs_Send函数返回实际写入的个数;
- 使用轮询方式将TxBuffer中的数据依次发送完毕,实现起来还是较为简洁、易懂。
/************************** Include Files ***********************************/
#include "xparameters.h"
#include "xuartps.h"
#include "stdio.h"
#include "sleep.h"
/************************** Constant Definitions ****************************/
#define UART_DEVICE_ID XPAR_XUARTPS_0_DEVICE_ID
#define BUFFER_SIZE 256 // 发送缓冲区大小
#define FIFO_TRIGGER_LEVEL 32 // FIFO触发阈值
#define RECV_TIMEOUT 4 // 接收超时时间(单位:波特率时钟周期)
/************************** Function Prototypes *****************************/
s32 UartPsInit(XUartPs *UartPsInstPtr, XUartPsFormat* UartFormatPtr);
void SendConfigFilePolled(XUartPs *UartPsInstPtr);
/************************** Variable Definitions ****************************/
XUartPs UartInst;
u8 TxBuffer[BUFFER_SIZE] = { 0 }; // 接收缓冲区
int RxDataLength = 0; // 接收到的数据长度
XUartPsFormat UartFormat = {
XUARTPS_DFT_BAUDRATE, // 115200
XUARTPS_FORMAT_8_BITS,
XUARTPS_FORMAT_NO_PARITY,
XUARTPS_FORMAT_1_STOP_BIT
};
/************************** Function Implementation *************************/
int main()
{
//
s32 Status;
//
for (int i = 0; i < BUFFER_SIZE; i++) {
TxBuffer[i] = (u8)i; // 填充从 0 开始的递增数
}
// 初始化UART
Status = UartPsInit(&UartInst, &UartFormat);
if (Status != XST_SUCCESS) {
return XST_FAILURE;
}
// 主循环
while(1)
{
sleep(3);
SendConfigFilePolled(&UartInst);
}
//
return 0;
}
s32 UartPsInit(XUartPs *UartInstPtr, XUartPsFormat* UartFormatPtr)
{
//
s32 Status;
XUartPs_Config *UartConfigPtr;
// 查找UART配置
UartConfigPtr = XUartPs_LookupConfig(UART_DEVICE_ID);
if(NULL == UartConfigPtr)
{
return XST_FAILURE;
}
// 初始化UART
Status = XUartPs_CfgInitialize(UartInstPtr, UartConfigPtr, UartConfigPtr->BaseAddress);
if (Status != XST_SUCCESS) {
return XST_FAILURE;
}
// 设置UART数据格式
XUartPs_SetDataFormat(UartInstPtr, UartFormatPtr);
// 设置UART操作模式
XUartPs_SetOperMode(UartInstPtr, XUARTPS_OPER_MODE_NORMAL);
// 设置接收FIFO触发阈值
XUartPs_SetFifoThreshold(UartInstPtr, FIFO_TRIGGER_LEVEL);
// 设置接收超时
XUartPs_SetRecvTimeout(UartInstPtr, RECV_TIMEOUT);
// 设置中断掩码,使能FIFO触发中断和接收超时中断
XUartPs_SetInterruptMask(UartInstPtr, XUARTPS_IXR_RXOVR | XUARTPS_IXR_TOUT);
//
return XST_SUCCESS;
}
void SendConfigFilePolled(XUartPs *UartPsInstPtr) {
//
u32 BytesSent;
u32 TotalBytesSent = 0;
//
while (TotalBytesSent < BUFFER_SIZE) {
// 每次发送剩余的数据
BytesSent = XUartPs_Send(UartPsInstPtr, &TxBuffer[TotalBytesSent], BUFFER_SIZE - TotalBytesSent);
if (BytesSent == 0) {
// 如果 UART 忙,等待一段时间再重试
usleep(1000); // 等待 1ms
continue;
}
TotalBytesSent += BytesSent;
}
//
// xil_printf("Config file sent successfully in polled mode!\n");
//
return;
}