قالب وردپرس درنا توس
Home / Tips and Tricks / A Hackers Guide to Programming Microcontrollers «Zero Byte :: WonderHowTo

A Hackers Guide to Programming Microcontrollers «Zero Byte :: WonderHowTo



While hackers know and love Raspberry Pi, many do not know about their cheaper cousin, microcontroller. Unlike a Pi, which can be used more or less like a regular computer, microcontrollers like the Wi-Fi connected ESP8266 require some necessary programming skills to master. In this guide, we will build an Arduino program from the beginning and explain the code structure in a way everyone can understand.

Raspberry Pi vs ESP8266

Raspberry Pi is a small, one-step computer that was first created in the UK in 2012 that changed how people thought about what a computer might be. With a massive group of loyal fans and excellent documentation, part of Pi's magic is so easy to get started. Aside from the Raspberry Pi's unusual appearance compared to a traditional computer, it works more or less like most computers you have used before.

The significant difference between a Raspberry Pi and a full blown computer is mostly in the ARM processor using the Raspberry Pi. Apart from that, Pi will start an operating system in the same way that most computers are expected. Operating systems such as Windows, Linux and MacOS provide intuitive interfaces for people to interact in real time, and this is one of the things that set up MCUs.

Instead of charging an operating system, MCUs get the right to business. The code we write for Arduino is loaded directly on the device and runs every time we turn it on. We write a code that says that microcontrollers should do something and then load these instructions on the device with a program like Arduino IDE. It may seem more restrictive than having a full operating system at your disposal, but microcontrollers can do some pretty amazing things smartly.

ESP8266 can be controlled via a web interface or mobile application to make it easy to manipulate, enabling a fine GUI interface even on a non-screen device. Microcontrollers allow a hacker to decide what they need the device to do, write down the instructions and have a working prototype in no time.

Code structure in Arduino

Unlike just writing a Python program, write code For microcontrollers, we need to learn some new rules. The first is how this code is structured, which means that we can use a simple device to do relatively complicated things. Because we don't have an operating system to do things for us, we have to do some things that an operating system usually takes care of.

First, we use the Arduino programming language which is almost identical to C ++ in the way it works. This means that we must explicitly specify variables that we will later use in our code and run some other functions to configure the hardware pins for input or output. To do this, we will include a section just to declare variables that we need to use later.

Then we can separate our code into two different main types. The first type is code that only runs once, which usually puts the pins in the right position and takes care of other one-time tasks. The other is code that will run repeatedly, which is used to determine how microcontrollers will react to their environment.

Setting function

Code intended to be run only once will often take care of critical installation functions such as ensuring that any pins you use are set to the correct position. How we do this we use what is called an empty function, which means a function that does not return anything specifically. Usually, when we call a function, we expect some value in response. Instead, this feature will be responsible for posting things that we will rely on later.

To create the idle function, we add a () at the end of "setup" to indicate that it is a function. Then we use a { symbol to tell the program that we start the instructions we want to run during the installation, and a } symbol to tell the program when the setup feature is done. Between these two symbols we can add any code we want to run the first time.

In this example, I set pin 4 to the initial position using the setting error function.

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

What the instructions say here is that during installation we want to set the position of pin 4 for output. Once we've done that, we can decide what we want to do with that needle in the loop section of our code.

Loop Function

The loop function is where the primary logic of your code will live. This is all that needs to be run all the time, like checking a sensor, running a pattern over and over or waiting for a specific trigger. Because of how fast a microcontroller works, the loop function can be performed many times per second, depending on how much it does.

The loop function is similar to the setting function, since they are both empty functions designed to keep the logic of your code. The formatting will be the same, but allow us to call functions or change the output to pins that we defined earlier based on conditions that we put in the loop.

In the example below, we turn on and off an LED, which would only be possible if pin 4 had previously been set to the initial position in our setup () function.

  void () {
digitalWrite (4, HIGH);
digitalWrite (4, LOW);
} 

If we want to define a function and call it later in the loop, we can easily do it. To create a function that flashes an LED on and off in a particular pattern, we can write a function called blink () that contains the instructions and then dial flashes () when we discover a sensor that is connected to an input pin that is triggered. Although the flash () function is defined at the beginning of the code and not in the loop, it can be called in the loop function at any time.

Features, Pin Modes & Delays

One of the best and The most exciting parts of using microcontrollers is to add input and output devices. By connecting hardware to the pins in our Arduino unit, we can control LEDs, read sensors and combine them into two useful ways. A perfect example would be to create a simple motion alarm by setting a pin to be input to read the status of a motion sensor and setting a pin to eject to allow a buzzer when we detect nearby motion.

To do this, you need to use features. Features let us pack code as we drive more than once to easy to recycle blocks. Some features are built into Arduino, and some we need to create ourselves. To use hardware lift we use built-in functions to determine if we want the pins to function as input or output pins. Doing so is easy, because we need to tell the function the number of the pin we want to control and which mode we want to switch to.

Another thing to remember when programming microcontrollers is delays. Microcontrollers work incredibly fast, and without delays it can be difficult for people to see what happens. We will examine an example of this today when you turn an LED on and off. In the code below, we try to flash an LED on and off, but there is a mistake that may not be obvious.

  digitalWrite (4, HIGH);
delay (1000);
digitalWrite (4, LOW); 

If we were to run this code to turn on an LED connected to pin 4, the LED would appear to light continuously, even though we say it should turn on, stop for one second, and then turn off. Why?

Due to the speed of the microcontroller, the LED lights up only a small part of a second. Without adding a second delay to tell the program how long we want the LED lamp to stay, the LED will remain forever. Delays are critical to working with microcontrollers, and we should train with them today while we write our code.

It may seem like a lot, but we should start with something simple so we can see how all moving pieces work. To start, we create some code to control an LED, although this can also control an output as a laser module or piezo converter.

What you need

To follow you just need a few basic materials. The setting is very flexible.

First you need a bread board ( Amazon) to connect everything. You can either get a cheap $ 1 to $ 10 breadboard (Alibaba | Sparkfun) that you need to plug into a microcontroller or a nicer $ 45 STEMTRADE breadboard (Amazon | Sparkfun) that lets you use an integrated Arduino for easy programming. If you have low money or plan to work with microcontrollers who need Wi-Fi, grab cheap breadboard.

If you didn't get a STEMTera card, you need a microcontroller. While many use devices like an Arduino Uno (Amazon), I like ESP8266-based devices (Amazon). Like a Raspberry Pi, these MCUs have a large group of enthusiastic developers, making troubleshooting much easier. When selecting a device, I recommend using a NodeMCU (Amazon) or a D1 Mini (Amazon).

NodeMCU is available in several different versions. The least useful is a NodeMCU v3 (Alibaba | Amazon), which has an extremely inconvenient width for use with a bread board. NodeMCU v1, sometimes called V2 (Alibaba | Amazon), is slim and fits easily on a bread board, so be sure to buy v1 rather than the space black v3 that doesn't give you space to connect anything else. [19659036] A Hackers Guide to Programming Microcontrollers ” width=”532″ height=”532″ style=”max-width:532px;height:auto;”/>

A visual guide to various versions of NodeMCUs. Picture of Spacehuhn / GitHub

The second difference is in the UART chip, which allows you to connect to the device with a Micro-USB cable (Amazon). Cheaper devices use the CH340 chip to do so, requiring you to download and install additional drivers to use. These boards are useful as they can also be connected to Wi-Fi. If Bluetooth is more your thing, ESP32 cards (Alibaba | Amazon) have Wi-Fi, Bluetooth and can be programmed in the same way, but are more expensive as a result.

Keep in mind that some of these boards are not supplied with soldered solder. If you get a cheap D1 Mini or ESP32 board, you can expect to braze the pins on yourself. If you don't want it, NodeMCU can be a better choice to start.

When we have our microcontroller and breadboard, we need jumper wires (Amazon). If you stop getting a bread board, maybe it already comes with jumpers. We also need between one and three pairs of resistors and LEDs (Amazon). It would be a resistor per LED because we didn't burn out our LED prematurely, but if you use a microcontroller running on 3.3-volt logic like ESP8266, it's less worrying. A STEMTera control runs on 5-volt logic, so it's more important to work with it or other 5-volt devices.

For resistance, you can use a resistor with a value between 220 and 330 ohms. A higher amount of resistance makes your LED dimmer, while a lower value makes it lighter but dies faster. You can decide how bright you want your LED to be against how long you want it to live to determine which one is right for you.

There are packages you can buy (Amazon) that contains everything (and more) you should

Kit with everything but MCU: Emakefun Electronics Component Fun Kit

Step 1: Connect your hardware [19659003] To begin with, we need to control a single LED, and later we can connect more to start doing several things at once. The basic setting will be to connect the digital pin that we want to control to an LED through a resistor, and then attach the other pin on the LED lamp to the base of our microcontroller.

If you are using a microcontroller such as D1 mini or NodeMCU, insert it into your breadboard and connect a cable to pin D3.

Picture of Kody / Null Byte

Now put the resistor on the breadboard. Keep in mind that each numbered row is connected electronically, with one part separating each side down the middle of the bread board. Connect the cable from the D1 pin to the same line that the resistor is connected to. On your LED, look for a leg that is longer than the other – it should be the positive light of the LED lamp.

Picture of Kody / Null Byte

Plug the LED of the LED lamp into the same row as the other side of the resistor and then connect the remaining leg of the LED lamp and a second wire in the same line. Finally, connect the new wire end to the ground pin, which forms a path for the current to flow from pin D1 to the resistor, to the LED lamp and back to the ground pins.

Step 2: Download and install Arduino IDE [19659003] We use the free and overlapping platform ] Arduino IDE, which allows us to quickly prototypes what we need. Arduino IDE (IDE stands for "Integrated Development Environment") lets you quickly write and upload scripts to Arduino-like microcontroller devices.

You can download Arduino IDE from the official website. If you use a STEM card, the correct card should already be in Arduino. Under the menu "Tools" you can select "Arduino / Genuino Uno" in the drop-down menu to select the right board.

If you are using an ESP8266-based microcontroller, you must click on the "Arduino" menu, then select "Preferences". Then paste the following URL into the field Additional Command Administrator Addresses . When done, click "OK" to close the menu.

  http://arduino.esp8266.com/stable/package_esp8266com_index.json 

Now you need to add NodeMCU to Board Manager . Click on "Tools" and then turn over the "Board" section to see the drop-down menu. At the top, click on "Boards Manager" to open the window that allows us to add more boards. When the Boards Manager window opens, type "esp8266" in the search field. Select "esp8266" from the "ESP8266 Community," and install it.

You should be ready to program your NodeMCU at this time. Connect your breadboard to your computer, which should have the NodeMCU already connected via the Micro USB cable. When you click on "Tools" you should see the correct port automatically selected.

Select "NodeMCU 1.0" or "D1 Mini", whichever you use from the "Board" menu. If you are using a bad cable or have not installed the driver, the port may not appear, so if you do not see anything after performing the other steps, try another cable first.

Step 3: Create a blank sketch

Now that we have Arduino IDE set up, open a blank sketch. You should see something like this:

There are two main buttons at the top. The check mark compiles and checks our code for mistakes, and the right arrow presses the code on our microcontroller.

To start, we must take care of the essential parts of the code, that is, headers, variables, main and loop functions. We can make all of these easier to understand with comments, which are parts of the code we leave to explain what we do and why. The compiler ignores these parts of the code, so they are not executed, and therefore it is only for other people to help understand the code.

Although this does not seem important, you try to understand code without commenting is a nightmare. In Arduino we can leave comments about either a full line with the // marker or multiple lines with the / * symbol followed by a * / to indicate where it stops You can see some examples below.

  // This part of the code will not run
/ * Neither will this part * / But this part will
The entire line will be executed
/ *
Everything from the symbol above to the symbol below will not be performed.
* /
This line will also be performed. 

If we ran that code, only part of line 2 and lines 3 and 7 would be executed.

  // Scripts to flash an LED on pin 3
// By Kody Kinzie, Null Byte 2019 

A few lines down, we will create another comment that explains that this is our variable department. Here we set up some variables that we need to work with later. It will also make it easier for us to change things later, such as how long the LED stays on or off.

To begin, enter the pin to which our LED is connected. The mine is a white LED, so I named it wLED, but you can choose which name you remember. We must also decide, in milliseconds, how long we want the LED lamp to continue and how long we want it to remain. We choose half a second or 500 milliseconds and save it to variables called OnDelay and offDelay.

  // Variable definitions
const int wLED = 3;
int onDelay = 500;
int offDelay = 500; 

In C ++, we must finish each line with a ; (semicolon) to let the program know that we are finished with the line. After creating a constant integer (a variable that should not change) with the "const int" declaration, we can enter it to a value of 3 (or D3 if we use an ESP8266) by assigning it with = symbol.

In Arduino means = NOT equal. It is done with the symbol == instead. The only = symbol, however, is a command. In this case, you say Arduino that the value is 3, do not ask it. This can be confusing later if you try to check if a variable is equal to a value and instead order the variable to be equal to this value instead.

Step 5: Write Setting Function

Now that our variables are defined, we need to take care of the part of the code that will run once. Although we have connected pin 3 via hardware, we still haven't told Arduino what we expect it to do with it. Arduino has no idea in itself whether we want to use this pin for input, output or anything else, so we have to say this in our installation function.

We have already assigned the number of our pin to the variable "wLED", so we can use it to rotate the stick to its initial position. This is done by calling the pinMode () function and transferring the pin we want to use and the mode we want in.

  // Setting settings for activating pins

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

Here we have said that we want the wLED pin to be set in the initial position, which means that we can operate the LED lamp connected to pin 3.

Step 6: Write loop function

Now, let's write the central part of our code. Here we will include the delays we set, so that we can make the light stay on and off during periods that a human can perceive. Within the loop, we call the function digitalWrite (), which accepts the pin we want to write to, and either the value LOW or HIGH. A value of HIGH means that the LED is on, while a value of LOW means that the LED is off.

  // Loop function, which turns the LED lamp on and off.

void loop () {
digitalWrite (wLED, HIGH);
delay (onDelay);
digitalWrite (wLED, LOW);
delay (offDelay);
} 

Together, this turns on the LED first, wait for the time we set (in this case half a second), and then shut it down. The code waits another half a second before you start over and creates a flashing LED that spends the same amount of time on and off. Together, our simple code now looks like this:

  // Scripts for flashing an LED on pin 3
// By Kody Kinzie, Null Byte 2019

// Variable definitions
const int wLED = 3;
int onDelay = 500;
int offDelay = 500;

// Setting settings for activating pin modes

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

// Loop function, which turns the LED light on and off.

void loop ()
{
digitalWrite (wLED, HIGH);
delay (onDelay);
digitalWrite (wLED, LOW);
delay (offDelay);
} 

Step 7: Press code for your microcontroller

Now that we have the code together, we can click on the checkbox to look for any mistakes. If the code is compiled, we can click on the arrow icon to send the code to our microcontroller. Make sure you select it under the "port" setting. If it is not shown here and your board is connected to a Micro-USB cable, you must install the driver for the board, try another cable, or try installing the board first.

Cover photo, screenshots and GIF by Kody / Null Byte




Source link