Electronic – ATtiny85 to control a relay, which will turn on and off a motor

attinylithium ionmotorrelay

I am trying trying to control a 5V relay (SRD-05VDC-SL-C) with the ATtiny85. I have a simple sketch uploaded (Blink without Delay example):

const int ledPin =  0;      // the number of the LED pin
int ledState = LOW;             // ledState used to set the LED
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  pinMode(ledPin, OUTPUT);      
}

void loop()
{
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;   

    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    digitalWrite(ledPin, ledState);
  }
}

The whole thing is being powered by an 18650 Li-Ion battery (3.7V-4.2V) and the measured input is averaging 3.88V. Here is a quick sketch of how the circuit looks like:
ATtiny85 motor control circuit using relay

Some issues comes up WITHOUT the motor connected:

  1. If I connect the battery and relay directly, you can hear it click, despite it being rated at 5V input.
  2. If I try to trigger the relay from Pin0, the oscilloscope will show the voltage of Pin0 to be about 2.72V, when the relay looks to be switching. If I replaced the relay with an LED, the voltage of Pin0 is about 3.88V. What causes the drop in voltage? I believe the current should be enough since it's an Li-Ion battery.
  3. What sort of protection do I need to implement in this circuit?
  4. Will the Li-Ion battery be enough to power this circuit? If I connect just battery, relay, and motor, it runs fine. The issue comes with the addition of the ATtiny85.

Best Answer

You should not really drive the relay coil directly from the microcontroller pin.

Instead, I would recommend using an NPN transistor between GND (emitter) and the coil (collector), then connect the other side of the coil to the positive supply directly.

Connect a diode backwards in parallel to the coil (i.e. diode cathode to positive supply, diode anode to transistor collector). This is a "fly-back" diode to protect against the back-EMF you get with the coil switches.

Put something like a 330 ohm resistor in series between the transistor base and the microcontroller pin. This limits the current into the base of the transistor to a level that is within the capabilities of the microcontroller.

That's the most common way I know of to control a relay with a GPIO pin of a micrcontroller.

enter image description here