text:
8 bit arduinos: What happens to the data in registers during a function call? During an interupt?
If I have one function that uses registers heavily calling another that does the same thing, what happens?  Does the data get destroyed?  What, then, would happen on return to the first function?  Is this different for interrupt handlers?

The compiler is capable of analyzing which registers are used by the function or ISR, so it generates prologue and epilogue code that saves the registers on the stack on entry and restores them on exit.

Is it any different for regular functions?

@MichaelStachowsky: Nope.


text:
Problem using HC-12 graphical configuration utility, invalid responses
I'm trying to use this utility [first time] to config a pair of HC-12s to a different channel, as I already have the default address in use.  It's a very handy utility, though I can find almost no reference to it via Google.
I found reference to the command here:
http://www.thebackshed.com/forum/forum_posts.asp?TID=8246&PN=1
When I use to change the channel, i get 5 error messages of the form:
invalid response(1),
invalid response(3.2),
invalid response(3.3),
invalid response(3.4),
invalid response(3.5)
I am running on Windows 10 x6, using a standard USB cable to an Uno.
The wiring config is as follows:
VCC to 5v,
GND to GND,
RXD to pin 4,
TXD to pin 5,
Set to pin 6
I've also tried connecting the Set pin to GND, as I don't know whether this is necessary or not.
The board also has an 1N4007 diode in series with the power line, and a 1000uf capacitor twixt 5v and GND.  Nothing else.
There is a sample program at:
http://www.allaboutcircuits.com/projects/understanding-and-implementing-the-hc-12-wireless-transceiver-module/
that should accomplish the same function via use of line commands and I shall try that next.  However, the configuration utility is so handy that I would like to have it in my kit of useful tools.
Seeking:
Assistance with the graphical configuration utility by someone who knows more than I, or perhaps a better alternative.

the 'SET' pin needs to be connected to ground to place (and keep) the HC-12 in setup mode. when this is done you should be able to click on the "check configuration" button and receive a popup response containing the device's current configuration.
if the popup response contains no configuration data then either the HC-12 is not in setup mode ('SET' pin not grounded), or the usb to serial bridge you are using is not working. check the bridge by disconnecting the HC-12 and shorting together TxD and RxD on the bridge. you can use any terminal emulator to check loopback is working.
feel free to join the backshed forums and ask further questions about the HC-12.
cheers,
robert rozee
(author of the HC-12 config utility)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Connect 9 V battery to Arduino Mega 2560 directly?
Is it safe to connect a 9 volt battery to an Arduino Mega 2560 directly to power it?

What do you mean by "directly"?

Means the +ve terminal of battery attached to vin of arduino and -ve to ground. No extra circuit require for voltage adjustment.

Yes. On this page, you can see that you can safely connect 7-12V to the VIN pin.
Furthermore, you can simultaneously connect the USB; your Arduino will automatically draw power from the appropriate source.
Note that the power supply jack pin is connected to the Vin pin through a diode. Do not connect a battery and an external power supply, since a sufficiently high power supply voltage will try to charge your battery, which may be bad news for the battery.

The Vin pin is NOT the same as the power supply jack pin. They are two separate circuit nodes in the Mega schemating. Diode D1 separates the two nodes, causing a 0.7V drop when forward biased. ..... The Arduino will NOT always draw from the appropriate source. If the battery voltage is greater than the Vjack - 0.7V, the Arduino will draw mostly from the battery instead of the adapter (ac-to-dc converter), which would frequently be the appropriate course. ..... The first sentence is correct though.

Thanks a lot, I overlooked that diode. I just happened to know that the PSU pin could supply for the vin pin.

I don't want to be hypercritical, but I don't want to mislead anyone either. The diode is a smart protection to design in, but the diode itself is not smart. I also find that constantly disconnecting and connecting a header is cumbersome and if plugged into the wrong pins (by a student still learning) it can damage the board. That's why my answer suggested using the power jack. (No one like the sacrificing of an adapter to the cause though. :) )

This answer suggests the power jack as well, noting that it's connected through a diode (which comes at the price of not being able to put a large load in parallel to the arduino due to the heat production in the diode). I still don't understand why you would want to kill a power adapter to get a $1 plug.

@DouglasDaseeco Pin and sleeve diameters are invariably listed, and are easy to measure using a caliper; sleeve length usually matches, and does not really matter. Any decent electronic parts shop has them in stock, starting at around €0.70. I'm not saying you can't destroy your transformers for a simple plug, but I find it ridiculous to state that as a baseline. It's like saying you need to demolish a second hand car to get new brake calipers - it could be useful at times, but it's hardly the 'normal' way of car maintenance.

DO NOT CONNECT IT TO Vcc, CONNECT IT TO VIn.
By connecting it to VIn, your 9V will go from the battery, though the VReg, and then to your Arduino. This is what you HAVE to do. By connecting it directly to the Arduino Vcc pin, you are basicly frying it.
Note that once the battery has gone bellow 7V, it might start getting unsafe because you are not giving the Arduino enough power.

The bit about overclocking makes no sense.

You are not overclocking anything, the clock speed is fixed at 16MHz. You are generating a small amount of heat, but this is produced in the voltage regulator, nowhere near the processor.

@jwpat7, what I really meant was that you are keeping the clock speed at 16MHz, but not supplying enough power to power the Arduino at such speeds. Ain't that somewhat the definition of overclocking?

..No it really isn't xD supplying not enough voltage might heat up an LDO regulator, and if you're really unlucky, it might heat up your MCU, but generally just causes undefined behaviour like random resets. Overclocking is an entirely different thing, and supply voltage is hardly the defining factor there.

@DatHa, overclockers typically raise the cpu voltage, instead of lowering it, and typically run the cpu at a higher frequency than it's rated for.  See eg wikipedia Overclocking article:  “Overclocking is configuration of computer hardware components to operate faster than certified by the original manufacturer [...] Commonly, operating voltage is also increased to maintain a component's operational stability at accelerated speeds.”  Granted, if frequency stays constant as voltage drops, the cpu ends up running faster than rated for given voltage.

Yes.
Batteries are acceptable power sources for the Arduino Mega and other Arduino boards.  I've used them for years for various applications where access to AC is inconvenient, impractical, or nearly impossible.
The Mega page on the Arduino site  also explicitly permits battery power.
Helpful Guidelines
Here are some important criteria to meet.

The Voltage is within the published range for the Arduino model you are using, which is 7 to 12 Volts DC for the Mega 2560
The positive of the battery supply connected to Vin (NOT any of the other power pins)
The negative of the battery supply is connected to Gnd
Critical applications don't run under the assumption that the battery will never drop below the required 7 Volts
The header is never plugged in backwards or in the wrong location, which would likely damage the Arduino circuitry

Connection Safety Using Plug and Jack
If you are connecting and disconnecting the Arduino from your battery frequently or you just want .
See the Power section of the page to make sure you never plug in the header wrong, you can connect your battery supply to the Arduino board's existing power jack.  When connecting a battery supply to an Arduino compatible plug, you can ensure that the plug's inner conductor is positive in Voltage relative to the outer sheath using a Voltmeter.
Battery Use in Robotics and Flight Control
A 9V battery will eventually drop in Voltage below 7V, upon which the operation of the board may fail at any time, so you may want to add more 9V batteries in parallel to extend your battery supply's life 1.
Another approach common in robotics or flight control applications, to preemptively avoid erratic behavior as the battery drains below operational thresholds, is to use the low voltage detection features of the CPU.  The Atmel CPU used by the Arduino Mega 2560 has a Brown-Out Detection feature.  The Atmel CPU for the Due and other boards have under-voltage detection too.
A simpler approach for critical applications is a resistor divider on an analog input is another related approach.
.....
[1] Batteries may vary in Voltage when purchased, but some small variance above or below 9V hurts neither the batteries nor the Arduino.  They will equalize themselves without dissipating (wasting) much energy, so you will get close to N times the battery life, where N is the number of 9V batteries in parallel.  See this Electronics StackExchange Q&A and this battery company article for more information.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Two signal with delay
I have a two pins for two blinks leds but I need delay the second signal from first. I start the first signal and I need start the second signal 50ms later. The first signal is 500ms HIGH and 500ms LOW, and the second signal is 400ms LOW and 600ms HIGH. If I start the second signal 50ms later, I can center the high period of the first signal with the low period of the second signal.
This is my code:
long DelaySecondSignal = 50;
int A = 1;

while (A == 1)
{
    long millis_actuales = millis();

        //Control Salida_A
        if (millis_actuales - TiempoTranscurrido_SalidaA > (Estado_SalidaA ? 500 : 400)) {
            digitalWrite(SalidaA, Estado_SalidaA = !Estado_SalidaA);
            TiempoTranscurrido_SalidaA = millis_actuales;
        }

        if (millis_actuales > DelaySecondSignal)
        {
            //Control Salida_B
            if (millis_actuales - TiempoTranscurrido_SalidaB > (Estado_SalidaB ? 500 : 600)) {
                digitalWrite(SalidaB, Estado_SalidaB = !Estado_SalidaB);
                TiempoTranscurrido_SalidaB = millis_actuales;
            }
        }
}

TiempoTranscurrido_?? is a int and Estado_Salida? is a boolean.
I need start the second signal with 50ms of delay but "if (millis_actuales > DelaySecondSignal)" no work.
Thanks.

Your problem is that you are treating both signal separately. Instead you need to think about the events of turning LEDs on and off and where they lie on a combined timeline:
     0    100   200   300   400   500   600   700   800   900  1000
     |-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|
     ^  ^                       ^  ^
  1 on  2 off                2 on  1 off
  1: ooooooooooooooooooooooooooooooo
  2: oooo                       oooooooooooooooooooooooooooooooooo

You see how I have looped the time around so that the turning off of the second signal, which would normally come at 1050ms, in fact comes at 50ms. By just working in a single 1000ms block of time as a loop things become much simpler.
You can do it now with just a simple set of delays, now you have it laid out in a single timeline like that:
void loop() {
    digitalWrite(led1, HIGH);
    delay(50);
    digitalWrite(led2, LOW);
    delay(400);
    digitalWrite(led2, HIGH);
    delay(50);
    digitalWrite(led1, LOW);
    delay(500);
}

All the delay() calls add up to 1000ms and it keeps looping around.
If you want to make it non-blocking you should set it up with a small finite state machine. There are 4 steady states which are the four spaces between the events on the timeline. There are 4 transitions, which are the events on the timeline.  So you:
Start in state 0 with both LEDs on (which is how they are at the start of the timeline).

0: When 50ms have passed turn off LED 2 and move to state 1.
1: When 400ms have passed turn on LED 2 and move to state 2.
2: When 50ms have passed turn off LED 1 and move to state 3.
3: When 500ms have passed turn on LED 1 and move to state 0.

This example work perfect, I can change the duty cycle and work. I have another question, How make this example without "delay()"?

Like I say in the second half of my answer - with a Finite State Machine.

I'd just base everything of millis.
int A = 1;

while (A == 1)
{
    int phase = millis() % 1000;// modulo 1 second

    // turn on A for the first 500ms of a period, and off for the rest
    if( phase<500 )
        digitalWrite(SalidaA, HIGH);
    else
        digitalWrite(SalidaA, LOW);

    // turn on B for the first 50ms, and last 550ms of a period, and off for the rest
    if( phase<50 || phase>=450 )
        digitalWrite(SalidaB, HIGH);
    else
        digitalWrite(SalidaB, LOW);

}

I did not explain myself well. This example works but not well, for example if I change the length of the period, no work ok until after 1 second. For example, I have a Rate that is "150". I divide 60 seconds beetwen 150 and I have 0.4. Now I need repeat 50% HIGH - 50% LOW of cycle in 400ms in period A, but for example the period B is 35% HIGH - 65% LOW (35*400/100 =  140ms HIGH and 400-140= 260ms LOW).

Majenko does not have this problem in his example because he repeats the cycle all time, so I asked if he knows how to do the same example with the milis() function. I need a similar PWM function with center aligned.

Just multiply all the numbers by this 0.4. So 1000 becomes 400; 50 becomes 20 etc.

Now work, I changed "millis() % 1000;" by "millis() % 400;" and work ok but I DON'T KNOW WHY IT WORK, sorry. :(

Do you know how modulo works? It's like like looking at a clock and saying; I don't care about the hours or minutes, I just want to know the seconds. After that you say; the first 5 seconds of every minute I want output A HIGH, the next 20 seconds LOW, and the rest of every minute HIGH again. For output B I want the output to be HIGH the first 30 seconds of every minute, and LOW the other 30 seconds.


text:
Array variable name changes from readings1 to readings2
I've been using two MB1240 Ultrasonic Sensors with analogRead, and have found that after using bubble sort, the array is found in array readings2, and not readings1. This is important because I would like to find the distance from each sensor.
Below is the code I've put together that uses buttons to determine when each sensor should be triggered.
const int anPin1 = 1;
const int anPin2 = 2;

const int triggerPin = 2;
long anVolt1, anVolt2;

// button Pins
const int buttonPin1 = 11;
const int buttonPin2 = 13;

int buttonState1;
int buttonState2;
int lastButtonState1 = false;
int lastButtonState2 = false;

long lastDebounceTime1 = 0;
long lastDebounceTime2 = 0;
long debounceDelay = 50; //ms

// initialise averaging array
const int numberOfReadings = 10; // reasonable DOF
long readings1[numberOfReadings];
long readings2[numberOfReadings];
long median;

void setup() {
  Serial.begin(9600);
  pinMode(triggerPin,OUTPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  delay(200); // Datasheet: Sensors require 175 ms to calibrate
}

void start_sensor(){
  digitalWrite(triggerPin,HIGH);
  delay(10);
  digitalWrite(triggerPin,LOW);
}

long read_sensor1(){
  //Used to read in the analog voltage output that is being sent by the XL-MaxSonar device.
  //Scale factor is (Vcc/1024) per centimeter. A 5V supply yields ~4.9mV/cm for standard range sensors
  anVolt1 = analogRead(anPin1);
  return anVolt1;
}

long read_sensor2(){
  anVolt2 = analogRead(anPin2);
  return anVolt2;
}

void printall(long readings[]) {
  int med = numberOfReadings/2;
  median = (readings[med-1] + readings[med])/2;

  Serial.print("Sensor: ");
  for (int i = 0; i < numberOfReadings; i++) {
    Serial.print(readings[i]);
    Serial.print("cm ");
  }
  Serial.println();

  Serial.print("Median: ");
  Serial.print(median);
  Serial.println(" cm");
}

void loop () {
  int reading1 = digitalRead(buttonPin1);
  int reading2 = digitalRead(buttonPin2);

  // for noise
  if (reading1 != lastButtonState1) {
    lastDebounceTime1 = millis();
  }

  // for noise
  if (reading2 != lastButtonState2) {
    lastDebounceTime2 = millis();
  }

  if ((millis() - lastDebounceTime1) > debounceDelay) {
    if (reading1 != buttonState1) {
      buttonState1 = reading1;
      if (buttonState1 == HIGH) {
        for (int i = 0; i < numberOfReadings; i++){
         start_sensor();
          readings1[i] = read_sensor1();
          delay(150); // From datasheet: Period = 99ms
        }

            **// bubble sort with flag
        for (int i = 0; i < sizeof(readings1)-1; i++) {
            bool flag = true;
            for (int j = 1; j < sizeof(readings1)-1; j++) {
                if (readings1[j-1] > readings1[j]) {
                    int t = readings1[j-1];
                    readings1[j-1] = readings1[j];
                    readings1[j] = t;
                    flag = false;
                }
            }
            if (flag) break;
        }
       printall(readings1);**
      }
    }
  }

  lastButtonState1 = reading1;

  if ((millis() - lastDebounceTime2) > debounceDelay) {
    if (reading2 != buttonState2) {
      buttonState2 = reading2;
      if (buttonState2 == HIGH) {
        for (int i = 0; i < numberOfReadings; i++) {
          start_sensor();
          readings2[i] = read_sensor2();
          delay(150);
        }
       printall(readings2);
      }
    }
  }
  lastButtonState2 = reading2;

  //clear previous readings
  memset(readings1, 0, sizeof(readings1));
  memset(readings2, 0, sizeof(readings2));
}

Scenario: I have clicked the first button to return a reading from the first sensor, and I am expecting the results to be stored then sorted in array readings1. After the bubble sort, if I enter printall(readings1), it returns an array of zeros, but if I use a printall(readings2), it returns the sorted array I expected.
I can't find where I'm going wrong with this one, any help would be greatly appreciated. Thank you!

Wouldn't using qsort be easier, faster, and more reliable?

qsort is brilliant. I switched from a bubble sort to a qsort algorithm for ordering triangles in a 3d mesh drawing library and it went from ~1fps for 8000 triangles to ~20fps.

for (int j = 1; j < sizeof(readings1)-1; j++) {

sizeof(readings1) is not the number of elements in the array, it is the size of the array in bytes (in your case, 40). You are exceeding the bounds of the array. You know the number of items (numberOfReadings) - why not use that?


text:
How many Ultrasonic sensors can be connected to an Arduino Uno R3?
How many Ultrasonic sensors (HC SR04 ) can be connected to an Arduino Uno R3 board?

As many as you like, but at some point you run out of pins to connect them.

You can make all your ECHO pins Open Drain by adding an N-channel MOSFET or NPN BJT, add a pullup to an input, and then have all your SR04's echoing to the same pin. Since you can really only trigger one at a time anyway you know which one the echo must be coming from even though they're all on the same pin. Note that this would invert the echo signal, so change your pulseIn() to compensate.

I am working on a project where I am using 6 sonar sensors in one Arduino Uno !

If you look into any example sketch, like this from sparkfun:
/**
 * HC-SR04 Demo
 * Demonstration of the HC-SR04 Ultrasonic Sensor
 * Date: August 3, 2016
 *
 * Description:
 *  Connect the ultrasonic sensor to the Arduino as per the
 *  hardware connections below. Run the sketch and open a serial
 *  monitor. The distance read from the sensor will be displayed
 *  in centimeters and inches.
 *
 * Hardware Connections:
 *  Arduino | HC-SR04
 *  -------------------
 *    5V    |   VCC
 *    7     |   Trig
 *    8     |   Echo
 *    GND   |   GND
 *
 * License:
 *  Public Domain
 */

// Pins
const int TRIG_PIN = 7;
const int ECHO_PIN = 8;

// Anything over 400 cm (23200 us pulse) is "out of range"
const unsigned int MAX_DIST = 23200;

void setup() {

  // The Trigger pin will tell the sensor to range find
  pinMode(TRIG_PIN, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);

  // We'll use the serial monitor to view the sensor output
  Serial.begin(9600);
}

void loop() {

  unsigned long t1;
  unsigned long t2;
  unsigned long pulse_width;
  float cm;
  float inches;

  // Hold the trigger pin high for at least 10 us
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Wait for pulse on echo pin
  while ( digitalRead(ECHO_PIN) == 0 );

  // Measure how long the echo pin was held high (pulse width)
  // Note: the micros() counter will overflow after ~70 min
  t1 = micros();
  while ( digitalRead(ECHO_PIN) == 1);
  t2 = micros();
  pulse_width = t2 - t1;

  // Calculate distance in centimeters and inches. The constants
  // are found in the datasheet, and calculated from the assumed speed
  //of sound in air at sea level (~340 m/s).
  cm = pulse_width / 58.0;
  inches = pulse_width / 148.0;

  // Print out results
  if ( pulse_width > MAX_DIST ) {
    Serial.println("Out of range");
  } else {
    Serial.print(cm);
    Serial.print(" cm \t");
    Serial.print(inches);
    Serial.println(" in");
  }

  // Wait at least 60ms before next measurement
  delay(60);
}

You can see it is used only two pins. So, as long as you can provide power to sensors and pins to it, you can have as much as you like. You can even expand with more IO pins using other electronics or go into some kind of multiplexing.


text:
How to drive RGB LED fading alongside MAX7219s
Merry XMAS
I have a pro mini which drives 2 RGB LED strips on its 6 PWM pins, via 6 2N7000 N-channel MOSFETs. Alongside these, I have  4 x MAX7219 modules in series controlled via SPI. Both work perfectly, but not concurrently - yet. I need to do sleek PWM on the RGB strips whilst outputting scrolling text on the MAX7219s.
The functions for the MAX7219 display take some time to complete for each blob of text.
I added a udelay() function (works like delay(), but just uses delayMicroseconds instead) so I could use interrupts/timers.
I am now interested in the best practice for doing that - I have no experience with interrupts, and would rather not use something lile FreeRTOS for this.
Desired functionality:
1) Drive 2 RGB LED strips on 6 PWM pins, smoothly.
2) While at the same time outputting arbitrary text/foo on the MAX7219s on SPI.
I have this snippet for smoother RGB fading ( http://forum.arduino.cc/index.php?topic=12004.0 ) and would also like to know what variables periode, displace denote, and if this method has merit.

void loop()
{
 time = millis();
 value = 128+127*cos(2*PI/periode*time);
 value2 = 128+127*cos(2*PI/periode*(displace-time));
 analogWrite(ledpin, value);           // sets the value (range from 0 to 255)
 analogWrite(ledpin2, value2);           // sets the value (range from 0 to 255)
}

@Majenko et al?
Cluebats at the ready - any advice would be appreciated!

The functions for the MAX7219 display take some time to complete for each blob of text. - They shouldn't. How are you driving them? Have you thought about interleaving updating each row with updating your LED strips? What are you even considering any form of delay function?

@Majenko I am using the LedControl library - no I haven't thought about that, I don't know how to interleave updating each row, and even if I did, the text blobs have to be displayed for some time. I am interested in the equivalent of two threads (I'll use FreeRTOS if I must), can't that be done with interrupts? I'm sure there's plenty of delay()s in the printbuffer( textStr ) functions for the fading to take place. The udelay() function is explicitly for functions which run as interrupts - do forgive me my lack of insight here; if fork() was possible, this would be straightforward.

I see that library uses shiftOut(). First step will be to ditch that and use proper hardware SPI.

I'd probably go the other way than Majenko suggest, and leave the max7219 code as is, but use a timer interrupt to update the PWM values.

@Gerben Alright - You validate my own idea. I will proceed accordingly. Post as answer and I will close this question.


text:
What is micro C in a circuit diagram?
This is probably a simple question but I am a beginner with these things. What does the micro C part of the circuit diagram mean? The diagram is from the datasheet of the tssp77038 IR receiver. Does it want there to be a capacitor on the output?
(http://www.farnell.com/datasheets/1915248.pdf?_ga=1.234529246.1943069395.1480959857)

If you Google "µC" you reach the page Microcontroller

It means "Micro Controller" - you know it as "Arduino".


text:
Why does this code not respond promptly to changes in the LDR reading?
So, I wrote some simple code like this :
void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
  Serial.begin (9600);
}

void loop() {
  LDRValue = analogRead(LDRSensor);
  Serial.println(LDRValue);
  delay(50);
}

The line will print the value of LDR sensor simultaneously, but when I add this "if" condition inside the loop :
 if (LDRValue < 100) {
   colorWipe(strip.Color(255, 0, 0), 50);
   colorWipe(strip.Color(0, 255, 0), 50);
   colorWipe(strip.Color(0, 0, 255), 50);
   colorWipe(strip.Color(0, 0, 0, 255), 50);
   theaterChase(strip.Color(127, 127, 127), 50);
   theaterChase(strip.Color(127, 0, 0), 50);
   theaterChase(strip.Color(0, 0, 127), 50);
   rainbow(20);
   rainbowCycle(20);
   theaterChaseRainbow(50);
  }

the LDR  value only printed once..
Is it a wrong "if" condition code ? I know it's kinda lame, but please give me some starting point, doesn't need to be fancy just a small lead will do, thanks!
edit : complete library

Guess: Try putting the delay before serial.print(). Sometimes LCD can prevent serial from working for a short time.

How are your functions inside the if block implemented? With delays?

Visual Micro, it has nothing to do with LCD tho, @gre_gor its just looping one after another, no delays in it. It's a LDR + WS2812b LED code, with neopixel library if anyone else need extra information.

Did you try @VisualMicro's suggestion of putting a delay in?

How are you supplying power to the ledstrip? Does it work without the strip attached? It may be that you're trying tot supply the ledstrip with power from the Arduino, and it may simply dip if you try to set the leds on.

Alternatively the code may loop endlessly or get a watchdog timeout.

You ought to post your complete code if you hope for a good answer rather than best tries and guesses at best. What is strip, how are all values declared and initialized, where do all functions colorWipe... come from?

Your code matches this example and those functions are blocking execution with delays.

Thank you all for your concern, and gre_gor, thanks for pointed the real problem, is there anything i can do so the LDR value could printed normally? what should i change? void colorWipe(uint32_t c, uint8_t wait) {   for(uint16_t i=0; i<strip.numPixels(); i++) {     strip.setPixelColor(i, c);     strip.show();     delay(wait);   } }

After all effect, the value should be printed neverthless?  You said it would only print once?

that is correct Paul, my mistake, it does printed again after all the loop called, never waited that long before you pointed that out

I'm going to lever off gre_gor's comment on the question.
The code you are calling (for example, rainbow) has delays in it:
void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

So we can see straight away that calling rainbow(20); is going to take at least 20 x 256 ms (256 iterations of the loop with a 20 ms delay) plus more because of whatever else it does. That is over 5 seconds already!
Then you call rainbowCycle(20); and then theaterChaseRainbow(50); so you won't get back to the main loop for a while.
How to fix? Well, it isn't just a case of adding a line or two. One solution is to rewrite without delays, but instead have a state machine.
An alternative would be to test the sensor in each loop. Let's guess your objective is to stop the display if the LDR gives a higher reading. You could copy/paste the functions in question, but test the LDR inside them, eg.
void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {

    int LDRValue = analogRead(LDRSensor);   // <--- add these 3 lines
    if (LDRValue >= 100)
       return;

    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

Suggested improvement to example
The code below uses a technique of supplying a "callback function" to the functions that do the pixel displays. I modified the Adafruit example to show the idea:
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

#define PIN 6

typedef bool (*AbortFunction) ();

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, PIN, NEO_GRB + NEO_KHZ800);

// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel.  Avoid connecting
// on a live circuit...if you must, connect GND first.

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
  #if defined (__AVR_ATtiny85__)
    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  #endif
  // End of trinket special code

  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

// function prototypes
void colorWipe(uint32_t c, uint8_t wait, AbortFunction fAbort = NULL);
void rainbow(uint8_t wait, AbortFunction fAbort = NULL);
void rainbowCycle(uint8_t wait, AbortFunction fAbort = NULL);
void theaterChase(uint32_t c, uint8_t wait, AbortFunction fAbort = NULL);
void theaterChaseRainbow(uint8_t wait, AbortFunction fAbort = NULL);

const byte LDRSensor = 0;

bool checkLDR ()
  {
  int LDRValue = analogRead(LDRSensor);
  return LDRValue > 100;
  }

void loop() {
  // start with black
  colorWipe(strip.Color(0, 0, 0), 0); // Black

  // Some example procedures showing how to display to the pixels:
  colorWipe(strip.Color(255, 0, 0), 50, checkLDR); // Red
  colorWipe(strip.Color(0, 255, 0), 50, checkLDR); // Green
  colorWipe(strip.Color(0, 0, 255), 50, checkLDR); // Blue
//colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
  // Send a theater pixel chase in...
  theaterChase(strip.Color(127, 127, 127), 50, checkLDR); // White
  theaterChase(strip.Color(127, 0, 0), 50, checkLDR); // Red
  theaterChase(strip.Color(0, 0, 127), 50, checkLDR); // Blue

  rainbow(20, checkLDR);
  rainbowCycle(20, checkLDR);
  theaterChaseRainbow(50, checkLDR);
}

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait, AbortFunction fAbort) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    if (fAbort && fAbort ())
      return;
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
  }
}

void rainbow(uint8_t wait, AbortFunction fAbort) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      if (fAbort && fAbort ())
        return;
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait, AbortFunction fAbort) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    if (fAbort && fAbort ())
      return;
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

//Theatre-style crawling lights.AbortFunction fAbort
void theaterChase(uint32_t c, uint8_t wait, AbortFunction fAbort) {
  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
    for (int q=0; q < 3; q++) {
      if (fAbort && fAbort ())
        return;
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait, AbortFunction fAbort) {
  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
    for (int q=0; q < 3; q++) {
      if (fAbort && fAbort ())
        return;
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

The important addition is to add another optional argument AbortFunction fAbort to each function call. The default is NULL, in which case the function behaves the same as before. However, if supplied, the function is called. If it returns true then the display function exits (thus avoiding the delays), like this:
if (fAbort && fAbort ())
  return;

The first test is "does the function exist?" and if so, the second test calls the function and checks to see if it returns true or false.
The modified example shows the scrolling patterns on the NeoPixels, provided A0 returns 100 or less. The function that does this is here:
bool checkLDR ()
  {
  int LDRValue = analogRead(LDRSensor);
  return LDRValue > 100;
  }

That function is passed as an argument to the other functions, eg.
rainbow(20, checkLDR);

I have a page about writing callback functions.

i'll try this out now, i'll get back to you with the result in a couple hours, thank you very much everyone!!

Sorry Nick, i can't make it to try this out yesterday, but I went to your page and this solve the problem, thanks for the answer and your time to explain them all, thank you very much Nick, and everyone else here too!

authors: ร้านสามารถ โปรเจ็ค


text:
GSM module connected with arduino uno giving garbage values in response
I connected a GSM module with the Arduino UNO. The connections are as follows:

Gnd of gsm -----> Gnd of arduino
TX of gsm  -----> pin 9 of arduino
Rx of gsm  -----> pin 10 of arduino

GSM is powered from a 9V-1Amp wall adapter.
The GSM is performing according to all the AT commands (like making a voice call, hanging a call, answering a call) which are given, but it is displaying garbage values on serial monitor in response.
Here is the code:
#include <SoftwareSerial.h>
SoftwareSerial myserial(9, 10);

void setup() {
    Serial.begin(115200);
    myserial.begin(9600);
    myserial.println("ATDXXXXXXXXXX;");
    delay(30000);
    myserial.println("ATH");
}

void loop() {
    if (myserial.available()>0){
        Serial.println(myserial.read());
    }
}

What could be reasons for the GSM to output garbage values and how can I resolve it?

115200 baud is at the top end of what software serial can handle. It's probably failing miserably. Better to use hardware serial on a board with multiple UARTs.

@Majenko from the code, the OP is using SoftwareSerial at only 9600 then that should be fine.

@jfpoilpret It was hard to tell since the code was such a mess. Yes, I could have formatted it myself, but that's the job of the OP to do. If they can't even be bothered to do that, then... meh...

Could you post the garbage (and its value in hexadecimal if unprintable) you get?

    Serial.println(myserial.read());

myserial.read() returns an integer. That integer is either the ASCII code of the next character in the buffer, or -1 if there is no character to read.
You then print that integer, each one on its own line.
So the response "OK\r\n" from, say, "AT\r\n" would look like:
79
75
13
10

Instead you need to write the data, not print it:
Serial.write(myserial.read());

Also, the way you have written your code, you will get no response for 30 seconds - that is, until everything has already happened. Only after it has all finished will you get some feedback - and that may not be complete since you may overrun the buffer depending on what the modem sends.

I tried using Serial.write() in place of Serial.println() but still I am getting the garbage values. The module is not responding even while sending an AT command through Serial Monitor.


text:
Random numbers recived by wifi shield
So I am sending a web request to a server, but for some reason the result is the number: 728484804749464932504848327975131083101114118101114583213106897116101583284117101443250483268101993250484954325049585054585249327177841310671111101161011101164584121112101583211610112011647104116109108131067111110116101110116457610111010311
Any ideas?
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C Lcd(0x27, 16, 6);

#include <SPI.h>
#include <WiFi.h>

char ssid[] = "AESRO2-2.4G";
char password[] = "EA8TDKNFGE";

int status = WL_IDLE_STATUS;

WiFiClient client;

String serverReturn;

String page[]
{
  "Flashlight",
  "Message",
  "S.O.S"
};
void displayPage(int pageNumber)
{
  Lcd.clear();
  Lcd.print(page[pageNumber]);

  Lcd.setCursor(0,1);
  Lcd.print("[Open]");
  Lcd.setCursor(10, 1);
  Lcd.print("[Next]");
}
int currentPage = 0;
int lastPage = 1;

void setup()
{
  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(8,OUTPUT);

  Lcd.begin();

  Lcd.print("BrickOS V5.0.0");
  digitalWrite(6, HIGH);
  delay(300);
  digitalWrite(6, LOW);

  delay(1000);

  if(WiFi.status() == WL_NO_SHIELD)
  {
    Lcd.clear();
    Lcd.print("No wifi shield");

    while(true);
  }

  String fv = WiFi.firmwareVersion();
  if(fv != "1.1.0")
  {
    String secline = fv += "->1.1.0";
    Lcd.clear();
    Lcd.print("Firmware update");
    Lcd.setCursor(0,1);
    Lcd.print(secline);

    while(true);
  }

  while(status != WL_CONNECTED)
  {
    Lcd.clear();
    Lcd.print("Connecting to");
    Lcd.setCursor(0, 1);
    Lcd.print("network...");

    status = WiFi.begin(ssid, password);

    delay(3000);
  }

  Lcd.clear();
  Lcd.print("Connected to:");
  Lcd.setCursor(0, 1);
  Lcd.print(ssid);
  delay(1000);
}

void loop()
{
  if(lastPage != currentPage)
  {
    if(currentPage > sizeof(page))
    {
      currentPage = 0;
    }
    displayPage(currentPage);
  }
  lastPage = currentPage;

  serverReturn = "";
  while(client.available()) {
    serverReturn += client.read();
  }
  client.stop();
  if(client.connect("www.nightfall.huskyclick.info", 80))
  {
    client.println("GET /msg.php?action=check&ID=1 HTTP/1.1");
    client.println("Host: nightfall.huskyclick.info");
    client.println();
  }
  else
  {
    Lcd.clear();
    Lcd.print("Failed to check");
    Lcd.setCursor(0, 1);
    Lcd.print("for messages");
  }

  Serial.println(serverReturn);

  if(serverReturn != "false" && serverReturn != "")
  {
    digitalWrite(8, HIGH);

    Lcd.clear();
    Lcd.print("Message received!");

    digitalWrite(6, HIGH);
    delay(500);
    digitalWrite(6, LOW);

    delay(1000);

    Lcd.clear();
    Lcd.print(serverReturn);

    delay(5000);
  }

  delay(5000);
}

Yes, that's what you get when you append an int to a String.

The fault lies here:
while(client.available()) {
  serverReturn += client.read();
}

client.read() returns an integer. That integer is either the ASCII code of the next character in the buffer, or -1 if there are no characters in the buffer left to read.
You then append that integer to the end of a String which gets converted to the ASCII representation of that integer before being appended.
So the string HTTP, for instance, which is ASCII characters 72, 84 (twice) and 80 ends up as "72848480".
Instead you need to cast the integer to a char before appending:
serverReturn += (char)client.read();

Or better still don't use any String variables at all and parse the data as it comes in pulling out any information you need to at the time it arrives.


text:
Serial - Send data to Arduino while Arduino sending data
Arduino send data to PC each iteration. When I'm trying to send data to Arduino while receiving data from it, it takes too long. Serial.available() returns false even I sent data from PC. But if I add delay like 20-30 ms, problem fixed. Can't I use serial simultaneously?
PS: It's Arduino mega and I'm using http://www.teuniz.net/RS-232/ library for serial communication.
Example code:
void loop(){

  if(Serial.available())
    Serial.write("goodbye", 7);
    Serial.write("hello", 5);
  }

In this situation, it takes long time to write "goodbye" after I sent data to Arduino.

Please edit your question and post your code. Format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

@Nick Gammon, done.

That's not all your code is it? What baud rate are you using? In any case, since you are sending "hello" every time around loop the output buffer will be filled with hello before you get a chance to insert goodbye. Your "delay" solution probably gives the output buffer time to empty.

@Nick Gammon 9600.

And I lid a led when receive message. I forget to write it. Ill add full code when Im open PC. I dont have full code by now.

Following up on what Nick Gammon says, don't try to use the serial output to debug serial.  Perhaps try using the built-in LED instead; you can use an oscilloscope to find out how much time it is spending reading characters.
The following is how I've been reading a line at a time using non-blocking operations:
const int SERIAL_BUFFER_LENGTH = 100;

// The +1 assures we'll always have room for null termination
char g_serial_buffer[SERIAL_BUFFER_LENGTH+1];
int g_char_count;         // index into serial buffer

void setup() {
  Serial.begin(9600);  // or 115200 if your host supports it
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  g_char_count = 0;
}

void loop() {
  while(Serial.available() > 0) {
    digitalWrite(LED_BUILTIN, HIGH);
    char c = Serial.read();   // won't block because Serial.available() > 0
    if (c == '\n') {
      g_serial_buffer[g_char_count] = '\0';  // null terminate
      process_buffer(g_serial_buffer);
      g_char_count = 0;
    } else if (g_char_count < SERIAL_BUFFER_LENGTH) {
      g_serial_buffer[g_char_count++] = c;
    }
  }
  digitalWrite(LED_BUILTIN, LOW);
  Serial.print(".");
}

// process_buffer: do whatever it is you intended to do with a
// line of received text...
void process_buffer(char *buffer) {
}

Try this:
  if(Serial.available())
    while(Serial.read());
    Serial.write("goodbye", 7);
    Serial.write("hello", 5);
  }

I think you have to read what you get in the serial port.


text:
Building a GPS-controlled Camera
I've been trying to build an Arduino UNO controlled Camera using two servo motors that points in the direction of an object with a certain tag.
Here's an Example: A camera is on the sideline of a gym, and the players are running around. One player has a portable GPS piece attached to him, and the camera should point in the player's direction in order to capture the player's movements along with his background.
A few questions:
Would I use two different compasses in order to both record the direction and point the camera in this direction? Or would I use a GPS for the player and somehow convert the streaming data into compass direction(in which the camera will point)?
In a way, what combination (Player-Camera) would I use (if I need a combination), a GPS-GPS, GPS-compass, or compass-compass?
Do I actually need two location devices or just one?
Thanks,
Mark

You should be aware of the accuracy of GPS, especially indoors. For consumer-grade products, it may not be enough for this project.

I agree with @Sanchises, unless you are going for a wide photo the resolution of GPS is about 10m.  You might be better using multiple directional radio signal sensors and triangulating the position, or if you have a camera with auto focus and no intervening objects you might be able to get a way with one directional radio sensor.  In either case you would need to do some reflection processing to cancel out the signal on the player bouncing off the gym walls.  Might it be better to look at the Pixy cam and visually track the 'player'?

A compass would be useless on the player. Whether the player is face towards or away from the camera, the camera should point in the same direction in either case.

you probably may want to look into this: http://sports.stackexchange.com/q/4996

Take a look at the uTube site of "iforce2d". Chris has a couple of GPS projects, which use a GPS and nRF24L01 transceivers to implement a "GPS tag" and he has a model car follow the tag. He also has a ground station with a pan and tilt and a camera following his quadcopter (drone). Lots of useful stuff there.


text:
Long Distance Shift Register
I am using a Mega to control some relay boards. I have a 16 relay board near the mega, and I want to put an 8 relay board about 40 ft. away. So I figured I could use a shift register - instead of running 9 wires (8 relays and gnd) I could just run 4 (gnd, latch, clock, and data). I had some cat5e cable so I ran that from the Mega to the shift register. (I have an external 5V power supply so that does not come from the mega).
Problem is that is works, but inconsistently. I wrote a test program to turn on the relays in sequence. Sometimes it goes in order as it should but other times it skips relays or goes out of order.
I think there might be 4 sources of the problem:
1  The cat5e cable is too thin. Would a bigger wire help? Will twisting one pair together and using it like it was one wire help?
2 The shift_out code timing is off. I tried inserting some delay statments and that seemed to help a little. But I'm not sure where to insert them.
 void shift_out() {
     DigitalWrite(latch_pin, LOW);
     for (i = 0; i < 8; i++)  {
         DigitalWrite(data_pin, !!(bits & (1 << i)));
         DigitalWrite(clock_pin, HIGH);
         DigitalWrite(clock_pin, LOW);
     }
     DigitalWrite(latch_pin, HIGH);
 }

DigitalWrite is my own function that manipulates the PORTn bits instead of using Arduino's digitalWrite().
3 The shift register is very close to some 110V wires. Maybe interference?
4 The 5V power supply isn't powerful enough to power the relay board and the shift register?
Any suggestions welcome.
Edit: here's a pic of what I've built. The Cat5 cable runs directly back to the Arduino.

Since cant5 has 8 wires, use multiple wires for GND and 5V. Add a large capacitor to the shift register to prevent voltage fluctuations when currents go up or down. Slow down shiftOut so the signal has more time to stabilize.

@Gerben I think I will try the capacitor. This image from the Arduino web site uses one. They use 1uf. Is that "large" enough?

NO! Don't do that. That capacitor shouldn't be there. That one of the many things wrong on the Arduino website. Just add a capacitor between GND and VCC. The largest value you have. As those relays use quite a bit of current when they get energized.

What its the output voltage of that power-adapter? How is that even connected? I was thinking you could use that to power the relays, instead of carrying the 5V over that 40ft cat5 cable.

@Gerben Yes, I am using that to power the relays and the shift register as I was not getting enough power from the Arduino. However, I just added a capacitor and preliminary testing indicates it has fixed my problem. If you write that up as an answer, I will accept it. I added it before I saw your comment about the Arduino web site. I will move it from the latch pin to the VCC pin and see what happens.

This is a very interesting whitepaper from TI describing probably exactly what you need. But there are easier options (under the answers). http://www.ti.com/lit/an/slyt441/slyt441.pdf

SPI is supposed to be used for things in close proximity to each other. See Wikipedia - Serial Peripheral Interface Bus.

The Serial Peripheral Interface (SPI) bus is a synchronous serial communication interface specification used for short distance communication, primarily in embedded systems.

(My emphasis).
At that distance, and at standard SPI speeds you are probably losing signal integrity. The default SPI speed is system clock divided by 4 (that is, 4 MHz). It's not surprising some bits go missing after 40 feet.
See my page about SPI - you can use SPI to transfer to a 595 register (as described here).
(I'm assuming you are talking about a 74HC595 shift register)
I suggest running at a somewhat lower speed - insert delays after toggling the clock pin (each way). Or use the SPI hardware at (say) SPI_CLOCK_DIV128.

The shift register is very close to some 110V wires. Maybe interference

You might also want to look at a balanced line driver (eg. RS485) - I have a page describing that.

The 5V power supply isn't powerful enough to power the relay board and the shift register?

The register won't take much power. I trust the relays are solid-state ones and not coils that you are directly driving from the 595 chip?

Also see How do you use SPI on an Arduino?

I'm not using SPI, just connecting some of the digital outputs to the shift register. I guess I didn't make it clear in my post. I just made a circuit board with a SN74HC595N soldered on it with leads going back to the Arduino and going to the relay board. Sorry if the question wasn't clear - I'm just a hobbyist.

I understand what you are doing. As you can see from my page about the 595 chip you can drive it with SPI so it is effectively equivalent. All SPI is, is a clock and a data line (and another data line in the other direction if you want it). Plus a slave select (ie. the same thing as the latch pin). My suggestion about slowing down the transfer rate still stands.

If nothing else works, consider a RS485 link. Nick Gammons forum has a useful and in depth tutorial on the subject. There is a bit of a hardware penalty - an additional Arduino or some other avr and a couple of RS485 driver chips, which is why I council "if nothing else works" in this case.

Nick posted an answer 2 days ago (from today, fri 23 Dec) also describing this option. This answer seems posted 1 day ago. If you think the same as an answer posted earlier, you can upvote it and if you have anything to add to it (without it being another solution) you can comment and/or edit the question. The problem here is that it's a bit like "spam" if everyone starts posting the same answer. Also, this would mean that votes get spread over good answers and may cause the best answer not to come up on top.

A good debugging tool in this case is a logic analyzer. It could help understand the timing characteristics for your code (and wiring).
void shift_out() {
     DigitalWrite(latch_pin, LOW);
     for (i = 0; i < 8; i++)  {
         DigitalWrite(data_pin, !!(bits & (1 << i)));
         DigitalWrite(clock_pin, HIGH);
         DigitalWrite(clock_pin, LOW);
     }
     DigitalWrite(latch_pin, HIGH);
 }

For instance, how long is the clock pulse? Does the data signal raise/fall correctly before the clock signal? What is the clock pulse frequency? How is it affected by the RC factor of the wiring.
Given that the signals are within limits you can add micro-second delays to compensate for propagation.
void shift_out() {
     DigitalWrite(latch_pin, LOW);
     for (i = 0; i < 8; i++)  {
         DigitalWrite(data_pin, (bits & (1 << i)));
         delayMicroseconds(T1);
         DigitalWrite(clock_pin, HIGH);
         delayMicroseconds(T2);
         DigitalWrite(clock_pin, LOW);
     }
     DigitalWrite(latch_pin, HIGH);
 }

Cheers!


text:
Is there any way to control current precisely with Arduino without using a DC-DC converter?
I have a circuit that consists of a torquer. Its torque is directly proportional to the current in the circuit. I want to precisely control the torque provided by the torquer and hence need to control the current in the circuit. Which is the best technique you would prefer using Arduino?

Depends on what you mean by "control current", what current and what voltage.

@Milliways I have a constant voltage source and wish to control the current in the circuit with Arduino. Can it be done using PWM?

If you want any sensible answer you need the provide detail of what you are trying to control.

@Milliways I have edited the question. I hope it has enough detail :)

There isn't much detail, like part numbers. You may as well ask if the Arduino can be used on the International Space Station. No doubt it could, but you need to provide more detail as to what it is expected to do, and in conjunction with what other circuitry.

Add a current sense resistor. Connect that to an analog pin so you can measure the current. Then change the PWM output value till the current is what you want it to be. Some people use a PID control loop for this.

The Arduino (like other microcontrollers) is a digital device. It doesn't "control current" on its own. It has outputs which can either be off or on. Off is 0V and on is 5V (assuming you are powering it from a 5V supply). The continuous current you can drawn from output pins is 20 mA.
You can use PWM to effectively reduce the power output (for example, a 50% duty cycle would be half on and half off, thus you would have 50% power).
If you drive your torquer from some sort of transistor (eg. a MOSFET) then PWM could conceivably achieve what you are wanting to do. A link to this device would be helpful. Plus, the other circuitry you have in mind.

Yes I have planned to include MOSFET switches. Could you provide details on how to do so? I am a beginner....

@yobro97. Google "using MOSFET as a switch".


text:
Feather32u4 device not accepting address 5, error -71
I'm using a Feather 32u4 bluetooth device connected
to a AM2302 temperature sensor via I/O pin
to my Linux PC via USB
Everything was working fine, uploading the code to the micro via Artuino IDE and reading the temperature on the Rapsberry PI connected via bluetooth to the Feather 32u4, until I decided to use the Raspberry PI3 to provide power feeding to the Feather (via USB).
After that attempt, I tried again to connect the Feather 32u4 to the Linux PC, but I've neve been able to do that. Everywhen I connect the Feather to the USB port of the PC it is not shown in the available serial ports of Arduino IDE and the dmesg is
[  358.028022] usb 8-2: new full-speed USB device number 6 using uhci_hcd
[  358.148026] usb 8-2: device descriptor read/64, error -71
[  358.372024] usb 8-2: device descriptor read/64, error -71
[  358.588029] usb 8-2: new full-speed USB device number 7 using uhci_hcd
[  358.708024] usb 8-2: device descriptor read/64, error -71
[  358.932024] usb 8-2: device descriptor read/64, error -71
[  359.148028] usb 8-2: new full-speed USB device number 8 using uhci_hcd
[  359.556026] usb 8-2: device not accepting address 8, error -71
[  359.668028] usb 8-2: new full-speed USB device number 9 using uhci_hcd
[  360.076038] usb 8-2: device not accepting address 9, error -71
[  360.076056] usb usb8-port2: unable to enumerate USB device

Is it possible that using the Rapsbery PI3 providing power feeding to the Feather destroyed its USB port? Why?
When I reset the Feather (using the reset button) the following is the dmesg
[53215.808027] usb 3-1: new full-speed USB device number 10 using uhci_hcd
[53215.993042] usb 3-1: New USB device found, idVendor=239a, idProduct=000c
[53215.993046] usb 3-1: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[53215.993049] usb 3-1: Product: Adafruit Feather
[53215.993051] usb 3-1: Manufacturer: Adafruit In
[53216.072814] cdc_acm 3-1:1.0: ttyACM0: USB ACM device
[53216.074154] usbcore: registered new interface driver cdc_acm
[53216.074157] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
[53225.664064] usb 3-1: USB disconnect, device number 10
[53225.904030] usb 3-1: new full-speed USB device number 11 using uhci_hcd
[53226.024024] usb 3-1: device descriptor read/64, error -71
[53226.248024] usb 3-1: device descriptor read/64, error -71
[53226.464024] usb 3-1: new full-speed USB device number 12 using uhci_hcd
[53226.584023] usb 3-1: device descriptor read/64, error -71
[53226.808022] usb 3-1: device descriptor read/64, error -71
[53227.024030] usb 3-1: new full-speed USB device number 13 using uhci_hcd
[53227.432025] usb 3-1: device not accepting address 13, error -71
[53227.544024] usb 3-1: new full-speed USB device number 14 using uhci_hcd
[53227.952021] usb 3-1: device not accepting address 14, error -71
[53227.952040] usb usb3-port1: unable to enumerate USB device

NEW EDIT
I tried the suggestion from @Majenko and the result is the following
Sketch uses 19,712 bytes (68%) of program storage space. Maximum is 28,672 bytes.
Global variables use 730 bytes of dynamic memory.
Forcing reset using 1200bps open/close on port /dev/ttyACM0
PORTS {/dev/ttyACM0, /dev/ttyS0, /dev/ttyS4, } / {/dev/ttyACM0, /dev/ttyS0, /dev/ttyS4, } => {}

<... a long list of similar PORTS rows>

Uploading using selected port: /dev/ttyACM0
/home/storassa/work/Arduino/hardware/tools/avr/bin/avrdude -C/home/storassa/work/Arduino/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -D -Uflash:w:/tmp/build133016433f76cdf39b8ff61da42c5037.tmp/Antoz.ino.hex:i

avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/home/storassa/work/Arduino/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/storassa/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory
avrdude: ser_send(): write error: Bad file descriptor
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I also tried with a
chmod 777 ttyACM0

with the same result

LAST EDIT
I tried again multiple times and eventually I was able to upload the sketch. Everything works fine now

The sketch on your Feather has no CDC/ACM interface - either because it was disabled in your code, or because the sketch has become corrupted somehow.
You need to re-flash the feather with a new sketch - but that's not going to be easy with no CDC/ACM device to access to start programming - except that you do for a short time.
You need to press reset and then upload in the few seconds you get while the CDC/ACM device is available:
\/\/\/ Reset pressed and bootloader entered \/\/\/
[53215.808027] usb 3-1: new full-speed USB device number 10 using uhci_hcd
[53215.993042] usb 3-1: New USB device found, idVendor=239a, idProduct=000c
[53215.993046] usb 3-1: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[53215.993049] usb 3-1: Product: Adafruit Feather
[53215.993051] usb 3-1: Manufacturer: Adafruit In
[53216.072814] cdc_acm 3-1:1.0: ttyACM0: USB ACM device
[53216.074154] usbcore: registered new interface driver cdc_acm
[53216.074157] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
*** UPLOAD RIGHT NOW!!! ***
*** You get about 9 seconds, because... ***
\/\/\/ Bootloader times out and your corrupt sketch runs \/\/\/
[53225.664064] usb 3-1: USB disconnect, device number 10

you can find the result in my new edit. Can I use the RST pin in this case? I found this in the operating guide of the Feather "The RST pin is the factory reset pin, which is also rarely used, but you can use it to set the module back to the factory default settings if it gets really messed up".

As you can see on my last edit, everything works fine now. Thank you very much. I couldn't get to this solution without your help


text:
Store data in flash/EEPROM and process it in parallel
I want to store incoming data in flash or EEPROM and then apply FFT or some other method to detect frequency and intensity.
I am taking sound through microphone amplifying it with an LM741 and giving this amplified signal as input to an Arduino and then processing it at the same time.
But the problem is that the time taken in running the code is interfering with the sampling rate. I want to store say 50 inputs in flash and then process these 50 numbers, while at the same time the next set of 50 numbers is being stored, so that I can have data stored at a constant sampling rate.
Also how can I store data continuously? Because if I do this in loop() won't it again have time lag due to rest of the code?
I am new to Arduino, so please give details or some link to help me understand.
Thanks.

Writing to EEPROM is probably too slow. Just store it in memory. You can set the ADC to run in free running mode, where it will continually measure the voltage. You can then attach a function to the interrup so it run whenever a conversion is ready. You can store the values in a ring buffer. So the interrupt will fill the buffer with new data, while the loop will process the data and remove it from the buffer.

But will I be able to measure the time between any two reading? I want to get the frequency and so I need the time between any two data which I intend to keep fixed. So to be clear, I should store data by setting clock frequency and using free mode in setup and attach a function (to process data) to interrupt when the ring buffer is full, and do nothing of this in Loop?

Time between readings is constant in free running mode. I think you can even use a timer to trigger ADC conversions if you need a specific sampling frequency (instead of changing the ADC clock prescaler). You don't need an interrupt for when the buffer is full. Just have the loop check with a if statement if there is enough data in the buffer to start prosessing it. Ideally you'd process the data as it is coming in instead of waiting for a lot of data, and the process I'll this data in one chunk. But this depends on your situation.

Thanks a lot. I am going to read more about it and try to implement it.

A common method of overlapping data input with data processing uses double (or multiple) buffering.  For example, one of two buffers is processed in the foreground (that is, in the loop() routine) while another buffer is filled in background (via interrupt handlers).  Each time a buffer fills, the usage of the two buffers swaps: that which was being processed now refills, while the recently-filled buffer gets processed.  To make this work, buffer processing must take less time than buffer filling.
For recording conversion times, because free-running ADC conversions each take the same amount of time, you can just save fill-start and fill-end times with each buffer, and interpolate to find out reading times.
If you plan to process audio data at near-normal speeds, it's likely most Arduinos won't be fast enough to keep up.  However, using an Arduino Due probably is feasible.  The Due is based on an ARM Cortex M3 processor with 72 MHz operating frequency, 32-bit arithmetic, large RAM (for an Arduino), etc.
An alternative method of processing audio data is to use a frequency analysis chip.   Here is a low-end example:  The MSGEQ7 Graphic Equalizer Display Filter is about $5 in an 8-pin DIP package from sparkfun.com.  Apparently, it continuously measures peak spectral intensity in each of seven frequency bands, and can read the peaks out perhaps a thousand times per second.  Audio goes in on the "Audio in" pin.  A Reset pin resets an output-multiplexor counter to zero.  Each time after you clock a strobe line, a band's reading is presented as an analog voltage on a "DC out" output line; the band's peak reading is decayed about 10%; and the multiplexor advances one band upward in frequency, rolling over from highest to lowest every seven strobes.

What I want to do is store incoming data from in flash or eeprom

No, for your application you absolutely do not want to do that. You want to use RAM instead.
The Arduino has three kinds of memory:

Bytes in RAM (also called SRAM) can be written an unlimited times and written very quickly. RAM is designed for short-term storage of information while a sketch is running. The contents vanish when the Arduino is turned off, but this isn't a problem for you unless you need to process previously read information later on after the Arduino is turned back on. An Arduino Uno has 2048 bytes of RAM and all your C/C++ variables must fit in that.
An EEPROM byte can be written around 100,000 times; writing it is much, much slower than writing a RAM location. This makes it very bad for doing intensive processing, as opposed to, e.g., just storing configuration variables that are rarely read. EEPROM is designed for storage of information across power cycles of the microcontroller; unlike RAM, previously written data are still there to be read when the Arduino is powered on. An Arduino Uno has 1024 bytes of EEPROM; this is only used when your code or library code explicitly requests data be written to or read from it.
Each block of flash memory can be written around 10,000 times; writing it is much slower than RAM, though it can be read very quickly. Flash storage is designed for storing programs, not data; it's the memory from which instructions are read, though you can with care store "constant" data in it too. It's only changed when you upload a sketch via USB.* An Arduino Uno has 32768 bytes of Flash memory and your program and any constants you store in Flash must fit in it.

* Not technically true, but if you know how to use Flash for runtime data storage, this answer isn't providing you any useful information. :-)


text:
Problem with uploading LUFA MassStorage .hex file to Leonardo
I have been trying to make my Leonardo board to work as a USB device. So I started with compiling the open source LUFA USB library demo "MassStorage" for the Leonardo board settings. Since I'm using Mac OS, I downloaded the "AVR Tools" software to upload the hex file to the board(I didn't want to use the ISP protocol to flash. Because it is not possible to remove the chip from the board to make the correct ISP circuit connection). Anyway I was managed to flash the board. But afterwards it is not detectable by the computer. The serial port is not detectable. This proves it flashed something. Afterwards I flashed it again with the original bootloader file and it was identified as before. I'm a beginner to Arduino programming and forgive me if I'm asking elementary question. What am I doing wrong?

Cannot say for sure, but if you was able to flash something, then loose functionality, but was still able to flash it back, then there is possibility, that you flashed the application part (with would-be-bootloder code), not the bootloader part (and the old bootloder in bootloader part then enabled you to flash back something sensibe).
bootloader is resposible for saving application in memory in process of flashing and running the application after that, or in case you just connect the board and do not start flashing it just after (maybe software/transmit) reset.
if you save bootloader to application part of memory, it is highly possible, that it would not do anything good, as the original bootloader would still run first and setup your board and the application (with new bootloader code) would try something futile (and maybe have bad addresses already, as it is suppose to be runned in bootloader place, not in application).
There are two parts of flash memory in arduino - one for application, other for bootloader and they have different use, even if they are just different parts of one big flash area. So make sure, what you actually updated and how was the hex compiled (for which address)

Thanks for your answer. This was my actual problem and I solved it before you posted this. But it explains well, what took me some research to understand. I solved the problem by using an external programmer to flash the uc. And also I was not using the latest lufa library for compiling the hex file. This was also part of the problem. Just mentioned it to complete your answer :)


text:
Creating variable inside if statement (conditional signed vs unsigned int)
I have an SPI chip that I would like to read out with an Arduino. Some of the registers are signed int others are unsigned int. I am writing a function to read any register.
A simplified version:

readRegister(byte thisRegister, char type) {

  if(type == 's'){
    signed int result;
  }else{
    unsigned int result;
  }

  // take the chip select low to select the device:
  SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
  digitalWrite(SlaveSelectPin, LOW);

  //now get the value
  result = SPI.transfer16(thisRegister);

  // finish up
  digitalWrite(SlaveSelectPin, HIGH);
  SPI.endTransaction();

  // return the result:
  return (result);
}

readRegister(0x4B87,'s')  //read signed int register
readRegister(0xB357,'u')  //read unsigned int register

However this doesn't work since the variable result is created inside the if statement so the scope is wrong. I get error: 'result' was not declared in this scope on the SPI.transfer() line.
How to solve this?

You can't have a function that return two different types of variable. Easiest solution would be to use two function; readRegister and readRegisterSigned. Alternatively, since SPI.transfer only returns an 8 bit value, and int is 16 bit, you could just use signed int for both returned values.

Sorry, I have editted the question so it reads SPI.transfer16, my mistake.
It seems like a horrible waste of repeating code to write 2 allmost identical functions (the real function has more lines).
Could I return the result as signed long no matter what the original type was?

A long would work. You could also implement the readRegisterSigned function as signed int readRegisterSigned(byte thisRegister){return (unsigned int)readRegister(thisRegister);}. Or just typecast at the calling end. I.e. (unsigned int)readRegister(0x4B87,'s');

Hmm, I understand what you are suggesting I think. But I don't follow the steps of your first example. Is this correct?: I read in the bits of an signed integer (from the SPI slave) into an unsigned int variable result,I return that from my function readRegister and I cast that return to unsigned again, but then I return it from a function that yields a signed int. And it gives me the correct value? In what steps is the value actually changing?

'cast' and 'conversion' are not the same thing, though casting native types may involve conversion. If you cast between signed and unsigned types of the same size, you are really only advising the compiler to treat this value as being of the new type. In the expression (uint8_t)signedVariable, you are really telling the complier: "trust me on this: signedVariable's value is really 8-bit unsigned".

Sorry. It should have been signed int readRegisterSigned(byte thisRegister){return (signed int)readRegister(thisRegister);}. My bad.

You could try something like this:
int16_t readRegister(byte thisRegister) {
  int16_t result;

  // take the chip select low to select the device:
  SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
  digitalWrite(SlaveSelectPin, LOW);

  //now get the value
  result = SPI.transfer16(thisRegister);

  // finish up
  digitalWrite(SlaveSelectPin, HIGH);
  SPI.endTransaction();

  // return the result:
  return (result);
}

uint16_t readUnsignedRegister(byte theRegister) {
  return (uint16_t) readRegister(theRegister);
}

Another alternative is to define a "universal" data type, i.e. a union and necessary cast operators.
union univ16_t {
  uint16_t as_uint16;
  int16_t as_int16;

  univ16_t(int value)
  {
    as_int16 = value;
  }

  operator uint16_t()
  {
    return (as_uint16);
  }

  operator int16_t()
  {
    return (as_int16);
  }
};

This allows the function to have the following form:
univ16_t readRegister(byte thisRegister) {
  int result;

  // take the chip select low to select the device:
  SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
  digitalWrite(SlaveSelectPin, LOW);

  //now get the value
  result = SPI.transfer16(thisRegister);

  // finish up
  digitalWrite(SlaveSelectPin, HIGH);
  SPI.endTransaction();

  // return the result:
  return (result);
}

With the two possible assignments.
uint16_t reg1 = readRegister(...);
int16_t reg2 = readRegister(...);

Cheers!

It would be better to have the main function returning unsigned int because otherwise you are loosing precision and the compiler will winge.

Based on the comments by Gerben and JRoberts, this is the answer I distilled (correct me if I misunderstood):
Since you need to define a return type of the function anyway, you cannot have a function returning one of two datatypes based on the input.
So there are basically four approaches:

Write two seperate functions
Have only one function and use datatype casting on the result
Combination of the above, where the second function is only a wrapper for the first function but with datatype casting.
Return both unsigned int and signed int register values as a signed long

Some extra info:
2.
When you cast between signed and unsigned of the same size, you are not changing the bits, you are just changing the way they are being interpreted. So that would work perfectly.
my_signed_register = (signed int)readUnsignedRegister(0x4B87)
my_unsigned_register = readUnsignedRegister(0xB357)

3.
 The same thing can be done in a function:
signed int readSignedRegister(byte theRegister) {
  return (signed int) readUnsignedRegister(theRegister);
}

(Also see the answer of Mikael Patel)
4.
If you want to use one function only, you could set the return type of the function to signed long. Because to represent both signed and unsigned ints you need signed long. You then read in the bits from the SPI.transfer in signed (or unsigned, whatever you like) and then change to signed long based on the type given in the function call 's' or 'u'.

Signed ints are capable of being stored in unsigned int, but unsigned its are not [technically] capable of being stored in signed ints if the compiler is being pedantic.  This is because an unsigned int can store a number between 0 and 0xFFFF where as a signed int can store numbers between -(0x7FFF) and 0x7FFF
So if you have a compiler that is doing type checking then you will get problems if you cast an unsigned int to an int, because you might loose data.
That said an unsigned in, int, char, long, float or double is just a series of sequential bits held in memory, so if you know what you are doing you can convert a char into an unsigned long and back again.  Or you can go the whole hog and store all your variables as void*.
So to answer the question I think you function should be this:
uint16_t readRegister(const byte theRegister);

If you want to read a value then you should just call:
uint16_t reg1 = readRegister(0x4B87);
int16_t  reg2 = static_cast<int16>(readRegister(0xB357));

If you really want a separate function then you might be better just #defining it.
#define readSignedRegister(r) {static_cast<int16>(readRegister(r))}
// And you would call it like this.
int16_t  reg2 = readSignedRegister(0xB357);

EDIT to correct the type typo and remove word aligned.

You said: “word aligned”. Not on the AVR-based Arduinos. And it's int16_t, not int_16.

Thaks @EdgarBonet - corrected.

One final option that isn't mentioned in any of the above solutions - Create a function that returns both as separate parameters.
I'm not sure why you would ever do this over Mikael Patel's solution, yes it's then a single function but it's not as nice to use. But it is a possible option.
The only possible advantage in using this pass by reference method of returning the value is that it allows the option for the read function to return a flag indicating whether the read failed or not (timeout, invalid address etc...). And even then it would still be more logical to have two functions, one for signed and one for unsigned.
void readRegister(byte thisRegister, int16_t *signedValue, uint16_t *unsignedValue) {

  unsigned int result_u;

  // take the chip select low to select the device:
  SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
  digitalWrite(SlaveSelectPin, LOW);

  //now get the value
  result_u = SPI.transfer16(thisRegister);

  // finish up
  digitalWrite(SlaveSelectPin, HIGH);
  SPI.endTransaction();

  if (signedValue)
    *signedValue = (int16_t)result_u;
  if (unsignedValue)
    *signedValue = result_u;
}

void someOtherFunction() {
  uint16_t unsignedRead;
  int16_t signedRead;

  readRegister(0x4B87,&signedRead,NULL);  //read signed int register
  readRegister(0xB357,NULL,&unsignedRead); //read unsigned int register

  //read the register as both signed and unsigned (fairly pointless)
  readRegister(0xA55A,&signedRead,&unsignedRead);

  //read the register and throw the result away
  readRegister(0xA55A,NULL,NULL);
}


text:
Hardware damage from executing tight polling loop over extended periods of time?
I want my project to be standing by at the ready for months and years at a time, so I started writing my code to throttle back from polling at delayMicroseconds  to just delay. Like, after 15 minutes with no user input, switch from 10 microsecond delay intervals to 10 millisecond (or even 10 second intervals). I wonder if spinning its wheels at warp speed for months on end will wear a path in the circuit pathways? This has got to be a stupid question (or at least make someone chuckle), but I'm really 50/50 at this point: worth the effort for the extra code or won't make a lick of difference? (I know there's my implementation and then there's the right one, but this is where I am right now. FYI, I went with 17 GPIO's in parallel to link my Pi to my teensyduino. add 17 optocouplers, hot glue, hinges, scavenged enclosures etc and this thing looks ridiculous.  But I LOVE IT! (It's a mouse that I control over the web)
EDIT
Although I didn't mention any concerns about using batteries, their mention didn't really detract from anything. Rather, I welcomed their inclusion because I realized that I had overlooked things more fundamental. I'm always telling others how important ventilation can be and the impact heat can have, but it went right by me this time!
I do value and appreciate the feedback I have gotten. I don't think I will be writing any code to vary polling speed after timing out. But I would still like if someone wanted to directly answer the specific concern I had when posting this question: "At certain times, my program waits for a GPIO pin to change states. I am using the polling method to determine the status of the pin, and I am using this bit of code to do so:
do
{

} while (digitalRead(pin#) == 0); //wait for pin to go high

So, my question is, "Does it make any difference at all, in terms of wear & tear or stress placed on the CPU, how many loops I choose to make in one second? I'm considering something in the range 0.1Hz -> 100kHz  Assuming that I keep heat under control and other vital parameters within their nominal operating levels, is it true that the frequency I choose won't make a bit of difference, one way or another?"
Thanks in advance for any interest given to this question.

You are just reading inputs? Then I don't see any point in increasing the interval between reads. (Also note that delay, will still keep the CPU busy. It will just continuously poll the time and see if enough time has passes). PS there isn't really a right way. PSS sounds like an awesome setup you have. Maybe ugly but working!

@Gerben  I have the teensyduino standing by waiting for instructions from the RPi. When an input changes state, then read the other pins for the screen coordinates (up to 1920 x 1080). My first impression was that doing 10k to 100k loops a second was more CPU load, but then its clock speed doesn't change so it just the same, but then, still there's a factor of 10,000 when comparing activity. So I don't know what to think. It's hard for me to imagine what the physical reality is like at that scale. I just keep imagining the difference between 100 RPM and 100,000 RPM. SILLY!! (or is it?)

Yes, it made me chuckle, that's for sure. There is no difference in doing a delay compared to reading an input as far as the CPU and power consumption are concerned. The CPU doesn't care what it is doing, unless you specifically tell it to go to sleep it will always be "spinning its wheels".

As for the car analogy. Delay is like going 100,00 RPM during checking the inputs, and then pressing on the clutch, but keep the engine going at 100,000 RPM. There is no difference. Delay doesn't halt the CPU or something.

There's nothing to save except battery charge (if your system even uses a battery). It will take just as much energy to delay() as it would to keep polling. The only way to save energy is to put the processor to sleep instead of delaying. And polling will be so brief that you might as well keep the sleep time short, too.
You probably don't need 10 uSec poll intervals; I should think your mouse would be plenty responsive with 1 mSec intervals. If polling takes, say, 100 uSec (and that's a total guess) and you sleep the processor for the other 900 uSec, you'll cut the energy use by 90%. If you don't need to save energy, it won't matter whether, or how long, you delay.
Update:

"Does it make any difference at all, in terms of wear & tear or stress
  placed on the CPU, how many loops I choose to make in one second? I'm
  considering something in the range 0.1Hz -> 100kHz Assuming that I
  keep heat under control and other vital parameters within their
  nominal operating levels, is it true that the frequency I choose won't
  make a bit of difference, one way or another?"

Yes, it is true. Your CPU can run full speed continuously, safely. It won't overheat from continuous running. Only if some part of your project is trying to draw too much current through the CPU; then that will cause heating, but the CPU polling a bunch of inputs is well within its specs.

For many applications within the realm of Arduino software & hardware development, the only practical concern is to limit the need to write to non-volatile types of memory.  Non-volatile types of memory, such as that which stores the Arduino program, do have a finite number of write cycles.  However, it is in the 10s (perhaps 100s) of thousands of writes.  So is not a concern to most developers.
Running code, however, does put a load on the processor's power source.  First we need to understand that a switch in a modern processor require only a minuscule amount of current if left alone.  But if asked to change from a 0 to a 1 or 1 to 0, the current spikes.  In processors pushed to their limits with 100s of thousands of switches, this extra current turns into heat which must be mitigated less damage is done.
Fortunately, most processors used in Arduinos are not pushed to their limits. So this is rarely a concern. To be clear, the processor chip used on most Arduinos will mostly likely not need a heat sink or fan.
However, even for an Arduino not pushed to its limits, this extra power demand is devastating to the long term life of portable battery operated devices.  Programming an Arduino to extend battery life is by no means a trivial task.  And certain processors (Arduinos can be made with many different processors) are orders of magnitude better at this then others. But, since most Arduino applications are powered from mains, this too is of little concern.

No, there won't be any writes to any non-volatile locations. Maybe store some macros there down the road. And there aren't any concerns about battery life since it draws power from the host USB port it plugs into (in a device running off AC mains). I'm itching to accept your right away if you could just add a line that says (pretty much verbatim) '

Hmmm I hit 'post

Apparently I can't edit my own comments... Anyway, I'll make sure the heat doesn't pose a problem (I've got all sorts of old cooling fans and heat sinks).  If I could just ask  you to add a line reassuring me that "there's no need to worry, that chip will be just as happy polling an input pin 100 times a second as it would doing 100,000" I would be most grateful and happy to dispatch your well earned green check-mark! Thanks in advance.

The processor chip used on most Arduinos will mostly likely not need a heat sink or fan.  I'll add this to the answer.  I believe everyone can only edit a  comment for 5 minutes.  My rule of thumb is you don't have a heat problem until the chip feels very warm to the touch.

I wasn't allowed to edit for any amount of minutes. Not so much a criticism as surprise.  I just need to be more careful of the enter key!

You have about 5 minutes to edit a comment. After that it is committed. The point is, I think, that editing a comment hours later makes follow-up comments make no sense. See Can the timeout on editing comments please be increased?

If you accidentally hit Enter you can either: 1) Quickly edit it and finish what you were saying; or 2) Delete the comment immediately and then retype it with what you really wanted to say.


text:
Environment Variable to change build
Is there a way to get the build to see an environment variable so that all the files can be built differently with one Environment variable change.  Such as
#ifdef UseFirstDir
    #include <C:\MyFirstDir\ImportantIncludes.h>
#else
    #include <C:\MySecondDir\ImportantIncludes.h>
#endif

Not environment, no.
If you have access to the compilation command line you can do the equivalent of #define from there:
avr-gcc ... blah blah ... -DUseFirstDir

That is most effective if you are using a Makefile build system rather than relying on the Arduino IDE which doesn't give you access to those kind of things without modifying the core configuration, which isn't nice, and certainly is neither permanent nor flexible (doesn't survive upgrades to new versions, and isn't easy to turn on and off at will).
A better IDE, though, can do it. Facilities for setting control flags like that exist within UECIDE and it's possible to tie them to menu entries to make switching options on and off easier. It's not documented how to do it though (yet).
Or you can just have a list of #define options at the top of your sketch:
/* Uncomment this to use the first directory. */
// #define UseFirstDir

// .... later ....

#ifdef UseFirstDir
    #include <C:\MyFirstDir\ImportantIncludes.h>
#else
    #include <C:\MySecondDir\ImportantIncludes.h>
#endif

I have Cygwin, but the command line (bash or dos) is not finding avr-gcc.  The second option seems best for now.

@Gregg I have just blogged about adding menu entries for a sketch in UECIDE..


text:
Where do I put the cables from my soldered l293d onto the arduino uno/arduino pro mini? (Drone)
I am trying to create a drone but I am struggeling a bit with the components and the schematic. I have 4 small drone motors from hubsan x107 and i have soldered their wires on a l293d driver like this below:

As you can see i have also soldered jumper cables on the l293d as well and I now look to put them on the arduino uno or a arduino mini pro (i have both at home) but I am not sure where to put these cables in order to make this work. I have typed them out as you can see on the picture and named them: Jumper cable 1, 2, 3, 4, 5, 6, 7 and 8.
This is the hardware I use:
Motor: http://www.banggood.com/Hubsan-H107C-X4-RC-Quadcopter-Spare-Parts-Motor-H107-a23-p-87563.html
Arduino uno
L293D
Cables
Would a setup like this work if I put the jumper cables on the correct pins on the arduino? And if so where on the arduino do i need to connect each wire?
Thanks a lot!!

I did not down vote you.  But will try to explain why it likely happened.  Your question is way too broad - actually to the point it  can not be answered.  All Arduino project are based on software / firmware.  And if there is none in the question, then there really can be no project.

Appreciate the feedback! Updated the post with the motor i use. Other then that It is a simple arduino uno board i work with along with the L293D driver that I also linked an image about. And of course cables

Hint: Most people who write code (drivers?) for the Arduino leave documentation explaining how to use their drivers.  This is to say, you are still leaving out a key piece of information in your question:  What driver are you using?

L293D driver? Well i only use x4 motors, the L393D and a arduino uno so I guess that is my driver haha :P

You are missing a huge piece.  There's bare metal programming.  Which is very difficult. But the Arduino paradigm abstracts you from that.  So there is at least the PWM drivers that come with the Arduino software package.  So you need to connect up to the pins that the Arduino will support with the built in PWM Arduino driver. But to control 4 motors for flying is going to take a lot more than that.  What are you using?  Are you writing your own software?

st2000, I partially agree, I think it's a valid question if you ask how to wire up the circuit. It doesn't need any code for that yet. But I agree: "would this setup work" is too broad, there are many points that may fail.

simulate this circuit – Schematic created using CircuitLab
The battery needs to be the right voltage for your motors. There are no specifications on the page you linked to at all, so your job now is to find out what your motors are and what voltage they run from.

The datasheet has an interesting addition to the ground prins: "Device ground and heat sink pin. Connect to printed-circuit-board ground plane with multiple solid vias."

@Paul Yeah, I was thinking of mentioning that. Not sure if the OP has a driver on a breakout (in which case it doesn't matter) or if he has directly wired jumpers to the chip pins - in which case he may want to solder on some lumps of metal as well to act as a heat sink...

Also, I'm curious if you could toggle the enable pin to get "active breaking" then it may be worth to not directly wire them to vcc.

@Paul That may be vaguely possible, but I wouldn't want to do that through an Arduino IO pin.

@Paul Actually that might be ok. I think the EN would be isolated from the back EMF from the motor.

Hmm, the outputs can be "high", " low" and "high impedance". According to the "function table" in the TI datasheet. But I was wondering if high impedance would cause breaking.

About back EMF, the functional block diagram does show diodes outside the chip itself, but the description says: "high voltage outputs for inductive load driving", so that's indeed not very clear. So when using this part, rather check with TI or just take the neccesary precautions (reverse diode).

@Paul Or even better, invest in a proper Arduino shield instead of dead-bugging it.

Agreed, but I was thinking of making an "all in one" robotics board that could be used as an educational tool. So I was wondering if it could be made breaking, but I guess that's a whole other question altogether (and I also think I won't have the time for this in naar future :p). I'll stop here to avoid further discussion that's more aimed on my question as on the person who posted this, though it can be interesting if he needs breaking on his quadcopter.

@Paul Braking is supposed to be done using just two motors per driver (1+2 and 3+4) with the input pins controlling the direction and the EN pins controlling the speed.