Showing posts with label Microcontroller AVR. Show all posts
Showing posts with label Microcontroller AVR. Show all posts

Wednesday, January 24, 2024

Defining F_CPU in Microchip Studio

The macro F_CPU specifies the CPU frequency and is used by libraries such as <delay.h> to calculate the delay based on the frequency of the processor or by UART libraries to calculate baud rate.

Up until now I used to define F_CPU like this:

#define F_CPU    16000000UL

Defining this way will work but it could lead to issues and confusion when you have multiple files that define this macro. The ideal way is to define it in a single place. This could be a Makefile if you are using custom Makefiles or in the IDE project configuration.

Defining F_CPU in Microchip Studio

Open the project properties window in Project -> Properties (Alt+F7) then in the left panel select the Toolchain menu. Next in AVR/GNU C Compiler -> Symbols use the green + button to define a new symbol F_CPU=16000000UL. Of course the F_CPU value depends on your CPU frequency that in this example is 16000000 Hertz or 16MHz. The UL at the end stands for unsigned integer.

Defining F_CPU symbol in Microchip Studio
click to enlarge

That's it. Now all included files in your project will use a single F_CPU value without giving errors such as "F_CPU is not defined", "F_CPU redefined", etc.

Since this method of defining is not as obvious as the first one, it is easy to forged to do it when starting a new project but there is a simple solution for that - using preprocessor conditionals.

#ifndef F_CPU
	#warning	"F_CPU not defined. Define it in project properties."
	
#elif F_CPU != 16000000
	#warning	"Wrong F_CPU frequency!"
#endif

This macro can be placed at the beginning of the main.c file before any type of code. If the F_CPU is not defined it will output a warning. If the F_CPU is defined but is not the value specified in the macro, it will also output a warning. This is also helpful to see what the CPU frequency is and to ensure that the defined value in project properties is correct.

Thursday, January 4, 2024

How to program an UPDI AVR microcontroller using avrdude and USB to serial programmer

After buying some ATtiny402 microcontrollers I've noticed that newer AVR models from Microchip are now using the UPDI interface for programming. Previously the programming was done using SPI or UART if a bootloader was present.

How to program an UPDI AVR microcontroller using avrdude and USB to serial programmer
 

Contents

 

What is UPDI and how do I use it?

UPDI stands for Unified Program and Debug Interface and is proprietary to Microchip. In many ways is similar to 1 wire UART. The main advantage is that it can be used for programming and also for debugging. Now there is no need for SPI, bootloader, debugWire... It's all Unified in one pin and one interface.

On certain devices such as ATtiny, the UPDI and Reset are on the same pin. In each case, the UPDI pin can also be used as a GPIO pin. When UPDI and Reset share the same pin, the functionality can be selected using the specific fuse. By default the fuse is set to select UPDI as a pin function. If you change the fuse and enable the Reset then you will need a 12V programmer to be able to program the microcontroller.

To prevent false triggering when the line is idle, it is recommended to have a pull-up resistor of at least 10k on the UPDI pin. Although some say that it works without problems even without a pull-up resistor so if you are using the UPDI pin also as a GPIO pin, you might consider not placing the resistor.

Source: https://microchip.my.site.com/s/article/AVR---Hardware-Design-Considerations-for-UPDI-pin.

Can i manually reset the microcontroller when UPDI is shared with RESET? 

Wednesday, December 20, 2023

Library for TMC2209 driver - AVR

This library is used to control one or more TMC2209 modules via UART using an AVR microcontroller. Apart from reading and writing the TMC2209 registers, this library can also be used to drive a stepper motor by using the stepperCon library in the background. The stepperCon library provides non blocking functions by using an interrupt, to drive multiple stepper motors with custom acceleration and speed, to keep track of motor positions, 3-axis motor coordination, as well as other useful functions. UART library is also provided that can use up to 2 USART peripherals at the same time: one for interfacing with the driver IC and one for debugging (assuming the microcontroller has two USART peripherals). 

The serial communication has some extra features for checkup such as:

  • reads the interface transmission counter (IFCNT) register after every write to ensure the IC received the correct data.
  • compares CRCs.
  • checks if correct number of bytes has been received.
  • if an error occurs it retries 2 times then sets a communication error flag that the user can check after each function is executed and take the appropriate action if an error occurs. 

Library for TMC2209 driver - AVR
The principle of operation is read-modify-write so there is no need to keep all driver IC registers in memory. The library only uses an 8 bytes union structure called replyDatagram where received and data to send is stored temporary.

If you wish to learn on how to wire the TMC2209 driver, you can find a tutorial here.

Contents

Monday, October 23, 2023

Pin interrupt library for AVR microcontrollers

This library can help to easily configure a pin interrupt on AVR microcontrollers without the need to check the datasheet every time. At the moment only PCINT pins are supported.

Pin interrupt library for AVR devices

In this blog post, I will explain how to use interrupts on AVR microcontrollers. Interrupts are a powerful feature that allow the microcontroller to respond to external or internal events without constantly polling for them. Interrupts can improve the performance and efficiency of your code, as well as enable new functionalities.

What are interrupts?

An interrupt is a signal that causes the microcontroller to temporarily stop its current execution and jump to a special function called an interrupt service routine (ISR). The ISR performs the necessary actions to handle the interrupt, and then returns to the original program flow. The ISR can be triggered by various sources, such as:

  • External pins (EXTINT)
  • Pin changes (PCINT)
  • Timers/Counters (TIMER)
  • Serial communication (USART, SPI, TWI)
  • Analog-to-digital conversion (ADC)
  • Analog comparator (AC)
  • Watchdog timer (WDT)
  • EEPROM ready (EE READY)
  • Store program memory ready (SPM READY)

Tuesday, October 3, 2023

stepperCon library for controlling stepper motor drivers using timer interrupt on AVR devices

The stepperCon library allows you to control multiple stepper motors at the same time. It can interface with any stepper motor driver that can take inputs such as step and direction. The library also has some extra useful functionalities such as motor coordination using Bresenham line algorithm - useful for controlling 3 axis motors for example, free spin - where the motor keeps spinning, and positioning the motor at a certain degree from 1 to 360 by finding the shortest path.

The maximum speed (step rate) on a 16MHz microcontroller is 25kHz, however the maximum practical speed is 6.25kHz or 8.33kHz depending on the motor, load, supply voltage and micro-step resolution. A higher voltage can yield higher RPM and with 1/32 micro-step resolution the step rate can be 25kHz as oppose to 6.25kHz when using 1/8 micro-step resolution.

Even with multiple motors running at the same time, the speed can be maintained and that is because the speed profile is segmented and calculated while the interrupt routine (ISR) is not executing steps. So the time spent inside the ISR is low since the calculations for acceleration and deceleration are not done there. Only the stepping is done inside the ISR. Having an interrupt to generate the steps is preferred over a function in the main loop where other code could delay the stepping function thus causing motor stuttering.

The stepper library includes the micros library that is used to trigger a timer interrupt every 40us and as a perk you also have a way to keep track of time in your project with a 40us time resolution.

 

stepperCon library characteristics

  • interface with multiple stepper motor drivers
  • up to 3 coordinated motors for X, Y and Z (can be extended for more)
  • maximum stepping rate speed of 6.25kHz (or 8.33kHz if the motor can have high acceleration). Speeds are given for a 16MHz CPU. With higher CPU clock the stepping rate will also be higher.
  • angular positioning function that finds the shortest path from current angle to target angle
  • perpetual motion
  • timer interrupt driven
  • individual settings for acceleration and deceleration

Saturday, June 10, 2023

Breadboard Development Board for AVR microcontrollers | Breaduino

A development board is an essential tool when working with projects that involve a microcontroller and most of the time you will also need a breadboard and a power supply. So why not combining all these in a single product?

Meet Breaduino - a custom development board build around ATmega328PB microcontroller. If you are a beginner in electronics or microcontrollers, building a development board is not only rewarding but also educational.

Breadboard Development Board for AVR microcontrollers | Breaduino

The Breaduino dev board is designed to be used with two breadboards where it outputs three voltages: 12V, 5V and 3.3V. It includes a TFT display, micro SD card socket, input current measurement and a rotary encoder for user interaction. On the right side of the case is space for a small logic analyzer and/or a 9V battery. All these are optional modules. Even the breadboard is optional so the board can be used standalone. Since this is a customizable board it can be modified to fit your needs.

Breadboard Development Board for AVR microcontrollers | Breaduino

Sunday, August 7, 2022

UART library for AVR microcontrollers using interrupts

This is a UART library that is made for AVR microcontrollers that can be used for serial communications.

UART is a type of serial interface, as opposed to a parallel interface. A parallel interface can work at higher speeds but the disadvantage is that it needs multiple input/output lines. Other examples of serial interfaces are SPI and I2C.

UART library for AVR microcontrollers using interrupts

Features

  • Custom Baud rate
  • Asynchronous or synchronous modes
  • Supports serial frames with 5, 6, 7, 8, or 9 data bits
  • Odd, even or no parity
  • Error detection
  • Multi-processor communication mode used to address multiple devices on the same serial bus
  • Double speed asynchronous communication mode

Thursday, August 4, 2022

Tutorial on how to program an AVR ATmega328PB microcontroller using Atmel Studio and a bootloader

In this tutorial you will be learning how to use Microchip Studio (previously known as Atmel Studio) to program an AVR microcontroller over UART using the Optiboot bootloader. The hardware necessary is very inexpensive. All you need is an ISP (In System Programming) module such as USBTinyISP (around 3$) and an USB to Serial adapter that is around the same price and you can even build it yourself if you wish.

Monday, July 25, 2022

Library for MCP4725 DAC for AVR microcontrollers

The MCP4725 is a low-power, high accuracy, single channel, 12-bit buffered voltage output Digital-to-Analog Convertor (DAC) with non-volatile memory (EEPROM). Its on-board precision output amplifier allows it to achieve rail-to-rail analog output swing. The advantage of this DAC is the A0 pin that can be used to control multiple DACs by changing their address (more on that later).

This DAC library also includes an I2C driver that is needed by the AVR to communicate with the MCP4725.

Library for MCP4725 DAC for AVR microcontrollers

Contents

  1. Pin Descriptions
  2. Wiring up one or multiple DACs
  3. MCP4725 Characteristics
  4. Code Example
  5. Using the MCP4725 library
  6. Download

 

1. Pin Descriptions

 

MCP4725 DAC pin description

MCP4725 pins

Thursday, May 12, 2022

Displaying Bitmap images on ST7735 display from a memory card using an AVR microcontroller

This is an extension for the ST7735 display driver library made for displaying Bitmap images stored on an SD memory card on the ST7735 TFT display using an AVR microcontroller. The Bitmaps can be of 16-bit or 24-bit colors. Since the ST7735 display driver only accepts 16-bit colors, the 24-bit images will be converted to 16-bits.

Here is a short demo video:


The images must be resized first to fit the size of your display. A free and popular software for this task is Irfanview. Open the image using Irfanview then press CTRL+R, specify the new image size then save it as a .bmp and place the images on the memory card in a folder of your choice.

Saturday, February 5, 2022

Library for ST7735 TFT display driver for AVR microcontrollers

There are already some libraries for the ST7735 display driver such as the one from Adafruit but made only for Arduino. I needed one for AVR microcontrollers in general, so I made this one. With a bit of twiking it could also be adapted to work with other types of microcontrollers. This library is based on the one from Adafruit but with some functions removed, modified and others added. The interface needs 4 microcontroller pins and it uses SPI for communication.

Library for the ST7735 TFT display driver for AVR microcontrollers

Library for the ST7735 TFT display driver for AVR microcontrollers demo

There are many GUI elements that can be created and above are a few examples such as: selectable menus, scrollbars, check-boxes and animated icons. I made those in Inkscape for a battery charger project.

Contents:


Wiring the ST7735 TFT display

It is important to note that the power supply voltage for the ST7735 display driver is maximum 3.3V and same for the other input pins. Some TFT modules include a 3.3V regulator and a voltage level shifter in which case it can be used with 5V microcontrollers, if not some level shifting must be done if the microcontroller is not powered from 3.3V.

ST7735 connection diagram with voltage level shifter

This schematic is an example that also includes an SD card. Here, MISO is used for DC pin (Data/Command) since the ST7735 doesn't use the MISO in the 1-Wire SPI protocol, and also as MISO (Master In Slave Out) for the SD card. The 74AHC125D can't be used for this pin since is not bi-directional, hence the mosfet level shifter.

ST7735 connection diagram with voltage level shifters and pinout

1 - GND - ground power supply

2 - VCC - 3.3V power supply (minimum 150mA)

3 - SCL - SPI serial clock pin (SCK)

4 - SDA - SPI serial data input/output (MOSI)

Friday, October 22, 2021

DAC library for MCP4706, MCP4716, MCP4726 and AVR microcontrollers

This library is intended for the MCP47x6 series of DAC devices that includes MCP4706 (8-bit DAC), MCP4716 (10-bit DAC) and MCP4726 (12-bit DAC).

DAC library for MCP4706, MCP4716, MCP4726 and AVR microcontrollers

Table of Contents


MCP47x6 DAC pinout

MCP47x6 DAC pinout

1 - VOUT: this is the DAC analog output voltage. In Normal mode, the DC impedance of the output pin is about 1Ω. In Power-Down mode, the output pin is internally connected to a known pull-down resistor of 1 kΩ, 125 kΩ, or 640 kΩ. The VOUT pin can drive up to 100 pF of capacitive load in parallel with a 5 kΩ resistive load. It is recommended to use a load with RL greater than 5 kΩ. Driving large capacitive loads can cause stability problems for voltage feedback op amps.

Tuesday, October 19, 2021

I2C and TWI (Two Wire Interface) library for AVR microcontrollers

In the last article I talked about How I2C and TWI protocol works and we saw that they are mostly the same so this library works for both I2C and TWI serial interfaces. You don't have to know every detail about how the I2C protocol works but I strongly recommend reading the article to have a general idea about it, and that way it will be easier to use this library.


Using the I2C, TWI library with an AVR microcontroller

Setting the library file

As always, first include the library file:

#include "twi.h"

Most AVR microcontrollers have two TWI modules TWI0 and TWI1 so to choose between the two there is the following line of code:

#define TWI_MODULE_NUMBER	0 // TWI module 0 or 1

The default module is TWI0.

Functions


void TWI_Init(uint32_t frequency)

Used to initialize the TWI module. This will set the TWI bit rate and enable global  interrupts. 400kHz is the maximum TWI speed that regular AVR microcontrollers supports although I have managed to talk to a DAC at 577kHz.

frequency:  can be one of the following constants or any value between 100-400kHz.

#define TWI_400KHZ	400000 // Hz
#define TWI_100KHZ	100000 // Hz

Wednesday, April 21, 2021

Building a Digital Clock with RGB Lamp & Spherical Shelf DIY

Here is how to build a simple digital wall clock encased in a spherical shelf that could make a nice gift for someone.

The clock is based on an ATmega328PB microcontroller that is using a 32.768 kHz crystal for time keeping. It also has 6 RGB leds that act as a night lamp or simply for aesthetic purposes.

Digital Clock With RGB Lamp & Spherical Shelf DIY

Saturday, February 6, 2021

Colorspace conversion between RGB and HSL library code for AVR microcontrollers | ATmega328P

I had a project where I needed to crossfade RGB colors and I thought why not using the HSL color space instead of the RGB color space because with the HSL the code looks neater and the Hue (color), Saturation and Lightness can easily be modified to create all kinds of light effects.

Colorspace conversion between RGB and HSL library code for AVR microcontrollers | ATmega328P

Converting HSL to RGB

HSLtoRGB(hue, saturation, lightness, rgb[])

Thursday, February 4, 2021

How to control RGB leds | RGB fader library for AVR ATmega328P

RGB leds are fun and because they can be used in many projects I have decided to make a library to easily crossfade the colors of one or multiple RGB leds.

To see this library used in a real project, check out this video Digital Clock With RGB Night Lamp & Spherical Shelf.

How to control RGB leds | Crossfading RGB leds | Library for AVR ATmega328P

Crossfading an RGB led in the RGB colorspace

With 8 bits we have 256 values from 0 to 255 that represents the duty cycle - how long a led will be on then off in a period. For example setting the RED led to 255 and GREEN and BLUE to 0 will result in RED color. Or RED 255, GREEN 0 and BLUE 255 will show a purple color. All leds on (255 value) will result in a white lite. So this is how a certain color can be produced but how to cycle through all the possible combinations?

Crossfading an RGB led in the RGB colorspace 1

First the red color is set at 255 and green and blue to 0. Then the red will be decremented and the green will be incremented. When the red will be 0 and green 255 we change the fading up and fading down colors.

Wednesday, February 3, 2021

Multi-channel software PWM library for AVR microcontrollers | ATmega328P

What you do when you run out of PWM pins on hardware? You make software PWM of course. This library is based on "AVR136: Low-Jitter Multi-Channel Software PWM" application note. It supports up to 10 PWM channels (more can be added) and it's suitable for led dimming, DC motor control and RGB led controller.

Multi-channel software PWM library for AVR microcontrollers | ATmega328P

Since this method is already explained in the AVR136 app note I won't go in to too many details. So the basic principles behind software PWM are this. A timer interrupt is set to trigger every 256 system clocks. For 8 bit timers the interrupt is on overflow and for 16 bit timers is on compare match. A 16 bit timer has the advantage that the base frequency can be modified. On every interrupt a variable "softcount" is incremented from 0 to 255 and each time is compared against each PWM channel. At the beginning of the cycle the pins are set high and when "softcount" equals to a channel's set value then the specific pin is set low. On 8MHz CPU the ISR takes between 4 and 10us to execute the code depending on how many channels and on how many ports there are. The size of the "softcount" variable dictates the PWM resolution and it is set to 8 bits. 

Saturday, January 23, 2021

Binary Code Modulation (BCM) aka Bit Angle Modulation (BAM) library for fading leds for AVR microcontrollers

Binary Code Modulation (BCM) was invented by Artistic Licence and is a form of PWM but not really. The main advantage over software PWM is the low CPU usage regardless of how many channels it controls.

This library provides a fast implementation of Binary Code Modulation useful for controlling RGB leds and dimming multiple leds for creating animations like led cubes and includes an array for logarithmic brightness. A complete cycle takes 8 timer interrupts and each interrupt takes only 4us on a 8MHz CPU. The leds can be on different ports.

Bit Code Modulation (BCM) aka Bit Angle Modulation (BAM) library for RGB led dimming - 8-bit

How Binary Code Modulation (BCM) works and how it differs from PWM

To dim a led with PMW is simple. If you want the led to be half as bright you turn the led on for 50% of the cycle and 50% for the other half. Or 20% on and 80% off for an even dimmer led.

 

PWM example

Bit Angle Modulation uses the weight of each bit in a binary number. For example in one byte there are 8 bits with numbers from 0 to 7. Bit 0 is called the Least Significant Bit (LSB) and it's weight is 1. Next bit 1 has a weight of 2, bit 2 has a weight of 4, then 8, 16, 32, 64 and 128. Bit 7 is called the Most Significant Bit (MSB) because it has the highest weight - 128.

8-bit binary weight

Monday, January 18, 2021

7 segment display library for AVR microcontrollers | ATmega328P

There are many ways to control a seven segment display - using a dedicated IC or shift registers which are preferred because they don't require many pins. However this library is made for when you have the segments driven directly from microcontroller pins and each digit is controlled using a transistor.

You have the option of padding the numbers with zeros and displaying them at a certain position, useful for making digital clocks.

To see this library used in a real project, check out this video Digital Clock With RGB Night Lamp & Spherical Shelf.

Seven segment display library for AVR microcontrollers

What is a 7-segment display

As the name suggests it is a display that is made up of 7 segments. Each segment is simply an LED. Including the dot there are actually 8 LEDs and this fits perfectly on an 8-bit microcontroller's port. This display is mainly made for numerical values but some alphabetical characters can be displayed as well.

Types of 7 segment displays

There are two types of seven segment displays - common cathode and common anode. Common cathode displays have all the ground sides (cathodes) of the LEDs connected together while common anode displays have all the positive sides (anodes) of LEDs tied together.

The 7 segment display can have from 1 up to 6 or 8 digits. One digit can display numbers from 0 to 9 and a dot for numbers with decimals. On 4 digit seven segment display the maximum number that can be displayed is 9999.

7 segment display internal equivalent circuit OPD-Q5621LE-BW
Figure 1: Internal equivalent circuit of a 7 segment display from OPD-Q5621LE-BW datasheet

 

Saturday, January 16, 2021

Read and debounce multiple buttons using interrupt on AVR microcontrollers

This library provides an easy way for reading and debouncing one or multiple buttons connected to a microcontroller. Apart from basic functionality, the library provides some extra functions such as reading a combination of buttons, and detecting a button long press or a double pressed button. These are especially useful in a low button count system.

There are many methods of reading buttons. The simplest way is having each button connected to a microcontroller pin, and the other button pin connected to ground. The microcontroller pin is set in output mode with the internal pull-up resistor activated. When the push button is pressed, the pin will be pulled to ground indicating that a button in pressed.

After a certain number of buttons, the above method becomes impractical since microcontrollers with high pin count are much more expensive. In that case multiplexing is used like on a keyboard, where the buttons are arranged in a grid having x number of pins for columns and y pins for rows.

This library uses the first method for when the buttons are connected directly to a microcontroller pin. Hopefully, when I'll get the time I will adapt the library to take inputs from a matrix.

Multiple buttons can also be read by a single ADC pin.


Button debouncing library for AVR microcontrollers

Contents

 

What is button debouncing