Hi folks, I have a problem regarding statements in class constructor. Before I raise my question, please allow me to go through my little trouble.
I was working on a TCS3200(color sensor) module, and I was writing a class for it. The module requires me to set up a few output digital pins, so in the class constructor, I read in pin numbers and set their direction to output using pinMode. It's something like this:
//constructor, get pin number for s0-3, and LED
TCS3200(int s0,int s1,int s2,int s3,int led){
//assign pin number
s_pin[0]=s0;
s_pin[1]=s1;
s_pin[2]=s2;
s_pin[3]=s3;
led_pin=led;
//data_pin=data;
for(int i=0;i<3;i++){
pinMode(s_pin[i],OUTPUT);
}
pinMode(led_pin,OUTPUT);
// update pin state(setting their state)
updatePins();
return;
}
In my program, I declared an instance of TCS3200 class as global variable(at least I intend to do so) with following code
//TCS3200 class definition
//code...
TCS3200 sensor(4,5,6,7,3);
void setup(){
//code...
}
void loop(){
//mode code...
}
I ran the program and there were error in its outputting data, and I successfully fixed it after hours of desperate attempt by setting pin direction(in/out) in setup code, like this:
void setup(){
pinMode(2,INPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
//mode pinMode()...
}
and the problem seem to disappear, and in reflection I realize the error earlier was caused by failure to set the output pins to correct state, because their directions were not set to OUTPUT. So it seems that the pinMode in my class constructor did not execute properly.
So here's my problem:
- when is constructor executed? before, or after setup or loop?
- why the pinMode() in constructor failed to execute in my example?
- what's the right thing to do? i.e. where to put the pinMode() command?
Thank you all in advance.