Ultrasonic Sensor HC-SR04 + Arduino Calculation? - c++

I'm using this code :
int trigPin = 7;
int echoPin = 8;
void setup() {
Serial.begin(9600);
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
}
void loop() {
int duration;
int distance;
digitalWrite(trigPin,HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin,LOW);
duration = pulseIn (echoPin,HIGH);
distance = (duration/2)/29.1;
Serial.print("distance = ");
Serial.println (distance);
delay(500);
}
I understand the concept that we send a pulse of 1000 µsec in this case and we wait for the reflected signal. But I don't understand how in this code, only the pulse width of the reflected signal is being used for the calculation.
I searched around and they say the reflected pulse width is proportional to the distance traveled. Can someone please explain how this happens (the physics behind it) and also where does the 29.1 comes from?
I read this documentation but I still don't understand the pulse width concept.
Many thanks in advance!

Like Chris touched on in the comments, the input pin goes HIGH for the time between it being send and received. I'm not exactly sure if it goes HIGH for a certain amount of time after or during the transmission, but you might be able to find that on a datasheet.
where does the 29.1 come from?
That's the speed of sound through air... you can use that to convert the time to centimeters. You'll have to divide it by two because it goes two ways.
Recap:
Arduino sends pulse to SR04 (1000 microseconds):
digitalWrite(trigPin,HIGH);, delayMicroseconds(1000);, &digitalWrite(trigPin,LOW);.
SR04 emits a ping and changes the signal pin to HIGH
The ping hits an object, bounces back, and goes back to the SR04
The SR04 sets the pin back to LOW
The Arduino measures the length the signal pin is HIGH with this:
duration = pulseIn (echoPin,HIGH);

Related

Can't update data through the Loop

I'm currently working on an EEG system using the Arduino. The purpose of the system is to vibrate a vibrator for .1 seconds, wait .5 seconds, and then vibrate again for .1 seconds. However from the start I want it to read the EEG (Serial.println(brain.readCSV()); Serial.println(brain.readErrors());) every .1 seconds from the start.
The problem is that it only takes one sample and just repeats it throughout the process until it cycles, instead of continuously updating through the loop.
How can I get it to continuously read the new data while the entire system is operating.
#include "Brain.h"
#include <SPI.h>
#include <Wire.h>
int n=0;
int m=0;
// Set up the brain parser, pass it the hardware serial object you want to listen on.
Brain brain(Serial);
int vib = 5;
void setup() {
// Start the hardware serial.
Serial.begin(9600);
pinMode(vib, OUTPUT);
}
void loop() {
// Expect packets about once per second.
// The .readCSV() function returns a string (well, char*) listing the most recent brain data, in the following format:
// "signal strength, attention, meditation, delta, theta, low alpha, high alpha, low beta, high beta, low gamma, high gamma"
if (brain.update()) {
Serial.println(brain.readCSV());
Serial.println(brain.readErrors());
if(brain.readSignalQuality() == 0) {
// Vibrate
digitalWrite(vib,HIGH);
Serial.println(brain.readCSV());
Serial.println(brain.readErrors());
delay(100);
while (n<500){
n=n+100;
digitalWrite(vib,LOW);
Serial.println(brain.readCSV());
Serial.println(brain.readErrors());
Serial.println(n);
delay(100);
}
digitalWrite(vib,HIGH);
Serial.println(brain.readCSV());
Serial.println(brain.readErrors());
delay(100);
while (m<10000){
m=m+100;
digitalWrite(vib,LOW);
Serial.println(brain.readCSV());
Serial.println(brain.readErrors());
Serial.println(m);
delay(100);
}
n=0;
m=0;
}
}
}
As Delta_G says in the comments, you need to be calling brain.update() each time you want new data. Looking at the source code for Brain.cpp, notice that "readErrors" just returns a variable that only changes after you run update() (and readCSV runs sprintf on a bunch of variables that also get updated in update()). This implies that readErrors and readCSV don't actually pull new data.

How to make DC motor's RPM come to its maximum value (analog 255) SLOWLY

It is a homework and I have completely NO idea, my teacher says you need just while, analogWrite and a counter. I have a DC motor, a transistor and a 9V battery.
I know my code does NOTHING, but just as example.
int analogPin = 3;
int count = 0;
void setup()
{
pinMode(analogPin, OUTPUT);
}
void loop() {
while(count<30){
analogWrite(analogPin , 255);
delay(20000);
count++;
}
}
You need to use counter value as your analogue output value:
void loop()
{
if( count < 256 )
{
analogWrite( analogPin, count ) ;
delay( 20000 );
count++ ;
}
}
Note that you do not need a while loop; the Arduino framework already calls loop() iteratively (the clue is in the name). However if your teacher thinks you need one and is expecting one, you may need to use one just for the marks. Alternatively discuss it with your teacher, and explain why it is unnecessary
In fact the delay too is arguably bad practice - it is unhelpful in applications where the loop() must do other things while controlling the motor. The following allows other code to run whilst controlling the motor:
unsigned long delay_start = 0 ;
void loop()
{
if( count < 256 &&
millis() - delay_start >= 20000ul )
{
analogWrite( analogPin, count ) ;
count++ ;
delay_start = millis() ;
}
// Do other stuff here
}
Because the loop() now never blocks on the delay() function, you can have code that does other things such as read switch inputs and it can react to them instantly, whereas as in your solution, such inputs could be ignored for up-to 20 seconds!
A typical DC motor will not start moving at very low values - you may want to start count somewhat higher than zero to account for the "dead-band". Analogue signals are also generally a poor way to drive a DC motor and varying speed; a PWM is generally a more efficient method, and will allow the motor to run at lower speeds. With an analogue signal at low levels (lower than for PWM), your motor will not move and will just get warm and drain your battery.
For test purposes, reduce the delay time; you don't want to sit there for an hour and 25 minutes just to find the code does not work! Set it to say 500ms, then start it, time how long it takes before the motor starts to move. If that is say 30 seconds, then yu know the motor starts to move when count is about 60; in which case that is a better starting value that zero. Then you can increase your delay back to 20 seconds if you wish - though a DC power supply might be better than a battery - I'm not sure it will last that long.

Arduino Measuring PWM with attachInterrupt()

Can someone explain the flow of this Arduino program shown below?
volatile int pwm_value = 0;
volatile int prev_time = 0;
void setup() {
Serial.begin(115200);
// when pin D2 goes high, call the rising function
attachInterrupt(0, rising, RISING);
}
void loop() { }
void rising() {
attachInterrupt(0, falling, FALLING);
prev_time = micros();
}
void falling() {
attachInterrupt(0, rising, RISING);
pwm_value = micros()-prev_time;
Serial.println(pwm_value);
I understand that PWM means looking for the length of time the signal remains high for each cycle.
In void setup(), the first rising edge of the signal will trigger the void rising(). So during void rising() the signal is at HIGH and prev_time = micros() is measuring the time of the signal at high (pulse width) right?
Then once the falling edge of the signal comes in, the attachInterrupt() function in void rising() will trigger void falling(). At this point the signal is at LOW, so micros() in void falling() is measuring the time of the signal at low? Then that will make no sense to take pwm_value = micros()-prev_time.
This will only make sense if prev_time is the measurement of the signal at LOW and micros() is the measurement of the period of the signal. Then pwm_value = micros()-prev_time is correct.
Based on my explanation, please explain to me what I am not getting.
This code will wait for a rising edge. Once the signal goes high it will store the current time in prev_time and start waiting for the signal to drop low. Once a falling edge is detected it will print the difference between prev_time and the current time which is your on-time in microseconds.
pwm_value is a misleading name. This is just a time measurement which is not related to PWM per se. PWM values are usually duty cycles. The on-time alone does not give you any information in terms of PWM. You further need the off-time or the total time to know the duty cycle.
As cleblanc mentioned in his comment using serial prints in an ISR is not very good.

Arduino interrupt frequency

I am using an Arduino uno to measure the speed of a dc motor.
I have a opto sensor that gives a pulse when the motor has made a full turn.
The problem I've got starts when the motor has a speed > 90Hz.
As soon as I reach 90Hz, the Arduino doesn't enter the interrupt function.
My code:
int pin = 13;
volatile int state = LOW;
volatile unsigned long startTijd = 0;
volatile unsigned long eindTijd = 0;
unsigned int frequentie = 0;
volatile int count = 0;
void setup()
{
pinMode(pin, OUTPUT);
attachInterrupt(0, blink, FALLING); //LOW, HIGH, FALLING, RISING, CHANGE
Serial.begin(19200);
}
void loop()
{
noInterrupts();
digitalWrite(pin, state);
interrupts();
}
void blink()
{
if (count == 0) {
startTijd = micros();
}
count++;
if (count == 31) {
count = 0;
eindTijd = micros();
eindTijd -= startTijd;
Serial.print(eindTijd);
Serial.print(" ms. - ");
frequentie = 30 * 1000000 / eindTijd;
Serial.print(frequentie);
Serial.println(" Hz.");
}
state = !state;
}
My question is : When the Arduino receives interrupts at 90Hz, it doesn't execute the code in the interrupt. When the motor goes below 90Hz after that, the code works again. What am I doing wrong ?
It looks as though blink is your ISR. If that's the case, you shouldn't be doing debug I/O within that routine for 2 reasons. The first is that you are calling a process that could block. The second is that ISRs should do their thing and finish (should be highly efficient). My guess is that if you remove the debug I/O from your ISR and pass info back to the interrupted task instead (safely, of course) you will be able to service interrupts at greater than 90 hz.
Just to add to #Bruce answer. You are using serial IO in the interrupt. Each time you are printing around 15-20 characters (depending on the values calculated). Each character is encoded by 8 bit data + 1 start bit + 1 stop bit = 10 bits. So, say 20*10=200 bits. The baud rate is 19200bps, so time required to transmit 200 bits is 200/19200 sec, or in terms of frequency 19200/200=96Hz. So this is the maximum frequency achievable for transmission of 20 characters, which is close to your measured 90Hz (take in account that I am not considering any time spacing overhead between the transmits).

Using 4 16bit timers for 400hz PWM

I'm dealing with arduino mega based quadcopter and trying to make PWM frequency for 4 motors - 400hz each. I've found an interesting solution where 4 ATmega2560 16bit timers are used to control 4 ESCs with PWM so it could reach 400hz frequency. 700 to 2000µs are normal pulse widths ESC are dealing with.
1sec/REFRESH_INTERVAL = 1/0.0025 = 400hz.
this is servo.h lib:
#define MIN_PULSE_WIDTH 700 // the shortest pulse sent to a servo
#define MAX_PULSE_WIDTH 2000 // the longest pulse sent to a servo
#define DEFAULT_PULSE_WIDTH 1000 // default pulse width when servo is attached
#define REFRESH_INTERVAL 2500 // minimum time to refresh servos in microseconds
#define SERVOS_PER_TIMER 1 // the maximum number of servos controlled by one timer
#define MAX_SERVOS (_Nbr_16timers * SERVOS_PER_TIMER)
The problem is to make it work each PWM should be controlled with 1 16bit timer. Otherwize, say, 2 escs on 1 timer would give 200hz. So all of 16bit timers are busy controlling 4 ESC but I still need to read input PPM from receiver. To do so I need at least one more 16bit timer which I don't have anymore. It's still one 8bit timer free bit it can only read 0..255 numbers while normal number escs operate with are 1000..2000 and stuff.
So what would happen if I'll use same 16bit timer for both pwm and ppm reading? Would it work? Would it decrease speed drastically? I have arduino working in pair with Raspberry Pi which controls data filtering, debugging, and stuff, is it better to move ppm reading to Raspberry?
To answer one of your questions:
So what would happen if I'll use same 16bit timer for both pwm and ppm
reading? Would it work?
Yes. When your pin change interrupt fires you may just read the current TCNT value to find out how long it has been since the last one. This will not in any way interfere with the timer's hardware PWM operation.
Would it decrease speed drastically?
No. PWM is done by dedicated hardware, software operations running at the same time will not affect its speed and neither will any ISRs you may have activated for the corresponding timer. Hence, you can let the timer generate the PWM as desired and still use it to a) read the current counter value from it and b) have an output compare and/or overflow ISR hooked to it to create a software-extended timer.
Edit in response to your comment:
Note that the actual value in the TCNT register is the current timer (tick) count at any moment, irrespective of whether PWM is active or not. Also, the Timer OVerflow interrupt (TOV) can be used in any mode. These two properties allow to make a software-extended timer for arbitrary other time measurement tasks via the following steps:
Install and activate a timer overflow interrupt for the timer/counter you want to use. In the ISR you basically just increment a (volatile!) global variable (timer1OvfCount for example), which effectively counts timer overflows and thus extends the actual timer range. The current absolute tick count can then be calculated as timer1OvfCount * topTimerValue + TCNTx.
When an event occurs, e.g a rising edge on one pin, in the handling routine (e.g. pin-change ISR) you read the current timer/couter (TCNT) value and timer1OvfCount and store these values in another global variable (e.g. startTimestamp), effectively starting your time measurement.
When the second event occurs, e.g. a falling edge on one pin, in the handling routine (e.g. pin-change ISR) you read the current timer/couter (TCNT) value and timer1OvfCount. Now you have the timestamp of the start of the signal in startTimestamp and the timestamp of the end of the signal in another variable. The difference between these two timestamps is exactly the duration of the pulse you're after.
Two points to consider though:
When using phase-correct PWM modes the timer will alternate between counting up and down successively. This makes finding the actual number of ticks passed since the last TOV interrupt a little more complicated.
There may be a race condition between one piece of code first reading TCNT and then reading timer1OvfCount, and the TOV ISR. This can be countered by disabling interrupts, then reading TCNT, then reading timer1OvfCount, and then checking the TOV interrupt flag; if the flag is set, there's a pending, un-handled overflow interrupt -> enable interrupts and repeat.
However, I'm pretty sure there are a couple of library functions around to maintain software-extended timer/counters that do all the timer-handling for you.
what is unit of 700 and 2000?I guess usec.You have not exaplained much in your question but i identified that you need pulses of 25msec duration in which 700 usec on time may be 0 degree and 2000 may be for 180 degree now pulse input of each servo may be attached with any GPIO of AVR.and this GPIOs provide PWM signal to Servo.so i guess you can even control this all motors with only one timer.With this kind of code:
suppose you have a timer that genrate inturrupt at every 50 usec.
now if you want 700 usec for motor1,800 usec for motor 2,900 usec for motor 3 & 1000 usec for motor 4 then just do this:
#define CYCLE_PERIOD 500 // for 25 msec = 50 usec * 500
unsigned short motor1=14; // 700usec = 50x14
unsigned short motor2=16; // 800usec
unsigned short motor3=18; // 900usec
unsigned short motor4=20; // 1000usec
unsigned char motor1_high_flag=1;
unsigned char motor2_high_flag=1;
unsigned char motor3_high_flag=1;
unsigned char motor4_high_flag=1;
PA.0 = 1; // IO for motor1
PA.1 = 1; // IO for motor2
PA.2 = 1; // IO for motor3
PA.3 = 1; // IO for motor4
void timer_inturrupt_at_50usec()
{
motor1--;motor2--;motor3--;motor4--;
if(!motor1)
{
if(motor1_high_flag)
{
motor1_high_flag = 0;
PA.0 = 0;
motor1 = CYCLE_PERIOD - motor1;
}
if(!motor1_high_flag)
{
motor1_high_flag = 1;
PA.0 = 1;
motor1 = 14; // this one is dummy;if you want to change duty time update this in main
}
}
if(!motor2)
{
if(motor2_high_flag)
{
motor2_high_flag = 0;
PA.1 = 0;
motor2 = CYCLE_PERIOD - motor2;
}
if(!motor2_high_flag)
{
motor2_high_flag = 1;
PA.1 = 1;
motor2 = 16;
}
}
if(!motor3)
{
if(motor3_high_flag)
{
motor3_high_flag = 0;
PA.2 = 0;
motor3 = CYCLE_PERIOD - motor3;
}
if(!motor3_high_flag)
{
motor3_high_flag = 1;
PA.2 = 1;
motor3 = 18;
}
}
if(!motor4)
{
if(motor4_high_flag)
{
motor4_high_flag = 0;
PA.3 = 0;
motor4 = CYCLE_PERIOD - motor4;
}
if(!motor4_high_flag)
{
motor4_high_flag = 1;
PA.3 = 1;
motor4 = 19;
}
}
}
& tell me what is ESC?