Simulation on a laptop

the forum looks slow

while the wokwi.com simulator is certainly nice, it can be tedious to repeatedly complete a test sequence by having to press buttons or change other input devices.

And of course it's much faster to test code on a laptop, avoiding the need to download/repost and rebuild the code.

(i often have a window open, repeatedly running make and executing the code, while editing in a 2nd window) (cygwin provides Linux tools including compilers the run under windows).

test.cpp is a simple Arduino program that monitors button pins and toggles an LED.

#include "Arduino.h"

const byte PinLed = LED_BUILTIN;
const byte PinBut = A1;

byte butState;

// -----------------------------------------------------------------------------
void loop ()
{
 // Serial.println ("loop:");

    byte but = digitalRead (PinBut);
    if (butState != but)  {                             // state change
        butState  = but;
        delay (30);                                     // debounce

        digitalWrite (PinLed, ! digitalRead (PinLed));  // toggle

        Serial.println ("button press");
    }
}

// -----------------------------------------------------------------------------
void setup ()
{
    Serial.begin (9600);

    pinMode (PinBut, INPUT_PULLUP);
    butState = digitalRead (PinBut);

    pinMode (PinLed, OUTPUT);
    digitalWrite (PinLed, HIGH);
}

sim.cmd is a list of commands executed by the code in simIo that set/resets pin values and executes loop() one or more times.

    loop  5

    set   A1
    loop  5

    reset A1
    loop  10

output

sim sim.cmd
sim: sim.cmd
      digitalWrite pin 13 H
    loop  5
    set   A1
    loop  5
      digitalWrite pin 13 L
button press
    reset A1
    loop  10
      digitalWrite pin 13 H
button press

simIo.cpp and Arduino.h provide a platform for testing Arduino code in .cpp files that can be moved to the Arduino IDE as .ino when testing is complete

It includes code for the basic arduino functions, as well as a table for standard symbols (e.g. A2). digitalWrite() and digitalRead() set pin values maintained in a table. the set and reset commands change those values outside the Arduino code.

delay() and millis() are essentially stubbed. millis() returns values incremented by 100.

// general purpose simulator handling digital I/O pins

#include <string.h>
#include <ctype.h>
#include <getopt.h>

char        *progname;
unsigned int dbg   = 1;

// -----------------------------------------------------------------------------
#include "Arduino.h"

static const int _Npins = 20;
static uint8_t   _pinVal [_Npins];

// ---------------------------------------------------------
struct Sym {
    int         val;
    const char *lbl;
};

static Sym _syms [] = {
    {  0,  "D0" }, {  1,  "D1" },
    {  2,  "D2" }, {  3,  "D3" },
    {  4,  "D4" }, {  5,  "D5" },
    {  6,  "D6" }, {  7,  "D7" },
    {  8,  "D8" }, {  9,  "D9" },
    { 10,  "D0" }, { 11,  "D1" },
    { 12,  "D2" }, { 13,  "D3" },

    { 14,  "A0" }, { 15,  "A1" },
    { 16,  "A2" }, { 17,  "A3" },
    { 18,  "A4" }, { 19,  "A5" },
};
static const int _Nsym = sizeof(_syms)/sizeof(Sym);

// -------------------------------------
int
getVal (
    const char *sym )
{
    if (isdigit (*sym))
        return atoi (sym);

    for (int n = 0; n < _Nsym; n++)
        if (! strcmp (_syms [n].lbl, sym))
            return _syms [n].val;

    fprintf (stderr, "Error: unknown symbol - %s\n", sym);
    exit (1);
}

// ---------------------------------------------------------
static void _resetPin (uint8_t pin)  {
    if (_Npins <= pin)  {
        fprintf (stderr, "Error: _setPin - pin out of range - %d\n", pin);
        exit (1);
    }

    _pinVal [pin] = 0;
}

// ---------------------------------------------------------
static void _setPin (uint8_t pin)  {
    if (_Npins <= pin)  {
        fprintf (stderr, "Error: _setPin - pin out of range - %d\n", pin);
        exit (1);
    }

    _pinVal [pin] = 1;
}

// ---------------------------------------------------------
uint8_t digitalRead (uint8_t pin) { 
    if (_Npins <= pin)  {
        fprintf (stderr, "Error: digitalRead - pin out of range - %d\n", pin);
        exit (1);
    }

    if (2 <= dbg)
        printf ("      digitalRead  pin %d %s\n",
                                    pin, _pinVal [pin] ? "H" : "L");

    return _pinVal [pin];
}

// ---------------------------------------------------------
void digitalWrite (uint8_t pin, uint8_t val) {
    if (_Npins <= pin)  {
        fprintf (stderr, "Error: digitalRead - pin out of range - %d\n", pin);
        exit (1);
    }

    _pinVal [pin] = val;
    if (1 <= dbg)
        printf ("      digitalWrite pin %d %s\n",
                            pin, _pinVal [pin] ? "H" : "L");
}

// ---------------------------------------------------------
void pinMode (uint8_t pin, int mode) {}
void delay   (unsigned long)         {}

unsigned long millis () {
    static unsigned long _ms;
    return _ms += 100;
}

// -----------------------------------------------------------------------------
extern void loop  ();
extern void setup ();

// --------------------------------------------------------------------
void
application (char *filename)  {
    FILE  *fp;
    char   s[BUFSIZ];

    printf ("%s: %s\n", progname, filename);

    if ( (fp = fopen (filename, "rb")) == NULL)  {
        perror ("app - fopen input");
        exit (1);
    }

    setup ();

    char sym [10];
    int  arg1;

    while (fgets (s, BUFSIZ, fp) != NULL)  {
        if ('\n' == *s)           // blank line
            continue;

        printf ("%s", s);

        if (1 == sscanf (s, " reset %s", sym))
            _resetPin (getVal (sym));

        else if (1 == sscanf (s, " set %s", sym))
            _setPin (getVal (sym));

        else if (sscanf (s, " loop %d", &arg1))  {
            while (arg1--)
                loop ();
        }

        else  {
            fprintf (stderr, "Error: inva1id cmd - %s\n", s);
            exit (2);
        }
    }
}

// --------------------------------------------------------------------
void help (void)  {
    printf (" Usage: %s \n", progname);
}

// --------------------------------------------------------------------
int main (int argc, char **argv)  {
    int   c;

    progname = *argv;

    while ((c = getopt(argc, argv, "D:o")) != -1)  {
        switch (c)  {
        case 'D':
            dbg = atoi (optarg);
            break;

        default:
            printf ("Error: unknown option '%c'\n", optopt);
                        help();
            break;
        };
    }

    if (optind == argc)
        help();
    else
        for ( ; optind < argc; optind++)
            application (argv[optind]);

    return 0;
}

Arduino.h


#ifndef _ARDUINO_H_
# define _ARDUINO_H_

# include <stdio.h>
# include <stdint.h>
# include <stdlib.h>

# define byte uint8_t

const byte LED_BUILTIN = 13;

enum { LOW, HIGH };
enum { OUTPUT, INPUT, INPUT_PULLUP };

enum { A0 = 14, A1, A2, A3, A4, A5, A6 };

void            delay   (unsigned long);
uint8_t         digitalRead (uint8_t pin);
void            digitalWrite (uint8_t pin, uint8_t);

unsigned long   millis ();
void            pinMode (uint8_t pin, int mode);

struct {
    void begin (int bps) {}

    int available ()             { return 1; };
    char read ()                 { return getchar (); }

    void print (const char *s)   { printf (s); }
    void print (int i)           { printf ("%d",  i); }
    void print (float f)         { printf ("%f",  f); }
    void print (unsigned u)      { printf ("%u",  u); }
    void print (unsigned long l) { printf ("%lu", l); }

    void println ()                { printf ("\n"); }
    void println (const char *s)   { printf ("%s\n",  s); }
    void println (int i)           { printf ("%d\n",  i); }
    void println (float f)         { printf ("%f\n",  f); }
    void println (unsigned u)      { printf ("%u\n",  u); }
    void println (unsigned long l) { printf ("%lu\n", l); }
} Serial;

#endif

this is far from a complete implementation of all possible Arduino functions and libraries. They can be added with varying difficulty.

A complete implementation is not needed to test a particular feature. Only those needed to test a particular feature may be required.

for that may be interested, my Makefile

# CFLAGS += -Wall -Werror
  CFLAGS += -I ../include
  CFLAGS += -isystem IncSys

  Obj   = ../Obj
  Objs  = $(patsubst %.cpp, $(Obj)/%.o, $(Srcs))
  Srcs  = $(shell echo *cpp)
  Targ  = sim

  Cmd   = sim.cmd

$(Obj)/%.o : %.cpp
        $(CXX) $(CFLAGS) -c -o $@ $^


# --------------------------------------------------------------------
all : $(Targ)
        $(Targ) $(Cmd)

$(Targ) : $(Obj) $(Objs)
        $(CXX) -o $(Targ) $(Objs) $(LIBS)

$(Obj) :
        mkdir $@

# --------------------------------------------------------------------
check :
        @ echo Src: $(Srcs)
        @ echo Obj: $(Objs)

neat :
        rm -f *~ *stackdump

clean : neat
        rm -rf $(Obj) *.exe

@gcjr - A user posted their "no-hardware" library here... somewhere... that lets you simulate off-line, without hardware (except your live MCU).

(searching for said user... found it)

useful for testing things other than Arduino

Other things. I missed that... somehow.

Interesting idea, although I haven't fully absorbed how it works yet. I sometimes use OnlineGDB to test concepts and function logic, but obviously can't test code that requires Arduino hardware functions. Something that avoids using Wokwi when its busy and running at a crawl would certainly be welcome.

Possibly the naming of the Arduino.h file might be a little unfortunate as it clashes with the name of the core Arduino.h header but that is easily renamed.

Thanks for sharing.

I wonder whether this actually materialized? I see no links to a repository or further discussion?

I did come across ArduinoFake and FakeIt, but have no idea whether they are related to the discussion in question.

Good question... for @ishakismaili

I use "fake hardware" when testing sketches on live hardware. I figure out what the hardware wants or returns and have fake data ready for the hardware (MCU and device).

i think the most generic part is processing commands from a file that can affect the hardware, such as setting a pin state or potentially to set the next millis() value returned. Different command files can be used for different types of testing

the list of commands and arduino functions is hardly complete and should be customized as needed.

and of course, this can be applied to other languages and hardware, even mouse presses to test a GUI application. Even commands to exercise sub-functions