本帖最后由 panda 于 2011-12-18 09:51 编辑
今天收到了买的元件立刻尝试做了用按键开关灯的实验。
代码如下-
- /*
- Panda Learning Arduino
- Exp:02
- Date:2011-12-15
- Program: Test the LED on UNO board.
- */
- //define const
- #define LED 13 //setting the LED on the PIN 13
- #define BUTTON 7 //setting the Botton input from the PIN 7
- #define SHORT 100 //setting the short delay is 100ms
- #define LONG 200 //setting the long delay is 200ms
- //Define Variable
- boolean ledStat = false; //save the led stat
- //setup
- void setup() {
- pinMode(LED,OUTPUT);
- pinMode(BUTTON,INPUT);
- }
- //function: the LED flashing
- void ledFlash() {
- digitalWrite(LED,HIGH);
- delay(LONG);
- digitalWrite(LED,LOW);
- delay(SHORT);
- }
- //function: the LED flashing return the button action
- void ledChecking(boolean f) {
- switch (f) {
- case 0:
- for(int i=0;i<=2;i++) ledFlash(); // close LED
- break;
- case 1:
- for(int i=0;i<=3;i++) ledFlash(); // open LED
- break;
- }
- }
- //main
- void loop() {
- if(digitalRead(BUTTON)==HIGH) {
- delay(10);
- if(digitalRead(BUTTON) == LOW) {
- ledStat = (!ledStat);
- ledChecking(ledStat);
- digitalWrite(LED,ledStat);
- }
- }
- }
复制代码 一开始的时候始终不行,后来请教了叫兽,才知道电路接的有问题,我只接了从 5V ---- button ---- pin7, 这样按键下去 pin7 会有5v, 原先想的是不按就没有了。叫兽说这样板子会读不到pin7,然后就开始随便给值,所谓的抽风。 于是改为现在的接法, ok了。
程序内部用了下降沿触发。
另外 自己搞了个让led闪的函数,呵呵,开灯闪三下,灭灯闪两下。
|