How and why to read datasheets if microcontrollers are your hobby

How and why to read datasheets if microcontrollers are your hobby

Microelectronics is a hot trend in recent years thanks to the magical Arduino. But here's the problem: with due interest, outgrowing DigitalWrite() turns out quickly, and what to do next is not entirely clear. The Arduino developers have put a lot of effort into lowering the barrier to entry into their ecosystem, but beyond its borders, a dark forest of harsh circuitry still sways, inaccessible to an amateur.

For example, datasheets. It seems that they have everything, take it and use it. But only their authors clearly do not set themselves the task of popularizing microcontrollers; Sometimes it seemsthat they deliberately abuse incomprehensible terms and abbreviations when describing simple things in order to confuse the uninitiated as much as possible. But not everything is so bad, if desired, the chest opens.

In this article, I will share the experience of communication between a humanist and datasheets for hobby purposes. The text is intended for amateurs who grew up from Arduino pants, it assumes some understanding of the principles of operation of microcontrollers.

I'll start with the traditional

Blink LED on Arduino

And immediately the code:

void setup() {
DDRB |= (1<<5);
}

void loop() {
PINB = (1<<5);
for (volatile uint32_t k=0; k<100000; k++);
}

"What is this? - The sophisticated reader will ask. “Why are you writing something to the PINB input register?” It's read-only!" Really, Arduino documentation, like most tutorial articles on the internet, states that this register is read-only. I thought so myself until I read it. datasheet to the Atmega328p while preparing this article. And there:

How and why to read datasheets if microcontrollers are your hobby

This is a relatively new functionality, it was not on Atmega8, not everyone knows about it or does not mention it for reasons of backward compatibility. But it is quite suitable for demonstrating the idea that datasheets are worth reading in order to use all the features of the chip, including little-known ones. And this is not the only reason.

Why else read datasheets

Usually, after playing with LEDs and AnalogWrites, arduino developers begin to connect all sorts of modules and chips to the board, for which there are already written libraries. Sooner or later, a library appears that does not work as it should. Then the amateur starts picking it to fix it, and there ...

And something categorically incomprehensible happens there, so you have to go to Google, read numerous tutorials, pull someone's suitable code in parts and finally achieve your goal. This gives a powerful sense of accomplishment, but in reality the process is like reinventing the bicycle by reverse engineering a motorcycle. Moreover, understanding how this bike works is not added. I know because I've been doing this myself for a long time.

If I had spent a couple of days studying the Atmega328 documentation instead of this exciting activity, I would have saved a huge amount of time. After all, this is a fairly simple microcontroller.

Thus, it is necessary to read datasheets at least in order to imagine how the microcontroller works in general and what it can do. And further:

  • to check and optimize other people's libraries. They are often written by the same amateurs who reinvent the wheel; or, on the contrary, the authors deliberately make them redundant protection from the fool. Let it be three times larger and slower, but it will definitely work;

  • to be able to use chips in the project for which no one has written a library;

  • to facilitate the task of migrating from one MK line to another;

  • to finally optimize your old code, which did not fit into Arduino;

  • to learn how to control any chip directly through its registers, without bothering to study the structure of its libraries, if any.

Why write directly to registers when there are HAL and LL?

Glossary
HAL, High Abstraction Layer - a library for controlling a microcontroller with a high level of abstraction. If you need to use the SPI1 interface, just configure and enable SPI1 without thinking about which registers are responsible for what.
LL, Low Level API - a library containing macros or structures with register addresses, allowing you to access them by name. DDRx, PORTx, PINx on Atmega is LL.

Disputes on the topic “HAL, LL or registers” regularly occur in the comments on Habré. Without claiming to have access to astral knowledge, I will simply share my amateur experience and thoughts.

Having more or less dealt with Atmega and having read articles about the beauty of STM32, I bought half a dozen different boards - both Discovery, and Blue Pills, and even just chips for my homemade products. All of them have been gathering dust in a box for two years. Sometimes I said to myself: “that’s it, I’m mastering STM this weekend”, I launched CubeMX, generated a setup for SPI, looked at the resulting wall of text, richly flavored with STM copyrights, and decided that this was somehow too much.

How and why to read datasheets if microcontrollers are your hobby

Of course, you can figure out what CubeMX wrote here. But at the same time it is clear that it is unrealistic to remember all the formulations, so that later you can write them with your hands. And to debug this if I accidentally forget to put some checkmark in Cuba - quite hello.

It's been two years, I'm still licking my ST MCU Finder on all sorts of tasty, but inaccessible to my understanding chips, and accidentally stumbled upon great article, albeit about STM8. AND suddenly I realized that all this time I was knocking on an open door: the STM registers are arranged in the same way as any other MK, and the Cube is not necessary to work with them. And what, so it was possible? ..

HAL and specifically STM32CubeMX is a tool for professional engineers who work closely with STM32 chips. The main feature is a high level of abstraction, the ability to quickly migrate from one MK to another and even from one core to another, while remaining within the STM32 line. Fans rarely face such tasks - our choice of MK is usually limited by the AliExpress assortment, and we often migrate between radically different chips - we move from Atmega to STM, from STM to ESP, or whatever new Chinese friends throw us. HAL will not help here, and learning it will eat up a lot of time.

It remains LL - but half a step from it to the registers. Personally, I find writing my macros with register addresses useful: I study the datasheet more carefully, think about what I will need in the future and what I definitely don’t, structure my programs better, and, in general, overcoming helps memorization.

In addition, there is a nuance with the popular STM32F103 - there are two incompatible versions of LL for it, one official from STM, the second from Leaf Labs, used in the STM32duino project. If you write an open-source library (and I had exactly such a task), you must either make two versions, or access the registers directly.

Finally, the rejection of LL, in my opinion, simplifies the migration, especially if you rely on it from the very beginning of the project. An exaggerated example: let's write an Arduino blink in Atmel Studio without LL:

#include <stdint.h>

#define _REG(addr) (*(volatile uint8_t*)(addr))

#define DDR_B 0x24
#define OUT_B 0x25

int main(void)
{
    volatile uint32_t k;

    _REG(DDR_B) |= (1<<5);

    while(1)
    {
        _REG(OUT_B) |= (1<<5);
        for (k=0; k<50000; k++);
        _REG(OUT_B) &= ~(1<<5);
        for (k=0; k<50000; k++);
    } 
}

In order for this code to blink an LED on a Chinese scarf with STM8 (from ST Visual Desktop), it is enough to change two addresses in it:

#define DDR_B 0x5007
#define OUT_B 0x5005

Yes, I use the LED connection feature on a specific board, it will blink very slowly, but it will be the same!

What are datasheets

In articles and forums, both Russian and English, “datasheets” mean any technical documentation for chips, and I do the same in this text. Formally, they are just one of the types of such documentation:

Datasheet - TTX, tactical and technical characteristics. A must for any electronic component. Reference information, it is useful to keep at hand, but there is nothing special to read thoughtfully. However, simpler chips are often limited to a datasheet so as not to produce unnecessary documents; in this case Reference Manual is included here.

Reference Manual - the actual instruction, a healthy book with 1000+ pages. The work of everything that is stuffed into the chip is signed in detail. The main document for the development of the microcontroller. Unlike datasheet, instructions are written for a wide range of MKs, they contain a lot of information about peripherals that are not available in your particular model.

Programming Manual or Instruction Set Manual - instructions for unique commands of the microcontroller. Designed for those who program in Assembler. Compiler authors actively use it to optimize code, so in the general case we don't need it. But looking here is useful for a general understanding, for some specific commands such as exiting an interrupt, as well as when actively using the debugger.

Application Note - useful tips for solving specific problems, often with code examples.

Errata Sheet – description of cases of non-standard behavior of the chip with bypass options, if any.

What is in datasheets

Directly in Datasheet we may need sections like this:

Device Summary - the first page of the datasheet briefly talks about the device. It is very useful in situations when you have found a chip somewhere (saw it in a store, soldered it, met a mention) and want to understand what it is.

General Description – a more detailed description of the capabilities of the chips from the line.

Pinouts - pinout schemes for all possible chip packages (on which leg which pin).

Pin Description - a description of the purpose and capabilities of each pin.

Memory Map - we are unlikely to need a map of addresses in memory, but sometimes it also includes a table of addresses of register blocks.

Register Map - the address table of register blocks, as a rule, is located in the datasheet, and in Ref Manual – only shifts (address offsets).

Electrical Characteristics In this section, we are primarily interested in absolute maximum ratings, listing the maximum loads on the chip. Unlike the indestructible Atmega328p, most microcontrollers do not allow serious loads to be connected to the pins, which becomes an unpleasant surprise for arduinos.

package information - drawings of available packages, useful when designing your boards.

Reference Manual structurally consists of sections dedicated to specific peripherals indicated in their heading. Each chapter can be roughly divided into three parts:

Overview, Introduction, – an overview of the capabilities of the periphery;

functional description, Usage Guide or simply the main block of the section - a detailed textual description of the principles of the device of the periphery and how to use it;

Registers – description of control registers. In simple cases like GPIO or SPI, this may be enough to start using peripherals, but often you still have to read the previous parts.

How to read datasheets

Datasheets out of habit scare away with their volume and abundance of incomprehensible words. In fact, everything is not so scary if you know a few life hacks.

Set good PDF reader. Datasheets are written in the glorious tradition of paper instructions and are great to print out, line with plastic bookmarks, and stitch together. Hypertext in them is observed in trace amounts. Fortunately, at least the structure of the document is bookmarked, so a suitable reader with easy navigation is very necessary.

The datasheet is not Stroustrup's textbook, it contains no need to read everything. If you used the previous advice, just find the desired section in the bookmarks bar.

datasheets, especially Reference manuals, may describe the capabilities of not a specific chip, but the entire line. This means that half, or even two-thirds of the information is not related to your chip. Before learning the TIM7 registers, check in General Descriptionwhether you have it.

Know English enough for basic level. Datasheets are half made up of terms unfamiliar to the average native speaker and half made up of simple linking constructs. There are also excellent Chinese datasheets in Chinese English, where half are also terms, and the second half is a random set of words.

If you meet unfamiliar word, do not try to translate it with an English-Russian dictionary. If it confuses you hysteresis, then from the translation "hysteresis" you will not become warmer. Use Google, Stack Overflow, Wikipedia, forums where the desired concept will be explained in simple terms with examples.

The best way to understand what you read is check in action. Therefore, keep at hand the debug board that you are getting acquainted with, and preferably two - in case you still misunderstood something and saw magic smoke.

It's a good habit to keep a datasheet handy when you reading someone's tutorial or study someone else's library. It is quite possible that you will find a better solution to your problem in it. And vice versa - if you can’t understand from the datasheet how the registry still works, google it: most likely, someone has already described everything in simple words or left understandable code on GitHub.

Glossary

A few useful words and notations that help you quickly get used to datasheets. What I remembered in the last couple of days, additions and corrections are welcome.

Electricity
Vcc, True - "plus", food
vss, and - "minus", earth
current – current
voltage - voltage
sink current - work as "ground" for external load
to source current - power an external load
high sink/source pin - pin with increased "tolerance" to the load

IO
H,High - on the Vcc pin
L,Low – on pin Vss
high impedance, Hi-Z, floating - there is nothing on the pin, "high resistance", it is actually invisible to the outside world.
weak pull up, weak pull down - built-in pull-up / pull-down resistor, an approximate analogue of 50 kOhm (see datasheet). It is used, for example, so that the input pin does not hang in the air, causing false positives. Weak - because it is easy to "interrupt".
push-pull – pin output mode, in which it switches between High и low - regular OUTPUT with Arduino.
open drain – designation of the output mode, in which the pin can be either lowor High Impedance/Floating. At the same time, this is almost always not a “real” open drain, there are protective diodes, resistors, and whatnot. It's just a ground/nothing mode designation.
true open drain - and this is already a real open drain: the pin leads directly to the ground if it is open, or is in limbo if it is closed. This means that, if necessary, it is possible to run a voltage greater than Vcc through it, but the maximum is still specified in the datasheet in the section Absolute Maximum Ratings/Voltage.

Interfaces
in series - connected in series
to chain - assemble chips in a chain by serial connection, increasing the number of outputs.
shift – shift, usually denotes a bit shift. Respectively, to shift in и to shift out - receive and transmit data bit by bit.
latch - a latch that covers the buffer while bits are being shifted through it. When the transfer is completed, the shutter opens, the bits begin to work.
to clock in – perform a bit-by-bit transfer, shift all the bits to the right places.
double buffer, shadow register, preload register - designations of history, when the register must be able to accept new data, but hold them until a certain moment. For example, for PWM to work correctly, its parameters (duty cycle, frequency) should not change until the current cycle ends, but new parameters can already be transferred. Accordingly, the current ones are held in shadow register, and new ones fall into preload register, being written to the corresponding register of the chip.

Anything
prescaler – frequency prescaler
to set a bit - set bit to 1
to clear/reset a bit - reset bit to 0 (reset - STM datasheet chip)

What's next

In general, a practical part was planned here with a demonstration of three projects on STM32 and STM8, made specifically for this article using datasheets, with light bulbs, SPI, timers, PWM and interrupts:

How and why to read datasheets if microcontrollers are your hobby

But the text is too much, so the projects are sent to the second part.

The ability to read datasheets will help you with your hobby, but it will hardly replace live communication with fellow hobbyists on forums and chats. For him, you still need to improve your English first of all. And therefore, those who have read it will receive a special prize: two free lessons in Skyeng with the first payment by code HABR2.

Source: habr.com

Add a comment