##// END OF EJS Templates

File last commit:

r132:133
r153:154
Show More
uart.cpp
108 lines | 1.8 KiB | text/x-c | CppLexer
/*
* uart.cpp
*
* Created on: Oct 16, 2014
* Author: Alan Aguilar Sologuren
*/
#include "uart.h"
namespace rbp {
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
/*!
*
*/
uart::uart(uint32_t baudrate,int buffsz){
fs=-1;
buffsize = buffsz;
rx_buffer = nullptr;
tx_buffer = nullptr;
if(!setup(baudrate)){
delete this; //TODO log
}
}
/*!
*
*/
uart::~uart() {
if(fs!=-1){
close(fs);
}
}
/*!
*
*/
bool uart::setup(uint32_t baudrate){
fs = -1;
//Open in non blocking read/write mode
fs = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fs == -1)
{
printf("Error - Unable to open UART. Ensure it is not in use by another application\n");// TODO cambiar al sistema de log
return false;
}
struct termios options;
tcgetattr(fs, &options);
options.c_cflag = baudrate | CS8 | CLOCAL | CREAD;
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcflush(fs, TCIFLUSH);
tcsetattr(fs, TCSANOW, &options);
return true;
}
/*!
*
*/
ssize_t uart::receive(uint8_t* rx_buff){
ssize_t cnt=0;
if (fs != -1)
{
rx_buffer = new uint8_t[256];
cnt = read(fs, (void*)rx_buffer, 255);
if (cnt < 0)
{
//An error occured (will occur if there are no bytes)
//TODO cambiar a sistema de log
}
else if (cnt == 0)
{
//No data waiting
//TODO cambiar a sistema de log
}
else
{
rx_buffer[cnt] = '\0';
rx_buff = rx_buffer;
}
}
return cnt;
}
/*!
*
*/
ssize_t uart::transmit(uint8_t* tx_buff, size_t nbytes){
ssize_t cnt=0;
if (fs != -1)
{
tx_buffer = tx_buff;
cnt = write(fs, (void*)tx_buffer, nbytes); //Filestream, bytes to write, number of bytes to write
if (cnt < 0)
{
printf("UART TX error\n");//TODO cambiar a sistema de log
}
}
return cnt;
}
} /* namespace rbp */