Hello! I have built my own code to interfacing ultrasonic(HC-SR04) sensor with Arduino/Genuino UNO board. It give correct reading at or below 9600 baud rate but when I change the baud rate above 9600 it goes crazy and the values come uneven.
Here's the code
sketch_dec21a
#include "US.h"
#include <SoftwareSerial.h>
uint16_t distance;
char gbuf[50];
int count;
void setup() {
// put your setup code here, to run once:
Serial.begin(38400);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// send an intro:
("UART Initialize");
Serial.println();
HC_SR04_Inti();
}
void loop() {
// put your main code here, to run repeatedly:
distance = HC_SR04_fun();
sprintf(gbuf, "%d cm \r\n", distance);
//Serial.println("HELLO\r\n");
Serial.print(gbuf);
}
US.h
#ifndef __US_H_
#define __US_H_
/*
* US_HC_SR04.c
*
* Created: 12/19/2016 11:38:57 AM
* Author: Utpal
* MCU: ATmega328
*/
#include <Arduino.h>
#include <util/delay.h>
#include <avr/interrupt.h>
static volatile uint16_t pulse = 0;
static volatile int ext_Int_count = 0;
void HC_SR04_Inti(void)
{
DDRD |= 0b11111011;
DDRD &= 0b11111011;
_delay_ms(50);
EIMSK &= (1 << INT0);
EICRA |= (1 << ISC00);
EIFR |= (1 << INTF0);
EIMSK |= (1 << INT0);
TCCR1A = 0; //Timer1 normal mode
sei(); //Enable Global Interrupt
Serial.println("HC_SR04_Inti\r\n");
}
int16_t HC_SR04_fun(void)
{
static uint16_t SR04_range = 0, avgSR04_range = 0; //Distance in cm
int16_t SR04_Read_count = 0;
for(SR04_Read_count = 0; SR04_Read_count < 10; SR04_Read_count++)
{
PORTD |= (1 << PIND3); //trigger
_delay_us(25);
PORTD &= ~(1 << PIND3);
SR04_range = pulse;
SR04_range /= 116;
//SR04_range /= 58;
avgSR04_range += SR04_range;
if(SR04_range <= 2){
avgSR04_range = 0;
return -1; //Minimum Range
}
if(SR04_range >= 350){
avgSR04_range = 0;
return -2; //Maximum Range
}
}
avgSR04_range /= 10;
return avgSR04_range;
}
ISR(INT0_vect)
{
if (ext_Int_count == 1)
{
TCCR1B = 0; //TurnOff Timer1
pulse = TCNT1;
TCNT1 = 0;
ext_Int_count = 0;
}
if (ext_Int_count == 0)
{
//TCCR1B |= (1 << CS10) | (1 << CS11); //TurnON Timer1 Clk/8 prescaler(CLK is 16MHz).
TCCR1B |= (1 << CS11); //TurnON Timer1 Clk/8 prescaler(CLK is 16MHz).
ext_Int_count = 1;
}
}
#endif
Here are readings at or below 9600 baud rate
112cm
116cm
117cm
117cm
116cm
116cm
116cm
117cm
116cm
116cm
116cm
116cm
116cm
116cm
These are readings above 9600 baud rate(at this time it's 38400 baud rate)
15 cm
117 cm
42 cm
35 cm
99 cm
24 cm
17 cm
16 cm
118 cm
37 cm
29 cm
102 cm
21 cm
13 cm
60 cm
14 cm
9 cm
8 cm
107 cm
Don't know what's wrong with my code.
Thank´s for help in advance and greetings
Utpal