RT-Thread 串口设备驱动

文件名   serial.c


驱动接口


1. 注册设备

2. 初始化设备

3. 打开设备

4. 关闭设备

5. 读操作

6. 写操作

--------------------------------------------------------------------------------------------------------

1. 注册设备

rt_err_t rt_hw_serial_register(rt_device_t device, const char* name, rt_uint32_t flag, struct stm32_serial_device *serial)
{
RT_ASSERT(device != RT_NULL);

if ((flag & RT_DEVICE_FLAG_DMA_RX) ||
(flag & RT_DEVICE_FLAG_INT_TX))
{
RT_ASSERT(0);
}

device->type  = RT_Device_Class_Char;
device->rx_indicate = RT_NULL;
device->tx_complete = RT_NULL;
device->init  = rt_serial_init;
device->open = rt_serial_open;
device->close = rt_serial_close;
device->read  = rt_serial_read;
device->write = rt_serial_write;
device->control = rt_serial_control;
device->user_data= serial;

/* register a character device */
return rt_device_register(device, name, RT_DEVICE_FLAG_RDWR | flag);
}


2.初始化设备
static rt_err_t rt_serial_init (rt_device_t dev)
{

/* Enable USART */
USART_Cmd(uart->uart_device, ENABLE);
}


3.打开设备

static rt_err_t rt_serial_open(rt_device_t dev, rt_uint16_t oflag)
{
return RT_EOK;
}

4.关闭设备
static rt_err_t rt_serial_close(rt_device_t dev)
{
return RT_EOK;
}


5.读操作

static rt_size_t rt_serial_read (rt_device_t dev, rt_off_t pos, void* buffer, rt_size_t size)
{
/* polling mode */
while ((rt_uint32_t)ptr - (rt_uint32_t)buffer < size)
{
while (uart->uart_device->SR & USART_FLAG_RXNE)
{
*ptr = uart->uart_device->DR & 0xff;
ptr ++;
}
}
}


6.写操作

static rt_size_t rt_serial_write (rt_device_t dev, rt_off_t pos, const void* buffer, rt_size_t size)

{

/* polling mode */
if (dev->flag & RT_DEVICE_FLAG_STREAM)
{
/* stream mode */
while (size)
{
if (*ptr == '\n')
{
while (!(uart->uart_device->SR & USART_FLAG_TXE));
uart->uart_device->DR = '\r';
}


while (!(uart->uart_device->SR & USART_FLAG_TXE));  //注:  等待上一个数据发送完毕,通过检查状态寄存器的TXE实现
uart->uart_device->DR = (*ptr & 0x1FF);                          //将要发送的数据写入DR寄存器,实现发送  


++ptr; --size;
}
}

}

附:STM32库中串口发送数据的代码

void USART_SendData(USART_TypeDef* USARTx, uint16_t Data)
{
  /* Check the parameters */
  assert_param(IS_USART_ALL_PERIPH(USARTx));
  assert_param(IS_USART_DATA(Data)); 
    
  /* Transmit Data */
  USARTx->DR = (Data & (uint16_t)0x01FF);
}

可见,向串口发送数据(写操作),主要是向DR写数据。



你可能感兴趣的:(STM32)