text:
74HC595 with 4 digit 7 segment display. Any way to get rid of leading zeros?
I am working on an Arduino based temperature reader using a DS18B20 temperature IC. The display is a 4 digit 7 segment LED common anode display driven by a single 74HC595 shift register. Currently, it is setup to read a variable assigned with a number to test the display portion. It displays to the tenths decimal place I am having troubles trying to get rid of the leading zeros. When the variable 'tempF' is assigned a number such as 12.3, the display yields 012.3 and if the variable is assigned a number such as 1.2, the display will yield 001.2. At the same time, I was wanting to have it place a minus (-) sign when the number is less than zero. So far, the examples I'm finding on the web don't seem to match into the code I'm currently working with or don't work at all. I haven't been able to locate a sketch that seems to work for this type of setup. I have posted below, the code I am working with. The original code was obtained from the link provided in the sketch.
The sketch there does not provide the means of reading negative temps or suppress leading zeros.

   /*
 * www.pial.net/arduino-controlling-a-4-digit-seven-segment-display/
 */

//#include <OneWire.h>
//#include <DallasTemperature.h>

//#define ONE_WIRE_BUS 2

//OneWire oneWire(ONE_WIRE_BUS);
//DallasTemperature sensors(&oneWire);
//DeviceAddress insideThermometer;

const int ledPin =  13;// LED connected to digital pin 13
const int latchPin = 8;//Pin connected to ST_CP of 74HC595
const int clockPin = 9;//Pin connected to SH_CP of 74HC595
const int dataPin = 10;//Pin connected to DS of 74HC595

const int digitPins[4] = {
  3,4,5,6}; //pins to control the 4 common anode pins of the display

const byte digit[10] = //seven segment digit bits
{
  B00111111, //0
  B00000110, //1
  B01011011, //2
  B01001111, //3
  B01100110, //4
  B01101101, //5
  B01111101, //6
  B00000111, //7
  B01111111, //8
  B01101111, //9
//  B00000000, //all segments off
//  B01000000 //-
};

int digitBuffer[4] = {
  1};
int digitScan = 0;
int soft_scaler = 0;
float tempC, tempF;
int tmp;

void setup()   {
  TCCR2A = 0;
  TCCR2B = (1<<CS21);
  TIMSK2 = (1<<TOIE2);
  TCNT2 = 0;
  Serial.begin(9600);

  pinMode(ledPin, OUTPUT);
  for(int i=0;i<4;i++)
  {
    pinMode(digitPins[i],OUTPUT);
  }
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

//  sensors.begin();
//  sensors.getAddress(insideThermometer, 0);
}

ISR(TIMER2_OVF_vect) {
  soft_scaler++;
  if(soft_scaler==15)
  {
    refreshDisplay();
    soft_scaler = 0;
  }
};

void refreshDisplay()
{
  for(byte k=0;k<4;k++)
  {
    digitalWrite(digitPins[k], LOW);
  }
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, B11111111);
  digitalWrite(latchPin, HIGH);
  delayMicroseconds(50);
  digitalWrite(digitPins[digitScan], HIGH);

  digitalWrite(latchPin, LOW);
//  if (digitScan==3)
//  {
//    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B00000000)); //inserting the blank
//    }
//    else
//  {
//    shiftOut(dataPin, clockPin, MSBFIRST, digit[digitBuffer[digitScan]]);
//  }

  if(digitScan==1)
  {
    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B10000000)); //inserting the dot
  }
  else
  {
    shiftOut(dataPin, clockPin, MSBFIRST, ~digit[digitBuffer[digitScan]]);
  }
  digitalWrite(latchPin, HIGH);
  digitScan++;
  if(digitScan>3) digitScan=0;
}

void loop()
{
  digitalWrite(ledPin, HIGH);
  boolean sign = false;
  //sensors.requestTemperatures();
  //tempC = sensors.getTempC(insideThermometer);
  //tempF = DallasTemperature::toFahrenheit(tempC);
  //tmp = int(tempF*100);
  tempF = 0.2;
  tmp = int(tempF*10);

//   if (digitScan == 4 ){
//    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitScan] | B00000000)); //inserting the blank
//    }
//    else
//  {
//    shiftOut(dataPin, clockPin, MSBFIRST, digit[digitBuffer[digitScan]]);
//  }

//if (tmp < 0){
//sign = true;
//tmp = abs(tmp);
//}

//if (digitScan == 3) {
//  if (tmp < 0){
//    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B01000000)); // outputs minus sign
//  }
//  else {
//    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B00000000));
//   }

//  tmp = abs(tmp);
// }
//  else if (digitScan == 3 && digit[digitScan-1] == 0) { // writing on the second display (tens; if there are none, outputs nothing)
//     shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B00000000));
//   }
//   else if (i == 2) { // writing on the third display, where decimal point is needed
//     shiftOut(data_pin, clk_pin, MSBFIRST, digit[digitBuffer[i-1]]);
//   }
//   else { // writing on "other" displays (in fact fourth display AND seecond display only if there are some tens)
//     shiftOut(data_pin, clk_pin, MSBFIRST, digit[digitBuffer[i-1]]);
//   }

  digitBuffer[3] = int(tmp)/1000;
  digitBuffer[2] = (int(tmp)%1000)/100;
  digitBuffer[1] = (int(tmp)%100)/10;
  digitBuffer[0] = (int(tmp)%100)%10;
  Serial.print("number assigned to the variable 'tmp' = ");
  Serial.println(tmp);
  Serial.print("number assigned to the variable 'tempF' = ");
  Serial.println(tempF);
  digitalWrite(ledPin, LOW);
  delay(500);
}

The commented out commands in the sketch were attempts to remove leading zeros and add a minus sign when needed but failed. I have also posted a schematic of the project as well. A 74HC595 was used in this manner to free up pins to be used later in a deep freezer project.
I am by no means an expert programmer but if anyone could help me out or provide some insight on how to solve this problem, it would be most appreciated.

Please edit your question (click "edit") and mark the code as code.  When including code in a stackexchange question or answer, first paste the code into the question or answer editing box; then in that editing box, highlight the code and press ctrl-k. Or highlight the code and click the {} icon in the toolbar at the top of the editing box. To highlight text click-drag across it or use the arrow keys while holding the shift key.

First figure out how you would do it by hand. Then translate that into code.

@IgnacioVazquez-Abrams - For me, easier said than done. I've been trying to find answers to this for a very long time with no luck. That or I don't know what exactly to search for to find the answers.

Remembermyname, I didn't downvote, merely commented, but if you hadn't fixed it, I might have downvoted tomorrow.  Anyhow, I upvoted after you fixed the code formatting.   Now your question has 1 upvote and 1 downvote.

@jwpat7 You're right, it was while before I caught my own error and had to correct it. If I had seen it, I would probably have downvoted it as well. I apologize, I didn't mean to accuse. I've removed the unwarranted comment.

Any way to get rid of leading zeros?

Sure but two conditions have to be true:
1) you have the font information for "blank"; you need to un-comment it in your code for that.
2) you need to get rid of leading zeros, after having calculated the display buffer.
  displayBuffer[0]=(displayBuffer[0]==0)?FONT_BUFFER:displayBuffer[0]; //eliminate leading zero for displayBuffer[0]
  displayBuffer[1]=((displayBuffer[1]==0) && (displayBuffer[0]==FONT_BUFFER))?FONT_BUFFER:displayBuffer[1];
  ...

edit:
here is an example implementation of the concept from above, on a PIC12F675 driving two HC595. The number to be displayed is "12" on a 4-digit display. Blanking done on the first three digits -> you can confirm that by looking at the value of the display buffer lRAM[4]. 0x11 is my blank designator.
The partial display of '1' is due to multiplexing. Code largely based on what I wrote here: https://dannyelectronics.wordpress.com/2017/03/03/driving-7-segment-leds/, modified to drive over HC595s.

it should work on any mcu with minimum changes.
edit 2: here is your code driving a CC display directly. the number to be displayed is 1.23, with the leading zeros in the most significant 2 digits taken out.

I was aware of the uncommenting parts. They were previous attempts that didn't work as explained earlier. I tried the code snip before the display portion with it changed to match the variables in the sketch but I'm not certain of 'FONT_BUFFER'. Please elaborate.

Is there an example anywhere that utilizes this? I've been going in circles on google for far too long. As if it were some kind of state secret. :/

I mean, this looks like a fairly straight forward answer. I tried to add shiftouts to use the masks (albeit poorly) and of course, they don't work. I'm just not aware why.

Well, this appears to be a microchip example. I'm certain that the principles are the same but I haven't been able to get this to work at all.

authors: Алдын Байкара


text:
7805 powered Atmega328 Stops working when input of 7805 exceeds 7volts
I am developing a circuit with atmega328, the MCU is powered by a LM7805.
The input of 7805 is given by a variable supply. Till the input of 7805 is 7volts, the output voltage is 4.9volts and current is around .75amps. Now if the input voltage of 7805 is increased, the current also increases and the MCU stops working(sometimes work with being reset after a few seconds), please help me out guys... i need to connect those circuits to my car battery, so it must work with 12volts.
I added capacitors and diodes as per Majenko mentioned. Now the situation is a) The circuit is working at 12V, b) With single C817 , output voltage of mcu is 3.5V, c)I used 56 ohms resistance, which is giving 1.2V to the input of C817, d) The Collector to Emitter resistance of C817 is 1520 ohms when turned on, this is creating a voltage drop of 3volts. e) This output is turning the led on, but being unable to switch the relay.
Circuit Upate
This the modified circuit, which solves the problem. But i have some questions, in the modified circuit if BC547 is used then its not working because the collector voltage which should be around 0.2 remains 1.8 volts, but replacing the BC547 with BC337 solves the problem(Collector voltage becomes around 0.3).

Have you added capacitors ? Reset problems may be attributed to inadequate current supply. Refer : http://www.circuitdiagram.org/images/12-to-5v-converter-circuit.gif

Maybe thermal protection? Voltage drop on the regulator is 2 volts if you have 7V input and that means  2V * 0.75A = 1.5W  turned into the heat. That means heatsink might be needed to work properly.

i have uploaded the circuit diagram, please take a look, and i will try all the hints mentioned above..

Do you have a phobia of capacitors? I can see at least 8 that are conspicuous by their absence - maybe more. You seem to have an aversion to diodes as well.

yeah, its embarrassing , i didnt think that capacitors will be that much important. Anyways i am gonna try it again after attaching the capacitors and diodes.

If you are simulating (vs. real parts on a breadboard or PCB), how a BC547  works vs a BC337 probably depends on what part suffixes you specify: BC547A, B, or C vs BC337-16, -25, or -40.  BC547C have higher gain at 100 mA collector current than BC337-16 and -25, but lower than BC337-40.  With real parts, it depends on which you buy and use.

okk, got you , but my new schematic is consuming all total of 840ma (with two output & relays) when they are turned on. Now if i use all six of them it  will consume more than 1amps, any ways to reduce them??? may be increasing the resistances or something??

There are a number of basic but vitally important components missing from your schematic. Namely input and output capacitors on the voltage regulators, which would result in oscillation and thus overheating (which would then shut them down through thermal overload), decoupling capacitors on the main chip, reverse biased diodes across the relay coils (maybe as well a small capacitor would be beneficial in parallel), and resistors to limit the current through your opto isolators.
Here is a version of your schematic with the missing components added in red. I have omitted the values - your job is to read the datasheets and work out the correct values to use.

Thanks @Majenko for your help, I am gonna try it and give you feedback.. thanks again.

I added capacitors and diodes as per Majenko mentioned. Now the situation is a) The circuit is working at 12V, b) With single C817 , output voltage of mcu is 3.5V, c)I used 56 ohms resistance, which is giving 1.2V to the input of C817, d) The Collector to Emitter resistance of C817 is 1520 ohms when turned on, this is creating a voltage drop of 3volts. e) This output is turning the led on, but being unable to switch the relay.

@SHILADITYADEY Have you got your diodes the right way round?

yes i have, and i have changed the circuit. There is some issue with the modified circuit tough, please check it

@SHILADITYADEY Are you relying solely on simulations for this, or do you have an actual real physical circuit?

@SHILADITYADEY Re your new circuit: you should have a pull-down resistor on the base of Q1.

I have not implemented the new circuit physically yet, what should i do? Should I use pull down?

@SHILADITYADEY I'd get breadboarding. Simulations are all very well, but you may find that in real life with real components it behaves very differently.

So i am going to make it with pull down at base, sounds ok?

@SHILADITYADEY Without that pull down, when the opto turns off the base is left floating. 10K should be a reasonable value.

Pulldown is not doing any change in simulation, but BC337 solving it

That's because your simulation isn't real. It's lacking the noise the base would pick up from the environment while floating. You need the pulldown even if your simulation says it works. Personally I prefer an n-channel MOSFET instead of a BJT.

ok, but adding pulldown is not reducing the collector voltage, it still is at 1.8 volts

Try it in real life. I never trust simulations to get it right.

okk, I am gonna try it tonight and let you know

Hello @Majenko, I made the new schematic i had uploaded yesterday, and its working fine, right now i did it for only two outputs, gonna do it for all six of them today, also added the pulldown. Thanks for your help. Really appreciate it.

It looks like the reason for the MCU drawing high current is operating the LEDs in half a dozen optical isolators without current-limiting resistors.  The part number of your isolators apparently is PC817, for which the suggested LED current is 5 to 20 mA at about 1.2 to 1.4 forward volts.  But if you don't limit the current, they are likely to draw 50 to 100 mA each when turned on.  Add a series resistor, say 220 to 330 Ω, in series with each isolator.
At this point, it's possible you may have damaged your ATmega328 by overheating it, due to drawing too much current from its outputs.  You probably should run some tests with simple sketches to see if they all work ok.
Note, it probably would make sense to use a buck regulator rather than a linear regulator in the 12 V environment.  MP1584-based buck regulator boards (“Mini DC 4.5~28V to DC 3.3V MP1584 3A Step-down Converter Regulator Module”), about 2x2 cm, are about a dollar on ebay and handle 2 amps typically.

thaks for your reply, i tried using 220E resistors, but its not working, 56E seems to work fine in the sketches. Also i connected 100E at the sketch, output LED, is glowing , but dimmed, what should i do?

@SHILADITYADEY, do you have an oscilloscope?  If so, check if regulator oscillation (as mentioned by Majenko) is an issue.  And/or, use a DVM to check output voltages on several IO pins, on load and off.  Also detach an isolator from its IO line, and drive the isolator with different voltages to test if the isolators+relays work by themselves.  Also detach 4 isolators+relays from the circuit and see if you have enough current to drive the remaining 2 (to check if problem is just too much load, or some wiring error, or a design problem).

Also, a 'glowing , but dimmed' LED either is at low current or is turning on/off rapidly.  Easy to check with a scope, not so easy with a DVM; possibly detectable by sweeping it across your field of vision.  Low current may be a result of high resistance (eg damaged IO lines) or low voltage.  Low voltage can be caused by shorts or low-resistance loads, or by power-supply oscillation.

gonna do it today and let you know

found out it was problem with the excessive current 817Cs are taking from controller. New modified circuit solved it. Thanku for the help.

source: Stack Exchange

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

sort: votes


text:
DC Motor's don't stop immediately
Functionality
I have written this code below for a buggy to continue moving forward until there is an obstacle which is <= 25cm both motors should stop.
Result
both motors stop when there is an obstacle which is <=25cm but the motors happen not to stop immediately when it comes across the obstacle please do find my code below is there something wrong with my code and how can I make it much better.
Code
#define PING_PIN  12  // Arduino pin tied to both trigger and echo pins on the ultrasonic sensor.
#define PING_MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

//initializing left DC Motor
const int in_1 = 2; // initializing the IN1 to Pin 2
const int in_2 = 3; //initializing the IN2 to Pin 3
const int EnA = 4;  //initializing pin 4 as pwm

////initializing Right DC Motor
const int in_3 =5;  // initializing the IN3 to Pin 5
const int in_4 = 6; // initializing the IN4 to Pin 6
const int EnB = 7;  //initializing pin 7 as pwm

// initialzing Ultrasonic sesor (Front view)
const int trigPin = 8;
const int echoPin = 9;

//For providing logic to L298 IC to choose the direction of the DC motor
void setup()
{
    /// initialize serial communication:
    Serial.begin(9600);
    pinMode(EnA,OUTPUT);   //we have to set PWM pin as output
    pinMode(in_1,OUTPUT);  //Logic pins are also set as output
    pinMode(in_2,OUTPUT);
    pinMode(EnB,OUTPUT);   //we have to set PWM pin as output
    pinMode(in_3,OUTPUT);  //Logic pins are also set as output
    pinMode(in_4,OUTPUT);

    //--------------------------------------------------------------
    // Reading the signal from the sensor: a HIGH pulse
    //-----------------------------------------------------------------
    pinMode(trigPin, OUTPUT);// set the trig pin to output (Send sound waves)
    pinMode(echoPin, INPUT);// set the echo pin to input (recieve sound waves)
    //pinMode(trigPin2, OUTPUT);// set the trig pin to output (Send sound waves)
    //pinMode(echoPin2, INPUT);// set the echo pin to input (recieve sound waves)
}

void loop()
{
    int duration, Distance; // start the scan
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2); // delays are required for a succesful sensor operation.
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10); //this delay is required as well!
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    //---------------------------------------
    // convert the time into a distance
    //---------------------------------------
    Distance = (duration/2)/29.1;
    Serial.print(Distance);
    Serial.print("cm");
    Serial.println();
    delay(1000);
    if (Distance <= 25)
    {
        //Stopping Right and Left Motors
        digitalWrite(in_1,HIGH);
        digitalWrite(in_2,HIGH);
        digitalWrite(in_3,HIGH);
        digitalWrite(in_4,HIGH);
    }
    else {
        //Moving both Motors in a Foward motion - IN_1 = LOW , IN_2 = HIGH, IN_3 = LOW , IN_4 = HIGH
        digitalWrite(in_1,HIGH);
        digitalWrite(in_2,LOW);
        analogWrite(EnA,200); // Enablling the Right motor @ speed of 200
        digitalWrite(in_3,HIGH);
        digitalWrite(in_4,LOW);
        analogWrite(EnB,200);// Enablling the Left motor @ speed of 200
    }
}

Do the motors stop immediately if you just disconnect them from the power?

Never use delay() on something that has to be responsive.

@MarkSmith yes they stop immediately when I disconnect them from the power

are you saying I shouldn't have delays for the ultrasonic sensor, and delay for displaying to the serial because those are the only place I used the delays in the program and I need the delays for a successful sensor operation  @EdgarBonet

delay(1000) is not directly responsive. Might want to move that to after the motor control?

As already stated, your problem is in the use of delay(), which
blocks the program until the delay is over. When your program needs to
be responsive, you have to write everything in a non-bloking manner.
The basics of non-blocking management of time are covered in the
Blink Without Delay Arduino
tutorial, which I
strongly encourage you to read. Applying the technique of the tutorial
to your printing of the distance gives something like this:
static uint32_t last_time_printed;
uint32_t now = millis();
if (now - last_time_printed >= 1000) {
    Serial.println(Distance);
    last_time_printed = now;
}

I think the code is quite straightforward: you record the last time you
printed the value and, if it has been one second since last time, you
print it again.
You also have some other blocking calls in the section where you operate
the sonar. I would not worry too much about delayMicroseconds(): these
are really tiny delays, and your robot does not need to be that
responsive. I would worry about pulseIn() though: this function blocks
until it sees the end of the pulse, or until it reaches a timeout. The
default timeout is one second, which is way too large for this
application. Instead of relying on the default, you should specify a
timeout as a third parameter, as in
duration = pulseIn(echoPin, HIGH, 50000);  // timeout: 50 ms

This would limit the range to about 8 m, which I think should be
more than enough.
Reading the sonar pulse in a completely non-blocking fashion is
possible, by using either an input capture unit or an interrupt, but I
guess it is not worth the trouble, as your robot can probably cope well
with being blocked for 50 ms.

While I totally agree with the other answers on the issue of using a non-blocking timer, I would like to add another factor about motor braking from a purely "electrical" point of view.......
To "brake" a running DC motor, you need to short the two terminals. This will generate a back current in the coil which will reverse the magnetic field and stop the motor much faster than by just cutting off power to the terminals. This is not possible to implement using a Bi-polar H bridge motor driver like L293D. You need to use a MOSFET type H-bridge.

You can break with a bipolar driver, if only through the free-wheeling diodes. This is even documented as “Fast motor stop” in the L293D datasheet.

@Edgar Could you provide a reference to this please? I can't find any mention of this in the [datasheet] (http://pdf.datasheetcatalog.com/datasheet/stmicroelectronics/1330.pdf)

See e.g. table 3 of the datasheet.

I see the reference now, thanks. But this TI datasheet looks much more detailed than the one I linked to (SGS Thomson). I wonder why...

As some of the comments have mentioned, the delay(1000); is probably doing you in. What's happening there is the code does absolutely nothing but count 1000ms for that time, so if the obstacle comes within 25cm during that delay, nothing will happen until the delay is done counting and the if statement occurs.
If you still want it to serial print every second, but not have that effect of slowing your response, try a counting variable (I forget the actual name). It's like a flag that you count on, so for example, you could have int printCount = 0; and instead of the delay(1000);, you'd have

delay(1);
if(printCount > 999){
  Serial.println('Whatever');
  printCount = 0; //resets counter
} else{
  printCount++;
}

make so much sense to me now thank you for your help I really appreciate it @Orotavia

Although this kind of works (albeit with very inconsistent timings), I don't think it's wise to encourage the OP to persist in using delay().

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


text:
Integrating an analog signal using Arduino Uno SMD
I need to integrate an analog signal using my Arduino Uno. I am sampling the input signal at 1 KHz using a delay command in my void loop() and adding up the values at the analog read at that specific time. Then I multiply my added output with 0.001 s to get my integration.
Since, I am new to Arduino Uno, I want some review on the code to check whether I am correct or not. Kindly help, I'll be indebted.
const int a=13; //my output pin
const int c=A0; //my input pin
int d=0; //my summation variable
int e=0; //my integration variable(integration as a summation)
void setup()
{
  pinMode(a, OUTPUT);
}
void loop()
{
  int b=analogRead(c);
  d=d+b; //my summation
  e=d*10^-3; //my integration as a summation, by sampling my signal at 1ms
  analogWrite(a,e); //writing my integration into my output pin

  //print the results to the serial monitor
  Serial.print("input=");
  Serial.print(b);
  Serial.print("\t output=");
  Serial.println(e);

  delay(1); //wait for 1ms as I want it sampled at that rate
}

Since you are using an int , d could overflow in as little as 32 measurements. Also analogRead does take some time, as does the code around it, so the time between measurements will be a bit more that 1 ms. I also don't see how you call dividing by 1000  integration.

Could you explain why you want to integrate in the first place? Integrating a positive signal will yield a diverging integral, meaning that, as your program runs, the result will increase without bounds. This is problematic. If your store the integral in an integer variable, even a long int, it will eventually overflow. If you store it in a float, it will loose precision as it grows and, eventually, the summation will have no effect, because d+b is exactly equal to d if d is a big enough float.

There are a couple of issues with your code.
First of all, 10^-3 is not a valid constant in C/C++ code. The correct syntax would be 1e-3, which means 1 × 10-3. But you have the further problem that you're working with integer variables, and 0.001 rounded to the nearest integer is just zero. You'll probably want to use float variables for this math.
Also, the values you get from AnalogRead() are all non-negative integers, so your summation will quickly overflow unless you subtract a constant from each reading in order to get both positive and negative values.
The second issue is about the delay() function, and trying to use it to determine the sample rate of your system. The delay() function is not all that precise. It really is just guaranteed to produce a delay of at least the number of milliseconds specified, but it can be more — sometimes much more.
Furthermore, the other operations in your loop take much longer than 1 ms anyway. For example, you're printing on the order of 25 to 30 characters to a serial port on every iteration, which is an overall rate of 25,000 to 30,000 characters per second. Unless you're running your serial port at an insane baud rate (430.8 kbaud or more), it simply won't be able to keep up, and it will end up increasing the period of your loop to whatever time it needs.
All of this means that the sample period of your loop is NOT 1 ms as you want, and in fact, it can vary quite a lot based on other things that are going on in the system, such as interrupts. For doing this kind of DSP, you will want to learn how to use a timer interrupt to control the sampling of the analog input, and you'll need to trim the amount of data transmitted for each sample to an amount your serial link can handle.

Thank you for your reply. It's valuable really, kindly help me with correcting my errors
1> Regarding the integer data types of d, b and e, I completely understand and hence I'll change them to float variables.
2> Regarding the AnalogRead being non negetive integers, is there any way to read floating value out of analog inputs?
3> Regarding the delay timer, could you direct me to some literature on using timer interrupts to sample my signal?
4> Is there any way around the problem, I mean some built in library functions to help with integration etc...

I'm not entirely clear on what you're trying to achieve mathematically. However, I can see a number of issues in your code which I'll try to address briefly.
Arithmetic
I suspect this line isn't doing what you intended:
e=d*10^-3

The ^ operator in C/C++ is actually a bitwise XOR (exclusive-or). There is no arithmetic raise-to-the-power operator.
There is a function called pow() for calculating exponents. However, there's no point using it for a fixed value. It would be better to explicitly write the number, i.e. 0.001.
Precision
The power issue notwithstanding, it's important to note that you're working with integers here, and the result of analogRead() is only in the range 0 to 1023. Dividing that by 1000 and storing the result as an integer will destroy your data -- most readings will effectively be 0. (That's not to mention the fact that an int has a limited range and will overflow quite quickly if you don't reset it.)
The simple solution would be to store the data using the float data type (floating point). You would need to declare variables b, d and e as float instead of int. That should let you divide down by 1000 without losing significant precision.
Output range
The analogWrite() function has a very specific output range. It will only accept values 0 to 255 (inclusive). I'm not entirely sure what you're hoping to do with it, but I suspect you'll need some way to map your integration calculation onto that output range, or possibly reset your summation periodically.
If you don't do that, you'll probably find that e ends up over 255 very quickly (within a couple of seconds). The result is that you won't see any change on the output PWM.

I'm trying to arrive at integration as a sum of discrete samples, dividing my 1000 I did because my time period was 0.001 seconds. Is there any way around this problem for analog integration, I'll be grateful for your help...

Here is an edited version of your code:
/*
 * Integrate a signal read on analog input 0.
 * Print the result every 2 seconds on the serial port.
 */

const int input_pin = A0;
unsigned long last_time_sampled = 0;
unsigned long last_time_printed = 0;

// The integral is in units of DN*us, 1 DN being the ADC step.
float integral = 0;

// Convert from DN*us to V*s, assuming a 5 V reference.
const float conversion = 5.0 / 1024 * 1e-6;

void setup()
{
    Serial.begin(9600);
}

void loop()
{
    int sample = analogRead(input_pin);
    unsigned long now = micros();

    // Approximate the signal as a constant equal to the current sample
    // from the time of the previous sample until now.
    integral += sample * (now - last_time_sampled);
    last_time_sampled = now;

    // Print the results every 2 seconds.
    if (now - last_time_printed >= 2000000) {
        Serial.print("input = ");
        Serial.print(sample);
        Serial.print(", output = ");
        Serial.println(integral * conversion);
        last_time_printed = now;
    }

    // Limit the sampling rate to no more than 1000/s.
    delay(1);
}

The main changes I did are:

I renamed the variables to give them more meaningful names. This
single change makes the code a lot more readable.
I removed those comments made redundant by the better variable names.
I removed analogWrite(), since I couldn't make any sense out of it.
I compute the time between samples as time differences. Unless you
take your samples on some kind of timer interrupt, the delay between
samples will never be 1 ms.
I stored the integral as a float to avoid overflows.
I removed the summation variable, as it was redundant with the
integration variable. Instead, there is a conversion factor for
converting the integral from its “natural” unit (DN⋅µs) into a more
human-friendly unit (V⋅s).
I print the results only every 2 seconds, as nobody will read
something printed every millisecond.
I added some comments, most importantly for making explicit the
approximation used in computing the integral.

There is still one caveat with this code: once the integral is roughly
107 times larger than the samples, which should happen after
only a few hours, the integral is not incremented any more, due to loss
of precision.


text:
PWM doesn't work with my sketch
I have a weird problem. again. This time it's the PWM. I have used PWM before and I used to work the way I am doing it now. But now it just wont work. The Fading sketch from example works. When I compile a code with the similar code it doesn't work. Everything with respect to compilation is same.
The code that works:
int ledPin = 3;    // LED connected to digital pin 9

void setup() {
  // nothing happens in setup
}

void loop() {
  for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
    analogWrite(ledPin, fadeValue);
    delay(30);
  }
  for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
    analogWrite(ledPin, fadeValue);
    delay(30);
  }
}

The code that doesn't work.
#define FAN1 3
#define FAN2 5

void setup() {
  //EMPTY
}

void loop() {
  int speed1 = 25;
  int speed2 = 127;
  analogWrite(5, speed1);
  analogWrite(3, speed2);
  delay(10000);
}

Why doesn't the second code work?
EDIT 1:
By not working I meant No output on Second Code and Expected Output on First one. Currently I'm using ISIS for simulation and Oscilloscope to view the output along with a L239D with motors attached.
In the first code the motor starts and stops as expected, with the expected PWM Waveform.
In second code, nothing. No waveform, no motor movement.

Could you clarify what you mean by "doesn't work", please? What does happen, and how are you determining this?

@MarkSmith edited the question. Thanks for pointing out the lacking.

One omission from your code which might be causing the problems is the fact that you haven't set the pinMode. You need to set the pins as OUTPUT in setup()
#efine FAN1 3
#define FAN2 5

void setup() {
    pinMode(FAN1, OUTPUT);
    pinMode(FAN2, OUTPUT);
}

void loop() {
  int speed1 = 127;
  int speed2 = 25;
  analogWrite(FAN1, speed1);
  analogWrite(FAN2, speed2);
  delay(10000);
}

I am curious to know why you declared FAN1 and FAN2, but didn't use them - I'd recommend changing the analogWrite statements to use them instead of referring to the pin numbers directly.
Also, the way you're using the pin and speed means that you're using speed2 for FAN1 and vice versa, I've switched these in my example so FAN1 and speed1 go together.

Yeah. I meant to use it but didn't to check it out if it was to blame. I was just checking. Let me post a result of this change, btw the code that does work also doesn't set the pins as outputs.

just checked it. still the same.

I think there is something wrong with the Arduino Library of ISIS. I just got back my arduino back from a friend an it works.

You don't need pinMode with analogWrite. Check the first couple of lines of the source for analogWrite to see why. It takes care of pinMode itself.


text:
Why does an Arduino UNO need two GND ports?
I have really bad eyesight, so whenever I plug in the power wire and the GND wire I always double check if I'm actually plugging in to the power port not one of the two GND ports.
Why does an Arduino UNO have two GND ports, and for what application would one use both of them?

There is actually a third one next to pin 13 on my Uno. It's just convenience to have multiple ground headers. That way you even do without a breadboard for very simple projects.

In electronics circuits, a major point in connecting two circuits and make them "talk" together is to ensure, at the minimum, that they have a common reference of voltage (typically called GND and defined as 0V voltage).
On Arduino, GND pins can be used in 2 situations:

to directly power the Arduino with an external supply which cannot be plugged to USB or power jack. In this case, the positive voltage of that external power source shall also be supplied to Vin pin.
to connect Arduino GND to your circuits.

Having 2 distinct GND pins is, I think, just a matter of convenience when you want to build prototypes but don't necessarily have a breadboard (if you use a breadboard, you will just need to connect its power rail to Arduino GND pin and use this power rail directly).

If you are not using a shield and are directly adding components to the arduino it is nice to have 2 ground so you can attach several components without having to add a bread board.
To be precise, you have 3 ground, since the third is sitting on the left hand side of the board (looking in to the USB port)


text:
Arduino Uno suddenly not recognized in Windows 8.1 (code 43)
I had my Arduino Uno connected to an external 12 V supply for 2-3 hours as I was working on other parts of my project. Suddenly the voltage from pin 9 which I was monitoring in the oscillator dropped down to 0 approximately.
I went on removing the external supply. The board was very very hot. I then connected the USB to my laptop and I got an error 43 (Windows did not allow the device to connect because it was reporting problems). I can't load any program of course. The 5 V pin works but it outputs a voltage lower than usual (at about 3.9 V). When I connect the external supply the 5 V pin outputs full voltage.
Any idea? Any fix?

Have you tried rebooting your laptop?

yes of course...and reseting arduino as well...

What is pin 9 of the oscillator?

pin 9 is from arduino

Is this a knock-off Arduino or Genuine Arduino?

I changed the cable and it works :)

Something is shorted out.
When you connect via USB, the USB port cannot supply enough current because of the short. The output drops to 3.9V and the USB port on your computer reports an error, probably due to over current.
When you connect the external power supply, it has enough power to supply the short. The output remains at 5V.
You can think of power supplies as having a very small internal resistance (R_p), and the board as being a resistive load (R_b). This forms a voltage divider, but because R_b >> R_p the voltage seen by the board is basically the same as that of the power supply. With a short, R_b is often < R_p, and thus the voltage seen by the board is much lower than the power supply voltage.
The fix will depend on which component is getting hot. Plug in the external power supply and check which one it is. Note: The component will get hot enough to burn your finger after a few seconds. One way is to check one component at a time, disconnecting the power between each check. Start with the big ICs.
If either the Atmega328P or the smaller ATmega8u2 (?) are hot, they will have to be replaced.
Finally, boards don't short out by themselves. Something is wrong with your circuit or you may have placed the board down on some conductive surface. If you post you circuit we might be able to spot the problem.

I've been dealing with the same issue, and have resolved it in a manner similar to random approach described above.
Drivers will get corrupted as we all know. But if you want to get past that Code 43 error, you need to have the arduino unplugged from the USB when reinstalling. Otherwise windows will bind the USB.inf generic driver to the device, which prevents the install of the CH341SER driver.
So unplug USB, delete the unknown device via Device mgr, run the CH341SER, *then plug in the USB cable. So I think that random approach worked not because the 9v reset was done unplugged, but because that was first chance (unplugged) that the CH341SER driver had to install without resources bound to generic USB.inf driver.

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


text:
Porting Arduino code to AVR/C++ input not working?
So. I'm trying to read an input on the Arduino Nano using C++/AVR/Eclipse instead of the regular arduino IDE.
The code below is working in the arduino IDE
void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
  pinMode(5, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(digitalRead(5)){
    digitalWrite(13,1);
  }else{
    digitalWrite(13,0);
  }
}

I'm porting the code to AVR/C++ in Eclipse, regular blinking leds is working... but I can't read inputs for some reason...
#define F_CPU 16000000UL //16MHz
#include <avr/io.h>
#include <util/delay.h>

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clear_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define isset_bit(Y,bit_x) (Y&(1<<bit_x))
#define toggle_bit(Y,bit_x) (Y^=(1<<bit_x))

int main( ){
    DDRB = 0xFF;//Setting all portB pins to output (D13/PB5 - LED)
    DDRD = 0x00;//Setting all portD pins to input  (D5 /PD5 - INPUT)

    while(1){
        if(isset_bit(PORTD,PD5)){//if input... doesn't work?
            set_bit(PORTB,PB5);//Set output (Tested to be working)
        }else{
            clear_bit(PORTB,PB5);//Clear output
        }
    }
}

Use the checkmark next to the answer rather than changing the title to indicate that the question has been answered.

During the creation of this question I found out the answer... Though I wanted to share it with you guys for later reference.
It has been quite a time since I have worked with AVR.
You should read pins from PINx
You should set pins in PORTx
Set DDRx to 1 for OUTPUT and to 0 for INPUT
^ This is fun because PIC/Microchip MCU's use 1 for input and 0 for output.
See code below:
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clear_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define isset_bit(Y,bit_x) (Y&(1<<bit_x))
#define toggle_bit(Y,bit_x) (Y^=(1<<bit_x))

int main( ){
    DDRB = 0xFF;
    DDRD = 0x00;

    while(1){
        if((PIND&(1<<PD5))){
            set_bit(PORTB,PB5);
        }else{
            clear_bit(PORTB,PB5);
        }
    }
}

This is interesting, what pins are you reading and writing? And how would you take an analog reading?

@user2497 The microcontrollers use registers that you can read/write to/from. Arduino is an environment and a wrapper around this, to make it easier and more understandable. You should check the datasheet, to find which registers hold what. The registers are 1 byte (I bits), so you'll have to do some bit manipulation/arethmic and write it to the correct registers.


text:
What means the ~ symbol in the code?
I'm learning Arduino (school and from myself).
We have the following code:
temp = Wire.read();
temp = ~temp;
temp = temp - 1;

This code is made to read, then print positive and negative values from a temp sensor. If you need more parts of the code, let me know.
I don't understand what does the ~ symbol, can someone help me?
Thanks.

As always, ~ in C++ is bitwise negation.


text:
GPS autonomous robot
I am working on a GPS autonomous robot using Arduino, HMC5883 compass, Adafruit GPS module and I have managed to sort of complete the coding for it and I tried compiling / verifying it and I get an error. It would be helpful if anyone could assist help me find out what I am doing wrong in my code as I have spent 2 days looking for what I have done wrong and if someone could suggest a better way of writing my code or even improving it here code I appreciate it. HERE IS MY CODE http://textuploader.com/drhfa
Error:
GPS_move_:468: error: unterminated argument list invoking macro "radians"

I assume the problem is with this line: Wire.send("A);

it's not that I just corrected it and it still comes up with the error-@gre_gor

There's numerous missing semicolons...

Also you seem to have a missing close bracket at differencelongitude = radians((longitudeWaypoint2 - (longitudeWaypoint1)); (or an excess open bracket)

And a colon instead of a semicolon here: turn_left():

Using autoformat helps to highlight where these kind of problems are since the formatter can't format it right if there are errors like this.

Please post the code.  the linked location says the post has expired..   Suggest posting the code as part of your question (indent all code 4 spaces, so it will be displayed as code.

I cannot compile because there are libraries missing. However, after auto-formatting the code I have this list of problems:

Many lines lack semicolons at the end (check your variable definitions near the top of the code)
You have an extra bracket in one of your radians() calls (the one that is giving the error I guess): differencelongitude = radians((longitudeWaypoint2 - (longitudeWaypoint1));
There is an unterminated string literal: Wire.send("A);
You have a colon instead of a semicolon: turn_left():

There may be more but as I cannot even begin to compile I cannot find them easily - also there may be similar errors in any included files you have created.


text:
Communication between Arduino and raspberry Pi
So I am working on a ground surveillance robot using Arduino for coding the Gps, motors and ultrasonic sensors and coding in raspberry Pi for facial recognition but now what I want to do is when my robot has gotten to its final waypoint and has stopped it should excute the python file that does the facial recognition by calling it in the Arduino  sketch but I don't know how to do it would be nice if someone could please help me out I appreciate your help in advance thank you

What is an arudionk?

You can't make the Arduino just run the Python script on the Pi. Instead you will have to run some software (probably of your own devising) on the Pi that listens for instructions from the Arduino.
The simplest way is probably to modify your existing Python script so that it runs all the time but sits idling waiting for instructions through the serial port (using pySerial). When it gets the instruction to perform the task you need it then goes off and runs the main bulk of its code. When that is done it can then return the results back through the serial port to the Arduino (if you need such results returning).
How you arrange those instructions to get it to do things is entirely up to you.


text:
Use registers as parameter?
I'm writing a helper class to manage timers, and I'm writing a lot of code like
if (timer == 1)
        ICR1 = icr;
    else if (timer == 3)
        ICR3 = icr;
    else if (timer == 4)
        ICR4 = icr;
    else if (timer == 5)
        ICR5 = icr;

Is there a better way to store these registers?
e.g. an array
timers {
{ ICR1, TCCR1A, OCR1A, OCR1B },
{ ICR2, TCCR2A, OCR2A, OCR2B }

etc.
to be accessed like
timers[1][0]

for ICR1.
And ultimately, how would I assign a value? e.g.
*timers[1][0] = 100;

UPDATE:
I solved the problem with
volatile uint16_t* ICRs[5];
ICRs[1] = &ICR1;
ICRs[3] = &ICR3;
ICRs[4] = &ICR4;
ICRs[5] = &ICR5;

*ICRs[1] = x;

afaik, since you assign to a different place each leaf, you can't use a look-up array, you need flow.

registers are nothing but pointers to memory addresses. so the best way to "parameterize" them is to do so via pointers.
assuming that ICRi is of 8-bit types - they are NOT to be sure:
uint8_t *ICRs[4];  //isr pointers

//initialize the icrs
ICRs[0]=(uint8_t *)&ICR0;
ICRs[1]=(uint8_t *)&ICR1;
...

*ICRs[i]=icr; //assign value to ICRi

note: that piece of code isn't operable in reality. The way to go is to use a pointer to void. But I'm sure you can figure that out.

i would suggest creating macro definitions for the timers you want
Something along the lines of:
#define OCR_BY_INDEX(i) OCR##i
//...other code...
OCR_BY_INDEX(1) = value;

and then have the indices in an array

That's wonderful, I didn't know about the token-pasting operator, https://msdn.microsoft.com/en-us/library/09dwwt6y.aspx

Note that this does not work with variables, so OCR_BY_INDEX(timer) does not work. This is a good solution if you don't need that.

You can better use a switch statement:
switch (timer)
{
case 1:
    ICR1 = icr;
    break;

case 3:
    ICR3 = icr;
    break;

case 4:
    ICR4 = icr;
    break;

case 5:
    ICR5 = icr;
    break;

default:
    // Handle other cases
    break;
}

About the variables:
You can make a 2 dimensional array:
typedef enum
{
   TYPE_ICR,   // Value 0
   TYPE_TCCRA, // Value 1
   TYPE_OCRA,  // Value 2
   TYPE_OCRB,  // Value 3
   TYPE_LAST,  // Value 4
} EType;

EType timers[TYPE_LAST][2];

You can access it by
timers[(int) TYPE_OCRB][0] = 3;
timers[(int) TYPE_OCRA][1] = 0;

Maybe the (int) cast is not needed.
You also can just iterate over the type:
for (int type = 0; type < (int) TYPE_LAST; type++)
{
    timers[type][0] = -1;
    timers[type][1] = -1;
}

Note 1: if a cast is needed probably static_cast(...) is better to use.
Note 2: I haven't tested the code above


text:
What happens if you write >10000 times to the flash memory of an ATmega?
I realized that I'm uploading code every 5 minutes and doing relatively intensive trial-and-error development, and that this habit could cause problems down the road, especially if I'm working on a custom board (non-Arduino) where the chip isn't readily replaceable.
What will happen?
I noticed that avrdude verifies the written flash. So will it simply start noticing errors and possibly be unable to write without failing?
Or will it work sometimes, sometimes not?
Example of heavy use: A custom PCB where easy replacement of the MCU is not possible. 10,000 writes would equal 100 days, each 8 hours of development, with flash write every 5 minutes.
I have several habits that drive frequent flash writing: I inject benchmarks into my code, test speed improvements of small optimizations, program size optimizations, and so on.
I now try to restrain myself from flashing too frequently and doing more code revisions before testing, rather than testing immediately.
In conclusion: Yes, it's unlikely, and arguably, if you're working full-time on a board, less intensively, for, say, a year, you can probably afford to buy another board when the first one starts failing the flash-verification.

As far as I know, avrdude checks every written byte. You will know when it failed. Some have done tests with the EEPROM, but I don't know a test with Flash. The old ATmega8 has the same numbers for flash (10k) and EEPROM (100k), but the newer chips are better. I suppose it starts failing after many 10k of writing.

@Jot, I'm still not sure if the consequence will be corrupted flash, if avrdude will gradually fail more frequently and have to retry, or if the flash will simply be incapable of being written to correctly, e.g. always yield an incorrect reading.

The datasheets tend to be conservative, and the numbers they give are usually valid for a wide temperature range. In room temperature conditions, chances are you can go far beyond the 10K cycles limit. You just cannot be 100% certain, as Atmel does not make any promise beyond 10K.

What I'm trying to ascertain, is how it will fail.

Actually, it will be undefined behaviour. Basically anything could happen and it should be avoided to do so.

@Paul, So in extreme cases, it would be relevant to separately keep track of flash write count? Since failure mode wouldn't behave predictably? E.g. a repeated failure on flash write

Soms programmer-boards or IDE's actually do this indeed. But often, you don't reprogram the micro more than 10.000 times.

This Wikipedia article about Flash memory discusses failure mechanisms including references to relevant papers. One point that surprised me was "Read Disturbance" of adjacent cells after a large number (>100,000) of reads from one cell since last erase, causing the adjacent cell(s) to read back erroneously. There's probably more there and in the referenced articles than you ever wanted to know about Flash failure mechanisms.
However...
At 5min per test, 10000 tests will take you 35 days working around the clock or 100+ days @8hrs/day, maintaining that rate of testing. My point being that you're not likely to reach 10K cycles. But if you are concerned about putting a heavily used chip in the field (and I might be, too, in some cases), socketing board #1 would be worth your while.

Indeed. My concern is mainly in regards to actively developing on a custom PCB, with an ATmega2560 which wouldn't be too much fun to replace manually, although doable (100 pins + risk of hard-to-see short circuit of the pins). Or alternatively, buying several boards.

The reason for the high number of writes is that I'm fine-tuning various functions for automation, sensing etc. -- perhaps some of that could be alleviated by writing to the EEPROM via serial etc. etc. but that's a lot more complicated than just rebuilding/reflashing ;)

My first thought is whether any of those functions could be tuned out-of-system? And if not, what is the cost of a failure in the field vs. the steps necessary to prevent one? Will failure cost some downtime? A global service call? A customer relationship? Killing a patient? Some scenarios just simply justify even a huge upfront investment to avoid them. Ouch - talk about the rock vs. the hard place...

What will happen?

it may not pass parity check. so uploading code wouldn't be possible.
with that said, I have never had one flash-based mcu failure due to endurance. that's countless mcus since as far as I can remember.
to give you some sense of design headroom, I wrote-to and then read-back from eeprom on a pic over several hours @ 10ms per read/write, without a failure. that eeprom is rated 1M in endurance.
so unless you get some weird parts or you write to it repeatedly over a long period of time, flash failure is unlikely a practical issue.

Assuming that you don't have to fine tune each board individually, just don't send the board that you do your testing/adjusting to the 'field'.....keep it in-house, and only use new boards for field use.

10k write cycles is a lot though.

AFAIK the manufacturer say, that the number of write cycles is guaranteed. Usually the chip is able to endure little more (for manufacturer to be safe to keep the guarantee), individual chips may, on random, endure much, much more.
Also the failure can result in two kinds of problems - first one is better in a way - the write just fail, following read returns "something" (usually part of written value, but some bits always set to the same 0/1). The second one is, that the wearing makes the write unreliable - you write it, you read it it is ok, but after some time (like days/months) the content is changed and if you read it again, you will get "something" as in previous case.
It would be better to make sure you are able to exchange the chip, before going to "normal use" and put there fresh one - use a socket/create new board/unsolder old chip and solder new one. Use the weared chip for more testing/developement, but for production use a fresh one with only few cycles of reflashing. Also software emulators could speed up your developement a lot and decrease the need to/number of reflashing the chip on the board.

Although it's not a direct answer to your question, it might be an answer for your problem (the need to do intensive trial-and-error.
Probably you are testing mostly your program (changes), and not your hardware (changes). Since I don't assume you change your hardware (breadboard) every 5 minutes.
In case the program is quite complicated, probably it will be best to write a specific off-line test program, and run it on a computer instead of an Arduino. You probably have to stub some classes/libraries you use, but it might save you a lot of time. Also you have the benefit of a better IDE and many more debug possibilities. After the tests on the offline test program pass, you try it on the Arduino.
This way you probably need to upload the program just a few times per day on the Arduino.

In my experience, this would be better suited as a comment than an answer.

I think it depends on what is more important: the answer of the question itself or the solution of his problem.

It is a good answer, because 10k trials is too much and it is better to fix the underlying problem. Perhaps delays are used which needs to be tuned (instead of using millis). Perhaps more than one Arduino board can be used, or Arduino Due with multiple tasks. I think that only a random generator to create working code would require so many trials.


text:
nRF24L01 - leaves out end characters during transmission
This is my Master's code.
#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>

RF24 radio(7, 8);

const byte address[6] = "00001";
char text[20] = "";
int flag;
char *p;
int i;

void print();
void read();
void rfwrite();
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setDataRate(RF24_1MBPS);
  radio.setChannel(1);
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();

  flag = 0;
  p = text;
}

void loop() {

  if (Serial.available()) {
    read();

  }
  if (flag) {
    print();
    rfwrite();

  }

}

void print() {
  Serial.println(text);
  flag = 0;
}

void read() {
  p = &text[0];
  for (i = 0; Serial.available(); p++, i++) {
    *p = Serial.read();
  }
  text[i + 1] = '\0';
  flag = 1;
}

void rfwrite() {

  radio.startWrite(text, strlen(text)+1);

}

Slave code:
#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>

RF24 radio(7, 8); //ce,csn

const byte address[6] = "00001";
char text[20] = "";
int  i;

void write_to_array();
void print();
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setDataRate(RF24_1MBPS);
  radio.setChannel(1);
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {
  while (radio.available()) {

    write_to_array();
    print();

  }

}

void write_to_array() {
  radio.read(text, strlen(text)+1);

}

void print() {
  Serial.println(text);

}

I edited the code and made it with an array like @Kwasmich said. But now some end characters are not getting printed. When I type 1234567890-= into the transmitter, only 1234567890- gets printed. When I type a new set of characters following that, the missing = gets printed. Also, this happens only on the second transmission after I upload the code to the Arduino. The first set of characters are received and printed correctly. How do I fix this? Will flushing the buffer help(I doubt this because the first transmission is received correctly)?

Your code char text = "" can only hold a single character, not a string. You either need a char array or a char pointer. Likewise sizeof(text) is 1 because this is always a single character.

@ChristianLindig, but that is not the cause of the missing character

Your code currently sends the message only one character at a time. Not sure where the missing character comes in, but I'm pretty sure (from experience), that when you fix the single character issue, your missing characters problem goes away as well.

I cannot test it right now, but I guess the problem is in your slave Code, the initialization of text = "". Therefore the sizeof(text) in the initial run is 0, so something in radio.read(&text, sizeof(text)) will go wrong. Could you check with a diffenent initalization of text, e.g. "0"?

@RJPlog I've tried what you suggested, initializing the text as 'a'. The output remained the same although I think sometimes I noticed that the first transmission after uploading the code to arduino resulted in successfully receiving all the characters, I can't say for sure.

This is not a proper solution explaining why the issue occurred in the first place but merely a workaround to anyone encountering the same problem.
There is another function in the RF24 library called startWriting(). The description in the library was not clear about the differences between this and write(). But I noticed that the last character was missing with the use of startWriting(). So I simply changed
radio.read(&text, sizeof(text));

in the master to
 radio.read(&text, sizeof(text+1));

and voila!
The code now does its intended purpose!!

You are riding on a wave of undefined behavior. sizeof returns the size of the underlying type. In your case char. Which is 1. What you really need is the propper allocated array char text[32] = "" and the required length of the string using strlen(text) + 1. +1 to also transmit the nul terminator of the string.
The maximum string Length that can be transmitted using nRF24L01 is 32 bytes. Because of the mandatory nul termination of a string you can send at most 31 characters as a valid string.
Fun fact: The same limitation of 31 characters applies to file name langths on the classic Mac OS at least up to 7.x and also on the Amiga DOS/Workbench.

Please check the new code in the question. I've edited like you suggested.

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


text:
LCD lights up but shows no text
I've connected an LCD display to an Arduino Uno following the instructions from the Adafruit LCD lesson.

I've used the code sample described in the Adafruit lesson.
What happens after I connect the Uno to the USB cable is that the LCD lights up, but no text is displayed.
I've checked all connections and they look good. I am not 100%sure I have connected the potentiometer correctly, as this is the symptom I usually found online.
Could this also be a bad solder job? It's my first attempt and I guess it did not go that great.

Here are some more images, maybe someone with more experience can spot the error.

Update: here's what the board looks like once connected

and after removing the ethernet shield I get some weird flashes from time to time, only when I switch the potentiometer to maximum on one side, see video at https://i.imgur.com/ZclD2xz.mp4 .
Update 2: I realised that this is a 20-pin LCD screen and re-reading the datasheet and some online tutorials I switched digital wire connections to pins to the LCD 7-10 (DB0-DB3) - same result and then 11-14 (DB4-DB7) - garbled output, shown below. Still no idea what is wrong.

By "no text is displayed" what do you mean?  Are there 4 rows of blocks displayed that are lighter than the background or darker than the background?  Can you post a picture of the display when lit?   Also I have had the Ethernet shield be problematic.  Try removing that shield and givi'n her a go without it.  If you have a volt meter, you can test the wiper voltage (the yellow wire) to ground and see if it varies as you turn the stem of the potentiometer.

Hint: Start by removing the Ethernet Shield, then check the schematics for the shield and you will see why this was not a very good idea.

@MrFixIt87 - thanks for the pointers! See my update with a screenshot and a link to a video of what happens after removing the Ethernet shield.

@MikaelPatel - thanks for the pointers! See my update with a screenshot and a link to a video of what happens after removing the Ethernet shield.

Ok, so the LCD is a LCD12864 and that needs a different LCD driver. Use this "tutorial" instead. https://playground.arduino.cc/Code/LCD12864

The ethernet shield uses power and the backlight of the display uses power. I don't know this display, but the common 16x2 lcd displays needs a resistor for the backlight. The common displays require also a voltage near 5v. Perhaps you can add a resistor to the backlight to reduce the power usage. Measure the 5v pin to check that it is above 4.5v.

From provided picture it is visible that your display is not alphanumeric display (with most popular HD44780 driver). It is a graphical display (most popular: KS0107 or KS0108 or ST7920). You can count horizontal pixels and vertical ones in the picture to confirm its resolution.
Without too many problems you can drive it with your Arduino. Try to use some of 128x64 Arduino libraries. Also, check the rear of the display for any part number to confirm the driver (search in google).
 Good luck!

Thanks for the answer. I still need to wait a couple of days as I ran out of wires, so can't validate this right away...


text:
How to connect ESP8266-01 (AT-commands) to its web server using AJAX
I am just new on using AJAX in web server, I got an error on declaring "server" I am confused about this because I just used only a AT commands to used the ESP8266-01 (wifi-module) I hope you can help me, I want to get the data (distance) to print in the web server(page) in real-time(no refresh). So I used the AJAX for it but this code is still error. Advance thanks on anyhelp :)
 #include "NewPing.h"
 #include <SoftwareSerial.h>
 #define DEBUG true

 SoftwareSerial esp8266(10,11);
 #define TRIGGER_PIN 4
 #define ECHO_PIN 3
 #define MAX_DISTANCE 400

 NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

 void setup() {
 Serial.begin (9600);
 Serial.println("START");
 esp8266.begin(9600);

 server.on("/",WebsiteContent);
 server.on("/xml",XMLcontent);
 server.begin();

 pinMode(TRIGGER_PIN, OUTPUT);
 pinMode(ECHO_PIN, INPUT);

 sendData("AT+RST\r\n",2000,DEBUG);
 sendData("AT+CWMODE=2\r\n",1000,DEBUG);
 sendData("AT+CIFSR\r\n",1000,DEBUG);
 sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
 sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);

}

void javascriptContent(){
Javascript ="\n";

}
void WebsiteContent(){
javascriptContent();

 Website="\n";
 Website+="\n";
 Website+="";
 Website+="
"+data+"
";
 Website+=Javascript;
 server.send(200,"text/html",Website);
 }
 void XMLcontent(){

 XML ="<?xml version='1.0'?>";
 XML+="<data>";
 XML+=data;
 XML+="</data>";

 server.send(200,"text/xml",XML);

 }
 void loop()
 {

 delay(2000);
 digitalWrite(TRIGGER_PIN, LOW);
 delayMicroseconds(2);
 digitalWrite(TRIGGER_PIN, HIGH);
 delayMicroseconds(10);
 digitalWrite(TRIGGER_PIN, LOW);

 long duration,distance;
 duration= pulseIn(ECHO_PIN,HIGH);

 distance = duration/58.2;

 data=(String)distance;
 delay(500);

 server.handleClient();

 if(esp8266.available())
 {
 if(esp8266.find("+IPD,"))
 {
 delay(1000);
 int connectionId = esp8266.read()-48;

 String cipSend = "AT+CIPSEND=";
 cipSend += connectionId;
 cipSend += ",";
 cipSend +=webpage.length();
 cipSend +="\r\n";
 sendData(cipSend,1000,DEBUG);
 sendData(webpage,1000,DEBUG);
 String closeCommand = "AT+CIPCLOSE=";
 closeCommand+=connectionId;
 closeCommand+="\r\n";
 sendData(closeCommand,3000,DEBUG);

}
}
}
String sendData(String command, const int timeout, boolean debug)
{
String response = "";
esp8266.print(command);
long int time = millis();
while( (time+timeout) > millis())
{
  while(esp8266.available())
  {
    char c = esp8266.read();
    response+=c;
  }
}
if(debug)
{
  Serial.print(command);
  Serial.print("> ");
  Serial.print(response);
}
return response;
}

Do you actually have a question? And is it related to Arduino, and not Javascript or HTML?

I already edited it sir :) sir do you have any idea about it?

Looks like you're confusing ESP8266 native code for Arduino code.

try to add a include ESP8266WebServer server(80);

@abu-ahmedal-khatiri I also add that earlier but still error

i cannot see on your code. you need to make a index.h to store data on AJAX see my header and include it to your sketch see my sketch

@Majenko I used AT commands because when I program ESP8266 (directly) it's not working and always got error about it, so I switch on AT commands.

like a mentioned @Majenko answered "To use these kind of constructs you have to program the ESP8266, not the Arduino, and then you don't have the AT commands available." ,why you need AT Commands if you can store data to AJAX script directly?

ah so your example @abu-ahmedal-khatiri will work sir?

@abu-ahmedal-khatiri can you help me here sir? https://chat.stackexchange.com/rooms/85432/discussion-on-question-by-xiaomy-arduino-uno-with-esp8266-01-with-at

anyone can help me about this ESP8266WebServer server(80); is error because I am using AT commands? because once I delete it the "server" methods are error too. Is there any alternatives here?

as mentioned in your question "I want to get the data (distance) to print in the web server(page) in real-time(no refresh)". I THINK you will display data to Web Page and MY ajaxcreated.h will works!. if you're using APP INVENTOR, the AJAX will not work!

You're trying to mix code that is intended to run directly on an ESP8266 using ESP8266-specific libraries on an Arduino.  It can't ever work.
Likes like:
server.on("/",WebsiteContent);
server.on("/xml",XMLcontent);
server.begin();

are for use with the ESP8266's ESP8266WebServer library which doesn't run on an Arduino. To use these kind of constructs you have to program the ESP8266, not the Arduino, and then you don't have the AT commands available.
So, either:

Do it all with AT commands only, or
Ditch the Arduino and program the ESP8266 directly instead.

can you send me a link about that in AT commands?

You already use them in your code.

I thought there will be for AJAX or what

can you help me sir?

Do you know what the AT commands that you have in your sketch actually do?

it is for me to use it as alternative for coding esp8266 directly

Yes, but do you know what they do? What do they mean?

Delete all the server and such rubbish that you randomly added, and then work out how you can use what the ESP8266 sends you when you request a web page to decide what you should be sending and when you should be sending it.


text:
I have the code printing the data I need but don't know how to connect the data on ESP8266 IP web server

   #include "DHT.h"
   #include "NewPing.h"
   #include <SoftwareSerial.h>

   #define DEBUG true
   SoftwareSerial esp8266(11,10);
   #define DHTPIN 2        // DHT-11 Output Pin connection
   #define DHTTYPE DHT11   // DHT Type is DHT 11 (AM2302)
   #define TRIGGER_PIN 4
   #define ECHO_PIN 3
   #define MAX_DISTANCE 400

    NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);
float hum;
float temp;
    DHT dht(DHTPIN, DHTTYPE);

void setup() {

   Serial.begin (9600);
   dht.begin();

   pinMode(TRIGGER_PIN, OUTPUT);
   pinMode(ECHO_PIN, INPUT);

   sendData("AT+RST\r\n",2000,DEBUG);
   sendData("AT+CWMODE=2\r\n",1000,DEBUG);
   sendData("AT+CIFSR\r\n",1000,DEBUG);
   sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
   sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);

 }

 void loop()

 {

 delay(2000);  // Delay so DHT-11 sensor can stabalize

   hum = dht.readHumidity();  // Get Humidity value
   temp= dht.readTemperature();  // Get Temperature value

 digitalWrite(TRIGGER_PIN, LOW);
 delayMicroseconds(2);
 digitalWrite(TRIGGER_PIN, HIGH);
 delayMicroseconds(10);
 digitalWrite(TRIGGER_PIN, LOW);

   long duration,distance;
   duration= pulseIn(ECHO_PIN,HIGH);
   distance = duration/58.2;

   Serial.print("Humid: ");
   Serial.print(hum);
   Serial.print(" %, Temp: ");
   Serial.print(temp);
   Serial.print(" C, ");
   Serial.print("Distance: ");
   Serial.print(distance);
   Serial.println(" cm");

   delay(50);

  if(esp8266.available())

   is sending a message
 {
   if(esp8266.find("+IPD,"))
 {
 delay(1000);

 int connectionId = esp8266.read()-48;

  /* We are subtracting 48 from the
  output because the read() function returns
  the ASCII decimal value and the
  first decimal number which is 0 starts at 48*/

  String webpage = "
IOT Garbage Monitoring System
";
  webpage += "

";

  if (distance<5)
 {
  webpage+= " Trash can is Full";
 }
   else{
   webpage+= " Trash can is Empty";
    }
   webpage += "

";
   String cipSend = "AT+CIPSEND=";
   cipSend += connectionId;
   cipSend += ",";
   cipSend +=webpage.length();
   cipSend +="\r\n";

   sendData(cipSend,1000,DEBUG);
   sendData(webpage,1000,DEBUG);

   String closeCommand = "AT+CIPCLOSE=";
   closeCommand+=connectionId;
   closeCommand+="\r\n";
   sendData(closeCommand,3000,DEBUG);

   }
   }
   }

   String sendData(String command, const int timeout, boolean debug)

   {

   String response = "";
   esp8266.print(command);
   long int time = millis();

   while( (time+timeout) > millis())
   {
   while(esp8266.available())
   {
   char c = esp8266.read();
   response+=c;
   }
   }
   if(debug)
      {
     Serial.print(response);
      }
     return response;
      }

Comments are not for extended discussion; this conversation has been moved to chat.

The esp-01 is in AP mode. To access the web page on the IP address 192.168.4.1 show in Serial Monitor you must connect to the WiFi network created by the esp-01.
If you click the WiFi icon in the bottom right corner of Windows, you will see a list of WiFi networks.


text:
Arduino Master-Slave Pins
Can I change the pins on the communication for a Master-Slave arduino Wire transmission? I want to communicate between 2 arduinos, but on one of them A4&A5 are taken

You cannot. Wire uses hardware I2C, and on the Uno only A4 and A5 are connected to the TWI peripheral on the MCU. You will need to either switch to a bit-bang I2C implementation or change the protocol you're using.

To complete Ignacio's answer, there's indeed no other hardware I2C on AVR Arduinos.
The only options you have to use other pins is:

to use bitbang i2c, which is way slower ;
or you can switch to the Arduino Due which features two TWI ports ;
or you can use an SPI to I2C serial bridge such has that one.


text:
Upload code on Arduino Leonardo using command line
I'm trying to upload a compiled .hex file on an Arduino Leonardo, using the terminal. Uploading a sample code using the Arduino IDE works well, and from the Arduino IDE I got the upload command
avrdude -C/etc/avrdude.conf -patmega32u4 -cavr109 -v -v -v -v -P/dev/ttyACM0 -b57600 -D -Uflash:w:[file.hex]:i

But executing it I got the following error
Connecting to programmer: .avrdude: Send: . [1b]
avrdude: Send: S [53]
avrdude: Recv: . [15]

avrdude: ser_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding

What's wrong?

The problem with the Leonardo is it doesn't automatically reset when you open the serial port like boards such as the Uno do.
The Arduino IDE contains code to manually reset the board (by opening the serial port at 1200 baud and closing it again) which avrdude doesn't have.
Basically you need a different way to reset the board so it enters the bootloader. That may be as simple as just pressing the reset button at the right time (the LED fades in and out when it's in bootloader mode) or using some command line utility to open the serial port at 1200 baud and close it again just before running avrdude.
I don't have my Leonardo to hand right now, but you might have some luck running:
stty -F /dev/ttyACM0 ispeed 1200 ospeed 1200 && avrdude -C/etc/avrdude.conf -patmega32u4 -cavr109 -v -v -v -v -P/dev/ttyACM0 -b57600 -D -Uflash:w:[file.hex]:i

This doesn't work for me.

After try some trial and error I have built a simple binary to upload into the Leonardo bootloader. This binary opens serial at 1200 baud then closes it, and wraps the avrdude binary to write .hex into flash.
In Arduino core CDC.cpp we can see that CDC not only waiting baudrate 1200, but CDC checking DTR value. If DTR goes high, CDC cancels to jump into the bootloader. That's why I cleared DTR value. I tried this in Ubuntu 16.04.
https://github.com/vanbwodonk/leonardoUploader
Only use this simple command:
leonardoUploader /dev/ttyACM0 Blink.ino.hex

I hope it helps other people searching for this.

For a Windows solution look here: How can I force a Leonardo to reset with avrdude?. I made simple bat file wrapper that automates avrdude invocation.
It identifies Leonardo COM port with WMI, resets this COM port to 1200 baud with mode command, then identifies bootloader COM port and invokes avrdude.
Firmware is supposed to be placed to firmware.hex, but bat file can be changed to be supplied from command line.
I've put the code to GitHub repo: Simple wrapper for avrdude to allow firmware upload to Arduino Leonardo from command line.

This is a link only answer and should be revised or deleted.


text:
Why is my LCD 16*2 is not displaying any characters, although all the wiring is correct?
Recently I have linked up a typical 16*2 LCD (Liquid Crystal Display) display to my Arduino Uno and have linked all the pins up.
Here is my connection:(LCD pin first)
1=GND, 2=+5v, 4=11, 6=12, 11=5, 12=4, 12=3, 14=2, 15=backlight positive, 16=backlight negative
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis()/1000);
}

This is the code that is the default for the LCD, I didn't write it.
So I have done all this and when I turn it on the screen is blank and nothing is happening. Could anyone explain what I have done wrong?

What is connected to LCD pin 3? It is the contrast V0 and need to be connected with a 10 Kohm potentiometer. https://www.arduino.cc/en/Tutorial/HelloWorld

I found connecting the LCD v0 (pin 3) to a 1k resistor to ground worked and provides a fairly viewable contrast.

Check out this tutorial on Adafruit. It will walk you through setting it up. In the tutorial they change the pins, which I believe is the issue here. Here is a snippet.

And change your pins:
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

Recently I also faced similar problem, with connection as:
1=GND, 2=+5v, 4=11, 6=12, 11=5, 12=4, 12=3, 14=2, 15=backlight positive, 16=backlight negative
Solution: I just connected VEE (pin 3) of LCD to Ground (GND) without use of potentiometer as it worked.

This will get you by in a pinch but at some viewing angles the LCD is hard to read.

If you don't need to constantly adjust the LED backlight brightness you can use a fixed resistor in place of the potentiometer.

This solution also worked for me. Just connect the ground with VEE(pin3) and showing display

worked for me as well

What is connected to LCD pin 3? Pin 3 is the contrast V0 and needs to be connected with a 10 KOhm potentiometer.
Some LCD's need a negative contrast voltage, check the datasheet of the display.
If the contrast voltage is not correct the display will stay blank.
I came across the same problem until i saw the negative voltage must be applied :-)


text:
How can I use arduino board for AC mains?
I want to use LDR to control a light bulb (12W) which runs on AC supply using Arduino.
Is it possible to do this?
If yes, how?

Yes, with a relay. Ask google, it knows how.

Try the PowerSwitch Tail II.
This is suitable if you are living in the USA (120VAC power).
You will find 240VAC versions as a kit on that web page as well.

The quick and dirty answer is that you need something that will safely handle the mains voltage that you can control with the Arduino (which is running at 5 (or 3.3) volts). There are two issues you need to consider:

Safety – keeping the mains voltage separate from the Arduino and the other low voltage components so that nobody gets hurt.
Capability of components – avoiding damage to the Arduino and related components due to the mains voltage.

A common way of achieving the second goal is with either a relay or a solid-state component like a triac.
The first goal is often accomplished by using an optocoupler – a device that isolates the low-voltage circuitry from the higher mains voltage by means of an LED and a photo transistor in a common housing.
The circuitry around the relay and optocoupler aren't all that complicated but it isn't trivial either. You might look on e-bay – a search for "arduino relay" will find you lots of modules that will do the job for you.

If you want to switch it on/off, there is a simple solution using a relay and an optocupler (safer option) or transistor. Here is a schematic:

but if you want to control intensity of light, then you have to use triac control, which you have explained here: AC Phase Control.

You can use a relay shield like these:
Relay Boards - eBay
Be sure to check the amp draw of the relays. Sometimes you need a transistor, but I don't think you should for these shields. Just be careful working with mains voltage.


text:
Newbie need help to make a motor run for a laser scanner and some questions
I am trying to make a laser scanner consisting of a webcam and a line laser scanner. I have tried to use a manual scanning (by hand) and has worked, but would now like to consider automating the laser rotation (upwards and downwards) as a higher accuracy entails a slow and smooth rotation.
I came across arduino a few weeks back and realised it could possibly help to make this a reality. From my limited readings so far, I have obtained an Arduino Uno and a motor shield that seems to be the essentials for my purpose.
I have a few queries that hopefully someone can help:

Do I need a stepper motor for slow rotations, instead of a normal brushed motor?
Do I need to connect the Arduino to computer to make it run? Can I run it off battery, if so, does it have an 'ON' button?
How long will a standard 9V battery last?
For the code, I thought of using the simple one here: Arduino Motor Shield Tutorial.
Would it be able to allow me to control the amount of rotation, speed and the ability to reverse its rotation?

Look at the rotating muktisided mirror and LASER unit from many LASER printers - avaialable at little cosr of free from junked machines. These do more or less exactly what you want. You may need to exchange their LASER with your but they have dome the mechanical work for you.

A servo motor would have a lot more control than a normal motor. You usually command them to go to one of the predefined steps (stops) by using a function call in the servo motor library.
You can run independently of the computer. Many people do this. Certainly you can run off a battery. It doesn't have an ON button, you normally would have this between your battery and the Uno (eg. built into the battery pack). Like this:

A 9 V battery? I wouldn't use one, especially to drive a motor. It won't last long. Get something like 3 x AA batteries in a battery holder.

To show you the idea, I have this servo motor (SG-5010) I got from Adafruit.
I measured it using about 200 mA of power when operating. Now, I looked up a typical Alkaline 9 V battery, and found that, consuming 200 mA, it lasts for around 400 mAh. Thus, you could say it would be good for two hours at that rate. Plus, the Arduino will take around 50 mA, so maybe less than two hours.

A smallish servo motor won't need a motor shield. The pictures on the linked page show ordinary brushed motors. A servo motor has 3 leads:

Power (eg. 5 V)
Gnd
Data

Make sure you connect the grounds together, but the power could go to a separate power pack. A bit depends on how much power your motor will use. The data goes to the Arduino for the information about which rotation point to step to.
You should be able, in code, to change the rotation position, forwards and backwards.

Are you confusing stepper motor with something else? Stepper motors typically have 4 leads, two for each coil. Perhaps you are thinking of a servo? Or perhaps a stepper with a built in controller?

Quite right. I had a brain fade then. A servo motor has 3 wires as I described. I've amended the post to correct that. Thanks. :)

Nick gives some great advice, I am trying to answer your questions more directly.

Do I need a stepper motor for slow rotations, instead of a normal brushed motor?

Many kinds of motors can be made to work.  I advise starting with the same type as in the Instructables you mention below.  You can change the speed with gears if the motor speed range is not good enough.

Do I need to connect the arduino to computer to make it run? Can I run it off battery, if so, does it have an 'ON' button?

You only need to connect the Arduino to a computer to load or change the program. The motor is probably your biggest battery user, I would connect it to a separate battery from the Arduino. One advantage of the servo motors Nick mentions is that they are used by model car and airplane enthusiasts and there are lots of motors, batteries and battery chargers available.

How long will a standard 9V battery last?

Not long!

For the code, I thought of using the simple one here: Arduino Motor Shield Tutorial. Would it be able to allow me to control the amount of rotation, speed and the ability to reverse its rotation?

I looked through this code and it should work well as long as you use the same type of motor. You may have to modify things if you need the stop and start points to be very precise, but this will get you started and is a big step beyond scanning by hand.


text:
nRF2401 communication (extended vs normal)
Communicating to the antenna-less version from an extended range nRF2401 seems to produce some strange results...
At a distance, the receiver seems to receive a number of values instead of one. For example, if I send a 1, I will receive a 1, but 30 times.
Has anyone had experience communicating across the two models, or is it just best practice to stick to communicating across same models? (Short range <-> short range, long range <-> long range)?

I've run both version fine together
Your symptom of receiving the same value 30 times would be related to a failed ACK, so the sender thinks it hasn't been received and resends it.
I've had potentially similar problems with the power amplified version running at full power causing interference in nearby circuity, try dialling down the power setting on it.

I agree. I've used one with an aerial and one without, with no problems.

When you say try dialing down the power, what do you mean? It's running at 3.3v, which is the prescribed voltage. I'm using the rf24network library for what it's worth. Thanks for the help

Use RF24::setPALevel

Yes i meant power amplifier setting

Setting the power level didn't seem to have an effect on the issue. Can you elaborate on the failed ACK? Maybe that's actually what I'm dealing with. The issue only seems to occur at a distance, but not an unreasonable distance. I have two antennae-less nrf2401's that communicate fine from the same range.

So you tried setting the PA level on the external antenna based one to lower than default. ACK is short for 'acknowledgement' and is the receiving device sending back a message automatically to confirm it got the message.  Try this fork of rf24, i had better results with it after initially having trouble with the original.

I don't see a link, did you paste it? Thanks again for the help.

sorry , here it is: http://maniacalbits.blogspot.com.au/2013/04/new-rf24-driver-release-fork.html

@jmwagg What library were you using? Also, are you aware that clone modules may lack proper ACK functionality?


text:
Smart Chess-board (possibly using RFIDs?)
I'd like to make a chess-board with the ability to detect the position of each piece.
The solution that occurs to me would be to put an RFID reader under each square and put RFID tags on the bottoms of each piece.
However, apart from the obvious cost (64 readers!) I'm concerned that:

Maybe RFID readers are too large for the squares of an ordinary chessboard
RFID reader range is too large, so a reader might pick up pieces on neighbouring squares
How the hell would I connect 64 readers anyway? Could an Arduino handle it?

So, questions.
Is this just stupid? And is there a better technology to use for this kind of application?
If RFIDs are basically a sane solution, what are the issues/suggestions? E.g. which RFID readers should I go for? (Based on size, energy, convenience for this application). What boards would let me handle this number of them?

I think the RFID range is probably too high for accuracy, plus managing 64 readers would be hard (somehow you would need to multiplex 64 serial ports). What might work would be to have a single reader, and 64 fairly small aerials - one under each square. Then somehow organize to use each aerial in turn and check for the chip. Maybe all but one aerial could be grounded, for example. With small aerials the range might not be too large.

As I read your post an idea came to me that must be obvious in its simplicity.  Since a chess board has pieces already on it we can simply use hall-effect sensors (dirt cheap) under each square and each piece has a magnet at its base.  Since pieces on a chess board move from one square to another and the initial position of all pieces is known/constant, the detection of a move would be that a piece is lifted from the board (hall effect sensor detects a magnetic field removal) and a piece being placed on a square would be detected by a hall effect senor addition of a magnetic field.  We wouldn't know which piece is placed on a square but we can calculate it by remembering what piece was lifted and it can only be the piece that was placed.

I like the idea, it seems too simple, but maybe it would work perfectly. :)  There have been chess boards around for years that detect where the pieces are, they can't all have 64 RFID readers in them, so perhaps they use a system like what you propose. For that matter, what about a simple light detector, when you lift the piece, light hits the square underneath, so you know it has been lifted?

Yes. That might actually be a good, simpler solution.

Some early ones actually had buttons under the squares.  You'd have to push the piece you were about to move first, then move it to the other square and push it again.  Crude, but cheap and effective.  You can also add some sanity checking to your system.  "I know the piece moved to here. I know the pieces are in this position, so only these three pieces could possibly move to that position.  Which one did?  That one!"

A light-detector based solution would allow the players to use their own chess pieces rather than a specific set with magnets in the base. Furthermore, not having to rely on a particular set of pieces means you don't even have to play chess - you could implement a Draughts (Chequers) alternative software, or anything else played on an 8x8 board.

@chaaarlie2 - I like that idea however it would require that the board be modified (or already be somewhat transparent) to insert photo detectors beneath the board.  While I agree that needing a magnetic based for the pieces may be undesirable, so too might modifying the board.  I wonder how thin and small magnets could be?  I wonder if there are disc magnets with little width that might be easily attached to the base of pieces?

I'd say that constructing a board with light sensors is easier than constructing one with hall sensors + modifying pieces. Plus, if you're going with semi-transparent board topping, why stop at a passive interaction? You could add an LED beneath each square: when the player lifts a piece of the board, all the possible destination squares light up. Could be a great aid to teaching chess!

Neodymium magnets are tiny, at least when considering volume-to-strength ratio. Most chess piece sets would allow you to drill a small (5mm?) hole in the base and glue  a magnet into it. Not sure on the cost of those magnets though!

Brilliant idea but with one flaw: What happens when a pawn gets to the end of the board? How does this system know what someone has chosen to be?