7.主函数进行相关初始化
int main(int argc, char **argv)
{
int err;
rt_kprintf("this is rt-thread test!rn");
virtual_com =rt_device_find("vcom");//查找设备
if(virtual_com!=RT_NULL)
{
err=rt_device_init(virtual_com);
}
else
return -1;
rt_device_open(virtual_com,RT_DEVICE_FLAG_RDWR|RT_DEVICE_FLAG_INT_RX);//打开设备
rt_sem_init(&rx_sem,"rx_sem",0,RT_IPC_FLAG_FIFO);//初始化接收信号量
rt_device_set_rx_indicate(virtual_com,uart_input);//设置串口接收回调函数
rt_thread_t thread =rt_thread_create("virtual_com",virtual_com_thread_entry,RT_NULL,1024,25,10);
if(thread!=RT_NULL) //创建串口处理函数线程
rt_thread_startup(thread);
else
return -1;
return 0;
}
8.接收数据并处理,上位机发送的数据,开发板收到后,再发送给上位机。
static rt_device_t virtual_com =RT_NULL;
static struct rt_semaphore rx_sem;
static char rcv_buf[64];
static unsigned char rcv_num=0;
static unsigned char rcv_startf=1;//上电默认一直等待接收数据
static rt_err_t uart_input(rt_device_t virtual_com,rt_size_t size)
{
rt_sem_release(&rx_sem);
return RT_EOK;
}
static char uart_get_char(void)
{
char ch;
while (rt_device_read(virtual_com, 0, &ch, 1) !=1)
{
rt_sem_control(&rx_sem, RT_IPC_CMD_RESET, RT_NULL);
if(rcv_startf)
rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
else if(-RT_ETIMEOUT == rt_sem_take(&rx_sem, 100))
{ //接收的数据之间加等待超时,超时或者有'n',认为一包数据接收完。
rcv_startf = 1;
ch = 'n';
return ch;
}
}
rcv_startf = 0; //
return ch;
}
static void virtual_com_thread_entry(void *parameter)
{
char ch,temp;
while(1)
{
temp = uart_get_char();
if(temp != 'n')
{
if(rcv_num<64)
rcv_buf[rcv_num++] = temp;
else {
rt_device_write(virtual_com,0,&rcv_buf,sizeof(rcv_buf));
rt_memset(rcv_buf, 0, sizeof(rcv_buf));
rcv_num=0;
rcv_buf[rcv_num++] = temp;
}
}
else
{
rt_device_write(virtual_com,0,&rcv_buf,sizeof(rcv_buf));
rcv_num = 0;
rt_memset(rcv_buf, 0, sizeof(rcv_buf));
}
}
}
9.编译工程,下载完成后,按下开发板复位键,打开电脑端串口软件。