With this serial interface you’ll be able to send commands from a console in your PC to the arduino. You can also define your own commands for the arduino.
In this example we use a desktop console app and an arduino program to move a servo attached to the Arduino.
Send the “servo” command from our desktop app to the arduino program, and type the desired angle. The arduino board connected via USB will do the rest!
Just need to use the methods read
and write
to communicate with the device through serial port. Those functions and the whole API definition are defined in david/serial_arduino and david/serial_cpp libraries.
You need to create two projects arduino_app and cpp_app, one will contain the code that will be uploaded to arduino and the other one the client application that will run in your PC.
$ bii init cpp_app
$ bii init arduino_app
Open the examples: C++ app code goes into your pc project and arduino code goes into the arduino’s project.
$ cd cpp_app $ bii open examples/serial_interface_cpp$ cd arduino_app $ bii open examples/serial_interface_arduino
Change the Serial Port ID in the main_cpp.cpp file with the one you are using with the arduino.
main_cpp.cpp
#include "david/serial_cpp/serial.h"
#include <string>
#include <iostream>
using namespace std;
int main()
{
string incomingData = "";
string input = "";
serial serialport('#', ';', "COM8", 9600); //Change the serial port ID!!
while(1){
input = serialport.read(); //read a message
if (input != "") cout << input << "\n";
else{
cout << "Enter: ";
cin >> incomingData;
incomingData = "#" + incomingData;
incomingData += ";";
serialport.writeString(incomingData); //send a message
}
}
return 0;
}
main_arduino.cpp
#include <Arduino.h>
#include <Servo.h>
#include "david/serial_arduino/serial.h"
serial serialport('#', ';', 9600);
String msg = "";
String premsg = "";
Servo myservo;
void setup() {
myservo.attach(9);
serialport.init();
}
// bii:#entry_point()
void loop() {
msg = serialport.read(); //read a message
if(msg != "")
{
serialport.writeOpen();
serialport.writeString(msg); //send a message
serialport.writeEnd();
if(premsg=="servo"){
int n;
n = atoi(msg.c_str());
myservo.write(n);
}
premsg = msg;
}
}
Execute following commands in each project:
Arduino App
$ bii arduino:settings
...
$ bii configure -t arduino
...
$ bii build
...
$ bii arduino:upload
C++ App
$ bii build
$ cd bin
$ #run solver executable
Enter: servo
servo
Enter: 180
180
Enter: servo
servo
Enter: 90
...
Now you can start hacking your own commands!