Go Down

Topic: Please explain this code to me (Read 609 times) previous topic - next topic

CrashingDutchman

I found this piece of code that is used to provide power to a Wiichuck (converterboard for use with Wii Nunchuck)
Code: [Select]

static void nunchuck_setpowerpins()
{
#define pwrpin PC3
#define gndpin PC2
   DDRC |= _BV(pwrpin) | _BV(gndpin);
   PORTC &=~ _BV(gndpin);
   PORTC |=  _BV(pwrpin);
   delay(100);  // wait for things to stabilize        
}


Can someone explain what it exactly does?

halley

#1
Mar 19, 2009, 02:13 pm Last Edit: Mar 19, 2009, 02:17 pm by halley Reason: 1
It's doing the equivalent of

Code: [Select]
#define PWRPIN 17 // 3 + 14 == Analog Pin 3
#define GNDPIN 16 // 2 + 14 == Analog Pin 2
pinMode(PWRPIN, OUTPUT);
pinMode(GNDPIN, OUTPUT);
digitalWrite(PWRPIN, HIGH);
digitalWrite(GNDPIN, LOW);
delay(100);


But it's using direct port manipulation to do it.

CrashingDutchman

That is easier to read and understand for me.

What is the advantage to use Arduino code or port manipulation?

halley


While the port manipulation routines happen about 20x~40x faster than the digitalWrite() routines, it's ridiculous to use such low-level nonsense before a 100ms delay.  As you just demonstrated, it doesn't make the code more readable or maintainable.

CrashingDutchman

ok  ;)

thank you very much for explaining

westfw

Quote
What is the advantage to use Arduino code or port manipulation?

I suspect that the original author was not aware that the "analog pins" of the arduino could be manipulated with pinMode() and digitalWrite()  (using the n+14 as pin number), and so dropped into the direct mode access that they knew would work...

Go Up