2

I am trying to send and receive character using UART (GPIO14 as Tx & GPIO15 as Rx). I can transmit character successfully which I can check on minicom. Now I have short my RX and Tx pin so that I can receive whatever I transmit. I can see in my code that on sending character 'a' I am receiving a character, but I cannot print its exact value . Here is my code:-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>

int main(void) {

    char *port;
port = "/dev/ttyAMA0";
    struct termios serial;
    char tab='a';

    printf("Opening %s\n", port);

    int fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);

    if (fd == -1) {
        perror(port);
        return -1;
    }

    if (tcgetattr(fd, &serial) < 0) {
        perror("Getting configuration");
        return -1;
    }
 // Set up Serial Configuration
    serial.c_iflag = 0;
    serial.c_oflag = 0;
    serial.c_lflag = 0;
    serial.c_cflag = 0;

    serial.c_cc[VMIN] = 0;
    serial.c_cc[VTIME] = 0;

    serial.c_cflag = B9600 | CS8 | CREAD;

    tcsetattr(fd, TCSANOW, &serial); // Apply configuration

    // Attempt to send and receive
    printf("Sending: %c\n", tab);

int wcount = write(fd, &tab,1);
    if (wcount < 0) {
        perror("Write");
        return -1;
    }
    else {
        printf("Sent successfully\n");
    }
int rcount = read(fd,&tab,1);
    if (rcount < 0) {
        perror("Read");
        return -1;
    }
    else {
        printf("Received %d characters\n", rcount);
    }

    printf("Received: %c\n", tab);

    close(fd);
}

Here is my output for this code:- Mostly I got:-

Opening /dev/ttyAMA0
Sending: a
Sent successfully
Received 1 characters
Received:

And rarely (around 1 out of 20 times) I got random character like this:-

Opening /dev/ttyAMA0
Sending: a
Sent successfully
Received 1 characters
Received: y

*note:- when I received some proper character (in rare case) it is not always 'y'. I can be any thing like 'y' , 'n' , 'p' etc.

So,can any one tell me where is the problem.

3

It is much easier to use the wiringSerial module from wiringPi, but if you must do it the hard way tab should be a buffer e.g. char tab[128] not a single char.

It looks like you are sending random junk and storing it who knows where.

NOTE You should use cfsetispeed to set baud rate read man termios

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.