Avr gcc mac os

Avr gcc mac os

Here is a ‘generic’ step-by-step to getting an AVR development platform going on your computer using the free AVR toolchain (avr-gcc, avr-libc and avrdude) Pretty much every project uses this toolset so its a good way to get going

The following two methods both place all of the files in the /usr/local/bin directory in the hard driver. Unfortunately that directory is not in the default path. That means that when you type avrdude into the terminal it cant figure out where to look. In this prep-step you’ll change the profile of your Terminal to add /usr/local/bin to the path.

Find the Terminal program, you’ll be using this to do most of this stuff. Its in the Applications/Utilities folder

In the new Terminal window, type in echo $SHELL and press return

If the output is /bin/bash then type the following command:
echo ‘PATH=$PATH:/usr/local/bin’ >>

/.bash_profile
all on one line. Press return.

If the output is /bin/csh or /bin/tcsh then type the following command:
echo ‘set path = ($path /usr/local/bin)’ >>

/.cshrc
all on one line. Press return.

Close any Terminal windows and open up a new one. This makes sure the .bash_profile or .cshrc is reloaded. Now type in echo $PATH (for bash) or echo $path (for t/csh) you should get something like the following:

The important thing is that at the end of the line is /usr/local/bin

This is the suggested method

Download the ready to go nice package from ObDev, I havent tried it but a friendly email’er said its great.

This isnt suggested, and is an older method, but we leave the documentation here in case its handy

You will need make which is included in XCode, as OSX-AVR doesn’t come with it (ugh)

Step 1. Download and install the mac developer tools (XCode).

You need to have make installed, but it doesn’t come with the OSXAVR package. You can try installing it with fink, which will require a lot less space but the following is guaranteed. If you want to have the latest avr-gcc you may also have to do it the «old way» which guarantees the most recent tools will be installed.

To install XCode you will need the official packages. These are available on your Mac OS X Install CD, or from apple at: apple developer tools. The file is about 900MB so unless you have a fast connection I strongly encourage grabbing it off of the Install CDs that came with your Mac (you do still have those, right?) Basically we need the native Mac OS X compiler tools so that we can generate the AVR compiler tools.

Читайте также:  Pascal free ��� mac os

There’s finally a good/fast way of installing all these tools under Mac OS X PPC or i386! First, download the OSX-AVR packge for PPC (older macs) or i386 (Intel macs, latest ones) from sourceforge.

Run the OSX-AVR.mpkg

(Images of installation and process are forthcoming but its rather easy so go ahead and try it anyways)

Don’t forget you have to install XCode as make doesn’t come with this package.

Can’t get it working? Dont worry, help is available in the forums!

This is the advanced method, for when you need bleeding-edge development and hackability. Not suggested

The following steps are essentially the same for MacOS X or Linux, BSD or any other unixy OS. This is the ‘old style’ of installing avr-gcc, its longer and more tedious but you are guaranteed to have the latest version.

(Note that this doesn’t seem to work on Intel Macs for unknown reasons, we’re investigating. )

Leah Buchley has an excellent tutorial, and you should follow it. I’ve reduplicated it here in case the site goes down. (also with a few minor ‘improvements’ and images

Step 2. Download & install binutils (an essential utility for the C compiler)

Download the current release of binutils from : http://www.gnu.org/software/binutils/ (you can also go straight to the download site here) For these examples, we’ll be using binutils-2.17.tar.gz but you should use whatever is most recent. Save it into your home directory, not the desktop.

Decompress the downloaded file and double click on it to decompress it (or use Stuffit Expander, in the Applications folder). You should now have a folder called binutils-2.17 which you should drag into your Home directory

Open up a Terminal window and navigate to the binutils directory. Type: cd binutils-2.17 (or whatever you downloaded) theb type in ls to verify everythings there

Configure binutils for AVR. type: ./configure —target=avr
this will start a long process that will spit out a lot of text.

Once its done, compile binutils. type: make
this will start an even longer compilation process

Once that’s done, install binutils. type: sudo make install
You will be prompted to enter your password. Only administrators can install software thats why the password is necessary.

Step 3. Download & install gcc (the C compiler)
First, download the current release of gcc from: http://gcc.gnu.org/mirrors.html currently thats gcc 4.2.0

Decompress the downloaded file and put the decompressed folder in your home directory. Open up a new Terminal window in your home directory, type cd gcc-4.2.0 and then ls to verify its all in there.

Next, c reate another directory to install gcc into.
type: cd .. to go back into the home directory, then
type: mkdir avrgcc-4.2 (substituting your gcc version for the 4.2)
Navigate to the folder you created.
type: cd avrgcc-4.2 (or whatever you named your folder)
C onfigure gcc for AVR.
Type: ../gcc-4.2.0/configure —target=avr —enable-languages=c —disable-libssp
(substituting the name of the folder you decompressed for the gcc-4.2.0)
**thanks to Seth Raphael for the —disable-libssp ti p

Читайте также:  Image software windows free

Once the configuration is done, compile gcc.
type: make CC=»cc —no-cpp-precomp»

This will take a long time so go have a sandwich

When its done and you’ve washed your plate and silverware, install gcc. type: sudo make install
and enter your password when prompted

Step 4. Download and install avr-libc (an essential C library for AVR chips)

Decompress the downloaded file and put the decompressed folder in your home directory

In a new Terminal window, navigagte to the avr-libc directory. from your home directory
type: cd avr-libc-1.4.6 (or whatever you downloaded)

Configure avr-libc. type: ./configure —host=avr

Compile avr-libc. type: make

Install avr-libc. type: sudo make install

Step 5. Download and install avrdude (the software that loads programs from your machine onto the chips)

Decompress the downloaded file and put the decompressed folder in your home directory

In a Terminal window, navigate to the avrdude directory. From your home directory type: cd avrdude-5.2 (or whatever you downloaded)
Configure avrdude. type: ./configure
Compile avrdude. type: make
Install avrdude. type: sudo make install

Yay all the software is installed!

Can’t get it working? Dont worry, help is available in the forums!

Источник

Как скомпилировать и записать код на микросхему AVR в Linux / MacOSX / Windows?

Это краткое руководство для начинающих, которое направлено на то, чтобы показать, как установить инструменты, скомпилировать код с помощью avr-gcc и отправить его в микроконтроллер с помощью avrdude.

Оно также знакомит с основами автоматизации этой задачи, помещая все инструкции в Makefile. Файлы примера ( main.c, main.bin, main.hex, Makefile) упакованы в архив который можно скачать по ссылке в конце данной статьи.

1. Установка avr-gcc и инструментов

Для компиляции исходного кода вашей прошивки на C и/или C ++ вам понадобится компилятор gcc-avr, библиотека C avr-libc и avrdude. Что очень полезно, существуют полные и простые в установке пакеты для всех основных платформ.

Linux, Ubuntu

Ubuntu предоставляет пакеты, поэтому вы можете просто установить их с помощью этой команды:

Mac OSX

Загрузите AVR MacPack. В образе диска MacPack есть установщик, который все сделает за вас.

Windows

Загрузите WinAVR, который включает в себя все необходимое и имеет хороший установщик.

2. Компиляция и запись кода

Теперь, когда у вас установлен компилятор, следующий шаг — скомпилировать простой исходный код в файл .BIN, затем сгенерировать файл Intel .HEX и, наконец, записать этот файл .HEX на микросхему AVR с помощью программатора для AVR.

Пример кода

Вот пример содержимого файла main.c. Код ничего не делает, кроме зацикливания в бесконечном цикле, но это для примера.

Компиляция

Приведенная ниже команда скомпилирует ваш код. Это GCC, поэтому я полагаю, что он вам знаком, и никакой дополнительной информации не требуется. Если вы хотите выполнить компиляцию для другого MCU, вам нужно указать соответствующую опцию -mmcu.

Читайте также:  Windows не распознает тип файла

После успешной компиляции вы можете проверить размер памяти программы и данных с помощью этой команды:

AVR Memory Usage
—————-
Device: Unknown
Program: 40 bytes
(.text + .data + .bootloader)
Data: 0 bytes
(.data + .bss + .noinit)

Создание .HEX

Большинство программаторов не принимают в качестве входного файла исполняемый файл GNU. Поэтому нам нужно проделать некоторую работу.

Итак, следующий шаг — преобразование информационной формы .BIN в файл .HEX. Утилита GNU, которая делает это, называется avr-objcopy.

Программирование

Утилита под названием avrdude может программировать микропроцессоры, используя содержимое файлов .HEX, указанных в командной строке.

С помощью приведенной ниже команды файл main.hex будет записан во флэш-память. Параметр -p attiny13 позволяет avrdude узнать, что мы работаем с микроконтроллером ATtiny13. Другими словами — эта опция определяет устройство.

Полный список поддерживаемых чипов можно найти здесь. Обратите внимание, что также допустимо использовать и полные имена (т. е. t13 равно attiny13).

И вуаля! Чип запрограммирован.

3. Make и makefiles

Теперь мы можем автоматизировать этот процесс, создав Makefile и поместив туда наши команды. Структура Makefile очень проста, и дополнительную информацию о ней можно найти здесь . Утилита make автоматически считывает файл Makefile в папке, в которой вы ее запускаете. Взгляните на готовый пример:

Если вы запустите в терминале простую команду make , будет выполнена только метка «all». При запуске (sudo) make flash будет выполнена метка «flash» и так далее.

avr-gcc -std=c99 -Wall -g -Os -mmcu=attiny13 -DF_CPU=1200000 -I. -o main.bin main.c
avr-objcopy -j .text -j .data -O ihex main.bin main.hex

avrdude -p attiny13 -c usbasp -U flash:w:main.hex:i -F -P usb

avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: AVR device initialized and ready to accept instructions

avrdude: Device signature = 0x1e9007
avrdude: NOTE: «flash» memory has been specified, an erase cycle will be performed
To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: reading input file «main.hex»
avrdude: writing flash (40 bytes):

avrdude: 40 bytes of flash written
avrdude: verifying flash memory against main.hex:
avrdude: load data flash data from input file main.hex:
avrdude: input file main.hex contains 40 bytes
avrdude: reading on-chip flash data:

avrdude: verifying …
avrdude: 40 bytes of flash verified

avrdude: safemode: Fuses OK (H:FF, E:FF, L:6A)

avrdude done. Thank you.

Резюме

По сути, если предположить, что наша программа находится в main.c , только эти три вещи необходимы для компиляции и записи кода на чип AVR.

  1. $ avr-gcc -Wall -g -Os -mmcu=attiny13 -o main.bin main.c
  2. $ avr-objcopy -j .text -j .data -O ihex main.bin main.hex
  3. $ avrdude -p attiny13 -c usbasp -U flash:w:main.hex:i -F -P usb

Важно подчеркнуть, что мы можем легко автоматизировать весь процесс с помощью Makefiles. Рано или поздно она вам понадобится!

Скачать файлы примера (2,1 KiB, скачано: 173)

Источник

Оцените статью