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

A Hacker Guide to Microcontroller Programming «Null Byte :: WonderHowTo



While hackers know and love the Raspberry Pi, many do not know about its cheaper cousin, the microcontroller. Unlike a Pi, which can be used more or less like a regular computer, microcontrollers such as the ESP8266 connected to Wi-Fi require some programming knowledge. In this guide, we'll create an Arduino program from scratch and explain the code structure in a way everyone can understand.

Raspberry Pi vs. ESP8266

The Raspberry Pi is a small single-board computer that was first created in the UK in 2012, which has changed the way people think about what a computer can be. With a huge community of loyal fans and excellent documentation, part of Pi's magic is how easy it is to get started. Apart from the unusual appearance of Raspberry Pi compared to a conventional PC, it works more or less like most of the computers you've used in the past.

The main difference between a Raspberry Pi and a full-fledged computer lies mainly in the ARM processor the Raspberry Pi uses. Apart from that, the Pi boots an operating system as most computers expect. Operating systems like Windows, Linux, and MacOS provide intuitive user interfaces for interacting with people in real-time, and this is one of the hallmarks of MCUs.

MCUs do not have to load an operating system, but can be used directly in companies. Code we write for the Arduino is loaded directly onto the device and executed each time it is turned on. We write a code that prompts the microcontroller to do something and then load those instructions onto the device with a program like Arduino IDE. It seems to be more restrictive than having a complete operating system, but microcontrollers can cleverly do some amazing things.

The ESP8266 can be controlled via a web interface or a mobile application to simplify manipulation. This allows for a fancy GUI interface even on a device without a screen. Microcontrollers enable a hacker to quickly decide what the device should do, write down the instructions, and have a working prototype.

Coding structure of the Arduino

In contrast to simply writing a Python program, code has to be written For microcontrollers we have to learn some new rules. The first is the way this code is structured, allowing us to use a simple device to do relatively complicated things. Since we do not have an operating system to do things for us, we have to do some things that an operating system normally does.

First, we use the Arduino programming language, which is virtually identical to C ++ as it works. This means that we must explicitly specify variables that we will use later in our code, and perform some other functions to configure the hardware pins for input or output. For this purpose, we insert a section only for declaring variables that need to be used later.

Next we can divide our code into two main types. The first type is code that runs only once. This will normally put the pins in the correct mode and do other unique tasks. The second code is executed repeatedly to decide how the microcontroller responds to its environment.

Setup Function

Code that runs only once often takes on critical setup functions such as ensuring pins you are using are set to the correct mode. The way we do this is to use a so-called void function, which is a function that returns nothing in particular. When we call a function, we usually expect a value in response. Instead, this function is responsible for setting up things we will rely on later.

To create the function to set up the void, we add () at the end of "setup" to indicate this. It is a function. We then use a { symbol to inform the program that we are starting the instructions that we want to run in setup, and a } symbol to use the program above the setup function is done to inform. Between these two symbols we can insert the code that we want to execute for the first time.

In this example, I put pin 4 into output mode with the "setup void" function.

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

The instructions here state that mode should be set from pin 4 to output during setup. Once that's done, we can decide what we want to do with this pin in the loop section of our code.

Loop function

The loop function contains the primary logic of your code. This is all that has to be done all the time, e.g. For example, checking a sensor, repeating a pattern, or waiting for a specific trigger. Because of the speed with which a microcontroller works, the loop function may be executed many times a second, depending on how much it is performing.

The looping function is similar to the setup function in that they are both empty functions to keep the logic of your code. The formatting is the same, but we can call functions or change the output to the previously defined pins, based on the conditions we set in the loop.

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

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

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

Functions, Pin Modes and Delays

One of the best and most exciting things about using microcontrollers is adding input and output devices. By connecting hardware to the pins of our Arduino device, we can control LEDs, read sensors, and combine them in a useful way. A perfect example would be to create a simple motion alert by setting a stylus as the input to read the status of a motion sensor and a stylus as the buzzer sound output when we detect nearby motion.

I have to use functions. With functions we can pack code that we execute several times in easily reusable blocks. Some features are built into Arduino, others we have to create ourselves. For using hardware pins, we use built-in functions to decide whether the pins should act as input or output pins. This is simple because we need to tell the function the number of the pin to be controlled and the desired mode.

When programming microcontrollers, delays must be noted. Microcontrollers work incredibly fast, and without delays, it can be difficult for people to see what's going on. We will examine an example today while turning an LED on and off. In the following code, we try to turn an LED on and off, but there is an error that may not be obvious.

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

If we run this code to turn on an LED connected to pin 4, the LED will light steadily, even if we say that the light should be turned on, stay on for a second and then turn it off. Why?

Due to the high speed of the microcontroller, the LED only stays off for a fraction of a second. Without adding a second delay to tell the program how long the LED should stay off, the LED seems to stay on forever. Delays are critical to working with microcontrollers, and we'll be practicing them today while writing our code.

It may seem like a lot, but we'll start with something simple so we can see how all the pieces move work. First, we create a code to control an LED, but it can also control an output, such as a laser module or a piezo buzzer.

What you need

To participate, you only need a few basic materials. The setup is very flexible.

First you need a breadboard ( Amazon) to connect everything. You can either buy a cheap $ 1 to $ 10 breadboard (Alibaba | Sparkfun) to which you need to connect a microcontroller, or a fancier $ 45 STEMTera breadboard (Amazon | Sparkfun) with an integrated breadboard Arduino can be used for easy programming. If you have little money or want to work with microcontrollers that require Wi-Fi, grab the cheap breadboard.

If you do not have a STEMTera board, you will need a microcontroller. While many people use devices like an Arduino Uno (Amazon), I like ESP8266-based devices (Amazon). Similar to a Raspberry Pi, these MCUs have a large community of enthusiastic developers, which greatly simplifies troubleshooting when working with them. When choosing a device, I recommend using either a NodeMCU (Amazon) or a D1 Mini (Amazon).

The NodeMCU is available in different versions. The least useful is a NodeMCU v3 (Alibaba | Amazon) whose width is extremely unfavorable for use with a breadboard. The NodeMCU v1, sometimes referred to as V2 (Alibaba | Amazon), is slim and fits easily on a breadboard. So rather buy the v1 than the bulky v3, which does not give you the space to do anything else. [19659036] A Hacker Guide to Microcontroller Programming ” width=”532″ height=”532″ style=”max-width:532px;height:auto;”/>

A visual guide to the different versions of NodeMCUs. Image of Spacehuhn / GitHub

The other difference is the UART chip, which allows you to connect to the device via a micro USB (Amazon) cable. Cheaper devices use the CH340 chip, so you'll need to download and install additional drivers to use. These boards are useful because they can also be connected to Wi-Fi. If you prefer using Bluetooth, ESP32 (Alibaba | Amazon) boards have Wi-Fi and Bluetooth and can be programmed in the same way, but are more expensive.

Note that some of these boards do not come with soldered pins. If you buy a cheap D1 Mini or the ESP32 board, you can expect to solder the pins to yourself. If you do not want this, the NodeMCU may be a better choice for startup.

After having our microcontroller and breadboard, we need jumper cables (Amazon). If you end up with a breadboard, it may already come with jumpers. We also need one to three pairs of resistors and LEDs (Amazon). It would be one resistor per LED to make sure we do not burn out our LED prematurely. However, using a 3.3V microcontroller like the ESP8266 is less of a concern. A STEMTera board is powered by 5 volt logic. Therefore, it is more important when working with this or other 5 volt devices.

For resistors, you can use a resistor with a value between 220 and 330 ohms. Higher resistance makes your LED darker, while a lower value makes it brighter, but it goes out faster. You can decide how bright your LED should be and how long it should live.

There are kits you can buy (Amazon) that contain everything you need (and more) Need this manual, except for the microcontroller itself.

Kit with everything except the MCU: Emakefun Electronics Component Fun Kit

Step 1: Connect your hardware to a single LED, and later we can connect more to do several things at the same time. The default is to connect the digital pin we want to control to one LED with one resistor and then connect the other pin of the LED to the ground pin of our microcontroller.

If you are using a microcontroller Connect it to your breadboard like the D1 mini or NodeMCU and connect a wire to pin D3 on the breadboard. Remember that each numbered row is electronically connected, with each side in the center of the breadboard separated by a gap. Connect the wire from the D1 pin to the same row in which the resistor is plugged. Look for a longer leg than the other on your LED – it should be the positive leg of the LED.

Image of Kody / Null Byte

Plug Plug the positive branch of the LED into the same row as the other side of the resistor, and then plug in the remaining one Branch of the LED and a second wire in the same row. Finally, connect the end of the new cable to the ground pin and form a current flow path from pin D1 to the resistor, to the LED, and back to the ground pin.

Step 2: Downloading and Installing the Arduino IDE

Using the free and cross-platform ] Arduino IDE, we can quickly create the prototypes we need. With Arduino IDE (the IDE stands for "integrated development environment") you can quickly write scripts and upload them to Arduino-like microcontroller devices.

You can download the Arduino IDE from the official website. If you are using a STEMTera card, the correct card should already be included in Arduino by default. In the Tools menu, you can select "Arduino / Genuino Uno" from the drop-down menu to select the correct card.

If you are using an ESP8266-based microcontroller, you need to click on the "Arduino" drop-down menu, then select "Settings." Next, paste the following URL into the Additional Board Manager URLs box. Then click on "OK" to close the menu.

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

Now you need to add the NodeMCU to the Boards Manager . Click Tools and hover over the Map area to display the drop-down list. Click on "Boards Manager" above to open the window where we can add more boards. When the Boards Manager window opens, enter "esp8266" in the search box. Select "esp8266" from "ESP8266 Community" and install it.

You should now be ready to program your NodeMCU. Connect your breadboard via the micro USB cable to your computer where the NodeMCU should already be connected. If you click on "Tools", the correct connection should be selected automatically.

Select "NodeMCU 1.0" or "D1 Mini" depending on which port you use in the Map menu. If you are using a faulty cable or have not installed the required driver, the port may not be displayed. If you do not see anything after completing the other steps, try another cable first.

Step 3: Create an empty sketch

After setting up Arduino IDE, open a blank sketch. You should see something like this:

There are two main buttons at the top. The checkmark will compile and check our code for errors, and the right arrow will push the code to our microcontroller.

First, we have to take care of the essential parts of the code, namely the headings, variables, main and loop functions. We can make all this more understandable through comments. These are parts of the code we leave to explain what we do and why. The compiler ignores these parts of the code so they will not run. Therefore, they are intended only for other people to improve the understanding of the code.

Although this does not seem important, trying to understand code without comments is a nightmare. In Arduino we can omit a comment either with the mark // or with several lines with the symbol / * followed by a * / where it stops. Below are some examples.

  // This part of the code is not executed
/ * Neither will this part * / But this part will
This whole line will be executed
/ *
Everything from the icon above to the icon below will not be executed.
* /
This line will also be executed. 

When we execute this block of code, only part of row 2 and rows 3 and 7 are executed. The other lines are skipped by the compiler.

Step 4: Write headers and define variables

Now we write the header of our code, which describes what he does and who wrote it.

  // Script to flash a LED on pin 3
// By Kody Kinzie, Zero Bytes 2019 

A few lines further we create another comment explaining that this is our variable section. Here we set up all the variables we need to work with later. This also makes it easier for us later to change settings, eg. For example, how long the LED stays on or off.

First enter the pin to which our LED is connected. Mine is a white LED, so I called it wLED, but you can choose any name that you will remember. We also have to decide in milliseconds how long the LED should stay on and how long it should stay off. We select half a second or 500 milliseconds and store them in variables called onDelay and offDelay.

  // variable definitions
const int wLED = 3;
int onDelay = 500;
int off Delay = 500; 

In C ++ we have to write each line with a ; Stop (semicolon) to tell the program that we have finished the line. Now that we've created a constant integer (a variable that should not change) with the "const int" declaration, we can set it to 3 (or D3, if we use an ESP8266) by calling it assign. = icon.

In Arduino, = is NOT the same. This happens instead with the symbol == . The single symbol = is a command. In the above case, tell Arduino that the value is 3 and do not ask for it. This can be confusing later if you try to check if a variable is equal to a value and instead command that the variable be equal to that value.

Step 5: Write setup function

Now that our variables are defined, we have to take care of the part of the code that is executed only once. Although we connected pin 3 via hardware, we still have not told Arduino what to expect. Arduino itself has no idea if we want to use this pin for input, output or something else. That's why we need to tell him in our setup function.

We have already assigned the number of our pin to the variable. "wLED," so we can put the pin in the output mode. To do this, call the function pinMode () and give it the desired pin and the desired mode.

  // Set the settings to enable the pin modes

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

Here we said that the wLED pin should be put into output mode, providing power to the LED connected to pin 3.

Step 6: Write Loop Function

Now let's write the central part of our code. Here, we take into account the delays that we set, so that the light stays on and off for periods of time that a human being can perceive. Within the loop, we call the function digitalWrite (), which accepts the pin to write to, and then 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 that turns the LED on and off.

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

Taken together, this first turns the LED on, waits for the specified time (half a second in this case) and then turns it off. The code then waits another half second before starting over, and produces a flashing LED that turns on and off the same time. Together, our simple code now looks like this:

  // script to blink an LED on pin 3
// By Kody Kinzie, zero byte 2019

// variable definitions
const int wLED = 3;
int onDelay = 500;
int off Delay = 500;

// make settings to enable pin modes

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

// Loop function that turns the LED on and off.

empty loop ()
{
digitalWrite (LED, HIGH);
delay (onDelay);
digitalWrite (LED, LOW);
delay (offDelay);
} 

Step 7: Send code to the microcontroller

After we have the code together, we can click the check mark to search for errors. When 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 does not appear here and your card is connected to a micro USB cable, you will need to install the driver for the card, try a different cable, or try to install the card first.

Make Your Program More Complex

If You Want When you add more LEDs, you can extend what you've learned to create our capabilities, and call them up every time you to make this color blink Declare new variables for each LED and put each pin in output mode.

Consider the following sample code where I added a red, green and blue LED as rLED, gLED or bLED.

  // Script for flashing an LED on pins 3, 4 and 5
// By Kody Kinzie, zero byte 2019

// variable definitions
const int rLED = 4;
const int gLED = 3;
const int bLED = 5;
int onDelay = 200;
int offDelay = 10;
int shortDelay = 3000;
int mediumDelay = 1000;
int longDelay = 20000;

// make settings to enable pin modes

void setup ()
{
pinMode (rLED, OUTPUT);
pinMode (gLED, OUTPUT);
PinMode (LED, output);
} 

We can also create functions to create flashing patterns or to make the blinking of each LED easier. Below, I've used the code to toggle each LED on and off and created a function that I can call in the main loop to turn that LED color on.

  // Flashing pattern functions

not red () {
digitalWrite (rLED, HIGH);
delay (onDelay);
digitalWrite (rLED, LOW);
delay (offDelay); }
not green () {
digitalWrite (GLED, HIGH);
delay (onDelay);
digitalWrite (LED, LOW);
delay (offDelay); }
Void blue () {
digitalWrite (LED, HIGH);
delay (onDelay);
digitalWrite (LED, LOW);
delay (offDelay); } 

After doing this, I can call blue () to blink the blue LED and change the length of the delays by changing the variables above. I can also create a light pattern in a function. If I want to turn the blue and red LEDs on and off like the lights of a police vehicle, I can create a function called polis () and save the pattern so it can be easily accessed.

  void polis () {
red();
Blue();
red();
Blue();
red();
Blue();
red();
Blue();
red();
Blue();
red();
Blue();
red();
Blue();
red();
Blue();
delay (mediumDelay); } 

Finally, in our loop function, we can keep things clear and simple by calling the previously created functions. Here I blink green, blue, red, green and then the color pattern of our police.

  // Loop function that lights up to turn them on and in which order.

void loop () {
Green();
Blue();
red();
Green();
polis ();
} 

As you can see, you can better organize and work out your work with these editions! In addition to features like digitalWrite, other useful features like analogWrite can pinpoint pin performance and help you customize the way your LED responds to your program. Although we will not go into input in this manual, the general format follows what I have described for defining, setting, and using output pins.

Microcontrollers are easy to program and make a lot of fun when putting together. While our example only shows you how to bridge the physical world of hardware and the mental logic of coding, this process lets you create incredible Arduino projects like the Wi-Fi Deauther.

I hope you liked this guide to writing your code first program for a microcontroller! If you have questions about this tutorial programming in Arduino or have a comment, feel free to contact me at the bottom of the comments or on Twitter @KodyKinzie .

Do not Miss: Detecting & Classifying WLAN Interference Packages with the NodeMCU

Cover photo, screenshots and GIF of Kody / Null Byte




Source link