What microcontroller/compiler do, when he see a "bit" which was already set before.

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hello programmers. Please help.

What microcontroller/compiler do, when he see a "bit" which was already set before. Is it bad programming style? Will a "bit" be overwritten again?

 

In the "else" we see as a " PB2 bit" could be rewritten to zero. Or maybe I should not think about it at all? The compiler does all the work for me. I guess I should learn assembler to solve similar questions by myself in the future, but may be somebody could explain. Thanks.

 

#include <avr/io.h>
#define BUTTON_PRESSED (PINB & (1<<PB1))
#define LED_ON PORTB |= (1<<PB2)
#define LED_OFF PORTB &= ~(1<<PB2)

void setup () {
	DDRB =  0b00011101;
	PORTB = 0b00100010;
}

int main(void)
{
	setup();
	
    while(1)
    {
        if (!BUTTON_PRESSED)
        {
			LED_ON;
        } 
        else
        {
			LED_OFF; // this place will executed again and again, while button not pressed. 
        }
    }
}

 

 

Last Edited: Sat. Jul 11, 2015 - 07:52 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

Compiler will generate the code to do what it was asked to do.

 

For simple variables it does not matter. But writing peripheral registers may have side effects. One good example is PINx registers on some AVRs. While normally the register reads the state of the inputs, if you write a one to any locations, corresponding pin will toggle. All those side effects are described in the documentation.

 

In this specific example you have noting to worry about.

 

NOTE: I no longer actively read this forum. Please ask your question on www.eevblog.com/forum if you want my answer.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Repeatedly setting a bit to 1 (or 0) does not harm anything and can simplify how you implement your logic.
In your example, you can ;
1) check if the button is pressed and then set the led on/off.
or
2) check if the button has changed state (from pressed to not-pressed, or from not-pressed to pressed) and then set the led off/on.
Either method will produce the same end result.


Having said that, for I/O or memory it does not matter if you repeatedly set/clear bits, but some internal modules *will* do something everytime you write to them (eg. the watchdog)

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
// this place will executed again and again, while button not pressed. 

So will this, whether the button is pressed or not:

if (!BUTTON_PRESSED)

A microcontroller program nearly always runs forever, so the "main loop" will constantly be executed unless the main processor clock is stopped (deep sleep).

You can put lipstick on a pig, but it is still a pig.

I've never met a pig I didn't like, as long as you have some salt and pepper.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks to all!