Repeat serial print indefinately?

I am new to Arduino and programming. I was wondering if there is a way to log and repeat indefinitely anything printed to serial. For example, using this code:

int switchPin1 = 5;
int switchPin2 = 6;

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

   pinMode(switchPin1, INPUT);
   digitalWrite(switchPin1, HIGH);
  
   pinMode(switchPin2, INPUT);                        // Second button
   digitalWrite(switchPin2, HIGH);
}

void loop(){
if(digitalRead(switchPin1) == LOW) 
    {
      Serial.println("John");
      delay(100);
    }
    
if(digitalRead(switchPin2) == LOW) 
    {
      Serial.println("Sally");
      delay(100);
    }
}

Everytime pin 5 touches ground, it prints John to serial, everytime pin 6 touches ground it prints Sally to serial. I want to make it so it will keep on repeating the results, with a delay of lets say 10 seconds, adding any new ones to the end.

For example, say I hit the pins to ground in the following order = 5 5 6 5 6, it will print:

John John Sally John Sally

but I want it to print the results every 10 seconds, so if I only hit those 5 pins, it would keep printing

John John Sally John Sally

delay(10000)

John John Sally John Sally

delay (10000)

John John Sally John Sally

indefinitely. Now lets say I then ground pins 6 6 and 5, it will add them to the end and continue repeating every 10 seconds:

John John Sally John Sally Sally Sally John

It's kind of like a log. Is this possible?

Yes, however, there is a finite amount of memory available. At some point you will have to stop adding to the sequence.

  • Brian

thats fine, the data won't become too long, do you know what code i need to add?

I assume that you’re not going to log the actual strings - that would be wasteful.
Store the strings in an array, and then all you need to store is the index into the array.
For a small array, this could be four bits, which will increase the amount of logging you could do.

const char* names [] = { "Tom", "Richard", "Harry", "Old Uncle Tom Cobbley"};
const int switchPin [] = {5, 6, 7, 12};
void setup()
{
  Serial.begin(9600);
  for (int i = 0; i < 4; ++i){
    pinMode(switchPin[i], INPUT);
    digitalWrite(switchPin[i], HIGH);
  }
}

void loop(){
  for (int i = 0; i < 4; ++i){
    if(digitalRead(switchPin[i]) == LOW)
    {
      Serial.println(names[i]);
               // and log the value "i" in an array for later replay
               // NB, this example needs only two bits of storage per name
      delay(100);
    }
}

Thank you so much :slight_smile: