avr-gcc-list
[Top][All Lists]

## Re: [avr-gcc-list] Using PORTB with variables, PORTB = var

 From: Ned Konz Subject: Re: [avr-gcc-list] Using PORTB with variables, PORTB = var Date: Sat, 22 Apr 2006 09:47:12 -0700

```
On Apr 22, 2006, at 2:29 AM, address@hidden wrote:

```
```On Sat, 22 Apr 2006 08:30:33 +0200
Lars Noschinski <address@hidden> wrote:

```
``` How can I use the PORTB constant with variables? eg:

while (1) {
var <<= 1;
PORTB = var
}
```
```
This will work. But after seven iterations (if var is (u)int8_t), var
will be 0.

```
That is what I'm trying to acheive. I'd like to be able to do it with variables like I do above, but it doesn't seem to work. Once I replace "var" with an
```actual number, it works as expected.
```
```
The problem lies probably elsewhere.
```
```

OK.  This is some brief code...  This works as expected.

int main() {
DDRB = 255;
while (1) {
int var=1;
while (var != 0) {
PORTB = var;
var <<= 1;
}
}
return 0;
}

```
This example doesn't, and I don't know why... I know it's specific to C, so that's why I'm asking here...
```
int var 1;

```
```// the problem is that "int" is both signed and 16-bits wide; you want
```
// an unsigned 8-bit value. And I assume you meant to have an = sign in there.
```// Better to use:
unsigned short var = 1;
```
```void blink()
{
PORTB ^= var; // LED on
```
// assuming you have an LED per pin and the low 8 bits of var are not zero, that'd work.
``` sleep(50);
PORTB = 255; // LEDs off
sleep(50);
}

void change() {
var <<= 1;
```
// the way you have it written, this would toggle each of the pins of PORTB once.
```// is that what you're getting?
```
// The problem is that when var gets to 128, it next becomes 256, which is all // 0s in the low 8 bits, so it won't affect your LEDs. The sequence would be:
```// 1, 2, 4, 8, 16, 32, 64, 128,    as intended
```
// 256, 512, 1024, 2048, 4096, 8192, 16384, -32768, // which won't work
```// 0, 0, 0, ...   // which clearly won't work
// better to do this (assuming var is 8 bits):
var <<= 1;
if (var == 0) var = 1;
```
```}

int main() {
DDRB = 255;
PORTB=255;
while (1) {
change();
}
return 0;
}

This doesn't work as expected...  not sure why.
```
```
```
It's always better to say *what it does do*, and *what you expected*, rather than "doesn't work as expected" if you want people to help you.
```
```
I would like to keep the functions if possible, I'm thinking it has something to do with scope perhaps?
```
It's hard to tell why you would like to keep the functions.
You're probably in a better position to say why <g>.
--
Ned Konz
MetaMagix embedded consulting