Hello,
I have to do a project that has to be written mainly in register level, with some exception that can be written in arudino code. I'm using a nano, so ATmega328P. I found this code that does the basic thing I need to do and I'm trying to build on it.
#include <avr/io.h>
#include <util/delay.h>
int main(void) {
DDRB |= 1 << PINB1; // Set pin 9 on arduino to output
/* 1. Set Fast PWM mode 14: set WGM11, WGM12, WGM13 to 1 */
/* 3. Set pre-scaler of 8 */
/* 4. Set Fast PWM non-inverting mode */
TCCR1A |= (1 << WGM11) | (1 << COM1A1);
TCCR1B |= (1 << WGM12) | (1 << WGM13) | (1 << CS11);
/* 2. Set ICR1 register: PWM period */
ICR1 = 39999;
/* Offset for correction */
int offset = 800;
/* 5. Set duty cycle */
while(1) {
OCR1A = 3999 + offset;
_delay_ms(1000);
OCR1A = 1999 - offset;
_delay_ms(1000);
}
return 0;
}
The code works and everything when I upload it. However, when I change the int main to void setup() and remove the return, it doesn't work. I tried putting what's in the while loop to void loop(), but still doesn't work. Any idea why it's not working and what should I do to fix it? I know it sounds like something simple, but I've been trying for several hours now and still no luck. I'm trying to learn how to do this.
#include <avr/io.h>
#include <util/delay.h>
#include <Arduino.h>
void setup() {
Serial.begin(115200);
DDRB |= 1 << PINB1; // Set pin 9 on arduino to output
/* 1. Set Fast PWM mode 14: set WGM11, WGM12, WGM13 to 1 */
/* 3. Set pre-scaler of 8 */
/* 4. Set Fast PWM non-inverting mode */
TCCR1A |= (1 << WGM11) | (1 << COM1A1);
TCCR1B |= (1 << WGM12) | (1 << WGM13) | (1 << CS11);
/* 2. Set ICR1 register: PWM period */
ICR1 = 39999;
}
void loop(){
/* Offset for correction */
int offset = 800;
/* 5. Set duty cycle */
while(1) {
OCR1A = 3999 + offset;
_delay_ms(1000);
OCR1A = 1999 - offset;
_delay_ms(1000);
}
}
I'm not getting any errors. It's just not doing anything.