Program atmega328p using arduino

Programming Atmega328p Microcontroller with Arduino IDE

Introduction

Over the past few tutorials, we have mentioned several scenarios where using any of the Arduino board in a project may be an overkill due to the cost, size, and more technical reasons such as high power consumption. In the last tutorial, we discussed an alternative way of using Arduino, i.e. using the Atmega328p microcontroller alone which removes all the downsides of using the Arduino board, while retaining one of the biggest benefits of the Arduino platform; the ease of programming.

Atmega328p Microcontroller

We covered details on preparing the Atmega328p microcontroller for programming by flashing the Arduino bootloader on Atmega328p and today’s tutorial will be a follow up to that tutorial, as we will look at how to program the boot-loaded Atmega328p microcontroller using the Arduino IDE.

The Atmega328p microcontroller, like any other microcontroller, can be quite tasking to use for a beginner. They usually require a certain set of tools, including a programmer (hardware), and a development platform (e.g Atmel Studio) for writing code. These development platforms, unlike the Arduino IDE usually require high knowledge of C or other programming languages, without the shortcuts and simplified functions which the Arduino provides.

To remove this difficulty, the microcontroller is flashed with the Arduino bootloader, which makes it ready for programming using the simpler and easy to use Arduino IDE.

To program the microcontroller using the Arduino IDE, the microcontroller must be connected via some sort of hardware to the computer. This is usually done via two major ways:

  1. Using a USB to Serial/TTL Adapter
  2. Using an Arduino board

Each of these approaches provides the microcontroller with an interface that enables interaction between the computer and the microcontroller.

We will take each of these approaches one after the other and look at the components and setup required to upload code to the microcontroller.

Using a USB to Serial/TTL Adapter

The first approach involves the connection of a USB to serial adapter to the microcontroller. The USB to Serial/TTL adapter converts data signals from the USB on the computer to serial/TTL for the microcontroller and vice versa. This enables communication from the microcontroller (serial) with the Arduino IDE running on the PC (USB). This setup, compared to the second one, is by far the cheapest, as these adapters are usually very cheap.

Required Components

The following components are required for this approach;

  1. Atmega328P microcontroller with the Arduino Bootloader installed
  2. Breadboard
  3. USB to serial/TTL Adapter
  4. 16MHz crystal oscillator
  5. 22pf capacitors x2
  6. 100nf capacitor
  7. Jumper Wires
  8. 100 ohms resistor
  9. LED

Schematic

Connect USB to Serial/TTL adapter to the microcontroller as shown in the schematics below. Don’t forget that this procedure will only work if the microcontroller has been flashed with a bootloader according to the procedure described in the last tutorial.

Schematics 1: USB to Serial Adapter and the Atmega328P

Most adapters can be configured to work at either 5v or 3.3v logic level. Ensure yours is configured to work on the 5v voltage level since supply to the microcontroller is 5v.

Uploading Code

Uploading code to the microcontroller after you are done with the connections, require no additional work asides, what you would have done if you where using an Arduino board. After typing in your code, select the port to which your adapter is connected, followed by the board type and hit the upload button. Upload takes only a few seconds, same as the Arduino board.

Note: when programming the Atmega328p MCU using the Arduino IDE, the matching board type you have to select is the “Arduino Duemilanove or Nano w/ ATmega328” board.

To test the setup, we will use the Arduino blink example. Select the example and click upload. You should see the connected LED start blinking after a while.

Using an Arduino Board

The second approach involves the use of an Arduino board in either of two similar ways;

  1. By replacing the microcontroller on the Arduino Uno with the one to be programmed
  2. By using any of the Arduino boards as an In-system programmer.

The first mode is the easiest way to upload code to the microcontroller, as it involves just replacing the microcontroller on the Uno, with the one to be programmed. However, this may not be the best when prototyping as the move of the chip from the Arduino to the project, back and forth, could lead to the pins of the microcontroller being damaged. Another downside to this is that it only works with the Arduino Uno as all other Arduino boards, use SMD type of microcontrollers which makes replacement impractical and development, expensive.

So no schematic for this, just swap the microcontroller and hit upload.

The second method involves the use of the Arduino Uno as an In-system programmer.

Required components

To use this approach, you will need the following components;

  1. Arduino Uno
  2. Breadboard
  3. USB to serial/TTL Adapter
  4. 16MHz crystal oscillator
  5. 22pf capacitors x2
  6. Jumper Wires
  7. 10k resistor
  8. 100 ohms resistor
  9. LED

Schematics

Connect the components as shown in the schematics below.

Programming Atmeg328p with the Arduino Uno

While using this approach, it is important to remove the microcontroller of the Arduino board to prevent interference.

Upload Code

Code upload process is the same as already described. Type the code to be uploaded or select an example -> select the board type (Duemilanove or Nano W/atmeg328), select the correct port and click upload. The code will be uploaded to the microcontroller.

After successful code upload using any of the approaches described above, the Arduino or USB – Serial/TTL converter can be disconnected and the project connected to a battery to run on standalone as shown in the image below.

Programmed Atmega328p Microcontroller

That’s it for this tutorial guys, thanks for following.

Feel free to drop questions and comments under the comment section, I will do my best to respond to them asap.

Источник

Программатор из Arduino

В своих проектах я использую ранее описанную минимальную обвязку на микроконтроллере Atmega328p. На базе такой схемы я делаю различные устройства которые отлично работают. И к тому же, в них я могу записать обычный скетч через среду Arduino IDE. Чтобы записать скетч в микроконтроллер Atmega328p, на понадобиться Arduino UNO или Arduino Nano.

Тоесть чтобы мне прошить «почти плату Ардуино», мне нужна еще одна Ардуинка.
На самом деле. Arduino UNO или nano выступает здесь в роли программатора. Но для этого нам необходимо подготовить все для прошивки.

Делаем из Arduino UNO программатор.

Открываем Arduino IDE, далее Файл — Примеры — 11.ArduinoIsISP — ArduinoISP.

Откроется скетч который загружаем в обычную плату Arduino UNO. Этот скетч и сделает из нее программатор, с помощью которого и будем загружать прошивку в контроллер.

Теперь необходимо подготовить адаптер для соединения платы Ардуино и разъема для программирования вашего устройства. В моем примере универсального контроллера я использую простые соединительные провода Мама-Папа.
Распиновка следующая:

Arduino Устройство
GND GND
5V +5v
10 RST
11 MOSI
12 MISO
13 SCK

В своих проектах я предусматриваю разъемы для внутрисхемного программирования ICSP. Если раньше я делал штырьковый разъем 2*3 с шагом 2,54мм, то теперь я использую специальную прищепку с контактами pogopin. В моем примере соединяю их вот так:

Если бывает небольшой конвейер по загрузке программ в контроллеры, меня выручает одна хитрость. Я достал с одной из сторон соединительных проводов, где мамы, пластиковые корпуса. И сам металлический контакт Мама установил в готовый пластиковый разъем типа 2*3. Так гораздо удобнее подключать и маловероятно что можно перепутать.

С подключением разобрались.
Следующий шаг. Открываем скетч который необходимо загрузить в наше устройство. Далее необходимо настроить Arduino IDE чтобы использовала Arduino UNO как программатор. Для этого нажимаем Инструменты — Программатор: и в выпадающем списке выбираем «Arduino as ISP».

Теперь необходимо нажать на пункт Записать загрузчик. Там же, в инструментах.
Если вы все верно настроили, вы получите сообщение «Запись загрузчика завершена».

Теперь можно приступать к загрузке скетча. Нажимаем Скетч — Загрузить через программатор. После этого должна начаться загрузка скетча в ваше устройство с микроконтроллером Atmega328p через другую Arduino UNO.

После успешной загрузки, будет сообщение «Загрузка завершена». А на моей плате включиться светодиод, который мне говорит о том что код записался верно и без ошибок.

Мы с вами разобрались что для своих проектов без проблем можно использовать микроконтроллер Atmega328p, писать для него код и прошивать через Arduino IDE. При этом без проблем работает внутрисхемное программирование через разъем ICSP. Данный способ кстати подойдет и для загрузки скетчей в Arduino micro.

Источник

From Arduino to a Microcontroller on a Breadboard

This tutorial explains how to migrate from an Arduino board to a standalone microcontroller on a breadboard. It’s similar to this tutorial, but uses an Arduino board to program the ATmega on the breadboard.

Unless you choose to use the minimal configuration described at the end of this tutorial, you’ll need four components (besides the Arduino, ATmega328P, and breadboard):

a 16 MHz crystal,

a 10k resistor, and

two 18 to 22 picofarad (ceramic) capacitors.

Burning the Bootloader

If you have a new ATmega328P (or ATmega168), you’ll need to burn the bootloader onto it. You can do this using an Arduino board as an in-system program (ISP). If the microcontroller already has the bootloader on it (e.g. because you took it out of an Arduino board or ordered an already-bootloaded ATmega), you can skip this section.

To burn the bootloader, follow these steps:

Upload the ArduinoISP sketch onto your Arduino board. (You’ll need to select the board and serial port from the Tools menu that correspond to your board.)

Wire up the Arduino board and microcontroller as shown in the diagram to the right.

Select «Arduino Duemilanove or Nano w/ ATmega328» from the Tools > Board menu. (Or «ATmega328 on a breadboard (8 MHz internal clock)» if using the minimal configuration described below.)

Select «Arduino as ISP» from Tools > Programmer

Run Tools > Burn Bootloader

You should only need to burn the bootloader once. After you’ve done so, you can remove the jumper wires connected to pins 10, 11, 12, and 13 of the Arduino board.

Using an Arduino board to burn the bootloader onto an ATmega on a breadboard.

Uploading Using an Arduino Board

Once your ATmega328P has the Arduino bootloader on it, you can upload programs to it using the USB-to-serial convertor (FTDI chip) on an Arduino board. To do, you remove the microcontroller from the Arduino board so the FTDI chip can talk to the microcontroller on the breadboard instead. The diagram at right shows how to connect the RX and TX lines from the Arduino board to the ATmega on the breadboard. To program the microcontroller, select «Arduino Duemilanove or Nano w/ ATmega328» from the the Tools > Board menu (or «ATmega328 on a breadboard (8 MHz internal clock)» if you’re using the minimal configuration described below). Then upload as usual.

Uploading sketches to an ATmega on a breadboard. Remember to remove the microcontroller from the Arduino board!

Minimal Circuit (Eliminating the External Clock)

If you don’t have the extra 16 MHz crystal and 18-22 picofarad capacitors used in the above examples, you can configure the ATmega328P to use its internal 8 MHz RC oscillator as a clock source instead. (You don’t really need the 10K pullup resistor on the reset pin either, so we remove it to get a truly minimal configuration.)

You’ll need to install support for an additional hardware configuration:

Download this hardware configuration archive: breadboard-1-6-x.zip, Breadboard1-5-x.zip or Breadboard1-0-x.zip depending on which IDE you use.

Create a «hardware» sub-folder in your Arduino sketchbook folder (whose location you can find in the Arduino preferences dialog). If you’ve previously installed support for additional hardware configuration, you may already have a «hardware» folder in your sketchbook.

Move the breadboard folder from the zip archive to the «hardware» folder of your Arduino sketchbook.

Restart the Arduino software.

You should see «ATmega328 on a breadboard (8 MHz internal clock)» in the Tools > Board menu.

Once you’ve done this, you can burn the bootloader and upload programs onto your ATmega328P as described above. Be sure to select «ATmega328 on a breadboard (8 MHz internal clock)» when burning the bootloader. (If you select the wrong item and configure the microcontroller to use an external clock, it won’t work unless you connect one.)

Attention

This procedure works on Arduino 1.0.x software.

Using an Arduino board to burn the bootloader onto an ATmega on a breadboard (w/o an external clock).

Uploading sketches to an ATmega on a breadboard.

Getting Rid of the Arduino Board

Once you’ve programmed the ATmega on the breadboard, you can eliminate the Arduino. To do so, you’ll need to provide an alternative power supply for the microcontroller. See the standalone Arduino on a breadboard tutorial for details.

Источник

Adblock
detector