Skip to main content
1 of 2

Class member variable would not update

Code would not update variable inside drive method. I wrote a simple class in normal C++ and the variable actually updated.

engine.hpp

#pragma once
#include <Arduino.h>

namespace engine
{
class Engine
{
public:
    Engine(const unsigned char t_motor, const unsigned char t_forward, const unsigned char t_backward);
    void drive(unsigned int t_speed, bool t_isForward = true);
    bool isMovingForward() const;
    void stop();

private:
    const unsigned char m_motor;
    const unsigned char m_forward;
    const unsigned char m_backward;

    // Movements
    bool m_isActive;
    bool m_isForward;
    unsigned int m_speed;
};
} // namespace engine

engine.cpp init list

Engine::Engine(const unsigned char t_motor, const unsigned char t_forward, const unsigned char t_backward)
    : m_motor(t_motor),
      m_forward(t_forward),
      m_backward(t_backward),
      m_isActive(false),
      m_isForward(true),
      m_speed(0U)
{
}

drive method

void Engine::drive(unsigned int t_speed, bool t_isForward)
{

    if (!m_isActive || m_isForward != t_isForward)
    {
        stop();

        // Set direction
        if (t_isForward)
        {
            digitalWrite(m_forward, HIGH);
            digitalWrite(m_backward, LOW);
        }
        else
        {
            digitalWrite(m_forward, LOW);
            digitalWrite(m_backward, HIGH);
        }

        m_isActive = true;
        m_isForward = t_isForward;
    }

    if (m_speed != t_speed)
    {
        m_speed = t_speed; // Updated here
        analogWrite(m_motor, t_speed);
    }
}