Using classes with the Arduino

前端 未结 7 1891
孤独总比滥情好
孤独总比滥情好 2020-12-25 11:01

I\'m trying to use class objects with the Arduino, but I keep running into problems. All I want to do is declare a class and create an object of that class. What would an e

7条回答
  •  情深已故
    2020-12-25 11:21

    I created this simple one a while back. The main challenge I had was to create a good build environment - a makefile that would compile and link/deploy everything without having to use the GUI. For the code, here is the header:

    class AMLed
    {
        private:
              uint8_t _ledPin;
              long _turnOffTime;
    
        public:
              AMLed(uint8_t pin);
              void setOn();
              void setOff();
              // Turn the led on for a given amount of time (relies
              // on a call to check() in the main loop()).
              void setOnForTime(int millis);
              void check();
    };
    

    And here is the main source

    AMLed::AMLed(uint8_t ledPin) : _ledPin(ledPin), _turnOffTime(0)
    {
        pinMode(_ledPin, OUTPUT);
    }
    
    void AMLed::setOn()
    {
        digitalWrite(_ledPin, HIGH);
    }
    
    void AMLed::setOff()
    {
        digitalWrite(_ledPin, LOW);
    }
    
    void AMLed::setOnForTime(int p_millis)
    {
        _turnOffTime = millis() + p_millis;
        setOn();
    }
    
    void AMLed::check()
    {
        if (_turnOffTime != 0 && (millis() > _turnOffTime))
        {
            _turnOffTime = 0;
            setOff();
        }
    }
    

    It's more prettily formatted here: http://amkimian.blogspot.com/2009/07/trivial-led-class.html

    To use, I simply do something like this in the .pde file:

    #include "AM_Led.h"
    
    #define TIME_LED    12   // The port for the LED
    
    AMLed test(TIME_LED);
    

提交回复
热议问题