Hi All,
My Tcl/Tk code for serial communication with Arduino is working but with a strange behavior.
I send a message through the serial port that calls a function in arduino and returns a message. The problem is that, at the beginning, I need to send the command 2 or 3 times before arduino start to respond. After the second or third attempt, the arduino starts to respond normally.
The Arduino code is: (adapted from Gammon Forum : Electronics : Microprocessors : How to process incoming serial data without blocking)
void setup() {
Serial.begin(9600);
Serial.flush();
}
void processIncomingByte (const byte inByte) {
static char input_line[MAX_INPUT];
static unsigned int input_pos = 0;
switch (inByte)
{
case '\n': // end of text
input_line[input_pos] = 0; // terminating null byte
// terminator reached! process input_line here ...
process_data (input_line);
// reset buffer for next time
input_pos = 0;
break;
case '\r': // discard carriage return
break;
default:
// keep adding if not full ... allow for terminating null byte
if (input_pos < (MAX_INPUT - 1))
input_line[input_pos++] = inByte;
break;
} // end of switch
}// end of processIncomingByte
//Process_data to process incoming serial data after a terminator received
void process_data (char *data) {
cmd = strtok(data, ";");
if ( (strcmp(cmd, "checkConnection") == 0) || (strcmp(cmd, "checkconnection") == 0) ) {
transaction_id = strtok(NULL, ";");
checkConnection( transaction_id );
} else {
Serial.print("#unknown command: ");
Serial.println(cmd);
} // end of if
}
//Send message "ACK" to to confirm the connection with the Arduino
void checkConnection(char *transaction_id ) {
Serial.print("ACK;");
Serial.println(transaction_id);
}
void loop() {
// if serial data available, process it
while (Serial.available () > 0)
processIncomingByte (Serial.read());
}
And the Tcl/Tk code is:
set serial_device [exec ls {}[glob /dev/ttyACM]]
set baud 9600
set parity n
set data_bit 8
set stop_bit 1
set id_serial_port [open $serial_device r+]
chan configure $id_serial_port -mode "$baud,$parity,$data_bit,$stop_bit"
chan configure $id_serial_port -buffering line
chan configure $id_serial_port -blocking 0
chan configure $id_serial_port -encoding ascii
#To set the procedure (receiveReadout) to be called when serial port is readable
chan event $id_serial_port readable [list [self] receiveReadout $id_serial_port]
And the procedure receiveReadout
proc receiveReadout { id_serial_port } {
if { [eof $id_serial_port ] } {
puts "Closing $id_serial_port"
catch { close $id_serial_port }
return
}
#To read the response from Arduino
set serial_return [chan gets $id_serial_port]
}
And send the command to check the connection:
chan puts $id_serial_port checkConnection
But as I said, to start receiving Arduino messages I need to send this command 2 or 3 times.
Please, any tips on how to resolve this?
Thank you,
Markos