Ich kann dir nur sagen, wie ich das gelöst habe. Eigentlich sollen sie volatile sein, aber ich weiss nicht warum und es funktioniert auch so.
Code:
byte state = 1;
int pwm_hi = 0;
int pwm_lo = 0;
int led_w = 13;
int servo_1 = 12;
int servo_1_pos = 150;
int servo_state = 0;
int n = 0;
void setup(){
pinMode(led_w, OUTPUT);
pinMode(servo_1, OUTPUT);
setup_timer1();
}
void loop()
{
if(servo_state == 0)
{
delay(20);
servo_1_pos = servo_1_pos + 1;
if(servo_1_pos ==200)
{
servo_state = 1;
}
}
if(servo_state == 1)
{
delay(20);
servo_1_pos = servo_1_pos - 1;
if(servo_1_pos ==100)
{
servo_state = 0;
}
}
}
void setup_timer1(){
cli(); // disable interrupts
TCCR1A = 0; // Register TCCR1A auf 0 setzen
TCCR1B = 0; // Register TCCR1B auf 0 setzen um Timer zu beenden
//CTC setzen
OCR1A = 19; // bis 15624 ticken dann interrupt
//enable CTC
TCCR1B |= (1 << WGM12);
// Set CS10 bit so timer runs at clock speed:
//Timerresolution: 1/(16*10^6 / 1024)
TCCR1B |= (0 << CS10);
TCCR1B |= (1 << CS11);
TCCR1B |= (0 << CS12); // prescaler 1024
// enable Timer1 compare interrupt
TIMSK1 |= (1 << OCIE1A);
// enable global interrupts:
sei();
}
ISR(TIMER1_COMPA_vect)
{
if (n == 20000)
{
digitalWrite(led_w, !digitalRead(led_w));
n = 0;
}
n++;
if (pwm_hi > 0)
{
digitalWrite(servo_1,HIGH);
pwm_hi = pwm_hi - 1;
pwm_lo = 0;
}
else if(pwm_hi == 0)
{
pwm_lo++;
digitalWrite(servo_1,LOW);
}
if (pwm_lo == 2000 - servo_1_pos)
{
pwm_hi = servo_1_pos;
}
}
Lesezeichen