automating arduino serial interaction with expect/tcl

Post your cool example code here.
Post Reply
ag123
Posts: 1655
Joined: Thu Dec 19, 2019 5:30 am
Answers: 24

automating arduino serial interaction with expect/tcl

Post by ag123 »

this isn't necessarily limited to libmaple but that i've tested this in libmaple core hence posted here

beside the well known languages c/c++/java/python etc there is an 'ancient' and little used language called expect and tcl
this seemed to be for the unix/linux folks (should work on Rpi, Beaglebone black as well)

the sketch a rather verbose 'hello world' (libmaple core). connect to the serial console send an enter, it prompts 'who are you' and it response with 'hello ' + whatever you type and hit enter

Code: Select all

#include <Arduino.h>
char buf[30];

void setup() {
	Serial.begin();
	while(!Serial.available());
	while(Serial.available()) Serial.read(); //flush
	Serial.println("who are you");	
}

void loop() {
  	uint8_t i = 0;
	memset(&buf,0,30);
	while(1) {
	    if (Serial.available()) {
	    	char c = Serial.read();
	    	//Serial.write(c); //echo on
	    	if(c == '\n' || c == '\r' )
				break;
			buf[i++] = c;
			if(i>29) break;
		} else
		//delay(10);
		for(int j=0;j<10;j++) asm("wfi");
	}
	Serial.print("hello ");
	Serial.println(buf);
}
the expect script

Code: Select all

#!/usr/bin/expect
set timeout 10
spawn -open [open "/dev/maple" w+]
send "\r"
expect {
    "who are you" {
      send "world\r";
    } \
    timeout {
      send "world\r";
    }
  }
expect {
  "hello*" {
#    send_user $expect_out(buffer) ;#print the response 
  } \
  timeout {
    send "\r"
    exp_continue;
  }
}
sample output

Code: Select all

who are you
hello world
accordingly tcl and expect runs in windows as well
https://wiki.tcl-lang.org/page/Tcl+Tutorial+Lesson+0a
but that instead of /dev/maple it is probably comX: for the port

one of the use case for this is for things like setting the RTC time, it is pretty tedious to sync the RTC time say using some text commands.
automating it makes it much easier. there are probably many other relevant use cases.
Post Reply

Return to “Code snippets”