1

I would like to send data from a C program into a Python program that will visualize this data. Development environment is a Linux (Ubuntu 18.04LTS) computer. To be clearer, both of the programs are running on the same computer.

I am using termios for opening the serial port in C program, and pySerial in the Python side. As for the serial port, I am using "ttyS0". The problem is that, when I send "Hello" from C program to the Python program and print it on the terminal what I see is space character, basically I am gettin this " ".

My question is, can I use the "ttyS0" serial port (I guess that is a virtual port) for this purpose?

Here is the C code:

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

// Termios init functions are not posted because the configuration
// is correct and proved that they are working.

int main()
{
    char *portname = "/dev/ttyS0";
    int fd;
    int wlen;
    unsigned char writeBuffer[] = "Hello!";

    fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        printf("Error opening %s: %s\n", portname, strerror(errno));
        return -1;
    }
    /*baudrate 115200, 8 bits, no parity, 1 stop bit */
    set_interface_attribs(fd, B115200);

    do{
        wlen = write(fd, writeBuffer, sizeof(writeBuffer));
        printf("Sent data is: \"%s\"\n", writeBuffer);
        delay(500);
    } while(1);
}

The Python code:

import serial
from time import sleep

port = "/dev/ttyS0"
ser = serial.Serial(port, 115200, timeout=0.5)

while True:
    data = ser.readline()   
    print(str(data.decode('utf-8')))
ser.close()

1 Answer 1

3

ttyS0 is your computer's serial port -- there's nothing "virtual" about it. Writing to this device will attempt to transmit data out of the computer using that port, and reading from the device will attempt to receive data from an external device connected to the port. There is no way for two programs on the same computer to usefully communicate using a serial port.

What I think you're looking for here is either a pipe, a socket pair, or a pty. Which one is most appropriate will depend on your specific requirements.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.