Pages: [1]   Go Down
Author Topic: Please explain this code to me  (Read 589 times)
0 Members and 1 Guest are viewing this topic.
Netherlands
Offline Offline
Sr. Member
****
Karma: 0
Posts: 414
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I found this piece of code that is used to provide power to a Wiichuck (converterboard for use with Wii Nunchuck)
Code:
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?
Logged

Connecticut, US
Offline Offline
Edison Member
*
Karma: 2
Posts: 1036
Whatduino
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

It's doing the equivalent of

Code:
#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.
« Last Edit: March 19, 2009, 08:17:18 am by halley » Logged

Netherlands
Offline Offline
Sr. Member
****
Karma: 0
Posts: 414
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

That is easier to read and understand for me.

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

Connecticut, US
Offline Offline
Edison Member
*
Karma: 2
Posts: 1036
Whatduino
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset


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.
Logged

Netherlands
Offline Offline
Sr. Member
****
Karma: 0
Posts: 414
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

ok  smiley-wink

 thank you very much for explaining
Logged

SF Bay Area (USA)
Offline Offline
Tesla Member
***
Karma: 137
Posts: 6792
Strongly opinionated, but not official!
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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...
Logged

Pages: [1]   Go Up
Jump to: