Okay, this is what the Arduino sketch looks like:
#define BAUD 9600
//led
#define led 2
//macro for on/off
#define on (digitalWrite(led, HIGH))
#define off (digitalWrite(led, LOW))
void setup() {
// initialize digital pin 2 as an output.
Serial.begin(BAUD);
pinMode(led, OUTPUT);
}
void loop(){
String input;
//If any input is detected in arduino
if(Serial.available() > 0){
//read the whole string until '\n' delimiter is read
input = Serial.readStringUntil('\n');
//If input == "ON" then turn on the led
//and send a reply
if (input.equals("ON")){
digitalWrite(led, LOW);
Serial.println("Led is ON");
}
//If input == "OFF" then turn off the led
//and send a reply
else if (input.equals("OFF")){
digitalWrite(led, HIGH);
Serial.println("Led is OFF");
}
}
}
And this is the code from my program.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SerialPort.h"
using namespace std;
//String for getting the output from arduino
char output[10];
/*Portname must contain these backslashes, and remember to
replace the following com port*/
char *port_name = "\\\\.\\COM5";
//String for incoming data
char incomingData[20];
int main()
{
SerialPort arduino(port_name);
if (arduino.isConnected()) cout << "Connection Established" << endl;
else cout << "ERROR, check port name";
while (arduino.isConnected()){
cout << "Input command: \n";
std::string input_string;
//Getting input
getline(cin, input_string);
//Creating a c string
char *c_string = new char[input_string.size() + 1];
//copying the std::string to c string
std::copy(input_string.begin(), input_string.end(), c_string);
//Adding the delimiter
c_string[input_string.size()] = '\n';
//Writing string to arduino
arduino.writeSerialPort(c_string, 20);
//Getting reply from arduino
arduino.readSerialPort(output, 20);
//printing the output
puts(output);
//freeing c_string memory
delete[] c_string;
}
}
Which is using this library:
https://blog.manash.me/serial-communication-with-an-arduino-using-c-on-windows-d08710186498The above code works for wired serial. The code on the Arduino works when sending commands via the ESP-link browser console.