Ir ao conteúdo

Compilando para Teensy 3.0 no Windows utilizando Makefile

Boa tarde,

Se você não quer utilizar a Arduino IDE (Teensy IDE?) para programar e enviar seus códigos para o Teensy 3.0 você pode utilizar o Makefile.

A última versão da IDE por enquanto você consegue no Forum do PJRC . Como ele diz, existe um exemplo de Makefile na pasta: “arduino-1.0.3\hardware/teensy/cores/teensy3” porém para utiliza-lo você precisa fazer alguns passos como adicionar o “arduino-1.0.3\hardware\tools\arm-none-eabi\bin” ao seu PATH para que possa utilizar os executaveis desta pasta tranquilamente. Para isso abra o seu Prompt de Comando: Iniciar – Executar – CMD

E em seguida insira o seguinte comando:

PATH = %PATH%;C:\CAMINHO_PARA_O_ARDUINO\arduino-1.0.3\hardware\tools\arm-none-eabi\bin

[Se você não quer entender as modificações que eu realizei va para o final da publicação]

Para garantir que não estragaria o arquivo, fiz uma copia completa do diretório. Em seguida ao executar o

cs-make.exe

Recebia a seguinte mensagem de erro:

C:\CAMINHO_PARA_O_ARDUINO\arduino-1.0.3\Projects\Example_not_working>cs-make.exe
C:/Users/X-warrior/Desktop/tools/arm-none-eabi/bin/arm-none-eabi-gcc -Wall -g -Os -mcpu=cortex-m4 -mthumb -nostdlib -MMD -DF_CPU=48000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH -I. -c -o analog.o analog.c
process_begin: CreateProcess(NULL, C:/Users/X-warrior/Desktop/tools/arm-none-eabi/bin/arm-none-eabi-gcc -Wall -g -Os -mcpu=cortex-m4 -mthumb -nostdlib -MMD -DF_CPU=48000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH -I. -c -o analog.o analog.c, …) failed.
make (e=2): The system cannot find the file specified.
cs-make.exe: *** [analog.o] Error 2

Verificando o Makefile decidi alterar as configurações das váriaveis para caminho completo já que eu fiz uma copia do teeensy/core.
TOOLSPATH = C:\CAMINHO_PARA_O_ARDUINO\arduino-1.0.3\hardware\tools
LIBRARYPATH = Deixei como estava
COMPILERPATH = C:\CAMINHO_PARA_O_ARDUINO\arduino-1.0.3\hardware\tools\arm-none-eabi\bin

O erro continuou o mesmo, continuando a entender o código percebi os “abspath” e pensei que poderia estar dando problema por eu estar usando caminhos absolutos então removi todos os “$(abspath” lembrando que o mesmo possui um parêntesis que fecha o comando. Então por exemplo:

$(abspath $(COMPILERPATH)) ficará $(COMPILERPATH)

Tentando compilar novamente com cs-make, iniciou a compilar mas no final aconteceu o seguinte erro:

C:\Users\X-warrior\Desktop\arduino-1.0.3\hardware\tools\arm-none-eabi\bin/arm-none-eabi-objcopy -O ihex -R .eeprom main.elf main.hex
C:\Users\X-warrior\Desktop\arduino-1.0.3\hardware\tools/teensy_post_compile -file=main -path= -tools=C:\Users\X-warrior\Desktop\arduino-1.0.3\hardware\tools
Opening Teensy Loader…
Teensy Loader could not find the file main
cs-make.exe: *** [main.hex] Error 1

Analisando o arquivo encontrei: “path=$(shell pwd)” e me pareceu que pwd não era um comando válido de shell em windows. Testei no console, e não era. Então alterei para “path=$(shell echo %cd%)”. Antes de compilar novamente decidi tentar limpar os arquivos que já foram gerados com cs-make clean

O erro encontrado foi:

C:\Users\X-warrior\Desktop\arduino-1.0.3\Projects\Example_not_working>cs-make.exe clean
rm -f *.o *.d main.elf main.hex
process_begin: CreateProcess(NULL, rm -f *.o *.d main.elf main.hex, …) failed.
make (e=2): The system cannot find the file specified.
cs-make.exe: *** [clean] Error 2

E me pareceu que ele estava chamando rm -f no windows o que também não é um comando válido. Alterei o comando rf para:

del *.o
del *.d
del $(TARGET).elf
del $(TARGET).hex

Com isso consegui limpar os arquivos. E tentei compilar novamente e funcionou! Realizei uns testes alterando o main.cpp e estava sendo compilado e enviado ao meu Teensy 3.0 como deveria ser. De qualquer forma trabalhar com todos aqueles arquivos e os meus juntos seria um tanto quanto trabalhoso, então copiei todos os arquivos com exceção do Makefile e do main.cpp para teensy/ dentro do meu projeto. Assim eu conseguiria compilar com o Makefile sem ter todos os arquivos em uma confusão. Alterei os CPP e C files para:

C_FILES := $(wildcard *.c) \
$(wildcard $(addprefix teensy/, *.c)) \
$(wildcard $(addprefix teensy/util, *.c)) \
$(wildcard $(addprefix teensy/avr, *.c))
CPP_FILES := $(wildcard *.cpp) \
$(wildcard $(addprefix teensy/, *.cpp)) \
$(wildcard $(addprefix teensy/util, *.cpp)) \
$(wildcard $(addprefix teensy/avr, *.cpp))
OBJS := $(C_FILES:.c=.o) $(CPP_FILES:.cpp=.o)

As configurações do linker para:

LDFLAGS = -Os -Wl,–gc-sections -mcpu=cortex-m4 -mthumb -Tteensy/mk20dx128.ld

E para ficar consistente:

$(TARGET).elf: $(OBJS) teensy/mk20dx128.ld
$(CC) $(LDFLAGS) -o $@ $(OBJS)

E encontrei o seguinte erro:

teensy/keylayouts.c:1: fatal error: avr/pgmspace.h: No such file or directory
compilation terminated.
cs-make: *** [teensy/keylayouts.o] Error 1

Alterei as CPPFLAGS para:

CPPFLAGS = -Wall -g -Os -mcpu=cortex-m4 -mthumb -nostdlib -MMD $(OPTIONS) -I. -Iteensy/

E também lembrei que o clean deveria ser alterado para:

clean:
del *.o
del *.d
del $(TARGET).elf
del $(TARGET).hex
del $(CURRENT_PATH)\teensy\*.o
del $(CURRENT_PATH)\teensy\*.d

E adicionei:

CURRENT_PATH=$(shell echo %cd%)

Logo após as configurações que não devem ser alteradas pelo usuário. Com isso consegui utilizar o Makefile no Windows 7 para compilar e fazer upload para o Teensy 3.0 e mantendo os arquivos separados.

Resumo:
Você deve editar as váriaveis TOOLSPATH , COMPILERPATH e LIBRARYPATH para o seu caminho COMPLETO.
Em seguida crie uma pasta para o seu projeto “Meu_Projeto”
Crie uma pasta dentro dela chamada “teensy” (Meu_Projeto/teensy/)
Copie “arduino-1.0.3\hardware/teensy/cores/teensy3/” para “Meu_Projeto/teensy/” (os sub-diretórios também, mas o Makefile não)
Adicione o Makefile que você encontra no final deste post em “Meu_Projeto”
Copie o arquivo “Meu_Projeto/teensy/main.cpp” para o “Meu_Projeto/main.cpp”
Programe apartir do main.cpp
Compile e faça Upload com cs-make

Makefile para Teensy no Windows

Espero que seja útil,
Matheus

Publicado emCcppTeensywindows

3.680 Comentários

  1. 888starz O’zbekistonda mahalliy foydalanuvchilar uchun qulay o’zbekcha interfeys taqdim etadi.
    Foydalanuvchilar jonli kazino stollarida real dilerlar bilan istalgan vaqtda o’ynashlari mumkin.
    888 бет https://888-uz8.com/
    Sayt jahon va mahalliy ligalarga, shu jumladan O’zbekiston chempionatiga stavkalar qo’yish imkonini beradi.
    Foydalanuvchilar uchun haftalik keshbek va promo aksiyalar doimiy ravishda mavjud.
    Saytda ro’yxatdan o’tish bir necha daqiqa ichida bir nechta usulda mumkin.

  2. Easy to recommend without reservations, the site delivers on every promise it implicitly makes, and a look at purposehaven kept that same standard going, the kind of consistency that earns trust over time rather than chasing it through aggressive marketing is what I see here and it is appreciated greatly by this particular reader today.

  3. يقدم الموقع الرسمي 888starz للاعبين المصريين بيئة آمنة تضم الكازينو والمراهنات الرياضية.
    كازينو 888 تسجيل الدخول https://wiki.tgt.eu.com/index.php?title=%d9%83%d8%a7%d8%b2%d9%8a%d9%86%d9%88_888_%d8%aa%d8%b3%d8%ac%d9%8a%d9%84_%d8%a7%d9%84%d8%af%d8%ae%d9%88%d9%84:_%d8%b3%d9%84%d9%88%d8%aa%d8%b3_%d9%88%d9%85%d8%a8%d8%a7%d8%b1%d9%8a%d8%a7%d8%aa_%d9%88%d8%b1%d9%87%d8%a7%d9%86%d8%a7%d8%aa_%d9%81%d9%8a_%d9%85%d9%83%d8%a7%d9%86_%d9%88%d8%a7%d8%ad%d8%af
    تتوفر تجربة الكازينو المباشر بموزعين حقيقيين تعمل على مدار الساعة بجودة عالية.

    يدعم الموقع المراهنة الحية مع بث للنتائج وتغير الأودز في الوقت الفعلي.

    تتوفر عروض دورية مثل الاسترداد النقدي والتأمين على الرهانات طوال الأسبوع.

    يقدم التطبيق تجربة مستقرة وتصميمًا سهل الاستخدام على الأجهزة المحمولة.

  4. Reading this brought back the satisfaction I used to get from blogs ten years ago, and a stop at radianttouch kept that nostalgic quality alive, sites that capture what was good about an earlier era of internet writing are increasingly precious and this one is doing that without feeling like a deliberate throwback at all.

  5. Roberterymn Roberterymn

    Эта статья подробно расскажет о процессе выздоровления, который включает в себя эмоциональную, физическую и психологическую реабилитацию. Мы обсуждаем значимость поддержки и наличие профессиональных программ. Читатели узнают, как строить новую жизнь и не возвращаться к старым привычкам.
    Подробнее – clinica plus в находке

  6. Robertisord Robertisord

    В этой статье мы рассмотрим современные достижения в области медицины, включая инновационные методы лечения и диагностики. Мы обсудим важность профилактики заболеваний и роль технологий в улучшении качества здравоохранения. Читатели узнают о влиянии медицины на повседневную жизнь и ее значение для современного общества.
    Получить дополнительную информацию – капельница от запоя ростов на дону

  7. Rasmiy saytga kirish orqali foydalanuvchilar barcha o’yin va tikish bo’limlaridan foydalanishlari mumkin.

    Foydalanuvchilar rasmiy sayt orqali jonli kazino stollarida istalgan vaqtda o’ynashlari mumkin.

    Rasmiy saytda futbol, tennis, basketbol va kibersport kabi ko’plab sport turlari mavjud.

    888starz rasmiy veb-sayti mahalliy foydalanuvchilar uchun qulay to’lov tizimini taklif etadi.
    888starbet https://888starz-uzb1.com/

  8. 888 starz зеркало https://888starz-uzb2.com/
    Rasmiy saytning bosh sahifasida eng muhim o’yinlar va tadbirlar darhol ko’rsatiladi.
    888starz rasmiy sayti ishonchli provayderlardan keng slot va stol o’yinlari to’plamini taklif etadi.
    Rasmiy sayt raqobatbardosh koeffitsiyentlar bilan jonli tikish rejimini taklif etadi.
    888starz rasmiy veb-sayti himoyalangan tizim orqali ishonchli o’yin muhitini yaratadi.

  9. Quality you can feel from the first paragraph, the writer clearly knows the topic and how to share it, and a quick look at trillsaddle confirmed the same depth runs throughout the rest of the site as well which is rare and worth pointing out when it happens online for any reader passing through.

  10. Reading this gave me a small jolt of recognition for an experience I thought was just mine, and a stop at artistnexus produced more such jolts, content that universalises private experiences without flattening them is doing genuinely useful work and this site is providing that recognition function for me reliably across topics I read.

  11. Bookmark added in three places to make sure I do not lose the link, and a look at businessnova got the same redundant treatment, sites I am afraid to lose are the rare keepers and this is clearly one of them based on what I have read so far across this and a couple of related posts.

  12. Reading this back to back with a similar piece elsewhere made the quality difference obvious, and a stop at supportnexus only widened the gap, comparing content side by side is a useful exercise and the gap between this site and average competitors in the space is large enough to be noticeable from the first paragraph.

  13. Reading this in the gap between work projects was a small but meaningful break, and a stop at humorvertex extended that gentle reset, content that provides genuine refreshment rather than just distraction during work breaks is content with a particular kind of utility and this site fits that role for me reliably during work days.

  14. Roberterymn Roberterymn

    Публикация охватывает основные направления развития современной медицины. Мы обсудим значимость научных исследований, инноваций в лечении и роли общественного участия в формировании системы здравоохранения.
    Изучить эмпирические данные – клиника плюс

  15. Found something quietly useful here that I expect to return to, and a stop at silverpathhub added more of the same, content with quiet utility ages well in a way that flashy hot takes do not and I have learned to weight quiet utility much higher when deciding what to bookmark for later use.

  16. JamesSleex JamesSleex

    Эта публикация исследует взаимосвязь зависимости и психологии. Мы обсудим, как психологические аспекты влияют на появление зависимостей и процесс выздоровления. Читатели смогут понять важность профессиональной поддержки и применения научных подходов в терапии.
    Более того — здесь – вызвать капельницу от запоя на дому

  17. Elmerculty Elmerculty

    В этой статье мы рассматриваем разные способы борьбы с алкогольной зависимостью. Обсуждаются методы лечения, программы реабилитации и советы для поддержки близких. Читатели получат информацию о том, как преодолеть зависимость и добиться успешного выздоровления.
    Более того — здесь – кодировка от алкоголя в ростове-на-дону

  18. Top notch writing, every paragraph carries weight and nothing feels like filler, and a stop at modernlivinghub reflected that same care, a rare thing on the open web these days where most pages exist for clicks rather than actual reader value or anything close to that which is honestly a real shame.

  19. Bookmark moved to my permanent reference folder rather than the casual maybe later folder, and a look at tattooharbor earned the same upgrade, the distinction between casual interest and lasting reference is something I track carefully and very few sites cross that threshold but this one did so without much effort apparently.

  20. WilliamLox WilliamLox

    В этой публикации мы предложим ряд рекомендаций по избавлению от зависимостей и успешному восстановлению. Мы обсудим методы привлечения поддержки и важность самосознания. Эти советы помогут людям вернуться к нормальной жизни и стать на путь выздоровления.
    Прочесть заключение эксперта – клиника плюс

  21. Now appreciating that the post left me with enough to say in a follow up conversation, and a look at connectnexus added more material for those follow ups, content that prepares me for related conversations rather than just informing me alone is content with social utility and this site provides that social armament reliably for me.

  22. WilliamDom WilliamDom

    Обзор посвящён процессу восстановления после зависимостей. Мы расскажем о различных этапах реабилитации, поддерживающих ресурсах и важности мотивации в достижении устойчивого выздоровления.
    Смотрите также – нарколог на дом в Пензе

  23. Domingopah Domingopah

    Эта статья подробно расскажет о процессе выздоровления, который включает в себя эмоциональную, физическую и психологическую реабилитацию. Мы обсуждаем значимость поддержки и наличие профессиональных программ. Читатели узнают, как строить новую жизнь и не возвращаться к старым привычкам.
    Только факты! – oryol clinica plus

  24. DerrickJed DerrickJed

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

  25. Shawnmug Shawnmug

    В этой статье рассматриваются способы преодоления зависимости и успешные истории людей, которые справились с этой проблемой. Мы обсудим важность поддержки со стороны близких и профессионалов, а также стратегии, которые могут помочь в процессе выздоровления. Научитесь первоочередным шагам к новой жизни.
    Неизвестные факты о… – клиника плюс

  26. Now feeling confident that this site will continue producing work I will want to read, and a look at parcelvoyager extended that confidence into the future, projecting forward from current quality to expected future quality is something I do for sites I genuinely follow and this one has earned that forward looking trust clearly today.

  27. Now thinking I want more sites built on this kind of editorial foundation, and a stop at urbanwellness extended that wish into a broader hope, sites built on substance and care rather than on metrics and growth are the kind of sites I want to see more of and this one is a small example worth supporting.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *