Файл: C Programming for microcontrollers (Joe Pardue, 2005).pdf

ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 13.06.2025

Просмотров: 2448

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

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

Chapter 2: Quick Start Guide

does. We only need to know how to coax it to do what we need it to do, which in our case is convert Blinky.c into Blinky.hex that we can download to the Butterfly. If you raise the hood on WinAVR you would see a massively complex set of software that has been created over the years by folks involved in the open software movement. When you get a little extra time check out www.sourceforge.net.

When you have questions about WinAVR, and you will, check out the forums on www.AVRFreaks.net, especially the gcc forum, since WinAVR uses gcc to compile the C software. Try searching the forums before asking questions since someone has probably already asked your question and received good responses. Forum helpers tend to get annoyed with newbies who don’t do sufficient background research before asking questions.

Simulation with AVRStudio

Now that you’ve gone to the trouble to construct the hardware, and have the burned fingers to prove it… guess what? You didn’t need to do any of that to test Blinky or get an introduction to C programming for microcontrollers. With a minor modification you can run Blinky in the AVR Studio simulator and learn the introductory C programming ideas in the next chapter without any of the hardware. I decided to do things the hard way, ummm… hardware way because our goal is to control ‘real’ things like LEDs, not virtual things like little boxes on your PC screen. Theoretically, we could have a whole slew of virtual things to control, from LEDs to motors to full blown Cylon robots reeking havoc on your screen, which actually sounds kind of fun, but not nearly so much fun as having a real Cylon robot stomping around your neighborhood scaring the noodles out of your enemies. Fun aside, it is often more practical to simulate software before running it in the real world. You wouldn’t want your Cylon to mistake you, the imperious leader, for an enemy, would you?

The simulator runs your program in a virtual environment that is MUCH slower than the real microcontroller. Most of your code will run plenty fast to simulate, but some things, such as the delay functions take too long to simulate. In Blinky we call _delay_loop_2(30000); We don’t know yet how this function works, but we can guess that we are telling it to do something 30000 times. If we simulate

35

Chapter 2: Quick Start Guide

the delay, the simulated LEDs will move at geologic speeds, making glaciers seem fast, so we remove the delay before simulation.

Open Blinky.c in Programmers Notepad and save it to a new directory, SimBlinky, as SimBlinky.c.

Put comment lines in front of both of the _delay_loop_2() function calls in main():

// _delay_loop_2(30000);

Open the makefile in the Blinky directory

Change the target: TARGET = SimBlinky

Save the makefile to the SimBlinky directory

Run the Make All, then Make Extcoff.

In the AVRStudio open the SimBlinky.coff file.

In the AVRStudio Workspace window click the I/O ATmega169, then the PORTD, you should see: (the following image shows PORTB instead of PORTD, -- live with it)

• In the toolbar click the AutoStep button:

36


Chapter 2: Quick Start Guide

The simulator will run showing the LED scan as a scan of the PORTD and PIND items in the Workspace window:(this shows PORTB but you’ll actually see PORTD)

See, I told you it wasn’t as much fun as watching real LEDs blink.

Spend some time with the AVR Studio simulator and associated help files; you’ll find the effort well worth it in the long run.

GOOD GRIEF!

That was a ‘Quick Start’???? Well, maybe things would go quicker if you wanted to pay a fortune for a software and hardware development system, but for FREE software, and unbelievably cheap hardware, you’ve got to expect to do a little more of the work yourself. Besides, you couldn’t pay for all the debugging education I bet you got just trying to follow what I was telling you. If you think the ‘Quick Start’ section was confusing, you should try reading all the stuff it’s based on.

37


Chapter 3: A Brief Introduction to C – What Makes Blinky Blink?

Chapter 3: A Brief Introduction to C – What Makes Blinky Blink?

This section takes a very brief look at Blinky.c to help begin understanding what each line means. Later, these items will be covered in greater detail in context of programs written specifically to aid in learning the C programming language as it is used for common microcontroller applications.

Comments

You can add comments (text the compiler ignores) to you code two ways. For a single line of comments use double back slashes as in

// Blinky.c

For multiline comments, begin them with /* and end them with */ as in:

/*

Blinky.c is a really great first program for microcontrollers

it causes eight LEDs to scan back and forth like a Cylon’s eyes */

Include Files

#include <avr/io.h> #include <avr/delay.h>

The ‘#include’ is a preprocessor directive that instructs the compiler to find the file in the <> brackets and tack it on at the head of the file you are about to compile. The io.h provides data for the port we use, and the delay.h provides the definitions for the delay function we call.

Expressions, Statements, and Blocks

Expressions are combinations of variables, operators, and function calls that produce a single value. For example:

PORTD = 0xFF – counter++

39

Chapter 3: A Brief Introduction to C – What Makes Blinky Blink?

This is an expression that sets the voltage on pins on Port D to +3v or 0v based on the value of the variable ‘counter’ subtracted from 0xFF (a hex number - we’ll learn about these and ports later). Afterwards the counter is incremented.

Statements control the program flow and consist of keywords, expressions, and other statements. A semicolon ends a statement. For example:

TempInCelsius = 5 * (TempInFahrenheit-32)/9;

This is a statement that could prove useful if the Butterfly’s temperature readings are derived in Fahrenheit, but the user wants to report them in Celsius.

Blocks are compound statements grouped by open and close braces: { }. For example:

for(int i = 1; i <= 128; i = i*2)

{

PORTD = ~i; _delay_loop_2(30000);

}

This groups the two inner statements to be run depending on the condition of the ‘for’ statement.

Operators

Operators are symbols that tell the compiler to do things such as set one variable equal to another, the ‘=’ operator, as in ‘DDRB = 0xFF' or the ‘++’ operator for adding 1, as in ‘counter++’.

Flow Control

Flow control statements dictate the order in which a series of actions are preformed. For example: ‘for’ causes the program to repeat a block. In Blinky we have:

for(int i = 1; i <= 128; i = i*2)

{

// Do something

}

40

Chapter 3: A Brief Introduction to C – What Makes Blinky Blink?

On the first pass, the compiler evaluates the ‘for’ statement, notes that ‘i’ is equal to 1 which is less than 128, so it runs the block of ‘Do something’ code. After running the block the ‘for’ expression is reevaluated with ‘i’ now equal to the previous ‘i’ multiplied by 2 ‘i = i*2’ which is 2 and 2 <= 128 is true, so the block is run again. Next loop, i = 4, and so on till i = 256, and ‘256 <=128’ is no longer true, so the program stops running the loop and goes to the next statement following the closing bracket.

Quick now, how many times does this loop run? The series of ‘i’ values evaluated against the ‘<= 128’ is ‘1,2,4,8,16,32,64,128,256’ and since it takes the 256 as the cue to quit, the loop runs 8 times.

The while(‘expression’) statement tests the ‘expression’ to see if it is true and allows the block to run if it is, then it retests the expression, looping thru the block each time it finds the expression true. The program skips the block and proceeds to the next statement when the expression is false. The while(1) will run the loop forever because ‘1’ is the definition of true (false is defined as 0).

Functions

A function encapsulates a computation. Think of them as building material for C programming. A house might be built of studs, nails, and panels. The architect is assured that all 2x4 studs are the same, as are each of the nails and each of the panels, so there is no need to worry about how to make a 2x4 or a nail or a panel, you just stick them where needed and don’t worry how they were made. In the Blinky program, the main() function twice uses the _delay_loop_2() function. The writer of the main() function doesn’t need to know how the _delay_loop_2(30000) function does its job, he only needs knows what it does and what parameters to use, in this case 30000, will cause a delay of about 1/8 second.

The _delay_loop_2() function is declared in the header delay.h and the makefile is set up so that the compiler knows were to look for it.

Encapsulation of code in functions is a key idea in C programming and helps make chunks of code more convenient to use. And just as important, it provides a way to make tested code reusable without having to rewrite it. The idea of function encapsulation is so important in software engineering that the C++

41