Sign in Join
Wiki copytemporary

AVR Programming: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11The FPC commands for programming AVR microcontrollers such as ATMega or ATTiny are the same commands as always, but because of its character of an embedded system, i.e. no underlaying operating system and direct hardware access, there are several specific topics to know.
22
33For building the FPC compiler see article [[AVR]].
44
55## LCL/FCL
66
77LCL is not available and FCL only partially.
88
99## Variables
1010
1111Variables declaration etc. works in the same way as always. As there is no operating system which provides memory allocation, dynamic types like AnsiString could not be used.
1212
1313### Integer variables
1414
1515The AVR is a 8 bit architecture, the native datatypes are *[[Byte]]* (= *uInt8*) with a range from 0 to 255 and *[[Shortint]]* (= *Int8*) ranging from -128 to 127. Calculations and operations with these two datatypes are always the fastest. A difference in comparison to e.g. target win32 is that the *Integer* type has 16 bit with range between -32768 and 32767 (instead of 32bit for win32). Using the integer type will increase the calculation time in comparison to the native types, but may be reasonable depending on the application. For loops with iteration of less than 256 cycles the iteration variable with type byte is appropriate.
1616
1717For clarity reasons if not using Byte or Integer, the type names Int8, uInt8, Int16, uInt16, Int32, uInt32, Int64 and uInt64 may be prefered.
1818
1919### Floating point variables
2020
2121The AVR architecture doesn’t have a floating point unit. Not sure if using soft float is possible by now.
2222
2323### String variables
2424
2525Only strings with fixed length can be used, as AnsiString and WideString types are dynamically allocated.
2626
2727Some Examples:
2828
2929``` pascal
3030// passing a string as a procedure variable
3131procedure UARTSend(const AText: ShortString);
3232// using a variable with fixed length string
3333var myString: String[5];
3434```
3535
3636> **Note:** The string type ShortString is always 255 chars in length. If you need fewer characters, use a string with fixed length to not waste the scarce memory. Use ShortString only if you don't know how long your string may be at maximum length.
3737
3838## Accessing hardware configuration registers
3939
4040All hardware configuration registers are defined in the controler specific configuration file which is located in the pascal sources under … \rtl\embedded\avr. The configuration file is named after the device, e.g. Atmega32.pp for the device Atmega32. Besides the configuration registers it also contains the predefined interrupt names. The file is included automatically for all units, so the register variables and constants are available in each unit. The device and thus the configuration file is defined by the command line parameter –wp*devicename* (e.g. –wpatmega32).
4141
4242The names of the hardware registers correspond to the register names defined in the device datasheet. The hardware registers can be accessed as easy as variables. E.g. \<syntaxhighlight lang="pascal\>UDR:= 25;
4343
44-</syntaxhighlight>
45-
4644writes the value 25 in the UARTDataRegister. Bit manipulation can effectively be done with shift operations ([[Shl|shl]] = „shift left“), e.g.
4745
4846``` pascal
4947UCSRB:= (1 shl TXEN) or (1 shl RXEN) or (1 shl RXCIE);
5048UCSRB:= (1 shl 3) or (1 shl 4) or (1 shl 7);
5149UCSRB:= %10011000; //Bit 3,4 and 7 are set
5250```
5351
5452All three lines are identical in the generated code: The bits TXEN, RXEN and RXCIE are set in the „USART Control and Status Register B“, thus the UART hardware is enabled for sending and receiving and for interrupts on receiving.
5553
5654## Register name aliases
5755
5856For hardware abstraction purpose its common to define application specific names for hardware configuration registers, especially for port registers. This can be done by a variable definition using the absolute modifier. In the below example LEDPort is just an other name for the hardware register PortA, such definitions are neutral in memory consumption and performance.
5957
6058``` pascal
6159var
6260 LEDPort: byte absolute PortA;
6361const
6462 LEDPin = 3;
6563
6664implementation
6765 LEDPort:= LEDPort or (1 shl LEDPin); //LED=on
6866```
6967
7068## Bit arithmetic
7169
7270Bit arithmetic is the Free Pascal standard, but as it is especially important for an embedded target and quite rarely used in desktop applications it is mentioned here. Available operators for bit manipulation: [[Not]], [[And]], [[Or]], [[Xor]], [[Shl]] and [[Shr]].
7371
7472Example:
7573
7674``` pascal
7775ByteVal1:= (ByteVal1 and %11110000) or %00001000;
7876```
7977
8078A leading ‚[[Percent sign|%]]’ indicates a [[Binary numeral system|binary number]], a leading ‚[[Dollar sign|$]]’ a [[Hexadecimal|hexadecimal number]]. For inline assembler ‚0b’ and ‚0x’ are the indicators respectively.
8179
8280## Classes/objects
8381
8482Again, classes are dynamically allocated, and thus are not available. But static classes (keyword *object*) can be used for structuring and reusing code.
8583
8684Example:
8785
8886``` pascal
8987Type TUART = object
9088 Procedure Init;
9189 Procedure Send(ByteVal:Byte);
9290end;
9391
9492var
9593 UART: TUART;
9694```
9795
9896Usage:
9997
10098``` pascal
10199UART.Init;
102100UART.Send(125);
103101```
104102
105103## Interrupts
106104
107105When using hardware interrupts one has to configure and enable a interrupt source, enable interrupts globally and define an interrupt service routine (ISR) which is called by the CPU when the interrupt occurs. The configuration is done via the hardware registers. For globally enabling interrupts the assembler command SEI is available, it can be easily used with inline assembler:
108106
109107``` pascal
110108asm SEI end;
111109```
112110
113111Globally disabling interrupts is done with the assembler command CLI:
114112
115113``` pascal
116114asm CLI end;
117115```
118116
119117**Note:** Since FPC 3.2.0 one can also clear/set interrupts without resorting to inline assembler:
120118
121119``` pascal
122120uses
123121 intrinsics;
124122
125123procedure unInterruptableCode;
126124begin
127125 avr_cli;
128126 // code that shouldn't be interrupted
129127 avr_sei;
130128end;
131129```
132130
133131The code above may introduce the side effect of enabling interrupts, even if disabled initially. To fix this, call avr_save to save the status register (it also disables interrupts), perform uninterrupted actions, then restore status register:
134132
135133``` pascal
136134uses
137135 intrinsics;
138136
139137procedure unInterruptableCodeImproved;
140138var
141139 prevState: byte;
142140begin
143141 prevState := avr_save;
144142 // code that shouldn't be interrupted
145143 avr_restore(prevState);
146144end;
147145```
148146
149147For definition of the ISRs, predefined names have to be used. Depending on the device, different interrupts are available. The proper names can be found in the device specific unit (e.g. „Atmega32.pp“) and have to be used in the *Alias* modifier. A working ISR looks as follows (example: External Interrupt 0):
150148
151149``` pascal
152150procedure ExternalInterrupt0_ISR; Alias: 'INT0_ISR'; Interrupt; Public;
153151begin
154152 //Do some stuff…
155153end;
156154```
157155
158156The procedure name itself can be chosen randomly, important is the name behind *Alias*. The *Alias* modifier forces the compiler to use the name *INT0_ISR* for the procedure without name mangling. If this name fits a predefined interrupt name, then the procedure will be automatically registered in the interrupt vector table. For the automatism to be possible, the procedure has to be globally visible, which is realised by the Public modifier. But this is only needed if the procedure is defined in a unit. Note: There is no procedure prototype to be defined in the INTERFACE section of the unit, but only the bare procedure in the IMPLEMENTATION section. If the procedure is placed in the program section instead of inside a unit, then the Public modifier is omitted. The Interrupt modifier makes sure that all registers and the status register are saved and recovered by the ISR and that interrupts are further enabled. Omitting the Interrupt modifier will result in the malfunction of and crashes of the program.
159157
160158## Inline assembler
161159
162160In some cases performance can be highly increased by a few assembler statements. The inline assembler provides a very convenient way of mixing Free Pascal and assembler.
163161
164162### Inline asm block
165163
166164The [[Asm|ASM statement]] starts an assembler block which is finished with an END statement.
167165
168166``` pascal
169167asm
170168 // do some assembly
171169end;
172170```
173171
174172In the assembler block modified registers have to be published to the compiler in the end statement, so that the compiler can take care of pushing or avoiding registers. The resulting code is more effective than pushing registers manually inside the asm section. Modified but unpublished registers may lead to malfunction.
175173
176174``` pascal
177175asm
178176 ldi r20,35 // r20 modified
179177 ldi r21,12 // r21 modified
180178end['r20','r21']; // publish modified registers to compiler
181179```
182180
183181The register r1 is assumed by the compiler to always be zero. If modified, e.g. by a *mul* operation, it must be cleared afterwards.
184182
185183``` pascal
186184 mul r16,r17 // result stored in r1 and r0
187185 movw r1:r0,r17:r16
188186 clr r1 // clear r1
189187```
190188
191189Constants and variables can be accessed within the inline assembler. The variables have to be distinguished between local variables (stack allocated), which are loaded and stored with the instructions LDD and STD (limited to 64 byte offset), and global variables (statically allocated), which are loaded and stored with the instructions LDS and STS. Variables passed by procedures are allocated on the stack and thus are handled like local variables. Its always useful to check the assembler listing (.s-file extension).
192190
193191When using jumps in the assembly then labels are used. They have to be declared in the label section of the procedure. Allowing this, the compiler directive *{\$goto on}* is mandatory.
194192
195193Note: The peripheral configuration registers defined in the controller-specific file (e.g. ‚atmega32.pp’) are variables with addresses in the memory address space and NOT in the I/O-space. There the addresses are shifted by 0x20, as the general registers are the bottom of the address space. Thus I/O assembler commands like **in**, **out**, **sbis**, **sbi** (and so on) doesn’t work with the register names. Compare with the memory map in the controller datasheet.
196194
197195Instead of **in**/**out** the commands **lds** and **sts** can be used:
198196
199197``` pascal
200198 lds r16, PORTB //Reads PORTB into register r16
201199```
202200
203201The bit definitions of the perpheral configuration registers can be used in the inline assembler.
204202
205203If I/O assembler commands are required, the I/O register addresses can be shifted manually by 32 (=0x20):
206204
207205``` pascal
208206//Wait until UART data register is empty
209207Procedure UARTBusyWait;assembler;
210208asm
211209 .waitBusy:
212210 sbis UCSRA+(-32),UDRE
213211 rjmp .waitBusy
214212end;
215213```
216214
217215In the following an example for a delay function with inline assembler, which pauses the program for a certain time making the CPU busy.
218216
219217``` pascal
220218unit Wait; //wait.pas
221219{$mode objfpc}{$H+}
222220{$goto on} //Important for using the label directive, the label is needed in the assembler section
223221
224222INTERFACE
225223
226224Const
227225 f_CPU = 4000000; //Hertz
228226
229227Procedure Wait10m(Time: Byte);
230228
231229IMPLEMENTATION
232230
233231// Waitingtime = Time * 10 Milliseconds
234232Procedure Wait10m(Time: Byte);
235233const
236234 Faktor = 15 * f_CPU div 1000000;
237235label // Labels, here for the loop, has to be declared explicitly
238236 outer, inner1, inner2;
239237var
240238 tmpByte: byte; // In Inline assembler local variables are accesed by the instructions LDD and STD, global variables are accessed by LDS and STS.
241239begin
242240 asm // asm states inline assembly block until the next END statement
243241 ldd r20,Time // Variables can be accessed, here a local variable
244242 outer:
245243 ldi r21, Faktor
246244 inner1: // 640*Faktor= 640*15*1 = 9600 cycles/1MHz
247245 ldi r22,128
248246 inner2: // 5*128 = 640 cycles
249247 nop // 1 cycle
250248 nop // 1 cycle
251249 dec r22 // 1 cycle
252250 brne inner2 // 2 cycles in case of branch //one loop in sum 5 cycles
253251 dec r21
254252 brne inner1
255253 dec r20
256254 brne outer
257255 end['r20','r21','r22']; //Used registers to be published to compiler
258256end; //procedure
259257
260258end. //unit
261259```
262260
263261### Asm procedure
264262
265263There is a second way to use inline assembler by defining a whole procedure or function as assembler.
266264
267265``` pascal
268266Procedure DoSomeAssembly;assembler;
269267asm
270268 // do some assembly
271269end;
272270```
273271
274272But beware, the procedure/function is called according the ABI conventions (Application binary interface). For this reasons an asm block is much easier to use than an asm procedure. For example on the target AVR according to the ABI some parameters may be passed via a register. Then the programmer has to consider this. There is no management code inserted by the compiler to access these parameters as local variable as it is done in 'normal' procedures with an asm block included. Also in opposite to the asm block the programmer has to take care of the used registers himself. Only for local variables (if defined) the compiler will insert management code for the stack frame.
275273
276274## Sections
277275
278276### Data
279277
280278Data (variables) can be placed in different linker sections by using the *section* directive. Care should be taken when placing data in *.progmem* or *.eeprom* sections, since these sections do not map to the data space for classical AVR controllers and the compiler currently doesn't generate correct code to access these sections. An example could be to place a variable in the *.noinit* section. This would place the variable in uninitialized RAM, thus a soft restart of the controller would preserve its value.
281279
282280Note: the *.noinit* section requires fpc 3.3.1 to work properly.
283281
284282### Code
285283
286284Support to associate section information with procedures and functions has been implemented in the compiler (currently only available in the development version 3.3.1). The startup code has been modified (so far only for the avrsim controller) to follow more or less the [avr-libc .initN sections](https://www.nongnu.org/avr-libc/user-manual/mem_sections.html#sec_dot_init) convention:
287285
288286- entry point - First instruction jumps to the linker provided label __trampolines_end. After the jump instruction follows the interrupt vector table. This code is different for each controller.
289287- Progmem data (if defined) is placed next. The __trampolines_end label points to the first address after this location.
290288- .init0 - not used, available for user code
291289- .init1 - not used, available for user code
292290- .init2 - Code to initialize zero register and stack pointer
293291- .init3 - not used, available for user code
294292- .init4 - Code to copy initialized variables to RAM and zero memory for uninitialized variables.
295293- .init4 - .init8 - not used, available for user code
296294- .init9 - Jump to main
297295
298296Note that the finalization code generated by FPC follows directly after the rest of the code, before the .finiN sections start. Currently it isn't possible to replace FPC generated finalization code or insert code via a .fini section that would execute after the finalization code.
299297
300298### Example
301299
302300``` pascal
303301program test;
304302
305303// Store MCU startup status early and set to 0 so that e.g. watchdog resets can be determined
306304
307305var
308306 startupMCUSR: byte; section '.noinit';
309307
310308// This should be marked noreturn since it should fall through into the next init section
311309procedure saveMCUSR; noreturn; section '.init1';
312310begin
313311 startupMCUSR := MCUSR;
314312 MCUSR := 0;
315313end;
316314
317315begin
318316 if startupMCUSR = 1 then
319317 writeln('Reset cause: Power-on');
320318end.
321319```
322320
323321## Resources
324322
325323### Wiki
326324
327325- [[Portal:Embedded|Embedded Portal]]
328326- [[Arduino]]
329327- [[ARM]]
330328- [[AVR]]
331329
332330### Forums
333331
334332- [Tutorial for building FPC-AVR and *blinky* example project](http://forum.lazarus.freepascal.org/index.php/topic,30960.0.html)
335333- [Forum topic with AVR Project Wizard](http://forum.lazarus.freepascal.org/index.php/topic,35486.msg)
336334
337335---
338336*From the Free Pascal wiki, page "AVR Programming", as it stood on 2022-08-14 after a change by Ccrause, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history