Hi. I am trying to make a device that can control my projector from its serial port. I am using a max232 device to connect my Arduino to the projector. I am able to send commands to turn it on and off and such but I want to be able to read data from it. So I wrote this piece of code that asks the projector what its power state is. This works and I am able to get a response from the projector and output it to the serial monitor. Now, I want to be able to set a boolean based on the data I receive. How can I do that?
@groundFungus reply is spot on.
Here is a slightly different sketch. It includes testing the *pow= start of the response. What sort of corruption are you getting.? Do you still get it with this sketch?
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); // RX, TX
// for testing uncomment this to test from Serial input
// #define mySerial Serial
void clearMySerialInput() {
mySerial.setTimeout(100);
mySerial.readString();
mySerial.setTimeout(5);
}
void setup() {
mySerial.begin(9600);
mySerial.setTimeout(5); // at 9600 get about 1char/1mS so when reading user input from Arduino IDE monitor can set this short timeout
Serial.begin(9600);
Serial.setTimeout(5); // at 9600 get about 1char/1mS so when reading user input from Arduino IDE monitor can set this short timeout
for (int i = 10; i > 0; i--) {
Serial.print(' '); Serial.print(i);
delay(500);
}
Serial.println();
Serial.println(F("mySerial Started"));
clearMySerialInput(); // flush any pending input
}
bool haveSentCmd = false;
void processInput() {
if (Serial.available()) { // skip readString timeout if nothing to read
String input = Serial.readString();
input.trim(); // strip off any leading/trailing space and \r \n
if (input.length() > 0) { // got some input handle it
Serial.println();
Serial.print(F(" got a some input '")); Serial.print(input); Serial.println("'");
// parse input here and set globals with results
if (!haveSentCmd) {
// just data printed above
} else {
// handle response
if (input.startsWith("*pow=")) {
if (input.indexOf("ON") >= 0) { // is "0N" in the input
Serial.println(F("projector is on"));
} else if (input.indexOf("OFF") >= 0) {
Serial.println(F("projector is off"));
}
} else {
Serial.println(F("unexpected response!!"));
}
haveSentCmd = false;
}
}
}
}
void loop() {
if (!haveSentCmd) {
mySerial.print("*pow=?#"); mySerial.print('\r');
haveSentCmd = true;
}
processInput(); // handle the Serial in this task
// other tasks here
}
The corruption may have been due to sending while receiving on the Software Serial.
If the sketch works then fine.
Other alternatives are
i) use a Mega2560 which has extra hardware serial ports
ii) use D0/D1 for the projector connection and use the Software Serial for the debugging prints to the Console. You would need a 5V TTL to USB connector to do that, or another UNO to pass the output through