Timeouts
Previous versions of jtag2updi could get hung up waiting for a target that wasn’t working (for example, because it was connected incorrectly) or the host (for example, if you entered a slow command, like reading a 128k flash memory when you didn’t intend to, and ctrl-c hoping to «save time»), requiring a reset to reconnect to it. This version has timeouts on communication with both the host (250ms — it gives up and assumes the host isn’t going to sat anything after three timeouts, and awaits a fresh session from avrdude), and when talking to the target (100ms — which is far more time than the target should ever take to respond). In the event of a timeout communicating with the target, it will return RSP_NO_TARGET_POWER response. The host timeout of course prevents terminal mode from working (target timeout should just prevent hangs without downside)
Both can be disabled by uncommenting #define DISABLE_TARGET_TIMEOUT and/or #define DISABLE_HOST_TIMEOUT in sys.h — the latter should uncommented if terminal mode is to be used, and should remain commented out if terminal mode will not be used.
Build
Building AVRDUDE for Windows
Windows Prerequisites
In order to build AVRDUDE on Windows, you need:
Microsoft Visual Studio 2019 with ‘Desktop development with C++’ enabled
Windows Build Instructions
To build AVRDUDE on Windows, do the following:
- Open the solution and build the project.
Note: The folder includes pre-built files from the AVRDUDE configure and grammar generation.
Building AVRDUDE for Linux
Note that the AVRDUDE for Linux version does not contain all extra Windows features. The features that have been added to the stock version of AVRDUDE include:
- Support Micronucleus bootloader
- Support Teensy HalfKay bootloader
Linux Prerequisites
In order to build AVRDUDE on Linux, you need to install the following packages:
sudo apt install git make gcc automake libtool flex bison libelf-dev libusb-dev libftdi1-dev libhidapi-dev
Linux Build Instructions
To build AVRDUDE on Linux, run the following commands:
git clone --branch windows https://github.com/mariusgreuel/avrdude cd avrdude ./bootstrap ./configure make
To install a local build of AVRDUDE on your system, run the following command:
sudo make install
Linux udev rules
If you intent to use either the Micronucleus or Teensy bootloader, you should edit the udev rules so that you can run AVRDUDE without root.
For instance, if you are on Ubuntu and you installed the avrdude package, you would edit and add the following rules:
# Micronucleus Bootloader SUBSYSTEM=="usb", ATTR{idVendor}=="16d0", ATTR{idProduct}=="0753", TAG+="uaccess" # Teensy Bootloader SUBSYSTEM=="usb", ATTR{idVendor}=="16c0", ATTR{idProduct}=="0478", TAG+="uaccess"
Main features
The major features of AVRDUDE include:
|
Troubleshooting
If you have triple-checked all the connections but still getting errors, the problem might be the speed of the serial links. I have set the jtag2updi entry on the avrdude configuration file to run at 115200 baud by default. This baud rate can cause errors if, for example, your MCU is running at 8MHz.
This can be changed with the avrdude «-b» option. Valid baud rates are 2400, 4800, 9600, 14400, 19200, 38400, 57600 and 115200. You can make the setting permanent by editing the jtag2updi entry on «avrdude.conf».
If the trouble is on the UPDI link, a slower speed can be selected by changing UPDI_BAUD and recompiling.
You can also try to use the alternate bit banging USART by setting UPDI_IO_TYPE to 2.
You will find these and other configuration settings in the «sys.h» header file.
Sometimes, the programmer can become irresponsive, in that case it should be reset.
Building with Arduino IDE
If you prefer, the program can be built as if it was an Arduino sketch. Inside the «source» directory, there is an empty file called «jtag2updi.ino» so that the Arduino IDE can recognize the source code.
Just copy all the files inside «source» to a new directory called «jtag2updi» inside your sketch main directory.
The Arduino IDE will automatically set the correct MCU model and F_CPU, but if you want to change the speed of the UPDI link, you will have to edit UPDI_BAUD directly in the source code.
When building for Logic Green AVR clones, I recommend that you install the board definitions from dbuezas (https://github.com/dbuezas/lgt8fx).
This version allows selection of the MCU running speed, unlike the official release (Larduino_HSP)
Note:
By default, the following pins are used for UPDI communication on common Arduino boards:
- Arduino Mega (1280/2560): PD3 -> Digital Pin 18
- Arduino (328P): PD6 -> Digital Pin 6
Установка AVRDUDE для Windows
На официальном сайте программы http://www.nongnu.org/avrdude/ в разделе для скачивания файлов http://download.savannah.gnu.org/releases/avrdude/
можно скачать все нужные файлы, в том числе и исходный код.
Я собрал в один архив AVRDUDE. 5.11 для Windows с документацией и необходимыми драйверами. Вы можете воспользоваться этой ссылкой, чтобы СКАЧАТЬ AVRDUDE. 5.11 для Windows. Просто скачайте и распакуйте содержимое архива в папку на диске. Далее в примерах будет подразумеваться, что это папка C:\avrdude\
Если используем LPT программатор, запускаем файл install_giveio.bat. Этот пакетный файл установит драйвер прямого доступа к портам (giveio.sys)
Если Вы используете программатор usbasp, обратите внимание на папку usbasp-windriver.2011-05-28. В ней находятся драйвера, их так же следует установить
Building with avr-gcc
To build, run the make.bat file, after editing it with the following options:
- path of AVR-GCC on your system
- correct target MCU
- Frequency at which your MCU is running (F_CPU, defaults to 16MHz)
- Baud rate of UPDI link (UPDI_BAUD, defaults to 225 kbaud)
I provide a makefile suitable for a MS-Windows environment, but I’m sure Linux users can manage.
The pre-built hex file is for ATMega 328P@16MHz; to use a different MCU of the same family, like the mega168, or running at a frequency different from 16MHz, you will need to rebuild.
When building for Logic Green AVR clones, select «atmega328p» as target. The macro ARDUINO_AVR_LARDU_328E must also be defined, either in the «sys.h» file (using #define) or in the gcc command line (by adding -DARDUINO_AVR_LARDU_328E). This allows the code to know the target is a LGT chip, and set the chip core speed at run time from F_CPU. Recommended values for F_CPU are 32MHz or 16MHz; 8MHz also works but is less reliable.
Using with avrdude
It has been modified to work with avrdude 6.3, by removing (actually, commenting out) some incompatible stuff, and adding the «jtag2updi» programmer type.
The definitions for UPDI chips were slightly modified so that avrdude thinks they use the PDI programming interface instead of UPDI (i.e., avrdude thinks they are some kind of XMegas).
This allows the jtagice mk2 protocol to be used for programming UPDI chips, since this protocol predates UPDI and is not formally compatible with it. Originally, I had planed to use the STK500v2 protocol, and emulate the ISP interface, and I actually wrote an ISP version of the programmer software.
However, this would require entirely new definitions for the UPDI chips inside the avrdude.conf file, while using jtagice2 requires only very slight changes to the definions provided by Atmel (now Microchip).
Note:
If you install the Arduino board «Nano Every» in your Arduino IDE, it will come with versions of avrdude and avrdude.conf files that support jtag2updi. You can use those files instead of the compatibility avrdude.conf supplied here which is meant for older avrdude versions.
Jtagice mk2 is the most advanced of Atmel’s programming protocols that still supports a UART serial connection instead of USB, making it easily compatible with any Arduino you choose to host this software, and any OS you run avrdude on.
It’s major limitation is speed; it can’t go over 115200 Baud, because the protocol lacks definitions for higher speeds. It’s actually inferior to the STK500v2 protocol in this respect, this older standard can run at any speed avrdude instructs it to.
Fortunately, the current UPDI chips do not have very large flash memories, so I think this isn’t a major issue.
Example command line (windows):
avrdude -c jtag2updi -P com7 -p t1614
If all the connections are correct and the target is indeed an unlocked tiny1614, the output will be:
avrdude: AVR device initialized and ready to accept instructions Reading | ################################################## | 100% 0.03s avrdude: Device signature = 0x1e9422 (probably t1614) avrdude done. Thank you.
If the chip is locked, the output will be:
avrdude: jtagmkII_reset(): bad response to reset command: RSP_ILLEGAL_MCU_STATE avrdude: initialization failed, rc=-1 Double check connections and try again, or use -F to override this check. avrdude: jtagmkII_close(): bad response to sign-off command: RSP_ILLEGAL_MCU_STATE avrdude done. Thank you.
To unlock the chip, you need to erase it, using the -e option on avrdude:
avrdude -c jtag2updi -P com7 -p t1614 -e
Alternatively, you can erase the chip from interactive mode, enter it using «-t», and «-F» to override the error:
Note: You must build with DISABLE_HOST_TIMEOUT defined for terminal mode to work. See below for more information on the timeouts.
avrdude -c jtag2updi -P com7 -p t1614 -t -F
You will enter the avrdude prompt:
avrdude: jtagmkII_reset(): bad response to reset command: RSP_ILLEGAL_MCU_STATE avrdude: initialization failed, rc=-1 avrdude: AVR device initialized and ready to accept instructions avrdude: Device signature = 0xffff00 avrdude: Expected signature for ATtiny1614 is 1E 94 22 avrdude: NOTE: Programmer supports page erase for Xmega devices. Each page will be erased before programming it, but no chip erase is performed. To disable page erases, specify the -D option; for a chip-erase, use the -e option. avrdude>
Enter «erase» then «quit» and the chip will be unlocked (and erased).
avrdude> erase >>> erase avrdude: erasing chip avrdude> quit >>> quit avrdude done. Thank you.
Решение
Разработку, прошивку и дальнейшее описание буду вести на Debian 9, но все необходимые компоненты есть и под Windows.
Подготовка окружения
Первым делом подготовим окружение, как писал выше: разработка на C, компиляция прошивки средствами avr-gcc, загрузка прошивки средствами avrdude, через программатор USBasp.
Для установки необходимого собрал следующий набор:
# apt-get install avr-libc gcc-avr binutils-avr avrdude
В Debian драйвера для USBasp устанавливать не надо, они есть в составе ядра. Для Windows необходимо скачать и установить драйвер с сайта разработчика fischl.de.
Подключение оборудования
На данном этапе не должно вызвать вопросов, но для порядка опишу подключение. Подключаем микроконтроллер к программатору USBasp: выводы SCK, MISO, MOSI, RESET, VCC. Так же не забываем к выходу D0 через резистор 220 Ом подключить анод светодиода, катод к GND.
Написание кода
На данный момент нет разницы в чем будет написан код, для себя выбрал Atom. Создаем файл с расширением .c, например main.c, в котором напишем код мигания светодиодом:
#define F_CPU 16000000UL // Частота работы МК от внешнего кварца #include <avr/io.h> #include <util/delay.h> void main() { DDRD = 0xFF; // Все выводы порта D как выход PORTD = 0x00; // На всех выводах установим 0 while (1) { PORTD |= (1 << PD0); // Включаем светодиод _delay_ms(1000); // Ждем 1 секунду PORTD &= ~(1 << PD0); // Выключаем светодиод _delay_ms(1000); // Ждем 1 секунду } }
Первой строкой явно указываю частоту с которой должен работать МК, т.к. у меня подключен внешний кварцевый резонатор на 16 МГц. Остальное ясно из комментариев.
Компиляция кода
Для компиляции будем пользоваться двумя командами(полного описания команд и их ключей приводить не буду, ибо каждая из них повод для отдельных статей и они легко находятся в интернете):
avr-gcc — производит компиляцию C в объектный файл.
К данной команде используем ключи:
- -mmcu для указания типа МК, в данном случае ATmega 328P;
- -DF_CPU для указания частоты с которой работает МК.
avr-gcc -g -Os -mmcu=atmega328p -DF_CPU=16000000UL main.c -o main.o
После выполнения команды в каталоге появится файл main.o
avr-objcopy — производит преобразование объектного файла в hex.
avr-objcopy -O ihex main.o main.hex
После выполнения команды в каталоге появится файл main.hex. Файл прошивки готов, необходимо загрузить его на МК.
Ссылки ни на какие статьи не привожу, т.к. просмотренные не содержат полного описания, только отрывочные сведения.
Загрузка прошивки в МК
!!! Внимание Настоятельно рекомендую перед выполнением команды avrdude ознакомиться с описанием ключей и все операции производить только после проверки написанного, во избежание окиричивания МК. Все дальнейшие расчеты на свой страх и риск!. Воспользуемся утилитой avrdude, к данной команде используем ключи:
Воспользуемся утилитой avrdude, к данной команде используем ключи:
- -c для указания программатора, в данном случае USBasp;
- -p для указания типа МК, в данном случае ATmega 328P;
- -U ключ для указания с каким типом памяти мы работаем, что именно делаем, и указываем файл источник/приемник. В данном случает производится запись во flas-память МК из файла main.hex.
avrdude -c usbasp -p atmega328p -U flash:w:main.hex
После выполнения команды МК оживает и начинает выполнять заложенные в код алгоритмы.
Изменение FUSE-битов
!!! Внимание Настоятельно рекомендую перед выполнением команды avrdude ознакомиться с описанием ключей и все операции производить только после проверки написанного, во избежание окиричивания МК. Все дальнейшие расчеты на свой страх и риск!. Но не все так гладко
В коде между включением и выключением указана задержка в 1 секунду, а на практике светодиод горит более 10 секунд. Вооружился секундомером, замер показал 16 секунд. Получается МК работает на частоте 1 МГц, вместо 16 МГц
Но не все так гладко. В коде между включением и выключением указана задержка в 1 секунду, а на практике светодиод горит более 10 секунд. Вооружился секундомером, замер показал 16 секунд. Получается МК работает на частоте 1 МГц, вместо 16 МГц.
Чтение документации показало, что необходимо МК указать на какой частоте он должен работать при подключении внешнего кварцевого резонатора. Для ATmega 328P указывается 3 байтами: lock, lfuse, hfuse.
Для расчета значений этих байтов есть калькуляторы фьюзов, обязательно необходимо проверить получившиеся значения с документацией! Для себя собрал следующую команду:
avrdude -c usbasp -p atmega328p -U lock:w:0xFF:m -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m
После выполнения команды МК начал работать на положенной ему частоте.
Список поддерживаемых программаторов
FT2232D based generic programmer FT2232H based generic programmer FT232H based module from FTDI and Glyn.com.au Amontec JTAGKey, JTAGKey-Tiny and JTAGKey2 Atmel AVR ISP Atmel AVR ISP V2 Atmel AVR ISP mkII The Bus Pirate Atmel STK500 Crossbow MIB510 programming board Atmel STK600 Avr910 USBasp USBtiny simple USB programmer Atmel Butterfly Development Board Atmel AppNote AVR109 Boot Loader Atmel AppNote AVR911 AVROSP Mikrokopter.de Butterfly Mikrokopter.de Butterfly Atmel JTAG ICE (mkI) Atmel JTAG ICE mkII in ISP mode Atmel AVR Dragon Jason Kyle`s pAVR Serial Programmer Brian Dean`s Programmer STK200 Pony Prog STK200 Dontronics DT006 Bascom SAMPLE programming cable Nightshade ALF-PgmAVR Steve Bolt`s Programmer Picoweb Programming Cable ABCmini Board, aka Dick Smith HOTCHIP Futurlec.com programming cable. Xilinx JTAG cable Direct AVR Parallel Access cable AT-ISP V1.1 programming cable for AVR-SDK1 ERE ISP-AVR Altera ByteBlaster Frank STK200 Atmel at89isp cable design ponyprog serial Lancos SI-Prog serial port banging
Hardware
Partlist
Partnumber | Value | Reichelt No |
---|---|---|
C1 | 4,7u | RAD 4,7/35 |
C2 | 100n | X7R-5 100N |
C3, C4 | 22p | KERKO 22P |
D1, D2 | 3V6 zener | ZF 3,6 |
CON1 | USB-B | USB BW |
CON2 | 10pol | WSL 10W |
IC1 | ATmega8-16 | ATMEGA 8-16 (not programmed!) |
JP1, JP2 | 2pol 2,54mm | SL 1X36G 2,54 |
LED1 | 3mm LED green | LED 3MM 2MA GN |
LED2 | 3mm LED red | LED 3MM 2MA RT |
Q1 | 12Mhz | 12,0000-HC49U-S |
R1, R2 | 68 | 1/4W 68 |
R3 | 2,2k | 1/4W 2,2k |
R4, R5, R6, R7 | 270 | 1/4W 270 |
R8 | 10k | 1/4W 10k |
R9, R10 | 1k | 1/4W 1k |
M1, M2 | Jumper | JUMPER 2,54GL SW |
M3 | Socket 28S | GS 28-S |
M4 | Case | TEKO 10007 |
M5 | PCB | — |
User PCB layouts
usbasp_single_side.t3001.zip by Thomas Fischl Single-Side PCB, TARGET 3001! layout file Size: 90×40 mm (optimized for case Hammond 1591ATBU) |
||
lv_usbasp.tar.gz by Pawel Szramowski (11/2007) With Low-voltage front-end. Single-Side PCB, EAGLE layout files, some SMD components |
||
by Bernhard Walle Double-Side PCB, EAGLE layout files, part list with order numbers for Reichelt.de and Conrad.de Size: optimized for case Hammond 1591ATBU |
||
http://thomaspfeifer.net/atmel_usb_programmer.htm by Thomas Pfeifer Single-Side PCB, PDF layout files, SMD components |
||
by Tomasz Ostrowski Single-Side PCB, PDF and EPS layout files, only four 0805 SMD parts, rest discrete components |
||
USBasp_CH.zip by Christian Heigemeyr Single-Side PCB, with some SMD 0805 components, PDF-files With additional buttons for reset and disconnection of the target |
||
USBasp.sch, USBasp.pcbComponentSide.pdf, TopSide.pdf, Schematics.pdf by Zhurov Pavel Single-Side PCB, P-CAD 2002 format and PDF files Crosspiece TXD and RXD are added for the ISP connector |
||
usbasp_gr.rar by J.A. de Groot The board is single sided (EAGLE format), measures 3 by 8 cm and uses only regular components. |
||
usbasb_mg.zip Single-Side PCB, eagle-format, with PS/PDF-files |
||
Tarball with layout Doubleside-Side PCB, SMD components, very small |
||
by Sergiy Bogdancev (01/2010) 3.3V version, ATMega48 only. Single-side PCB, ExpressPCB layout format + socket board for varies AVRs. |
||
Eaglefiles (sch/brd) and CAD case design (dxf) by Hans Hafner, HTL Mössingerstrasse-Klagenfurt, Österreich, hans.hafner (at) htl-klu (dot) at (01/2010) CNC-milled case (DXF file available), Eagle layout, only a few SMD parts |
||
Different USBasp versions: Easy to built non-smd, smd version and a very small USBasp by Sven Hedin (01/2011) Eagle files available. |
||
USB Key AVR Programmer by Fabio Baltieri (09/2011) Very small USB key like dimensions. SMD parts. |
||
AVR ISP Programmer by Jaroslav Vadel (04/2012) Small programmer. SMD parts. |
||
Target project and PDFs (layout/schematics) by Marius Schäfer (09/2013) |
||
by Stephan Bärwolf |
||
USBasp on breadboard with socket for controller daughter boards. by Fabian Hummel (11/2018) |
||
Tjaart van Aswegen designed an SMD board: DIP TRACE and GERBER files. by Tjaart van Aswegen (09/2019) |
||
Feature rich (e.g. different voltage levels, integrated USB to serial converter, USB-C connector) USBasp compatible design. |
||
USBasp with ZIF socket and through hole components. by Bruno (04/2020) |
||
USBasp board with additional 6pin header and selectable target supply (3.3V/off/5.0V). by Marty E. (10/2020) |
||
John included a 40 pin universal socket which takes 8, 14, 20 and 28 pin devices. He also added a versatile crystal oscillator with outputs of 1, 2, 4, 8 and 16 Mhz to clock the chips. There is also the standard 6pin ICSP connector and a user led connected to the MOSI pin. by John P. (11/2020) |
||
QUSBASP features a small size and flexibility (different connection options: USB-A or pin header, ICSP with 6 or 10 or pogo pins). by Qetesh (07/2021) |
Список поддерживаемых микроконтроллеров Atmel серии AVR
ATtiny11 ATtiny12 ATtiny13 ATtiny15 ATtiny4 ATtiny5 ATtiny9 ATtiny10 ATTINY26 ATTINY261 ATTINY461 ATTINY861 ATtiny88 ATtiny2313 ATtiny4313 ATtiny25 ATtiny45 ATtiny85 ATtiny24 ATtiny44 ATtiny84 AT90S1200 AT90S4414 AT90S2313 AT90S2333 AT90S2343 AT90S4433 AT90S4434 AT90S8515 AT90S8535 AT90CAN128 AT90CAN64 AT90CAN32 AT90PWM2 AT90PWM3 AT90PWM2B AT90PWM3B AT90USB646 AT90USB647 AT90USB1286 AT90USB1287 AT90USB162 AT90USB82 ATMEGA103 ATMEGA64 ATMEGA128 ATMEGA16 ATMEGA164P ATMEGA324P ATmega324PA ATMEGA644 ATMEGA644P ATMEGA1284P ATMEGA162 ATMEGA163 ATMEGA169 ATMEGA329 ATMEGA329P ATMEGA3290 ATMEGA3290P ATMEGA649 ATMEGA6490 ATMEGA32 ATMEGA161 ATMEGA8 ATMEGA8515 ATMEGA8535 ATMEGA48 ATMEGA88 ATMEGA88P ATMEGA168 ATMEGA168P ATMEGA328P ATMEGA640 ATMEGA1280 ATMEGA1281 ATMEGA2560 ATMEGA2561 ATMEGA128RFA1 ATmega32U4 ATmega32U2 ATmega16U2 ATmega8U2 ATMEGA325 ATMEGA645 ATMEGA3250 ATMEGA6450 ATXMEGA64A1 ATXMEGA128A1 ATXMEGA128A1REVD ATXMEGA192A1 ATXMEGA256A1 ATXMEGA64A3 ATXMEGA128A3 ATXMEGA192A3 ATXMEGA256A3 ATXMEGA256A3B ATXMEGA16A4 ATXMEGA32A4 ATXMEGA64A4 ATXMEGA128A4 AVR32UC3A0512
Main features
The major features of AVRDUDE include:
|
Troubleshooting Tips & Tricks
Atmel DFU Device driver broken
The current version of the Atmel DFU drivers that are distributed via the Windows Update are goofed up (@Atmel: It might have something to do with the fact that you commented out the CopyFiles sections!).
Symptoms are:
- You cannot use AVRDUDE to connect to an Atmel DFU device, and you get the error message «No matching USB device found».
- When installing the drivers via Windows Update, you get the error message «Windows encountered a problem installing the drivers for your device» and «A service installation section in this INF is invalid.»
- In Windows Device Manager, the Atmel DFU device shows up as an unknown device.
You should use an older driver package that does not contain this bug.
Outdated libusb0 driver
The most current version of libusb0.sys is 1.2.6.0, signed on 12/17/2012 by Travis Lee Robinson. If you are using an older version (check with Windows Device Manager), you may not be able to connect to your USB devices using the libusb0 driver.
History
AVRDUDE has once been started by Brian S. Dean as a private project
of an in-system programmer for the Atmel AVR microcontroller series,
as part of the Opensource and free software tools collection available for
these controllers. Originally, the software was written for the FreeBSD operating system,
maintained in a private CVS repository, and distributed under the name
avrprog.
Due to the growing interest in porting the software to other
operating systems, Brian
decided to make the project publically accessible on
savannah.nongnu.org. The name change to AVRDUDE has been chosen to
resolve the ambiguity with the avrprog utility as distributed
by Atmel together with their AVRstudio software.