مشروع الحلقة 4: تصنيع جهاز إنذار ضد الحريق

نص البرنامج (الكود):

 

//Arduino-MQ2 Gas Sensor-Darah
// Darahmakers.com


int buzzer = 6;
int smokeA0 = 0;

// Your threshold value. You might need to change it.
int sensorThres = 320;

void setup() {
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  Serial.begin(9600);
}

void loop() {
  int analogSensor = analogRead(smokeA0);

  Serial.print("Pin A0: ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  
  if (analogSensor > sensorThres)
  {
        playTone(300, 160);
        delay(150);
    
  }
  else
  {
    noTone(buzzer);
  }
  delay(100);
}

// duration in mSecs, frequency in hertz

void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;

     while (elapsed_time < duration) {
        digitalWrite(buzzer,HIGH);
        delayMicroseconds(period / 2);
        digitalWrite(buzzer, LOW);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
    }
}