Simple circuits on the attiny2313 microcontroller. Circuits and devices on microcontrollers. Schematic diagram of the experiment

A simple experiment with connecting a button to an AVR microcontroller is described, and a simple C program for processing button presses is analyzed. Let's look at the features of connecting a button to the MK ports, as well as methods for reading button states in the C language.

Previous articles discussed experiments with LEDs that were connected to microcontroller ports configured for Output.

In this article, we will connect a button to the microcontroller, the contacts of which close when pressed, and open when released (closed button).

Schematic diagram of the experiment

In order to be able to at least somehow observe and control something using a button, we will connect two more LEDs to the microcontroller. The diagram is very simple, here it is:

Rice. 1. Schematic diagram of the experiment with the ATtiny2313 microcontroller and button.

As you can see, two LEDs are connected to two ports PB0 and PB1 through limiting resistors, and a button is connected to port PD2 and it also has a limiting resistor. To connect the programmer to the MK, the Conn 1 (AVR-ISP) connector is used, and to connect the circuit to a separate +5V power source, two contacts are used - P1 and P2.

Rice. 2. An experiment diagram with a microcontroller and a button assembled on a solderless breadboard.

It is important to note that for safe use of a port with a button, a resistor with a resistance of 1 KOhm is connected in series with it (you can also connect it to another resistance of 600 Ohms - 2 KOhms). Accept this as a rule of good manners when working with pins, which will protect the MK port from failure in the event of an erroneous high-level supply to the pin and when the button is closed.

Structure of I/O ports in AVR microcontrollers

The microcontroller pins are universal GPIO (General Purpose Input Output), you can connect both actuators (indicators, power switches) and various digital sensors (buttons, switches) to them.

Several pins in the MK can be connected to an ADC/DAC (Analog-to-Digital-Converter and vice versa), with their help you can analyze and generate analog signals. Conventional GPIOs cannot work with analog signals; they can only have 0 (0V) or 1 (+5V) at their input/output.

Each GPIO pin inside the microcontroller is connected to several blocks and electronic components that are useful to know about:

  • Between the port pin and each of the power rails (GND and VCC) connected via diode. They are used to “dampen” short-term interference, voltage surges relative to the pin and each of the power rails;
  • There is also a capacitor between the pin and GND. I don’t know exactly why it is needed, perhaps for protection against interference, to prevent contact bounce when using buttons and switches connected to a pin, or for something else;
  • Connected to each pin an electronic key with a resistor is a pull-up of the pin to the voltage of the power source (Pull-UP). This electronic key is turned on by software and serves to set the default high logical level 1 (+5V) when working with a pin in input mode (Input);
  • Between the pin and each of the power buses (GND and VCC) two more electronic switches (without resistors) are included; they are needed to set a high (+5V) or low (0V) logical level on the pin when the pin is operating in Output mode.

For software control and configuration of each of the ports, three special registers are used, for example for port “B”:

  • DDRB - register (8 bits) for setting the operating modes of pins - input or output. This is done by setting the corresponding bits in the register;
  • PORTB is a register for controlling the state of the port pins in output mode - high or low level. Also used in input mode, used to enable pull-up resistors and set the default input level high;
  • PINB is a register that contains the logical states of the pins on a port, used to read the values ​​of ports that are configured in input mode.

You can learn more about the design of ports for a specific microcontroller model from its datasheet, in the “I/O-Ports” section; there may also be examples of code in C and Assembly for working with ports.

RESET pin as I/O port

It is useful to know that the “RESET” pin of the microcircuit (in our diagram it is pin number 1), which is intended for resetting the execution of the microcontroller program (reboot), can also be used to connect buttons, LEDs and other input/output devices, that is, it can be turned into a regular GPIO.

This can be useful if the microcircuit does not have enough pins for your design. For example, when assembling some device on an ATtiny13 chip (8 pins, 2 pcs for power, 5 pcs for I/O ports, 1 pc for RESET), you found that one pin was missing for the LED. There may be several options to solve the problem:

  1. Reprogramming the RESET pin for an I/O port;
  2. Connecting an LED to one of the adjacent already used pins, using some histrosts in the circuit design and taking into account the possibility of its general use;
  3. Using another MK that has more pins, for example ATtiny2313.

Which of these options is simpler and cheaper in terms of finances/time - judge according to your own case.

To turn the "RESET" pin into an I/O port, you will have to change a special fuse - RSTDISBL (Reset Disable). But before you do this, you need to remember that after this operation, reprogramming the microcontroller will only be possible using a high-voltage programmer (12V); a regular USB ISP or another programmer powered by 5V will no longer be able to do its job.

C program

So, we have one button and two LEDs that are connected to the microcontroller, what can we do with them? - and we’ll do this (algorithm):

  1. After turning on the power, the LEDs will flash alternately and with a delay of 300 milliseconds;
  2. When you press and hold the button, only the blue LED will light;
  3. After releasing the button, the blue LED will flash 3 times with a delay of 500 milliseconds, after which the LEDs will flash alternately again with a delay of 300 milliseconds.

An example of the implementation of such an algorithm in C language under AVR is given below. Let's create a new file for our program and open it for editing:

Nano /tmp/avr-switch-test.c

Let's put the following code in the body of the file:

/* Experiment with a button on ATtiny2313 * https://site */ #define F_CPU 1000000UL // Core frequency = 1 MHz #include #include // -- Macros for controlling LEDs -- #define LED_BLUE_ON PORTB |= (1<< PB0) // Засвечиваем синий диод #define LED_BLUE_OFF PORTB &= ~(1 << PB0) // Гасим синий диод #define LED_RED_ON PORTB |= (1 << PB1) // Засвечиваем красный диод #define LED_RED_OFF PORTB &= ~(1 << PB1) // Гасим красный диод // Основная программа void main(void) { DDRD |= (0 << PD2); // Пин 6 - на вход PORTD |= (1 << PD2); // Включаем подтягивающий (Pull-UP) резистор для пина 6 DDRB |= (1 << PB0); // Пин 12 - на вывод DDRB |= (1 << PB1); // пин 13 - на вывод // -- Бесконечный цикл -- while(1) { _delay_ms(300); // Задержка 300 мс LED_BLUE_ON; // Включаем синий диод LED_RED_OFF; // Гасим красный диод _delay_ms(300); LED_RED_ON; // Включаем красный диод LED_BLUE_OFF; // Гасим синий диод if(!(PIND & (1 << PD2))) { // Проверяем нажата ли кнопка _delay_ms(50); // Задержка 50 мс (дребезг контактов) LED_RED_OFF; LED_BLUE_ON; while(!(PIND & (1 << PD2))); // Ждем пока кнопка не будет отпущена _delay_ms(500); // Дальше мигаем синим диодом LED_BLUE_OFF; _delay_ms(500); LED_BLUE_ON; _delay_ms(500); LED_BLUE_OFF; _delay_ms(500); LED_BLUE_ON; _delay_ms(500); LED_BLUE_OFF; _delay_ms(200); } // Конец блока работы с кнопкой } // Конец блока с вечным циклом }

First of all we ask constant F_CPU, which will indicate to the compiler the operating frequency of the microcontroller core; this is necessary for some subroutines and functions to work correctly. In our example, we use the time delay function - "_delay_ms" from the "util/delay.h" library, which calculates the time spent on idle cycles, based on the value in the F_CPU constant.

You can view the code of the "delay" library for organizing a time delay and which uses the F_CPU constant in GNU Linux using any text editor, for example, you can run the following command:

Nano /usr/lib/avr/include/util/delay.h

The factory set frequency of the internal RC oscillator in the ATtiny2313 microcontroller is 8000000Hz (8MHz), the frequency division fuse is also set by default - CKDIV8 (Clock Divide by 8), so the actual operating frequency of the crystal = 8000000Hz / 8 = 1000000Hz = 1MHz.

You can see what fuses are installed in the microcontroller using avrdude or a graphical shell for it called AVR8 Burn-O-Mat.

Further in the program, macros are defined to control the state of the ports to which the LEDs are connected: LED_BLUE_ON, LED_BLUE_OFF, LED_RED_ON, LED_RED_OFF. By calling a similar macro anywhere in the program, we can very easily turn on or turn off each of the LEDs, without having to repeat its code, which in turn will simplify the program and make it more visual.

In the main program "void main(void)" we start with the port configuration:

  • DDRD |= (0<< PD2) - установка разряда PD2 регистра DDRD на ввод, к нему подключена кнопка (пин 6);
  • PORTD |= (1<< PD2) - включение подтягивающего резистора для пина к которому привязан разряд PD2 регистра PORTD (пин 6);
  • DDRB |= (1<< PB0) - установка разряда PB0 в регистре DDRB на вывод, к нему подключен СИНИЙ светодиод (пин 12);
  • DDRB |= (1<< PB1) - установка разряда PB1 в регистре DDRB на вывод, к нему подключен КРАСНЫЙ светодиод (пин 13).

Next, using macros, we turn off the red LED and turn on the blue one. Now, using another eternal loop, but with a condition, we will wait until the button is released: "while(!(PIND & (1<< PD2)));".

When the button is released, a high level will appear on pin 6 (this will be done by the internal pull-up resistor that we turned on earlier), and logical 1 will be set in the PD2 bit of the PIND register.

After this, the blue LED flashes three times (on-off) with a delay of 0.5 seconds and the main eternal cycle starts working in a new way - two LEDs will light up alternately.

A very simple program, but nevertheless, it is a good example and grounds for further experiments.

Setting up Geany for ATtiny2313

In previous publications I conducted experiments with the ATMega8 microcontroller, but here I use a less “stuffed” MK - ATTiny2313.

To compile the program and flash it into the MK, you need to slightly reconfigure the commands for assembly in the Geany integrated programming environment.

Go to the Build menu - Set Build Commands. In the compilation command (C commands), you need to change the model of the chip used: "-mmcu=attiny2313". In the command to flash the MK, you need to change the chip type for avrdude: "-p t2313".

Rice. 3. Reconfiguring Geany to work with the ATTiny2313 microcontroller.

All commands are given for GNU Linux OS; if you have Windows, you may have to enter the full paths to the binary files “avr-gcc.exe”, “avr-objcopy.exe”, “avrdude.exe”.

I discussed in more detail how to configure Geany in GNU Linux in one of the previous articles in the series.

Compilation and firmware of the program in MK

Compiling, assembling and flashing the program can be done by clicking three buttons in turn in the Geany environment: “Compile”, “Build” and “Run”. Also, all these operations can be performed from the console, here are the commands for these actions (perform sequentially):

Avr-gcc -mmcu=attiny2313 -Os /tmp/avr-switch-test.c -o /tmp/avr-switch-test.o avr-objcopy -j .text -j .data -O ihex /tmp/avr- switch-test.o /tmp/avr-switch-test.hex avrdude -c usbasp -p t2313 -P usb -U flash:w:/tmp/avr-switch-test.hex

All commands are almost completely (with the exception of file name substitutions) identical to those that we corrected in the Geany settings.

Conclusion

Despite the simplicity of the experiment, I also tried to highlight some very important technical aspects of working with ports; the knowledge and experience provided will be useful in further study and work with ATMEL microcontrollers.

Many household appliances and industrial automation devices of relatively recent production years have mechanical counters installed. They are products on a conveyor belt, turns of wire in winding machines, etc. In the event of a failure, finding a similar meter is not easy, and it is impossible to repair due to the lack of spare parts. The author proposes to replace the mechanical counter with an electronic one. An electronic counter, developed to replace a mechanical one, turns out to be too complex if it is built on microcircuits with a low and medium degree of integration (for example, the K176, K561 series). especially if a reverse account is needed. And in order to maintain the result when the power is turned off, it is necessary to provide a backup battery.

But you can build a counter on just one chip - a universal programmable microcontroller that includes a variety of peripheral devices and is capable of solving a very wide range of problems. Many microcontrollers have a special memory area - EEPROM. Data written into it (including during program execution), for example, the current counting result, is saved even after the power is turned off.

The proposed counter uses the Attiny2313 microcontroller from the AVR family from Almel. The device implements reverse counting, displaying the result with cancellation of insignificant

hive on a four-digit LED indicator, storing the result in EEPROM when the power is turned off. An analog comparator built into the microcontroller is used to timely detect a decrease in supply voltage. The counter remembers the counting result when the power is turned off, restoring it when turned on, and, similarly to a mechanical counter, is equipped with a reset button.

The counter circuit is shown in the figure. Six lines of port B (РВ2-РВ7) and five lines of port D (PDO, PD1, PD4-PD6) are used to organize dynamic indication of the counting result on the LED indicator HL1. The collector loads of phototransistors VT1 and VT2 are resistors built into the microcontroller and enabled by software that connect the corresponding pins of the microcontroller to its power supply circuit.

An increase in the counting result N by one occurs at the moment the optical connection between the emitting diode VD1 and the phototransistor VT1 is interrupted, which creates an increasing level difference at the INT0 input of the microcontroller. In this case, the level at the INT1 input must be low, i.e., the phototransistor VT2 must be illuminated by the emitting diode VD2. At the moment of a rising differential at the INT1 input and a low level at the INT0 input, the result will decrease by one. Other combinations of levels and their differences at the inputs INT0 and INT1 do not change the counting result.

Once the maximum value of 9999 is reached, counting continues from zero. Subtracting one from the zero value gives the result 9999. If counting down is not needed, you can exclude the emitting diode VD2 and phototransistor VT2 from the counter and connect the INT1 input of the microcontroller to the common wire. The count will only continue to increase.

As already mentioned, the detector of a decrease in supply voltage is the analog comparator built into the microcontroller. It compares the unstabilized voltage at the output of the rectifier (diode bridge VD3) with the stabilized voltage at the output of the integrated stabilizer DA1. The program cyclically checks the state of the comparator. After disconnecting the meter from the network, the voltage on the rectifier filter capacitor C1 drops, and the stabilized voltage remains unchanged for some time. Resistors R2-R4 are selected as follows. that the state of the comparator in this situation is reversed. Having detected this, the program manages to write the current counting result to the EEPROM of the microcontroller even before it stops functioning due to the power being turned off. The next time you turn it on, the program will read the number written in EERROM and display it on the indicator. Counting will continue from this value.

Due to the limited number of microcontroller pins, to connect the SB1 button, which resets the counter, pin 13 was used, which serves as the inverting analog input of the comparator (AIM) and at the same time as the “digital” input of PB1. The voltage divider (resistors R4, R5) here sets the level perceived by the microcontroller as high logical. When you press the SB1 button, it will become low. This will not affect the state of the comparator, since the voltage at the AIN0 input is still greater than that at AIN1.

When the SB1 button is pressed, the program displays a minus sign in all digits of the indicator, and after releasing it, it starts counting from zero. If you turn off the power to the meter while the button is pressed, the current result will not be written to the EEPROM, and the value stored there will remain the same.

The program is designed in such a way that it can be easily adapted to a meter with other indicators (for example, with common cathodes), with a different printed circuit board layout, etc. A slight correction of the program will also be required when using a quartz resonator for a frequency that differs by more than 1 MHz from the specified one.

When the source voltage is 15 V, measure the voltage at pins 12 and 13 of the microcontroller panel relative to the common wire (pin 10). The first should be in the range of 4...4.5 V, and the second should be more than 3.5 V, but less than the first. Next, the source voltage is gradually reduced. When it drops to 9 ... 10 V, the difference in voltage values ​​at pins 12 and 13 should become zero and then change sign.

Now you can install the programmed microcontroller into the panel, connect the transformer and apply mains voltage to it. After 1.5...2 s you need to press the SB1 button. The counter indicator will display the number 0. If nothing is displayed on the indicator, check the voltage values ​​at the AIN0.AIN1 inputs of the microcontroller again. The first must be greater than the second.

When the counter has been successfully launched, all that remains is to check the correctness of the count by alternately shading the phototransistors with a plate opaque to IR rays. For greater contrast, it is advisable to cover the indicators with a red organic glass filter.

The device of this article is working with SD cards. The topic is old and quite hackneyed, but the use of SD cards is worth writing about it again.
In general, SD cards (SDC, SD Card) have many advantages and are very simple and convenient to use in small embedded projects. A number of factors contribute to this:
- a very simple interface for interacting with the card (implemented via SPI);
- high operating speed (the microcontroller is capable of transferring data from an SD card at a speed close to 10 Mbit/s);
- low power consumption (literally a couple of milliamps - no more);
- small sizes;
- availability and low cost.
SD cards have virtually no drawbacks (except, perhaps, for their initialization procedure :)).

1. Introduction.

I called the device described in this article SD Card Talking Device. A little pretentious ;), but the name makes it clear that this is a talking device. It is intended for voicing your projects. In short, it works as follows: numbered sound files are recorded on the SD card, which the device plays at your command. The scope of application is quite wide - warning systems, toys, robots, smart home, etc. The dimensions of the device are quite modest (it could be smaller, but I deliberately chose the ATtiny2313 microcontroller, which is cheaper and easier to get). I tried to place the main emphasis on simplicity and maximum functionality.
Looking ahead, let's see what should happen in the end:

Is such a device useful? Then let's collect!

2 Memory card.

The device uses an SD memory card. I have already written about the reasons for this choice, but I will only add that SD cards are becoming almost the standard memory card for mobile devices. Even manufacturers who fanatically promoted/are promoting their type of memory cards are slowly starting to use SD cards. The reason for such popularity was probably the low price of these cards. For amateur devices, the SD card is, in fact, the only card suitable for use, and the reason for this is the simple interface for working with it.

The SD card has come a long way in evolution and has several options for its implementation (MMC - as an SD card option, SD ver1, SD ver2, SDHC, SDXC). The procedure for communicating with the card is simple and universal for all types of cards, but putting it into operation (initializing the card) is a rather ambiguous and confusing process, with ritual “jerking” of the card, sending empty “dummy” commands and other incomprehensible things (in short, dancing with tambourines required:)). The specification for the SDC protocol itself describes the initialization process in quite some detail, which is understandable; there are a lot of card manufacturers, each with their own hardware, with their own characteristics... What am I getting at? - I tried to make the initialization procedure as universal as possible, but be prepared for the fact that some cards will not work. Therefore, if something is not going well with your device, try another memory card - this may be the reason.

This device supports SD cards up to 2 GB in size. Everything higher (SDHC and SDXC) is not supported.
It makes no difference for the device what form factor the card is (SD, MiniSD or MicroSD), but you must connect it correctly, according to the card pinout.

3 File system.

The device uses cards with the FAT16 file system. This system is ideally suited for devices like ours, as it is simple and easy to implement (FAT12 and FAT32, in principle, are also not difficult to implement, but this is impractical due to the lack of any advantages compared to FAT16).

There are no special requirements for formatting the card - it can be formatted in any available device. Standard Windows formatting is quite suitable for these purposes.

For the device to operate correctly, sound files located on the SD card must meet certain requirements:
a) The file format must be uncompressed WAV.
The file parameters are as follows:
- Bitrate - sampling frequency (Frequency) - 32000 Hz;
- Number of channels (Channels) - 1 (mono);
- Sample size - 8 bits.
Another possible reduction is WAV PCM 8U

b) The file must be named in a special way. In order for the device to know which file is the first, second, third, etc. The first character of the file name must be a capital letter of the Latin alphabet (the rest of the name, like the file extension, is ignored).
For example, the following file names would be correct:
A_Lai_dog.wav - first track
B-This is the second track.wav - the second track
With Warning! Error!.wav - third track

c) To use additional features of the device, files can be located in two folders named “1” and “2”. The device has a switch for selecting the active folder, that is, the same command to start playback can play tracks from folder “1” or “2”, depending on the level on the switching input (a kind of selection of the sound scheme - a very useful thing!) . If one of the folders (or both) does not exist, the files are played from the root directory.

You can store any other files along with audio tracks, provided that they do not create conflicts with their names (it is better to put them in a separate directory, then you will not have to pay attention to how they are named there).

d) Due to the small amount of SRAM on the ATtiny2313, it is impossible to create a buffer for pre-reading data, so data from the file is directly output for playback. Accordingly, there is no way (there is not enough time) to search for file fragments using the FAT table. In other words, the files written to the card must not be fragmented.

In fact, this is not a big problem, since any operating system always tries to write the file as a whole piece, and as long as you have space on the card, any actions with the files (deleting, copying, renaming) will not affect their integrity. If you have a very small card or you have filled a large card to capacity, in order to be sure of the integrity of the files, simply copy them to your computer’s hard drive, format the card and return the files back.

4 Scheme. Printed circuit board.

The device diagram is as simple as possible. In fact, apart from the microcontroller itself and the SD card, there is nothing in it. For myself, I made a signet for SMD components, since I plan to use this device in a place with limited dimensions. If the dimensions are not critical for you, you can assemble the circuit on a breadboard in the DIP version. In the case of a breadboard, assembling the device will take you, at most, 15 minutes. The permissible supply voltage for an SD card is from 2.7 to 3.6 volts. The microcontroller also works normally in this interval, so there is no need to use any matching components. I checked the operation of the entire device with a power supply of 5 volts - everything worked fine, but I do not recommend doing this on an ongoing basis, since different cards may react differently to excess voltage. I used an adapter as a microSD cardholder, soldering it directly to its contacts. If you need smaller dimensions, it is better to use a real cardholder for microSD.

To flash the microcontroller firmware, the same connector is used as for the SD card, so you will have to think about how to connect the programmer to it (I specially made an adapter).

After the board is soldered, you can flash the microcontroller.

A small gallery of the finished device:




A small nuance regarding the scheme.
When installing an SD card into a cardholder (connecting the card to a power source), a current surge is created and, accordingly, a voltage drop in the circuit (it seems that significant capacities are being charged in the card at this time). The drawdown is so significant that the microcontroller resets. I use this to start the card initialization procedure (installing the card restarts the microcontroller and the first thing the firmware does is search for and initialize the card). If you do not reset the microcontroller when installing a card (a powerful power supply or large smoothing capacitors), then you need to take care of the reset button in the circuit for manually resetting the microcontroller (this is if you plan to “hot” change cards).

5 Device operation.

As I wrote above, working with the device is very simple: copy the correctly named tracks to the SD card, insert the card into the cardholder, the device will automatically find the card, turn on the green LED - that’s it, the device is ready to play the tracks. Now you just need to select and start playing the track in the way that suits you best.

5.1 Device buttons and their actions.

I tried to make the device as functional as possible, so a lot of microcontroller legs are used for operating mode switches (this makes the device resemble a hedgehog :)). If you don’t need any function, just leave your leg “hanging” in the “air”.
Switch action:
- “Monster” - allows you to slow down (2 times) the playback of the track - creating the effect of a low voice. The switch works “on the fly” - the speed changes upon switching;
- “Helium” - speeds up the track playback (by 1/3) - creating the effect of a high-pitched voice. The switch works on the fly;
- “Repeat” if this switch is shorted to ground, the selected track will play endlessly (until the switch is opened). This can be useful, for example, if you need to create a certain sound background - the sound of rain, a burning fire, the murmuring of a stream...;
- “Select / Play” button that starts the track for playback (description below);
- “Select track” - setting the number of the track being played (description below);
- “Dir1 / Dir2” - select a sound scheme (description below).

5.2 Start playback.

There are three ways to start playing a specific track:
- by sending a capital letter of the Latin alphabet via UART, playback of the file containing this letter at the beginning of the name immediately begins;
- if using “Select track” the file number is selected (binary code 0001=”A”, 0010=”B”, etc. 1 - leg is closed to the ground, 0 - “hanging” in the “air”), then the “Select / Play” button will start the corresponding file for playback;
- if nothing is selected using “Select track” (0000 - legs “hang” in the “air”)), then by pressing the “Select / Play” button a certain number of times, we launch the corresponding track (1 time = “A”, 2 times =”B”, etc.).

5.3 Sound schemes.

A very useful feature is the function of selecting one of two sound schemes. This means that the “Dir1 / Dir2” switch selects the folder on the card from which the track will be played.

There are a lot of applications: messages in Russian and English (educational toys), children's and adult voices, noises of flowing water and burning fire, cat/dog, good and evil policeman :), calming/invigorating sounds and a bunch of other similar options.

For example, you need your device to be able to communicate in a male and female voice. It is implemented like this:
- create two sets of messages, respectively, in the female and male version;
- file numbering for both options is the same. Don’t forget that the device “sees” only the first letter in the file name, so you can make the names more understandable for yourself, for example, “S_Waiting for command_male.wav” and “S_Waiting for command_female.wav” are quite correct;
- copy the set of men’s messages into folder “1”, and the women’s messages into folder “2”.
Now, depending on the state of the “Dir1 / Dir2” switch, the same command will play tracks from the “male” or “female” folder.

5.4 Indication of device operation.

Since Teeny2313 has very few legs, and almost all of them are used for switches, I had to sacrifice a normal indication, and in return attach something NOT normal. To indicate different operating modes, only one leg of the microcontroller is used, to which two LEDs are connected - red and green (or whichever you prefer). The different operating modes of the device are indicated by a specific color code:
- red LED flashes - there is no SD card or its type is not supported by the device;
- the red LED is on - the SD card is supported and has been successfully initialized, but the card is not formatted in FAT16;
- the green LED is on - the SD card has been successfully initialized, the required file system has been found and the device is ready to play the track - waiting for a command;
- green LED flashes - the device is playing a track;
- green lights up, red lights up briefly, green lights up again - track not found;
- green lights up, goes out briefly and turns green again - the track selection key is pressed.

5.5 Debugging information.

To make it easier to find problem areas (if the device does not want to work), I duplicated each initialization stage in the program with messages via UART. After each successful step, the corresponding character is sent to the UART:
- “S” - (Start) the microcontroller peripherals are initialized normally;
- “C” - (Card Init) The SD card is initialized normally and is supported;
- “F” - (FAT Init) FAT system supported;
- “1” - (No 1 Dir) there is no folder “1” reading will be carried out from the root directory;
- “2” - (No 2 Dir) there is no folder “2” reading will be carried out from the root directory;
- “R” - (Ready) the device is completely ready - awaiting the command to start the track;
- In addition, each time a track is started, the capital letter of the track name is transmitted to the UART.

6 Tracks for dubbing your devices.

6.1 Converting tracks

If you didn’t find anything suitable in the library above, then you can get the necessary tracks on the Internet (there are many special sites for musicians and video editing, where large libraries of sounds have already been collected), in game installations (often gameplay sounds are divided into tracks and put into a separate folder). You can also cut sound effects from films and music compositions. The found tracks need to be converted into a format that the device supports. Let me remind you that the file format must be uncompressed WAV. 32000 Hz, 1 channel, 8 bit (WAV PCM 8U)
Any music editor is suitable for converting to this format, or, if you just need to convert a track without editing it -

How to program ATtiny2313 microcontrollers? So, we have an ATtiny2313 microcontroller, an LPT port (necessarily an iron one - no USB-2-LPT works), several wires (no more than 10cm long) and of course a soldering iron. It is advisable to have a DB-25M connector (male), it will be more convenient to connect a microcontroller with it, but you can do without it. We solder the wires to pins 1, 10, 17, 18, 19, 20 of the microcontroller. We get something like what is in the photo:


I did it without a connector (only mothers were available...), and this is what happened:


True, my LPT port is placed on the table using a 1.5 meter long cable. But the cable must be shielded, otherwise there will be interference, interference and nothing will work. The diagram of this microcontroller programming device is like this:


To be completely honest, it is advisable to assemble the “correct” programmer. And then it will be easier and the port will be intact. I use STK200/300. Next we use the PonyProg2000 program. After starting the program, it will "neigh...." like a real pony. To stop hearing this again, check the “Disable sound” box in the window that appears. Click "OK". A window pops up saying that you need to calibrate the program. There are different types of computers, both slow and fast. Click "OK". Another window pops up - this tells us that we need to configure the interface (which programmer and where it is connected.). So go to the menu: Setup -> Calibration. In the window that appears:


Click "YES". A couple of seconds pass and the program says "Calibration OK". Next, go to the menu: Setup -> Interface Setup. In the window that appears, configure it as shown in the figure.


Now go to the menu: Command -> Program Options. In the window that appears, configure it as shown in the figure.


Everything is ready for programming!... So, the sequence of actions:


1. Select "AVR micro" from the list
2. From another list, select "ATtiny2313"
3. Load the firmware file (File -> Open Device File), select the desired file, for example “rm-1_full.hex”.
4. Click the “Launch program cycle” button. When programming is completed the program will say "Program successful"
5. And finally, you need to program the so-called Fuses. To do this, click the “Security and Configuration Bits” button. In the window that appears, click “Read”, then check the boxes and click “Write”.

ATTENTION! If you don't know what a particular configuration bit means, don't touch it. Now we have the ATtiny2313 controller ready for use! On the forum you can download the PonyProg2000 program and the original article with additional pictures. Material for the Radio Circuit website was provided by Ansel73.

Today we will try to use a simpler microcontroller ATtiny2313 and connect to it a character LCD display containing two lines of 16 characters.

We will connect the display in the standard 4-bit way.

First, let's start, of course, with the microcontroller, since we are already very familiar with the display from previous lessons.

Let's open the controller datasheet ATtiny2313 and let's see its pinout

We see that this controller exists in two types of cases, but since I got it in a DIP package, we will consider this particular version of the case, and in principle, they do not differ much, except in appearance, so how the number of legs is the same - 20 each.

Since there are 20 legs compared to the 28 legs of the ATMega8 controller, which we have been working on all along and will continue to work on, then, accordingly, there will also be fewer possibilities.

In principle, everything that the ATmega8 had is here, the only thing is that there are fewer port claws. But since the task before us is to try to connect it via the SPI bus with another controller, this does not depress us much.

There are some other differences, but they are minor and we will get to know them as needed.

Let's assemble a circuit like this (click on the picture to enlarge the image)

The display is connected to the pins of port D. PD1 and PD2 are to the control inputs, and the rest are connected to the pins of the display module D4-D7.

Let's create a project with the name TINY2313_LCD, transfer everything into it except the main module from the project for connecting the display to Atmega8.

Of course, some things will need to be redone. To do this, you need to carefully study which leg is connected to what. The E bus of the display is connected to PD2, and the RS bus is connected to PD1, so let's make changes to the file lcd.h

#definee1PORTD|=0b0000 01 00 // set line E to 1

#definee0PORTD&=0b1111 10 11 // set line E to 0

#definers1PORTD|=0b00000 01 0 // set the RS line to 1 (data)

#definers0PORTD&=0b11111 10 1 // set the RS line to 0 (command)

As we can see from the bold font, we have not had such drastic changes.

Now information inputs. Here we use legs PD3-PD6, that is, they are shifted by 1 point compared to the connection to Atmega8, so we will also correct something in the file lcd.c in function sendhalfbyte

PORTD&=0b 1 0000 111; // erase information on inputs DB4-DB7, leave the rest alone

But that is not all. We previously shifted the transmitted data by 4, but now, due to the above changes, we will only have to shift it by 3. Therefore, in the same function we will also correct the very first line

c<<=3 ;

That's all the changes. Agree, they are not that great! This is achieved by the fact that we always try to write universal code and use macro substitutions. If we had not spent time on this at one time, we would have had to correct the code in almost all the functions of our library.

In the main module, we do not touch the initialization of port D; let the whole module go into the output state, as in lesson 12.

Let's try to assemble the project and first see the result in Proteus, since I also made a project for it, which will also be in the attached archive with the project for Atmel Studio

Everything works great for us! This is how you can quickly remake a project for one controller for another.

Proteus is very good, but it’s always nicer to look at real details. The entire circuit was assembled on a breadboard, since I did not make or assemble a debug board for this controller. We will connect the programmer via a standard connector like this

Here's the whole diagram

Everything is standard here. Pull-up resistor to RESET, etc.

Now, before flashing the controller in avrdude, we need to select the controller and read its flash memory

Then go to the FUSES tab and set the fuses correctly. Since we don’t have a quartz resonator, we install the fuses this way