This is easy to do and produces optimal code on GCC (e.g. sbi/cbi when
appropriate):
typedef union // Delclare a union that allows bit & byte access
{
unsigned char byte; // This is a byte for 8 bit access
struct
{
unsigned char P0:1; // These are bit-fields
unsigned char P1:1;
unsigned char P2:1;
unsigned char P3:1;
unsigned char P4:1;
unsigned char P5:1;
unsigned char P6:1;
unsigned char P7:1; // We can use an anonomous struct
}; // because the bit names are unique.
} sfr_struct;
#define PORTB (*(sfr_struct *)0x38) // Cast the sram address to the
structure
...
#define MOTOR_ENABLE_PIN PORTB.P2 // Now make an alias for your bit
...
MOTOR_ENABLE_PIN = TRUE; // Now, just use it.
If you want to access the port as a byte value, then use:
PORTB.byte = ...
-----Original Message-----
From: Stefan Trethan [mailto:stefan_trethan@gmx.at]
Sent: Monday, January 31, 2005 7:14 AM
To: AVR-Chat@yahoogroups.com
Subject: Re: [AVR-Chat] accessing bits (e.g. of ports)
On Mon, 31 Jan 2005 09:47:49 -0500 (EST), <ethan@bufbotics.org> wrote:
>
> <code>
> if (turn_motor_on) {
> setbit(MOTOR_ENABLE_PORT, MOTOR_ENABLE_PIN);
> } else {
> clrbit(MOTOR_ENABLE_PORT, MOTOR_ENABLE_PIN);
> }
> </code>
> Personally, I would prefer something like.....
> <code>
> write_bit(turn_motor_on, MOTOR_ENABLE_PORT, MOTOR_ENABLE_PIN);
> </code>
You could make that with a define i think. I guess even i could figure out
how eventually.
But well, wouldn't it be great if one could just write
MOTOR_ENABLE_PIN = turn motor on;
or, if need be
MOTOR_ENABLE_PORT.MOTOR_ENABLE_BIT = turn motor on;
I have the same situation here.
I don't understand why that doesn't work. I'm no programmer as everyone
sees easily, but when reading various stuff i get the impression "well, if
you don't use bit operations you aren't a proper programmer, get lost.".
That might well be true, and i'm not a proper programmer, but i still
don't understand why i must fight with &|!<< to change or read a single
bit.
I mean, life is hard enough, why make it any harder?
Why exactly is't a bit just a variable like for example PORTB?
I can write PORTB=0xFF; but can't do the same with bits.
ST
Yahoo! Groups LinksMessage
RE: [AVR-Chat] accessing bits (e.g. of ports)
2005-01-31 by Larry Barello
Attachments
- No local attachments were found for this message.