Розетка, активируемая звуком

valera678
Offline
Зарегистрирован: 04.11.2016

Привет,друзья

не силен пока в программироваии

нужна помощь по этому девайсу http://cxem.net/arduino/arduino148.php

как переписать скетч чтобы свет включался по запрограммированному хлопку и отключался по хлопку?

Заранее благодарю!!!

Клапауций 234
Offline
Зарегистрирован: 24.10.2016

по какому из двух хлопков включаться?

valera678
Offline
Зарегистрирован: 04.11.2016

хотелось бы менее остроумных но более конструктивных ответов)

Клапауций 234
Offline
Зарегистрирован: 24.10.2016

valera678 пишет:

хотелось бы менее остроумных но более конструктивных ответов)

всем хотелось бы 

Genri5
Offline
Зарегистрирован: 31.05.2016

Собрать схему, скачать код, там есть подробные коментарии - колличество ударов, время ожидания и т. д. И путем проб и ошибок переделать под свои нужды. А вообще помоему там есть режим программирования.

И вообще,  Arduino Uno использовать для этого кода - это черезчур.

p.masyukov
p.masyukov аватар
Offline
Зарегистрирован: 14.11.2015

Кто мешает сделать так и разбираться???

/*
Parts of this code were based on code from The Secret Knock Detecting Door Lock by Steve Hoefer
*/

/* Pin Connections
   Analog Pin 1: Input from electret microphone assembly
   Digital Pin 2: Switch to enter a new code.  Short this to enter programming mode.
   Digital Pin 3: Output Relay
   Digital Pin 4: Red LED. 
   Digital Pin 5: Green LED. 
 */
 
// Pin Variable definitions
const int NoiseSensor = 1;         // electret microphone sensor on pin 1.
const int programSwitch = 2;       // If this is high we program a new code.
const int Output = 3;              // Output Relay
const int redLED = 4;              // Status LED
const int greenLED = 5;            // Status LED
 
// Tuning constants.  Could be made vars and hooked to potentiometers for soft configuration, etc.
const int threshold = 8;          // Minimum signal from the microphone to register as a knock
const int rejectValue = 25;        // If an individual knock is off by this percentage of a knock we don't trigger output.
const int averageRejectValue = 15; // If the average timing of the knocks is off by this percent we don't trigger output.
const int knockFadeTime = 150;     // milliseconds we allow a knock to fade before we listen for another one. (Debounce timer.)
const int maximumKnocks = 20;       // Maximum number of knocks to listen for.
const int knockComplete = 1200;     // Longest time to wait for a knock before we assume that it's finished.

// Variables.
int secretCode[maximumKnocks] = {50, 25, 25, 50, 100, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};  // Default setup: "Shave and a Hair Cut, two bits."
int knockReadings[maximumKnocks];   // When someone knocks this array fills with delays between knocks.
int NoiseSensorValue = 0;           // Last reading of the knock sensor.
int programButtonPressed = false;   // Flag so we remember the programming button setting at the end of the cycle.



void setup() {
  pinMode(Output, OUTPUT);
  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(programSwitch, INPUT);
  
  Serial.begin(9600);               			     // Uncomment the Serial.bla lines for debugging.
  Serial.println("Program start.");  			     // but feel free to comment them out after it's working right.
  
  digitalWrite(greenLED, HIGH);                // Green LED on, everything is go.
}


void loop() 
{

NoiseSensorValue = analogRead(NoiseSensor);   // Listen for any knock at all.
  
  if (digitalRead(programSwitch)==HIGH)       // Если нажата кнопка программирования
  {
    programButtonPressed = true;               // Yes, so lets save that state
    digitalWrite(redLED, HIGH);                // Включаем красный светодиод для показухи - что режим программирования.
  } 
  else 
  {
    programButtonPressed = false;
    digitalWrite(redLED, LOW);                 // Выключаем красный светодиод для показухи - что режим программирования выключен.
  }
  
  if (NoiseSensorValue >=threshold)
  {
    listenToSecretKnock();
  }
} 



void listenToSecretKnock()        // Records the timing of knocks.
{
  Serial.println("knock starting");   

  int i = 0;
  // First lets reset the listening array.
  for (i=0;i<maximumKnocks;i++)
  {
    knockReadings[i]=0;
  }
  
  int currentKnockNumber=0;         			// Incrementer for the array.
  int startTime=millis();           			// Reference for when this knock started.
  int now=millis();
  
  digitalWrite(greenLED, LOW);      			// we blink the LED for a bit as a visual indicator of the knock.
  if (programButtonPressed==true)
  {
     digitalWrite(redLED, LOW);                         // and the red one too if we're programming a new knock.
  }
  delay(knockFadeTime);                       	        // wait for this peak to fade before we listen to the next one.
  digitalWrite(greenLED, HIGH);  
  if (programButtonPressed==true)
  {
     digitalWrite(redLED, HIGH);                        
  }

  do     //listen for the next knock or wait for it to timeout. 
  {
    NoiseSensorValue = analogRead(NoiseSensor);
    if (NoiseSensorValue >=threshold)        //got another knock. Record the delay time.
    {                   
      Serial.println("knock.");
      now=millis();
      knockReadings[currentKnockNumber] = now-startTime;
      currentKnockNumber ++;                             //increment the counter
      startTime=now;                // and reset our timer for the next knock

      digitalWrite(greenLED, LOW);  
      if (programButtonPressed==true)
      {
        digitalWrite(redLED, LOW);                       // and the red one too if we're programming a new knock.
      }
      delay(knockFadeTime);                              // again, a little delay to let the knock decay.
      digitalWrite(greenLED, HIGH);
      if (programButtonPressed==true)
      {
        digitalWrite(redLED, HIGH);                         
      }
    }

    now=millis();
    
   
  } 
  while ((now-startTime < knockComplete) && (currentKnockNumber < maximumKnocks));  //did we timeout or run out of knocks?

                                                   //we've got our knock recorded, lets see if it's valid
  if (programButtonPressed==false)                 // only if we're not in progrmaing mode.
  {
    if (validateKnock() == true)
    {
      triggerOutput(); 
    } 
    else 
    {
      Serial.println("Secret knock failed.");
      Serial.println("");
      digitalWrite(greenLED, LOW);  		// We didn't trigger output, so blink the red LED as visual feedback.
      for (i=0;i<4;i++)
      {					
        digitalWrite(redLED, HIGH);
        delay(100);
        digitalWrite(redLED, LOW);
        delay(100);
      }
      digitalWrite(greenLED, HIGH);
    }
  } 
  else    // if we're in programming mode we still validate the knock, we just don't do anything with the output
  { 
    validateKnock();
    Serial.println("New code stored.");      // and we blink the green and red alternately to show that program is complete.
    digitalWrite(redLED, LOW);
    digitalWrite(greenLED, HIGH);
    for (i=0;i<3;i++)
    {
      delay(100);
      digitalWrite(redLED, HIGH);
      digitalWrite(greenLED, LOW);
      delay(100);
      digitalWrite(redLED, LOW);
      digitalWrite(greenLED, HIGH);      
    }
  }
}



void triggerOutput()    // Triggers the output
{
  Serial.println("Output Triggered!");
  Serial.println("");
  int i=0;
  
  digitalWrite(Output, HIGH);          // turn the output on for a set time.
  digitalWrite(greenLED, HIGH);        // And the green LED too.
  delay(10000);
  digitalWrite(Output, LOW);           // Turn the motor off.
}
   




// Sees if our knock matches the secret.
// returns true if it's a good knock, false if it's not.
boolean validateKnock(){
  int i=0;
  int currentKnockCount = 0;
  int secretKnockCount = 0;
  int maxKnockInterval = 0;          			// We use this later to normalize the times.
  
  for (i=0;i<maximumKnocks;i++){
    if (knockReadings[i] > 0){
      currentKnockCount++;
    }
    if (secretCode[i] > 0){  					//todo: precalculate this.
      secretKnockCount++;
    }
    
    if (knockReadings[i] > maxKnockInterval){ 	// collect normalization data while we're looping.
      maxKnockInterval = knockReadings[i];
    }
  }
  
  // If we're recording a new knock, save the info and get out of here.
  if (programButtonPressed==true){
      for (i=0;i<maximumKnocks;i++){ // normalize the times
        secretCode[i]= map(knockReadings[i],0, maxKnockInterval, 0, 100); 
      }
      // And flash the lights in the recorded pattern to let us know it's been programmed.
      digitalWrite(greenLED, LOW);
      digitalWrite(redLED, LOW);
      delay(1000);
      digitalWrite(greenLED, HIGH);
      digitalWrite(redLED, HIGH);
      delay(50);
      for (i = 0; i < maximumKnocks ; i++){
        digitalWrite(greenLED, LOW);
        digitalWrite(redLED, LOW);  
        // only turn it on if there's a delay
        if (secretCode[i] > 0){                                   
          delay( map(secretCode[i],0, 100, 0, maxKnockInterval)); // Expand the time back out to what it was.  Roughly. 
          digitalWrite(greenLED, HIGH);
          digitalWrite(redLED, HIGH);
        }
        delay(50);
      }
	  return false; 	// We don't trigger the output when we are recording a new knock.
  }
  
  if (currentKnockCount != secretKnockCount)    //Did we get the right number of knocks?
  {
    return false; 
  }
  
  /*  Now we compare the relative intervals of our knocks, not the absolute time between them.
      (ie: if you do the same pattern slow or fast it should still open the door.)
      This makes it less picky, which while making it less secure can also make it
      less of a pain to use if you're tempo is a little slow or fast. 
  */
  int totaltimeDifferences=0;
  int timeDiff=0;
  for (i=0;i<maximumKnocks;i++)
  { 
    knockReadings[i]= map(knockReadings[i],0, maxKnockInterval, 0, 100);      // Normalize the times
    timeDiff = abs(knockReadings[i]-secretCode[i]);
    if (timeDiff > rejectValue)    // Individual value too far out of whack
    { 
      return false;
    }
    totaltimeDifferences += timeDiff;
  }

  if (totaltimeDifferences/secretKnockCount>averageRejectValue)     // It can also fail if the whole thing is too inaccurate.
  {
    return false; 
  }
  
  return true;
  
}

Строки подсвечены.

Переведешь и выложишь сюда обратно - может кому в будущем пригодится.

Учись. 

https://www.youtube.com/watch?v=bO_jN0Lpz3Q&index=1&list=PLfDmj22jP9S759DT250VVzfZs_4VnJqLa

http://arduino.ru/

http://arduino.ru/Reference

Вчера было скучно, сегодня только за вознаграждение (у меня кофе и печеньки заокончились )))

ua6em
ua6em аватар
Offline
Зарегистрирован: 17.08.2016

Здесь обивают пороги в основном ГУРу ардуиностроения им эта тривиальная задача совсем не интересна, по существу из скеча надо выбросить 99% кода для вашей задачи

Что имеем?

выход = LOW;

Задан пороговый уровень на аналоговом входе, он считывается, если он превышает пороговый включить розетку. (выход = !выход)
Потом по вашей задаче сделать выдержку на пару секунд (delay(2000); и снова считывать с аналогового входа.

Как бы всё

PS
const int NoiseSensor = 1;  .//сюда подключен микрофон

const int threshold = 8;  Это константа порогового уровня с микрофона

Аconst int Output = 3;   а сюда подключено реле

void setup() {

выход = LOW;
}

void loop() {
 NoiseSensorValue = analogRead(NoiseSensor);
    if (NoiseSensorValue >=threshold)   
    {   
      digitalWrite(Output, !выход); //здесь вывести инверсное значение пина выхода
    delay(2000);   //задержка
    }            

}

 

valera678
Offline
Зарегистрирован: 04.11.2016

Спасибо,ua6em