- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
秋月で買ってきた超音波センサ (HC-SR04)
http://akizukidenshi.com/catalog/g/gM-11009/
のサンプルを TSoC (CY8C4146LQI-S433) 基板に移植してみました。
(以前のスレッド)
https://community.cypress.com/thread/35411
丁度、TSoC もブレッドボードに乗っていたので、HC-SR04 を隣に乗せて4本ジャンパを増やすだけでハードウェアの準備は完了でした。
ソフトウェアの方も、UART と Trigger, Echo のピン設定をするだけで main.c は無変更で動いてくれました。(互換性って、素敵だ・・・)
実際、測定をして見ますと、写真のおじぞうさんのような小さなオブジェクトですと
距離が測定毎にばらつきましたが、本などのようにある程度の大きさの面であれば
とても安定した値が表示されていました。
下記の TeraTerm ログはセンサーから 20cm 程度の距離に雑誌(トラ技)を置いて測定したものです。
Pins
main.c
=====================
/* ========================================
* HC-SR04 test program for CQ TSoC Board
* UART RX : P1[0]
* UART TX : P1[1]
* Echo : P0[0]
* Trigger : P0[1]
* ========================================
*/
#include "project.h"
#include <stdio.h>
/* https://keisan.casio.jp/exec/system/1231998943 */
#define MACH 346.513 /* Mach 1.0 at 25.0 */
char str[128] ; /* print buffer */
void init_hardware(void)
{
CyGlobalIntEnable; /* Enable global interrupts. */
Clock_12MHz_Start() ;
UART_Start() ;
Timer_Start() ;
}
/**
* pulse_trigger
* Generate 10us high pulse from trigger pin
*/
void pulse_trigger(void)
{
Trigger_Write(1) ;
CyDelayUs(10) ;
Trigger_Write(0) ;
}
/**
* measure_echo
* Measure high pulse width of echo pin
*/
uint32_t measure_echo(void)
{
uint32_t length ;
#if 0
while(Echo_Read() == 0) ;
Timer_WriteCounter(0) ;
while(Echo_Read() != 0) ;
length = Timer_ReadCounter() ;
return( length ) ;
#else
Timer_Stop() ;
Timer_WriteCounter(0) ;
while(Echo_Read() == 0) ;
Timer_Start() ;
while(Echo_Read() != 0) ;
Timer_Stop() ;
length = Timer_ReadCounter() ;
return( length ) ;
#endif
}
/**
* print_value
* Calculate distance from the duration
* Since the duration include both way of the trip
* to get the distance, the real duration is the half
* of the duration.
*
* distance = duration * MACH(m/s) * 100(cm) / (2 * 12000000(Hz)) ;
*
*/
void print_value(uint32_t duration)
{
double distance = 0.0 ;
distance = (double)(duration) * MACH / 240000.0 ;
sprintf(str, "%d.%02dcm\n", (int)distance, (int)(100 * distance)%100) ;
UART_UartPutString(str) ;
}
int main(void)
{
uint32_t duration ;
init_hardware() ;
for(;;) {
pulse_trigger() ;
duration = measure_echo() ;
print_value(duration) ;
CyDelay(1000) ;
}
}
/* [] END OF FILE */
=====================
moto
- Labels:
-
PSoC 345 LP