Как подключить ультразвуковой датчик измерения расстояния HC-SR04 к ATmega16 и передать данные через USART/UART на компьютер
Очень часто нам нужно подключить датчик измерения расстояния HC-SR04 к ATmega16, Arduino или другому микроконтроллеру и отображать данные на экран или передать через USART/UART на наш компьютер.
В данной статье мы решим эти проблемы, а именно:
- подключим HC-SR04 к ATmega16;
- подключим радио модуль TB387 к ATmega16 или напрямую, или другой имеющийся радио модуль как HC-11/12 или FS1000A/XD-FST;
- напишем прошивку для ATmega16;
- проверим работоспособность.
Схема подключения модуля TB387 и датчика движения HC-SR04 к ATmega16
Пример программы в Atmel Studio 7
uart.h
#ifndef UART_H_ #define UART_H_ void USARTInit(unsigned int); void USARTTransmitChar(char); void USARTTransmitString(char*); void USARTTransmitStringLn(char*); char USARTReceiveChar(void); #endif /* UART_H_ */
uart.c
#include <avr/io.h>
#include "uart.h"
void USARTInit(unsigned int ubrr) {
// нормальный асинхронный двунаправленный режим работы
// UBRR = f / (16 * band)
// Установка скорости
UBRRH = (unsigned char)(ubrr>>8);
UBRRL = (unsigned char)(ubrr);
// RXC - завершение приёма
// |TXC - завершение передачи
// ||UDRE - отсутствие данных для отправки
// |||FE - ошибка кадра
// ||||DOR - ошибка переполнение буфера
// |||||PE - ошибка чётности
// ||||||U2X - Двойная скорость
// |||||||MPCM - Многопроцессорный режим
// ||||||||
// 76543210
UCSRA = 0;
// RXCIE - прерывание при приёме данных
// |TXCIE - прерывание при завершение передачи
// ||UDRIE - прерывание отсутствие данных для отправки
// |||RXEN - разрешение приёма
// ||||TXEN - разрешение передачи
// |||||UCSZ2 - UCSZ0:2 размер кадра данных
// ||||||RXB8 - 9 бит принятых данных
// |||||||TXB8 - 9 бит переданных данных
// ||||||||
// 76543210
// разрешен приём и передача данных по UART
UCSRB = 1<<RXEN | 1<<TXEN;
// URSEL - всегда 1
// |UMSEL - режим: 1-синхронный 0-асинхронный
// ||UPM1 - UPM0: 1 чётность
// |||UPM0 - UPM0: 1 чётность
// ||||USBS - стоп биты: 0-1, 1-2
// |||||UCSZ1 - UCSZ0: 2 размер кадра данных
// ||||||UCSZ0 - UCSZ0: 2 размер кадра данных
// |||||||UCPOL - в синхронном режиме - тактирование
// ||||||||
// 76543210
// 8-битовая посылка, 2 стоп бита
UCSRC = 1<<URSEL | 1<<USBS | 1<<UCSZ0 | 1<<UCSZ1;
}
// Отправка байта
void USARTTransmitChar(char c) {
// Устанавливается, когда регистр свободен
while(!( UCSRA & (1<<UDRE)));
UDR = c;
}
// Отправка строки
void USARTTransmitString(char str[]) {
register char i = 0;
while(str[i]) {
USARTTransmitChar(str[i++]);
}
}
// Отправка строки
void USARTTransmitStringLn(char str[]) {
USARTTransmitString(str);
USARTTransmitChar((char)13);
USARTTransmitChar((char)10);
}
// Получение байта
char USARTReceiveChar(void) {
// Устанавливается, когда регистр свободен
while(!(UCSRA & (1<<RXC)));
return UDR;
}
hcsr04.h
#ifndef HCSR04_H_ #define HCSR04_H_ void initHCSR04(); void stopHCSR04(); void trigHCSR04(); void waitHCSR04(); uint32_t getDistance(); #endif /* HCSR04_H_ */
hcsr04.c
// HC-SR04 к ATmega16
#define F_CPU 11059200UL // Clock Speed
#define TRIG_DDR DDRD
#define TRIG_PORT PORTD
#define TRIG_PIN PIND3
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdbool.h>
#include "hcsr04.h"
uint16_t rising, falling;
uint32_t counts;
uint32_t dist;
bool star = false;
// Режим захвата
ISR(TIMER1_CAPT_vect) {
// ICES1 = 1
// фронт - положительный срез
if (TCCR1B & (1<<ICES1)) {
// Сохраняем текущее значение счетчика
rising = ICR1;
// В следующий раз обнаружить спад (отрицательный срез)
TCCR1B &= ~(1<<ICES1);
// Просто код ошибки, что измерение не произошло
dist = -2;
}
// ICES1 = 0
// спад - отрицательный срез
else {
// Сохраняем текущее значение счетчика
falling = ICR1;
// считаем число тактов
counts = falling - rising;
// определяем растояние в миллиметрах
dist = (counts * 100) / 813;
// уведомляем функцию waitHCSR04() что можно отправить
// результат заказчику т.е. растояние определено
star = false;
}
}
// обработчик прерывания по совпадению значения таймера со значением регистра OCR1A
// OCR1A = 0xFFFF
ISR(TIMER1_COMPA_vect) {
// уведомляем функцию waitHCSR04() что можно отправить
// результат заказчику т.е. растояние не определено
// HC-SR04 не получил обратный сигнал т.е. растояние
// слишком большая, сенсор не подключён или сигнал слишком слабый
dist = -1;
star = false;
}
// инициализация HCSR04
void initHCSR04() {
// инициализация ножки TRIG как выход
TRIG_DDR |= 1<<TRIG_PIN;
rising = falling = counts = dist = 0;
// инициализация таймера 1 TIMER1
// CS12,CS11,CS10: Clock Select. Эти 3 бита задают источник тактового сигнала для счетчика.
// 0 1 0 : F_CPU/8 (с выхода делителя)
// ICNC1: Установка этого бита в лог. 1 активирует входной подавитель шума
// WGM13,WGM12,WGM11,WGM10:
// 0 1 0 0 : режим CTC, максимальное значение OCR1A = 0xFFFF
TCCR1B |= (1<<ICNC1) | (1<<CS11) | (1<<WGM12);
// TICIE1 = 1: разрешено прерывание захвата таймера/счетчика 1
// OCIE1A = 1: разрешено прерывание по совпадению регистра A с состоянием таймера/счетчика1
TIMSK |= (1<<TICIE1) | (1<<OCIE1A);
// ICES1 = 1: захват входа ICR1 по нарастающему фронту (положительный срез).
TCCR1B |= (1<<ICES1);
// максимальное значение счетчика
OCR1A = 0xFFFF;
// активируем прерывания
sei();
}
// отключаем режим захвата
void stopHCSR04() {
TRIG_DDR &= ~(1<<TRIG_PIN);
// TIMER1 INIT
TCCR1B &= ((1<<ICNC1) | (1<<CS11) | (1<<WGM12));
TIMSK &= ((1<<TICIE1) | (1<<OCIE1A));
TCCR1B &= ((1<<ICES1));
OCR1A = 0;
}
// Генерируем импульс на 12us
void trigHCSR04() {
TRIG_PORT ^= (1<<TRIG_PIN);
_delay_us(12);
TRIG_PORT ^= (1<<TRIG_PIN);
}
// ждём пока star равно true т.е. завершение измерения
void waitHCSR04() {
star = true;
while(star) {
_delay_us(1);
}
}
uint32_t getDistance() {
// Инициализируем таймер (HCSR04)
initHCSR04();
// Генерируем импульс на 12us
trigHCSR04();
// Ждем, пока растояние не определено
waitHCSR04();
// Останавливаем таймер
stopHCSR04();
// Возвращяем результат
return dist;
}
main.c
#define F_CPU 11059200UL // Clock Speed
#define BAUD 9600
#define MYUBRR F_CPU/16/BAUD-1
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include "uart.h"
#include "hcsr04.h"
int main(void) {
uint32_t d;
char str[20];
USARTInit(MYUBRR);
while (1) {
d = getDistance();
sprintf(str, "Distance: %dmm", d);
USARTTransmitStringLn(str);
_delay_ms(1000);
}
}
Результат
Скачать
Terminal 1.9b — работаем с COM-портом
datasheet ATMEGA16.pdf
Проект в Atmel Studio 7 HC-SR04+UART+ATmega16


продать аккаунт https://birzha-accauntov.ru/
аккаунты с балансом площадка для продажи аккаунтов
магазин аккаунтов социальных сетей https://pokupka-akkauntov-online.ru/
Account Buying Service Ready-Made Accounts for Sale
Account Exchange Service Account Selling Service
Account Trading Platform Account Exchange Service
Accounts for Sale Buy accounts
Buy accounts Purchase Ready-Made Accounts
find accounts for sale account trading platform
account selling platform buyaccountsdiscount.com
sell accounts sell accounts
account market account exchange
guaranteed accounts accounts market
account selling service buy accounts
account trading service buy accounts
sell account verified accounts for sale
account market https://social-accounts.org
account marketplace https://buy-social-accounts.org/
secure account sales account market
website for buying accounts secure account sales
account marketplace profitable account sales
account acquisition profitable account sales
buy accounts account exchange
buy accounts sell accounts
account purchase account purchase
accounts marketplace verified accounts for sale
buy and sell accounts buy accounts
sell accounts https://accounts-marketplace.xyz
account marketplace https://buy-best-accounts.org/
account buying service https://social-accounts-marketplaces.live
gaming account marketplace https://social-accounts-marketplace.xyz
buy pre-made account https://buy-accounts-shop.pro
online account store buy accounts
account catalog https://social-accounts-marketplace.live
find accounts for sale account market
secure account purchasing platform https://accounts-marketplace.online
маркетплейс аккаунтов akkaunty-na-prodazhu.pro
площадка для продажи аккаунтов rynok-akkauntov.top
маркетплейс аккаунтов https://akkaunty-market.live
покупка аккаунтов kupit-akkaunty-market.xyz
маркетплейс аккаунтов https://akkaunty-optom.live
купить аккаунт kupit-akkaunt.online
facebook account sale facebook ads account buy
buy facebook ads manager https://buy-ad-account.top
facebook ads accounts https://buy-ads-account.click
buy fb ad account buying facebook accounts
buy aged facebook ads account buy facebook advertising accounts
buy facebook accounts for ads https://buy-ad-account.click
buy facebook accounts for advertising https://ad-accounts-for-sale.work
buy aged google ads account https://buy-ads-account.top
google ads accounts for sale https://ads-account-for-sale.top
buy verified google ads account https://ads-account-buy.work/
buy google ads threshold account https://buy-ads-invoice-account.top
buy google ads invoice account https://buy-account-ads.work
buy google agency account buy-ads-agency-account.top
buy google adwords accounts https://sell-ads-account.click
buy google ads buy-verified-ads-account.work
buy verified business manager buy-business-manager.org
buy facebook ads accounts and business managers buy-business-manager-acc.org
buy facebook business manager buy business manager account
buy fb bm https://buy-verified-business-manager.org
unlimited bm facebook business-manager-for-sale.org
buy facebook bm account https://verified-business-manager-for-sale.org
buy tiktok ad account https://buy-tiktok-ads-account.org
tiktok ads account buy https://tiktok-ads-account-buy.org
buy tiktok ad account https://tiktok-agency-account-for-sale.org
buy tiktok ads https://buy-tiktok-ads-accounts.org
tiktok ads agency account https://buy-tiktok-business-account.org
tiktok ads account for sale https://buy-tiktok-ads.org
buy tiktok business account https://tiktok-ads-agency-account.org
buy accounts facebook buy and sell accounts gaming account marketplace
indian pharmacy paypal: Online medicine order — india pharmacy mail order
https://nyupharm.com/# best canadian online pharmacy
indian pharmacies safe: Umass India Pharm — cheapest online pharmacy india
india pharmacy: indian pharmacy paypal — reputable indian online pharmacy
Great blog! Do you have any recommendations for aspiring
writers? I’m planning to start my own blog soon but I’m a little lost
on everything. Would you advise starting with a free platform like WordPress or go for a paid option? There are
so many choices out there that I’m completely confused .. Any
ideas? Many thanks!
http://unmpharm.com/# semaglutide mexico price
https://t.me/s/Officials_888STARZ
https://unmpharm.com/# Unm Pharm
http://unmpharm.com/# cheap cialis mexico
jokerstar casino anmeldung freispiele
References:
https://online-spielhallen.de/willkommen-bei-nine-casino-und-ihren-exklusiven-promo-codes/
http://unmpharm.com/# Unm Pharm
https://t.me/s/officials_7k_casino
Does anyone know buying generic pills online. I discovered a good archive that reviews affordable options: п»їhttps://polkcity.us.com/# pharmacy delivery. Looks legit.
п»їJust now, I stumbled upon an informative resource regarding generic pills from India. It details how to save money for ED medication. For those interested in reliable shipping to USA, take a look: п»їkisawyer.us.com. It helped me.
п»їRecently, I found a helpful article concerning buying affordable antibiotics. The site discusses how to save money on prescriptions. If you are looking for cheaper alternatives, visit this link: п»їkisawyer.us.com. Might be useful.
п»їJust now, I stumbled upon a great article concerning buying affordable antibiotics. It explains how to save money on prescriptions. For those interested in reliable shipping to USA, visit this link: п»їhttps://kisawyer.us.com/# indian pharmacy paypal. It helped me.
For those looking to save big on pills, I recommend reading this report. The site explains where to buy cheap. Huge savings at this link: п»їUpstate Medical.
FYI, a helpful analysis on Mexican Pharmacy safety. The author describes how to avoid scams for antibiotics. You can read it here: п»їhttps://polkcity.us.com/# mexico drug store online.
п»їJust now, I discovered a helpful article concerning Indian Pharmacy exports. It details WHO-GMP protocols when buying antibiotics. In case you need factory prices, go here: п»їtop 10 pharmacies in india. Cheers.
п»їLately, I discovered an informative article about ordering meds from India. It details WHO-GMP protocols on prescriptions. If you are looking for factory prices, check this out: п»їhttps://kisawyer.us.com/# indian pharmacy paypal. It helped me.
п»їTo be honest, I stumbled upon an interesting article regarding cheap Indian generics. The site discusses WHO-GMP protocols for ED medication. If anyone wants factory prices, visit this link: п»їhttps://kisawyer.us.com/# Online medicine order. Worth a read.
п»їRecently, I came across a helpful resource about ordering meds from India. It details the manufacturing standards on prescriptions. If you are looking for reliable shipping to USA, go here: п»їkisawyer.us.com. Cheers.
п»їRecently, I discovered a great resource about buying affordable antibiotics. It covers regulations for generic meds. If you are looking for Trusted pharmacy sources, go here: п»їonline pharmacies. Cheers.
Just wanted to share, an important overview on Mexican Pharmacy safety. It explains the best shipping methods for generics. You can read it here: п»їhttps://polkcity.us.com/# farmacia pharmacy mexico.
п»їRecently, I stumbled upon an informative article regarding Indian Pharmacy exports. The site discusses CDSCO regulations for ED medication. For those interested in Trusted Indian sources, visit this link: п»їhttps://kisawyer.us.com/# indian pharmacy online. Might be useful.
Just wanted to share, a detailed article on Mexican Pharmacy safety. It explains pricing differences for generics. Full info: п»їhttps://polkcity.us.com/# mexican drug stores.
п»їJust now, I found a helpful page regarding buying affordable antibiotics. It details WHO-GMP protocols when buying antibiotics. For those interested in cheaper alternatives, go here: п»їkisawyer.us.com. Hope it helps.
п»їJust now, I stumbled upon an interesting guide concerning ordering meds from India. It covers WHO-GMP protocols for generic meds. If you are looking for cheaper alternatives, go here: п»їhttps://kisawyer.us.com/# п»їlegitimate online pharmacies india. Worth a read.
http://www.google.by/url?q=https://t.me/s/officials_7k/1102
Does anyone know buying generic pills online. I saw a decent site that lists best pharmacies: п»їpolkcity.us.com. Seems useful..
Just wanted to share, a detailed overview on Mexican Pharmacy safety. The author describes the best shipping methods for antibiotics. You can read it here: п»їUpstate Medical.
п»їLately, I came across an interesting guide concerning ordering meds from India. It details WHO-GMP protocols for generic meds. If you are looking for Trusted Indian sources, take a look: п»їhttps://kisawyer.us.com/# online pharmacy india. Might be useful.
п»їTo be honest, I discovered a useful guide regarding ordering meds from India. It details WHO-GMP protocols on prescriptions. If anyone wants factory prices, visit this link: п»їhttps://kisawyer.us.com/# п»їlegitimate online pharmacies india. Hope it helps.
п»їActually, I stumbled upon a useful resource about buying affordable antibiotics. It details CDSCO regulations when buying antibiotics. For those interested in reliable shipping to USA, visit this link: п»їhttps://kisawyer.us.com/# india online pharmacy. Might be useful.
To save big on pills, I suggest reading this archive. The site explains trusted Mexican pharmacies. Good deals at this link: п»їUpstate Medical.
п»їTo be honest, I came across a useful page about generic pills from India. The site discusses WHO-GMP protocols for generic meds. For those interested in reliable shipping to USA, check this out: п»їcheck here. Might be useful.
п»їRecently, I found an informative article concerning generic pills availability. It explains the safety protocols on prescriptions. If you are looking for affordable options, read this: п»їhttps://polkcity.us.com/# mexican drug store. Worth a read.
п»їJust now, I found an interesting report about ordering meds from India. It details WHO-GMP protocols for generic meds. If anyone wants factory prices, go here: п»їhttps://kisawyer.us.com/# india online pharmacy. It helped me.
п»їJust now, I stumbled upon a helpful guide concerning Indian Pharmacy exports. The site discusses how to save money for ED medication. If you are looking for cheaper alternatives, check this out: п»їhttps://kisawyer.us.com/# indianpharmacy com. Good info.
п»їRecently, I came across an informative page concerning generic pills from India. It covers the manufacturing standards on prescriptions. For those interested in cheaper alternatives, take a look: п»їOnline medicine order. Worth a read.
п»їTo be honest, I discovered a helpful report about buying affordable antibiotics. It details the manufacturing standards on prescriptions. If you are looking for reliable shipping to USA, read this: п»їkisawyer.us.com. Hope it helps.
п»їTo be honest, I discovered a great resource concerning cheap Indian generics. It details WHO-GMP protocols for generic meds. For those interested in cheaper alternatives, visit this link: п»їlink. Worth a read.
Sharing, a detailed analysis on FDA equivalent standards. It breaks down quality control for ED meds. Link: п»їUpstate Medical.
п»їRecently, I discovered a great guide concerning Indian Pharmacy exports. It details WHO-GMP protocols on prescriptions. In case you need cheaper alternatives, read this: п»їlink. Might be useful.
п»їRecently, I discovered a useful article about cheap Indian generics. It explains WHO-GMP protocols when buying antibiotics. For those interested in cheaper alternatives, take a look: п»їindia pharmacy. Good info.
п»їRecently, I found a useful article about cheap Indian generics. It covers how to save money when buying antibiotics. If anyone wants cheaper alternatives, go here: п»їkisawyer.us.com. Might be useful.
In fact when someone doesn’t be aware of after that its up to other people that they will assist,
so here it occurs.
Stop overpaying and save on pharmacy costs, you should try reading this resource. It reveals shipping costs. Good deals available here: п»їpolkcity.us.com.
п»їJust now, I found a great resource concerning generic pills from India. It covers how to save money for generic meds. In case you need cheaper alternatives, read this: п»їhttps://kisawyer.us.com/# online pharmacy india. Cheers.
п»їJust now, I found a useful page concerning generic pills from India. The site discusses the manufacturing standards for ED medication. If you are looking for cheaper alternatives, take a look: п»їbest india pharmacy. Cheers.
п»їJust now, I stumbled upon an informative guide concerning ordering meds from Mexico. It explains the safety protocols when buying antibiotics. For those interested in reliable shipping to USA, check this out: п»їhttps://polkcity.us.com/# mexico pharmacy price list. Might be useful.
п»їActually, I came across a great guide regarding generic pills from India. The site discusses WHO-GMP protocols on prescriptions. If anyone wants Trusted Indian sources, go here: п»їkisawyer.us.com. It helped me.
п»їJust now, I discovered a useful article about generic pills from India. It explains CDSCO regulations on prescriptions. In case you need factory prices, go here: п»їhttps://kisawyer.us.com/# buy medicines online in india. Good info.
п»їTo be honest, I found an informative guide about generic pills from India. It details the manufacturing standards for generic meds. If you are looking for factory prices, take a look: п»їindian pharmacy paypal. Might be useful.
п»їActually, I came across an informative article about cheap Indian generics. It details how to save money for generic meds. For those interested in cheaper alternatives, visit this link: п»їhttps://kisawyer.us.com/# mail order pharmacy india. Might be useful.