Saturday, October 19, 2019

0000 0000 0001 0001

Attiny13 microcontroller

A little divergence here because it is important to point out that a lot of the logic chips and other components used so far in this blog can easily be replaced by a simple microcontroller. Take for example the CD4017 featured in a previous blog as a clap switch circuit.

Here it the circuit repeated but with the Attiny13 doing the work.





The CD4017 comes in to Aus at around 11c each and the Attiny13 at around 40c each. However the Attiny13 has a great deal of flexibility and in fact programming it to "listen" to sound and then react accordingly is quite straight forward.


#define ledPin PB0
#define TINY_ADC_PB4 0x02
int sensorValue = 0;
int background = 0;
boolean lightup = false;
int sensitivity = 50;     // adjust up for less sensitivity

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(TINY_ADC_PB4, INPUT);
  delay(50);
  // take 5 readings and average for background noise
  for (byte i = 0; i < 5; i++) {
    digitalWrite(ledPin, HIGH);
    background = background + analogRead(TINY_ADC_PB4);
    delay(100);
    digitalWrite(ledPin, LOW);
    delay(100);
  }
  background = background / 5;
}

void loop() {

  sensorValue = analogRead(TINY_ADC_PB4);       // take initial reading
  sensorValue = abs(background - sensorValue);  // adjust for background noise

  if (sensorValue > sensitivity) {              // did I hear a clap?

    if (!lightup) {
      lightup = true;
      digitalWrite(ledPin, HIGH);
    }
    else {
      lightup = false;
      digitalWrite(ledPin, LOW);
    }
    delay(50);
  }
  delay(50);
}


Another great advantage of most of these types of microcontroller is that they can be put to sleep and have very little power requirements until required (e.g. woken up with a sensor). That makes them great for battery driven or solar powered projects where energy consumption is an important consideration for design.

One criticism of the Attiny13 microcontroller is lack of memory (only 1k flash!) for larger projects but if you can learn some assembler along with your c-style arduino code, then you can squeeze an awful lot of instructions into it's "tiny", but very capable, brain. Also, I have been known to scale up to the Attiny85 (four times the capacity) or the Atmega series if more features and/or GPIOs are required.

More often than not a combination of parts are required for a particular application, but in general I do reach for a microcontroller first.


No comments:

Post a Comment