The first step to hardware in the loop: the laptop tells a board what to do. Here it switches the LED of an Arduino on and off over the USB cable, with ArduinoConnectorUSBBase.
What you need
- an Arduino UNO, or any board with an LED on LED_BUILTIN, on /dev/ttyACM0;
- the sketch in the comment at the top of arduino_usb.cpp, uploaded with the Arduino IDE. It reads a line from the serial port at 9600 baud and switches the LED on for ON and off for OFF.
Commands
A command is a ArduinoCMDBase whose get_cmd() gives the text to send. The example has two, ArduinoONCMD and ArduinoOFFCMD; the connector writes their text, with a new line, to the serial port.
Running the example
Type ON or OFF and Enter to switch the LED, and e to switch it off and stop. If the board is on another port, change /dev/ttyACM0 in the code; on Linux you may need to be in the dialout group to open it.
An Arduino over WiFi does the same over WiFi, and A differential drive robot with real motors drives the motors of a robot from a board.
The code
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
{
struct ArduinoONCMD : public ArduinoCMDBase
{
virtual std::string
get_cmd() const final;
};
std::
string ArduinoONCMD::
get_cmd()
const {
return "ON"; }
{
virtual std::string get_cmd() const final;
};
std::string ArduinoOFFCMD::get_cmd() const { return "OFF"; }
}
{
using namespace example;
ArduinoConnectorUSBBase connector("/dev/ttyACM0");
connector.connect();
ArduinoONCMD on_cmd;
ArduinoOFFCMD off_cmd;
std::string user_input;
while (true)
{
std::cout << "Enter command ON/OFF or e (to exit): ";
std::getline(std::cin, user_input);
if (user_input == "e")
{
connector.send_cmd(off_cmd);
break;
}
if (user_input == "ON")
{
connector.send_cmd(on_cmd);
}
if (user_input == "OFF")
{
connector.send_cmd(off_cmd);
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
connector.close_connection();
return 0;
}
Definition arduino_connector_usb_base.h:15
int main()
Definition discounted_returns.cpp:19
Definition pytorch_linear_regression.cpp:17
Definition arduino_connector_base.h:18
virtual std::string get_cmd() const final
Definition arduino_usb.cpp:45