В данной статье пойдет речь о том, как подключить ультразвуковой дальномер HC-SR04 к ATtiny2313 и отображать данные на ЖКИ-дисплее 16×1 на базе HD44780. Также сделал пример программы для отправки результата по UART. Для приёма я использовал Terminal 1.9b и преобразователь USB-UART на базе PL2303HX. Для проверки работоспособности программы и схемы я использовал Proteus 7. Проект в Atmel Studio 7 целиком вы сможете скачать по ссылке в конце статьи. При прошивке микроконтроллера ATtiny2313 не забудьте менять фьюзы: CKSEL3…0 = 0100 – Внутренний тактовый генератор — частота 8 МГц и поставить галочку (т.е. отключить) на SCKDIV8 – деление тактовой частоты на 8.
- 1 Схема подключения TB378 и HC-SR04 к ATtiny2313
- 2 Пример программы в Atmel Studio 7
- 3 Схема подключения LCD HD44780 и HC-SR04 к ATtiny2313
- 4 Пример программы в Atmel Studio 7
- 5 Скачать файлы
- 6 Купить HC-SR04 на AliExpress
- 7 Купить ATTINY2313A на Aliexpress
- 8 Купить LCD1602 HD44780 на Aliexpress
- 9 Похожие записи
Схема подключения TB378 и HC-SR04 к ATtiny2313
Для начала сделал программу для получения данных по UART.
Пример программы в Atmel Studio 7
main.c
#define F_CPU 8000000UL #define BAUD 9600 #define MYUBRR F_CPU/16/BAUD-1 #include <avr/io.h> #include <util/delay.h> #include <string.h> #include <stdlib.h> #include "uart.h" #include "hcsr04.h" inline void prepareText(char * text, int distance) { char textDistance[5]; itoa(distance, textDistance, 10); strcat(text, "D = "); strcat(text, textDistance); strcat(text, "mm"); } int main(void) { int distance; char text[17]; USARTInit(MYUBRR); while (1) { text[0] = '\0'; distance = getDistance(); prepareText(text, distance); USARTTransmitStringLn(text); _delay_ms(333); } }
Краткое описание
Вместо функции sprintf()
сделал собственную функцию для преобразования числа в строку, потому что sprintf()
жрёт больше половины флеш памяти контроллера.
inline void prepareText(char * text, int distance)
Функция prepareText преобразует целое число distance
(расстояние) в строку и добавляет строку в text
.
itoa(distance, textDistance, 10);
Функция itoa
преобразует целое число distance
в строку textDistance
в формате 10
.
strcat(text, textDistance);
Объединение строк. Функция добавляет textDistance
строки srcptr в конец строки text
.
Результат
Так как в Протеус нету HC-SR04, я его просто нарисовал. На первой картинке результат в -1 означает что датчик HC-SR04 не подключён или Echo не отправил сигнал.
После прошивки реального ATtiny2313, подключил к компьютеру и вот результат.
Схема подключения LCD HD44780 и HC-SR04 к ATtiny2313
После того, как убедился, что датчик HC-SR04 и программа работают правильно, для вывода результата подключил однорядный ЖК на 16 символов — HD44780.
Пример программы в Atmel Studio 7
main.c
#define F_CPU 8000000UL #include <avr/io.h> #include <util/delay.h> #include <string.h> #include <stdlib.h> #include "hcsr04.h" #include "LCD.h" inline void prepareText(char * text, int distance) { char textDistance[5]; itoa(distance, textDistance, 10); strcat(text, "D="); strcat(text, textDistance); strcat(text, "mm"); } int main(void) { _delay_ms(100); lcdInit(); lcdClear(); lcdSetDisplay(LCD_DISPLAY_ON); lcdSetCursor(LCD_CURSOR_OFF); int distance; char text[17]; while (1) { text[0] = '\0'; distance = getDistance(); prepareText(text, distance); lcdClear(); lcdGotoXY(0, 0); lcdPuts(text); _delay_ms(333); } }
Результат
В Протеусе всё работает, текст отображается правильно.
Скачать файлы
ATtiny2313 + HC-SR04 + LCD — Atmel Studio 7 проект
ATtiny2313 + HC-SR04 + UART — ISIS Professional (Proteus) проект
ATtiny2313 + HC-SR04 + LCD — ISIS Professional (Proteus) проект
ATtiny2313 + HC-SR04 + UART — Atmel Studio 7 проект
ATtiny2313A даташит на Русском
ATtiny2313A datasheet (EN)
Excellent blog post. I certainly appreciate
this website. Thanks!
being vegan can help the environment essay writing paper with lines psych 1 integrative essay help
Wow, incredible blog layout! How long have you been blogging for?
you made blogging look easy. The overall look of your web site is wonderful, as well as the content!
Great post. I used to be checking continuously this blog and I’m inspired!
Very useful information particularly the final part 🙂 I deal with such info a lot.
I was looking for this certain information for a long time.
Thank you and good luck.
Leg cramps in ketosis usually stem from dehydration and loss of minerals. This doesn’t necessarily have to be your weight, unless weight loss is your goal. When you enter ketosis, you lose a lot of water weight. But the problem is, it’s hard to maintain ketosis, and one snack is all it takes to slip up. In one study in 17 men with obesity, following a ketogenic diet providing 30% of calories from protein for 4 weeks led to blood ketone levels of 1.52 mmol/L, on average. People following the keto diet process will have several issues like the urge to eat, tiredness, mood swings, and many other problems. Lazy: «Lazy keto» means that you’re following a http://tou-ka.sakura.ne.jp/rosa-gigantea/index.cgi?room=msgs diet without tracking your intake. The reasons behind this increase in fullness include a higher protein intake compared to a standard Western diet. High ketone levels in your body can cause an increase in acid buildup in your blood. It is specially formulated to increase your body’s metabolism to break down fat faster, and more efficiently.
generic viagra online for sale viagra for women sildenafil citrate over the counter
help with an essay history research paper how parents can help with college essay
weight gain after stopping tamoxifen taxomifenshopping.org tamoxifen and aromatase inhibitors
sildenafil citrate 100mg lowest price buy viagra online usa sildenafil 20mg
medications with no prescription
cialis viagra online cialis from india cialis review
Nicely put. Appreciate it!
Ozone (O3) is a gasoline that normally takes place in the atmosphere. It is a blend of three oxygen particles and also has a clear, specific scent that resembles chlorine bleach. When inhaled, O3 can easily aggravate the lungs, leading to coughing as well as throwing up, https://intensedebate.com/people/thomasleaf4.
were can i buy cialis canadian pharmacy cialis 20mg cheap generic cialis
Great post however I was wondering if you could write a litte more on this topic?
I’d be very thankful if you could elaborate a little bit further.
Appreciate it!
best online pharmacy reviews
best rated canadian pharmacy
I know this if off topic but I’m looking into starting my own weblog and was curious what all
is required to get setup? I’m assuming having a blog like yours would cost a
pretty penny? I’m not very internet smart so I’m not 100% certain. Any tips or advice would be greatly appreciated.
Many thanks