cattledog:
There is another piece of code which sends the trigger signal and then reads the pulse coming back. You will need to post that in order for us to help with troubleshooting.
How do you know the coded you posted (which sends a pulse when receiving an input) does not work?
When I drive the posted sketch as written with this one on another Arduino, and connect pin2 to pin2, I see an expected pulse of 1000 microseconds come back every 5 seconds.
void setup()
{
Serial.begin(9600);
}
void loop()
{
pinMode(2,OUTPUT);
digitalWrite(2,HIGH);
delayMicroseconds(20);
digitalWrite(2,LOW);
pinMode(2,INPUT);
Serial.println(pulseIn(2,HIGH));
delay(5000);
}
Hi, the other piece of code is written with Labview and make use of a NI USB-6221 DAQ and has been tested with an oscilloscope, but it does pretty much the same function you wrote. I've got updates, not good by the way. First of all the pin must be set as INPUT in the setup() function, if not the trigger signal from the DAQ is distorted to 1 V and doesn't trigger the interrupt (of course it goes all in the arduino given the fact that there is almost no input resistance, no damage to the Arduino fortunately).
When the interrupt is triggered I toggle pinMode to OUTPUT, generate the output impulse, toggle back to INPUT before exiting the ISR. This sequence doesn't produce the expected results by the way. It gives a train of identical impulses (of the right width) and so I guess that the first response impulse triggers the interrupt a second time and so on. My guess is interrupts are not disabled during the ISR.
Then I played with the noInterrupt() and interrupts() functions which I placed inside the ISR but still I had a strange behaviour: this sequence produce two identical impulses of the right width, it seems like the ISR is called twice...
I can't figure out a predictable behaviour and I ask you if it could depend from my Arduino UNO which is rev 2, so a bit outdated...
I'm a bit confused now... Thank you all.
This is the latest code i wrote. Notice that moving the noInterrupts() and interrupts() function gives totally unpredictable behaviours...
int pin = 2;
int pulse_duration = 500;
void setup() {
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(pin),send_impulse, RISING);
pinMode(pin, INPUT);
Serial.println("Ready...");
}
void loop() {
}
void send_impulse(){
delayMicroseconds(200);
noInterrupts();
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);
interrupts();
delayMicroseconds(pulse_duration);
digitalWrite(pin,LOW);
pinMode(pin, INPUT);
delayMicroseconds(200);
Serial.println("Ciao interrupt!");
}