Using a function in Embedded C.
In this example, we will make animations by turning off and on Leds with some delays. We could simply do it like this. We could simply do it like this.
PORTB=0B10101010; _delay_ms(1000); PORTB=0B01010101; _delay_ms(1000); . . . PORTB=0B01000001; _delay_ms(1000);
But instead of writing like this, we would use the function Led_pin( ). It will reduce the typing a bit but in the next blog, we will learn to make it very small by learning a concept called Bit Shifting.
Let\’s go for an example.
#define F_CPU 16000000UL //defining the clock speed of the processor #include <avr/io.h> // library for using registers [PORTX,PORTD,PINX] #include <util/delay.h> // library for using delay void Led_pin(uint8_t byte) // Making a function with argument \"byte\" having data type unsigned int 8. { PORTB = byte; // Whenever the function is called it will store the argument byte in PORTB with delay. _delay_ms(100); } int main(void) { DDRB = (0b00111110); while(1) { Led_pin(0b00101010); Led_pin(0b00010100); Led_pin(0b00101110); Led_pin(0b00010001); Led_pin(0b00101010); Led_pin(0b00011100); Led_pin(0b00101011); Led_pin(0b00010100); PORTB=0b00000000; _delay_ms(1000); } return(0); }
In the above code we made a function Led_pin( ).
void Led_pin(uint8_t byte) { PORTB = byte; _delay_ms(100); }
Here Led_pin takes a single byte of data type unsigned int [uint8_t]. Whenever our code calls this function the arguments inside it directly go to the PORTB and blink for 100 microseconds asset in delay.
OUTPUT
If you are new and feeling confused about other libraries and functions then please refer to this blog.