1

I have a situation where the default case in my switch statement doesn't appear to execute as expected. I wonder if there is some subtlety I'm missing here?

Given the following enum:

enum HomingPhase
    {
    Idle = 0,
    Detecting,
    Stopping,
    Reversing,
    AtHome,
    };

and the following methods:

void HomeSensor::setPhase(HomingPhase newPhase)
    {
    phase = newPhase;
    Serial.print("Phase ");
    Serial.println(phase);
    }

void HomeSensor::onMotorStopped() const
    {
    std::cout << "Hstop " << phase << std::endl;
    switch (phase)
        {
        case Reversing:
            setPhase(AtHome);
            break;
        case Stopping:
            setPhase(Reversing);
            const auto target = commandProcessor.targetStepPosition(homeSettings->position);
            motor->moveToPosition(target);
            break;
        default:
            setPhase(Idle);
            return;
        }
    }

At runtime, onMotorStopped() is called and I see the following output, which indicates that phase is AtHome (4) on entry to the method.

Hstop 4

I expect the default case to execute, setting the phase to Idle but I do not see the output from setPhase(), which suggests that the default case isn't executing. Subsequent output from elsewhere in the code confirms that phase in fact remains set to AtHome (4) and isn't being set to Idle as expected.

I think I may have gone code blind. Can anyone see the issue?

4
  • 3
    One's going to std::cout (works). The other to Serial. I don't know std::cout on an Arduino... Are you really running it on an Arduino?
    – Majenko
    Dec 7, 2019 at 21:48
  • Yes, <ArduinoSTL> works surprisingly well. I should probably change thos to use one or the other and not mix them like that, but the Serial.println does produce output in other circumstances so it's not that the print statement isn't working.
    – Tim Long
    Dec 7, 2019 at 23:16
  • I would try it with Arduino AVR core 1.6.21. Newer have problems
    – Juraj
    Dec 8, 2019 at 11:20
  • What happens if you put debug output (either way) on each case and default? Dec 8, 2019 at 16:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.