Помощь в проекте BUZZER+BLUETOOTH
- Войдите на сайт для отправки комментариев
Ср, 08/01/2020 - 18:25
Добрый день, уважаемые форумчане. Совсем недавно начал работать с Arduino, и связи с моим незнанием, появилась проблема. У меня есть ардуино уно, к которой подключен hc-06 и buzzer. Когда я подключаюсь к блютуз и отправляю нужную команду, buzzer начинает проигрывать звуки, в принципе так и нужно. Но, я бы хотел проигрывание звуков отправкой другой команды, а как это сделать, не пойму.
Мой код. Пытался с помощью булина контролировать это, но тоже безуспешно
#include <SoftwareSerial.h> #include "pitches.h" // notes in the melody: int melody[] = { //using note c5 e5 a5 b4 g5 NOTE_C5, NOTE_E5, NOTE_A5, NOTE_B4, NOTE_G5 }; // note durations: 8 = eighth note int noteDurations[] = { 8,8,8 }; #define TxD 2 #define RxD 3 #define buzzer 4 boolean canplay = true; SoftwareSerial mySerial(RxD, TxD); // RX, TX for Bluetooth void setup() { mySerial.begin(9600); // For Bluetooth pinMode(buzzer, OUTPUT); Serial.begin(9600); // For the IDE monitor Tools -> Serial Monitor } void loop() { // put your main code here, to run repeatedly: boolean isValidInput; do { byte c; // get the next character from the bluetooth serial port while ( !mySerial.available() ) ; // LOOP... c = mySerial.read(); // Execute the option based on the character recieved Serial.print(c); // Print the character received to the IDE serial monitor switch ( c ) { case 'a': // You've entered a // Do the code you need when 'a' is received..... mySerial.println( "You've start fuck buzzing!" ); canplay = true; StillIt(); isValidInput = true; break; case 'b': // You've entered b // Do the code you need when 'a' is received..... mySerial.println( "You've stop fuck buzzing!" ); canplay = false; isValidInput = true; break; default: // Do the code you need when any other character is received..... mySerial.println( "Please enter 'a' or 'b'" ); isValidInput = false; break; } } while ( isValidInput == true ); // Repeat the loop } void StillIt() { if (canplay == true) { // iterate over the notes of the melody: for (int songLoop = 0; songLoop < 4; songLoop++){//loop to play the all the notes several times for (int loop1 = 0; loop1 < 8; loop1++){//loop to play notes c5 e5 a5 right after each other for (int thisNote = 0; thisNote < 3; thisNote++) { // to calculate the note duration, take one second // divided by the note type. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc. int noteDuration = 1000 / noteDurations[thisNote]; tone(buzzer, melody[thisNote], noteDuration); // to distinguish the notes, set a minimum time between them. int pauseBetweenNotes = noteDuration * 0.5; delay(pauseBetweenNotes); // stop the tone playing: noTone(3); } delay(150); digitalWrite(8, HIGH); // turn the LED on (HIGH is the voltage level) delay(1); // wait for a milisecond digitalWrite(8, LOW); // turn the LED off by making the voltage LOW delay(1); // wait for a milisecond digitalWrite(9, HIGH); // turn the LED on (HIGH is the voltage level) delay(1); // wait for a milisecond digitalWrite(9, LOW); // turn the LED off by making the voltage LOW delay(1); // wait for a milisecond } for (int loop2 = 0; loop2 < 3; loop2++){ //loop to play notes b4 e5 a5 tone(buzzer, NOTE_B4, 125); delay(62.5); noTone(buzzer); tone(buzzer, NOTE_E5, 125); delay(62.5); noTone(buzzer); tone(buzzer, NOTE_A5, 125); delay(62.5); noTone(buzzer); delay(150); digitalWrite(8, HIGH); // turn the LED on (HIGH is the voltage level) delay(1); // wait for a milisecond digitalWrite(8, LOW); // turn the LED off by making the voltage LOW delay(1); // wait for a milisecond } for (int loop3 = 0; loop3 < 5; loop3++){//loop to play b4 e5 g5 tone(buzzer, NOTE_B4, 125); delay(62.5); noTone(buzzer); tone(buzzer, NOTE_E5, 125); delay(62.5); noTone(buzzer); tone(buzzer, NOTE_G5, 125); delay(62.5); noTone(buzzer); delay(150); digitalWrite(9, HIGH); // turn the LED on (HIGH is the voltage level) delay(1); // wait for a milisecond digitalWrite(9, LOW); // turn the LED off by making the voltage LOW delay(1); // wait for a milisecond } digitalWrite(8, HIGH); // turn the LED on (HIGH is the voltage level) delay(1); // wait for a milisecond digitalWrite(8, LOW); // turn the LED off by making the voltage LOW delay(1); // wait for a milisecond digitalWrite(9, HIGH); // turn the LED on (HIGH is the voltage level) delay(1); // wait for a milisecond digitalWrite(9, LOW); // turn the LED off by making the voltage LOW delay(1); // wait for a milisecond } } }Мы тоже не понимаем, что такое "другая команда" - "ФАС!!!", "Быстро заиграл, ёп!", удар ардуине по кумполу или что-то иное?
При отправке команды b, по идеи проигрывание должно было остановиться, но не получается
Давайте подумаем вместе... вот, скажем, я вам говорю: сиди и перебирай гречу. А через полчаса прихожу и спрашиваю - почему пол не метён? Каков ваш ответ?
Если скажу что вы смешной, ответите по теме?
Это и есть по теме - МК не может делать две вещи одновременно. И пока StillIt() не закончит выполнять - никакие иные команды исполнять и не подумает.
Есть решение этому или есть другие способы?
Есть решение этому или есть другие способы?
видимо научить эту функцию прерываться
Можете дать пример или ссылку где это описывается?
Можете дать пример или ссылку где это описывается?
например, раз в секунду проверяйте - нет ли новых команд
Думаешь, что со всеми его дилеями это поможет? ;)
Думаешь, что со всеми его дилеями это поможет? ;)
там у него три цикла, в каждом и проверять, задержка получится в пределах полсекунды, как вариант
Думаешь, что со всеми его дилеями это поможет? ;)
Если понимать мой совет буквально - поможет :)
Ведь чтоб проверять раз в секунду - все делеи придется выкинуть, заодно и код перепишет :)