タイマー2で呼び出す関数中でSerial.print(),Serial.println()が不安定になるというよりプログラムが止まる
Arduino IDE ver.1.0.5では動かない(途中で止まる)のにver.1.6.4では動くスケッチ.
loop()でコメントアウトされている1文を戻して,シリアルモニタを見ると良いです.
温度センサーと照度センサーを使用しているが,そのあたりは適宜いい感じにしてください.
環境
- Windows 8.1
- Arduino UNO
- Arduino 1.0.5 -> 動かない
- Arduino 1.6.4 -> 動く
スケッチ
#include <MsTimer2.h> enum sensor { temperature, illumination }; // 照度と温度のどちらを計測するか const int RED1 = 13; // 赤色LEDはpinNO.D13 const int YELLOW2 = 9; // 黄色LEDはpinNO.D9 const int SW = 2; // スイッチはpinNO.D2 const int LUX = A0; // 照度センサーはpinNO.A0 const int TEMP = A5; // 温度センサーはpinNO.A5 float MAX_TEMP = 0.0, MIN_TEMP = 100.0; // 計測温度の最高と最低 float MAX_LUX = 0.0, MIN_LUX = 100.0; // 計測照度の最高と最低 sensor sw = temperature; // 照度と温度のどちらを計測するか(温度から) volatile int flag = 0; // 外部割り込みの有無 void measure(); // 温度計測または照度計測 void switching(); // ここで計測素子を変更せず,割り込みがあったことだけを認知 /* 各ピンの入出力設定 */ /* シリアル通信のbps設定 */ /* タイマー割り込みの設定・開始 */ /* 外部割り込みの設定・開始 */ void setup() { pinMode(RED1, OUTPUT); pinMode(YELLOW2, OUTPUT); Serial.begin(9600); MsTimer2::set(10, measure); MsTimer2::start(); attachInterrupt(0, switching, RISING); } /* 繰り返し */ void loop() { // Serial.println("*"); } /* タイマー割り込み */ /* 温度計測または照度計測 */ /* 温度計測時には計測温度,照度計測時には計測照度 最高温度・最低温度 最高照度・最低照度 を出力 */ void measure() { if( flag ){ // 外部割り込みがあったら flag = 0; switch( sw ){ case temperature: sw = illumination; break; case illumination: sw = temperature; break; default: Serial.println("default in switching"); break; } } if( sw == temperature ){ // 温度計測 int sensorValue = analogRead(TEMP); float vo = sensorValue * (5.0 / 1024.0); float temp = (vo * 1000.0 - 600.0) / 10.0; MAX_TEMP = MAX_TEMP < temp ? temp : MAX_TEMP; MIN_TEMP = temp < MIN_TEMP ? temp : MIN_TEMP; analogWrite(YELLOW2, map(temp, MIN_TEMP, MAX_TEMP, 0, 255)); Serial.print("temp: "); Serial.println(temp); Serial.println(); } else if( sw == illumination ){ // 照度計測 int sensorValue = analogRead(LUX); float vo = sensorValue * (5.0 / 1024.0); float lux = 222 * vo; MAX_LUX = MAX_LUX < lux ? lux : MAX_LUX; MIN_LUX = lux < MIN_LUX ? lux : MIN_LUX; analogWrite(YELLOW2, map(lux, MIN_LUX, MAX_LUX, 0, 255)); Serial.print("lux: "); Serial.println(lux); Serial.println(); } Serial.print("MAX_TEMP: "); Serial.println(MAX_TEMP); Serial.print("MIN_TEMP: "); Serial.println(MIN_TEMP); Serial.print("MAX_LUX: "); Serial.println(MAX_LUX); Serial.print("MIN_LUX: "); Serial.println(MIN_LUX); } /* 外部割り込み */ /* ここで計測素子を変更せず,割り込みがあったことだけを認知 */ /* 理由: タイマー割り込み宙に外部割り込みをすると狂う可能性があるから */ void switching() { flag = 1; }