I have a program that has many different long running sections (can be 15 mins at a time) and it uses an “IF” statement to decide what section to execute.
My problem is that I want to be able to press a button and have it move to another section immediately without having to wait for the current section to complete.
I thought I could use and external interrupt but I see the interrupt just causes the program to stop execute the interrupt code and continue running from the same place it was before the interrupt was called .
I then thought I could use the “goto” statement, but that does not work ether because the compiler complains if your label is outside of the function you are using the “goto” statement.
I have posted my code below I basically want to be able to press the button and have the code move on to the next “IF” statement no matter what it was doing when I pressed the button.
The delays are just their to simulate what the program would do.
The program is actually for a robot that has many different modes.
In mode 1 in just navigates around.
In mode 2 it can be controlled by a controller.
In mode 3 it will just sit until the PIR sensor see some thing then it will start roaming around.
So you see the robot could be in any state for any amount of time doing any thing.I want to push a button and have it stop and change modes.
Example code
volatile int state = LOW;
int mode = 0;
void setup()
{
Serial.begin(9600);
attachInterrupt(0, blink, RISING);
}
void loop()
{
Serial.println();
Serial.print("##########################");
Serial.println();
Serial.print("Start it again");
Serial.println();
Serial.print("##########################");
if(mode==0)
{Serial.println();
Serial.print("0");
Serial.println();
delay(30000);}
if(mode==1)
{Serial.println();
Serial.print("1");
Serial.println();
delay(30000);}
if(mode==2)
{Serial.println();
Serial.print("2");
Serial.println();
delay(30000);}
if(mode==3)
{Serial.println();
Serial.print("3");
Serial.println();
delay(30000);}
if(mode==4)
{Serial.println();
Serial.print("4");
Serial.println();
delay(30000);}
}
void blink()
{ delay(800); // This is just a delay to allow for the button press
if(mode >= 4)
{mode = 0;}
else{mode = ++mode ;}
}
You should structure your code so that the subroutines don't take a long time.
while(1){
switch(mode){
case 0: //one cycle of case 0
break;
case 1: //one cycle of case 1
break;
}
}
Then, in your interrupt service routine, you can set the mode.
replace all occurances of delay(3000); with a new function, which does the following 30 times: if the button has been pressed, return, otherwise, delay 100.
Related
I want to make a device like Knocki(https://knocki.com), which essentially is a relay control using a vibration sensor. i can detect vibrations rn but the problem is, once i knock the relay blinks on and then turns off. i understand this is a lack of programming that is causing this. could someone help me write code which makes it so that when i knock the relay is turned on indefinitely; until I knock again to turn relay off.
And yes u can probably tell that this code is copied from somewhere(https://wiki.keyestudio.com/Ks0068_keyestudio_37_in_1_Sensor_Kit_for_Arduino_Starters#Project_21:_Vibration_Sensor).I took it from the home page of the vibration sensor. the code was initially so that every time i knocked, the onboard Arduino led lit up. Also, right now the relay is blinking faintly every time i knock(Although correctly,in sync with my knocks)
#define SensorLED 13
#define SensorINPUT 3 //Connect the sensor to digital Pin 3 which is Interrupts 1.
unsigned char state = 0;
int Relay = 5;
void setup()
{
pinMode(SensorLED, OUTPUT);
pinMode(SensorINPUT, INPUT);
attachInterrupt(1, blink, FALLING);// Trigger the blink function when the falling edge is detected
}
void loop()
{ if(state!=0)
{
state = 0;
digitalWrite(SensorLED,HIGH);
delay(500);
digitalWrite(Relay,HIGH);
}
else
digitalWrite(SensorLED,LOW);
digitalWrite(Relay,lOW);
}
void blink()//Interrupts function
{ state++;
Yes its in your code: The (bad) example works only because there is a
digitalWrite(SensorLED,HIGH);
->>> delay(500);
a delay for 1/2 sec to keep the led on.So as a check put an other delay after the relay line and it should go on for 1/2 sec too (so the led is lit 1 sec in total)
digitalWrite(SensorLED,HIGH);
delay(500);
digitalWrite(Relay,HIGH);
delay(500);
Thats just for checking -> NEXT STEP:
Get rid of the delays (see blinkwithoutdelay example in
Arduino->File->Examples->2.Digital -> blinkwithoutdelay
and introduce a second state variable e.g.
bool relayStateOn = false;
to get an independent on/off of the relay and the led.(If thats - what I understand -what you want to do)
If you feed your relay from the board, that is not the problem. Please, check the voltage in your relay when you try to set it on, if your voltage falls down, it means that this output to your relay does not supply the necessary current.
I am trying to create a working physical simulation of a traffic light intersection. I want to listen for button readings (pedestrian buttons to turn pedestrian lights green) continuously throughout the program and want to run a different function that will handle pedestrian lights if the buttons are ever pressed during the program.
I have tried it with while loops and if conditions but it just won't work because then it would read the button input at a specific point in time when I want it to read the readings constantly throughout the program and break the loop if the condition is ever untrue (while and do-while loops only check the condition at the end of the loop when I want it to check the condition throughout the loop). I also need to get which button was pressed if that possible. Then depending on which button was pressed, I want to run a function called pedes() or pedes2().
Feel free to ask if you need any clarifications.
I have posted my original code below that I want to run constantly until a button will be pressed.
Thanks!
// If at any point in time during this code, a button is pushed, I want to run a function called
pedes() or pedes2() depending on which button is pressed.
// First set of Trafiic Lights
int redT = 13 ;
int yellowT = 12;
int greenT = 11;
// First set of Pedestrian Lights
int redP = 10;
int greenP = 9;
// Second set of Traffic Lights
int redT2 = 8;
int yellowT2 = 7;
int greenT2 = 6;
// Second set of Pedestrian Lights
int redP2 = 5;
int greenP2 = 4;
// Pedestrian Buttons
int buttonT = 3;
int buttonT2 = 2;
int buttonT3 = 1;
int buttonT4 = 0;
int buttonStateT = 0;
int buttonStateT2 = 0;
int buttonStateT3 = 0;
int buttonStateT4 = 0;
// Booleans which will handle which button was pressed
void setup() {
// First set of Trafiic Lights
pinMode(redT, OUTPUT);
pinMode(yellowT, OUTPUT);
pinMode(greenT, OUTPUT);
// First set of Pedestrian Lights
pinMode(redP, OUTPUT);
pinMode(greenP, OUTPUT);
// Second set of Traffic Lights
pinMode(redT2, OUTPUT);
pinMode(yellowT2, OUTPUT);
pinMode(greenT2, OUTPUT);
// Second set of Pedestrian Lights
pinMode(redP2, OUTPUT);
pinMode(greenP2, OUTPUT);
// Pedestrian Buttons
pinMode(buttonT, INPUT);
pinMode(buttonT2, INPUT);
pinMode(buttonT3, INPUT);
pinMode(buttonP4, INPUT);
}
void loop() {
// Resetting all the traffic lights
digitalWrite(redP, HIGH); // Turns on red pedestrian LED from 1st bunch
digitalWrite(redP2, HIGH); // Turns on red pedestrian LED from 2nd bunch
digitalWrite(yellowT, LOW); // Turns off yellow traffic LED from 1st bunch
digitalWrite(yellowT2, LOW); // Turns off yellow traffic LED from 1st bunch
digitalWrite(redT, HIGH); // Turns on red traffic LED from 1st bunch
digitalWrite(redT2, HIGH); // Turns on red traffic LED from 2nd bunch
delay(2000);
digitalWrite(redT, LOW); // Turns off red traffic LED from 1st bunch
digitalWrite(redT2, HIGH); // Turns on red traffic LED from 2nd bunch
digitalWrite(greenT, HIGH); // Turns on green traffic LED from 1st bunch
digitalWrite(greenT2, LOW); // Turns off green traffic LED from 2nd bunch
delay(10000); // Pauses program for 8 seconds
digitalWrite(greenT, LOW); // Turns off green traffic LED from 1st bunch
digitalWrite(yellowT, HIGH); // Turns on yellow traffic LED from 1st bunch
delay(3000); // Pauses program for 3 seconds
digitalWrite(yellowT, LOW); // Turns off yellow traffic LED from 1st bunch
digitalWrite(redT, HIGH); // Turns on red traffic LED from 1st bunch
delay(2000); // Pauses program for 3 seconds
digitalWrite(redT2, LOW); // Turns off red traffic LED from 2nd bunch
digitalWrite(greenT2, HIGH); // Turns on green traffic LED from 2nd bunch
delay(6000); // Pauses program for 8 seconds
digitalWrite(greenT2, LOW); // Turns off green traffic LED from 2nd bunch
digitalWrite(yellowT2, HIGH); // Turns on yellow traffic LED from 2nd bunch
delay(3000); // Pauses program for 3 seconds
digitalWrite(yellowT2, LOW); // Turns off yellow traffic LED from 2nd bunch
digitalWrite(redT2, HIGH); // Turns on red traffic LED from 2nd bunch
delay(2000); // Pauses program for 3 seconds
}
Instead of constantly polling you could use an interrupt on the button pin and set a flag or call a function from within the interrupt routine.
Also make sure to debounce the button in hardware or software.
Since you seem to be learning, here are some extra improvements you could add as an exercise:
To switch the lights you could use timer interrupts instead of delays (you could even put the mcu in sleep mode in between).
Another improvement would be to create a TrafficLight class which contains all the logic. Here is an interesting tutorial. This way you could easily create multiple objects: TrafficLight tl1(..), tl2(..); or even arrays of traffic lights (for example with the same timings).
You could then even create a class Intersection which contains all the traffic lights and the logic for that intersection.
Well if you delay for 10 seconds you cannot react to something in the meantime.
You can use millis() to implement a non-blocking delay.
https://www.arduino.cc/en/tutorial/BlinkWithoutDelay
Instead of being idle and unable to respond you spend your time with checking and responding to your button states and/or time conditions.
Avoid using delays. Delays will pause everything until the time is up, which makes everything less responsive. Delays are useful when learning how to code, but they can hinder usability if you need to react to an external sensor or button.
A better habit to get into is using timers instead of delays. This lets your code keep looping without pausing, and you can add code to check for user input more frequently.
Here is an example of what you should NOT do:
void loop() {
digitalWrite(MY_LED,HIGH);
delay(1000);
digitalWrite(MY_LED,LOW);
delay(1000);
//This code only gets reached every 2 seconds
//This means you may need to hold the button for up to
//2 seconds before it will print a message
if (digitalRead(MY_BUTTON) == LOW) {
Serial.println("You pressed the button");
}
}
You can use millis() to return the number of milliseconds since the arduino started running. Here is a basic example of a timer:
bool ledState = false;
unsigned long toggledTime = 0; //The last time we toggled the led
void loop() {
//Calculate how much time has passed since the last time
//we turned the LED on or off
unsigned long timeElapsedSinceLastToggle = millis() - toggledTime;
//If 1000ms (1s) has passed, we'll toggle the LED
if (timeElapsedSinceLastToggle > 1000) {
ledState = !ledState; //Invert the state
digitalWrite(MY_LED,ledState); //Perform the action
toggledTime = millis(); //Reset our timer to the current time
}
//This code now checks very frequently since the code above
//never uses delay()
if (digitalRead(MY_BUTTON) == LOW) {
Serial.println("You pressed the button");
}
}
I would recommend using a different timer for each LED that you want to toggle. This will make your code much more responsive, and your buttons will respond (nearly) instantly.
There is one thing you will want to be careful with regarding timers. millis() is how many milliseconds since boot, but what happens when your code runs for a very long time? millis() resets (starts over at 0) after about 50 days. For lots of people, this doesn't matter much, but it is worth keeping in mind if your code will be running indefinitely for long periods of time.
I have an arduino nano. I want to connect MX Cherry switches and detect pressing throught the serial port. What pins should i use on arduino and what code should be uploaded to the plate?
I understand that i have to power the switches so there has to be 5v pin and input pin. But i'm new to electronics so i didn't manage to figure it out.
//that's just basic code for sending a number every second via 13 pin
int i=0;
void setup() {
Serial.begin(57600);
pinMode(13, OUTPUT);
}
void loop() {
i = i + 1;
Serial.println(i);
delay(1000);
}
Basically, i need a way of sending '1' if button is pressed and '0' if it's not.
Perhaps I've misunderstood your question. Why not just read the button and send a '1' if pressed and '0' if not?
void loop(){
int buttonState = digitalRead(buttonPin);
// Assumes active low button
if (buttonState == LOW){
Serial.print('1');
}
else {
Serial.print('0');
}
delay(500);
}
Of course you probably want to add some sort of timing to that so it doesn't send thousands of 0's and 1's per second. I added a delay, but that might not be the best answer for the application you have (and chose not to share). I've also assumed that your button is wired active-LOW with a pull-up since you didn't share that either.
I am currently trying to use an Adafruit Feather 32u4 to control a 2 motors (a small remote control car) with an android app. Here's what I am using:
MitAppInventor 2 for the app, obviously the Arduino IDE for the car.
App Inventor doesn't have a pleasant way of sharing the code, but basically I get passed the pairing, and get to where its just the buttons to press. They work perfectly, making the car go forwards and backwards, left and right. The problem I have is when I unplug the feather from the computer, the time between button presses and motors moving goes to about 1.5 seconds which is definitely not okay for driving.
All the Arduino does is take in the array from the phone, which will be Status, 0, 1, 2, 3, or 4. Depending on that number it turns the motors on in the desired direction.
The code I used it just modified code from this guide
This is my Arduino IDE code:
/*********************************************************************
This is an example for our nRF51822 based Bluefruit LE modules
Pick one up today in the adafruit shop!
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
MIT license, check LICENSE for more information
All text above, and the splash screen below must be included in
any redistribution
*********************************************************************/
#include <Arduino.h>
#include <SPI.h>
#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_)
#include <SoftwareSerial.h>
#endif
#include "Adafruit_BLE.h"
#include "Adafruit_BluefruitLE_SPI.h"
#include "Adafruit_BluefruitLE_UART.h"
#include "BluefruitConfig.h"
/*=========================================================================
APPLICATION SETTINGS
FACTORYRESET_ENABLE Perform a factory reset when running this sketch
Enabling this will put your Bluefruit LE module
in a 'known good' state and clear any config
data set in previous sketches or projects, so
running this at least once is a good idea.
When deploying your project, however, you will
want to disable factory reset by setting this
value to 0. If you are making changes to your
Bluefruit LE device via AT commands, and those
changes aren't persisting across resets, this
is the reason why. Factory reset will erase
the non-volatile memory where config data is
stored, setting it back to factory default
values.
Some sketches that require you to bond to a
central device (HID mouse, keyboard, etc.)
won't work at all with this feature enabled
since the factory reset will clear all of the
bonding data stored on the chip, meaning the
central device won't be able to reconnect.
MINIMUM_FIRMWARE_VERSION Minimum firmware version to have some new features
MODE_LED_BEHAVIOUR LED activity, valid options are
"DISABLE" or "MODE" or "BLEUART" or
"HWUART" or "SPI" or "MANUAL"
-----------------------------------------------------------------------*/
#define FACTORYRESET_ENABLE 1
#define MINIMUM_FIRMWARE_VERSION "0.6.6"
#define MODE_LED_BEHAVIOUR "MODE"
/*=========================================================================*/
// Pin Configuration and Firmware Declarations
#define LED_PIN 13
const unsigned long
BLINKTIME = 100;
unsigned long
t_blink = 0L;
int
blinkState = LOW;
// Create the bluefruit object, either software serial...uncomment these lines
/*
SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);
Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,
BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);
*/
/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */
// Adafruit_BluefruitLE_UART ble(Serial1, BLUEFRUIT_UART_MODE_PIN);
/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */
Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);
/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */
//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,
// BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,
// BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);
// A small helper
void error(const __FlashStringHelper*err) {
Serial.println(err);
while (1);
}
/**************************************************************************/
/*!
#brief Sets up the HW an the BLE module (this function is called
automatically on startup)
*/
/**************************************************************************/
void setup(void)
{
pinMode(LED_PIN, OUTPUT);
while (!Serial); // required for Flora & Micro
delay(500);
Serial.begin(115600);
Serial.println(F("Adafruit Bluefruit Command Mode Example"));
Serial.println(F("---------------------------------------"));
/* Initialise the module */
Serial.print(F("Initialising the Bluefruit LE module: "));
if ( !ble.begin() )
{
error(F("Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?"));
}
Serial.println( F("OK!") );
if ( FACTORYRESET_ENABLE )
{
/* Perform a factory reset to make sure everything is in a known state */
Serial.println(F("Performing a factory reset: "));
if ( ! ble.factoryReset() ){
error(F("Couldn't factory reset"));
}
}
/* Disable command echo from Bluefruit */
ble.echo(false);
Serial.println("Requesting Bluefruit info:");
/* Print Bluefruit information */
ble.info();
Serial.println(F("Please use Adafruit Bluefruit LE app to connect in UART mode"));
Serial.println(F("Then Enter characters to send to Bluefruit"));
Serial.println();
ble.verbose(false); // debug info is a little annoying after this point!
/* Wait for connection */
while (! ble.isConnected()) {
delay(500);
}
// LED Activity command is only supported from 0.6.6
if ( ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION) )
{
// Change Mode LED Activity
Serial.println(F("******************************"));
Serial.println(F("Change LED activity to " MODE_LED_BEHAVIOUR));
ble.sendCommandCheckOK("AT+HWModeLED=" MODE_LED_BEHAVIOUR);
Serial.println(F("******************************"));
}
}
/**************************************************************************/
/*!
#brief Constantly poll for new command or response data
*/
/**************************************************************************/
void loop(void)
{
// Now Check for incoming characters from Bluefruit
ble.println("AT+BLEUARTRX");
ble.readline();
ble.waitForOK();
String BLEbuffer = ble.buffer;
if (BLEbuffer.length() && BLEbuffer.indexOf("OK") == -1)
Serial.print(F("[Recv] ")); Serial.println(BLEbuffer);
if (BLEbuffer.indexOf("Status") >= 0) {
Serial.println(F("Status Request Received"));
ble.print("AT+BLEUARTTX=");
if (t_blink) {
ble.println("BLNK");
}
else {
if (blinkState)
ble.println("ON");
else
ble.println("OFF");
}
// check response stastus
if (! ble.waitForOK() ) {
Serial.println(F("Failed to get response"));
}
ble.println("AT+BLEUARTRX");
}
else if (BLEbuffer.indexOf("0") >= 0) {
blinkState = LOW;
digitalWrite(LED_PIN, blinkState);
analogWrite(13, 0);
analogWrite(11, 0);
digitalWrite(18, LOW);
digitalWrite(19, LOW);
digitalWrite(20, LOW);
digitalWrite(21, LOW);
t_blink = 0;
ble.print("AT+BLEUARTTX=");
ble.println("OFF");
//Serial.println(F("OFF Request Received"));
ble.println("AT+BLEUARTRX");
}
else if (BLEbuffer.indexOf("1") >= 0) {
//if (!t_blink) t_blink = millis();
analogWrite(13, 100);
analogWrite(11, 100);
digitalWrite(18, HIGH);
digitalWrite(19, LOW);
digitalWrite(20, LOW);
digitalWrite(21, HIGH);
ble.print("AT+BLEUARTTX=");
ble.println("FORWARD");
//Serial.println(F("BLINK Request Received"));
ble.println("AT+BLEUARTRX");
}
else if (BLEbuffer.indexOf("2") >= 0) {
blinkState = HIGH;
digitalWrite(LED_PIN, blinkState);
analogWrite(13, 100);
analogWrite(11, 100);
digitalWrite(18, LOW);
digitalWrite(19, HIGH);
digitalWrite(20, HIGH);
digitalWrite(21, LOW);
t_blink = 0;
ble.print("AT+BLEUARTTX=");
ble.println("BACK");
//Serial.println(F("ON Request Received"));
ble.println("AT+BLEUARTRX");
}
else if (BLEbuffer.indexOf("3") >= 0) {
analogWrite(13, 100);
analogWrite(11, 100);
digitalWrite(18, HIGH);
digitalWrite(19, LOW);
digitalWrite(20, HIGH);
digitalWrite(21, LOW);
ble.print("AT+BLEUARTTX=");
ble.println("LEFT");
//Serial.println(F("BLINK Request Received"));
ble.println("AT+BLEUARTRX");
}
else if (BLEbuffer.indexOf("4") >= 0) {
//if (!t_blink) t_blink = millis();
analogWrite(13, 100);
analogWrite(11, 100);
digitalWrite(18, LOW);
digitalWrite(19, HIGH);
digitalWrite(20, LOW);
digitalWrite(21, HIGH);
ble.print("AT+BLEUARTTX=");
ble.println("RIGHT");
//Serial.println(F("BLINK Request Received"));
ble.println("AT+BLEUARTRX");
}
BLEbuffer = "";
}
All this should be doing every loop is reading in a line, picking out the character, and running the code block for that character. I don't see a reason for it to be lagging as the amount of data seems to be very minimal. Also there is little to no lag if I have it plugged in and the Serial Monitor running. As soon as I unplug it, it stays connected and everything still works except for the massive delay.
My initial thoughts were that the buffer was getting too full of "blank" commands, and that it had to process all of them before the real commands, but if that was the case then it would be lagging with the serial monitor open.
So far I have tried changing the BAUD rate to a lower number, thinking 300 was the minimum and if the problem was that the stack was getting too many commands to sort through 300 would be a tiny amount compared to the 115600 I had it at before, but this yielded no results. I have also tried cutting back the code and this seems to be the very minimum code I could use to make it still work.
I did read that it might help to apply the onSerialEvent() method, but when I try it gets stuck at:
if ( ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION) )
{
// Change Mode LED Activity
Serial.println(F("******************************"));
Serial.println(F("Change LED activity to " MODE_LED_BEHAVIOUR));
ble.sendCommandCheckOK("AT+HWModeLED=" MODE_LED_BEHAVIOUR);
Serial.println(F("******************************"));
}
Could it be that maybe its the wiring? For example, I might need a capacitor before the motors to keep them from having to "ramp up" to the power needed to actually start moving? I'm not super knowledgeable in electrical things but this was just a thought.
So the solution is very simple and I don't think it is a BLE only solution as it only has to do with the Serial commands (I.E. serial.print()). Having these commands in the code after the device is no longer connected to a computer will cause the board to not respond to them or take an extra long time trying to process them before eventually giving up (my guess as to what actually happens).
The solution is to simply comment out all the Serial commands before you upload to the device with intent to run the code without being plugged in. Or you can obviously just erase them all but it might hinder your debugging experience the next time you are trying to edit the code.
I figured instead of deleting the question, answering it with what I found out might help someone else in the future.
I need help with debounce of push button. Sometimes it send twice same string to serial link, and I don't know why. Could someone help me, where is a problem?
int reading;
int exbutton= LOW;
unsigned long ddelay= 200;
unsigned long last= 0;
void loop(){
reading= digitalRead(prkgbrake);
if (reading== HIGH && exbutton == LOW && millis() - last> ddelay){
if (brake == 0){
Serial.write("brake:1\n");
while( digitalRead(prkgbrake) == HIGH){
}
}
else{
Serial.write("brake:0\n");
while( digitalRead(prkgbrake) == HIGH){
}
}
last = millis();
}
Thank you in advance.
I hope you didn't copy this code from somewhere, some of the code doesn't make sense.
For instance, what is 'prkgbrake'? What is 'brake'? They are not declared. Why don't you have a 'setup()' function?
Nevertheless, debouncing can be achieved in many ways. I will just fix your code. That way you will understand what you did wrong.
int exbutton = LOW;
unsigned int _delay = 200;
int pushButton = 2;
void setup()
{
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
pinMode(pushButton, INPUT_PULLUP);
}
void loop()
{
while (digitalRead(pushButton) == LOW && exbutton == LOW)
{
if((millis() - last) > _delay)
{
Serial.println("Button Pressed");
while(digitalRead(pushButton) == LOW);
}
}
last = millis();
}
Explanantion: Assuming your pushbutton is connected with digital pin 2. When you use a digital pin with a button it is better to use pullup/pulldown. You can use external resistor or the internal resistor for that. The internal resistor only supports Pull-up.
To know more about pull-up/-down checkout this Arduino page. The bottom line is when you use a pin as input it acts like an antenna and can capture signals from surroundings, known as floating state. So it is better to keep the pin in a known state. If you use internal pull-up, the pin will be always HIGH. So the button configuration has to be in a way so that when it is pressed the pin should go LOW.
Pull Up Configuration
The code pinMode(pushButton, INPUT_PULLUP); enables the digital pin 2 as input with pull-up enabled.
the loop() should work like this:
1) Check if the button is pressed (i.e. if it is LOW).
2) If not update the last variable.
3) If yes then DONT update last, and enter the while loop.
4) Now keep checking if millis()-last is greater than _delay. If not it will go back to while loop and check if the button is still pressed or not. If yes then it will come back and check if millis()-last is more than _delay or not. It will continue to do so until it passed the mentioned amount of debounce delay.
5) If button get depressed (i.e. goes to HIGH) before the '_delay' time then it will update the last and will check if button is pressed or not and will start counting the delay time.
N.B. Play with the _delay variable. It will define the responsiveness of your button.