Sunday, February 27, 2022

[SOLVED] Sending user inputted commands to an arduino in c++ using system() on a linux terminal

Issue

Using a c++ program i can successfully send commands to an arduino. The code uses the command:

system("$echo [command] > dev/ttyACM0");

Currently i must manually input the commands into this space, I was wondering if it's possible for a user to input the command, and for it to then be added to the string within system()?


Solution

This is an approximation of what I think you want:

#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::string command;
    if(std::getline(std::cin, command)) {  // read user input
        std::ofstream ard("/dev/ttyACM0"); // open the device
        if(ard) {
            ard << command << '\n';        // send the command
        }
    } // here `ard` goes out of scope and is closed automatically
}

Note that you do not need the unsafe system() command at all here. Just open the device and send the string directly.



Answered By - Ted Lyngmo
Answer Checked By - Timothy Miller (WPSolving Admin)