NIOS II串口非阻塞方式接收数据

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()函数。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

巨大八爪鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值