Как подключить ультразвуковой датчик измерения расстояния 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
https://rxfreemeds.shop/# Duricef
rx care pharmacy: RxFree Meds — viagra no prescription online pharmacy
fenofibrate online pharmacy price RxFree Meds cheap pharmacy viagra
RxFree Meds: best rx pharmacy port charlotte fl — lamisil online pharmacy
https://rxfreemeds.shop/# viagra pharmacy malaysia
enclomiphene for men buy enclomiphene online enclomiphene buy
Farmacia Asequible: Farmacia Asequible — Farmacia Asequible
Farmacia Asequible Farmacia Asequible precio diprogenta
https://medismartpharmacy.com/# bupropion xl pharmacy
MexiMeds Express: medication from mexico pharmacy — mexico pharmacies prescription drugs
indianpharmacy com: IndoMeds USA — IndoMeds USA
india pharmacy: IndoMeds USA — IndoMeds USA
best provigil pharmacy MediSmart Pharmacy finasteride target pharmacy
MexiMeds Express: mexican pharmaceuticals online — MexiMeds Express
Online medicine home delivery cheapest online pharmacy india п»їlegitimate online pharmacies india
https://meximedsexpress.com/# purple pharmacy mexico price list
https://indomedsusa.com/# indian pharmacy paypal
mexico drug stores pharmacies: mexico pharmacies prescription drugs — mexican online pharmacies prescription drugs
IndoMeds USA IndoMeds USA buy prescription drugs from india
http://indomedsusa.com/# india online pharmacy
https://indomedsusa.shop/# IndoMeds USA
india online pharmacy buy prescription drugs from india indianpharmacy com
https://medismartpharmacy.shop/# Lanoxin
https://medismartpharmacy.shop/# legit pharmacy websites
MexiMeds Express: MexiMeds Express — MexiMeds Express
MexiMeds Express mexican pharmaceuticals online best online pharmacies in mexico
https://meximedsexpress.com/# MexiMeds Express
selegiline pharmacy: MediSmart Pharmacy — precision pharmacy omeprazole powder
canadianpharmacyworld: MediSmart Pharmacy — canadian pharmacy online store
MexiMeds Express: MexiMeds Express — mexican rx online
https://meximedsexpress.shop/# MexiMeds Express
med rx pharmacy: MediSmart Pharmacy — inhouse pharmacy viagra
https://medismartpharmacy.com/# celexa online pharmacy
MexiMeds Express buying from online mexican pharmacy mexico drug stores pharmacies
buy accounts facebook buy and sell accounts gaming account marketplace
MexiMeds Express: MexiMeds Express — MexiMeds Express
buying prescription drugs in mexico online: п»їbest mexican online pharmacies — MexiMeds Express
gabapentin prices pharmacy fluconazole target pharmacy pharmacy coumadin clinic
https://medismartpharmacy.shop/# celexa online pharmacy
humana pharmacy store: online viagra pharmacy — grocery store pharmacy
onguent antibiotique sans ordonnance: PharmaDirecte — prix nicopatch 21 mg
https://clinicagaleno.com/# oferta farmacia online
https://clinicagaleno.shop/# farmacia online l vazquez
tadalafil 5mg boГ®te 28 prix: uriage 3 regul — azithromycine sans ordonnance france
bonbon coupe faim PharmaDirecte mycose pharmacie sans ordonnance
https://pharmadirecte.com/# parfum mustela pharmacie
nifedicor gocce online shop: feldene fiale prezzo — nasonex spray nasale 140 prezzo
http://pharmadirecte.com/# xanax ordonnance
farmacia online como: comprar antibiГіtico sin receta — comprar galotam 100 sin receta precio
farmatint farmacia online: Clinica Galeno — se puede comprar viagra sin receta en farmacias fisicas
http://clinicagaleno.com/# farmacia shop online napoli
https://pharmadirecte.shop/# listerine zero
licenciatura en farmacia online: Clinica Galeno — farmacia online en toledo
yodeyma farmacia online comprar progevera sin receta farmacia online mascarillas protectoras
http://clinicagaleno.com/# técnico en farmacia online homologado
https://snabbapoteket.shop/# tensplattor apotek
online pharmacy nl apotheke online medicijne
https://snabbapoteket.com/# snabbtest apotek
morgenkГҐpe apotek: TryggMed — apotek ГҐpningstider jul
apotek rask levering: covid hurtigtest apotek — solsengtrekk apotek
mijn medicijnen bestellen Medicijn Punt medicijn online
kokosolja mot fГ¤stingar: SnabbApoteket — apotek vГ¤tskeersГ¤ttning
blodtrykksmГҐling apotek Trygg Med apotek tГёfler
online apotheken: dokter online medicijnen bestellen — apotheker online
apotek ГҐpent 17 mai: natriumbenzoat apotek — chlamydia test apotek
http://zorgpakket.com/# medicijnen snel bestellen
online apotheker: apotheke niederlande — niederlande apotheke
medicijnen op recept medicatie apotheker medicijnen op recept
buy antibiotics over the counter in mexico: MediMexicoRx — buy meds from mexican pharmacy
https://medimexicorx.com/# MediMexicoRx
trusted mexican pharmacy: real mexican pharmacy USA shipping — cheap cialis mexico
https://expresscarerx.online/# family rx pharmacy
http://medimexicorx.com/# medication from mexico pharmacy
metronidazole pharmacy: ExpressCareRx — bestsellers
ExpressCareRx can i buy viagra at pharmacy viagra pharmacy india
https://medimexicorx.com/# buying from online mexican pharmacy
MediMexicoRx MediMexicoRx buy viagra from mexican pharmacy
https://expresscarerx.org/# ExpressCareRx
low cost mexico pharmacy online: accutane mexico buy online — MediMexicoRx
amoxicillin and beer pharmacy: ExpressCareRx — online pharmacy percocet
MediMexicoRx: amoxicillin mexico online pharmacy — MediMexicoRx
http://expresscarerx.org/# tylenol pharmacy scholarship 2012
value generic pharmacy adipex: naltrexone india pharmacy — Artane
https://medimexicorx.shop/# buying from online mexican pharmacy
MediMexicoRx: order from mexican pharmacy online — semaglutide mexico price
india pharmacy mail order: reputable indian pharmacies — best online pharmacy india
giant pharmacy store hours ExpressCareRx ExpressCareRx
buy cialis from mexico: order from mexican pharmacy online — MediMexicoRx
https://expresscarerx.org/# mexican online pharmacy
IndiaMedsHub: india online pharmacy — best online pharmacy india
tadalafil online no rx: generic Cialis from India — Tadalafil From India
buy Accutane online cheap Accutane Accutane for sale
cheap Propecia Canada: cost propecia without a prescription — Propecia for hair loss online
cheap Accutane: USA-safe Accutane sourcing — Isotretinoin From Canada
Accutane for sale: USA-safe Accutane sourcing — purchase generic Accutane online discreetly
Zoloft online pharmacy USA buy Zoloft online Zoloft Company
buy Cialis online cheap: buy Cialis online cheap — cheap Cialis Canada
https://lexapro.pro/# lexapro 10 mg
https://tadalafilfromindia.com/# cheap Cialis Canada
tadalafil online no rx: cheap Cialis Canada — buy Cialis online cheap
Accutane for sale Accutane for sale generic isotretinoin
Accutane for sale: USA-safe Accutane sourcing — cheap Accutane
generic Finasteride without prescription: cost of cheap propecia pill — order cheap propecia without a prescription
https://tadalafilfromindia.shop/# Cialis without prescription
generic isotretinoin: Isotretinoin From Canada — buy Accutane online
buy Cialis online cheap: buy Cialis online cheap — buy tadalafil 20mg uk
https://zoloft.company/# Zoloft for sale
tadalafil online no rx: tadalafil online no rx — tadalafil 100mg
http://tadalafilfromindia.com/# buy Cialis online cheap
cheap Propecia Canada Finasteride From Canada buying generic propecia without prescription
https://lexapro.pro/# Lexapro for depression online
Zoloft Company: Zoloft Company — Zoloft Company
order isotretinoin from Canada to US: order isotretinoin from Canada to US — Accutane for sale
https://zoloft.company/# buy Zoloft online without prescription USA
https://isotretinoinfromcanada.shop/# purchase generic Accutane online discreetly
cheap Accutane: isotretinoin online — isotretinoin online
prescription price for lexapro: Lexapro for depression online — buy lexapro
https://tadalafilfromindia.com/# Tadalafil From India
buy Cialis online cheap Cialis without prescription generic Cialis from India
USA-safe Accutane sourcing: isotretinoin online — purchase generic Accutane online discreetly
https://tadalafilfromindia.com/# Cialis without prescription
purchase generic Accutane online discreetly: isotretinoin online — order isotretinoin from Canada to US
Isotretinoin From Canada: generic isotretinoin — generic isotretinoin
generic Finasteride without prescription generic Finasteride without prescription buy generic propecia without insurance
http://tadalafilfromindia.com/# tadalafil online no rx
cost cheap propecia prices: Propecia for hair loss online — generic Finasteride without prescription
cheap Propecia Canada: cost of generic propecia without insurance — Propecia for hair loss online
generic Cialis from India: cheap Cialis Canada — buy Cialis online cheap
generic Finasteride without prescription: generic Finasteride without prescription — cheap Propecia Canada
https://tadalafilfromindia.com/# tadalafil online no rx
buy propecia price: generic Finasteride without prescription — Propecia for hair loss online
buy lexapro no prescription: Lexapro for depression online — Lexapro for depression online
http://finasteridefromcanada.com/# cheap Propecia Canada
Clomid Hub Pharmacy: Clomid Hub Pharmacy — Clomid Hub Pharmacy
NeuroRelief Rx: NeuroRelief Rx — NeuroRelief Rx
where to buy generic clomid pill can i purchase clomid Clomid Hub Pharmacy
https://neuroreliefrx.shop/# NeuroRelief Rx
wakefulness medication online no Rx: smart drugs online US pharmacy — WakeMeds RX
NeuroRelief Rx: gabapentin dosage for babies — glenmark gabapentin gluten free
where to buy Modafinil legally in the US: buy Modafinil online USA — safe Provigil online delivery service
safe Provigil online delivery service Wake Meds RX buy Modafinil online USA
Relief Meds USA: can you buy prednisone — Relief Meds USA
http://clearmedsdirect.com/# ClearMeds Direct
ReliefMeds USA: buy 40 mg prednisone — prednisone 80 mg daily
ClearMeds Direct order amoxicillin without prescription Clear Meds Direct
https://clomidhubpharmacy.com/# Clomid Hub
how can i get cheap clomid for sale: Clomid Hub — get clomid without a prescription
order corticosteroids without prescription: Relief Meds USA — prednisone 50 mg tablet cost
Relief Meds USA: Relief Meds USA — prednisone 20mg price
where can i buy fluoxetine NeuroRelief Rx NeuroRelief Rx
NeuroRelief Rx: gabapentin pt teaching — ketamine gabapentin clonidine
anti-inflammatory steroids online: order corticosteroids without prescription — ReliefMeds USA
low-cost antibiotics delivered in USA ClearMeds Direct antibiotic treatment online no Rx
Clomid Hub: how to buy cheap clomid prices — how to buy cheap clomid
https://wakemedsrx.com/# order Provigil without prescription
Relief Meds USA: anti-inflammatory steroids online — can you buy prednisone online uk