c++ - arrays, constructors and instances -
i explain problem: i'm trying solve arrays proble, got programme done in oop in has class called lights. want array pin numbers inside , set them output. did pin pin , easy loop , array don't know how build constructors , handle of array whit pin numbers in it.
//---------------------------------------------------------------------------------- class lights{ int pins[5]; //array 5 elements int i; public: lights(int ledpins[]){ for(i=0; i<5; i++){ //pins set output pinmode(pins[i],output); } }//end constructor void attempt(){ //metodo para pobrar si se enciende los leds for(i=0; i<5; i++){ digitalwrite(pins[i],high); serial.println(pins[i]); } }//end attempt };//end class //--------------------------------------------------------------------------------------------------------------------- int mypins[] = {5,6,7,8,9}; //i declare inside lights lit(mypins); //i create objet array parameters void setup(){ serial.begin(9600); } void loop(){ lit.attempt(); }
you don't need put class. think using class lights overkill.
in experience, functions used process light pins , take pin enum.
unless have huge amount of pins set up, loop may not worthwhile. unrolling loop may increase programs efficiency:
pinmode(5,output); pinmode(6,output); pinmode(7,output); pinmode(8,output); pinmode(9,output); initialization occurs once, optimization not warranted.
if need use classes, suggest 1 class models single light.
every light has associated pin.
you can have container of lights (such array):
class light { public: light(unsigned int pin) : m_pin(pin), m_is_on(false) { ; } void initialize(); // sets appropriate pin void on(); // turns on light void off(); // turns off light void blink(unsigned int rate, unsigned int duration); private: unsigned int m_pin; bool m_is_on; }; light display[] = {light(5), light(6), light(7), light(8), light(9)}; const unsigned int light_quantity = sizeof(display) / sizeof(display[0]); an advantage model program can in terms of lights , not worry pins.
Comments
Post a Comment