I have a simple code with delays.
I'd like to know how to convert this code to millis? Is there a function to do so?
long revers = 1000;
void setup() {
pinMode(D1, OUTPUT);
pinMode(D2, OUTPUT);
}
void loop() {
digitalWrite(D1, LOW);
delay(revers);
digitalWrite(D2, HIGH);
delay(revers);
digitalWrite(D2, LOW);
delay(revers);
digitalWrite(D1, HIGH);
delay(revers);
}
The basic concept is this: record the millis() at a given moment in a variable - say 'starttime'. Now, during every loop(), check the time that has elapsed by subtracting millis() from 'starttime'. If the elapsed time is greater than the delaytime you set, execute code. Reset the starttime to create a repeating pattern.
That may be too short of an explanation for you, so before you dive into the code, I highly advise you to read this introduction about using millis() for timing. It's lengthy, but it explains the principle extensively. This will help you understand the code below.
Lastly, there are several libraries written to make the use of timing easier. For instance the SimpleTimer-library, but you can google "arduino timer library" for others. I've included an example below.
1 second on, 3 seconds off:
unsigned long startMillis; //some global variables available anywhere in the program
unsigned long currentMillis;
const unsigned long period = 1000; //the value is a number of milliseconds
int fase; //value used to determine what action to perform
void setup() {
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
startMillis = millis(); //initial start time
fase = 0;
}
void loop() {
currentMillis = millis(); //get the current "time" (actually the number of milliseconds since the program started)
if (currentMillis - startMillis >= period) //test whether the period has elapsed
{
if (fase == 0)
{
digitalWrite(8, LOW);
startMillis = currentMillis; //IMPORTANT to save the start time of the current LED state.
fase = 1; //increment fase, so next action will be different
}
else if (fase == 1)
{
digitalWrite(7, HIGH);
startMillis = currentMillis;
fase = 2;
}
else if (fase == 2)
{
digitalWrite(7, LOW);
startMillis = currentMillis;
fase = 3;
}
else if (fase == 3)
{
digitalWrite(8, HIGH);
fase = 0;
startMillis = currentMillis;
}
}
}
Example of a flashing led using the SimpleTimer library
#include <SimpleTimer.h>
// the timer object
SimpleTimer timer;
int ledPin = 13;
// a function to be executed periodically
void repeatMe() {
digitalWrite(ledPin, !digitalRead(ledPin));
}
void setup() {
pinMode(ledPin, OUTPUT);
timer.setInterval(1000, repeatMe);
}
void loop() {
timer.run();
}
Related
I am trying to send data from an accelerometer to Java from an Arduino. I am using delta time to limit it to sending only every 250 ms.
The problem is that all the Java program is reading is the first message sent in the setup() over and over.
I added a test Serial.write to check if the program is ever entering the delta time block, and it seems to be sending (or at least, reading) the first 2 characters of that message. The Arduino code is below.
#include <SparkFun_MMA8452Q.h>
int sleepPin = 7;
int stepPin = 6;
int buttonPin = 8;
int stepCount = 0;
boolean stepMode = true;
int delTime = 5000;
MMA8452Q accel; //accelerometer
void setup() {
Serial.begin(9600);
while (millis() < 4000); //wait so I can start java program
Serial.write("Connected");
//set pins
pinMode(sleepPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(buttonPin, INPUT);
digitalWrite(stepPin, HIGH); //starts in step mode
delTime = millis() + 250;
}
void loop() {
if (digitalRead(buttonPin) == HIGH) stepMode = !stepMode;
if (millis() > delTime) {
Serial.write("delTime"); //test case
//set led's according to mode
if (stepMode) {
digitalWrite(stepPin, HIGH);
digitalWrite(sleepPin, LOW);
} else {
digitalWrite(stepPin, HIGH);
digitalWrite(sleepPin, LOW);
}
//create string to store data
String data = "";
if (stepMode) data += "s"; //s is step mode key
else data += "z"; //z is sleep mode key
//add actual reading stuff
data += String(accel.getX()) + "," + String(accel.getY());
Serial.write(data.c_str()); //send the lad over
}
}
The Java side is nearly identical (sans the conditions of an if statement, but it doesn't matter because if it doesn't meet the statement it just prints what it sees) to a functional program for serial communication that I've used before. I can include it if necessary though.
The Java console output appears as:
Connected
de
Connected
de
Connected
de
where a new iteration appears about once a second. What am I doing that prevents the Arduino from sending the data?
Not a proper answer yet, more of a test, but I couldn't fit it in a comment.
Changes made:
delTime is now an unsigned long int;
delTime is now reset at the end of the loop();
String object and manipulations were replaced by heap-friendlier code.
Added accel.begin();
Let me know if this works for you, and if not, where it complains. Haven't fully tested the code. You could also try replacing accel.getX() and accel.getY() with numbers; they return short ints, I think.
BTW the button needs debouncing.
#include <SparkFun_MMA8452Q.h>
int sleepPin = 7;
int stepPin = 6;
int buttonPin = 8;
boolean stepMode = true;
unsigned long int delTime = 0;
MMA8452Q accel; //accelerometer
void setup(){
Serial.begin(9600);
while(millis() < 4000); //wait so I can start java program
Serial.write("Connected");
//set pins
pinMode(sleepPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(buttonPin, INPUT);
accel.begin();
digitalWrite(stepPin, HIGH); //starts in step mode
delTime = millis() + 250;
}
void loop() {
char str[15];
if (digitalRead(buttonPin) == HIGH)
stepMode = !stepMode;
if (millis() > delTime) {
//set led's according to mode
if (stepMode) {
digitalWrite(stepPin, HIGH);
digitalWrite(sleepPin, LOW);
Serial.write('s');
} else {
digitalWrite(stepPin, HIGH);
digitalWrite(sleepPin, LOW);
Serial.write('z');
}
sprintf(str, "%d", accel.getX());
Serial.write(str);
Serial.write(',');
sprintf(str, "%d", accel.getY());
Serial.write(str);
Serial.write('\n');
delTime = millis() + 250;
}
}
I'm using an Arduino Uno to control LED. I want the LED to turn on every m seconds and remain ON for n seconds.
I've tried this code using the delay() function (by adding delays after LED is turned ON and OFF) and also using the millis() function (by keeping a track of the time passed since the previous event - ON/OFF). However, in both the approaches, the LED develops a lag of ~1 second after a few (!10) iterations of the ON-OFF cycle. What can I do to increase the accuracy of the time at which the events occur?
int led = 13;
long experimentTime = 240000;
long ledOFFDuration = 8000;
void setup() {
pinMode(led, OUTPUT);
pinMode(button, INPUT);
}
void loop() {
for (int i = 0; i < 100; i++){
digitalWrite(led, HIGH);
delay(10000);
digitalWrite(led, LOW);
delay(10000);
}
}
I've also tried using the watchdog timer (shown below). However, it has the same issue:
#include <avr/wdt.h>
int led = 13;
volatile byte watchDogState = 0b01000000;
volatile int counter = 0;
int counterMax = 5;
bool state = 1;
void setup() {
// put your setup code here, to run once:
wdt_disable();
pinMode(led, OUTPUT);
digitalWrite(led, 1);
setWDT(watchDogState);
}
void loop() {
// put your main code here, to run repeatedly:
// if (time_elapsed == 40){
//state = !state;
//}
}
void setWDT(byte sWDT){
WDTCSR |= 0b00011000;
WDTCSR = sWDT | WDTO_2S;
wdt_reset();
}
ISR (WDT_vect){
counter++;
if (counter >= counterMax){
state = !state;
digitalWrite(led, state);
counter = 0;
}
}
I tried using the port registers directly to avoid using digitalWrite completely. But that doesn't work either. There's a lag of ~5s after 20 minutes using the following code:
int led = 13;
int m = 10;
int n = 10;
boolean on;
long change;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
long now = millis();
if (!on && change < now) {
on = true; //led is now on
change = now + n*1000; //turn off in <n> seconds
PORTB |= B00100000;
}
else if (on && change < now){
on = false; //led is now off
change = now + m*1000; //turn on in <m> seconds
PORTB &= B11011111; // Set pin 4 to 0
}
}
The lag is caused by the digitalWrite-calls. Your processing application waits until digitalWrite has finished and this may take 0.05 seconds or so. To fix your problem I would save the current time in milliseconds.
int led = 13;
int m = 24;
int n = 8;
boolean on;
long change;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
long now = System.currentTimeMillis();
if (!on && change < now) { //led is off and time for change has come
on = true; //led is now on
change = += n*1000; //turn off in <n> seconds
digitalWrite(led, HIGH); //turn on led
} else if (on && change < now) { //led is on and time for change has come
on = false; //led is now off
change = += m*1000; //turn on in <m> seconds
digitalWrite(led, LOW); //turn off led
}
}
the lamp will now instantly turn on on startup, wait n seconds, turn off, wait m seconds and restart from the beginning.
If you want to create a delay at the beginning so that the lamp doesn't get turned on immediately you can simply add this to your setup-function:
change = now + SECONDS*1000;
EDIT
You pointed out that it still gives you lag.
One problem might be that loop() is not run every millisecond. So I maybe got a solution for you.
Replace the following two lines:
change = now + n*1000; //turn off in <n> seconds
...
change = now + m*1000; //turn on in <m> seconds
to this:
change += n*1000; //turn off in <n> seconds
...
change += m*1000; //turn on in <m> seconds
Now it won't take the current time anymore which means that even if loop is only run every second or two it should still not cause any lag.
If this won't work I'm afraid it looks like the timer on the arduino might not be the most precise one. If this is the case try to measure the exact offset and then create a miltiplicator for the time.
For a project containing a led-strip controller I want to replace the IR remote with an Arduino nano. Now after doing some research (http://blog.allgaiershops.com/2012/05/10/reversing-an-rgb-led-remote/) and measurements I found that the led-strip controller uses the NEC protocol.
Now I have tried to create a program that will emulate one of the button press events as measured on the IR_receiver. However, when the output on the digital pin 2 (which is PWM supported) is measured, the timing isn't anywhere near desired.
However, if I use the for loop as written in the functions (high/low output) in the main loop it is possible to create a high output for 500us.
I was wondering if you could give me some support in order to get the code functioning, or could you give me some tips as how to handle timing on the Arduino in an efficient way.
/*
Timer2_Counter_display_time_elapsed.ino
Timer2 Counter Basic Example - Demonstrates use of my Timer2_Counter, which is a timer function with 0.5us precision,
rather than 4us precision like the built-in Arduino micros() function has.
By Gabriel Staples
Visit my blog at http://electricrcaircraftguy.blogspot.com/
-My contact info is available by clicking the "Contact Me" tab at the top of my blog.
-Please support my work & contributions by buying something here: https://sites.google.com/site/ercaguystore1/
My original post containing this code can be found here: http://electricrcaircraftguy.blogspot.com/2014/02/Timer2Counter-more-precise-Arduino-micros-function.html
Written: 17 May 2014
Updated: 30 May 2014
*/
//CODE DESCRIPTION:
//This code demonstrates the use of my Timer2, which provides a more precise timer than micros().
//micros() has a precision of only 4us. However, Timer2 keeps track of time to a precision of 0.5us.
//This is especially important in my code which reads an RC receiver PWM signal, which varies from 900~2100us.
//Though this code demonstrates the use of the Timer_2 functions I have written, it does not adequately demonstrate the
//real utility of the code, so I will state the following:
//By using my Timer2 timer to measure the PWM high time interval on an RC receiver, in place of using micros(), I can get repeatable
//pulse width reads with a fluctuation of ~1us, rather than having a read-in range fluctuating by as much as +/- 4~8 us when I use micros().
//This is an increase in precision of ~8x.
//include the library
#include <eRCaGuy_Timer2_Counter.h>
#define pin_output 2
#include <time.h>
//Note: an object of this class was already pre-instantiated in the .cpp file of this library, so you can simply access its methods (functions)
// directly now through the object name "timer2"
//eRCaGuy_Timer2_Counter timer2; //this is what the pre-instantiation line from the .cpp file looks like
boolean on=false;
int values[24][32]={0};
int one_output =1680;
int zero_output= 560;
void low_output(int );
void high_output(int );
void start_protocol(int);
void end_protocol(int);
void setup() {
//configure Timer2
timer2.setup(); //this MUST be done before the other Timer2_Counter functions work; Note: since this messes up PWM outputs on pins 3 & 11, as well as
//interferes with the tone() library (http://arduino.cc/en/reference/tone), you can always revert Timer2 back to normal by calling
//timer2.unsetup()
//values[0]={8,4,1,5,8,6};
//prepare serial
Serial.begin(115200);
pinMode(pin_output, OUTPUT);
digitalWrite(pin_output, HIGH);
//Output a header of info:
/*Serial.println(F("Notes:"));
Serial.println(F("micros() has a precision of 4us"));
Serial.println(F("get_count() with unsigned long final data type has a final precision of 1us, and is fast"));
Serial.println(F("get_count() with float final data type has a final precision of 0.5us, and is not quite as fast"));
Serial.println(F("get_micros() has a precision of 0.5us, and is slower than the above 2 methods, so one of the above 2 methods is preferred"));
Serial.println(F("=============================================="));*/
}
void loop() {
//declare local variables
delay(2000);
start_protocol();
low_output(8);
high_output(4);
low_output(1);
high_output(5);
low_output(8);
high_output(6);
end_protocol();
static unsigned long t_start = timer2.get_count();
// unsigned long t_micros = micros();
unsigned long t_T2_count = timer2.get_count();
//float t_T2_micros = timer2.get_micros();
if ((t_T2_count - t_start)/2 >= 2000003)
{
digitalWrite(pin_output, HIGH);
}
} //end of loop()
void low_output(int xtimes)
{
for (int i =0 ; i<xtimes ; i++){
static unsigned long t_start = timer2.get_count(); //units of 0.5us; the count accumulated by Timer2_Counter
//acquire time stamps
unsigned long t_T2_count = timer2.get_count(); //units of 0.5us; the count accumulated by Timer2_Counter
//See if 1.000003 seconds has elapsed. If so, print out the time stamps. Note: I am using this elapsed time because I want it to NOT be divisible by 4, so that
//you can hopefully see the extra precision provided by the Timer2_Counter library, which the default Arduino micros() function does not have
if ((t_T2_count - t_start)/2 >= zero_output)//1000003) //if 1.000003 seconds has elapsed
{
t_start = t_T2_count; //update start time
if(on==false) {
digitalWrite(pin_output, LOW);
on=true;
}else {
digitalWrite(pin_output, HIGH);
on=false;
}
}
}
return;
}
void high_output(int xtimes)
{
for (int i =0 ; i<xtimes ; i++){
static unsigned long t_start = timer2.get_count();
//acquire time stamps
unsigned long t_T2_count = timer2.get_count();
if ((t_T2_count - t_start)/2 >= one_output)
{
t_start = t_T2_count; //update start time
if(on==false) {
digitalWrite(pin_output, LOW);
on=true;
}else {
digitalWrite(pin_output, HIGH);
on=false;
}
}
}
return;
}
void start_protocol(){
static unsigned long t_start = timer2.get_count();
unsigned long t_T2_count = timer2.get_count();
digitalWrite(pin_output, LOW);
t_start = timer2.get_count();
t_T2_count = timer2.get_count();
if ((t_T2_count - t_start)/2 >= 9000)
{
digitalWrite(pin_output, HIGH);
}
}
void end_protocol(){
static unsigned long t_start = timer2.get_count();
unsigned long t_T2_count = timer2.get_count();
if ((t_T2_count - t_start)/2 >= zero_output)
{
digitalWrite(pin_output, LOW);
}
t_start = timer2.get_count();
t_T2_count = timer2.get_count();
if ((t_T2_count - t_start)/2 >= 40000)
digitalWrite(pin_output, HIGH);
t_start = timer2.get_count();
t_T2_count = timer2.get_count();
if ((t_T2_count - t_start)/2 >= 9000)
{
digitalWrite(pin_output, LOW);
}
t_start = timer2.get_count();
t_T2_count = timer2.get_count();
if ((t_T2_count - t_start)/2 >= 2100)
{
digitalWrite(pin_output, HIGH);
}
t_start = timer2.get_count();
t_T2_count = timer2.get_count();
if ((t_T2_count - t_start)/2 >= zero_output)
{
digitalWrite(pin_output, LOW);
}
digitalWrite(pin_output, HIGH);
}
For this this code, I used a timing library made by Gabriel Staples.
[update]
After following the tips of #Gmodjackass the following code got the NEC signal on the output of pin 2. note: code can be optimized by adding support for direct pin port manipulation.
#define pin_output 2
#include <time.h>
boolean on=false;
int values[24][32]={0};
int one_output =1680;
int zero_output= 560;
int sb=-1;
void low_output(int );
void high_output(int );
void start_protocol();
void end_protocol();
void selection_protocol(String);
void setup() {
Serial.begin(115200);
pinMode(pin_output, OUTPUT);
digitalWrite(pin_output, HIGH);
Serial.print("user_inpu: on(1) / off(0)");
delayMicroseconds(400);
}
void loop() {
//declare local variables
if (Serial.available())
{
char sb = Serial.read();
Serial.print(sb);
switch (sb){
case '0':
selection_protocol("off");
break;
case '1':
selection_protocol("on");
break;
}
sb=-1;
}
} //end of loop()
void low_output(int xtimes)
{
for (int i =0 ; i<xtimes*2 ; i++){
if(on==false) {
digitalWrite(pin_output, LOW);
on=true;
}else {
digitalWrite(pin_output, HIGH);
on=false;
}
delayMicroseconds(zero_output);
//}
}
return;
}
void high_output(int xtimes)
{
for (int i =0 ; i<xtimes*2 ; i++){
if(on==false) {
digitalWrite(pin_output, LOW);
on=true;
delayMicroseconds(zero_output);
}else {
digitalWrite(pin_output, HIGH);
on=false;
delayMicroseconds(one_output);
}
//}
}
return;
}
void start_protocol(){
digitalWrite(pin_output, LOW);
delayMicroseconds(9000);
digitalWrite(pin_output, HIGH);
delayMicroseconds(4400);
return;
}
void end_protocol(){
digitalWrite(pin_output, LOW);
delayMicroseconds(zero_output);
digitalWrite(pin_output, HIGH);
delay(40);
digitalWrite(pin_output, LOW);
delayMicroseconds(9000);
digitalWrite(pin_output, HIGH);
delayMicroseconds(2100);
digitalWrite(pin_output, LOW);
delayMicroseconds(zero_output);
digitalWrite(pin_output, HIGH);
return;
}
void selection_protocol(String user_input){
if(user_input == "on"){
Serial.print("on selected");
start_protocol();
low_output(8);
high_output(4);
low_output(1);
high_output(5);
low_output(8);
high_output(6);
end_protocol();
}
if(user_input == "off"){
Serial.print("off selected");
start_protocol();
low_output(8);
high_output(4);
low_output(1);
high_output(3);
low_output(1);
high_output(1);
low_output(6);
high_output(1);
low_output(1);
high_output(6);
end_protocol();
}
return;
}
Some of your timing discrepancies may be caused by the very slow nature of arduino's digitalWrite, maybe look into using direct port manipulation. Also consider using this delay function instead since it may cause some more of your timing issues.
(edited for spelling errors)
I'm making a game with my Arduino Uno.
4 leds on the breadboards are displaying a random binary number.
The player needs to press the button to put in the number that he sees
(for example, if the leds are 0011, push the button 3 times).
If he guessed right, he wins (another led blinks). If not, he loses (led turns on and stays on).
But I want the player to automatically lose if he hasn't pressed a button for two seconds.
But I'm really a beginner so bear with me. Below I'll post what I've got so far. But it's not exactly working. When I turn it on, without me pressing the button, it just goes straight to "you win" and the next round. What am I doing wrong?
int led1 = 9;
int led2 = 6;
int led3 = 5;
int led4 = 3;
int ledResult = 13; //will blink when you won, stay on when you lost
int buttonPin = 2;
int val = 0; // variable for reading the pin status
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
long interval = 2000;
long randomNumber;
void setup() {
Serial.begin(9600); //starts serial communication
pinMode (led1, OUTPUT);
pinMode (led2, OUTPUT);
pinMode (led3, OUTPUT);
pinMode (led4, OUTPUT);
pinMode (ledResult, OUTPUT);
pinMode (buttonPin, INPUT);
randomSeed(analogRead(A0)); //the pin is unconnected so it'll return something random (0-1023)
}
void loop() {
randomNumber = random(1, 16);
Serial.println("Random Numbers sequence"); //just for self-check
Serial.println(randomNumber);
if (randomNumber >= 8)
{
digitalWrite (led1, HIGH);
randomNumber - 8;
}
else
{
digitalWrite (led1, LOW);
}
if (randomNumber >= 4)
{
digitalWrite (led2, HIGH);
randomNumber - 4;
}
else
{
digitalWrite (led3, LOW);
}
if (randomNumber >= 2)
{
digitalWrite (led4, HIGH);
randomNumber - 2;
}
else
{
digitalWrite (led1, LOW);
}
if (randomNumber = 1)
{
digitalWrite (led2, HIGH);
}
else
{
digitalWrite (led1, LOW);
}
unsigned long currentMillis = millis();
if (currentMillis > interval) {
Serial.println("You lost.");
digitalWrite(ledResult, HIGH);
}else{
//READ BUTTON STATE
buttonState = digitalRead(buttonPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
if (buttonState == HIGH)
{
buttonPushCounter++;
Serial.println("Button push counter:");
Serial.println(buttonPushCounter);
}
// Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state, for next time through the loop
lastButtonState = buttonState;
if (buttonPushCounter = randomNumber) {
Serial.println("You won!");
digitalWrite(ledResult, HIGH);
delay(700);
digitalWrite(ledResult, LOW);
delay(700);
}
else
{
Serial.println("You lost.");
digitalWrite(ledResult, HIGH);
}
}
}
Essentially you'll want to have a main loop that probes/polls for user input, and if there's no input from the user on probe, then check the current millis time against when you called it for start. This will give you the elapsed time since no input was detected. If the elapsed time is greater than your threshold, you break out of the loop and check a timeout flag to see if you proceed with the button validation code or branch to the "lose" code.
Without writing the whole thing, here's a C pseudo-code mock up of the idea (commented to explain):
void loop() {
while (is_running) { // main loop
unsigned long start = millis(); // get starting probe time
bool timeout = false;
while ((buttonState = probe_input()) == no_input_val) {
/* probe_input function returned no input,
so check for timeout. If the probe_input function
did return a 'value', then this loop won't iterate
and you can check the buttonState below */
if ((millis() - start) >= interval) {
/* millis is monotonic time, so calling it, then
subtracting the value from the start value will give
us elapsed time since user did not give input. */
timeout = true;
break;
}
}
if (!timeout) {
/* button state/level code */
} else {
// lose code
}
}
}
Again, this is just pseudo-code and won't compile as you'd need to implement the probe_input function to poll for input, but it's more to illustrate what you'd need to do to get you moving in the direction you're wanting.
I hope that can help.
I'm making an Arduino program and I can't get it to work.
All the program does is turn an LED on whenever someones becomes 5 inches away from the sensor. The problem is whenever I start the program the LED stays off no matter what. Here's my program
const int pingPin =7 ;
const int ledPin = 13;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
long duration, inches, cm;
pinMode(pingPin,OUTPUT);
digitalWrite(pingPin,LOW);
delayMicroseconds(2);
digitalWrite(pingPin,HIGH);
delayMicroseconds(5);
digitalWrite(pingPin,LOW);
pinMode(pingPin,INPUT);
duration =pulseIn(pingPin,HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
while (true) {
if (inches <= 5) {
digitalWrite(ledPin, HIGH);
}
else {
digitalWrite(ledPin, LOW);
}
}
}
long microsecondsToInches(long microseconds)
{
return microseconds /74/2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds /29/2;
}
How can I fix this so that the LED turns on and off at the correct distances?
Take a close look at this last bit of your code:
while (true) {
if (inches <= 5) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
You see what it is doing? It is looping forever.
So... your var inches gets a value once and then for all and eternity (or until you unplug) that value will remain the same..
Get rid of the while() and you should see some responsiveness (assuming everything else is hooked up correctly).