Бұл, шамасы, біршама жетілдірілген, бірақ ...
Циклдік функцияны циклге дейін азайту үшін негізгі сынып пен көрсеткіштерді алынған LED және Buzzer сыныптарына пайдалануға болады. Сіз осы деңгейде көп нәрсе таба алмайсыз, бірақ сіз жыпылықтайтын фаралар мен айна шамдар сияқты қосымша нысандарды қосқанда, тіпті артқы жағына қарап тұрған хабар тақтасы өзіңіздің өміріңізді оңайырақ етеді.
/*
Jacob & Dad’s Police Car light and sounds
*/
class BaseOutputObject
{
protected:
int Pin;
public:
BaseOutputObject(const int& pin)
: Pin(pin)
{
pinMode(Pin, OUTPUT);
}
virtual void Update()
{
}
};
class FlashingLED : public BaseOutputObject
{
long OnTime;
long OffTime;
int ledState;
unsigned long previousMillis;
public:
FlashingLED(const int& pin, const long& on, const long& off, const bool& startLow = true)
: BaseOutputObject(pin) //Call base class constructor
, OnTime(on) //Use initialisers rather than assignments
, OffTime(off)
, ledState(startLow ? LOW : HIGH)
, previousMillis(0)
{
}
void Update()
{
//check to see if it's time to change the state of the LED
const unsigned long currentMillis = millis(); //Make it const because it won't change within this call of the function.
if (currentMillis - previousMillis >= OnTime)
{
ledState = (ledState == LOW ? HIGH : LOW); //Toggle the state.
previousMillis = currentMillis; //Remember the time
digitalWrite(Pin, ledState); //Update the actual LED
}
}
};
class Buzzer : public BaseOutputObject
{
float SinValue;
int ToneValue;
public:
Buzzer(const int& pin)
: BaseOutputObject(pin)
, SinValue(0.0f) //Always initialise variables, in case you change the code later.
, ToneValue(0)
{
}
void Update()
{
for (int x = 0; x < 360; x++)
{
SinValue = sin(x * (PI/180));
ToneValue = 2000 + SinValue * 500;
tone(Pin, ToneValue);
delay(1);
}
}
};
// The objects could be declared dynamically, but thats not a great idea on embedded systems.
FlashingLED ledOne(5, 100, 400);
FlashingLED ledTwo(7, 100, 400);
Buzzer buzzer(9);
enum { LED_ONE, LED_TWO, BUZZER, MaxObjects };
// Have to have pointers to the objects to allow you to cast them down to the base objects.
BaseOutputObject* objects[MaxObjects] = { &ledOne, &ledTwo, &buzzer};
void setup()
{
}
void loop()
{
for (int index = 0; index < MaxObjects; ++index)
{
objects[index]->Update();
}
}