|
|
Examples
Few basic examples of input and output to test out your circuit and softwares that they work like they should.
Pins:
PB0 (pin 5) = 1 (dec), 0x01 (hex), [00001 bin]
PB1 (pin 6) = 2 (dec), 0x02 (hex), [00010 bin]
PB2 (pin 7) = 4 (dec), 0x04 (hex), [00100 bin]
PB3 (pin 2) = 8 (dec), 0x08 (hex), [01000 bin]
PB4 (pin 3) = 16 (dec), 0x10 (hex), [10000 bin]
Example 1: Simple LED flasher
This simple code just flashes the LED on for 1 sec and then off for 1 sec and loops it forever.
// Frequency needed by the delay function.
// The chip is factory set to run on internal
// oscillator at 1 MHz so the value is 1000000UL
#define F_CPU 1000000UL
#include <avr/io.h>
#include <util/delay.h>
// LED is connected to PB4 (pin 3 on the chip)
#define LEDPIN 4
int main(void)
{
DDRB = 0x1F; // PB0-PB4 output
PORTB = 0x00; // Set all pins low
// Turn LED on for 1 sec and then off for 1 sec forever
while(1)
{
PORTB |= _BV(LEDPIN); // Turn LED on
_delay_ms(1000); // Wait 1000 ms (1 sec)
PORTB &= ~(_BV(LEDPIN)); // Turn LED off
_delay_ms(1000); // Wait 1000 ms (1 sec)
}
return 0;
}

Example 1 in action
Example 2: LED and a button
The LED will be on when the button is pressed. Just a quick example how to read the state of a button. First let's do a little modification to the board and add a button between pin 2 of the chip and ground:

Button added to the original circuit
// Frequency number needed by the delay function.
// The chip is factory set to run on internal
// oscillator at 1 MHz so the value is 1000000UL
#define F_CPU 1000000UL
#include <avr/io.h>
// LED is connected to PB4 (pin 3 on the chip)
#define LEDPIN 4
// Button is connected to PB3 (pin 2 on the chip)
#define BTNPIN 3
int main(void)
{
DDRB = 0x17; // PB3 input, others output (0x1F-0x08=0x17 or 31-8=23)
PORTB = 0x08; // Enable internal pull-up resistor on PB3 and set others low
// Turn LED on for 1 sec and then off for 1 sec forever
while(1)
{
// Check if PB3 is low (button connects it to ground)
// PB3 is normally high as it has been pulled up by the internal resistor
if(bit_is_clear(PINB, BTNPIN))
PORTB |= _BV(LEDPIN); // Turn LED on
else
PORTB &= ~(_BV(LEDPIN)); // Turn LED off
}
return 0;
}

Example 2 in action
| | Pages: 1 2 3 4 5 6 | |


Content in english!
Sisältö suomeksi!
