Serial Communication – Why isn't this C program behaving like this Python program?

I have two programs that communicate through a serial USB interface with a CNC machine running grbl. The first program, written in Python using the pyserial library, produces intelligible output:

b'ok\r\n'
b'ok\r\n'

The second program, written in C using the libserialport library produces mangled output:

Found port: /dev/ttyUSB0
in:


in: M3 S100

out: �]�
in: M3 S0

out: �WH�

I’ve been staring at this for days trying to find substantive differences that could explain why the Python program works and the C one doesn’t, but I haven’t come up with anything yet. Both programs flush their input buffers, both programs send the same data with the same line endings, and both programs wait for the same amount of time in the same places. Any ideas on what I am doing wrong?

Python program:

import serial
import time

s = serial.Serial('/dev/ttyUSB0', 115200)

s.write(b"\r\n\r\n")
time.sleep(2)
s.flushInput()

s.write(b'M3 S100\n')
out = s.readline()
print(out)

time.sleep(1)

s.write(b'M3 S0\n')
out = s.readline()
print(out)

time.sleep(2)
s.close()

C program:

#include <libserialport.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

struct sp_port **port_list;
struct sp_port *main_port;

void ports_init() {

  sp_list_ports(&port_list);

  for (int i = 0; port_list[i] != NULL; i++) {
    struct sp_port *port = port_list[i];
    char *port_name = sp_get_port_name(port);

    printf("Found port: %s\n", port_name);

    if (strcmp(port_name, "/dev/ttyUSB0") == 0) {
      sp_open(port_list[i], SP_MODE_READ_WRITE);
      sp_set_baudrate(port_list[i], 112500);
      main_port = port_list[i];
      return;
    }
  }
}

void send_command(char *c) {
  sp_blocking_write(main_port, c, strlen(c), 1000);
  printf("in: %s\n", c);
}

void read_response() {
  char hi[256];
  bzero(hi, 256);
  sp_blocking_read(main_port, hi, 255, 1000);
  printf("out: %s\n", hi);
}

int main() {

  ports_init();

  send_command("\r\n\r\n");
  usleep(2 * 1000 * 1000);
  sp_flush(main_port, SP_BUF_BOTH);

  send_command("M3 S100\n");
  read_response();

  usleep(1 * 1000 * 1000);

  send_command("M3 S0\n");
  read_response();

  usleep(2 * 1000 * 1000);
}

>Solution :

You have a typo. In your python program you use 115200 as your baud rate, but in your C program you use 112500. Just change this line:

sp_set_baudrate(port_list[i], 112500);

to

sp_set_baudrate(port_list[i], 115200);

Leave a Reply