此程式碼使用TIME函數,利用呼叫副程式的方式,來達到同步,因此省去delay,避免子程式互相延遲的問題。總共有4個子程式,分別是夜光燈、底部呼吸燈與2個音樂撥放程式。程式撰寫與測試的時間差不多2天。

#include <Arduino.h>
#include <SoftwareSerial.h>
#include "Garan.h"
#include "Timer.h"

Timer t;
const int bottomSet[4]={2,4,7,12};
const int analogInPin = A0; // Analog input pin that the potentiometer is attached to
const int analogOutPin = 11; // Analog output pin that the LED is attached to
int brightness[4] = {0,64,128,192};
int fadeAmount[4] = {5,5,5,5};

#if !defined(__MSP430_CPU__)
SoftwareSerial garanSerial(8, 10); // RX, TX
#else
SoftwareSerial garanSerial(P1_4, P1_5); // RX, TX
#endif
Garan player(garanSerial);
void setup() {
pinMode(bottomSet[4],INPUT);
pinMode(3, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);
t.every(100, music,1);
t.every(100, musicSET);
t.every(random(10)*random(10), ThePwm);
t.every(1000, NightLed);
}
void loop() {
t.update();
}
//--------------------------------------------------------------------
void music()
{
player.sequencePlay(2);
player.setVolume(15);
}
void musicSET()
{
for(int i=0;i<4;i++ )
{
if (digitalRead(bottomSet[i])==HIGH)
{
switch(i)
{
case 0:
player.volumeDown();
break;
case 1:
player.volumeUp();
break;
case 2:
player.prev();
break;
case 3:
player.next();
break;
}
}
}
}
void ThePwm()
{
for (int i=0;i<4;i++){
switch (i)
{
case 0:
analogWrite(3, brightness[0]);
break;
case 1:
analogWrite(5, brightness[1]);
break;
case 2:
analogWrite(6, brightness[2]);
break;
case 3:
analogWrite(9, brightness[3]);
break;
}
brightness[i] = brightness[i] + fadeAmount[i];
if (brightness[i] <= 0 || brightness[i] >= 255) {
fadeAmount[i] = -fadeAmount[i] ;
}
}
}

void NightLed()
{
int sensorValue = analogRead(analogInPin);
if (sensorValue >=1000 ){
analogWrite(analogOutPin,255);
}
else {digitalWrite(analogOutPin,LOW); }
}

arrow
arrow
    文章標籤
    Code
    全站熱搜
    創作者介紹
    創作者 兩隻小豬 的頭像
    兩隻小豬

    **兩隻小豬**

    兩隻小豬 發表在 痞客邦 留言(0) 人氣()