Skip to content

Instantly share code, notes, and snippets.

@pondahai
Created March 25, 2019 05:31
Show Gist options
  • Save pondahai/61813e185e10d7c55895407259f9863f to your computer and use it in GitHub Desktop.
Save pondahai/61813e185e10d7c55895407259f9863f to your computer and use it in GitHub Desktop.
/*
----------------------- pin 9
|
|
\
/
\ 100 ohm
/
|
| \ |
+---------| >|---------- GND
| / |
| LED
pinA0
0823
關掉通訊monotor之後會造成蠟燭自動明滅,推斷是因為serial關掉後迴圈變快,讓變化率跑偏
*/
#define BUFFER_SIZE 5
int CANDLE_PIN = 9;
long data_array[BUFFER_SIZE];
int array_index=0;
long max,min;
int steady_count=0;
int steady=0;
long now_value,last_value;
int holdtime = 0;
int candle_pwm = 255;
long sensorValue = 0;
void setup() {
pinMode(CANDLE_PIN,OUTPUT);
Serial.begin(9600);
analogWrite(CANDLE_PIN,0);
}
void loop() {
sensorValue = 0;
// sum adc value
for(int i=0;i<1024;i++){
sensorValue += analogRead(A0);
}
// save value in array
data_array[array_index] = sensorValue;
if (array_index < BUFFER_SIZE-1) array_index++;
else array_index = 0;
// find max
max = 0;
for(int i; i<BUFFER_SIZE ;i++){
if (data_array[i] > max) max = data_array[i];
}
// find min
min = 9999999;
for(int i; i<BUFFER_SIZE ;i++){
if (data_array[i] < min) min = data_array[i];
}
now_value = ((array_index - 1) < 0)?data_array[BUFFER_SIZE-1]:data_array[(array_index - 1)];
last_value = data_array[array_index];
/*
if(((max - min) < 30000)){
if (((now_value - last_value) > 1000) ) {
if ( candle_pwm > 50)candle_pwm-=50;
}else if(((now_value - last_value) > 300) ) {
if ( candle_pwm > 20) candle_pwm-=10;
//analogWrite(CANDLE_PIN, candle_pwm);
holdtime = 20;
}else {
if (candle_pwm < 250) candle_pwm+=5;
if (holdtime > 0) holdtime--;
if (holdtime == 0) {
candle_pwm = 255;
//analogWrite(CANDLE_PIN, candle_pwm);
}
}
analogWrite(CANDLE_PIN, candle_pwm);
}
*/
if((candle_pwm == 255) && ((now_value - last_value) > 1000) && (last_value > 620000)) candle_pwm = 0, holdtime = 20;
if(holdtime > 0) holdtime--;
if (candle_pwm <= 240 && holdtime == 0) candle_pwm+=15;
analogWrite(CANDLE_PIN, candle_pwm);
/*
if (steady == 1){
if ((max - min) > 100) digitalWrite(A1, LOW);
steady_count--;
if(steady_count == 0){
steady = 0;
digitalWrite(A1, HIGH);
}
}else{
if ( (max - min) < 100) steady_count++;
if (steady_count > 50) steady = 1;
}
*/
Serial.println(sensorValue);
// Serial.println(max-min);
Serial.println((now_value - last_value));
Serial.println(candle_pwm);
Serial.println(holdtime);
Serial.println();
delay(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment