0

I'm working on a project part of it to have some reads with ultrasonic sensor and send it with serial communication, i wrote code and it gives random reads and sometimes gives 0 as a read, is the formula i used for finding distance right !?, or there is another formula, I'm using Atmega32 with internal 8MHz clock, can someone help me and know what's wrong with my code !?.

#define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

void inti_serial();

static volatile int pulse = 0;
static volatile int change = 0;

int main(void)
{ 

/* Replace with your application code */
inti_serial();

MCUCR |= (1 << ISC00); //Any logical change on INT0
GICR |= (1 << INT0); //Enable INT0

TCCR1A=0;
sei();

while (1) 
{
PORTC |= (1<<0);
_delay_us(15);
PORTC &= ~(1<<0);
while(!(UCSRA & (1<<UDRE)));
UDR = ((pulse/2)*1*(1/F_CPU)*343) ;
_delay_ms(100);
}
}

ISR(INT0_vect){


if (change==1)//when logic from HIGH to LOW

{

    TCCR1B=0;//disabling counter

    pulse=TCNT1;//count memory is updated to integer

    TCNT1=0;//resetting the counter memory

    change=0;

}

if (change==0)//when logic change from LOW to HIGH

{

    TCCR1B|=(1<<CS10);//enabling counter

    change=1;

}
}

void inti_serial()
{
 UCSRB |= (1<<TXEN);
 UCSRC |= (1<<UCSZ0) | (1<<UCSZ1) | (1<<URSEL);
 UBRRL = 0x33;
}
JimmyB
  • 12,101
  • 2
  • 28
  • 44
  • Possible duplicate of [Serialize Data Structures in C](https://stackoverflow.com/questions/371371/serialize-data-structures-in-c) – Gianluca Ghettini Oct 19 '17 at 14:59
  • 1
    @GianlucaGhettini This question has nothing to do with serialization but, remotely, with *serial communication*. – JimmyB Oct 19 '17 at 15:14

1 Answers1

1

I see a few options for improvement in your development:

  • You are writing a sample from the ISR to variable and you read it continuously from the main loop and output it. Instead you should only output a new sample once (makes the serial data much smaller and easier to concentrate on the actual content and sample timing)

  • Before you think about the correct formula you should verify that your sampling mechanism is right. Without details about your sensor, nobody here can judge your formula, anyway.

  • Instead of sampling a free running counter you could use the input capture circuit of the processor (more accurate, less jitter due to interrupt latency)

  • Instead of resetting the counter register to zero you could subtract two consecutive samples from each other (less sample jitter due to interrupt latency)

  • Instead of deducing the edge from a toggled flag, ask the hardware about the state of the pin or which edge triggered the interrupt (or the capture)

Stefan Bormann
  • 643
  • 7
  • 25