Skip to content

4 What is a microcontroller and how to use one

A microcontroller is an integrated circuit (IC), or chip, that you can program to do things.

An 8-pin microcontroller

It has a number of pins that you can connect stuff to. The most common pin is a pin that can be turned on and off.

​How do you turn a pin on or off?

By writing commands (or code) that you upload into the microcontroller. The command for turning a pin on or off is usually very simple, like pin.on() and pin.off().

You can upload these commands to your microcontroller, for example by connecting it to your computer via USB if your microcontroller supports it.

If you connect something to the pin, you can write commands to control the thing you’ve connected however you want. Here’s an example with an LED:

An LED connected to a microcontroller

If you want to have the light lit for 5 seconds, then turn it off, the code would be something like this:

pin.on()
time.sleep(5)
pin.off()

​ This is a very simple example. But when you know this, you can do the same for other stuff. For example, let’s say you connect a motor that can open your garage door:

hola

A motor needs a lot of current. A microcontroller pin cannot provide much current…

The solution? A transistor!

By using a transistor, the pin only needs to provide enough current to turn on the transistor. And the motor takes its current directly from its power supply.

​ Let’s say your garage door motor needs to be on for 10 seconds to open the door fully. Then the code would be something like this:

pin.on()
time.sleep(10)
pin.off()

You would probably want to have a button that you can press to open the door. And that’s also not only possible but pretty easy!

Most pins can be either an input or an output. So you just need to connect a button to a pin and configure it as input

Button and motor connected to microcontroller

Then you can add a condition for running your commands. And the code would look similar to this:

if button_pin_pressed:
pin.on()
time.sleep(10)
pin.off()

Now, the garage door opens when you push the button.

But why stop there?

Most likely you want to be able to close the door too. And maybe you want to use sensors instead of time for checking if the door is fully open/closed.

All of this is possible.

Are you starting to see how easy it would be to build circuits using these commands to control stuff instead of using a bunch of capacitors, resistors, and transistors to achieve the same?

It’s not only LEDs and motors you can connect to a pin.

Anything electrical can be controlled.

  • Your TV? Yes.
  • Your lamp? Yes.
  • Your internet router to limit your kids’ time online? Yes.
  • Whatever else you have in mind? Probably yes. ​

Last update: January 27, 2023