GithubHelp home page GithubHelp logo

hexagon5un / avr-programming Goto Github PK

View Code? Open in Web Editor NEW
719.0 101.0 338.0 2.72 MB

Code examples for the book "Make: AVR Programming"

Home Page: http://littlehacks.org/AVR-Programming

License: MIT License

Makefile 39.02% C 51.46% C++ 0.30% Python 4.12% MATLAB 0.48% Objective-C 4.62%

avr-programming's Introduction

Code and Examples from "Make: AVR Programming"

Welcome!

Here you'll find all the code (and more!) for the Maker Media book Make: AVR Programming.

Getting Started

  • First, download the contents of this repository onto your hard-drive. The easiest way is with the "Download ZIP" button above and on the right-hand side of this very web page. Extract the zip file wherever is comfy. (Feel free to clone the repo if you are comfortable with Git.)

  • Most of the projects share a common set of pin defines and a common simple USART serial library in the AVR-Programming-Library directory. The makefiles I've included depend on the directory structure here by default, so don't go moving the folders around unless you also change the path to included files in the makefile.

  • If you're using the Arduino IDE, you'll want to copy the AVR-Programming-Library directory into your sketchbook/libraries folder. If you don't know where this is, you can find out in the "File...Settings" dialog within Arduino. Now you can link your code to use this library simply using "Sketch...Import Library" and selecting the library from the the menu.

  • Now you will be set to open the code, edit it, and flash it into the AVR following the directions in the book.

Repo Layout

All of the project code is organized by the chapters in the book. So if you're looking for an example of some SPI code, see the "Chapter16_SPI" folder for SPI-related projects. That's obvious.

But a bunch of the projects are interesting in addition to the topic covered in the chapter. For instance, "Chapter05_Serial-IO" includes a project that uses the serial communication between your desktop computer and the AVR to turn your computer keyboard into a musical keyboard that plays notes generated on the AVR, turning it into a serial-port-controlled organ. You wouldn't think to go looking in the Serial I/O chapter unles you were following along in the book.

So for an overview all the projects, the file allProjectsList lists them all out by name.

setupProject

If you'd like a blank template to start writing your own AVR code, have a look in the setupProject directory that I've included here. Inside, you'll find main.c and main.h files that are essentially blank and ready to go. main.c makes use of my simple USART library, which is also included an linked in by the Makefile. In short, you could copy this directory, rename files, and start using it in your own projects.

But you don't have to do that manually. Running python setupProject.py myProjectName will create a directory called myProjectName for you, copy the blank main files, renaming them as appropriate, and set up the Makefile accordingly. All that's left for you to do is the hard part -- actually coding.

If you use this setup a lot, you'll want to personalize the Makefile and the two main files to suit your own preferences. That way, whenever you start up a new project, it'll include a customized Makefile that has your programmer, chip type, and favorite baud rate already set.

Finally, if you like to map out your pin definitions in macro definitions, run python createPinDefines.py. The program will ask you what you'd like to call each pin macro (e.g. "LED0") and then which pin on the AVR you'd like to associate with it (e.g. "PB1"). When you're done entering your pin layout, it'll create a "pinDefines.h" file with (I hope) nicely-named macros. Move this file into the right directory, and include it in your code. Calling LED0_SET_HIGH will turn your LED on.

More!

You've read the book, you've built the projects, you've worked through the code. But still you hunger for more projects, more examples, more, more, more! If I may toot my own horn, you should visit LittleHacks.org where I blog about whatever microcontroller projects I'm currently up to.

In particular, if you're reading Make: AVR Programming, and you're interested in fully-elaborated versions of the projects with more photos, videos, and explanation than could fit in a book, head on over to LittleHacks.org's AVR-Programming Section.

Once you've exhausted all of these resources, you should definitely head over to The Cornell University ECE 4760 Final Projects list page. It's an awe-inspiring collection of applications, and sure to spark some creative thoughts. It's all well-documented and there's tons of source code in C. [Professor Land's links section] (http://people.ece.cornell.edu/land/courses/ece4760/#links) is also top-notch, and his lectures on YouTube are also worth a look if you're getting serious about this whole AVR deal.

avr-programming's People

Contributors

hexagon5un avatar sachleen avatar thomasaw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

avr-programming's Issues

USART does not work

Hi, can someone help me I'm using AVR studio 7 and when I compile the SerialLoopback code I get the folowing error's:

 Description                                                                    File                   Line
 #error "F_CPU must be a constant value"                                   setbaud.h                    121
 #error "setboud.h requires F_CPU to be defined"                        setbaud.h                    113
 #warning "UBRR value overflow" [-Wcpp]                                   setbaud.h                     235
 #'F_CPU' undeclared (first use in this function)                          USART.c                       24

the code I use is:

/*

  • serialLoopback.c
    *
  • Created: 31-1-2016 11:28:35
  • Author : Dark
    A simple test of serial-port functionality.
    Takes in a character at a time and sends it right back out,
    displaying the ASCII value on the LEDs.
    */

define F_CPU 100000 UL

// ------- Preamble -------- //

include <avr/io.h>

include <util/delay.h>

include "lib/pinDefines.h"

include "lib/USART.h"

int main(void) {
char serialCharacter;
// -------- Inits --------- //
LED_DDR = 0xff; /* set up LEDs for output /
initUSART();
printString("Hello World!\r\n"); /
to test /
// ------ Event loop ------ //
while (1) {
serialCharacter = receiveByte();
transmitByte(serialCharacter);
LED_PORT = serialCharacter;
/
display ascii/numeric value of character /
} /
End event loop */
return (0);
}

thanks in advance

Chapter 8 Interrupt code and serialScope do not match together

There is something odd in the setup.
The serial scope under https://github.com/hexagon5un/AVR-Programming/blob/master/Chapter08_Hardware-Interrupts/capSense/serialScope.py
does only handle USART data in terms of reading it as ord (https://github.com/hexagon5un/AVR-Programming/blob/master/Chapter08_Hardware-Interrupts/capSense/serialScope.py#L6)

But the entire capSense code at trunk does not work well with that. It sends string data and newlines to the serial scope making no sense. See here and here.
The capSense line

printString("==[ Cap Sensor ]==\r\n\r\n");

and others cannot be interpreted properly by the mentioned serial scope python script.


(Bonus brag :) )
I also spent about two days trying to get this working without success because I am using Atmel Studio with my custom defined header and project files (not the Makefiles), where I've defined #define F_CPU 1000000UL // 1 MHz
Since this chapter delays the explanation of the line clock_prescale_set(clock_div_1); /* full speed */ and does not even briefly mention that F_CPU must be adjusted here I would somewhere drop a hint for newbies like me.

Unused makefile definitions

Hi, first of all thanks for this awesome resource. I just had a look at the chapter 2 makefile and I noticed there are two variable definitions that are never used in any of the rules:

##List of all header files
HEADERS = $(SRC:.c=.h) 

##For every .c file, compile an .o object file
OBJ = $(SRC:.c=.o) 

Probably remnants from an earlier version?

undefined reference to `initUsart'

I'm trying to upload a serial example and when trying to compile I get these errors:

alkopop79$ avr-gcc -g -mmcu=atmega328p -o serial.elf serial.o
serial.o: In function main': /Users/alkopop79/Documents/AVR/serial/serial.c:9: undefined reference toinitUsart'
/Users/alkopop79/Documents/AVR/serial/serial.c:10: undefined reference to printString' /Users/alkopop79/Documents/AVR/serial/serial.c:13: undefined reference torecieveByte'
/Users/alkopop79/Documents/AVR/serial/serial.c:14: undefined reference to `transmitByte'
collect2: error: ld returned 1 exit status

I wonder what am I doing wrong? I'm using avrdude in Terminal (OS X) and an Arduino Nano board. So far I have managed to upload the Blink example successfully.

file not found error on first make attempt

Hi,
I have tried the blinkLED example and get this error on make
C:\AVR-Programming-master\Chapter02_Programming-AVRs\blinkLED>make flash
avr-gcc -Os -g -std=gnu99 -Wall -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -ffunction-sections -fdata-sections -DF_CPU=1000000UL -DBAUD=9600UL -I. -I../../AVR-Programming-Library -mmcu=atmega168p -c -o blinkLED.o blinkLED.c
process_begin: CreateProcess(NULL, avr-gcc -Os -g -std=gnu99 -Wall -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -ffunction-sections -fdata-sections -DF_CPU=1000000UL -DBAUD=9600UL -I. -I../../AVR-Programming-Library -mmcu=atmega168p -c -o blinkLED.o blinkLED.c, ...) failed.
make (e=2): The system cannot find the file specified.
make: *** [blinkLED.o] Error 2

The AVR-Programming-Library is 2 folders above my source/make
The avrdude_utilities is on my search so I can run make from the source folder

From what I remember of make, all .c files in a folder and those in the LIBDIR are linked and compiled to an object file?

I am not sure what this error is telling me. It appears to say it can't find the object, but isn't that what make does, creates the object file, blinkLED.o ?

Any help is welcome!

Tony

avr 328p, crystal and leds

If a crystal is used, this does make DDRB unusable for using it for the LEDs, as in the book? Or is there a trick to make it work?
The crystal is covering up the PB6 and PB7 pins.

Related:
#24

Makefile not working xmega

I am trying to program the xmega128a1u with blink code. I made the changes form DDRB to PORTB.DIRSET and so on, but the makefile is having an error in compiling the code.

avr-gcc -Os -g -std=gnu99 -Wall -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -ffunction-sections -fdata-sections -DF_CPU=8000000UL -DBAUD=9600UL -I. -I../../xmegalibrary -mmcu=atxmega128a1u -c -o blinkLED.o blinkLED.c
:0:6: error: expected identifier or ‘(’ before numeric constant
: recipe for target 'blinkLED.o' failed
make: *** [blinkLED.o] Error 1

Help?

Hi!
I'm reading the book and doing all the projects. On the chapter that talks about the hardware interrupts I'm stuck trying to make two pins to change state. This is my code:

include <avr/io.h>

include <util/delay.h>

include <avr/interrupt.h>

include "pinDefines.h"

ISR(PCINT2_vect) { /Run every time there is a change on button... ISR is a macro that denotes a function of interrupt.h/
if (bit_is_set(BUTTON_PIN, BUTTON)) //PIND, PD2//
{
LED_PORT |= (1 << LED1); //PORTB, PB1//
}
else {
LED_PORT &= ~(1 << LED1); //PORTB, PB1//
}

if (bit_is_set(BUTTON_PIN, BUTTON3)) 
{
    LED_PORT |= (1 << LED1); 
}
else {
    LED_PORT &= ~(1 << LED1); 
}

}

void initInterrupt18(void) {
PCICR |= (1 << PCIE2); /* Set pin-change interrupt for D pins /
PCMSK2 |= (1 << PCINT18); /
Set mask to look for PCINT18 / PD2 /
//PCMSK2 |= ((1 << PD2) | (1 << PD4)); //This works as well for the pin mask */
sei(); /
Set (global) interrupt enable bit */
}

void initInterrupt20(void) {
PCICR |= (1 << PCIE2);
PCMSK2 |= (1 << PCINT20);
sei();
}

int main(void)
{
// ------ Inits -------//
LED_DDR = 0xff; // All LEDs active //
BUTTON_PORT |= (1 << BUTTON); // Pullup on PD2 AND PD4. BUTTON_PORT IS PORTD IN PINDEFINES.H //
BUTTON_PORT |= (1 << BUTTON3); // Pullup on PD4. BUTTON_PORT IS PORTD IN PINDEFINES.H //
initInterrupt18();
initInterrupt20();

while(1)
{
    //TODO:: Please write your application code
    _delay_ms(200);
    LED_PORT ^= (1 << LED0); // PB0 IN PORTB

}
return(0);

}

When I program the microcontroller I get PD4 to behave as expected but PD2 doesn't. I had tried before using the method described in the book (PCMSK2 |= ((1 <<PD2) | (1<<PD4));) but it didn't work either.

What am I doing wrong?

Serial output from CapSense example in Chapter08 is garbage

Hi Elliot
I'm currently working with your AVR-Programming book. All examples until now did just work fine. But now I stuck in the CapSense example in chapter08. The serial output from this code is just garbage. Only strange symbols. I use the ATmega168P with WinAVR and I already downloaded the latest zip file with the code examples here to make sure that I have the latest version and all code is untouched. But still there is nothing but garbage comming from serial output. The serial output from the programs in all chapters before worked just fine.
Do you have an idea what the problem could be here?

Thanks a lot for any kind of help and for this great book!!

BR
Boris

Hi again :-)
After some experimenting with the code I now found out, that I get readable results from the serial output, if I remove the "full speed" command: clock_prescale_set(clock_div_1); /* full speed */.
But then I only get results about 80 or 85 counts. This can't be correct I guess?

BR
Boris

Issue with Serial Connection on Arduino

I am currently on Chapter 5. So the thing is I am using an Arduino (meaning using the m328p). I flash my arduino with the SerialLoopback code. I hook up a USB to TTL from my computer onto my Arduino.

It is strange, because when I set the bit rate on the serial monitor to 9600, the LED lights are not lighting up. In addition to that, the serial monitor is printing out unreadable code.

The only way the LED lights are lighting up is if I set the BAUD rate to 115200. However, I am still getting gibberish data printed out on the serial monitor. Why is it that when I set the BAUD rate to 9600, I don't get any LED lights lighting up (the RX and TX lights on the USB to TTL do happen to flash)

pwmOnAnyPin: Incorrect register bit access

I'm just writing this for clarity, In pwmOnAnyPin.c, In the initTimer0(void) function, there's this line

TIMSK0 |= ((1 << OCIE0A) | (1 << OCIE1B));

I think it is OCIE0B not OCIE1B
I don't think it affect the exicution of code, both means (1 << 2)

compiler warnings atmel328p

Chapter 07
using the atmel328P

Wondering why I get these compile warnings. slowScope is working here anyway.

$ sudo make flash avr-gcc -Os -g -std=gnu99 -Wall -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -ffunction-sections -fdata-sections -DF_CPU=16000000UL -DBAUD=9600UL -I. -I../../AVR-Programming-Library -mmcu=atmega328p -c -o slowScope.o slowScope.c In file included from /usr/avr/include/avr/io.h:99, from slowScope.c:4: In function 'initFreerunningADC', inlined from 'main' at slowScope.c:27:3: slowScope.c:13:3: warning: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-Warray-bounds=] 13 | ADMUX |= (1 << REFS0); /* reference voltage on AVCC */ | ^~~~~ In function 'main': cc1: note: source object is likely at address zero In function 'initFreerunningADC', inlined from 'main' at slowScope.c:27:3: slowScope.c:13:9: warning: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-Warray-bounds=] 13 | ADMUX |= (1 << REFS0); /* reference voltage on AVCC */ | ^ In function 'main': cc1: note: source object is likely at address zero In function 'initFreerunningADC', inlined from 'main' at slowScope.c:27:3: slowScope.c:15:3: warning: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-Warray-bounds=] 15 | ADCSRA |= (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); /* ADC clock prescaler /16 */ | ^~~~~~ In function 'main': cc1: note: source object is likely at address zero In function 'initFreerunningADC', inlined from 'main' at slowScope.c:27:3: slowScope.c:15:10: warning: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-Warray-bounds=] 15 | ADCSRA |= (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); /* ADC clock prescaler /16 */ | ^ In function 'main': cc1: note: source object is likely at address zero In function 'initFreerunningADC', inlined from 'main' at slowScope.c:27:3: slowScope.c:17:3: warning: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-Warray-bounds=] 17 | ADMUX |= (1 << ADLAR); /* left-adjust result, return only 8 bits */ | ^~~~~ In function 'main': cc1: note: source object is likely at address zero In function 'initFreerunningADC', inlined from 'main' at slowScope.c:27:3: slowScope.c:17:9: warning: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-Warray-bounds=] 17 | ADMUX |= (1 << ADLAR); /* left-adjust result, return only 8 bits */ | ^ In function 'main': cc1: note: source object is likely at address zero In function 'main': cc1: note: source object is likely at address zero In function 'initFreerunningADC', inlined from 'main' at slowScope.c:27:3: slowScope.c:19:3: warning: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-Wa 19 | ADCSRA |= (1 << ADEN); /* enable ADC */ | ^~~~~~ In function 'main': cc1: note: source object is likely at address zero In function 'initFreerunningADC', inlined from 'main' at slowScope.c:27:3: slowScope.c:19:10: warning: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-W 19 | ADCSRA |= (1 << ADEN); /* enable ADC */ | ^ In function 'main': cc1: note: source object is likely at address zero In function 'initFreerunningADC', inlined from 'main' at slowScope.c:27:3: slowScope.c:20:3: warning: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-Wa 20 | ADCSRA |= (1 << ADATE); /* auto-trigger enable */ | ^~~~~~ In function 'main': cc1: note: source object is likely at address zero In function 'initFreerunningADC', inlined from 'main' at slowScope.c:27:3: slowScope.c:20:10: warning: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-W 20 | ADCSRA |= (1 << ADATE); /* auto-trigger enable */ | ^ In function 'main': cc1: note: source object is likely at address zero In function 'initFreerunningADC', inlined from 'main' at slowScope.c:27:3: slowScope.c:21:3: warning: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-Wa 21 | ADCSRA |= (1 << ADSC); /* start first conversion */ | ^~~~~~ In function 'main': cc1: note: source object is likely at address zero In function 'initFreerunningADC', inlined from 'main' at slowScope.c:27:3: slowScope.c:21:10: warning: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-W 21 | ADCSRA |= (1 << ADSC); /* start first conversion */ | ^ In function 'main': cc1: note: source object is likely at address zero slowScope.c:30:5: warning: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-Wa 30 | transmitByte(ADCH); /* transmit the high byte, left-adjusted */ | ^~~~~~~~~~~~~~~~~~ cc1: note: source object is likely at address zero avr-gcc -Wl,-Map,slowScope.map -Wl,--gc-sections -mmcu=atmega328p slowScope.o ../../AVR-Programming-Library/USART.o -o slowScope avr-objcopy -j .text -j .data -O ihex slowScope.elf slowScope.hex avrdude -c usbasp -p atmega328p -P usb -U flash:w:slowScope.hex avrdude: AVR device initialized and ready to accept instructions

Windows 10. avr-gcc and avrdude want different MCU strings

At first I hit "make flash" and get this:
avrdude
I change "atmega16a" to "m16" in the Makefile and it worked.
But then i edited the code and when compiling it I get this:
avrgcc
I change it back to "atmega16". It compiles but avrdude complains again.
To fix this i replaced "MCU" in line 51 with the appropriate string for avr-gcc ("atmega16a" in my case)
Just thought I should mention this here.

issue building makefile on ubuntu

whenever i try to build any of the makefiles i get this error.

gcc: fatal error: input file ‘Makefile’ is the same as output file
compilation terminated.

Instructions for using examples with ATtiny chips

I'm using the book with an ATtiny84, and while I understand that this chip doesn't have a USART I can't see why some of the examples wouldn't work if I can get them to compile.

However I'm trying to work out how to exclude the USART from being compiled - short of deleting USART.c, is there a better way?

Also, I'm not 100% convinced that the fuse values in the default makefiles are correct for the ATtiny84 and the last thing I want to do is brick the chip... in particular the Extended fuse value differs - in the Makefile it is set to 0x00 but the default fuse value for the ATtiny84 is 0xFF. It looks like writing 0x00 to efuse will enable SELFPRGEN which seems benign, but I'm not sure.

ATmega168 on the left, ATtiny84 on the right:

image

question about makefile

%.o: %.c $(HEADERS) Makefile

This line means each object file has dependencies on .c file and all header file and Makefile
However in each project, each .c file did not have corresponding header file
For example blankLED project did not have blankLED.h file
So how to explain about this?

Help on USART Communication

Hi,

I am working with your book and get stuck in chapter 5 "Serial I/O".

When wiring up the serialLoopBack example (code and breadboard) I receive only garbage on the computer side.

So i simplified the code, but still gets garbage. Unfortunately your book, does not give any suggestion in the case, something is received, but the received values are not what was expected.

Any ideas what might be wrong?

Here is the Code / Using a simple setup (just a FTDI Serial Connection):

ATMEL Code

#include <avr/io.h>
#include <util/delay.h>
#include "pinDefines.h"
#include "USART.h"

#define DELAY 100
#define BAUDRATE 9600


int main(void) {
    initUSART();
    uint8_t serialCharacter = 0;
    while (1) {
        serialCharacter++;
        printByte('c');
        transmitByte(serialCharacter);
        _delay_ms(DELAY);
    }

    return (0);
}

Python Code

SERIAL_PORT = "/dev/cu.usbserial-AH02DXO3"
BAUD_RATE=9600

import serial

sp = serial.Serial(SERIAL_PORT,BAUD_RATE, timeout=5)
sp.flush()

while (1):
    response = sp.read(1)
    print "[" + response + "]" + "[" + str(ord(response)) + "]" 
    print "--------------------------------------------------"

Unfortunately I can see, nor the character "c", nor any values incrementing:
This is the Output:

[?][128]
--------------------------------------------------
[][0]
--------------------------------------------------
[][0]
--------------------------------------------------
[?][128]
--------------------------------------------------
[][0]
--------------------------------------------------
[][0]

what is missing in the implementation, or configuration? Where should I continue searching?

examples 11-1 vs 11-2, prescaling and count speed

Example 11-1 uses / 1 prescaling, while example 11-2 is using / 8. Still the ICR1 are both on 20000, marked as 20ms in the comments. If the prescaling differs, then the speed of the count is not the same right? So how can they be both 20ms with different prescaling?

Serial Loopback with ATMega328p-pu

Hi,

I'm trying to get the serial loopback from Chapter 5 working with my ATMega328p-pu chip. I've tried changing F_CPU as well as updating the fuses, but it seems that no matter what I change the fastest I can get is 3600 baud. I'm not sure if I'm doing something wrong, or if 3600 baud is the fastest this chip can do (without an external crystal).

Thanks in advance!

Chapter 12 Footstep Detector - Minor Fix for Serial Comm

This isn't really a fix, just an alternative for terminals to read the serial data as ASCII instead of bytes:

Original code:
transmitByte(adcValue - 512 + 127);
transmitByte((lowValue >> 4) - 512 + 127);
transmitByte((highValue >> 4) - 512 + 127);
_delay_ms(CYCLE_DELAY);

Replace with:
printByte(adcValue - 512 + 127);
printString(" - ");
printByte((lowValue >> 4) - 512 + 127);
printString(" - ");
printByte((highValue >> 4) - 512 + 127);
printString("\r\n");
_delay_ms(CYCLE_DELAY);

The serial comm will look like this afterward:
124 - 124 - 125
124 - 124 - 125
124 - 124 - 125
124 - 124 - 125
...

Hope this helps!

-TheEJM3

massively redundant makefiles

Rather than forcing the user to configure each and every makefile in each and every project directory, would you consider a refactor which made use of the GNU Make include ?

Ideally, I would think, we could provide one make snippet, in a common directory, for the user to configure, and another with the rules and targets and supporting stuff.

I work this way internally, and my per-project makefiles look like this:

# disable optimization when debugging!
COPTIMIZ	:= 

include ../../make-include/avr8.mak
include ../../make-include/basic.mak

all:	avr-training.html avr-training.pdf

If so, you can assign this issue to me and I can give you a pullable fork you can review. I wouldn't take literally the approach above, I would try to keep the the style of your stuff.

The only gotcha here is that this is a GNU make specific syntax if I am not mistaken. That compatibility issue might be a killer, in which case, just close the ticket.

Missing prototipe

In the file uart.c missing function prototype char nibbleToHexCharacter(uint8_t nibble)

USART.h header file does not work

/*
A simple test of serial-port functionality.
Takes in a character at a time and sends it right back out,
displaying the ASCII value on the LEDs.
*/

// ------- Preamble -------- //
#define F_CPU 12000000UL
#include <avr/io.h>
#include <util/delay.h>
#include "pinDefines.h"
#include "USART.h"

int main(void) {
char serialCharacter;

// -------- Inits --------- //
LED_DDR = 0xff; /* set up LEDs for output /
initUSART();
printString("Hello World!\r\n"); /
to test */

// ------ Event loop ------ //
while (1) {

serialCharacter = receiveByte();
transmitByte(serialCharacter);
LED_PORT = serialCharacter;
                       /* display ascii/numeric value of character */

} /* End event loop */
return 0;
}


ERRORS

error "recipe for target 'USART.o' failed "
error "F_CPU must be a constant value"
error "setbaud.h requires F_CPU to be defined"
#warning "UBRR value overflow" [-Wcpp]
error "F_CPU' undeclared (first use in this function)"
each undeclared identifier is reported only once for each function it appears in
Severity Code Description Project File Line
Error "recipe for target 'USART.o' failed"


using ATMEL STUDIO 7.0.

Unclear statement Chapter 10: only 3 LEDs for hardware PWM when ATmega168PA has 6

Chapter 10, page 206 states

You might be wondering why we're only lighting up three LEDs using the hardware PWM, [...] AVR's dedicated PWM pins are limited to [...] four pins at an 8-bit PWM depth, and two at 16 bits.

That makes the mentioned six PWM channels, ok so far.

The pwmTimers.c examples then continues to use OC2A, OC1B and OC1A output compare pins.

What is the book actually implying here? Can't I use 3 more pins for PWM? AFAIK OCR2B and those of Timer/Counter 0 OC0A and OC0B?

Or is it merely saying that in our current setup, where those 8 LEDs are currently wired to the B bank this would not be possible without rewiring some of those LEDs to the D bank?

Chapter5 Serialloopback. "Strange characters"

Testing serial loopback with the listing in Example 5.1 results in "strange" characters being returned. Entering "a" results in the following LED pattern: 01001111, which is capital "O". Typing "c" for example results in LED pattern 01001110, which is capital "N". The message "hello World" is displayed as ú‹…m:ºê+ë. When connecting USB-serial converter Rx and Tx, characters are returned correctly. The program was successfully flashed into an Atmega 168.
I have no idea where to start looking for possible causes. Any ideas from your side?
Thanks in advance, Folkert

Undefined reference to initUSART

Hi, I'm using AVR studio and when I compile the SerialLoopback code I get an error "undefined reference to 'initUSART. I copied over the USART.h file to my working directory and I'm not receiving any errors for that file.
Thanks,
Derek

Chap 5 - Serial is garbled

I'm trying to get the serial loopback test working. The data I receive back is garbled. I'm using a USB-2-Serial cable. When I remove the AVR and just hook up the serial cable's RX and TX everything is fine. It gets garbled going through the AVR. Any ideas? I've verified the F_CPU and BAUD are correct for my chip. I ordered one of the FTDI cables you talk about in the book. I still suspect there is something about the cable I'm using. If I don't unplug it from the AVR when I attach it to the PC, Windows thinks it is broken?! (weird) Having a lot of fun reading and learning with this book!

Mistake !

DDRB = 0b0000001;(6 zeroes after b)

should be

DDRB = 0b00000001; (7 zeroes after b)

its making the wrong pin as output, according to the circuit in MAKE: Avr programming

littlehacks.org - looks like it's down

Just a heads up!

The home page looks to be a test page ... "The littlehacks virtual host is barely working!" Other pages are not working.

I'll just have to go back to reading your book - which I am really enjoying. :-)

Some code does not compile in Arduino IDE or Atmel Studio

Just a note, perhaps for the next edition of the book. The sample code provided in the book and this repo is for c only compilers (no C++ linkage) and does not compile in Atmel Studio (c++ projects) or the Arduino IDE 1.6.X. The front page of this repo gives instructions on how to setup the Arduino IDE. The instructions are correct but some code does not compile, like the USART.h. With the help of the folks over at AVR Freaks, they pointed this out to me as I am not an expert in C or C++ (I c# by day). Their suggestion was to either add an extern c or rewrite the code in c++. I choose the later as it was great to learn. But I think you should let people know of the issue, because a large chunk of AVR programmers are newbies :) . Although your book does not say we need to use these IDEs/Compilers, most newbies use them. This is just a suggestion. I am an advocate of your book, and I am compelled to inform you.

With that said, your book is outstanding and a create read.

Lost the ability to receive bytes via USART by Chapter 9!

Help! I'm still able to transmit bytes (my atmega168 is able to send text to my terminal) but I'm not able to send data from my terminal to my avr anymore. I first noticed this when I tried to run Chapter 9's reactionTimer.c so I'm wondering if maybe I have a bit set somewhere from a previous program that I need to clear? I've confirmed that my serial-usb connection is working (when I short the tx/rx wires together I can type on my terminal) but my avr isn't picking anything up in receiveByte(). I had all this working back in Chapter 5 so I don't know what could have changed since then. Thanks for any help!

python code updated to python 3

I updated autoPlay.py (Chapter 5, serialOrgan) for python 3 (and skipped the serialorgansongs.jottit.com lines since that site no longer exists) and added some notes for figuring out the current serial port. Thanks so much for this wonderful book!

## Scripting in python to drive the serial-port organ

## So far, the "protocol" is simple.  
## Python routine sends a note, waits for a return character, then sends next, etc.
## Organ listens for notes, when it gets one sends an 'N' to say it's ready
 
import serial

def playString(noteString, serialPort):
  for letter in noteString:
    print(letter)
    serialPort.write(letter.encode())
    returnValue = serialPort.read(1)
    
if __name__ == "__main__":

  import time
  from urllib.request import urlopen

  ## Need to consider alternatives for Mac / Windows
  ## list all serial ports being used: python -m serial.tools.list_ports
  PORT = "/dev/cu.usbserial-14130" # Change this to the current serial port being used
  BAUD = 9600

  s = serial.Serial(PORT, BAUD)
  s.flush()                     
  ## flush clears the buffer so that we're starting fresh
  ## More on serial buffers later.

  ## An intentional example.  You can use this for playing music on purpose.
  playString("f g h j k l ; ]'[", s)
  input("Press enter for next demo\n")

  ## A fun / stupid example.  You can just type stuff and see what comes out.
  playString("hello there, this is a random string turned into 'music'", s)
  input("Press enter for next demo\n")

  ## Website no longer alive... skipping:
  ## A really frivolous example.  Play websites!
  ## Bonus points for first person to tweet themselves a song.
  #print ("Downloading song data from http://serialorgansongs.jottit.com/...")
  #import re
  #contentFilter = re.compile(r'<p>(.*?)</p>')
  #songSite = urlopen("http://serialorgansongs.jottit.com/").read()
  #songText = contentFilter.findall(songSite)[0]
  #playString(songText, s)
 
  ## Or interactive
  mySong = input("\nType in your own song: ")
  playString(mySong, s)

Atmel Studio 7 Serialloopback error USART.H

Hi:

I known that this issue has already been discussed in previous posts, but after reading all of the posts, i still can´t find an answer to this problem.
The project recognizes the USART.H and pinDefines.h, but when i compile, it gives many error. I checked all the code and can't find what i'm doing wrong.
The errors are in the attached file.

if someone has manged to compile and make it work with atmel studio, please help me so i can progress in the book.

Thanks
João Ferreira
error.xlsx

USART.c ATmega16A fix.

When trying to compile for the first time I got this:
Capture
So in USART.c I change "UBR0H" to "UBRH", "UBR0L" to "UBRL" etc. until the code compiled. But when I finally got to actualy using the USART I had to make one last tweak before the serialLoopback.c code worked.
Change:"UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);"
to: " UCSRC = (1 << UCSZ1) | (1 << URSEL) | (1 << UCSZ0); "
This is because you need to set the URSEL bit when you write to the UCSRC register.

Chapter 2 - BlinkLED with ATMega 328p

Hello, congratualations to this great book!
However, I had a very hard time getting BlinkLED from Chapter 2 to work... Figure 2-8 just wouldn't work with the "Atmega328p-pu Chip w/ Arduino UNO Bootloader" that I had purchased from Amazon. I knew that everything was fine with them, as they worked well in my Arduino Uno R3 board. I had the exact same setup as in Figure 2-8, and the Pocket AVR Programmer / usbTiny. However, I always got the "avrdude: initialization failed, rc=-1" error message. The programmer was working as I could see from its blinking lights upon transmission, but it couldn't talk to the Atmega.

On page 39, you are discussing possible causes for this "rc=-1" error - however, it is not mentioned that certain Atmega 328p's (such as mine) are configured such that they need an 8 Mhz or 16 Mhz quartz, as shown in https://www.arduino.cc/en/uploads/Tutorial/BreadboardAVR.png. For me, this was the only way I could overcome this issue. Added the 8 Mhz (16 Mhz) quartz and the 2 20pf capicators - problem solved. It took me 8 hours to figure that out, though :-(

It would be extremely helpful to at least mention this possibility in the book and put a pointer there, otherwise newbies will be extremely frustrated. Maybe for the next edition of the book?

Thanks for the great book otherwise,
Michael

download zip fails with a 0kb download

Hi Elliot, I bought the book (AVR Programming) and arrived here to get the sample files but the download zip just gives a 0kb file in my downloads folder. I've managed to clone the repository with Github desktop, so no probs.

Chapter 9: timerAudio.c

At the beginning of the playNote function, there should be a counter reset, I think. Otherwise some tones get skipped in my case. (It's more problematic for me, since I use an Atmega8 with the 16bit counter).

In organ.c, the variable "wavelength" should called "period" or "timePeriod"

In the file organ.c in Chapter05_Serial-IO, there is a variable called wavelength that is the reciprocal of frequency. However, in every day usage, "wavelength" refers to the the distance between successive crests of a wave (wavelength = v/f, where v is the velocity and f is the frequency), and therefore wavelength is not equal to the reciprocal of frequency. On the other hand, the "period" of a wave is equal to the reciprocal of the frequency: T = 1/f.

Therefore, to increase code readability, in organ.c, the variable "wavelength" should called "period" or "timePeriod".

When changing Makefile new hex is not generated

I was working though the book using the 168 as is used in the book. I got a couple atmega8 chips for something else and figured I'd test them by swapping them into my testbed. I changed the Makefile to reflect the new chip and flashed the new chip. Everything reported as okay but I wasn't getting any activity on the leds. Since the rule for making the hex isn't dependent on changes to the Makefile like the c (etc) files are, the chip was flashed with the hexfile for the atmega168, not the m8 that I needed. Adding the Makefile as a prerequisite to the elf file would most likely fix this issue. Once I modified the .c file everything was rebuilt and the flash after that worked as expected.
Great book. Thanks for that.

Changing baud rate and clock cycle in Make file does nothing (serial not working mega328)

I am using the atmega328, which compiles fine if I change the chip to atmega328 from 168p in the makefile, but in chapter05 for the serial, when I hook the output up to a scope, the baud rate is way off and changing it in the makefile does nothing to the output. also, changing the clock frequency does nothing either. I realize the clock is set with the fuses, so Im not entirely sure what the clock frequency portion of the makefile does, but I tried following the header files back to see where baud rate is set and I cant seem to find the difference between the 168 and 328 that would cause the baud rate to be so far off.

strange behavior with Chapter 5 serialOrgan/organ.c

The microsecond delay in organ.c doesn't work for me using avr-gcc 4.8.1.

for (i = 0; i < period; i++) {
    _delay_us(1);
}

The delay is much longer than expected (~7*period). I can get the code to work using _delay_loop_2(), but it's sparked my curiosity trying to figure out what's going on.

In case anybody else is also curious, I started a thread on AVRFreaks to discuss a code fragment that demonstrates the problem.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.