Using multiple timers for servo, tone and pwm simultaneously

Hi, I'd like to control speed of motor with PWM signal, position of servo that depends on button state (open/close) and give sound signal before servo moves. I wrote this code - it's just sequential sketch, not real program - but I found problems, because I think the same timers are used to different tasks. I am using Arduino Pro mini with 16MHz@5V. Can you help me to solve this problem?

#include <Servo.h>
#include "pitches.h"

const int btnUP=4;
const int btnDN=5;
const int analogInPin = A0;  // wejście potencjometru - prędkość pociągu
const int analogOutPin = 9;  // wyjście D9 - sygnał PWM na mostek H
int melody[] = {NOTE_C7, NOTE_G7, 0};
int noteDurations[] = {32, 16, 32};
Servo drzwi;
int sensorValue = 0;  
int outputValue = 0; 
int pos=0; 

void sygnal2(){
for (int thisNote = 0; thisNote < 3; thisNote++) {
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(8, melody[thisNote], noteDuration);//8 to wyjśice D8
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    noTone(8);
  }
}

void zamkDrzwi(){
    drzwi.write(0);              // tell servo to go to position in variable 'pos'
  }

void otwDrzwi(){
      drzwi.write(180);              // tell servo to go to position in variable 'pos'
    }

void setup() {
  Serial.begin(9600);
  pinMode(btnUP, INPUT_PULLUP);
  pinMode(btnDN, INPUT_PULLUP);
  drzwi.attach(11);
}

void loop() {
int btnUPstate=digitalRead(btnUP);
if(btnUPstate==LOW){
  for(int i=0;i<9;i++){sygnal2();}
  otwDrzwi();
  delay(10);
}

int btnDNstate=digitalRead(btnDN);
if(btnDNstate==LOW){
  for(int i=0;i<3;i++){sygnal2();}
  zamkDrzwi();
  delay(10);
}

  sensorValue = analogRead(analogInPin);
  outputValue = map(sensorValue, 0, 1023, 0, 255);
  analogWrite(analogOutPin, outputValue);

  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\t output = ");
  Serial.println(outputValue);
  delay(2);
}

What problems? How do they show up?

Which timers?

Try and comment out tone, for a test. Does it work?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.