New to this and have questions about a 7 seg led common anode unit and its code

Hello all, so i am very new to arduino and have some questions about this little code i made and why it functions this way. below is the code and yes it is probably not clean and please if you have a slicker/better way to do this then let me know...

int button = 0;
int n=2;

void setup(){
pinMode(9, INPUT);


void loop(){


button = digitalRead(9);

if(button == LOW){
if ( n >8 )
n = 2;



basically all i'm doing is testing the led and when i send the code to the arduino the top segment lights up, when i press the pushbutton switch it just increments the variable and then lights up the next segment and if you hold the button down it just cycles through the segments with that short delay. it all works fine but I was confused at first about about why it worked the way it did. When I first made the code I did not initialize all values to 1023 and all segments of the led were on. Is this just because it is common anode and not common cathode.?? is this why it seems people don't like common anode led units.?? I didn't think a negative value or lets say a zero value would light the unit up but I guess that's how it works with anode displays. If this were a common cathode unit then would the code be able to be much shorter by not initializing everything to 1023.?? Any info would be great, thanks


analogWrite() only takes numbers between 0 and 255.

For a common anode display, if you output a logic 1, the LEDs are off, if you output a logic 0, the LEDs are on.

So outputting a pwm with 100% duty cycle will result in the light being off.

Setting an output to 0 doesn't mean that no current will flow, it means that the pin will sink current (current will flow from +5V, through the LED and into the pin to ground).

ah ok, so i could just change this to be a digitalWrite and use 1's and 0's instead since i'm not varying the led intensity between off and on. If this were a common cathode display then would it be opposite and a 1 would be on and a zero would be off.?


Final note, if you have no external pull-up resistor hooked up to the button, use INPUT_PULLUP as the pinmode so that the input is forced HIGH when the button is open, and the input isn't left floating.

ah thanks for that pull up thing.