经常大家的程序会有需要用到定时器和中断触发的地方,Edison也支持。
功能和之前的例子相同:
1.定时器中断完成舵机的控制。
2.外部中断使按键处于被按下状态时,LED亮。
代码如下:
- #include
- #include
- #include "rgb_lcd.h"
- #include <timerOne.h>
- rgb_lcd lcd;
- Servo myservo;
- const int colorR = 255;
- const int colorG = 255;
- const int colorB = 255;
- const int thresholdvalue = 10 ; //led trun on value
- const int timerInterval = 15*1000; //15ms
- const int APinTemp = 0;
- const int APinBright = 1;
- const int APinPot = 2;
- const int DPinLed = 2;
- const int DPinServo = 3;
- const int DPinKey = 4;
- const int DPinBuzzer = 5;
- void setup()
- {
- lcd.begin(16, 2);
- lcd.setRGB(colorR, colorG, colorB);
- lcd.setCursor(0, 0);
- lcd.print("temp:");
- lcd.setCursor(6, 1);
- lcd.print("panpan2333");
- pinMode(DPinLed , OUTPUT);
- pinMode(DPinBuzzer , OUTPUT);
- pinMode(DPinKey ,INPUT);
- myservo.attach(3);
- Timer1.initialize(timerInterval);
- Timer1.attachInterrupt( autoServoControl );
- attachInterrupt(DPinKey,interruptKeyControlLed,CHANGE);
-
-
- }
- void loop()
- {
- lcd.setCursor(5, 0);
- lcd.print(getTemperature(APinTemp));
- lcd.setCursor(0, 1);
- lcd.print(getBright(APinBright));
- delay(100);
- }
- float getTemperature(int Pin)
- {
- int a;
- float temperature;
- int B = 3975; //B value of the thermistor
- float resistance;
- a = analogRead(Pin);
- resistance = (float)(1023 - a) * 10000 / a;
- temperature = 1 / (log(resistance / 10000) / B + 1 / 298.15) - 273.15;
- return temperature;
- }
- float getBright(int Pin)
- {
- float Rsensor = 0;
- int sensorValue = analogRead(Pin);
- Rsensor = (float)(1023 - sensorValue) * 10 / sensorValue;
- if (Rsensor > thresholdvalue)
- {
- //digitalWrite(DPinLed, HIGH);
- }
- else
- {
- //digitalWrite(DPinLed, LOW);
- }
- return Rsensor;
- }
- void autoServoControl()
- {
- int val = 0;
- val = analogRead(APinPot);
- val = map(val, 0, 1023, 0, 179);
- myservo.write(val);
- }
- void interruptKeyControlLed()
- {
- digitalWrite(DPinLed, !digitalRead(DPinLed));
- }
- /*********************************************************************************************************
- END FILE
- *********************************************************************************************************/
复制代码
定时器中断需要头文件:
然后需要设置一个定时间隔:
- const int timerInterval = 15*1000; //15ms
复制代码
根据这个间隔初始化定时器:
- Timer1.initialize(timerInterval);
复制代码
设置定时器时间:
- Timer1.attachInterrupt( autoServoControl );
复制代码
而定时器时间就是我的舵机控制程序:
- void autoServoControl()
- {
- int val = 0;
- val = analogRead(APinPot);
- val = map(val, 0, 1023, 0, 179);
- myservo.write(val);
- }
复制代码
按键中断只需要一步设置:
- attachInterrupt(DPinKey,interruptKeyControlLed,CHANGE);
复制代码
第一个参数是中断出发的引脚,第二个是中断函数,第三个是触发类型:
触发类型在文件中有写到~
RISING or FALLING or CHANGE 即上升沿下降沿和电平改变三种触发类型。
按键中断函数为触发取反,所以一个中断会有按下和弹回两次触发,刚好就是LED灯状态0到1到0的样子。
- void interruptKeyControlLed()
- {
- digitalWrite(DPinLed, !digitalRead(DPinLed));
- }
复制代码
|