MitchSF:
Hi All,
I want to write a function that will bring a pin high or low based on the pattern passed to it periodically, for example:
void toggle(111001, 3)
Calling this every 10ms will keep a pin high for 30ms, then low for 20ms, then high again for 10ms. The pattern will repeat three times based on the second parameter. Would it be more efficient to do this using binary numbers and bit shifting? Please give me ideas on how best to code this. It should be coded to run as efficiently as possible.
Thanks in advance.
@MitchSF,
your approach is memory efficient, but it adds programming complexity, solving for the number of bits that will lite if the sequence is less than 8. to show you, refer to the example below. But, your method can be extended (efficiently) if sequences are longer than 8 bits.
In the example I included a byte array as another means to solve the problem, not as efficient from a memory use perspective, but less lines of code.
(I was able to compile but not able to test)
const byte ledPin = 13;
int num_times = 3;
byte myArray[] = {1,1,1,0,0,1};
void setup()
{
pinMode(ledPin, OUTPUT);
}
void loop()
{
while(num_times) toggle(B00100111, num_times); // notice i reversed the order of your byte
//while(num_times) arrayToggle(myArray, sizeof(myArray)/sizeof(myArray[0]), num_times);
}
void toggle(byte myBitMask, int ×)
{
if (times == 0) return;
byte magnitude = 0;
for(byte i = 0; i < 8; i++) // locate most significant byte
{
if(bitRead(myBitMask,i))
magnitude = i;
}
for (int i = 0; i <= magnitude; i++) // only process up to most significant byte
{
digitalWrite(ledPin, bitRead(myBitMask,i));
delay(10);
}
digitalWrite(ledPin, LOW);
times--;
}
void arrayToggle(byte *array, size_t arraySize, int ×)
{
if (times == 0) return;
for (byte i = 0; i < arraySize; i++)
{
digitalWrite(ledPin, array[i]);
delay(10);
}
digitalWrite(ledPin, LOW);
times--;
}