Shop OBEX P1 Docs P2 Docs Learn Events
PWM Counter — Parallax Forums

PWM Counter

hylee101001hylee101001 Posts: 48
edited 2016-02-04 03:28 in Propeller 1
Hi. I'm trying to count pwm for a distance sensor. The sensor outputs pwm that is 1 micro sec for 1 mili meter. So if 300 micro sec high, it means 300 mm. Data sheet:(http://www.maxbotix.com/Ultrasonic_Sensors/High_Resolution_Sensors.htm)

So I got a code as below. And around 70cm the value goes to 60cm as I move the sensor further. And then the value increases again. Yet, I have tested the sensor with arduino pulsein() and the sensor output looked correct. So I wondered if there's any glitch in my code. I'd like to ask a little bit of help on my code to check for possible error.

Thanks!
CON
  _clkmode = xtal1 + pll16x     
  _xinfreq = 5_000_000

VAR
  long  stack[128], ping, gctra, counter, dist
   
OBJ
  uart : "FullDuplexSerial.spin"
  
PUB main

  uart.quickStart
                       
  cognew(report, @stack) 

  dira[8] := 0
  
  ctra := %01000_000  << 23 + SIGNAL 'Establish mode and APIN (BPIN is ignored)
  frqa := 1
  dira[8]~

  gctra := ctra

  repeat
    if (counter := phsa) ' if pin is high and, obviously, phsa is not 0
      if counter == phsa  ' if pin is low(phsa stopped increasing)
        ping := phsa ~    ' update ping and clear phsa


PUB report | temp

  repeat
    uart.clear
    temp := ping
    temp := temp / 80 ' milimeter
    dist := dist*70/100 + temp*30/100
    uart.dec(dist/10)
    uart.str(string("."))
    uart.dec(dist//10)
    uart.strln(string(" cm"))     
    waitcnt(cnt + clkfreq/10)

Comments

  • JonnyMacJonnyMac Posts: 9,105
    edited 2016-02-04 04:38
    What you may want to do is create a generic pulse_in() method that will return the pulse width in microseconds -- something like this:
    pub pulse_in(pin) | mask
    
      mask := 1 << pin                                              ' mask for pin
    
      frqa := 1                                                     ' set for high-resolution measurement
    
      ctra := (%01000 << 26) | pin                                  ' set ctra to POS detect on pin   
      waitpne(mask, mask, 0)                                        ' wait for pin to be low
      phsa := 0                                                     ' clear accumulator
      waitpeq(mask, mask, 0)                                        ' wait for pin to go high
      waitpne(mask, mask, 0)                                        ' wait for pin to return low
    
      return phsa / (clkfreq / 100_000)                             ' convert ticks to us
    
  • Thanks, that works much better.
Sign In or Register to comment.