syedatta94
Posts: 1
Joined: Sun Jul 03, 2016 11:17 am

serial communication raspberry pi in C

Sun Jul 03, 2016 11:31 am

need help!!! I want to send data from arduino to raspberry pi, i want a c code which recieves the data from arduino and save it in an integer variable, please anybody can provide me with the code?? i have tried 2 or three codes from the internet but that doesn't work.

edo1
Posts: 136
Joined: Sun Jun 15, 2014 3:33 pm
Location: Russia

Re: serial communication raspberry pi in C

Sun Jul 03, 2016 10:03 pm

there is nothing raspberry-specific (except serial port name)

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

Re: serial communication raspberry pi in C

Sun Jul 03, 2016 10:10 pm

Explain how you have connected the Arduino to the Pi.

Show us your Arduino code.

Show us your Pi code.

Tell us what doesn't work.

AndyNC
Posts: 43
Joined: Thu Aug 30, 2012 7:04 am

Re: serial communication raspberry pi in C

Sat Jul 09, 2016 8:00 am

Hi,

From first principles and not giving complete code, one way to progress is:
list the serial devices

Code: Select all

ls /dev/tty*
You should get something like

Code: Select all

ls /dev/tty*
/dev/tty    /dev/tty16  /dev/tty24  /dev/tty32  /dev/tty40  /dev/tty49  /dev/tty57  /dev/tty8
/dev/tty0   /dev/tty17  /dev/tty25  /dev/tty33  /dev/tty41  /dev/tty5   /dev/tty58  /dev/tty9
/dev/tty1   /dev/tty18  /dev/tty26  /dev/tty34  /dev/tty42  /dev/tty50  /dev/tty59  /dev/ttyprintk
/dev/tty10  /dev/tty19  /dev/tty27  /dev/tty35  /dev/tty43  /dev/tty51  /dev/tty6   /dev/ttyUSB0
/dev/tty11  /dev/tty2   /dev/tty28  /dev/tty36  /dev/tty44  /dev/tty52  /dev/tty60
/dev/tty12  /dev/tty20  /dev/tty29  /dev/tty37  /dev/tty45  /dev/tty53  /dev/tty61
/dev/tty13  /dev/tty21  /dev/tty3   /dev/tty38  /dev/tty46  /dev/tty54  /dev/tty62
/dev/tty14  /dev/tty22  /dev/tty30  /dev/tty39  /dev/tty47  /dev/tty55  /dev/tty63
/dev/tty15  /dev/tty23  /dev/tty31  /dev/tty4   /dev/tty48  /dev/tty56  /dev/tty7
Choose the device you want.eg /dev/ttyUSB0
if its a USB serial converter. This is the name of MODEMDEVICE device in the following code:

Code: Select all

#include <termios.h>                                                         
#include <stdio.h>
#include <stdlib.h>	
#include <string.h>
#include <unistd.h>                                                          
#include <fcntl.h>                                                                                                               
#include <sys/types.h> 
#include <stdint.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <sys/types.h>
#include <termios.h>
#include <time.h>
#include <stdbool.h>
#include <stropts.h>
#include <poll.h>	

#include <errno.h>

#define BAUDRATE B19200                                                      
#define MODEMDEVICE "/dev/ttyAMA0"


int set_interface_attribs (int fd, int speed, int parity)
{
        struct termios tty;
        memset (&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                printf ("error %d from tcgetattr", errno);
                return -1;
        }

        cfsetospeed (&tty, speed);
        cfsetispeed (&tty, speed);

        tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;     // 8-bit chars
        // disable IGNBRK for mismatched speed tests; otherwise receive break
        // as \000 chars
        tty.c_iflag &= ~IGNBRK;         // disable break processing
        tty.c_lflag = 0;                // no signaling chars, no echo,
                                        // no canonical processing
        tty.c_oflag = 0;                // no remapping, no delays
        tty.c_cc[VMIN]  = 0;            // read doesn't block
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl

        tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
                                        // enable reading
        tty.c_cflag &= ~(PARENB | PARODD);      // shut off parity
        tty.c_cflag |= parity;
        tty.c_cflag &= ~CSTOPB;
        tty.c_cflag &= ~CRTSCTS;

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
        {
                return -1;
        }
        return 0;
}

void set_blocking (int fd, int should_block)
{
        struct termios tty;
        memset (&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                printf("error %d from tggetattr", errno);
                return;
        }

        tty.c_cc[VMIN]  = should_block ? 1 : 0;
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
                printf("error %d setting term attributes", errno);
}

	
int main(void)
{ 
	int fd;                                                             
    char buf[255];  
	int variable;
	struct pollfd fds[1];
	int ret, res;
		
	/* open the device */
	fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY | O_NONBLOCK);
	if (fd == 0)
	{
		perror(MODEMDEVICE);
		printf("Failed to open MODEMDEVICE \"/dev/ttyAMA0\"\n");
		exit(-1); 
	}

	set_interface_attribs (fd, BAUDRATE, 0);  // set speed to 19200 bps, 8n1 (no parity)
	set_blocking (fd, 0);                // set no blocking

	/* Open STREAMS device. */
	fds[0].fd = fd;
	fds[0].events = POLLRDNORM;

	for (;;)		// forever
	{
		ret = poll(fds, 1, 1000);		//wait for response

		if (ret > 0)
		{
			/* An event on one of the fds has occurred. */
			if (fds[0].revents & POLLHUP)
			{
				printf("Hangup\n");
			}
			if (fds[0].revents & POLLRDNORM)
			{
					res = read(fd,buf,255);
					buf[res]=0;		// terminate buffer
					sscanf(buf,"%d\n",&variable);
					printf("Received %d\n",variable);
			}
		}
	}
}

Compile with

Code: Select all

cc -c serialiopoll.c
cc  -o serialiopoll  serialiopoll.o
All the above I gleaned from the web and I'm thank full for their contribution.

This is a stripped down version of some code I use to receive asynchronous data from an RF receiver. I assume this is the way you will receive it from the Arduino.

It does compile and probably work but I've not tested it. There are a lot of header files, These are left over from the original program and I can't remember exactly which ones are required.

The points you need to pay attention to are
1) in linux the serial device is a file
2) the poll() function waits for data on the serial line and returns with fds[0].revents -> POLLRDNORM
3) res = read(fd,buf,255); reads up to 255 chars from the serial buffer
4) sscanf(buf,"%d\n",&variable); scans the string buf and converts the data to integer and places it in variable.
5) The functions set_blocking() and set_interface_attribs() were gleaned from the web.

As joan has explained you haven't given us much to go on so this post may not fit your application but is is one way forward and give one way of handling serial IO.

HIH

Andy

Romonga
Posts: 123
Joined: Mon May 09, 2016 7:09 pm
Location: Montgomery Il

Re: serial communication raspberry pi in C

Mon Jul 11, 2016 4:42 pm

The easiest class I have found to use is part of the wiringPi library. https://github.com/WiringPi/WiringPi/bl ... ngSerial.h

It takes care of the low level details. I use this lib to talk to any serial device.
You can run, but you will only die tired.

User avatar
[email protected]
Posts: 1984
Joined: Tue Feb 07, 2012 2:14 pm
Location: Devon, UK
Contact: Website

Re: serial communication raspberry pi in C

Fri Jul 15, 2016 6:27 am

Romonga wrote:The easiest class I have found to use is part of the wiringPi library. https://github.com/WiringPi/WiringPi/bl ... ngSerial.h

It takes care of the low level details. I use this lib to talk to any serial device.
Just FYI: wiringPi is maintained at http://wiringpi.com/

The github site is not mine and may not be up to date.

-Gordon
--
Gordons projects: https://projects.drogon.net/

John Public
Posts: 89
Joined: Thu Jan 16, 2014 2:16 pm

Re: serial communication raspberry pi in C

Sat Aug 20, 2016 12:53 pm

I have an addition question to OP.
I tested the code shown in this forum post with an USB input device connected to an RPi3. Works fine when I use open("/dev/ttyACM0"..) etc..
I'd like to send and receive data from an old Nokia Symbian mobile phone I have connected to another USB port.
The Linux command:

Code: Select all

ls /dev/tty*
It shows many USB devices. How do I find out which is connected to my mobile phone? Do I open all in sequence and try sending AT command and see if I get a response? Or what?

User avatar
topguy
Posts: 4931
Joined: Tue Oct 09, 2012 11:46 am
Location: Trondheim, Norway

Re: serial communication raspberry pi in C

Sat Aug 20, 2016 9:00 pm

Is your phone the only usb device connected ?
A good way to figure out which devices are creater for a specific device is to plug it in after boot and look at the last lines of the output of the "dmesg" command after that.
Some GSM modems ( which are mobiles phones in a way ) create multiple serialports and the simplest is to test with a terminal program like minicom or similar.
I always try "at" and "ate1v1" commands first. ( "ate1v1" turns on "echo" and "answers" )

John Public
Posts: 89
Joined: Thu Jan 16, 2014 2:16 pm

Re: serial communication raspberry pi in C

Sun Aug 21, 2016 8:51 am

My Rpi has multiple USB devices (keyboard, camera etc.).
I am designing a program (C) that should know when the phene is connected and what is the handle I can use to send sms messages.

User avatar
[email protected]
Posts: 1984
Joined: Tue Feb 07, 2012 2:14 pm
Location: Devon, UK
Contact: Website

Re: serial communication raspberry pi in C

Mon Aug 22, 2016 9:10 pm

John Public wrote:I have an addition question to OP.
I tested the code shown in this forum post with an USB input device connected to an RPi3. Works fine when I use open("/dev/ttyACM0"..) etc..
I'd like to send and receive data from an old Nokia Symbian mobile phone I have connected to another USB port.
The Linux command:

Code: Select all

ls /dev/tty*
It shows many USB devices. How do I find out which is connected to my mobile phone? Do I open all in sequence and try sending AT command and see if I get a response? Or what?

Code: Select all

ls /dev/serial
after you plug something in.

-Gordon
--
Gordons projects: https://projects.drogon.net/

User avatar
DavidS
Posts: 3239
Joined: Thu Dec 15, 2011 6:39 am
Location: USA
Contact: Website

Re: serial communication raspberry pi in C

Tue Aug 23, 2016 9:54 pm

syedatta94 wrote:need help!!! I want to send data from arduino to raspberry pi, i want a c code which recieves the data from arduino and save it in an integer variable, please anybody can provide me with the code?? i have tried 2 or three codes from the internet but that doesn't work.
You did not say on what OS?

I would assume Bare Metal (no OS at all), based on your description of what you wish to do.

In case of RISC OS
I can not help you in C, though in assembly I could.

In the case of a n*x (Linux, BSD, etc), read form and write to the serial device.
Save power, use fewer cycles total. Assembly Language forever :) .

3lev3n
Posts: 1
Joined: Fri Oct 12, 2018 7:59 am

Re: serial communication raspberry pi in C

Fri Oct 12, 2018 8:08 am

Code: Select all

if (fds[0].revents & POLLRDNORM)
			{
					res = read(fd,buf,255);
					buf[res]=0;		// terminate buffer
					sscanf(buf,"%d\n",&variable);
					printf("Received %d\n",variable);
			}

If I wan't to send a string from COM 3 on PC to USB0 on raspbian ? How to ?

AndyNC
Posts: 43
Joined: Thu Aug 30, 2012 7:04 am

Re: serial communication raspberry pi in C

Fri Oct 12, 2018 11:35 am

There is a load of info on the web.
A quick Google brings

https://www.cmrr.umn.edu/~strupp/serial.html

Have a read. There are many snippets there and probably many other places.

Cheers
Andy

Return to “C/C++”