delayMicroseconds()内で、引数を左に2ビットシフトしているため、実質14ビットが有効なビット数となるからです。 また、引数のエラー処理をしていないことにも注意してください。If you need to generate a 1-minute time delay with Arduino, you can still use the delay() function. 5 nanoseconds". Currently, the largest value that will produce an accurate delay is 16383. A better way: micros() and a C++ Class. The TB6600 driver can handle a wide range of input voltages (from 9V to 42V) and can drive stepper motors with up to 4. 程序上是分别三. g. e. Let’s measure how long the digitalWrite call takes. There is no real advantage to use unsigned numbers, as they will also wrap around sooner or later. As our code works now, we have full speed forward, and variable speed backwards. As far as I can tell, you've been getting the code from there. functions. Viewed 4k times. Mon Jun 15, 2015 5:09 pm. 2. One is transmitter which outputs ultrasonic sound pulses and the other is receiver which listens for reflected waves. There are a thousand microseconds in a millisecond, and a million microseconds in a second. // Clears the trigPin digitalWrite (trigPin, LOW); delayMicroseconds (2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite (trigPin, HIGH); delayMicroseconds (10); "Clearing" here is in fact making sure you're sending no sound wave at all before starting to. Writes an analog value ( PWM wave) to a pin. Patch courtesy Jeremy Mortis. delayMicroseconds() ここはdelayMicroseconds() 関数のページです. Language delay() Language micros()非常に小さい遅延時間に対しては、delayMicroseconds()の精度は保障できない。大きい遅延時間を指定すると、実際には極端に短い遅延を生成するかもしれない。 Arduino 0018以降から、delayMicroseconds()は割り込み禁止にしない。 参照 オリジナル. Once you have it ironed on, place the copper board in an acid bath for 15 mins. Read up on the blink tutorials and PWM as this would apply to your pizeo. These functions rely on interrupts themself, so they won’t work while the processor handles your custom interrupt callback function. As a remark I repeat here what was said by @Unimportant in the comments:. monotonic_ns () You might also try time. 8 ms with java. (Actually, it reach near 10 microseconds!) The tips are: 1. Description. Digital Pins Usable For Interrupts. Learn more about Teams Check out the implementation of delayMicroseconds() /* Delay for the given number of microseconds. ต่อวงจรดังรูปMore knowledgeable programmers usually avoid the use of delay () for timing of events longer than 10’s of milliseconds unless the Arduino sketch is very simple. Also delayMicroseconds() is a possibility. Diese Funktion arbeitet im Bereich von 3 Mikrosekunden und mehr sehr genau. The delayMicroseconds() function pauses the program for the amount of time (in microseconds) specified as a parameter. In circuit connections Ultrasonic sensor module’s “trigger” and “echo” pins are directly connected to pin 18 (A4) and 19 (A5) of arduino. hashan_sudeera. The demo Several Things at a Time illustrates the use of millis() to manage timing without blocking. then connect vcc (positive) of sensor to the positive rail. Returns the number of microseconds since the Arduino board began running the current program. We are delaying here to make sure, that the HC. In short each button is attached to analog pins (A0,A1,A2. The primary issue that I see is that your code doesn't match your wiring diagram. delayMicroseconds (ุ1000); // หน่วงเวลา 1000us 13 ให้อัพโหลดโค้ดตัวอย่างข้างบนลงบอร์ด Arduino คำสั่ง delayMicroseconds จะหน่วงเวลา 1000 us หรือ 1000/1,000,000 วินาที ค่าจะวิ่ง. Hallo Leute, ich bräuchte mal Eure Hilfe. The second ISR would be connected to the Timer. 50uSec. I have some code running as a FreeRTOS task on my ESP32. No other interrupt service routines can run while this is happening. This is done with the help of the Servo library, which is pre-installed library in the Arduino IDE (both offline and online versions). You're spending a LOT more time doing the digitalWrites (and returning from and returning to loop()) than you are doing the delays. This could change in future Arduino releases. To do that, a little math is required. Arduino の delayMicroseconds () 関数を使用して、マイクロ秒単位で遅延を追加できます。. For example, consider we have to print some numbers on the serial. It can pause with an accuracy of 0. For ESP-IDF, you can use this:대신 delayMicroseconds() 함수를 사용하는 만큼 ISR 구문의 처리가 길어져 다른 인터럽트 (예를 들면 시리얼이라던지) 가 처리될 수 없기 때문에 좋지 않은 코드인 것은 마찬가지지만 우린 단지 LED 를. 3. e esp_timer_get_time() return a int64_t value and is parsed as uint32_t in delayMicroseconds(). I am worried however that delayMicroseconds() pauses the entire program and that I cannot perform other tasks in while the sensors are working (e. マイクロは10の-6乗なので、1,000マイクロ秒は1ミリ秒、1,000,000マイクロ秒は1秒となります。. //delay_us (us); // for the 16. However, this crashes my ESP32 every time. 155 microseconds per centimeter. I have an ADS1115 board. Pin. import time usleep = lambda x: time. Here is the code I currently have: //Tell the Arduino Ide to include the Servo. In this tutorial, you will learn how the sensor works and how to use it with Arduino. La aproximación es debida a la ejecución de las otras instrucciones en el código. This function works very accurately in the range 3 microseconds and up to 16383. delayMicroseconds 가 작은 지연시간동안 정확히 수행한다고 보장할 수 없다. 1 Answer. Two things: Steppers have a lot of mass in the rotor and thus high inertia. Có một nghìn micro giây trong một phần nghìn giây và một triệu micro giây trong một giây. If you need better resolution, you can use micros(). Wir können nicht garantieren, dass delayMicroseconds () genau für kürzere Verzögerungszeiten funktionieren. 5 ms (90°) to 2 ms (180°), followed by a pause that makes the total duration of a cycle 20 ms. 1. At the expense of more complicated programming the eight data lines as well as the Enable and Register Select lines may. 0 CH340/ATmega328P、Nano V3. So I changed delayMicroseconds(100) to delayMicroseconds(1000) which should be the same as delay(1) which didnt crash. Upload code and open your Serial Terminal, data will appear. Description. I have tried for a bit now, but it seems like it doesn't work. シリアルモニタに”. 0) usleep (100) #sleep during 100μs. targetDistance1 = targetDistance1 * 160934. 18 KB. The 20 ms correspond to a 50 Hz signal. Arduino에서 delayMicroseconds () 함수를 사용하여 마이크로초 단위로 지연을 추가할 수 있습니다. Hi all, I'm a new member. 1 or // 2 microseconds) gives delays longer than desired. This means that, by the time the function returns, startMicros will be very close to the current time. 0343 cm/μs = 1 / 0. The High Resolution Timer (ESP Timer) provided by FreeRTOS uses a 64 bit hardware timer. Larger delay times may actually delay for an extremely brief time. delayMicroseconds(1000); digitalWrite(trig , LOW); duration = pulseIn(echo , HIGH); For calculation the duration with the help of pulseln() function. Even a simple loop causes it to crash: ELF file SHA256: 0000000000000000 Backtrace: 0x4008860c:0x3ffbf8f0 0x40088889:0x3ffbf910. You can find the other interface types here. The function of delay() is in both cases correct. 아두이노 0018 현재, delayMicroseconds () 는 더이상 인터럽트를 비활성화 하지 않는다. Prescaler divides the Timer clock further, by the value that you input in the prescaler. (=> unsigned int scales with the. 9 delayMicroseconds (100); // Approximately 10% duty cycle @ 1KHz. cpp","contentType":"file"},{"name. Pauses the program for the amount of time (in microseconds) specified as parameter. Description. 1. Pin(pyb. If the object is not moving – the microcontroller will stop the motors (and, therefore, the robot) once the robot is 10 cm away from the object. Step 2: Connections. ***Before you do the following, be. Syntax – delay (ms) delay function takes only one argument, Which will be the amount of time we have to pause the code. Don’t use await any async operation inside of a code segment where you need precise timing. The delay () function uses the milliseconds interrupt. Serial communication that appears. and ground of the sensor to the negative rail. Sound travels at 343 meters per second, which means it needs 29. For delays longer than a few thousand. We cannot assure that delayMicroseconds will perform precisely for smaller delay-times. For example, consider we have to print some numbers on the serial monitor at a specific time interval. The circuit diagram for arduino and ultrasonic sensor is shown above to measure the distance. And for this reason, the prescaler value is 72. This could change in future Arduino releases. paste clipboard into write-window of a posting. delayMicroseconds() works in arduino. • Connect resistors with the positive terminal of this LED's. To get the 10us pulse width I needed to use 8us argument for delayMicroseconds function, but the actual problem is that randomly. 其实 delayMicroseconds 函数会判断传入时间如果小于100us就使用 delayMicrosecondsHard 占用式延时,否则会调用 nanosleep 函数。 如果我们想要精确延时,是可以使用 delayMicrosecondsHard 函数的,这个函数在. Currently, the largest value that will produce an accurate delay is 16383. setSpeed (20); // Change speed according to your needs, negative values let. delayMicroseconds() Description. low() echo = pyb. However, to answer your actual question, there is a more accurate alternative to delayMicroseconds (): the function _delay_us () from the AVR-libc is cycle-accurate and, for example. In addition, you have full control the duty cycle and frequency. 2.計量・重量センサを作り重さを取得するスケッチを描く. Blocking functions prevent a program from doing anything else until that particular task has completed. delayMicroseconds 가 작은 지연시간동안 정확히 수행한다고 보장할 수 없다. I'm doing a project where I have 2 ultrasonic sensors that will control led lights wherein if 1 sensor first detects a movement it will light up led1 while the other lights up led2 based on the distance of which one detects the nearest object first. So is there a way I can implement a delay…More knowledgeable programmers usually avoid the use of delay() for timing of events longer than 10's of milliseconds unless the Arduino sketch is very simple. Obviously, I need 25882 microseconds, which is above that limit. MicroTimer: A microsecond and millisecond timer in C# that is used in a similar way to the . Và cứ mỗi 1000000 micro giây = 1 giây. The Arduino programming language Reference, organized into Functions, Variable and Constant, and Structure keywords. Second line of the code is the problem. As a part of my project I need to generate 10 microseconds pulses with 10 milliseconds intervals. The Blue Pill where delayMicroseconds() runs twice as fast was bought from a random ebay dealer. print the result. Decreasing the delay time is straightforward, just lower the delayMicroseconds and the stepper motor will have an increased step rate. Ignore the loop for now, and focus on the digitalWrite line. The argument order is the same as for subtraction operator, ticks_diff(ticks1, ticks2) has the same meaning as ticks1-ticks2. We simply need to connect the control pin of the servo to any digital pin of the Arduino board, connect the Ground and the positive wires to the external 5V power supply, and also connect the Arduino ground to the servo ground. h) will allow you to busy-wait for a. このプログラムの中で「ESP32にdelayMicrosecondsがない」としてシステム時間の計算をして擬似的にμsのdelayを行なっていました。. You set your limit switch pin Lim1 as output, though to read a switch you need to configure it as input. Sonali_B. Ignore the loop for now, and focus on the digitalWrite line. 8inch to 157inch) with an accuracy of 0. The ATmega328P MCU of the UNO Board has hardware to genertae high frequency PWM signal using TCNT1 (Timer/Counter 1). 0:15. Stop thinking in microseconds, and think in "clock cycles" or "nanoseconds" instead. This could change in future Arduino releases. Precision of delayMicroseconds () Using Arduino Programming Questions. This function works very accurately in the range 3 microseconds and up to 16383. Here’s the code steps = 400 for (int s = 0; s < steps; s++){ digitalWrite( STEP_PIN, HIGH); delayMicroseconds (375);. When you read the datasheet of the HC-SR04 you will see that it needs a 10us trigger pulse. Description. My target is to run in a specific speed up to specific steps. If the pin is configured as an INPUT, digitalWrite () will enable ( HIGH) or disable ( LOW) the internal pullup on the input pin. */ void delayMicroseconds (unsigned int us) { // calling avrlib's delay_us () function with low values (e. And if you want to use a pullup resistor (in contrast to a pulldown resistor) you can activate the internal pullup in the same step: pinMode (Lim1, INPUT_PULLUP); When reading the limit switch inside the outer for loop you write. There are a thousand microseconds in a millisecond and a million. 0 Followers • 0 ProjectsHàm delayMicroseconds () chấp nhận một đối số số nguyên (hoặc số). delayMicroseconds () deaktiviert ab Arduino 0018 keine Interrupts mehr. delayMicroseconds () deaktiviert ab Arduino 0018 keine Interrupts mehr. 2 - Album on Imgur. 3同时连接到三个adc的对应引脚,然后用esp32的三个引脚作为片选,分别连接到ads1256的片选引脚,然后信号线上串联了一个100欧姆的牌组. 5 ms for neutral position. It travels to the object and then back to the sensor. RayLivingston March 22, 2017, 7:51pm 6. All without using the delayMicroseconds() function. by xhr0428 » Fri Aug 29, 2014 11:38 am. okey i'v secceded to opreate the motor,and also added some other function like changing direction and controling speed. Notice also that the delay loop is done in inline assembly, in order to be independent of compiler optimizations. During this process, the HC-SR04 will measure the time that it took the ultrasound to return. There are two ways you can control the speed of your stepper motor. png 800×480 37. Certain things do go on while the delay () function is controlling the Atmega chip, however, because the delay function does not disable interrupts. It's not advisable to make the tick period any shorter than 1ms. The main caveat is that the argument has to be a compile-time constant. To ensure correct sampling of the clock signal, the minimum low and high periods should be: Low period: longer than 2 CPU clock cycles. I was wondering what the difference between these two is, because it seems to me that they're the same. The HC-SR04 ultrasonic sensor works by emitting an ultrasound. Global variables use 28 bytes (1%) of dynamic memory. e. Certain things do go on while the delay () function is controlling the Atmega chip, however, because the delay function does not disable interrupts. 2 Answers. There are a thousand microseconds in a millisecond, and a million microseconds in a second. the overhead // of the function call yields a delay of approximately 1 1/8 us. I am trying to control a stepper motor's movements with a pressure sensor input (0 to 5 V digital). Serial communication that appears. Pauses the program for the amount of time (in microseconds) specified as parameter. The delay function seems to be based on system ticks so that the delay time can be used for other tasks. I would like to move 400 steps in one direction. X4) trigger. (Assuming you are using the NewPing 1. Second; Change the boards. And that was why I investigate this whole situation. 26. The servo library for the AVR uses timer interrupts to generate the. Country: Question Everything. THIS IS THE CODE FOR THE PROJECT. In this example, if the object is close to ultrasonic sensor then servo motor rotates to 90 to 180 degree. sleep (ms), or the even worse accuracy of 15 ms with pause (). 1000us는 1ms (밀리세컨드: millisecond)이며, 1000000 (백만)us는 1초입니다. h library. Use the BlinkWithoutDelay example in the IDE to make a micros() based timer. I have an ADS1115 board. If you need better resolution, you can use micros(). Pauses the program for the amount of time (in microseconds) specified as parameter. Assume the board is already enabled. So it is pretty obvious that you the variable trigPin multiple times. delayMicroseconds() works in arduino. Open the attached file “RGB board” in Eagle. In this tutorial, we will learn how to control a standard servo motor, to go back and forth across 180 degrees, using a. The TB6600 Stepper Motor Driver is a high-performance and cost-effective driver for bipolar stepper motors. Intensity of light (on LDR) ↓ - Resistance↑ - Voltage at analog pin↓ - Duty cycle (PWM)↑ - Brightness of Power LED. Step 2: BUILDING:-. . Download Console demo project (MicroTimerConsoleDemo. The Arduino programming language Reference, organized into Functions, Variable and Constant, and Structure keywords. GPIO number, or one of RPI_GPIO_P1_* from RPiGPIOPin. cmaglie removed the New label on Feb 27, 2014. The demo Several Things at a Time illustrates the use of millis() to manage timing without blocking. During this 10 µs the transmitter will cycle 8 bursts. Plenz September 19, 2015, 9:45am 1. {"payload":{"allShortcutsEnabled":false,"fileTree":{"cores/arduino":{"items":[{"name":"USB","path":"cores/arduino/USB","contentType":"directory"},{"name":"compact. delayMicroseconds가 더 작은 지연 시간에 대해 정확하게 수행된다는 것을 보장 할 수 없습니다. Bluetoothは、ESP32の標準ライブラリのBluetoothSerialを使用します。Bluetoothをシリアル接続して、シリアルモニタと同じような使い方で使用することができ. Não é possível assegurar que delayMicroseconds () irá funcionar corretamente para valores menores. Reported by Mark Dootson. Цена: US $0. Pin. 1ミリ秒以上. 4 CODE CREATED AND EDITED BY - AMEYA ANGADI 5 LAST EDITED ON - 02/05/2021 6 IF DISTANCE IS LESS THAN 20 CM. パラメータの単位はマイクロ秒です。. Advertencias. Here’s the circuit diagram for this example. Currently, the largest value that will produce an accurate delay is 16383. delaymicroseconds() does not use a timer. 매개변수에 지정된 시간 (마이크로 초)동안 프로그램을 멈춘다. Step 2: Servo to Arduino. g. In general, interrupts need to be processed as fast as possible to allow other interrupts to fire. For example, I want to run 20 rpm for 300 step (or 1. A 16x2 LCD is connected with arduino. In this project we gonna make an arduino radar with arduino IDE and processing , this project uses arduino , ultrasonic sensor and servo motor , the realtime analysis is done in the processing pde, after uploading the code this is a simple project which can be made within 2 hours simple and easy. Portable spectroscopic instruments are an interesting alternative for in-field and on-line measurements. Then we take our sample and add another delay of 40uS, this will. Try replacing the start of your code with this:1. The servo library is not compatible with the ATtiny85 so I had to write code from scratch. Arduino 0018부터 delayMicroseconds. The delayMicroseconds() function accepts a single integer (or number) argument. But I can't find the way how to delay microsecond in esp-idf. Hi, I just found out that delayMicroseconds() produces only at 8 MHz clock correct values. Rate me: 4. Another problem. For a more complete version that can handle various clock frequencies, see the delayMicroseconds() function from the Arduino AVR core. You do not want the reading of the incoming pulse to block your program execution. When the first pulse of the 40 kHz bounces in the object and gets back to the receiver, the echopin sets itself in LOW. This could change in future Arduino releases. , MS1, MS2 & MS3. 3V on 3. board. 3ms, so I changed the register setting for data rate and used delayMicroseconds () function instead of delay () for delay. 설명. In SPI Slave mode, the control logic will sample the incoming signal of the SCK pin. Just like delay () has a microsecond-version called delayMicroseconds (), millis () has micros (). note that it should be of 5v only otherwise it may harm the sensor. This time can then be used to determine the distance to. If the ISR is getting executed during your measurement, then the execution time of the ISR will. Hey guys! I have been working with ultrasonic sensors for a while but never encountered anything like this but, now a days am facing one problem ,my ultrasonic sensor is not giving me correct readings. 이 함수는 3 마이크로 초 이상 범위에서 매우 정확하게 돌아간다. Check the board every few minutes. But for some reason Timer0 is being disabled, and can't use the delay(), millis() and delayMicroseconds(). パラメータの単位はマイクロ秒です。. For example, your diagram shows Trig connected to pin 4. Step 2. 3V boards) for HIGH, 0V (ground) for LOW. Project description. There are a thousand microseconds in a millisecond, and a million microseconds in a second. Step 3: Write Your Code. We cannot assure that delayMicroseconds will perform precisely for smaller delay-times. Control Input Pins: STEP & DIR are the 2 control input pins. The SR04 sets the pin back to LOW. BUT. 4 KB. This diagram might help:The first step is to include the library with #include . _delay_us (1. 맞습니다. You might need to check the Arduino Mega/ATmega2560 product description and SPI slave mode. 아두이노 0018 현재, delayMicroseconds() 는 더이상 인터럽트를 비활성화 하지 않는다. A partir da versão Arduino 0018, delayMicroseconds () não mais desativa interrupções. This means that we can control the stepper motor with just 2 pins from our controller,. Sonali_B Sonali_B. August 15, 2022. . Is there a library function for the Keil Compiler for the Silabs EFM8 to provide a timer. I would love them to run concurrently but it didn't work as planned when I upload. First of all, set the clock source as internal clock. You can find the other interface types here. Essa função funciona bastante precisamente para valores maiores que 3 microssegundos. Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. running a very short program on a mega, just to generate a 8 microsecond wide clock pulse on pin 18, every 250 microseconds- closest 'delay' values I can get are delayMicroseconds(3), and (83) off, gives a 7. I was using a separate Arduino Micro and a simplest code with delayMicroseconds() and delay() functions. The rotation returns to normal. Anmerkungen und Warnungen. #define trigPin 2. So something along the lines of: stepper1. And to move it to the other direction when its LOW i. Chances are that using a delay function inside an interrupt service routine wouldn't even work, because that function could. 1. 1 or // 2 microseconds) gives delays longer than desired. This module is a little bit tricky in order to learn the way of working of pulseIn. We used the delay () function to add a delay in the code to see the output in the code. The timer setup is documented in wiring. loveday. There are a thousand microseconds in a millisecond, and a million microseconds in a second. To change a pin after 10µs, you could start a timer. Certain things do go on while the delay () function is controlling the Atmega chip, however, because the delay function does not disable interrupts. We do this for 10 µs (microseconds). Thread. 1.ロードセル(SC133)とADコンバータ(HX711)の使い方を学習する. 28ms. I have included 5 examples with a wiring diagram and code so you can start. SR04 emits a ping and changes the signal pin to HIGH. #include <AccelStepper. But, be aware that micros() will overflow about every 70 minutes, and millis() about 50 days. 1. It is widely used in various applications, including CNC machines, 3D printers, robotics, and more. The timer setup is documented in wiring. Pauses the program for the amount of time (in microseconds) specified by the parameter. h> //Setup the variables for the HC-SR04 const int trigPin = 11; const int echoPin = 12; // create servo object to control a servo // a maximum of eight servo objects can be created Servo myservo; // variable to store the servo position int. The delay time should be around 1. So, try this first and compare it to what I have done below: import time time_ns = time. I'm messing around with the following code: #define cyclespermicro 240 #define microcycles (n) (n*cyclespermicro) uint32_t startCounter, counter, cpu_cycles; int. This guide also includes a comparison of vTaskDelay () function provided by FreeRTOS with different delay values in milliseconds. Basically, I found out that delayMicroseconds(x) delays (on Arduino UNO, 16MHz) 7 Clock cycles for (x = 0, 1) 14 Clock cycles Short for (x >= 2) I noticed a too quick delay on 'x = 2' case. g. If the object is moving – the robot moves forward and follows the object. マイクロは10の-6乗なので、1,000マイクロ秒は1ミリ秒、1,000,000マイクロ秒は1秒となります。. When an interrupt is received during the execution of the delayMicroseconds(), the timing of delayMicroseconds() will be wrong. Pauses the program for the amount of time (in microseconds) specified as parameter. There are three steps to taking a time measurement: 1. We cannot assure that delayMicroseconds will perform precisely for smaller delay-times. Compilation error: 'distance' was not declared in this scope. 1 cm = 0,393701 in. delayMicroseconds(50); } } //WANT CODE TO STOP CODE ANYTIME I PRESS STOP BUTTON } arduino-mega; interrupt; code-review; Share. Tegangan operasional 5 Vdc. Which can be used to create a time base for various events in your applications (like LED blinking, short pulse generation, or whatever). delayMicroseconds(tiempo); Parámetros tiempo el lapso (en microsegundos) en el que el programa se detiene (unsigned int). But, be aware that micros() will overflow about every 70 minutes, and millis() about 50 days. zip) - 8. This could change in future Arduino releases. Learn how to use the delayMicroseconds () function to pause the program for a certain number of microseconds in Arduino code. 21 delayMicroseconds is now not susceptible to 32 bit timer overruns. Стерео радиоприёмник Rda5807m + Attiny13a ценой меньше 1$. For a more complete version that can handle various clock frequencies, see the delayMicroseconds() function from the Arduino AVR core. exit status 1 'microsecondsToCentimeters' was not declared in this scope. */ void delayMicroseconds(unsigned int us) { // call = 4 cycles + 2 to 4 cycles to init us(2 for constant delay, 4 for variable) // calling avrlib's delay_us() function with low values (e. and echo pin to digital pin 9. You can request the current time using millis (), for example, but the value returned by. It should look something like this once you have it ironed on. delayMicroseconds(ระยะเวลาที่ต้องการหน่วงมีหน่วยเป็นไมโครวินาที : µs หรือ 1/1000000 วินาที) เปิดตัวอย่างซอร์สโค้ด . 0 Licenseの下でライセンスされています. delay 가. . 无. It took 1060 microseconds to execute the lines of code before the micros () function. There are a thousand microseconds in a millisecond, and a million microseconds in a second. In your example there are two macro definitions with the same name as the following const int declarations: #define ECHOPIN 10 #define TRIGPIN 9 const int TRIGPIN = 9; const int ECHOPIN = 10; The preprocessor will substitute every. So is timer 2 responsible for the delay() and delaymicroseconds() on mega? No, Timer0 is used on the mega for millis() and micros().