Hello.
There are a few problems I see with your code that I’d like to first address:
DDRB = (0<<PB3);
Bitshifting zero doesn’t actually accomplish anything as 0 << x is always still just 0. This line is equivalent to DDRB = 0;
DDRD = (1 << PD3);
This line does what you want, but it could have unwanted side effects. You see, while you’re setting PD3 to be an output, you’re simultaneously setting all other pins on port D to be inputs. Typically, if you only want to affect the I/O state of a single pin, you want to use an operation like &= or |= in a way that will leave the rest of the pins of the port unchanged.
To set bit n of a byte while leaving the rest of the bits unchanged, you would use: byte |= (1 << n);
To clear bit n of a byte while leaving the rest of the bits unchanged, you would use: byte &= ~(1 << n);
This kind of bit manipulation can seem confusing at first. If it doesn’t quite make sense to you, I strongly suggest you take a look at the fantastic explanation Nexisnet wrote in the second post of this thread.
if PORTB |=(1<<PB3)
This if statement is syntactically incorrect in that it’s missing parentheses around the argument. Furthermore, the argument is actually changing the value of PORTB rather than just checking to see what the value is.
The following code should cause the buzzer on your Orangutan to make sound. If your Orangutan is running at 1 MHz, you should either uncheck its divide-by-8 fuse so that it runs at 8 MHz, or modify my code below by replacing the line
#define F_CPU 8000000
with
#define F_CPU 1000000
#include <avr/io.h>
#define F_CPU 8000000 // The Orangutan has an 8 MHz clock
#include <util/delay.h> // uses F_CPU to provide delay routines
// This function delays by sitting in a loop for time_ms milliseconds
void delay_ms(unsigned int time_ms)
{
while (time_ms != 0)
{
_delay_ms(1); // delay for 1 ms (_delay_ms comes from <util/delay.h>)
time_ms--;
}
}
int main()
{
DDRB |= 1 << PB0; // make PB0 (buzzer pin) an output
while (1)
{
PORTB |= 1 << PB0; // make PB0 (buzzer pin) high
delay_ms(5);
PORTB &= ~(1 << PB0); // make PB0 (buzzer pin) low
delay_ms(5);
}
return 0;
}
The following code should turn on the user LED when button SW3 is pressed:
#include <avr/io.h>
int main()
{
DDRB &= ~(1 << PB3); // make PB3 (button SW3 pin) an input
DDRD |= 1 << PD1; // make PD1 (LED pin) an output
while (1)
{
// to check a pin's input value, use PIN register masked for desired bit
if (PINB & (1 << PB3)) // if PB3 pin is high (i.e. if button SW3 is pressed)
PORTD |= 1 << PD1; // make pin PD1 high (turn on user LED)
else
PORTD &= ~(1 << PD1); // make pin PD1 low (turn off USER LED)
}
return 0;
}