User avatar
jbeale
Posts: 3517
Joined: Tue Nov 22, 2011 11:51 pm
Contact: Website

very simple serial port example?

Sun Apr 22, 2018 5:16 pm

If I want to read 4 bytes from the serial port in Python, it takes three lines, for example:

Code: Select all

import serial
ser = serial.Serial('/dev/ttyUSB0',115200)
inWord = ser.read(4)
If I want to do the same thing in C, what I have found takes more than a full page of code setting up the serial port. Here is one such example: https://stackoverflow.com/questions/694 ... -port-in-c

Is there a simpler way to do this in C?

EDIT: Actually the main() part of the code isn't too bad, I guess I can ignore all the details in the setup function.

User avatar
joan
Posts: 14473
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: very simple serial port example?

Sun Apr 22, 2018 5:59 pm

It's slightly unfair to compare C and Python in this way.

Python has no support, it's all handled by the imported serial module. The equivalent in C would be linking something like wiringPi and using its serial wrappers.

User avatar
DougieLawson
Posts: 36568
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: very simple serial port example?

Sun Apr 22, 2018 6:15 pm

There's lots of faffing about to do it in C (69 lines in my sample to read stuff from an Arduino).

Code: Select all

 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <termios.h>
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
 #include <unistd.h>

 #define BAUDRATE B9600
 #define MODEMDEVICE "/dev/arduino"
 #define _POSIX_SOURCE 1 /* POSIX compliant source */

 #define FALSE 0
 #define TRUE 1

 volatile int STOP=FALSE;

 void  main() {
   int ardin, timout, c, res;
   struct termios oldtio,newtio;
   char buf[255];
   char *filename = "/home/pi/ardtime.html";

   char ht_head[300] = "<html><HEAD><script type=\"text/javascript\">\r\nfunction reFresh() {\r\nlocation.reload(true)\r\n}window.setInterval(\"reFresh()\",1000);\r\n</script></HEAD><body><h1>";
   char ht_foot[100] = "</h1>Autoreload - once a second</body></html>";

   ardin = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
   if (ardin <0) {
     perror(MODEMDEVICE);
     exit(-1);
   }

   if ((timout = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1) {
     perror("Cannot open output file\n");
     exit(1);
   }
   close(timout);

   tcgetattr(ardin,&oldtio); /* save current serial port settings */
   bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */

   newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
   newtio.c_iflag = IGNPAR | ICRNL;
   newtio.c_oflag = 0;
   newtio.c_lflag = ICANON;
   newtio.c_cc[VMIN]     = 1;     /* blocking read until 1 character arrives */

   tcflush(ardin, TCIFLUSH);
   tcsetattr(ardin,TCSANOW,&newtio);

   while (STOP==FALSE) {
     res = read(ardin,buf,255);
     buf[res]=0;             /* set end of string, so we can printf */
     if (res > 1) {
       // printf("%s", buf);
       timout = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
       write(timout,ht_head,strlen(ht_head));
       write(timout,buf,res);
       write(timout,ht_foot,strlen(ht_foot));
       close(timout);
     }


     if (buf[0]=='z') STOP=TRUE;
   }

   tcsetattr(ardin,TCSANOW,&oldtio); /* restore the old port settings */
 }
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

paulslocum
Posts: 75
Joined: Sun Apr 09, 2017 10:54 pm

Re: very simple serial port example?

Sun Apr 22, 2018 7:26 pm

Generally C is a bit messy, but it's easy to wrap the messiness with whatever level of convenience functions you like. You could also try some of these answers:

https://stackoverflow.com/questions/297 ... al-library

1dot0
Posts: 430
Joined: Mon Nov 28, 2016 12:31 pm

Re: very simple serial port example?

Mon Apr 23, 2018 12:32 pm

hi,
as stated before, wiringPi is supposed to be the simplest way.
To enable UART:
1. Add the line
enable_uart=1
to the '/boot/config.txt' file, this line will set up the Serial Port UART and the necessary clocks on all Pi models.
2. Remove the phrase "console=serial0,115200" from the '/boot/cmdline.txt' file.
This action prevents Linux from starting a Console on the Serial Port.

wiringPi Homepage, explaining the API functions: http://wiringpi.com/reference/serial-library/
(unfortunately not showing some simple examples)

inofficial (!!) sourcecode on github, but eventually feat some examples:
https://github.com/WiringPi/WiringPi/tr ... r/examples

User avatar
jbeale
Posts: 3517
Joined: Tue Nov 22, 2011 11:51 pm
Contact: Website

Re: very simple serial port example?

Tue Apr 24, 2018 12:16 am

Thank you for the WiringPi suggestion! This is the simple C example I was looking for: https://github.com/WiringPi/WiringPi/bl ... rialRead.c

Return to “C/C++”