参考:RPi Serial Connection

本文来自:http://www.raspberry-projects.com/pi/programming-in-c/uart-serial-port/using-the-uart

Using the UART

If you are running Raspbian or similar then the UART will be used as a serial console.  Using a suitable cable, such as the TTL-232R-3V3-WE, you can connect it to your PC and using some simple terminal software set to 115200-8-N-1 use the command line interface to the Raspberry Pi in the same way as if you we're using a keyboard and screen connected to it.  However that's no use if you want to use the UART interface for your own application running on the RPi.

Turning off the UART functioning as a serial console

See here.

Using The UART In Your C Code

(This is based on the example code given here).

Headers required

#include <stdio.h>
#include <unistd.h> //Used for UART
#include <fcntl.h> //Used for UART
#include <termios.h> //Used for UART
Setting Up The UART

//-------------------------
//----- SETUP USART 0 -----
//-------------------------
//At bootup, pins 8 and 10 are already set to UART0_TXD, UART0_RXD (ie the alt0 function) respectively
int uart0_filestream = -1; //OPEN THE UART
//The flags (defined in fcntl.h):
// Access modes (use 1 of these):
// O_RDONLY - Open for reading only.
// O_RDWR - Open for reading and writing.
// O_WRONLY - Open for writing only.
//
// O_NDELAY / O_NONBLOCK (same function) - Enables nonblocking mode. When set read requests on the file can return immediately with a failure status
// if there is no input immediately available (instead of blocking). Likewise, write requests can also return
// immediately with a failure status if the output can't be written immediately.
//
// O_NOCTTY - When set and path identifies a terminal device, open() shall not cause the terminal device to become the controlling terminal for the process.
uart0_filestream = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY); //Open in non blocking read/write mode
if (uart0_filestream == -1)
{
//ERROR - CAN'T OPEN SERIAL PORT
printf("Error - Unable to open UART. Ensure it is not in use by another application\n");
} //CONFIGURE THE UART
//The flags (defined in /usr/include/termios.h - see http://pubs.opengroup.org/onlinepubs/007908799/xsh/termios.h.html):
// Baud rate:- B1200, B2400, B4800, B9600, B19200, B38400, B57600, B115200, B230400, B460800, B500000, B576000, B921600, B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, B4000000
// CSIZE:- CS5, CS6, CS7, CS8
// CLOCAL - Ignore modem status lines
// CREAD - Enable receiver
// IGNPAR = Ignore characters with parity errors
// ICRNL - Map CR to NL on input (Use for ASCII comms where you want to auto correct end of line characters - don't use for bianry comms!)
// PARENB - Parity enable
// PARODD - Odd parity (else even)
struct termios options;
tcgetattr(uart0_filestream, &options);
options.c_cflag = B9600 | CS8 | CLOCAL | CREAD; //<Set baud rate
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcflush(uart0_filestream, TCIFLUSH);
tcsetattr(uart0_filestream, TCSANOW, &options);
Transmitting Bytes

//----- TX BYTES -----
unsigned char tx_buffer[20];
unsigned char *p_tx_buffer; p_tx_buffer = &tx_buffer[0];
*p_tx_buffer++ = 'H';
*p_tx_buffer++ = 'e';
*p_tx_buffer++ = 'l';
*p_tx_buffer++ = 'l';
*p_tx_buffer++ = 'o'; if (uart0_filestream != -1)
{
int count = write(uart0_filestream, &tx_buffer[0], (p_tx_buffer - &tx_buffer[0])); //Filestream, bytes to write, number of bytes to write
if (count < 0)
{
printf("UART TX error\n");
}
}
Receiving Bytes

Because O_NDELAY has been used this will exit if there are no receive bytes waiting (non blocking read), so if you want to hold waiting for input simply put this in a while loop


//----- CHECK FOR ANY RX BYTES -----
if (uart0_filestream != -1)
{
// Read up to 255 characters from the port if they are there
unsigned char rx_buffer[256];
int rx_length = read(uart0_filestream, (void*)rx_buffer, 255); //Filestream, buffer to store in, number of bytes to read (max)
if (rx_length < 0)
{
//An error occured (will occur if there are no bytes)
}
else if (rx_length == 0)
{
//No data waiting
}
else
{
//Bytes received
rx_buffer[rx_length] = '\0';
printf("%i bytes read : %s\n", rx_length, rx_buffer);
}
}
Closing the UART if no longer needed

//----- CLOSE THE UART -----
close(uart0_filestream);

Using minicom on the UART

Install minicom:

sudo apt-get install minicom

Running minicom:

minicom -b 115200 -o -D /dev/ttyAMA0

To test the UART is working you can simply link the TX and RX pins to each other and verify minicom receives what you type.

Troubleshooting UART Problems

The above code works (we've used it for TX and RX). If you can't get to to work for you and you've been through the steps to release the UART from being used for the console try the following:

Permissions

This command will set read and write access permissions for all users on the UART – it shouldn't be needed but can be used just to be sure there is not a permissions problem:


sudo chmod a+rw /dev/ttyAMA0
Baud Rate Error

Try using a slower BAUD rate (or a single 0xFF byte which only has the start bit low) and see if it works.  We had a problem using 115k2 baud rate where our microcontroller communicating with the RPi could hit 113636baud or 119047baud.  113636baud had the lowest error margin so we used it and TX from the RPi being received by the microcontroller worked fine.  However when transmitting to the RPi nothing was ever received. Changing the microcontroller to use 119047baud caused RX to work. We then tested the RPi transmitting a byte of 0×00 and measured the low state on a scope we got 78uS, showing an actual baud rate of 115384 from the RPi (8bits + the start bit all low).  This was odd as 113636baud still had to lower error margin but that was the finding.

Are you over or under clocking the RPi? If so do you need to adjust the baud rate to compensate for this?

General UART Programming Resources

http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/x115.ht

Raspberry Pi Resources-Using the UART的更多相关文章

  1. Raspberry Pi UART with PySerial

    参考:http://programmingadvent.blogspot.hk/2012/12/raspberry-pi-uart-with-pyserial.html Raspberry Pi UA ...

  2. A new comer playing with Raspberry Pi 3B

    there are some things to do for raspberry pi 3b for the first time: 1, connect pi with monitor/KB/mo ...

  3. RASPBERRY PI 外设学习资源

    参考: http://www.siongboon.com/projects/2013-07-08_raspberry_pi/index.html Raspberry Pi         Get st ...

  4. Raspberry Pi上手

    2013-05-21 买的树莓派终于到手了,嘿嘿.我在官方代理ICKEY买的,是英国版,B型. 上手教程可以根据Getting Started with Raspberry Pi(网上有电子版免费下载 ...

  5. Adding an On/Off switch to your Raspberry Pi

    http://www.raspberry-pi-geek.com/Archive/2013/01/Adding-an-On-Off-switch-to-your-Raspberry-Pi#articl ...

  6. Raspberry Pi GPIO Protection

    After damaging the GPIO port on our raspberry pi while designing a new solar monitoring system we de ...

  7. Device trees, Overlays and Parameters of Raspberry Pi

    Raspberry Pi's latest kernels and firmware, including Raspbian and NOOBS releases, now by default us ...

  8. Raspberry Pi - Huawei HiLink E3256 3G modem to ethernet adapter

    Raspberry Pi - Huawei HiLink E3256 3G modem to ethernet adapter This page documents how to configure ...

  9. 【树莓派】【转载】Raspberry Pi (树莓派)折腾记

    在网上看到一篇对树莓派折腾记录比较详细的文章,时间比较早,但是有些东西没变. 对于新手而言,还是有点参考价值.文章参见:http://skypegnu1.blog.51cto.com/8991766/ ...

随机推荐

  1. Openstack+Kubernetes+Docker微服务实践之路--弹性扩容

    服务上线就要顶的住压力.扛的住考验,不然挨说的还是我们这帮做事的兄弟,还记得上图这个场景吗 老办法是服务集群部署,但总归有个上限,之前跟阿里合作的时候他们有个弹性计算可以通过设置CPU的阀值来动态扩展 ...

  2. UVA Open Credit System Uva 11078

    题目大意:给长度N的A1.....An 求(Ai-Aj)MAX 枚举n^2 其实动态维护最大值就好了 #include<iostream> #include<cstdio> u ...

  3. 数据格式json讲解

    JSON 在使用名称/值对或XML时,实际上是使用javascript从应用程序中取得数据并将数据转换成另一种数据格式.javascript不仅作为格式化语言使用,还可以使用javascript语言中 ...

  4. Nginx基础知识之————RTMP模块中的中HLS专题(翻译文档)

    一.在Nginx配置文件的RTMP模块中配置hls hls_key_path /tmp/hlskeys; 提示错误信息: nginx: [emerg] the same path name " ...

  5. zoj3806Incircle and Circumcircle

    链接 自己的本本没有装画图软件,先借用两张图片..博客园不让贴源地址... 可以想到对于一个确定的外接圆的三角形来说内切圆最大的时候为等边三角形,如下图: 确定有合法的解之后,接下来就是去找这个解,解 ...

  6. 关于STM32的抢占式优先级说明。——Arvin

    关于STM32的中断设置.--Arvin 中断 STM32 很多人在配置STM32中断时对固件库中的这个函数NVIC_PriorityGroupConfig()配置优先级分组方式,会很不理解,尤其是看 ...

  7. APP敏捷测试,测试和开发并行!

    测试和开发具有同等重要的作用,从一开始,测试和开发就是相向而行的.测试是开发团队的一支独立的.重要的支柱力量. 测试要具备独立性,独立分析业务需求,独立配置测试环境,独立编写测试脚本,独立开发测试工具 ...

  8. 结合个人经历总结的前端入门方法 (转自https://github.com/qiu-deqing/FE-learning)

    结合个人经历总结的前端入门方法 (https://github.com/qiu-deqing/FE-learning),里面有很详细的介绍. 之前一直想学习前端的,都不知道怎么下手都一年了啥也没学到, ...

  9. Android TabWidget底部显示

    TabHost控件默认使用LinearLayout包裹TabWidget和FrameLayout,布局文件如下: <TabHost xmlns:android="http://sche ...

  10. Java内存模型

    1. 概述 多任务和高并发是衡量一台计算机处理器的能力重要指标之一.一般衡量一个服务器性能的高低好坏,使用每秒事务处理数(Transactions Per Second,TPS)这个指标比较能说明问题 ...