Você está na página 1de 4

Interfacing ARDUINO with C++

Requirements: Visual C++ 2008 (tested) or Visual C++ 2010 (most probably will work) Arduino 22

Visual C++ 1. Create a new CLR Console Application Project

2. The only file you have to mess with is the file named the same way as your project but with the .cpp extension.

3. Copy Paste the following code into VC++ project and build it Code to transmit data
#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(); SerialPort^ arduino; arduino = gcnew SerialPort(portName, baudRate); arduino->Open(); // open port while(1) { Console::WriteLine("Type \"on\" to turn the light on or \"off\" to turn it off and \"exit\" to quit"); answer=Console::ReadLine(); // get answer 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 if(String::Compare(answer,"exit")==0) return 0; else Console::WriteLine(answer+" was not an option"); Console::Clear(); } }

Code to receive data


#include "stdafx.h" using namespace System; using namespace System::IO::Ports; int main(array<System::String ^> ^args) { String^ portName; String^ message; int baudRate=9600; Console::WriteLine("Type in a port name and hit ENTER"); portName=Console::ReadLine(); SerialPort^ arduino; arduino = gcnew SerialPort(portName, baudRate); arduino->Open(); // open port while(1) { message = arduino->ReadLine(); //read data received until \n Console::WriteLine(message); //display message on console } }

4. Upload the appropriate code into arduino Code to receive data (to be used with Code to transmit data on VC++)
int state=0; void setup() { pinMode(13, 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(13,HIGH); break; case '0': // if 0 was sent digitalWrite(13,LOW); break; } } }

Code to transmit data (to be used with Code to receive data on VC++)
Int value; Void setup() { Serial.begin(9600); } Void loop() { value= analogRead(0); Serial.write(value); Serial.write(\n); Delay(100) }

5. Connect the arduino to the PC via USB cable 6. Run the code on ardino and on VC++ 7. At runtime enter the COM port number when Promted

Note: COM port number can be obtained from arduino IDE (Tools>Serial port)

References: http://msdn.microsoft.com/enus/library/system.io.ports.serialport.aspx http://arduino.cc Documented by: Nischal K.N Dt: 5th Nov11

Você também pode gostar