Arduino Serial Communication With C++

I just go my Arduino a couple of weeks ago and even though I haven’t had much chance to play with it one of the first things I wanted to do was send data to it from my computer. Am starting very simple, in this tutorial I will show you how to turn Arduino’s pin 13 light with C++

Why Visual C++

Before trying or even thinking about Microsoft’s .Net framework I was looking for open source solutions or native code, I came across great frameworks like openframeworks but the truth of the matter is that I could find a project that was as well documented and testes as Visual C++ was.

Another major set back was that the most popular solutions seemed to work with Linux only. Visual studio is also free and its IDE was specifically designed for the .Net framework so there is no better choice for me.

Step 1: Download and Install Visual Studio C++

Like I said, the IDE and the framework are free, so have at it.

Download the .Net Framework.

Download Visual Studio C++ 2010 Express Edition (free edition).

Step 2: Start a New C++ Console Project

Go to File->New->Project and choose console program as shown below. Name the project how ever you like.

Visual Studio C++ Console Project

Console Project Selection

Your Visual C++ Project Files

The only file you have to mess with is the file named the same way as your project but with the .cpp extension. I named my project “ArduinoComm”, so my file is “ArduinoComm.cpp”. Double click on that file to open it.

Visual Studio: Empty C++ Arduino Project

Empty C++ Arduino Project

How The Program Is Going to Work

Our program is going to work this way, it will ask the user to enter the serial port he wants to use and store the answer in a variable called portName. Then we will ask the person if they want to turn the light on or off, if they type on, the number 1 will be sent to the Arduino, 0 will be sent for off.

The program will contain a loop to ask the user if he wishes to continue or end the program.

We also need to set a baud rate, this is kinda like the frequency at which we will set the Arduino board to communicate. Add the following lines of code to your main function.

	String^ answer;
	String^ portName;
	int baudRate=9600;
	Console::WriteLine("Type in a port name and hit ENTER");
	portName=Console::ReadLine();

If you have used regular C++ only think of Console::WriteLine as cout and Console::ReadLine() as getline(cin,variable).

The SerialPort Class

The .Net framework has a class for you to play with your computer’s serial ports, this class is called SerialPort and it can be found under the namespace "System::IO::Ports". We will also use other methods under the System namespace so let’s use this one as well.

using namespace System;
using namespace System::IO::Ports;

Instantiating the Port Class

The serial port object needs a port name and baud rate in its constructors, so add the following lines to your code. Our serial port object will be "arduino".

	SerialPort^ arduino;
	arduino = gcnew SerialPort(portName, baudRate);

Opening The Port

Just like with text files the first thing you have do is open ports. Open is a method of the serial port class of which arduino is an object of.

arduino->Open();

The Loop

We will use a do while loop to run the loop the first time our program is run. Our answer string variable will store the answer for our two questions, "Want to continue?" and "on or off?"

do{
// all the communication will happen here
}while(String::Compare(answer,"yes")==0);

Inside The Loop

Sending a string to your Arduino board is done by using the method WriteLine of your arduino object. Add the following code to your loop, I think it is self explanatory but leave me a comment if you got any questions.

			// ask on or off
			Console::WriteLine("Type \"on\" to turn the light on or \"off\" to turn it off");
			// get answer
			answer=Console::ReadLine();
			//check that user typed one of the options
			if(String::Compare(answer,"on")==0)
				arduino->WriteLine("1"); // send 1 to arduino
			else if(String::Compare(answer,"off")==0)
				arduino->WriteLine("0"); // send 0 to arduino
			else
				Console::WriteLine(answer+" was not an option");
			// ask user if he wants to continue
			Console::WriteLine("Try again? yes/no");
			// get answer
			answer=Console::ReadLine();
			// clear the screen
			Console::Clear(); // clear the command line

The Full C++  Script

Here is the full script for those who are too lazy to follow or just don’t give a damn about what I say. Please note that I added some exception handling to test for errors in typing and what not.

#include "stdafx.h"

using namespace System;
using namespace System::IO::Ports;

int main(array<System::String ^> ^args)
{
	
	String^ answer;
	String^ portName;
	int baudRate=9600;
	Console::WriteLine("Type in a port name and hit ENTER");
	portName=Console::ReadLine();
	// arduino settings
	SerialPort^ arduino;
	arduino = gcnew SerialPort(portName, baudRate);
	// open port
	try
	{
		arduino->Open();

		do
		{
			// ask on or off
			Console::WriteLine("Type \"on\" to turn the light on or \"off\" to turn it off");
			// get answer
			answer=Console::ReadLine();
			//check that user typed one of the options
			if(String::Compare(answer,"on")==0)
				arduino->WriteLine("1"); // send 1 to arduino
			else if(String::Compare(answer,"off")==0)
				arduino->WriteLine("0"); // send 0 to arduino
			else
				Console::WriteLine(answer+" was not an option");
			// ask user if he wants to continue
			Console::WriteLine("Try again? yes/no");
			// get answer
			answer=Console::ReadLine();
			// clear the screen
			Console::Clear();
		}while(String::Compare(answer,"yes")==0);
		// close port to arduino
		arduino->Close();
	}
	catch (IO::IOException^ e  ) 
	{ 
		Console::WriteLine(e->GetType()->Name+": Port is not ready");
	}
	catch (ArgumentException^ e)
	{
		Console::WriteLine(e->GetType()->Name+": incorrect port name syntax, must start with COM/com");
	}
	// end program
	Console::Write("Press enter to close the program");
	Console::Read();
    return 0;
}

The Arduino Script

If you haven’t used Arduino’s serial class this is how it works. In your set up function you need to begin communication with your serial and set the baud rate the same value as we did in our C++ script (9600).

The next thing we do is check if the serial port is available, if it is we read the incoming data.

int ledPin = 13;
int state=0;
void setup() {
    pinMode(ledPin, OUTPUT); // pin will be used to for output
    Serial.begin(9600); // same as in your c++ script
}

void loop() {
  if (Serial.available() > 0)
  {
    state = Serial.read(); // used to read incoming data
    
    switch(state)// see what was sent to the board
    {
      case '1': // if the the one was sent
        digitalWrite(ledPin,HIGH);
      break;
      case '0': // if 0 was sent
        digitalWrite(ledPin,LOW);
      break;
      default:
      break; 
    }
  }
}
 

Not much can be said about the code above. We are using pin number 13 and setting it to HIGH if 1 was sent if 0 was sent we set it to LOW. We don’t do anything otherwise.

Test Your Program

Once your have uploaded the arduino script to your arduinio board head back to Visual Studio and press F5, the program should compile and you should see a console screen like the following.

Arduino C++ Program Running

Arduino Visual C++ Program

How To Get Your Port Name

The port name your Arduino is using starts with "com" and is followed by a number, you can get it by going to your Arduino compiler. Under Tools > Serial Port.

Arduino Port Name

My Arduino's Port Name is COM4

My port name is COM4, and that is exactly what I have to type in the console so that the program continues to run.

This will not always be your port name however, it depends on which USB port your Arduino is connected in.

Running Your Program Outside Of Visual Studio

You don’t have to be in Visual Studio to run your C++ program. If you look in your project files OUTSIDE of Visual Studio, in your debug folder you will find a file with the type "Application" and the same name as your project. This is your program’s executable file. You can take this file anywhere and double click it run the program.

Arduino Executable

Arduino Executable (.exe)

blog comments powered by Disqus