Push button jump into a random case

Good morning,

Just wondering if it would be possible to have a push button that when pushed it will jump to a random case of a state machine?

James

Just wondering if it would be possible to have a push button that when pushed it will jump to a random case of a state machine?

Yes, it is.

Thanks for your quick response PaulS,

how would the code for this sort of thing look, would you have an example you could point me at?

state machine is pretty generic.

I assume you have a state machine in your code? Post your code I'll show you how to make the button do what you want.

Off the top of my head you could sample millis() when the button is pushed and take a mod (%) of the result.

The mod number would be the same as the number of case states.

Unless I'm mistaken I think it's pretty classic stuff...

You generally have an enum for states ina state machine. It should be as simple as taking a random pick ...

typedef enum
{
    RANDOM_STATE_1 = 0,
    RANDOM_STATE_2 = 0,
    RANDOM_STATE_3 = 0,
    RANDOM_STATE_4 = 0,

    COUNT,
}states_e;

states_e g_state = RANDOM_STATE_1; 

void loop()
{
    if( button_pressed )
        g_state = random( RANDOM_STATE_1, COUNT );

    // state machine here
    //...
}

I haven’t yet written the code, but the idea is that I’m creating something interactive, waiting for a user to push a ‘start’ button.

I want the same bit of code to run, but the audio files played back to the user to be chosen at random

My thought was to write the code out three times, with one of three sets of audio files in it each time, these would then become cases 2 to 4

case 1, the default case would be waiting for the user to push start, once a button push is detected the code would jump into case 2, 3 or 4 at random

I hope this makes sense!

Yes it makes sense, but don’t forget you can have state machines withing state machines.

Though in your case wouldn’t an array be more beneficial? I’d have to see the code when you get it underway, but if you had a function that played the audio from file (or any source):

// defined at the top
#define MAX_AUDIO_FILES 3

// We're in the state that picks the random audio:
case RANDOM_AUDIO:
{
	// store these wherever you want, Here for clarity.
	char *audio_path_p[] = 
	{
		"audio_1.wav",
		"audio_2.wav",
		"audio_3.wav",
	};

	// your function to play audio from source 
	play_sfx_from_file( audio_path_p[random( 0, MAX_AUDIO_FILES )] );
}
break;

aw I think it’d be much more fun making your own RNG (random number generator) than using the on board function !

This project has all the requirements built in, OP may as well learn something ?