I'm trying to make a Whack-A-Mole game using an Arduino Mega with 10 LEDs (Moles) and 10 Push Buttons (Whack). The electronics are completed and tested, everything works fine. It also has a BLE radio attached which prompts the board to start one of three games I plan to do.
The problem I'm having is this:
In my main loop, I listen for a command from the app coming via BLE. When a "1" is sent by the app (serial pass through), I call the function
playGameOne();
The main thing is that everything loops in the main loop fine, but when I jump to the game function, it runs once and returns back to the main loop again. How can I keep the user looping in the game function until the game is over? Oh - and I'm not trying to use any Interrupts, but I imagine thats one way of doing it.
The latest incarnation of the game function looks like this:
//////////////////////////////////////////////
////////////////// GAME 1 //////////////////
void gameOne(){
//var int eTime;
// inform player game is about to begin
playCountdown();
Serial.println("Game Begun");
// initialize var to count time
elapsedMillis timeElapsed;
if(gameState < 1){
gameOneOne();
Serial.print("Game finished - Your time: ");
Serial.println(timeElapsed);
}
}
void gameOneOne(){
while(digitalRead(btPin31) == LOW){
// turn on LED45
digitalWrite(ledPin45, HIGH);
// wait for user to push corresponding button
if(digitalRead(btPin31) == HIGH){
// turn off the LED and jump to next LED - gameOneTwo()
digitalWrite(ledPin45, LOW);
gameOneTwo();
}
}
}
void gameOneTwo(){
while(digitalRead(btPin39) == LOW){
// turn on LED53
digitalWrite(ledPin53, HIGH);
if(digitalRead(btPin39) == HIGH){
digitalWrite(ledPin53, LOW);
// Finish the game, set state to 1
gameState = 1;
}
}
}
Not only this doesn't work, I highly doubt this is the proper way of coding games. In fact the ideal would be to have a Game Script that can be uploaded dynamically. The game Script would look like:
Header {name of game}
45 {pin of first LED}
500 {how long to keep it on, in ms}
49 {pin of the second LED}
500 {how long to keep it on, in ms}
... and so on
End of File
What is the best resource to learn this properly.
EDIT
Here's my main loop
// included header files
#include <elapsedMillis.h> // Measuring Elapsed Time Library
// Constant - Piezzo Speaker Pin
const int beepPin = 11; // the number of the Piezo Spkr pin
// Constants - Button Pins
const int btPin30 = 30;
const int btPin31 = 31;
const int btPin32 = 32;
const int btPin33 = 33;
const int btPin34 = 34;
const int btPin35 = 35;
const int btPin36 = 36;
const int btPin37 = 37;
const int btPin38 = 38;
const int btPin39 = 39;
// Constants - LED Pins
const int ledPin53 = 53;
const int ledPin52 = 52;
const int ledPin51 = 51;
const int ledPin50 = 50;
const int ledPin49 = 49;
const int ledPin48 = 48;
const int ledPin47 = 47;
const int ledPin46 = 46;
const int ledPin45 = 45;
const int ledPin44 = 44;
//Variable for storing BLUETOOTH received data
char data = 0;
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int btPin30State = 0;
int btPin31State = 0;
int btPin32State = 0;
int btPin33State = 0;
int btPin34State = 0;
int btPin35State = 0;
int btPin36State = 0;
int btPin37State = 0;
int btPin38State = 0;
int btPin39State = 0;
// declare game state variable
int gameState = 0;
void setup() {
// initialize Serial Comms for Debug (0) and BT(3)
Serial.begin(9600); //Sets the buad for Serial (debug port)
Serial3.begin(9600); //Sets the baud for Serial3 data transmission
// initialize all button pins as INPUTs
for (int x = 30; x <= 39; x++){
pinMode(x, INPUT);
}
// initialize LED pins as OUTPUTs:
for (int i = 44; i <= 53; i++){
pinMode(i, OUTPUT);
}
// lightup all LEDs
for (int j = 44; j <= 53; j++){
digitalWrite(j, HIGH);
delay(100);
}
// prompt device is ready
Serial.println("Device Ready");
}
void loop() {
// Read Data from Serial3 -- This is to get initial game status/command from app/bluetooth
if(Serial3.available() > 0) { // Send data only when you receive data:
data = Serial3.read();
// See what the command is
if(data == '1') {
Serial.write("Send it to GameOne");
Serial.write("\n");
gameOne();
}
// See what the command is
if(data == '2') {
Serial.write("Send it to GameTwo");
Serial.write("\n");
gameTwo();
}
if(data == '3') {
Serial.write("Send it to GameThree");
Serial.write("\n");
gameThree();
}
if(data == '4') {
Serial.write("Test");
Serial.write("\n");
}
}
btPin30State = digitalRead(btPin30);
btPin31State = digitalRead(btPin31);
btPin32State = digitalRead(btPin32);
btPin33State = digitalRead(btPin33);
btPin34State = digitalRead(btPin34);
btPin35State = digitalRead(btPin35);
btPin36State = digitalRead(btPin36);
btPin37State = digitalRead(btPin37);
btPin38State = digitalRead(btPin38);
btPin39State = digitalRead(btPin39);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (btPin30State == HIGH) {
digitalWrite(ledPin44, HIGH);
tone(11, 1000, 500);
Serial.println("BTN 30 / LED 44");
gameOne();
} else {
digitalWrite(ledPin44, LOW);
}
if (btPin31State == HIGH) {
digitalWrite(ledPin45, HIGH);
Serial.println("BTN 31 / LED 45");
} else {
digitalWrite(ledPin45, LOW);
}
if (btPin32State == HIGH) {
digitalWrite(ledPin46, HIGH);
Serial.println("BTN 32 / LED 46");
} else {
digitalWrite(ledPin46, LOW);
}
if (btPin33State == HIGH) {
digitalWrite(ledPin47, HIGH);
Serial.println("BTN 33 / LED 47");
} else {
digitalWrite(ledPin47, LOW);
}
if (btPin34State == HIGH) {
digitalWrite(ledPin48, HIGH);
Serial.println("BTN 34 / LED 48");
} else {
digitalWrite(ledPin48, LOW);
}
if (btPin35State == HIGH) {
digitalWrite(ledPin49, HIGH);
Serial.println("BTN 35 / LED 49");
} else {
digitalWrite(ledPin49, LOW);
}
if (btPin36State == HIGH) {
digitalWrite(ledPin50, HIGH);
Serial.println("BTN 36 / LED 50");
} else {
digitalWrite(ledPin50, LOW);
}
if (btPin37State == HIGH) {
digitalWrite(ledPin51, HIGH);
Serial.println("BTN 37 / LED 51");
} else {
digitalWrite(ledPin51, LOW);
}
if (btPin38State == HIGH) {
digitalWrite(ledPin52, HIGH);
Serial.println("BTN 38 / LED 52");
} else {
digitalWrite(ledPin52, LOW);
}
if (btPin39State == HIGH) {
digitalWrite(ledPin53, HIGH);
Serial.println("BTN 39 / LED 53");
} else {
digitalWrite(ledPin53, LOW);
}
}
I think it would be ok to structure it something like this.
play_a_game:
for (some_number_of_times)
{
show_a_mole_and_let_them_wackit();
}
setup:
set up pins
say the game is starting
loop:
do
{
play_a_game();
}
while(game ending button not pressed and less then 10 moles have died);
say the game is over
Related
I'm currently working on a mini project to have my pushbutton toggle a blinking LED, meaning: when I press the button, I want the LED to keep blinking until I press the button again.
I managed to toggle the LED without blinking (when I press the button, the LED lights up, and when I press the button again, the LED switches off, but no blinking).
I've appended my code below, and my logic is based on tracking the current button state and the previous button state, which I think is the correct logic (but if I'm wrong please criticise/correct me!!) to cause a change in LED output state, so I'm not sure what's wrong with my thinking/code. The problem I have now is that the LED will only blink twice (according to the line of code I've written in void loop) but it does not keep blinking forever until I want it to stop (what can I do to execute this?)
const int ledPin = 8;
const int buttonPin = 7;
int buttonState;
int ledState = HIGH;
int lastbuttonState = LOW;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState != lastbuttonState) {
if (ledState == HIGH) {
digitalWrite(ledPin, HIGH);
delay(200);
digitalWrite(ledPin, LOW);
delay(200);
} else {
digitalWrite(ledPin, LOW);
}
}
lastbuttonState = buttonState;
}
Will be extremely grateful if anyone can point out any mistakes!! Thank you!
The most important idea here is use the button to toggle blinkState. When the state indicate the LED should be blinking, use millis() get the current time and calculate when ledState should be toggled. When enough time has passed, calculate the next time, toggle ledState, and loop back.
Note I am using the bounce2 library to debounce the button. You could do button debouncing with timer as well.
#include <Bounce2.h>
#define LED_PIN 13
#define BUTTON_PIN 2
#define DEBOUNCE_DELAY 100
#define BLINK_DELAY 200
uint32_t nextMillis = 0;
bool blinkState = 0, ledState = 0, previousLedState = 0;
Bounce b = Bounce();
void setup() {
Serial.begin(9600);
delay(1000);
pinMode(LED_PIN, OUTPUT);
b.attach(BUTTON_PIN, INPUT_PULLUP);
b.interval(DEBOUNCE_DELAY);
}
void loop() {
b.update();
if(b.fell()){
blinkState = !blinkState;
}
if (blinkState){
if (millis() > nextMillis){
nextMillis = millis() + BLINK_DELAY;
ledState = !ledState;
}
} else {
ledState = 0;
}
//only write to pin if ledState changed
if (ledState != previousLedState){
digitalWrite(LED_PIN, ledState);
previousLedState = ledState;
}
}
This part
(buttonState != lastbuttonState)
is logically incorrect as the state of the push button will immediately become false when you press the push button once and release it. The last state of the push button would be FALSE as per the logic that you have written.
Another way could be to implement would be to increment an counter variable on pressing the push button once and start blinking when the counter value is odd and stop blinking when the counter value is even.
const int ledPin = 8;
const int buttonPin = 7;
int buttonState=HIGH,reading;
int ledState = LOW;
int lastbuttonState = HIGH,icounter;
unsigned long latchMillis,lastDebounceTime;
void setup()
{
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop()
{
unsigned long blinkdelay = 1000,debounceDelay=1;
/***Debounce logic for the input ***/
reading = digitalRead(buttonPin); //Check for the change in PB
if (reading != lastbuttonState)
{
lastDebounceTime = millis(); // reset the debouncing timer
}
lastbuttonState = reading; //Update previous button state
if ((millis()-lastDebounceTime) > debounceDelay) //If debounce has elapsed then accept the input
{
if (buttonState != lastbuttonState)
{
if (buttonState == LOW)
{
icounter = icounter +1; //Increment counter on every rising edge of PB
latchMillis = millis(); //Latch the current millis
}
buttonState = lastbuttonState;
}
}
if ((icounter%2)!= 0)
{
if ((millis() - latchMillis) > blinkdelay)
{
ledState = !ledState;
latchMillis = millis();
digitalWrite(ledPin,ledState);
}
}
else
{
digitalWrite(ledPin, LOW);
}
}
`
I'm trying to turn on the relay for 5s when I press the button(U), then turn it off. Then switch on the second one for 10 seconds and turn it off.I would like to use the millis function to control 8 relays at different time intervals.
Please correct my code.
Why doesn't it work?
(code with one relay)
#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
int ssr1 = 2;
int ssr2 = 3;
int lcd_key = 0;
int adc_key_in = 0;
#define R 0
#define U 1
#define D 2
#define L 3
#define S 4
#define N 5
unsigned long interval = 5000;
unsigned long previousMillis = 0;
int read_LCD_buttons(){
adc_key_in = analogRead(0);
if (adc_key_in > 1000) return N;
if (adc_key_in < 50) return R;
if (adc_key_in < 250) return U;
if (adc_key_in < 450) return D;
if (adc_key_in < 650) return L;
if (adc_key_in < 850) return S;
return N;
}
void setup(){
lcd.begin(16, 2);
lcd.setCursor(0,0);
lcd.print("Select:");
pinMode(3, OUTPUT);
}
void loop(){
unsigned long currentMillis = millis();
lcd.setCursor(0,1);
lcd_key = read_LCD_buttons();
switch (lcd_key){
case U:{
digitalWrite(3, HIGH);
if ((unsigned long)(currentMillis - previousMillis) >= interval){
digitalWrite(3, LOW);
previousMillis = millis();
}
lcd.print("START");
break;
}
case D:{
digitalWrite(3, LOW);
lcd.print("STOP");
break;
}
case N:{
break;
}
}
}
I suggest you check out various Arduino tutorials.
However, based on your request, I have included example code below.
Please note that this has not been tested. However, you should get an idea of the logic and adapt accordingly.
There are many other ways to achieve the same result.
int relayState = RELAY_STATE_OFF; // track state of the relay
unsigned long relayOnAt = 0; // time at which relay was turned ON
void relay(int turnOn)
{
if( turnOn == ON ) digitalWrite(3,HIGH);
else digitalWrite(3,LOW);
}
void processRelay(int operateRelay)
{
switch(relayState){
case RELAY_STATE_OFF:
if( operateRelay == 1) {
relay(ON);
relayState = RELAY_STATE_ON;
relayOnAt = millis(); // remember when the relay was turned on
}
break;
case RELAY_STATE_ON: // wait here for interval seconds to elapse
if( millis() - relayOnAt >= interval) {
relay(OFF);
relayState = RELAY_STATE_OFF; // go back to checking key input
}
break;
default:
relayState = RELAY_STATE_OFF;
break;
}
}
int operateRelay = 0;
void loop(){
lcd.setCursor(0,1);
lcd_key = read_LCD_buttons();
operateRelay = 0;
if( lcd_key == U ) {
operateRelay = 1;
}
processRelay(operateRelay);
}
I am building a program that measure the voltage of a component (photoswitch). When the potential is under 5 V, the lamp will turn on.
But my problem is, I want the Arduino to turn on the lamp, if the voltage has been under 5 V for 10 seconds or more. For example, if the voltage level is under 5 V for 8 seconds and then it changes to over 5 V again, the lamp should not turn on.
Here is my code so far:
int Pin = 2;
const float baselineVoltage = 5.0;
void setup() {
Serial.begin(9600);
pinMode(Pin,OUTPUT);
}
void loop() {
int sensorValue = analogRead(A0);
float voltage = sensorValue * (5.0 / 1023.0);
Serial.println(voltage);
if(voltage < baselineVoltage){
digitalWrite(2,HIGH);
}
delay(10);
}
I believe something like this addresses your 10 second delay issue. If you want the same 10 second delay to turn it off, you will need to do something similar.
int Pin = 2;
const float baselineVoltage = 5.0;
int belowBaselineVoltage = false;
unsigned long turnOnAt;
const unsigned long turnOnDelay = 10 * 1000;
void setup() {
Serial.begin(9600);
pinMode(Pin, OUTPUT);
}
void loop() {
int sensorValue = analogRead(A0);
float voltage = sensorValue * (5.0 / 1023.0);
Serial.println(voltage);
if (voltage < baselineVoltage)
{
if (belowBaselineVoltage == true)
{
if (millis() >= turnOnAt)
{
digitalWrite(2, HIGH);
}
}
else
{
belowBaselineVoltage = true;
turnOnAt = millis() + turnOnDelay;
}
}
else
{
belowBaselineVoltage = false;
}
}
I have a question about arduino considering a setup with 8 leds and an potentiometer. I want to let 1 led light up, which is the led that matches the value returned by the potentiometer, and the rest of the leds should be turned off. Furthermore, when I change the position of the potentiometer, the leds should change accordingly. So far ive got this:
for(int i = 0; i)
{
if (i = draaiKnopStand)
{
status[i] = HIGH;
}
else
{
status[i] = LOW;
}
digitalWrite(draaiKnopStand, status[i]);
}
I'm considering this is Arduino Uno Front
I have no Arduino here in my job. I did this using a simulator. Please try it:
int _potentiometer = 9; // Potentiometer - Analog Pin
int _val = 0;
int _borderLineVal = 0;
int ledPins[] = { 2, 3, 4, 5, 6, 7 }; // an array of pin numbers to which LEDs are attached
int pinCount = 6; // the number of pins (i.e. the length of the array)
void setup() {
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
}
}
void loop() {
_val = analogRead(_potentiometer); //reading the Potentiometer value interval: 0 - 1023
_borderLineVal = (int)(1023 / pinCount);
Serial.println(_val);
// turn all leds off
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
digitalWrite(ledPins[thisPin], LOW);
}
// turn the select led on
if(_val > 0){
_pinHigh = (int)(1023 / _borderLineVal);
digitalWrite(ledPins[_pinHigh], HIGH); // turn the pin on
}
}
I'm doing project like this http://grathio.com/2013/11/new-old-project-secret-knock-drawer-lock/ The project only process time interval between knock, and I try to add amplitude as input, if I just use the code from the link above it works fine but I want to add amplitude (loud and soft knock) as input too. But my code still have problem, it can't recognise knock and the LED acting weird. I need to recognise knock time interval and knock amplitude. Comment 'This is what I add' is the code that I add myself, but the code doesn't work. Could anyone tell me what is wrong with my code?
Below is the code:
#include <EEPROM.h>
const byte eepromValid = 123; // If the first byte in eeprom is this then the data is valid.
/*Pin definitions*/
const int programButton = 0; // Record A New Knock button.
const int ledPin = 1; // The built in LED
const int knockSensor = 1; // (Analog 1) for using the piezo as an input device. (aka knock sensor)
const int audioOut = 2; // (Digial 2) for using the peizo as an output device. (Thing that goes beep.)
const int lockPin = 3; // The pin that activates the solenoid lock.
/*Tuning constants. Changing the values below changes the behavior of the device.*/
int threshold = 3; // Minimum signal from the piezo to register as a knock. Higher = less sensitive. Typical values 1 - 10
const int rejectValue = 25; // If an individual knock is off by this percentage of a knock we don't unlock. Typical values 10-30
const int averageRejectValue = 15; // If the average timing of all the knocks is off by this percent we don't unlock. Typical values 5-20
const int knockFadeTime = 150; // Milliseconds we allow a knock to fade before we listen for another one. (Debounce timer.)
const int lockOperateTime = 2500; // Milliseconds that we operate the lock solenoid latch before releasing it.
const int maximumKnocks = 20; // Maximum number of knocks to listen for.
const int maximumAmp = 20; // This is what i add
const int ampLoud = 10; // This is what i add
const int ampSoft = 20; // This is what i add
const int knockComplete = 1200; // Longest time to wait for a knock before we assume that it's finished. (milliseconds)
byte secretCode[maximumKnocks] = {50, 25, 25, 50, 100, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Initial setup: "Shave and a Hair Cut, two bits."
byte secretAmp[maximumAmp] = {10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // This is what i add
int knockReadings[maximumKnocks]; // When someone knocks this array fills with the delays between knocks.
int ampReadings[maximumAmp]; // This is what i add
int knockSensorValue = 0; // Last reading of the knock sensor.
int amp = 0; // This is what i add
boolean programModeActive = false; // True if we're trying to program a new knock.
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(lockPin, OUTPUT);
readSecretKnock(); // Load the secret knock (if any) from EEPROM.
doorUnlock(500); // Unlock the door for a bit when we power up. For system check and to allow a way in if the key is forgotten.
delay(500); // This delay is here because the solenoid lock returning to place can otherwise trigger and inadvertent knock.
}
void loop() {
// Listen for any knock at all.
knockSensorValue = analogRead(knockSensor);
if (digitalRead(programButton) == HIGH){ // is the program button pressed?
delay(100); // Cheap debounce.
if (digitalRead(programButton) == HIGH){
if (programModeActive == false){ // If we're not in programming mode, turn it on.
programModeActive = true; // Remember we're in programming mode.
digitalWrite(ledPin, HIGH); // Turn on the red light too so the user knows we're programming.
chirp(500, 1500); // And play a tone in case the user can't see the LED.
chirp(500, 1000);
} else { // If we are in programing mode, turn it off.
programModeActive = false;
digitalWrite(ledPin, LOW);
chirp(500, 1000); // Turn off the programming LED and play a sad note.
chirp(500, 1500);
delay(500);
}
while (digitalRead(programButton) == HIGH){
delay(10); // Hang around until the button is released.
}
}
delay(250); // Another cheap debounce. Longer because releasing the button can sometimes be sensed as a knock.
}
if (knockSensorValue >= threshold){
if (programModeActive == true){ // Blink the LED when we sense a knock.
digitalWrite(ledPin, LOW);
} else {
digitalWrite(ledPin, HIGH);
}
knockDelay();
if (programModeActive == true){ // Un-blink the LED.
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
listenToSecretKnock(); // We have our first knock. Go and see what other knocks are in store...
}
}
// Records the timing of knocks.
void listenToSecretKnock(){
int i = 0;
int j = 0;
// First reset the listening array.
for (i=0; i < maximumKnocks; i++){
knockReadings[i] = 0;
}
for (j=0; j < maximumAmp; j++){ // This is what i add
ampReadings[j] = 0;
}
int currentKnockNumber = 0; // Position counter for the array.
int currentAmpNumber = 0;
int startTime = millis(); // Reference for when this knock started.
int now = millis();
do { // Listen for the next knock or wait for it to timeout.
knockSensorValue = analogRead(knockSensor);
//===========================================================================================================
if(knockSensorValue >=3 && knockSensorValue <=75){ // This is what i add
amp = ampSoft; // This is what i add
}
if(knockSensorValue >=76){ // This is what i add
amp = ampLoud; // This is what i add
}
ampReadings[currentAmpNumber] = amp; // This is what i add
currentAmpNumber++; // This is what i add
//===========================================================================================================
if (knockSensorValue >= threshold){ // Here's another knock. Save the time between knocks.
now=millis();
knockReadings[currentKnockNumber] = now - startTime;
currentKnockNumber ++;
startTime = now;
if (programModeActive==true){ // Blink the LED when we sense a knock.
digitalWrite(ledPin, LOW);
} else {
digitalWrite(ledPin, HIGH);
}
knockDelay();
if (programModeActive == true){ // Un-blink the LED.
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
now = millis();
// Stop listening if there are too many knocks or there is too much time between knocks.
} while ((now-startTime < knockComplete) && (currentKnockNumber < maximumKnocks));
//we've got our knock recorded, lets see if it's valid
if (programModeActive == false){ // Only do this if we're not recording a new knock.
if (validateKnock() == true){
doorUnlock(lockOperateTime);
} else {
// knock is invalid. Blink the LED as a warning to others.
for (i=0; i < 4; i++){
digitalWrite(ledPin, HIGH);
delay(50);
digitalWrite(ledPin, LOW);
delay(50);
}
}
} else { // If we're in programming mode we still validate the lock because it makes some numbers we need, we just don't do anything with the return.
validateKnock();
}
}
// Unlocks the door.
void doorUnlock(int delayTime){
digitalWrite(ledPin, HIGH);
digitalWrite(lockPin, HIGH);
delay(delayTime);
digitalWrite(lockPin, LOW);
digitalWrite(ledPin, LOW);
delay(500); // This delay is here because releasing the latch can cause a vibration that will be sensed as a knock.
}
// Checks to see 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 currentAmpCount = 0; // This is what i add
int secretAmpCount = 0; // This is what i add
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){
secretKnockCount++;
}
if (ampReadings[i] > 0){ // This is what i add
currentAmpCount++; // This is what i add
}
if (secretAmp[i] > 0){ // This is what i add
secretAmpCount++; // This is what i add
}
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 (programModeActive == true){
for (i=0; i < maximumKnocks; i++){ // Normalize the time between knocks. (the longest time = 100)
secretCode[i] = map(knockReadings[i], 0, maxKnockInterval, 0, 100);
}
for (int j = 0; j < maximumAmp; j++){
secretAmp[j] = ampReadings[j];
}
saveSecretKnock(); // save the result to EEPROM
programModeActive = false;
playbackKnock(maxKnockInterval);
return false;
}
if (currentKnockCount != secretKnockCount && currentAmpCount != secretAmpCount){ // Easiest check first. If the number of knocks is wrong, don't unlock. // This is what i add
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++){ // Normalize the times
knockReadings[i]= map(knockReadings[i], 0, maxKnockInterval, 0, 100);
timeDiff = abs(knockReadings[i] - secretCode[i]);
if (timeDiff > rejectValue){ // Individual value too far out of whack. No access for this knock!
return false;
}
totaltimeDifferences += timeDiff;
}
// It can also fail if the whole thing is too inaccurate.
if (totaltimeDifferences / secretKnockCount > averageRejectValue){
return false;
}
return true;
}
// reads the secret knock from EEPROM. (if any.)
void readSecretKnock(){
byte reading;
int i;
int j;
reading = EEPROM.read(0);
if (reading == eepromValid){ // only read EEPROM if the signature byte is correct.
for (int i=0; i < maximumKnocks ;i++){
secretCode[i] = EEPROM.read(i+1);
}
for (int j=0; j < maximumAmp ;j++){ // This is what i add
secretAmp[j] = EEPROM.read(j+1); // This is what i add
}
}
}
//saves a new pattern too eeprom
void saveSecretKnock(){
EEPROM.write(0, 0); // clear out the signature. That way we know if we didn't finish the write successfully.
for (int i=0; i < maximumKnocks; i++){
EEPROM.write(i+1, secretCode[i]);
EEPROM.write(i+1, secretAmp[i]); // This is what i add
}
EEPROM.write(0, eepromValid); // all good. Write the signature so we'll know it's all good.
}
// Plays back the pattern of the knock in blinks and beeps
void playbackKnock(int maxKnockInterval){
digitalWrite(ledPin, LOW);
delay(1000);
digitalWrite(ledPin, HIGH);
chirp(200, 1800);
for (int i = 0; i < maximumKnocks ; i++){
digitalWrite(ledPin, 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(ledPin, HIGH);
chirp(200, 1800);
}
}
digitalWrite(ledPin, LOW);
}
// Deals with the knock delay thingy.
void knockDelay(){
int itterations = (knockFadeTime / 20); // Wait for the peak to dissipate before listening to next one.
for (int i=0; i < itterations; i++){
delay(10);
analogRead(knockSensor); // This is done in an attempt to defuse the analog sensor's capacitor that will give false readings on high impedance sensors.
delay(10);
}
}
// Plays a non-musical tone on the piezo.
// playTime = milliseconds to play the tone
// delayTime = time in microseconds between ticks. (smaller=higher pitch tone.)
void chirp(int playTime, int delayTime){
long loopTime = (playTime * 1000L) / delayTime;
pinMode(audioOut, OUTPUT);
for(int i=0; i < loopTime; i++){
digitalWrite(audioOut, HIGH);
delayMicroseconds(delayTime);
digitalWrite(audioOut, LOW);
}
pinMode(audioOut, INPUT);
}
I'm guessing that you are wanting to record the knock pattern and knock volume at the same time. So that a similar pattern with softer or louder knocks will not activate the lock. If this is the case, I would suggest that you make the array mySecretKnock a 2 dimensional array.
Then use two variables to record the analog and digital inputs.
Capture them one after the other in the same control structure.
i.e. If the value of one is high enough to trigger the if statement just record the value of the other one on the next line of code.
Keep in mind that the analog input will be lower if processed after the digital one, so you may have to adjust your threshold numbers