[solved] Ubuntu C++ <--> Mega2560 Serial Communication

Hello,

I would like to communicate with my Arduino Mega2560 under Ubuntu with C++.
I couldn't find a working code in the web.

Does anybody know, how to solve my problem?

Nathan

I couldn't find a working code in the web.

Unbelievable.

Does anybody know, how to solve my problem?

Google again. Perhaps with a less narrow search. C++ on Ubuntu, windoze, etc. is the same.

PaulS:

I couldn't find a working code in the web.

Unbelievable.

Does anybody know, how to solve my problem?

Google again. Perhaps with a less narrow search. C++ on Ubuntu, windoze, etc. is the same.

What's windoze? I have never heard of it.

The only code I found is up here: Arduino Serial Communication With C++ Tutorial
Maybe now you could understand why I would like a Linux tutorial, because clr isn't possible in codeblocks, afaik.
Any advises?

It really is dead easy you know!

It's as simple as this - the serial ports (both in windows and *nix) may be read using the very same interface used to read files.

So, all you need to do is call fopen with the name of the serial port device as the filename.
You then read/write from/to the 'file'. It's a 27 line program to provide a dodgy read-only 'Serial Monitor' like the one in the arduino ide.

Here's the first 11 lines of something I threw together. You'll be fine from here. If you can read from a disk file, serial ports are just as easy to get started with.
If not, research how to read from a file.
Just make sure you change the serialPortFilename to reflect the port you're actually connected to (you can see it in the bottom right corner of the arduino ide, in the status-bar)

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

char serialPortFilename[] = "/dev/ttyACM0";

int main()
{
    char readBuffer[1024];
    int numBytesRead;

    FILE *serPort = fopen(serialPortFilename, "rwb");

Solution for reading from serial port:

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

char serialPortFilename[] = "/dev/ttyACM0";

int main()
{
    char readBuffer[1024];
    int numBytesRead;

    FILE *serPort = fopen(serialPortFilename, "r");

	if (serPort == NULL)
	{
		printf("ERROR");	
		return 0;
	}

	printf(serialPortFilename);
	printf(":\n");
	while(1)
	{
		memset(readBuffer, 0, 1024);
		fread(readBuffer, sizeof(char),1024,serPort);
		if(sizeof(readBuffer) != 0)
		{
			printf(readBuffer);
		}
	}
	return 0;
}

Writing to serial port:

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

char serialPortFilename[] = "COM5";

int main()
{
	FILE *serPort = fopen(serialPortFilename, "w");

	if (serPort == NULL)
	{
		printf("ERROR");	
		return 0;
	}

	char writeBuffer[] = {'1'};

	fwrite(writeBuffer, sizeof(char), sizeof(writeBuffer), serPort);
	fclose(serPort);
	return 0;

}

Thanks for your help. :slight_smile:

Ripper!

Learning is a lot of fun. Helping someone else to learn feels even better!