Определение изменения положения кнопки
Как только у вас появится работающая , вам часто захочется делать что-нибудь, основанное на количестве нажатий на кнопку. Чтобы сделать это, вам нужно знать, когда кнопка меняет свое состояние с выключенного положения на включенное (off-on), и посчитать, сколько раз это состояние изменялось. Это называется определением изменения положения кнопки или определением края.
Подключаем три провода к плате Arduino. Первый идет от одной ножки кнопки через резистор со спуском (в нашем случае 10 КОм) к земле. Второй идет от соответствующей ножки кнопки на 5 B. Третий соединяется с цифровым входом/выходом в данном случае 2-го pin-а, который читает положение кнопки (on или off).
Когда кнопка открыта (т.е. не нажата) — это означает, что между двумя ножками кнопки нет электрической связи, таким образом пин заземлен, (через резистор со спуском), и мы читаем низкое. Когда кнопка закрыта (нажата), происходит соединение между двумя ножками, соединяя пин с напряжением, так, что мы читаем высокое (пин все еще заземлен, но резистор сопротивляется потоку, таким образом путь минимального сопротивления идет к +5 В.)
Если вы отсоедините от всего цифровой входной/выходной пин, светодиод может начать беспорядочно мигать. Это потому, что вход «плавает» — то есть либо не подключен к напряжению, либо не заземлен. Из-за этого будет беспорядочно прыгать с высокого на низкий и наоборот. Именно поэтому вам нужен резистор со спуском в цепи.
Схема:
Нижеприведенный код непрерывно читает положение кнопки на данный момент. Затем сравнивается положение кнопки с предыдущим положением с помощью главного цикла. Если текущее положение кнопки отличается от предыдущего положения, и текущее положение кнопки высокое, то кнопка изменяется с выключенного на включенное. А программа после этого увеличивает в счетчике количество нажатий на кнопку.
Код:
/*
State change detection (edge detection)
Often, you don't need to know the state of a digital input all the time,
but you just need to know when the input changes from one state to another.
For example, you want to know when a button goes from OFF to ON. This is called
state change detection, or edge detection.
This example shows how to detect when a button or button changes from off to on
and on to off.
The circuit:
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
* LED attached from pin 13 to ground (or use the built-in LED on
most Arduino boards)
created 27 Sep 2005
modified 17 Jun 2009
by Tom Igoe
http://arduino.cc/en/Tutorial/ButtonStateChange
*/
// this constant won't change:
const int buttonPin = 2; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to
// Variables will change:
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter, DEC);
}
else {
// if the current state is LOW then the button
// wend from on to off:
Serial.println("off");
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
}
// turns on the LED every four button pushes by
// checking the modulo of the button push counter.
// the modulo function gives you the remainder of
// the division of two numbers:
if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
комментарии(0)
Комментировать