Author Topic: Interfacing parallax ping with ATMEGA, programming in C  (Read 3693 times)

0 Members and 1 Guest are viewing this topic.

Offline Kdog44Topic starter

  • Contributor
  • Posts: 39
Interfacing parallax ping with ATMEGA, programming in C
« on: August 28, 2014, 05:34:13 am »
hello,

I am relatively new to programming the ATMEGA328 in C. My knowledge is shady when it comes to utilizing the counter/timing registers with the mcu. I am trying to interface the parallax ping ultrasonic sensor with the ATMEGA328 chip.

http://www.parallax.com/sites/default/files/downloads/28015-PING-Documentation-v1.6.pdf

To communicate with the sensor I need to send a 5us pulse to the sig pin, then wait 750us and then listen for the signal pulse. The length of the signal pulse is related to how far away the object is.

I started implementing the algorithm to do this with the help of: http://pomprocker.blogspot.ca/2009/01/adding-parallax-ping-to-avr-using-c.html

here is my code:
note that the sig pin on the ping is connected to PB1 and a led is connect to PB0
Code: [Select]

void ping(void)
{

DDRB |= (1 << PB1);
PORTB |= (1 << PB1) | (1 << PB0);
_delay_us(5);
PORTB |= (0 << PB1);
DDRB |= (0 << PB1);
TCCR1B |= (1 << CS10); // No clk prescaling
loop_until_bit_is_set(PINB, PB1);
TCNT1 = 0;
loop_until_bit_is_clear(PINB,PB1);
time = TCNT1;
if( TCNT1 < 1000)
{
PORTB |= (1<<PB0);
}
}

void main(void)
{
{
ping();
_delay_ms(200);
}
}


Is there a better way of doing this? my code is really messy and doesn't seem to work. Basically I was trying to light an LED when an object was detected about a couple of cm away from the sensor. Where did I make a mistake?

thanks in advance
 

Offline AndreasF

  • Frequent Contributor
  • **
  • Posts: 251
  • Country: gb
    • mind-dump.net
Re: Interfacing parallax ping with ATMEGA, programming in C
« Reply #1 on: August 28, 2014, 06:18:17 am »
Quote
Code: [Select]
PORTB |= (0 << PB1);
DDRB |= (0 << PB1);

This is not how you clear bits. You probably want ...
Code: [Select]
PORTB &= ~(1 << PB1);
DDRB &= ~(1 << PB1);
my random ramblings mind-dump.net
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf