这是我用来在mbed设备上每120秒显示一次平均温度并在按下SW2时显示以前的平均温度的代码。 当我多次按下SW2按钮时,它不会显示正确的输出。按下一次时应为先前的平均值,而在经过10s之前按下时应为“ r”。如果我再次过快按下按钮,则不会提供上面指定的所需输出。
赞赏一些有关为什么发生这种情况以及如何纠正它的指导。提前致谢。
这个程序是否也似乎没有按照预期执行的不良设计/逻辑?
#include "mbed.h"
//LM75B.h package used to obtain
//temperature readings
#include "LM75B.h"
//C12832.h package used to display
//readings on LCD
#include "C12832.h"
//temperature sensor
static LM75B temperature(D14,D15);
//display
static C12832 lcd(D11, D13, D12, D7, D10);
//Button SW2 as a interrupt
InterruptIn sw(SW2);
//Ticker object to run a function at intervals
Ticker ticker;
Ticker ticker2;
//Timer to keep track of time in seconds
Timer timer;
//volatile variable to help with ticker
volatile int actionThis=0;
//variable to check if button
//was already pressed
int pressed=0;
//assign initial temperature values
float avgTemp=temperature.temp();
float tempNow=temperature.temp();
//how often temperature should be taken
#define TEMP_FREQUENCY 10//in seconds
//how many times temperature should be taken
// to get average
#define AVG_TEMP_AFTER_N_TEMPS 12
//function to initialise temperature taking to calculate
//average temperature
void somethinghappened(void)
{
actionThis=2;
}
//second function to resolve issue
//of ticker not detaching and attaching correctly
void somethinghappened2(void)
{
actionThis=2;
}
//function to display temperature
//at button press
void theTemp(void)
{
//check if a temperature reading
//was taken
if((timer.read()<TEMP_FREQUENCY)&& pressed) {
pressed=0;
//position output on screen
lcd.locate(0,3);
//display laterst average temperature again
lcd.printf("%.2f%c\n", avgTemp,'r');
wait(3);
lcd.cls();
//stop current ticker
ticker.detach();
//start ticker2 with different frequency
//to resolve problem of ticker not correctly detaching
//and re attching to same function
ticker.attach(somethinghappened2,(TEMP_FREQUENCY+1));
} else {
pressed=1;
lcd.locate(0,3);
lcd.printf("%.2f\n", avgTemp);
wait(3);
//clear the screen
lcd.cls();
//reset timer to 0
timer.reset();
ticker.detach();
ticker.attach(somethinghappened2,(TEMP_FREQUENCY+1));
}
}
//function to get temperature at a regular
//interval and display average after certain
//time has passed
void calcAvg(void)
{
int x;
tempNow=0;
//loop to display average temperature after
//certain time period
for( x=1; x<(AVG_TEMP_AFTER_N_TEMPS+1); x++) {
tempNow=tempNow+temperature.temp();
if(x==AVG_TEMP_AFTER_N_TEMPS) {
timer.stop();
avgTemp=tempNow/x;
lcd.locate(0,3);
lcd.printf("%.2f\n", avgTemp);
wait(3);
lcd.cls();
break;
}
//sleep until called by ticker
sleep();
}
}
int main (void)
{
//timer to track time passed
timer.start();
//run function at button press
sw.rise(&theTemp);
ticker.attach(somethinghappened,TEMP_FREQUENCY);
//run infinitely
while(1) {
if(actionThis==2) {
actionThis=0;
calcAvg();
}
//sleep till called
sleep();
}
}