MAGAZÍN D'INVESTGACIÓ PERIODÍSTICA (iniciat el 1960 com AUCA satírica.. per M.Capdevila a classe de F.E.N.)
-VINCIT OMNIA VERITAS -
VOLTAIRE: "El temps fa justícia i posa a cadascú al seu lloc.."- "No aniràs mai a dormir..sense ampliar el teu magí"
"La història l'escriu qui guanya".. així.. "El poble que no coneix la seva història... es veurà obligat a repetir-la.."
12-07-2016 (2348 lectures) | Categoria: Articles |
The book assumes a slightly advanced knowledge of programming (in languages C and Python ), electronics , hexadecimal and computing in general. Examples of these are written in two languages and is expected to Linux environment on a PC (instructions tested on Ubuntu 8.04). If you have Windows or any other system, probably the situation does not differ much with minor modifications, can be examples in this book use as well.
The entire book is for the purpose of simplicity will only deal with one type of single-chip computer, and it Atmega8 and a newer version of ATmega8. In the store you buy it in a matter of 50 to 70 CZK under the name ATMEGA8. The book is conceived in a "jump into the water and learn to swim." For any confusion with readers we apologize and hope that the missing parts conjecture or find elsewhere. Examples are commented on them, and if something is not completely clear, we will try to bring enough references. Instead of the classical schemes are sometimes used directly sketches chips from top to make it clear location pins.
Do not be afraid to talk to ascribe this page your questions, comments and requests to the next chapter. Text is in an early stage of development. You can also contribute with their experience.
Atmega8 is called. Single-chip computer or microcontroller. The single chip contains all of the components that are needed to run a computer, even if they are compared with a desktop PC rather weak:
Supply of the entire single-chip computer is + 5 V. Current consumption is small at a frequency of 1 MHz is the order of 3 mA. The consumption is proportional to the frequency and it can significantly reduce podtaktováním e.g. at 1 kHz. Note that 8 KB of program memory is completely separate from one kilobyte of RAM and running ATMega into them on paper. This is called the Harvard architecture. In districts ATMega is more I / Os than the chip legs. It is believed that never use any internal pins simultaneously. The individual legs during programming can connect to a given inner conductor and thereby determine their function. The following chapters take a closer look at the features and capabilities of the chip and the functional interpretation illustrated instructions.
Atmega8 has three ports: two eight-bit PORTB, PORTD and one six-bit PORTC. Their individual pins can operate as an input or output. That will be determined individually for each pin registers DDRA, DDRB, DDRC.
For most pins for more labels. These pins can be run for the microcontroller to switch between whether to behave like a digital port, or whether they will use a special feature that they have been assigned. (The exception is pin RESET / PC6, which can be changed to an I / O pin setting fuses RSTDSBL only during programming.) The list of special features:
Instructions assume that the reader has a computer with one hand parallel port (If none of the computers Netrc, do not worry, there are still frequent internal connector on the motherboard -labeled as LPT- outlet and comes to CZK 80), both the basic electronic equipment such as wires, soldering like. Specific needs depends on the use ATMega. If readers want to start with the first few instructions, you should visit the shop of electronic components [1] and buy in adequate amounts:
(Sooner or later, something will be missing as well. Boxes full of bananas from electronic scrap to rozpájení in this irreplaceable.)
To upload your own program in FLASH memory ATMega may be as follows:
Hardware programmer is a device that is used to connect the microcontroller and PC so that the microcontroller to put the record program. Here we describe how one simple to produce.
There are also more practical version of programmer usbasp that connects to your computer via USB. Its production of which we describe, but because it itself contains a microcontroller without the programmer can not do.
ATmega big advantage is that the program upload is no need for complicated electronics. Programmer for building known as the STK200 can get by with:
ATMega during the recording of the program requires a power supply + 5V Most other guides it solves by an additional stabilized AC power source. Current consumption is very low at Atmega8. If the microcontroller is connected to additional stress, we can use the power directly from the parallel cable. Just find a pin, which is permanently turned on during programming logic 1, ie + 5 V. In this case, the pin 14. If the program fails, firstly with a voltmeter to check whether the pin is permanently voltage of 5 V and possibly programmed chip can power an external source. Then make sure that the country must be common to both the source and the computer.
Particular embodiments leave to the reader. If you are working on a solderless field is probably the most practical to the relevant cables directly solder the resistors and colored wires and secure them against short circuits. Slot with resistors can be built into the connector housing, creating a very compact programmer without cable. Another possibility is to incorporate the base into the wall of a cardboard box with tiskárenským connector, as illustrated by images.
Assembler is a low level language in which to write the specific steps that the processor has to perform. It is suitable where it is necessary to write very efficient and fast code. For normal programming recommended to use the C language.
Listing language program assembler
.NOLIST .INCLUDE "/usr/avr/inc1/m8def.inc" ; odkaz na inc soubor .LIST .DEF tmp = R16 ; tmp - registr pro docasna data rjmp RESET ; provede nezbytne nastaveni mikroprocesoru - inicializace RESET: LDI tmp , LOW ( RAMEND ) OUT SPL , tmp LDI tmp , HIGH ( RAMEND ) OUT SPH , tmp rjmp Start ; nyni spustime vlastni program Start: ; sem nen í dobre psat prikazy , stane se program spatne citelny LDI tmp , $01 ; do tmp nahrajem hodnotu 0 b00000001 - > tzn 1 OUT DDRB , tmp ; a tu pak nahrajem do DDRB - takze urcime vstupy a vystupy sbi PortB , 0 ; rozsviti LED rcall Cekej ; spusti 1 s zpozdeni cbi PortB , 0 ; zhasne LED rcall Cekej ; opet spusti zpozdeni rjmp Start cekej: LDI R19 , 14 ; do registru R19 zapise hodnotu 14 v destkove soustave clr R20 ; vymaze data v registru R20 clr R21 ; vymaze data v registru R21 cekej1: dec R21 ; odecte z registru R21 cislo 1 ( zmensi o 1 ) brne cekej1 ; pokud bude hodnota v R21 rovna 0 , pak program pokracuje na dalsi radek , jinak skoci dec r20 brne cekej1 dec r19 brne cekej1 ret ; navrat z podprogramu
Install Packages
gcc-avr avr-libc Avra
We will compile a program in assembler
Avra blikajici_LED.asm
Translated program will therefore appoint blikajici_LED.hex
Install the package avrdude:
sudo apt-get install avrdude
To upload your own program to the MCU exists for Linux and a few other programs, for example. Uisp or ponyprog. Atmel supplies a complete development environment AVRStudio that supports programming through parallel programmer as well. Rather we are here for reasons of space deal.
Connect Atmegu8 a computer programmer using the STK200 and run the command:
sudo avrdude -p m8 -c usbasp -U flash: w: main.hex
It is likely that this command you use frequently. You can create so for him. Alias! Add the following line at the end of your ~ / .bashrc:
avrload () {sudo avrdude -p m8 -c usbasp -U flash: w: $ 1; }
Now simply place the above command run only
avrload main.hex
Atmega8 also has 16 so-called. Fuses, English fuses. They are 2 bytes of EEPROM memory, referred to as lfuse and hfuse whose value is retained when you turn off the circuit and to determine which pins have what function, what the source of clock signals used Atmega8 like.
The value to which they switch fuses, the program passes avrdude as a parameter. For the calculation of these parameters can be used: http://www.engbedded.com/fusecalc/
Very easy to become that man when programming fuses and confuses either set an unusable source clock, or turn off the option to reset the chip. Atmega8 with incorrect settings then will not work, nor collaborate in programming through ISP. It must then be reset using a second chip and parallel programming, which is documented in the Appendices. Be careful when setting policies.
Open the file in a text editor ~ / .bashrc and at its end, copy the following three lines. Applies if you program Atmegu8 with simple programming cable "STK200".
avrload () {sudo avrdude -p m8 -c STK200 -U flash: w: $ 1; } avrfuseXtal () {sudo avrdude -p m8 -c -U STK200 lfuse w: 0xff: m -U hfuse w: 0xd9: m; } avrfuseIntOsc () {sudo avrdude -p m8 -c -U STK200 lfuse w: 0xc1: m -U hfuse w: 0xd9: m; }
These shortcuts course, you can add or modify as needed. If instead you use a cable usbprogramátor which is given in a later chapter, replace the STK200 for usbasp. Furthermore, if you do not use ATmega8, ATmega16 but necessary, replace the parameter for m8 m16. In order avrload note the string $ 1, for which there completed the first parameter that you specify for the command avrload.
After you restart the terminal, or upload edited ~ / .bashrc command source ~ / .bashrc, you'll be able to load a program into the chip mujprogram.hex:
avrload mujprogram.hex
... And switch it to an external clock crystal:
avrfuseXtal
or to reset the clock at 1 MHz oscillator built:
avrfuseIntOsc
Output at seven-segment display
Program for easy switching on and off the pin on PORTB.1 button on PORTB.0. There are also resolved glitches buttons and continuing until after releasing the button.
Reading the value pin
#include <avr / io.h>
#define F_CPU 8000000UL
#include <util / delay.h>
int main (void)
{
DDRB = 0x06; // controlling the input and output, 1 output, 0-log entry
PORTB = 0x07; // output register and DDR == 1 then the port is transferred to the output differently based log pullup 1-ON, a pullup log 0-OFF
do {
if (! bit_is_set (PINB, 0))
{
_delay_us (500);
if (! bit_is_set (PINB, 0))
{
if (bit_is_set (PINB, 1))
{PORTB & = ~ ((1 << 1));}
else
{PORTB | = (1 << 1);}
while (! bit_is_set (PINB, 0))
{};
};
}
} While (1);
return (0); // return 0 = termination right
}
To delay runtime, which in microcontrollers uses quite often, you can use the function _delay_ms () and _delay_us (), whose argument is the time in milliseconds, respectively. microseconds. We recommend that those functions are always called static value; Indeed, if they pass a variable in the program nalinkuje of magnitude 10K libraries for mathematical calculations. For proper timing define the value F_CPU as clock frequency (ending UL).
For a simple analog-to-digital conversion is necessary to involve AVCC pins (20) and AREF (21) to a supply voltage of 5 V. assume that the following code segment measures the voltage at the input ADC0 (pin 23).
ADMUX = 0; // Initialize the A / D converter channel 0 ADCSRA | = _BV (ADEN) | _BV (ADPS1) | _BV (ADPS2); ADCSRA | = _BV (ADSC); // Start measuring while (! (ADCSRA & _BV (ADIF))); // Awaits completion ADCSRA | = _BV (ADIF);
A / D converter has 10-bit accuracy, ie the value "0" corresponds to 0 V, the "1023" corresponds to 5 V. The bottom 8 bits are stored in the registry ADCL, the upper two bits into the register ACH. We will add a section of code that this 10-bit value is converted to a 4-digit decimal number in ASCII format and send it over the serial port.
UBRRL = 25; // Init USART 2400 bps (assuming 1MHz internal clock) UCSRB | = _BV (TXEN); int VInput; VInput ADCL = + 256 * (ACH & 3); // 10 bits ADC input usart_putchar (0x30 + (% VInput 10000) / 1000); usart_putchar (0x30 + (VInput% 1000) / 100); usart_putchar (0x30 + (VInput% 100) / 10); usart_putchar (0x30 + (VInput% 10)); usart_putchar (0x0A); // End of line
When this function is used
void usart_putchar (uint8_t c) / * {{{* / { UDR = c; while (bit_is_clear (UCSRA, TXC)); UCSRA = _BV (TXC); }
Description of communication through the serial port, see the relevant chapter.
If we have more demands, you can also use an external ADC and read data from it via the SPI. For about 70 CZK can be purchased eg. MCP3202 12-bit dual channel transmitter, which incorporates a sample-and-hold circuit. If you want to use a higher sampling rate can be selected eg. Eight-bit AD9280 which samples with frequencies up to 32 MHz. Data then should temporarily stored in external memory (see [2] ).
Further information is provided in the datasheet and the http://www.avrbeginners.net/architecture/adc/m8_adc_example.html .
#include <avr / eeprom.h> eeprom_read_block (data, eeprom_offset, len); eeprom_write_block (data, eeprom_offset, len);
Atmega8 is equipped with the USART , who cares about communicating over the serial port. To send and receive data from the computer because just a few commands. If your computer does not have a serial port, you can replace a variety of ways using a USB port, which is dedicated to some of the following chapters.
Serial port (in this case) will use only three wires: ground, data sending and receiving data. Because the data transfers do not use a clock signal, that would point to the arrival of each new bit, the computer must be precisely determined and chip common baud rate.
These frequency ( "baud rate") are standardized. In this example, we assume that using the internal oscillator at 1 MHz ATMega and use a baud rate of 2400 bit / s. If we used ATMega clock crystal frequency of 4 MHz, we would use instead of 9600 bit / s.
Atmega8 uses TTL voltage levels (0 V / 5 V). PC serial port uses a significantly different voltage levels (-12 V / +12 V). The transfer between these levels should be used MAX232, which requires connecting additional four capacitors. So buy MAX232CPE circuit (about 19 CZK) and 4x him electrolytic capacitor 1 uF / 20 V.
#include <avr / io.h>
// Get a char
unsigned char uart_getc (void)
{
/ * Wait for data to be received * /
while (! (UCSRA & (1 << RXC)))
;
/ * Get and return received data from buffer * /
return UDR;
}
// Send char
void uart_putc (unsigned char data)
{
while (! (UCSRA & (1 << UDREs)))
;
UDR = data;
}
int main (void)
{
char character;
/ UART initialization ***** ***** /
UCSRA = 0x00;
UBRRH = 0x00; // Set the speed to 1 MHz crystal
UBRRL = 25; // (in case of 8 MHz clocked here Use UBRRL = 0x33;)
UCSRB = 0x18; // enable the transmission and reception
UCSRC = 0x86; // data frame: 8 data, 1 stop bit, no parity
while (1)
{
uart_getc character = ();
uart_putc (character);
}
}
3 We describe the environment in which they can communicate with ATmega. Which one is best depends on the application.
Receiving data from the serial port devices, accessible as / dev / ttyS0 or / dev / ttyS1. If you're lucky, it will directly read data:
cat / dev / ttyS0
Received data was flowing to standard output, as is customary.
If it does not, read from port probably requires adding a few parameters:
stty -F / dev / ttyS0 clocal cread -crtscts CS8 -cstopb hup -parenb parodd -brkint -icrnl ignbrk
-igncr ignpar imaxbel -inlcr inpck -istrip -iuclc -ixany ixoff -ixon bs0 CR0 FF0 nl0 -ocrnl
-ofdel -ofill -olcuc -onlcr -onlret onocr -opost Tab0 vt0 -crterase crtkill -ctlecho -echo
-echok -echonl -echoprt -icanon -iexten -isig -noflsh -tostop -xcase time 5 min 1 2400
Todo: data
For receiving data in Python, there is an easy to use library USPP, which will probably require installation (sudo apt-get install python-USPP).
Firmware providing complete communication using USART interrupt.
Chip type: ATmega16 Clock frequency: 12MHz jan.kalenda [at] gmail.com
#include <avr / io.h>
#include <avr / interrupt.h>
#include <string.h>
#define rdataSize 100
// USART
void USART_Init (unsigned int divisor);
void USART_Transmit (char * data);
void usart_busy_wait ();
Tdata char = 0, * = transmitted_data & Tdata;
rdata char [rdataSize] * = received_data rdata;
#define UBRR 77
int main (void)
{
USART_Init (UBRR);
sei ();
while (1)
{
usart_busy_wait ();
USART_Transmit (rdata);
}
return 0;
}
void USART_Init (unsigned int divisor)
{
// Set the port as the TxD output.
DDRD | = 0x02;
// Set baud rate
UBRRH = (unsigned char) (divisor >> 8);
UBRRL = (unsigned char) divisor;
// Set frame format: 8data, 1 stop bit.
UCSRC = (1 << Ursel) | (3 << UCSZ0);
// Enable Receiver and Transmitter
UCSRB | = (1 << RXEN) | (1 << TXEN);
UCSRB | = (1 << RXCIE);
}
usart_busy_wait void ()
{
/ * Wait for empty transmit buffer * /
while (transmitted_data! = NULL);
while (! (UCSRA & (1 << UDREs)));
}
void USART_Transmit (char * data)
{
transmitted_data = data;
if (* transmitted_data)
{
// Enable Data Register empty interupt
UCSRB | = (1 << strikes);
}
}
// Data transfer using data register empty interrupt.
ISR (USART_UDRE_vect)
{
// Put data into buffer, sends the data.
if (* transmitted_data)
{
UDR = * transmitted_data;
transmitted_data ++;
}
else
{
// Disable Data Register empty interupt
UCSRB & = ~ (_BV (strikes));
}
}
// Receive data using USART Receive Complete interupt
ISR (USART_RXC_vect)
{
if (received_data! = & rdata [rdataSize])
{
* Received_data = UDR;
// UDR = * received_data;
received_data ++;
}
else
{
received_data = rdata;
}
}
http://www.mikrozone.sk/pluginy/content/content.php?content.43
USB has over the serial port baud rate and higher is supported even new computers. Also includes power conductor (5 V, 500 mA). A substantial disadvantage is the complexity of communication by the device via USB lead. There are several ways to connect microcontroller with computer:
The author has a good experience in using the first option. For their experiments zvolis USB driver from Objective Development. For commercial use are free under the GPL. To try it out, download and unzip their source codes in zip format and examine examples.
For easy communication with computer is suitable eg HID class device-DATA. Circuit proved to be a zener diode (also referred to in that archive). Further description of communication via USB is beyond the scope of this Wiki.
In one of the opening chapters described the construction of a simple programmer STK200, utilizing parallel port. Because some computers already have a parallel port, there are a series of instructions for building a programmer which connects via USB. Some of them have advanced features such as parallel programming, support for a wide array chip debugging, etc.
For most purposes, but will do a simple programmer usbasp by page http://www.fischl.de/usbasp/ . Enable continuous programming several microcontrollers from Atmel (including Atmegy8 and Atmegy16). Scheme and the program can be found in the archive to the author, the programmer may be a few tens of minutes to deploy solderless field.
The author had trouble with the newer version of avrasp 2009. [ http://www.fischl.de/usbasp/usbasp.2007-10-23.tar.gz
Atmegu8 need to switch to an external clock crystal and programmed. So if you have no parallel port, or borrowed programmer, you need to contact someone to record the program.
To upload the program to Atmegy8 and setting its policies have been using serial programming. (Byte in it serially transmitted over wires 3, although the computer uses the parallel port.) Also known as In System Programming, because they often can be done without Atmega8 took out of the circuit.
In some cases it is necessary to use a complicated high voltage parallel programming:
In the following instructions we will deal first and most common case where we have mistakenly set the fuses and the chip has not overridden by using the ISP. The chip mark as ill patient. Using the second atmegy8 chip reset so that it could re-programmed using the ISP.
The parallel programming can not use the simple computer's parallel port, because it has enough pins. Instead, we'll get
The doctor will record the following recipe: Programujeme_jednočipy / VnParProg_hex_code :
sudo avrdude -p m8 -c STK200 -U flash: w: atmega8-fuse-repair.hex
If you want to modify the program or read, is available here: Programujeme_jednočipy / VnParProg_c_code . In this case, compile the classical orders and upload it as described above.
avr-gcc -g -Wall -O1 -mmcu = atmega8 -c atmega8-fuse-repair.c -o atmega8-fuse-repair.o avr-gcc -g -Wall -O1 -mmcu = atmega8 atmega8-fuse-repair.o -o atmega8-fuse-repair.elf AVR-objcopy j j .text .data O iHex atmega8-fuse-repair.elf atmega8-fuse-repair.hex sudo avrdude -p m8 -c STK200 -U flash: w: atmega8-fuse-repair.hex
Both Atmegy8 placed on the solder field close to each other. Most of the pins connect directly to PB0 PB0 etc. This will create PB0 - PB6, PC0 - PC2, PD1 - PD7, a total of 17 straight jumpers that are on the diagram drawn merged in a thick line:
PC3 connect the output to the input of the switch +12 V output switches connect via a 10 Ohm resistor to pin PC6 patient. The diagram is a draft with transistors, but because the 12 V signal is switched on for programming, can be transistor circuits replacing manual switch and a single resistor.
Both chips, the doctor and the patient, connect according to the above scheme. We recommend that you then proceed as follows:
Now, the patient should be cured. Power supply fails, you take it and try to program a conventional, serial interface.
It is not related directly to ATmega, but it might come in handy. Lptout following program (written in C for Linux) is set to PC parallel port number specified as the first parameter. On Windows (XP) can write to the parallel port as well, but it requires the installation of additional drivers. Writing to LPT only works when it is running with root privileges.
/ * Lptout - sets given value on parallel port * /
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys / io.h>
#define base 0x378 / * printer port address * /
int main (int argc, char ** argv)
{
int value;
if (ioperm (base, 1, 1)) {fprintf (stderr, "Could not get permission for the port 0x% x. n", base) exit (1);}
if (argc <2) {fprintf (stderr, "Please specify the value to be set. n"); exit (2);}
if (sscanf (argv [1], "% i", & value) == 1) {outb ((unsigned char) (value), 0x378);}
else {fprintf (stderr, "1st parameter must be an integer Between 0 - 255. n", base) exit (3);}
return 0;
}
Compile and an example to set pins nastřídačku:
g ++ -o lptout.c lptout sudo ./lptout $ ((1 * 1 + 0 * 2 + 1 * 4 + 0 * 8 + 1 * 16 + 0 * 32 + 1 * 64 + 0 * 128))
Be careful when working with parallel port! Computer circuits are sensitive to surges and static electricity. For parallel ports, the risk of damage in the event of a short circuit.