삼성 아틱 HC-SR04 초음파 거리센서 사용하기

메이커 2018-09-11 (화) 09:23 6년전 3986  

HC-SR04 초음파 거리센서 사용하기


본 튜토리얼의 전체 PDF는 다음의 링크에서 참고하실 수 있습니다. 

 

https://goo.gl/JVMp9q 


아두이노 IDE 사용시

1.    OTG, Debug 케이블 연결 후

2.    VCC – 5V / GND – GND / Trig – GPIO0 / Echo – GPIO1

3.    Putty 접속 후, 터미널에서 /root/watcher 입력

4.    아두이노에서 삼성 아틱의 COM포트 설정

5.    소스코드 업로드

#include <DebugSerial.h>

const int trigPin = 2;

const int echoPin = 3;

 

// defines variables

long duration;

int distance;

void setup() {

pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output

pinMode(echoPin, INPUT); // Sets the echoPin as an Input

DebugSerial.begin(115200); // Starts the Dustserial communication

}

void loop() {

// Clears the trigPin

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds

digitalWrite(trigPin, HIGH);

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds

duration = pulseIn(echoPin, HIGH);

// Calculating the distance

distance= duration*0.034/2;

// Prints the distance on the Serial Monitor

DebugSerial.print("Distance: ");

DebugSerial.println(distance);

}

 

6.    Putty로 모니터링

1f7c3ee5d7e718d5cf0b1a77c77892dc_1536645
 

 

파이썬 코드

nano hcsr04.py로 파일을 만들고, 다음의 소스코드를 붙여 넣습니다.


 import time

 

OUTPUT = 1

INPUT = 0

HIGH = 1

LOW = 0

TIMEOUT = 60000

 

uS = 1e-6

 

def reg(pin):

    try:

        exp = open('/sys/class/gpio/export','wb',0)

        exp.write(str(pin))

        print('Registion Successful: pin%d' %pin)

        #exp.close()

    except IOError as e:

        #print('Registion Error: pin%d' %pin)

        print('Error: %d - %s' %(e.errno,e.strerror))

 

def unreg(pin):

    try:

        uexp = open('/sys/class/gpio/unexport','wb',0)

        uexp.write(str(pin))

        print('Unregistion Successful: pin%d' %pin)

        uexp.close()

    except IOError as e:

        #print('Unregistion Error: pin%d' %pin)

        print('Error: %d - %s' %(e.errno,e.strerror))

 

def pinMode(pin, mode):

    try:

        direction = open('/sys/class/gpio/gpio%d/direction' %pin,'wb',0)

        direction.write('out' if mode == OUTPUT else 'in')

        #print('pin%d setted at %s' %(pin,'out' if mode == OUTPUT else 'in'))

        direction.close()

    except IOError as e:

        #print('CANNOT SET PIN MODE: pin%d' %pin)

        print('Error: %d - %s' %(e.errno,e.strerror))

 

def digitalWrite(pin,value):

    try:

        val = open('/sys/class/gpio/gpio%d/value' %pin,'wb',0)

        val.write(str(value))

        val.close()

    except IOError as e:

        #print('WRITE ERROR: pin%d' %pin)

        print('Error: %d - %s' %(e.errno,e.strerror))

 

def digitalRead(pin):

    try:

        file = open('/sys/class/gpio/gpio%d/value' %pin,'rb',0)

        value = file.read()

        file.close()

        return int(value)

    except IOError as e:

        #print('READ ERROR')

        print('Error: %d - %s' %(e.errno,e.strerror))

        return 0

 

def analogRead(pin):

    filePath = '/sys/devices/platform/c0000000.soc/c0053000.adc/iio:device0/in_voltage%d_raw' %pin

    print(filePath)

    try:

        file = open(filePath,"rb",0)

        value = file.read()

        file.close()

        return int(value)

    except IOError as e:

        print('Error: %d - %s' %(e.errno, e.strerror))

        return 0

 

def pulseIn(pin,state,timeout=1000000L):

    #Wait for any previous pulse to stop

    while (digitalRead(pin) == state):

        print(timeout)

        if (timeout == 0): 

            print('PULSE TIMEOUT')

            return 0

        #time.sleep(uS)

        timeout -= 1

 

    #Wait for next pulse to start

    while (digitalRead(pin) != state):

        if (timeout==0): 

            print('PULSE TIMEOUT')

            return 0

        #time.sleep(uS)

        timeout -= 1

 

    #Initialize TIMER

    Timer = time.time()

 

    #Measuring current pulse

    while (digitalRead(pin) == state):

        if (timeout==0): 

            print('PULSE TIMEOUT')

            return 0

        #time.sleep(uS)

        timeout -= 1

 

    return (time.time() - Timer) * 1000000

 

 

#ULTRASONIC SENSOR

trig = 128 # ARTIK 710의 GPIO 0번

echo = 129 # ARTIK 710의 GPIO 1번

 

reg(trig)

reg(echo)

 

pinMode(trig,OUTPUT)

pinMode(echo,INPUT)

 

try:

    while True:

        digitalWrite(trig,LOW)

        time.sleep(20 * uS)

        digitalWrite(trig,HIGH)

        time.sleep(1 * uS)

        digitalWrite(trig,LOW)

        

        duration = pulseIn(echo,HIGH)

        distance = duration/2/29.412

 

        print('Duration: %d - Distance: %0.2f' %(duration,distance))

 

        time.sleep(0.5)

except KeyboardInterrupt:

    unreg(trig)

    unreg(echo)




실행하기 위해 python hcsr04.py

 

1f7c3ee5d7e718d5cf0b1a77c77892dc_1536645
 

 
메카리워즈 Image Map


모바일 버전으로 보기