Quartus II 10.0版本以上可以用fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK)将标准输入stdin设为非阻塞模式,然后用getchar,read,scanf等函数接收串口数据。
笔者用的版本是Quartus II 13.0sp1 (64-bit)。
下面的程序实现了每隔1秒钟打印一次hello world和系统毫秒计数器的值,收到串口字符时立即打印出来的功能。
用read函数接收1字节字符,函数不阻塞,如果没有字符就会返回-1,有字符则返回1。
/*
* "Hello World" example.
*
* This example prints 'Hello from Nios II' to the STDOUT stream. It runs on
* the Nios II 'standard', 'full_featured', 'fast', and 'low_cost' example
* designs. It runs with or without the MicroC/OS-II RTOS and requires a STDOUT
* device in your system's hardware.
* The memory footprint of this hosted application is ~69 kbytes by default
* using the standard reference design.
*
* For a reduced footprint version of this template, and an explanation of how
* to reduce the memory footprint for a given application, see the
* "small_hello_world" template.
*
*/
#include <ctype.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/alt_alarm.h>
#include <unistd.h>
int main()
{
alt_u32 now, ticks = 0;
char ch;
int i = 0;
int ret;
printf("Hello from Nios II!\r\n");
printf("tick_rate=%lu\r\n", alt_ticks_per_second());
usleep(100000);
printf("ticks=%lu\r\n", alt_nticks());
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
while (1)
{
now = alt_nticks();
if (now - ticks > 1000)
{
ticks = now;
printf("Hello World! i=%d, ticks=%lu\r\n", i, now);
i++;
}
ret = read(STDIN_FILENO, &ch, 1);
if (ret == 1)
{
if (isprint(ch))
printf("UART0: %c\r\n", ch);
else
printf("UART0: 0x%02x\r\n", ch);
}
}
}
Qsys里面添加了Interval Timer IP核,定时时间为1ms,无起停控制位,固定定时周期。
在BSP Editor里面的Settings -> Common -> hal -> sys_clk_timer选中这个定时器,就可以用alt_nticks()函数了。这个函数就类似于STM32单片机HAL库里面的HAL_GetTick()函数。