0

I am trying to use serial communication in Raspberry Pi. I found this link. I made only one change in the code and increase the buffer value to 30. Here my edited code:-

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

int main(int argc, char* argv[]) {

    struct termios serial;
    char* str = "Hello";
    char buffer[30];

    if (argc == 1) {
        printf("Usage: %s [device]\n\n", argv[0]);
        return -1;
    }

    printf("Opening %s\n", argv[1]);

    int fd = open(argv[1], O_RDWR | O_NOCTTY | O_NDELAY);

    if (fd == -1) {
        perror(argv[1]);
        return -1;
    }

    if (tcgetattr(fd, &serial) < 0) {
        perror("Getting configuration");
        return -1;
    }

    // Set up Serial Configuration
    serial.c_iflag = 0;
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 = B115200 | CS8 | CREAD;

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

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

//int wcount = write(fd, &str, strlen(str));
int wcount = write(fd, str, strlen(str));
    if (wcount < 0) {
        perror("Write");
        return -1;
    }
    else {
        printf("Sent %d characters\n", wcount);
    }

   // int rcount = read(fd, &buffer, sizeof(buffer));
int rcount = read(fd, buffer, sizeof(buffer));
    if (rcount < 0) {
        perror("Read");
        return -1;
    }
    else {
        printf("Received %d characters\n", rcount);
    }
    buffer[rcount] = '\0';

    printf("Received: %s\n", buffer);

    close(fd);
}

I short Rx and Tx pin and run this code. I should receive "Hello" but I am getting this:-

Received: pi@raspberrypi:~$ Hello

So, it is clear that I am receiving "Hello" but additionally I am automatically transmitting

 pi@raspberrypi:~$

So, please tell me I to stop transmitting my user name.

Community
  • 1
  • 1
Tabish Saifullah
  • 570
  • 1
  • 5
  • 25
  • *"I found [this link](http://stackoverflow.com/questions/17254923/raspberry-pi-uart-program-in-c-using-termios-receives-garbage-rx-and-tx-are-con)"* -- You didn't pay attention to my comment. Just because both of you have the same hardware doesn't mean you're using identical versions of Linux. Zeroing out the *termios* structure is simply bad coding practice and is unreliable. Debugging hint: (always) print out the **wcount** and **rcount**. – sawdust Mar 09 '15 at 00:10
  • Thanks for advise. but is there any way to avoid transmitting username? – Tabish Saifullah Mar 09 '15 at 04:48

0 Answers0