Main elf error 1

Hello Altera Guys;    I am having problem building my software in NIOS II SBT 15.0 (eclipse) and I really need your great help.    I have this message on my console and I do not know how to solve this problem.    make all   Info: Building ../my_hello_world_bsp/  C:/altera/15.0/nios2eds/bin/gnu/H-x86...

— Quote Start —  

Hey, try clicking on auto assign base address in Qsys tool before generating the component. The .rwdata and .bss might not be within the memory space. 

Auto assign option is available in the system tab in Qsys tool. 

— Quote End —  

   

Hi expert,  

I have the same problem. Can any boby help me. How can i fix it. I tried to make auto assign but still the same thing. 

i got this error.  

i need your help !!!  

  

[BSP build complete] 

Info: Compiling hello_world.c to obj/default/hello_world.o 

nios2-elf-gcc -xc -MP -MMD -c -I../SDC_Top_Test_bsp//HAL/inc -I../SDC_Top_Test_bsp/ -I../SDC_Top_Test_bsp//drivers/inc -pipe -D__hal__ -DALT_NO_INSTRUCTION_EMULATION -DALT_SINGLE_THREADED -O0 -g -Wall -mno-hw-div -mno-hw-mul -mno-hw-mulx -mgpopt=global -o obj/default/hello_world.o hello_world.c 

Info: Linking SDC_Top_Test.elf 

nios2-elf-g++ -T’../SDC_Top_Test_bsp//linker.x’ -msys-crt0=’../SDC_Top_Test_bsp//obj/HAL/src/crt0.o’ -msys-lib=hal_bsp -L../SDC_Top_Test_bsp/ -Wl,-Map=SDC_Top_Test.map -O0 -g -Wall -mno-hw-div -mno-hw-mul -mno-hw-mulx -mgpopt=global -o SDC_Top_Test.elf obj/default/hello_world.o -lm -msys-lib=m 

c:/intelfpga/17.1/nios2eds/bin/gnu/h-x86_64-mingw32/bin/../lib/gcc/nios2-elf/5.3.0/../../../../../H-x86_64-mingw32/nios2-elf/bin/ld.exe: SDC_Top_Test.elf section `.text’ will not fit in region `onchip_memory2_0′ 

c:/intelfpga/17.1/nios2eds/bin/gnu/h-x86_64-mingw32/bin/../lib/gcc/nios2-elf/5.3.0/../../../../../H-x86_64-mingw32/nios2-elf/bin/ld.exe: address 0x16e84 of SDC_Top_Test.elf section `.rwdata’ is not within region `onchip_memory2_0′ 

c:/intelfpga/17.1/nios2eds/bin/gnu/h-x86_64-mingw32/bin/../lib/gcc/nios2-elf/5.3.0/../../../../../H-x86_64-mingw32/nios2-elf/bin/ld.exe: address 0x1929c of SDC_Top_Test.elf section `.bss’ is not within region `onchip_memory2_0′ 

c:/intelfpga/17.1/nios2eds/bin/gnu/h-x86_64-mingw32/bin/../lib/gcc/nios2-elf/5.3.0/../../../../../H-x86_64-mingw32/nios2-elf/bin/ld.exe: address 0x16e84 of SDC_Top_Test.elf section `.rwdata’ is not within region `onchip_memory2_0′ 

c:/intelfpga/17.1/nios2eds/bin/gnu/h-x86_64-mingw32/bin/../lib/gcc/nios2-elf/5.3.0/../../../../../H-x86_64-mingw32/nios2-elf/bin/ld.exe: address 0x1929c of SDC_Top_Test.elf section `.bss’ is not within region `onchip_memory2_0′ 

c:/intelfpga/17.1/nios2eds/bin/gnu/h-x86_64-mingw32/bin/../lib/gcc/nios2-elf/5.3.0/../../../../../H-x86_64-mingw32/nios2-elf/bin/ld.exe: region `onchip_memory2_0′ overflowed by 94876 bytes 

collect2.exe: error: ld returned 1 exit status 

make: *** [SDC_Top_Test.elf] Error 1 

 

13:00:31 Build Finished (took 6s.580ms)

Форум РадиоКот • Просмотр темы — Помогите слинковать проект

Сообщения без ответов | Активные темы

Часовой пояс: UTC + 3 часа

Список форумов » Микроконтроллеры и ПЛИС » AVR

ПРЯМО СЕЙЧАС:

Начать новую тему Ответить на тему  Страница 1 из 1  [ Сообщений: 8 ] 
 

Для печати

Предыдущая тема | Следующая тема 

Автор Сообщение

Не в сети

Заголовок сообщения: Помогите слинковать проект

СообщениеДобавлено: Вт сен 30, 2014 12:27:30 

Встал на лапы

Зарегистрирован: Пн дек 06, 2010 12:26:45
Сообщений: 98

Рейтинг сообщения: 0

Здравствуйте!

Помогите сделать makefile

вот часть кода где видно какие модули я использую (главный модуль main.c):

Код:

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>

#include «module1.c» //находится в каталоге рядом с main
#include «module2.c» //находится в каталоге рядом с main
#include «usbdrv/usbdrv.h» — это исходники из статьи  http://radiokot.ru/konkursCatDay2014/15/

выдает ошибку:
Linking: main.elf
avr-gcc -mmcu=atmega32 -I. -gdwarf-2 -DF_CPU=16000000UL -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=main.o -std=gnu99 -MMD -MP -MF .dep/main.elf.d main.o —output main.elf -Wl,-Map=main.map,—cref -lm
main.o: In function `RunTasks’:
C:………/main.c:66: undefined reference to `usbPoll’
main.o: In function `main’:
C:……../main.c:182: undefined reference to `usbInit’
make.exe: *** [main.elf] Error 1

раз ошибка линковщика то я предполагаю что makefile ошибочный, я его делал из sample

ругается как раз на функции и еще указатель из этой библиотеки

makefile прикрепил

что сделать???

Вложения:


makefile.rar [5.67 KiB]

Скачиваний: 100

Вернуться наверх
 

ПрофильПрофиль

 

Реклама

eess9

Не в сети

Заголовок сообщения: Re: Помогите слинковать проект

СообщениеДобавлено: Вт сен 30, 2014 14:52:29 

Вымогатель припоя
Аватар пользователя

Зарегистрирован: Ср фев 29, 2012 01:58:32
Сообщений: 672
Откуда: Харьков, Украина

Рейтинг сообщения: 0

undefined reference to `usbPoll’
main.o: In function `main’:
C:……../main.c:182: undefined reference to `usbInit’

Все же ясно написано, функции usbPoll и usbInit не найдены. Подключен ли файл с этими функциями в проект? Просто компановщик не может найти эти функции. Makefile тут, вроде, не при делах.

Вернуться наверх
 

ПрофильПрофиль

 

Реклама

vdavid

Не в сети

Заголовок сообщения: Re: Помогите слинковать проект

СообщениеДобавлено: Вт сен 30, 2014 17:24:46 

Мучитель микросхем

Карма: 8

Рейтинг сообщений: 101

Зарегистрирован: Чт ноя 13, 2008 16:33:42
Сообщений: 410

Рейтинг сообщения: 0

ESWANT
Добавьте в строку «SRC =» файл usbdrv/usbdrv.с
а в строку «ASRC =» файл usbdrv/usbdrvasm.S
Именно через пробел, без запятых.
И будет Вам счастье.

Вернуться наверх
 

ПрофильПрофиль

 

Реклама

PCBWay — всего $5 за 10 печатных плат, первый заказ для новых клиентов БЕСПЛАТЕН

Сборка печатных плат от $30 + БЕСПЛАТНАЯ доставка по всему миру + трафарет

Онлайн просмотровщик Gerber-файлов от PCBWay + Услуги 3D печати

ESWANT

Не в сети

Заголовок сообщения: Re: Помогите слинковать проект

СообщениеДобавлено: Ср окт 01, 2014 06:15:02 

Встал на лапы

Зарегистрирован: Пн дек 06, 2010 12:26:45
Сообщений: 98

Рейтинг сообщения: 0

vdavid писал(а):

ESWANT
Добавьте в строку «SRC =» файл usbdrv/usbdrv.с
а в строку «ASRC =» файл usbdrv/usbdrvasm.S
Именно через пробел, без запятых.
И будет Вам счастье.

Счастье не наступило где-то нагнал :cry:
make.exe: *** No rule to make target `main.elf’, needed by `elf’. Stop.

а написал вот как
# List C source files here. (C dependencies are automatically generated.)
SRC = $(TARGET).c usbdrv/usbdrv.с
………
ASRC = usbdrv/usbdrvasm.S

Вернуться наверх
 

ПрофильПрофиль

 

Реклама

Выгодные LED-драйверы для решения любых задач

КОМПЭЛ представляет со склада и под заказ широкий выбор LED-драйверов производства MEAN WELL, MOSO, Snappy, Inventronics, EagleRise. Линейки LED-драйверов этих компаний, выполненные по технологии Tunable White и имеющие возможность непосредственного встраивания в систему умного дома (димминг по шине KNX), перекрывают практически полный спектр применений: от простых световых указателей и декоративной подсветки до диммируемых по различным протоколам светильников внутреннего и наружного освещения.

Подобрать LED-драйвер>>

vdavid

Не в сети

Заголовок сообщения: Re: Помогите слинковать проект

СообщениеДобавлено: Ср окт 01, 2014 08:25:31 

Мучитель микросхем

Карма: 8

Рейтинг сообщений: 101

Зарегистрирован: Чт ноя 13, 2008 16:33:42
Сообщений: 410

Рейтинг сообщения: 0

ESWANT писал(а):

Счастье не наступило где-то нагнал

Убедитесь, что в папке usbdrv есть файлы usbdrv.c и usbdrvasm.S. Кроме того могут быть косяки с путем по умолчанию. Попробуйте из командной строки, находясь в папке проекта сделать male all.

Вернуться наверх
 

ПрофильПрофиль

 

Реклама

Реклама

LIMF – источники питания High-End от MORNSUN со стандартным функционалом на DIN-рейку

На склад Компэл поступили ИП MORNSUN (крепление на DIN-рейку) с выходной мощностью 240 и 480 Вт. Данные источники питания обладают 150% перегрузочной способностью, активной схемой коррекции коэффициента мощности (ККМ; PFC), наличием сухого контакта реле для контроля работоспособности (DC OK) и возможностью подстройки выходного напряжения. Источники питания выполнены в металлическом корпусе, ПП с компонентами покрыта лаком с двух сторон, что делает ее устойчивой к соляному туману и пыли. Изделия соответствуют требованиям ANSI/ISA 71.04-2013 G3 на устойчивость к коррозии, а также нормам ATEX для взрывоопасных зон.

Подробнее>>

ESWANT

Не в сети

Заголовок сообщения: Re: Помогите слинковать проект

СообщениеДобавлено: Ср окт 01, 2014 10:57:37 

Встал на лапы

Зарегистрирован: Пн дек 06, 2010 12:26:45
Сообщений: 98

Рейтинг сообщения: 0

vdavid писал(а):

ESWANT писал(а):

Счастье не наступило где-то нагнал

Убедитесь, что в папке usbdrv есть файлы usbdrv.c и usbdrvasm.S. Кроме того могут быть косяки с путем по умолчанию. Попробуйте из командной строки, находясь в папке проекта сделать male all.

файлы есть, из командной строки, такая же ошибка :cry:

а вообще попросить бы makefile у того товарища кто статью написал :)))

Вернуться наверх
 

ПрофильПрофиль

 

Реклама

vdavid

Не в сети

Заголовок сообщения: Re: Помогите слинковать проект

СообщениеДобавлено: Ср окт 01, 2014 11:14:20 

Мучитель микросхем

Карма: 8

Рейтинг сообщений: 101

Зарегистрирован: Чт ноя 13, 2008 16:33:42
Сообщений: 410

Рейтинг сообщения: 0

Скачал этот проект. Скомпилировал с Вашим makefile. Все нормально.

Код:

Size after:
AVR Memory Usage
———-
Device: atmega32

Program:    2390 bytes (7.3% Full)
(.text + .data + .bootloader)

Data:        208 bytes (10.2% Full)
(.data + .bss + .noinit)

ESWANT писал(а):

SRC = $(TARGET).c usbdrv/usbdrv.с

Ё-моё, так тут вместо латинской «c» русская «c». Я когда первоначально писал не заметил.

Вложения:


makefile.rar [4.86 KiB]

Скачиваний: 125

Вернуться наверх
 

ПрофильПрофиль

 

ESWANT

Не в сети

Заголовок сообщения: Re: Помогите слинковать проект

СообщениеДобавлено: Ср окт 01, 2014 11:54:04 

Встал на лапы

Зарегистрирован: Пн дек 06, 2010 12:26:45
Сообщений: 98

Рейтинг сообщения: 0

:))
Спасибо!!!
чё то собралось!!!!

Вернуться наверх
 

ПрофильПрофиль

 

Показать сообщения за:  Сортировать по:  Вернуться наверх
Начать новую тему Ответить на тему  Страница 1 из 1  [ Сообщений: 8 ] 

Часовой пояс: UTC + 3 часа

Список форумов » Микроконтроллеры и ПЛИС » AVR

Кто сейчас на форуме

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 8

Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете добавлять вложения

Найти:

Перейти:  

I am getting the following error when buildign my project in AVR Studio 6:
400 Id returned 1 exit status collect2.exe

And if I look at my output I have the following:

Building target: main.elf
    Invoking: AVR/GNU Linker : 3.4.2
    "C:Program Files (x86)AtmelAtmel ToolchainAVR8 GCCNative3.4.2.1002avr8-gnu-toolchainbinavr-gcc.exe" -o main.elf  eeprom.o panel6.o testmode.o uart.o AT45DB161.o delay.o dtmf.o keypad.o lcd.o main.o mcu.o menu.o remote_rx.o spi.o tx75x.o bootloader.o txcellular.o   -Wl,-Map="main.map" -Wl,--start-group  -Wl,--end-group -Wl,--gc-sections -mmcu=atmega64 
    c:/program files (x86)/atmel/atmel toolchain/avr8 gcc/native/3.4.2.1002/avr8-gnu-toolchain/bin/../lib/gcc/avr/4.7.2/../../../../avr/lib/avr5libc.a(cmpsf2.o):/data2/home/toolsbuild/jenkins-knuth/workspace/avr8-gnu-toolchain/src/avr-libc/libm/fplib/cmpsf2.S:58: multiple definition of `__ltsf2'
    c:/program files (x86)/atmel/atmel toolchain/avr8 gcc/native/3.4.2.1002/avr8-gnu-toolchain/bin/../lib/gcc/avr/4.7.2/avr5libgcc.a(_lt_sf.o):/data2/home/toolsbuild/jenkins-knuth/workspace/avr8-gnu-toolchain/src/gcc/libgcc/fp-bit.c:1269: first defined here
    c:/program files (x86)/atmel/atmel toolchain/avr8 gcc/native/3.4.2.1002/avr8-gnu-toolchain/bin/../lib/gcc/avr/4.7.2/../../../../avr/lib/avr5libc.a(cmpsf2.o):/data2/home/toolsbuild/jenkins-knuth/workspace/avr8-gnu-toolchain/src/avr-libc/libm/fplib/cmpsf2.S:58: multiple definition of `__lesf2'
    c:/program files (x86)/atmel/atmel toolchain/avr8 gcc/native/3.4.2.1002/avr8-gnu-toolchain/bin/../lib/gcc/avr/4.7.2/avr5libgcc.a(_le_sf.o):/data2/home/toolsbuild/jenkins-knuth/workspace/avr8-gnu-toolchain/src/gcc/libgcc/fp-bit.c:1290: first defined here

collect2.exe(0,0): ld returned 1 exit status
make: *** [main.elf] Error 1
The command exited with code 2.


Done executing task "RunCompilerTask" -- FAILED.
Done building target "CoreRebuild" in project "main.cproj" -- FAILED.
Done building project "main.cproj" -- FAILED.

The main error which sticks out is: multiple definition of __lesf2'
I am very new to AVR could some one please help me out here.

Mathlight's user avatar

Mathlight

6,33617 gold badges63 silver badges106 bronze badges

asked Feb 4, 2014 at 13:46

Zapnologica's user avatar

ZapnologicaZapnologica

21.7k43 gold badges154 silver badges247 bronze badges

1

I did eventually figure out what was wrong so I just wanted to say what I did so if some one else every has the same issue they know what to do.

It was Actually quite a simple fix.

All I needed to do was go to the project properties, linker , libraries and then add «limb» to the lib. (mine was blank originally)

Here is a picture of what it must look like.

enter image description here

answered Feb 6, 2014 at 6:24

Zapnologica's user avatar

ZapnologicaZapnologica

21.7k43 gold badges154 silver badges247 bronze badges

да я уже всё туда положил из той папки,осталось только все файлы скинуть в одну папку чтоб он их (личность голубого цвета) нашёл.
Да и ещё ,что интересно он обращается к странным путям,посмотрел в файл мониторе…

Код: Выделить всё • Развернуть
Ё:  CreateFile                         C:winavr-20100110libgccavr4.3.3avr4libC:mouseusbconfig.so                                           NAME INVALID        Desired Access: Generic Read, Disposi...
16:34...  _ ld.exe                                                                                                     2008  - CreateFile                         C:winavr-20100110libgccavr4.3.3avr4libC:mouseusbconfig.a                                             NAME INVALID        Desired Access: Generic Read, Disposi...
16:34...  _ ld.exe                                                                                                     2008  - CreateFile                         C:winavr-20100110avrlibavr4libC:mouseusbconfig.so                                                            NAME INVALID        Desired Access: Generic Read, Disposi...
16:34...  _ ld.exe                                                                                                     2008  - CreateFile                         C:winavr-20100110avrlibavr4libC:mouseusbconfig.a                                                              NAME INVALID        Desired Access: Generic Read, Disposi...
16:34...  _ ld.exe                                                                                                     2008  - CreateFile                         C:winavr-20100110libgccavr4.3.3libC:mouseusbconfig.so                                                    NAME INVALID        Desired Access: Generic Read, Disposi...
16:34...  _ ld.exe                                                                                                     2008  - CreateFile                         C:winavr-20100110libgccavr4.3.3libC:mouseusbconfig.a                                                     NAME INVALID        Desired Access: Generic Read, Disposi...
16:34...  _ ld.exe                                                                                                     2008  - CreateFile                         C:winavr-20100110libgcclibC:mouseusbconfig.so                                                                    NAME INVALID        Desired Access: Generic Read, Disposi...
16:34...  _ ld.exe                                                                                                     2008  - CreateFile                         C:winavr-20100110libgcclibC:mouseusbconfig.a                                                                      NAME INVALID        Desired Access: Generic Read, Disposi...
16:34...  _ ld.exe                                                                                                     2008  - CreateFile                         C:winavr-20100110avrliblibC:mouseusbconfig.so                                                                     NAME INVALID        Desired Access: Generic Read, Disposi...
16:34...  _ ld.exe                                                                                                     2008  - CreateFile                         C:winavr-20100110avrliblibC:mouseusbconfig.a

тоесть вот такого пути: «C:winavr-20100110libgcclibC:mouse» естественно быть не может,откуда он такое взял вообще.

ладно забил пока на настройки…
всё в студии сделано через задницу или у меня,какашки вместо мозгов.

решил использовать внешний makefile

выдаёт вот что:
gcc plug-in: Error: Object file not found on expected location C:hidmausevusb20120109exampleshid-mousefirmwaremain.elf
Make sure your makefile specifies the output .elf file as main.elf
сам файл:

Код: Выделить всё • Развернуть
# Name: Makefile
# Project: hid-mouse example
# Author: Christian Starkjohann
# Creation Date: 2008-04-07
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
# This Revision: $Id$

DEVICE  = atmega48
F_CPU   = 12000000   # in Hz
FUSE_L  = # see below for fuse values for particular devices
FUSE_H  =
AVRDUDE = avrdude -c usbasp -p $(DEVICE) # edit this line for your programmer

CFLAGS  = -Iusbdrv -I. -DDEBUG_LEVEL=0
OBJECTS = usbdrv/usbdrv.o usbdrv/usbdrvasm.o usbdrv/oddebug.o main.o

COMPILE = avr-gcc -Wall -Os -DF_CPU=$(F_CPU) $(CFLAGS) -mmcu=$(DEVICE)

##############################################################################
# Fuse values for particular devices
##############################################################################
# If your device is not listed here, go to
# http://palmavr.sourceforge.net/cgi-bin/fc.cgi
# and choose options for external crystal clock and no clock divider
#
################################## ATMega8 ##################################
# ATMega8 FUSE_L (Fuse low byte):
# 0x9f = 1 0 0 1   1 1 1 1
#        ^ ^ /   --+--/
#        | |  |       +------- CKSEL 3..0 (external >8M crystal)
#        | |  +--------------- SUT 1..0 (crystal osc, BOD enabled)
#        | +------------------ BODEN (BrownOut Detector enabled)
#        +-------------------- BODLEVEL (2.7V)
# ATMega8 FUSE_H (Fuse high byte):
# 0xc9 = 1 1 0 0   1 0 0 1 <-- BOOTRST (boot reset vector at 0x0000)
#        ^ ^ ^ ^   ^ ^ ^------ BOOTSZ0
#        | | | |   | +-------- BOOTSZ1
#        | | | |   + --------- EESAVE (don't preserve EEPROM over chip erase)
#        | | | +-------------- CKOPT (full output swing)
#        | | +---------------- SPIEN (allow serial programming)
#        | +------------------ WDTON (WDT not always on)
#        +-------------------- RSTDISBL (reset pin is enabled)
#
############################## ATMega48/88/168 ##############################
# ATMega*8 FUSE_L (Fuse low byte):
# 0xdf = 1 1 0 1   1 1 1 1
#        ^ ^ /   --+--/
#        | |  |       +------- CKSEL 3..0 (external >8M crystal)
#        | |  +--------------- SUT 1..0 (crystal osc, BOD enabled)
#        | +------------------ CKOUT (if 0: Clock output enabled)
#        +-------------------- CKDIV8 (if 0: divide by 8)
# ATMega*8 FUSE_H (Fuse high byte):
# 0xde = 1 1 0 1   1 1 1 0
#        ^ ^ ^ ^   ^ -+-/
#        | | | |   |   +------ BODLEVEL 0..2 (110 = 1.8 V)
#        | | | |   + --------- EESAVE (preserve EEPROM over chip erase)
#        | | | +-------------- WDTON (if 0: watchdog always on)
#        | | +---------------- SPIEN (allow serial programming)
#        | +------------------ DWEN (debug wire enable)
#        +-------------------- RSTDISBL (reset pin is enabled)
#
############################## ATTiny25/45/85 ###############################
# ATMega*5 FUSE_L (Fuse low byte):
# 0xef = 1 1 1 0   1 1 1 1
#        ^ ^ +/   --+--/
#        | |  |       +------- CKSEL 3..0 (clock selection -> crystal @ 12 MHz)
#        | |  +--------------- SUT 1..0 (BOD enabled, fast rising power)
#        | +------------------ CKOUT (clock output on CKOUT pin -> disabled)
#        +-------------------- CKDIV8 (divide clock by 8 -> don't divide)
# ATMega*5 FUSE_H (Fuse high byte):
# 0xdd = 1 1 0 1   1 1 0 1
#        ^ ^ ^ ^   ^ -+-/
#        | | | |   |   +------ BODLEVEL 2..0 (brownout trigger level -> 2.7V)
#        | | | |   +---------- EESAVE (preserve EEPROM on Chip Erase -> not preserved)
#        | | | +-------------- WDTON (watchdog timer always on -> disable)
#        | | +---------------- SPIEN (enable serial programming -> enabled)
#        | +------------------ DWEN (debug wire enable)
#        +-------------------- RSTDISBL (disable external reset -> enabled)
#
################################ ATTiny2313 #################################
# ATTiny2313 FUSE_L (Fuse low byte):
# 0xef = 1 1 1 0   1 1 1 1
#        ^ ^ +/   --+--/
#        | |  |       +------- CKSEL 3..0 (clock selection -> crystal @ 12 MHz)
#        | |  +--------------- SUT 1..0 (BOD enabled, fast rising power)
#        | +------------------ CKOUT (clock output on CKOUT pin -> disabled)
#        +-------------------- CKDIV8 (divide clock by 8 -> don't divide)
# ATTiny2313 FUSE_H (Fuse high byte):
# 0xdb = 1 1 0 1   1 0 1 1
#        ^ ^ ^ ^   -+-/ ^
#        | | | |     |   +---- RSTDISBL (disable external reset -> enabled)
#        | | | |     +-------- BODLEVEL 2..0 (brownout trigger level -> 2.7V)
#        | | | +-------------- WDTON (watchdog timer always on -> disable)
#        | | +---------------- SPIEN (enable serial programming -> enabled)
#        | +------------------ EESAVE (preserve EEPROM on Chip Erase -> not preserved)
#        +-------------------- DWEN (debug wire enable)

# symbolic targets:
help:
   @echo "This Makefile has no default rule. Use one of the following:"
   @echo "make hex ....... to build main.hex"
   @echo "make program ... to flash fuses and firmware"
   @echo "make fuse ...... to flash the fuses"
   @echo "make flash ..... to flash the firmware (use this on metaboard)"
   @echo "make clean ..... to delete objects and hex file"

hex: main.hex

program: flash fuse

# rule for programming fuse bits:
fuse:
   @[ "$(FUSE_H)" != "" -a "$(FUSE_L)" != "" ] ||
      { echo "*** Edit Makefile and choose values for FUSE_L and FUSE_H!"; exit 1; }
   $(AVRDUDE) -U hfuse:w:$(FUSE_H):m -U lfuse:w:$(FUSE_L):m

# rule for uploading firmware:
flash: main.hex
   $(AVRDUDE) -U flash:w:main.hex:i

# rule for deleting dependent files (those which can be built by Make):
clean:
   rm -f main.hex main.lst main.obj main.cof main.list main.map main.eep.hex main.elf *.o usbdrv/*.o main.s usbdrv/oddebug.s usbdrv/usbdrv.s

# Generic rule for compiling C files:
.c.o:
   $(COMPILE) -c $< -o $@

# Generic rule for assembling Assembler source files:
.S.o:
   $(COMPILE) -x assembler-with-cpp -c $< -o $@
# "-x assembler-with-cpp" should not be necessary since this is the default
# file type for the .S (with capital S) extension. However, upper case
# characters are not always preserved on Windows. To ensure WinAVR
# compatibility define the file type manually.

# Generic rule for compiling C to assembler, used for debugging only.
.c.s:
   $(COMPILE) -S $< -o $@

# file targets:

# Since we don't want to ship the driver multipe times, we copy it into this project:
usbdrv:
   cp -r ../../../usbdrv .

main.elf: usbdrv $(OBJECTS)   # usbdrv dependency only needed because we copy it
   $(COMPILE) -o main.elf $(OBJECTS)

main.hex: main.elf
   rm -f main.hex main.eep.hex
   avr-objcopy -j .text -j .data -O ihex main.elf main.hex
   avr-size main.hex

# debugging targets:

disasm:   main.elf
   avr-objdump -d main.elf

cpp:
   $(COMPILE) -E main.c

Зачем он пишет что его там нет если он сам должен его там создать ?
Скоро у меня в глазах эльфы появятся.

make hex
из консоли нормально собирает проект.

Добавлено спустя 1 час 58 минут 28 секунд:
в общем без использования внешнего makefile
нужно добавить файлы
oddebug.c
usbdrv.c
usbdrvasm.S
в папку «Source Files» дерева каталога проекта,правой кнопкой мышки.

А ошибка типа:

c:/winavr-20100110/bin/../lib/gcc/avr/4.3.3/../../../../avr/bin/ld.exe: cannot find -lC:hidmauseusbconfig
make: *** [main.elf] Error 1

возникает в результате добавления файла usbconfig.h во вкладку библиотек.

Sorry! I will upload more detail

This is the config.ini file:

    [env:engduinov3]
    platform = atmelavr
    framework = arduino
    board = engduinov3

This is the source code.

/**
* addtogroup EngduinoLEDs
*
* This is the driver code for LEDs on the Engduino
* These LEDS are not directly connected to pins on the
* AtMega32u4 processor. Instead they are connected through
* LED drivers so should only be accessed through this code.
*
* The Engduino has 16 RGB LEDs on it, each of which
* can be controlled independently. To make the granularity
* of control greater, we implement a software PWM for each
* LED. This allows for 16 levels of brightness in each of
* the RGB channels on each LED with minimal flicker.
* 
* This implementation uses TIMER4 Comparator A to
* implement the PWM. The timer is set to run at ~320Hz. The
* clock is reset on interrupt, so you should be very wary
* about using the other comparators.
*
* @{
*/

/**
* file 
*       Engduino LED driver
* author
*       Engduino team: support@engduino.org
*/

#include "pins_arduino.h"
#ifdef __BOARD_ENGDUINOV3
    #include <SPI.h>
#endif
#include "EngduinoLEDs.h"

/*---------------------------------------------------------------------------*/
/**
* brief Constructor
* 
* C++ constructor for this class. Empty.
*/
EngduinoLEDsClass::EngduinoLEDsClass()
{
}

/*---------------------------------------------------------------------------*/
/**
* brief begin function - must be called before using other functions
*
* The connection to the LEDs is not direct. Instead, it happens through
* three LED drivers - one each for the R, G, and B channels. These are
* connected through a daisy-chained SPI connection. There is a single latch
* line connected to all driver chips, which latches the value set by SPI when
* the line is pulsed high. The output from each driver chip can be switched on
* or off with a separate output enable line to each driver - when these are LOW
* the driver output lines go to the LEDs; when HIGH, they do not.
* 
*/
void EngduinoLEDsClass::begin() 
{
    for (int i = 0; i < 15; i++) {
      RSet[i]   = GSet[i]   = BSet[i]   = 0;
      RAccum[i] = GAccum[i] = BAccum[i] = 0;
      RDisp[i]  = GDisp[i]  = BDisp[i]  = 0;
    }

    // RGB LED drivers - output enable lines
    pinMode(LED_R_OE, OUTPUT);
    pinMode(LED_G_OE, OUTPUT);
    pinMode(LED_B_OE, OUTPUT);

    // Disable the output from the LED drivers while we set up
    digitalWrite(LED_R_OE, HIGH);
    digitalWrite(LED_G_OE, HIGH);
    digitalWrite(LED_B_OE, HIGH);

#if defined(__BOARD_ENGDUINOV1)||defined(__BOARD_ENGDUINOV2)
    pinMode(LED_MISO,  INPUT);
    pinMode(LED_MOSI,  OUTPUT);
    pinMode(LED_SCLK,  OUTPUT);
    pinMode(LED_LATCH, OUTPUT);
    // Clock line is initially low.
    // We must pulse high to tick
    digitalWrite(LED_SCLK, LOW);
#elif defined (__BOARD_ENGDUINOV3)  
    // Set up SPI data connection to the RGB LEDs
    // start the SPI library:
    SPI.begin();
    pinMode(LED_LATCH, OUTPUT);
#endif


    // Latch line is initially low
    // We must pulse high to latch
    digitalWrite(LED_LATCH, LOW);

    // The buffers might have something latched from the
    // last time they were programmed, so remove it - nothing
    // will be shown, because the LED driver OE lines are pulled
    // high at this point in time.
    setAll(OFF);

    // Set up timer 4. We use a software PWM to drive the LEDs to control both
    // brightness and colour. This requires a tick, which we set at 320Hz - this
    // is determined by the fact that we have 16 brightness levels per channel on
    // our PWM. Brightness 1 corresponds to 1 on period and 15 off periods. To
    // avoid flicker, we need this to happen at >15-18Hz, so we choose to run
    // through the 16 on/off periods 20 times per second, meaning that we need
    // a timer tick of 320Hz.
    //
    // Timer 4 is a free running 8 or 10 bit timer; NOTE: there is no CTC
    // (Clear Timer on Compare match) mode as for timers 1 and 3, so we must
    // manually reset the clock when an interrupt occurs.
    //
    // Note, as with other timers, if we set the count to, n, then we will
    // interrupt after n+1 clock cycles
    //
    // For a 10 bit write we must write the high byte before the low byte;
    // in this case there is a single shared register for the high bits, TC4H
    // and this is used for writing to ANY 10 bit register, so we need to be
    // aware of what is in there when we write what we might think is an
    // 8 bit value.
    //
    // At 8MHz with a /128 prescaler, one count is equal to 16 us
    // At 194 counts, we will interrupt every 195 periods:
    // at 3.12ms intervals, or 320.51Hz  
    //

    cli();      // Disable interrupts

    TIMSK4  = 0x00;     // Disable interrupts for all timer 4 comparisons, plus overflow

    TC4H    = 0x00;     // Reset the timer to zero, high byte first
    TCNT4   = 0x00;     // Reset the timer to zero
                        // This must be done first because the TC4H is used to provide
                        // high bits for the 10 bit registers accessed below

    TCCR4A  = 0x00;     // Turn off OC4Ax/OC4Bx connections, FfOC and PWM
    TCCR4B  = 0x08;     // No PWM inversion, don't reset the prescaler, don't set dead time, clock/128
    TCCR4C  = 0x00;     // Comparator B and D to normal mode
    TCCR4D  = 0x00;     // Fault protection off
    TCCR4E  = 0x00;     // Don't lock and switch off all output compare pins
    OCR4A   = 0x4F;     // Set the counter to 194 (0xC2), giving ~320Hz

    TIMSK4 |= 0x40;     // And enable interrupts for a compare A match only

    // Finally, enable the output from the LED drivers
    digitalWrite(LED_R_OE, LOW);
    digitalWrite(LED_G_OE, LOW);
    digitalWrite(LED_B_OE, LOW);

    sei();      // Enable interrupts    
}


/*---------------------------------------------------------------------------*/
/**
* brief end function - switch off the LEDs
*
* We drive the output enables for all three drivers high. This disconnects
* the driver from the LEDs and so all subsequent changes will have no effect.
* We also stop the timer interrupt.
* 
*/
void EngduinoLEDsClass::end() 
{
    // Disable output from LED drivers
    digitalWrite(LED_R_OE, HIGH);
    digitalWrite(LED_G_OE, HIGH);
    digitalWrite(LED_B_OE, HIGH);

    TIMSK4  = 0x00;     // Disable interrupts for all timer 4 comparisons, plus overflow
}


/*---------------------------------------------------------------------------*/
/**
* brief Internal function to set an LED to a given colour/brightness.
* param LEDidx     LED index, ranging from 0 (for LED0) to 15 (LED15)
* param c          Colour, as chosen from the colour enum
* param brightness A 0-MAX_BRIGHTNESS(=15) value
*
* Internal function to set the colour/brightness of an LED. The colour value
* here is chosen from an enum and corresponds to the primary and secondary
* colours of light, plus white and off. Brightness ranges from 0 to
* MAX_BRIGHTNESS (currently 15), and is shifted here to an internal 8 bit
* representation (0-255) to make some of the maths slightly quicker later.
* Choosing a brightness of zero will turn an LED off. 
* 
* Note: in the Engduino 1.0, we cannot use the full brightness for the LEDs
* when the colour white is requested, simply because this causes too big a
* drain on current whilst the device is attached to the USB. This
* causes a system reset, which is both irritating and makes reprogramming
* rather tedious.
*
*/
void EngduinoLEDsClass::_setLED(uint8_t LEDidx, colour c, uint8_t brightness)
{   
    LEDidx &= 0x0F;                 // We only have 16 LEDS
    brightness = brightness << 4;   // Translate brightness to a 0-255 scale

    switch (c) {
        case RED:
            RSet[LEDidx]=brightness; GSet[LEDidx]=0x00;       BSet[LEDidx]=0x00;
            break;
        case GREEN:
            RSet[LEDidx]=0x00;       GSet[LEDidx]=brightness; BSet[LEDidx]=0x00;
            break;
        case BLUE:
            RSet[LEDidx]=0x00;       GSet[LEDidx]=0x00;       BSet[LEDidx]=brightness;
            break;
        case YELLOW:
            RSet[LEDidx]=brightness; GSet[LEDidx]=brightness; BSet[LEDidx]=0x00;
            break;
        case MAGENTA:
            RSet[LEDidx]=brightness; GSet[LEDidx]=0x00;       BSet[LEDidx]=brightness;
            break;
        case CYAN:
            RSet[LEDidx]=0x00;       GSet[LEDidx]=brightness; BSet[LEDidx]=brightness;
            break;
        case WHITE:
            brightness = (brightness > 0xB0) ? 0xB0 : brightness;   // Can't use full scale for white
            RSet[LEDidx]=brightness; GSet[LEDidx]=brightness; BSet[LEDidx]=brightness;      
            break;
        case OFF:
            RSet[LEDidx]=0x00;       GSet[LEDidx]=0x00;       BSet[LEDidx]=0x00;
            break;
    }
}

/*---------------------------------------------------------------------------*/
/**
* brief Internal function to set an LED to a given point in the rgb space.
* param LEDidx     LED index, ranging from 0 (for LED0) to 15 (LED15)
* param r          Brightness of the red channel from 0-MAX_BRIGHTNESS (15)
* param g          Brightness of the green channel from 0-MAX_BRIGHTNESS (15)
* param b          Brightness of the blue channel from 0-MAX_BRIGHTNESS (15)
*
* Internal function to set the colour/brightness of an LED to a point in rgb
* space. The brightness in each channel may range from 0 to MAX_BRIGHTNESS
* (currently 15), and is shifted here to an internal 8 bit representation
* (0-255) to make some of the maths slightly quicker later.
* 
* Note: in the Engduino 1.0, we cannot use the full brightness for the LEDs
* when the colour white, or colours close to white are requested, simply
* because this causes too big a drain on current whilst the device is attached
* to the USB. This causes a system reset, which is both irritating and makes
* reprogramming rather tedious. So we limit the sum of the rgb values to
* a number we chose empirically, and we reduce the chosen rgb values until they
* sum to less than that chosen.
* 
*/
void EngduinoLEDsClass::_setLED(uint8_t LEDidx, uint8_t r, uint8_t g, uint8_t b)
{   

    LEDidx &= 0x0F;     // We only have 16 LEDS
    r = r << 4;         // We only use 16 brightness levels to avoid flickering
    g = g << 4;         // Turn the 0-15 scale into a 0-255 scale; makes maths easier
    b = b << 4;

    #if defined(__BOARD_ENGDUINOV1) || defined(__BOARD_ENGDUINOV2)// Only for version 1 and 2
        // The brightest colours cause a reset on the engduino v1.0
        // when running on USB. So we limit what we allow someone to choose.
        // This subtraction avoids division, which is slow.
        //
        uint16_t sum;
        sum = r + g + b;
        while (sum > 0x240) {   // Empirically determined: (0x24 << 4)
            r -= 1;
            g -= 1;
            b -= 1;
            sum = r + g + b;
        }
    #endif

    RSet[LEDidx] = r;
    GSet[LEDidx] = g;
    BSet[LEDidx] = b;
}

/*---------------------------------------------------------------------------*/
/**
* brief Set the colour of a single LED at maximum brightness
* param LEDNumber  LED number, ranging from 0 (for LED0) to 15 (LED15)
* param c          Colour, as chosen from the colour enum
*
* Set the colour of an LED. The colour value here is chosen from an enum and
* corresponds to the primary and secondary colours of light, plus white and
* off.
* 
*/
void EngduinoLEDsClass::setLED(uint8_t LEDNumber, colour c)
{   
#ifdef __BOARD_ENGDUINOV1
    LEDNumber--;
#endif
    _setLED(LEDNumber, c, MAX_BRIGHTNESS);

}


/*---------------------------------------------------------------------------*/
/**
* brief Set an LED to a given colour/brightness.
* param LEDNumber  LED number, ranging from 0 (for LED0) to 15 (LED15)
* param c          Colour, as chosen from the colour enum
* param brightness A 0-MAX_BRIGHTNESS(=15) value
*
* Set the colour of an LED. The colour value here is chosen from an enum and
* corresponds to the primary and secondary colours of light, plus white and
* off. Brightness ranges from 0 to MAX_BRIGHTNESS (currently 15). Choosing a
* brightness of zero will turn an LED off. 
* 
*/
void EngduinoLEDsClass::setLED(uint8_t LEDNumber, colour c, uint8_t brightness)
{
#ifdef __BOARD_ENGDUINOV1
    LEDNumber--;
#endif
    _setLED(LEDNumber, c, brightness);
}

/*---------------------------------------------------------------------------*/
/**
* brief Set an LED to a given point in the rgb space.
* param LEDNumber  LED number, ranging from 0 (for LED0) to 15 (LED15)
* param r          Brightness of the red channel from 0-MAX_BRIGHTNESS (15)
* param g          Brightness of the green channel from 0-MAX_BRIGHTNESS (15)
* param b          Brightness of the blue channel from 0-MAX_BRIGHTNESS (15)
*
* Set the colour/brightness of an LED to a point in rgb space. The brightness
* in each channel may range from 0 to MAX_BRIGHTNESS (currently 15).
* 
* Note: in the Engduino 1.0, we cannot use the full brightness for the LEDs
* when the colour white, or colours close to white are requested, simply
* because this causes too big a drain on current whilst the device is attached
* to the USB. This causes a system reset, which is both irritating and makes
* reprogramming rather tedious. So we limit the sum of the rgb values to
* a number we chose empirically, and we reduce the chosen rgb values until they
* sum to less than that chosen.
*
*/
void EngduinoLEDsClass::setLED(uint8_t LEDNumber, uint8_t r, uint8_t g, uint8_t b)
{   
#ifdef __BOARD_ENGDUINOV1
    LEDNumber--;
#endif
    _setLED(LEDNumber, r, g, b);
}

/*---------------------------------------------------------------------------*/
/**
* brief Set the colour of all LEDs at maximum brightness
* param c          Colour, as chosen from the colour enum
*
* Set the colour of all LEDs. The colour value here is chosen from an enum and
* corresponds to the primary and secondary colours of light, plus white and
* off.
*
*/
void EngduinoLEDsClass::setAll(colour c)
{   
    for (int i = 0; i < 16; i++)
        _setLED(i, c, MAX_BRIGHTNESS);
}


/*---------------------------------------------------------------------------*/
/**
* brief Set all LEDs to a given colour/brightness.
* param c          Colour, as chosen from the colour enum
* param brightness A 0-MAX_BRIGHTNESS(=15) value
*
* Set the colour of all LEDs. The colour value here is chosen from an enum and
* corresponds to the primary and secondary colours of light, plus white and
* off. Brightness ranges from 0 to MAX_BRIGHTNESS (currently 15). Choosing a
* brightness of zero will turn all LEDs off. 
*
*/
void EngduinoLEDsClass::setAll(colour c, uint8_t brightness)
{   
    for (int i = 0; i < 16; i++) {
        _setLED(i, c, brightness);
    }
}

/*---------------------------------------------------------------------------*/
/**
* brief Set all LEDs to a given point in the rgb space.
* param r          Brightness of the red channel from 0-MAX_BRIGHTNESS (15)
* param g          Brightness of the green channel from 0-MAX_BRIGHTNESS (15)
* param b          Brightness of the blue channel from 0-MAX_BRIGHTNESS (15)
*
* Set the colour/brightness of all LEDs to a point in rgb space. The brightness
* in each channel may range from 0 to MAX_BRIGHTNESS (currently 15).
* 
* Note: in the Engduino 1.0, we cannot use the full brightness for the LEDs
* when the colour white, or colours close to white are requested, simply
* because this causes too big a drain on current whilst the device is attached
* to the USB. This causes a system reset, which is both irritating and makes
* reprogramming rather tedious. So we limit the sum of the rgb values to
* a number we chose empirically, and we reduce the chosen rgb values until they
* sum to less than that chosen.
*
*/
void EngduinoLEDsClass::setAll(uint8_t r, uint8_t g, uint8_t b)
{   
    for (int i = 0; i < 16; i++)
        _setLED(i, r, g, b);
}

/*---------------------------------------------------------------------------*/
/**
* brief Set the colour of all LEDs at maximum brightness from an array of
*        individual values
* param c          Array of colour values, as chosen from the colour enum
*
* Set the colour of all LEDs from an array of colour values - i.e. each LED
* can be set to a different colour, though all are at maximum brightness. The
* colour value here is chosen from an enum and corresponds to the primary and
* secondary colours of light, plus white and off.
*
*/
void EngduinoLEDsClass::setLEDs(colour c[16])
{   
    for (int i = 0; i < 16; i++)
        _setLED(i, c[i], MAX_BRIGHTNESS);
}


/*---------------------------------------------------------------------------*/
/**
* brief Set all LEDs to a given colour/brightness from arrays of
*        individual values
* param c          Array of colour values, as chosen from the colour enum
* param brightness Array of brightness values, from 0-MAX_BRIGHTNESS(=15)
*
* Set the colour/brightness of all LEDs from two arrays of values - i.e.
* each LED can be set to a different colour/brightness value. The colour
* value here is chosen from an enum and corresponds to the primary and
* secondary colours of light, plus white and off. Brightness ranges from 0
* to MAX_BRIGHTNESS (currently 15). Choosing a brightness of zero will turn
* an LED off. 
*
*/
void EngduinoLEDsClass::setLEDs(colour c[16], uint8_t brightness[16])
{   
    for (int i = 0; i < 16; i++) {
        _setLED(i, c[i], brightness[i]);
    }
}

/*---------------------------------------------------------------------------*/
/**
* brief Set all LEDs to a given point in the rgb space from arrays of
*        individual values.
* param r          Array of red channel brightness, from 0-MAX_BRIGHTNESS (15)
* param g          Array of green channel brightness, from 0-MAX_BRIGHTNESS (15)
* param b          Array of blue channel brightness, from 0-MAX_BRIGHTNESS (15)
*
* Set the colour/brightness of all LEDs to a point in rgb space from three
* arrays of values - i.e. each LED can be set to a different rgb point. The
* brightness in each channel may range from 0 to MAX_BRIGHTNESS (currently 15).
* 
* Note: in the Engduino 1.0, we cannot use the full brightness for the LEDs
* when the colour white, or colours close to white are requested, simply
* because this causes too big a drain on current whilst the device is attached
* to the USB. This causes a system reset, which is both irritating and makes
* reprogramming rather tedious. So we limit the sum of the rgb values to
* a number we chose empirically, and we reduce the chosen rgb values until they
* sum to less than that chosen.
*
*/
void EngduinoLEDsClass::setLEDs(uint8_t r[16], uint8_t g[16], uint8_t b[16])
{   
    for (int i = 0; i < 16; i++)
        _setLED(i, r[i], g[i], b[i]);
}

/*---------------------------------------------------------------------------*/
/**
* brief Set all LEDs to a given point in the rgb space a 2D array of
*        individual values. The array is of form rgb[3][16]
* param rgb        2D array of rgb brightnesses, from 0-MAX_BRIGHTNESS (15)
*
* Set the colour/brightness of all LEDs to a point in rgb space from a 2D
* array values - i.e. each LED can be set to a different rgb point. The array
* is of form rgb[3][16] - i.e. the first index is the red/green/blue channel
* and the second is the LED (ranging from 0-15). The brightness in each
* channel may range from 0 to MAX_BRIGHTNESS (currently 15).
* 
* Note: in the Engduino 1.0, we cannot use the full brightness for the LEDs
* when the colour white, or colours close to white are requested, simply
* because this causes too big a drain on current whilst the device is attached
* to the USB. This causes a system reset, which is both irritating and makes
* reprogramming rather tedious. So we limit the sum of the rgb values to
* a number we chose empirically, and we reduce the chosen rgb values until they
* sum to less than that chosen.
*
*/
void EngduinoLEDsClass::setLEDs(uint8_t rgb[3][16])
{   
    for (int i = 0; i < 16; i++)
        _setLED(i, rgb[0][i], rgb[1][i], rgb[2][i]);
}


/*---------------------------------------------------------------------------*/
/**
* brief Set all LEDs to a given point in the rgb space a 2D array of
*        individual values. The array is of form rgb[16][3]
* param rgb        2D array of rgb brightnesses, from 0-MAX_BRIGHTNESS (15)
*
* Set the colour/brightness of all LEDs to a point in rgb space from a 2D
* array values - i.e. each LED can be set to a different rgb point. The array
* is of form rgb[16][3] - i.e. the first index is the LED (ranging from 0-15).
* and the second is the red/green/blue channel. The brightness in each
* channel may range from 0 to MAX_BRIGHTNESS (currently 15).
* 
* Note: in the Engduino 1.0, we cannot use the full brightness for the LEDs
* when the colour white, or colours close to white are requested, simply
* because this causes too big a drain on current whilst the device is attached
* to the USB. This causes a system reset, which is both irritating and makes
* reprogramming rather tedious. So we limit the sum of the rgb values to
* a number we chose empirically, and we reduce the chosen rgb values until they
* sum to less than that chosen.
*
*/
void EngduinoLEDsClass::setLEDs(uint8_t rgb[16][3])
{   
    for (int i = 0; i < 16; i++)
        _setLED(i, rgb[i][0], rgb[i][1], rgb[i][2]);
}

#if defined(__BOARD_ENGDUINOV1)||defined(__BOARD_ENGDUINOV2)
/*---------------------------------------------------------------------------*/
/**
* brief This is an internal routine to set the LED latches appropriately
* param value      The on/off bits for each LED on a given channel
*
* This function is written using low level C programming primitives for
* changing the voltages on ATMega32U4 pins rather than the Arduino
* digitalWrite equivalents. This has to be done in this way for speed - it is
* around 18 times faster than the alternative and, because we update the
* values rather frequently to avoid flickering, speed is important. This code
* manually emulates SPI functionality (mode 0), both for simplicity and speed
* 
* Notes:
* PB1 is pin 9  - SPI SCLK
* PB2 is pin 10 - SPI MOSI
* PB3 is pin 11 - SPI MISO
*
*/
inline void writeLEDs(volatile uint8_t *value)
{
    // This is code to emulate SPI mode 0 = we set the
    // data value first and then tick the clock with a rising
    // edge to latch the data into the slave.
    //
    for (int i = 15; i >= 0; i--) {
        if (value[i] != 0)          // Set the data line...
            PORTB |= _BV(PORTB2);   // Drive MOSI high
        else
            PORTB &= ~_BV(PORTB2);  // Drive MOSI low
        PORTB |= _BV(PORTB1);       // ...and tick the SPI clock
        PORTB &= ~_BV(PORTB1);
    }
}

#elif defined (__BOARD_ENGDUINOV3)
/*---------------------------------------------------------------------------*/
/**
* brief This is an internal routine to set the LED latches appropriately
* param value      The on/off bits for each LED on a given channel
*
* This function sends two SPI 8bit packages to simulate 16bit SPI package.
* 
* Notes:
* PB1 is pin 9  - SPI SCLK
* PB2 is pin 10 - SPI MOSI
* PB3 is pin 11 - SPI MISO
*
*/
inline void writeLEDs(volatile uint8_t *value)
{
    uint8_t temp1 = 0;
    uint8_t temp2 = 0;

    for (int i = 15; i >= 8; i--) 
    {
        if (value[i] != 0)  // Check if bit is one
        {
            temp1 = temp1 + (1 << (i-8));
        }
    }


    for (int i = 7; i >= 0; i--) 
    {
        if (value[i] != 0)  // Check if bit is one
        {
            temp2 = temp2 + (1 << i);
        }
    }

    SPI.transfer(temp1);
    SPI.transfer(temp2);
}
#endif

/*---------------------------------------------------------------------------*/
/**
* brief ISR routine for comparator A of TIMER 4
*
* TIMER4 interrupt code  ticks at ~320Hz, which means we can do 16 brightness
* levels at 20Hz, so flickering is invisible to the naked eye. This ISR
* implements the software PWM and calls the LED display function. 
* 
* Because we must update the LEDs very frequently, and because it still takes
* a significant period to write all 3*16 values to the LED drivers, we need
* this code to run as fast as possible. We also need to ensure that we do not
* prevent other interrupts from occurring whilst we process this. To that end
* we stop interrupts for this ISR to prevent any nesting, reset the counter
* and re-enable interrupts generally before calling setting the LED values.
*
* The PWM implementation relies on counting in units of the brightness on a
* channel and setting the apropriate colour channel on for an LED when the
* accumulated value overflows. This is slightly faster if the rgb values are
* in the range 0-255 than 0-15, because we can do it with a simple comparison.
* 
* This function then calls writeLEDs for each of the RGB values, in reverse
* order. The drivers are daisy chained and we need to shift the blue values
* to the far end of that chain before pulsing the latch. This written using
* low level C programming primitives of changing the voltages on ATMega32U4
* pins rather than the Arduino digitalWrite equivalents. This has to be done
* in this way for speed - it is around 18 times faster than the alternative
* and, because we update the values rather frequently to avoid flickering,
* speed is important.
* 
* Notes:
* The PWM implementation will occasionally put one more dark period
*   in than it should, but we can live with this for simplicity.
* PB7 is pin 12 on the ATMega32U4 and is attached to the LED LATCH
*
*/
ISR(TIMER4_COMPA_vect)
{  
    // Temporarily disable interrupts on this ISR to avoid nesting.
    //
    TIMSK4  = 0x00;

    // Because there is no CTC mode, we need to reset the timer
    // count manually.
    //
    TC4H    = 0x00;     // Reset the timer to zero, high byte first
    TCNT4   = 0x00;     // Reset the timer to zero

    // And re-enable interrupts for all other ISRs whilst we set the LEDs 
    sei();


    // Accumulate RGB values for each LED into their respective arrays
    // and only set the LED on when we overflow the count; it is otherwise
    // set off.
    //
    for (int i = 0; i < 16; i++) 
    {
        uint8_t ra = EngduinoLEDs.RAccum[i];
        uint8_t ga = EngduinoLEDs.GAccum[i];
        uint8_t ba = EngduinoLEDs.BAccum[i];

        EngduinoLEDs.RAccum[i] += EngduinoLEDs.RSet[i];
        EngduinoLEDs.GAccum[i] += EngduinoLEDs.GSet[i];
        EngduinoLEDs.BAccum[i] += EngduinoLEDs.BSet[i];

        EngduinoLEDs.RDisp[i]   = (EngduinoLEDs.RAccum[i] < ra);
        EngduinoLEDs.GDisp[i]   = (EngduinoLEDs.GAccum[i] < ga);
        EngduinoLEDs.BDisp[i]   = (EngduinoLEDs.BAccum[i] < ba);
    }

    // Now display the values we calculated.
#ifdef __BOARD_ENDDUINOV1
    PORTB &= ~_BV(PORTB7);          // Drive LATCH low - disable 
#elif defined (__BOARD_ENGDUINOV2)
    PORTB &= ~_BV(PORTB4);  
#elif defined (__BOARD_ENGDUINOV3)
    LED_LATCH_PORT &= ~_BV(LED_LATCH_BIT);          // Drive LATCH low - disable 
#endif

    writeLEDs(EngduinoLEDs.BDisp);  // Write the RGB values
    writeLEDs(EngduinoLEDs.GDisp);
    writeLEDs(EngduinoLEDs.RDisp);
#ifdef __BOARD_ENGDUINOV1   
    PORTB |= _BV(PORTB7);           // Pulse LATCH to switch
    PORTB &= ~_BV(PORTB7);
#elif defined (__BOARD_ENGDUINOV2)
    PORTB |= _BV(PORTB4);           // Pulse LATCH to switch
    PORTB &= ~_BV(PORTB4);
#elif defined(__BOARD_ENGDUINOV3)   
    LED_LATCH_PORT |= _BV(LED_LATCH_BIT);           // Pulse LATCH to switch
    LED_LATCH_PORT &= ~_BV(LED_LATCH_BIT);
#endif
    // And we're done with this call of the ISR, so re-enable interrupts
    //
    TIMSK4 |= 0x40;     // And enable interrupts for a compare A match only
}


/*---------------------------------------------------------------------------*/
/*
 * Preinstantiate Objects
 */ 
EngduinoLEDsClass EngduinoLEDs = EngduinoLEDsClass();

/** @} */

Понравилась статья? Поделить с друзьями:
  • Main device init error no description 2
  • Make fewer http requests как исправить вордпресс
  • Main decoder error failed to create audio output
  • Make exe error 126
  • Make error codes