// MyFirstWrenchUno.ino
//
// Extra notes for Uno:
// WRENCH_DEFAULT_STACK_SIZE set to 10
// 'buf[40]' in print function and also in 'asString'
//
// Test sketch for the 'wrench' interpreter.
// This Wokwi project: https://wokwi.com/projects/347587575048831571
// I learned about 'wrench' here: https://forum.arduino.cc/t/c-like-interpreter-that-actually-fits-and-runs-inside-most-arduino-chips-wrench/1050025/
// #include <Arduino.h>
#include "wrench.h"
#include "basic.h" // bytecode generated on the PC
// Below is the wrench code.
// It exists only on my PC and is compiled on my PC.
// With: wrench ch basic.w basic.h basic
// The resulting binary code is in "basic.h".
/*
// ==============================================================================
// Glue for Arduino things
enum { INPUT = 0, OUTPUT = 1, };
enum { LOW = 0, HIGH = 1, };
// The multi-platform compatible wrench code is below
ledPin = 5;
count = 0;
print( "Hello almost Arduino code\n" );
pinMode( ledPin, OUTPUT );
while( true) // wrench has no Arduino loop()
{
delay = 500 - (50 * count);
count++;
if( count >= 9)
count = 0;
digitalWrite( ledPin, HIGH);
delay( delay);
digitalWrite( ledPin, LOW);
delay( delay);
}
// ==============================================================================
*/
void setup()
{
Serial.begin( 115200 );
// delay( 2000 ); // wait for link to come up for sample
WRState* w = wr_newState(); // create the state
wr_registerFunction( w, "print", print ); // bind a function
wr_registerFunction( w, "pinMode", pinMode ); // bind a function
wr_registerFunction( w, "digitalWrite", digitalWrite ); // bind a function
wr_registerFunction( w, "delay", delay ); // bind a function
wr_run( w, basic_bytecode ); // load and run the code!
wr_destroyState( w );
}
void loop()
{}
// The functions convert the wrench code to the specific platform code.
void print( WRState* w, const WRValue* argv, const int argn, WRValue& retVal, void* usr )
{
char buf[40];
for( int i=0; i<argn; ++i )
{
Serial.print( argv[i].asString(buf, 40) );
}
}
// No translation is needed for the LOW and HIGH in the wrench code,
// they seem to be 0 and 1 no every platform.
// The INPUT and OUTPUT can have differenct numbers on different platforms,
// those need an extra translation.
void pinMode( WRState* w, const WRValue* argv, const int argn, WRValue& retVal, void* usr )
{
if ( argn == 2 )
{
if ( argv[1].asInt() == 1 ) // wrench value for OUTPUT
{
pinMode( argv[0].asInt(), OUTPUT ); // Arduino value for OUTPUT
}
else if ( argv[1].asInt() == 0 ) // wrench value for INPUT
{
pinMode( argv[0].asInt(), INPUT ); // Arduino value for INPUT
}
}
}
void digitalWrite( WRState* w, const WRValue* argv, const int argn, WRValue& retVal, void* usr )
{
digitalWrite(argv[0].asInt(), argv[1].asInt());
}
void delay( WRState* w, const WRValue* argv, const int argn, WRValue& retVal, void* usr )
{
delay(argv[0].asInt());
}