I'm trying to make a 10Hz pulse wave output at Arduino's pin 9 by using the following code I wrote:
#define F_CPU 16000000UL
#include <avr/io.h> //Defines pins, ports, etc.
#include <util/delay.h>
int main(void)
{
DDRB |= (1<<DDD1); //Does this set port B pin 1 and is this pin 9 in UNO board?
PORTB |= (1<<PORTB1);
while(1){
PORTB |= ~(1<<PORTB1);
_delay_ms(100);
PORTB |= (1<<PORTB1);
}
}
I use Atmel Studio to uplaad the code and it works fine with other codes. But for some reason this code doesn't work. What can be the problem here?
Still doesnt work edit:
#define F_CPU 16000000UL
#include <avr/io.h> //Defines pins, ports, etc.
#include <util/delay.h>
int main(void)
{
DDRB |= (1<<DDD1);
PORTB |= (1<<PORTB1);
while(1){
PORTB &= ~(1<<PORTB1);
_delay_ms(100);
PORTB |= (1<<PORTB1);
}
}
3 Answers 3
You have your whole 100ms wait time while the pin is low. You need half of it while low, half while high.
while(1){
PORTB &= ~(1<<PORTB1);
_delay_ms(50);
PORTB |= (1<<PORTB1);
_delay_ms(50); // You need a delay here too.
}
-
oh without the second delay it just jumps to low again. i see thanks. just curious is this a good way to obtain a very precise pulse frequency? i mean by using delay function as i did? or interrupts required? im trying to build a as precise as possible simple pulse generator.floppy380– floppy3802017年02月21日 11:28:13 +00:00Commented Feb 21, 2017 at 11:28
-
@doncarlos no kidding, I was telling to you for a while!KIIV– KIIV2017年02月21日 11:29:42 +00:00Commented Feb 21, 2017 at 11:29
-
@doncarlos and no, this is horrible way to do frequency generator. Use Timers and it's waveform generator modes instead.KIIV– KIIV2017年02月21日 11:33:30 +00:00Commented Feb 21, 2017 at 11:33
Your code doesn't clear anything.
PORTB |= ~(1<<PORTB1); // set everything except PORTB1 pin
_delay_ms(100);
PORTB |= (1<<PORTB1); // set PORTB1 pin
And recommended tutorial: Bit manipulation (AKA "Programming 101") from the AVRFreaks.net
BTW: next issue might be "the pulse is way too fast so it seems there is none"
Try this:
while(1) {
PINB = _BV(PINB1); // toggle pin
_delay_ms(50);
}
-
Doesn't PORTB |= ~(1<<PORTB1); set PORTB1 pin to zero?floppy380– floppy3802017年02月21日 11:11:18 +00:00Commented Feb 21, 2017 at 11:11
-
No, pipe | is logic OR, that means whenever is corresponding bit logic one, result is logic oneKIIV– KIIV2017年02月21日 11:12:29 +00:00Commented Feb 21, 2017 at 11:12
-
pulse is not fast and set to 10Hz _delay_ms(100). And I check with a scope. Theres nothing stillfloppy380– floppy3802017年02月21日 11:18:38 +00:00Commented Feb 21, 2017 at 11:18
-
@doncarlos Well - there is clear bit, wait for 100ms, set bit ... and repeat.. that pause between setting and resetting bit might be even less than 200nsKIIV– KIIV2017年02月21日 11:28:28 +00:00Commented Feb 21, 2017 at 11:28
PORTB |= ~(1<<PORTB1);
change it to:
PORTB &= ~(1<<PORTB1);
if you want to clear PB1.