body:
At this moment I am using oversampling to increase my analogread resolution.
This in combination with increasing the frequency of the ADC.
Is someone able to take a look at it?

    #define FASTADC 1
    // defines for setting and clearing register bits
    #ifndef cbi
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    int value[100];   // variable to store the value coming from the sensor
    int i=0;

    void setup()
    {
      Serial.begin(9600) ;
     int start ;
     int i ;

    #if FASTADC
     // set prescale to 16 (1MHz)
     sbi(ADCSRA,ADPS2) ;
     cbi(ADCSRA,ADPS1) ;
     cbi(ADCSRA,ADPS0) ;
    #endif
    }

    void loop()
      {
      for (i=0;i<100;i++)
      {
       value[i]=Read12bit(0);
      }
      for (i=0;i<100;i++)
      {
       Serial.println(value[i]);
      }
      Serial.println();//Some blanks between values
      Serial.println();
      delay(5000);

    }

    int Read12bit(uint8_t pin){
          int Result = 0;
          analogRead(pin);                      //Switch ADC
          for(int i = 0;i < 16; i++) {          //Read 16 times
            Result = Result + analogRead(pin);  //Sum results
          }
          Result = (int)Result/4;               //Divide by 4 for 12 bit value
          return(Result);
        }

At this moment the resolution of this oversampled analogread is 12-bits. With a little calculation the time to read will take 0,208milliseconds. If I want to increase my resolution more i.e. 13-bit. This will take the measurement 0,832 milliseconds. This seems rather big, so my question is can I do this in another way?

EDIT
**Why?**
*I am trying to position multiple linear actuator using multiple arduino's connected via CAN-bus (the arduino's will not communicate with eachother unless an error occures) THe positioning has to be precise (<0.1mm on a 30 cm rod).*

**Why is 12 or 13 bit accuracy and/or resolution needed?**

*12 is probably enough. But I just like to find out the boundaries of the equipment :)*

**What real world processes are being monitored that 0.012% perbit step sizes are not swallowed in the noise of reality?**

Probably none 13-bit resolution is probably too high for my application anyways.

**Other reason why I like a higher resolution**
First couple of voltages I cannot use. My sensor gives a 4 to 20mA signal which i convert with resistor to ground.

title: Increasing ADC resolution

Answers: 4

body:
Yes, you can use an external ADC chip. You can get SPI and I2C ΣΔ ADC chips at 16-bit and higher quite easily.

I often use the [MCP3553](http://www.microchip.com/wwwproducts/Devices.aspx?product=MCP3553) which allows 60sps at 22-bit.

body:
This is in response to the question.
It is an answer to the extent that it says that

 - The current method may not work (several reasons given),

 - There may be better ways to do it, and

 - Is it necessary?

Addressing these points, or knowing that they have been addressed, is an essential part of arriving at a good solution .

If we knew the desired conversion time and actual desired resolution it would allow better answers.
If we knew what you were trying to do it might help immensely.
ie knowing what you are really trying to do may allow a quite different approach to be suggested or allow a fatal flaw to be identified.

Apart from the statistical sampling considerations that you are addressing, you cannot usually extend ADC bits indefinitely by oversampling with any great  expectations of accuracy. Oversampling works on the basis of the variable + noise being linearly randomly distributed across the 'space' at least 1/2 a bit size either side of the true value. And it makes assumptions about ways in which ADC sample and hold and acquisition gating and more work.
As you try to squeeze more bits out of the ADC the assumptions become less likely to be consistently valid.

Also, implementation of the analog input circuitry initially becomes important and then immensely important as bits of ADC resolution increase (whether achieved by over sampling or other means).

12 bits  = 0.0244% per step (as you know)
or 1.22 mV steps in a 5V reference system
or 0.81 mV/bit in a 3.3V reference system.
Getting your overall system working to that level of accuracy is possible but usually not achieved.
Any reference you are using will be natively much less accurate than that and those sort of accuracies will require calibration both initially and possibly ongoingly.
Ratiometric systems, where eg the excitation voltage of a bridge also serves as a reference, allow reference accuracy to notionally be perfect (as readings and excitation are the same and move together.
However, ensuring that the voltage at the controllers Aref pin wrt controller Agnd, and the bridge's excitation pin wrt the bridge's ground input are the same  within usefully under 1.22 mV in a 5V 12 bit system (0.6 mV in a 13 bit system, and that the bridge and controller grounds are the same within say a few hundred uV, are an obvious necessity if the 13 bits of resolution are to be meaningful - but unlikely to be achieved without the most exquisite attention to both design & implementation. (Ask me how I know :-).)

Generally, it will be much easier to obtain and maintain ADC resolutions of as many bits as are needed by the use of purpose designed conversion ICs operating as close to the signal source as is reasonably possible. (Or using instrumentation amplifiers to acquire the signals and reliably "convey" them elsewhere.) Knowing desired conversion times and resolutions is a necessary first step.

**BUT**

Why?
Why is 12 or 13 bit accuracy and/or resolution needed?
What real world processes are being monitored that 0.012% perbit step sizes are not swallowed in the noise of reality?
Such requirements - and much more accurate again, certainly do exist.
But knowing what the actual application is may help with decisions of how to meet it.

body:
you squeezing run time, I wonder, how much time you may save,
if instead of looping to measure you do 16 times +=
and >>2 instead /4
an another optimization to make  an own analog read function, it would be pretty simple based on original, so in additional you save time to call read function 16 times with all CPU overhead for each call.

lastly, in your own read function run the ADC in free run mode and accumulate a significant amount of data samples for oversampling.

body:
In my tests, the Arduino ADC starts to suffer from accuracy issues when you push it to 500kHz for oversampling, but 250kHz does not suffer from this problem. Also you need some kind of dither/noise, or the oversampling does not really work. I found that pulsing a digital pin with a resistor connected to ground gave me enough noise for the techinque:

https://edwardmallon.wordpress.com/2017/02/27/enhancing-arduinos-adc-resolution-by-dithering-oversampling/


body:
Sorry for bothering.
I have a problem with my project and I can't fine someone who can help me yet.

I need the next configuration:
PC --------------USB cable-----------------MegaA---------------USB cable----------------MegaB

I need serial communication with USB cable in both boards.

I have now solved the ( PC --------USB cable------MegaA) part.

And the other part, I have done PC------------------USB cable------------------MegaB

But I need do that like the first schematic.
I don't have access to the MegaB because this is inside a machine, I can't access to its pines, I need connect to it by USB Cable.
Is possible do that with ARDUINO MEGA ADK in the MEGA A position? or I need other kind of board or add one shield (like USB host)?
I need send one thing from the pc to MegaA and Mega A send the same thing to MegaB.
Is it possible? because I can't find some way to specify that I need recieve the information from one serial port, and send it to another different serial port.
I need help, is very important.
Excuse my english
Thanks

title: Arduino ADK, other board, shield or what?

Answers: 3

body:
A USB host is far beyond what an AVR Mega handle. You could add a 'daugther' board of some kind, but that would be a computer far more powerfull than the Mega itself (think of a RaPi, or a fat 32-bit micro-controller), so it would be a bit weird.

You might physically patch the first USB through to the second one, using for instance a relay. That would allow the PC (but not the first Mega) to talk to the second Mega.

body:
You don't actually need to use serial-over-usb, the two devices can communicate more simply. The simplest way would be to Serial1, which uses pins D18 and D19; connect Serial1 on MegaA to either the serial or serial1 on MegaB. Since MegaA's transmit is MegaB's receive, you need to cross-over the wires (i.e. connect MegaA's TX to MegaB RX and vice versa).

Complete details can be found at: http://www.arduino.cc/en/Tutorial/MultiSerialMega

Make sure the two Megas have a common ground - the easiest way is to use one power supply (in your case, the USB) - you should just be able to wire GND and +5V from one board to the same pins on the other. If you use two different power supplies (e.g. two USB ports, even on the same PC), they may have different ground levels, and you can get a current flow directly out of one ground, and in to the other, damaging your PC.

body:
You would need a USB host shield to achieve what you want.

The Arduino by itself is not capable of connecting to both a PC and another Arduino through USB without the addition of extra hardware.  In this case the USB Host Shield as detailed on the Arduino website:

http://www.arduino.cc/en/Main/ArduinoUSBHostShield

In the list of supported devices is:

* USB to serial converters: FTDI, PL-2303, ACM, as well as certain cell phones and GPS receivers.

The magic word there is ACM - that (or more specifically CDC/ACM) is what the Arduino USB Serial interface is.


body:
I just downloaded the latest version of the Arduino software (1.6.5). However, when I look into the Application Support folder under Library (I have a mac), I find that I have a folder named 1.6.3:

   Library ▸ Arduino15 ▸ packages ▸ arduino ▸ hardware ▸ sam ▸ 1.6.3

Does this mean there is a hidden 1.6.5 folder that I am not seeing?

BTW, this issue surfaced, because I am trying to fiddle around with the ADC clock speed, but it seems that nothing is happening:

    void setup() {
      #define ADC_FREQ_MAX = 1;
      Serial.begin(9600);
      Serial.println(ADC_FREQ_MAX);
    }

    void loop() {
    }

gives me:

    opamp.ino: In function 'void setup()':
    opamp:2: error: expected primary-expression before '=' token
    opamp.ino:4:18: note: in expansion of macro 'ADC_FREQ_MAX'
    opamp:4: error: expected primary-expression before ')' token
    opamp:4: error: expected ';' before ')' token
    expected primary-expression before '=' token

title: I am running 1.6.5, but the folder says 1.6.3?

Answers: 2

body:
1.6.5 is the version of the Arduino IDE.

1.6.3 is the version of the Arduino SAM Boards package that you have installed.

>Does this mean there is a hidden 1.6.5 folder that I am not seeing?

Library/Arduino15 is where your preferences.txt file and Boards Manager index files are stored. Library/Arduino15/packages is where hardware packages installed via **Tools > Board > Boards Manager** are stored. The Arduino IDE will be located elsewhere on your hard drive. If you need to find it here is an easy way:

1. **Tools > Examples > 01.Basics > BareMinimum**
2. **Sketch > Show Sketch Folder** - this will open the Examples/01.Basics/BareMinimum subfolder of the Arduino IDE installation folder.

>BTW, this issue surfaced...

That's off the topic of your question and already answered in a comment on your question so I will refrain from answering it.

body:
The error you see is because of the equal sign in your #define.  That equal should not be there. So the line that uses it ends up being.

Serial.println(= 1);

Which is obviously wrong.


body: I have a simple code, part of which contains the calculation 800/1000, which seems to return a value of zero for some reason (even though I store it in a float variable). When I replace the calculation with the expected result (0.8) the code works as expected, I just wonder why the calculation doesn't produce the same result.

title: Weird Arduino math result

Answers: 2

body: A whole numbers like 800 or 1000 are integers, while a number like 800.4 is considered fractional and is treated as a float. Two integers divided gives an whole integer result, in your case 0. If one number in the division is an integer, and one is a float, the result is a float.

body:
Both 800.0/1000 or ((float)800)/1000 will work.

The former works only with hardcoded constants, while the latter works also with variables:

    int a = 800;
    int b = 1000;
    float c = ((float)a) / b;


body:
I have an mpx12DP pressure sensor that I want to use to measure the depth of water in a 1m tall water tank.

But it only measures up to 55mV of voltage change, which the arduino can't really detect changes in. (The sensor measures 0 to 1.45psi- 1m of water should give me 1.4psi, so I should be able to get really good accuracy).

Is this as good sensor to use for this purpose? How do I amplify the signal from the sensor? I have tried an LM324 op-amp, but couldn't get it to work (this may be entirely the wrong thing to use! And I was utterly unsure of the kind of circuit to use it in). Any advice on parts.. schematics.. a suitable already-amplified sensor that reads only up to 1.45psi?

Thank you,

Pressure sensor datasheet: http://www.digikey.co.uk/product-detail/en/MPX12DP/MPX12DP-ND/684659
Op amp datasheet: http://www.ti.com/lit/ds/symlink/lm124-n.pdf

title: Reading tiny voltage changes

Answers: 3

body: You could try using `analogReference(INTERNAL);`, to reduce the upper range of the ADC to 1.1volts, thus giving you better voltage resolution.

body:
Your sensor has differential output, with a voltage difference between the Vout+ and Vout- being the measurement. The span of this difference is 0 to 55mV. The reason the sensor is wired this way is to reduce noise. To amplify this type of output you would need a differential output amplifier which is more complicated than a single op amp.

However, you can also just wire the Vout- from the sensor to ground, and then use the sensor as a single-ended output from 0 to 55mV (noise might be a problem). If you do this, you can then amplify Vout+ with your LM324 op-amp as described on page 13 of the LM324 datasheet with a non-inverting amplifier. By setting the ratio of R2/R1 to 60, you would get up to 55mV*80 = 4.4V which is pretty good.

The op amp needs some voltage headroom, so if you are using 5V supply for it, don't set the amplified voltage max to 5V.

edit: I don't think you need much headroom and 4.4V will give you better resolution than 3.3V

body:
It is reasonable to use  `analogReference(INTERNAL);`, as suggested by Alexander M, to set the range of the ADC to 1.1 V.

Another alternative is to use two resistors to make a voltage divider, to make an external reference of 1 V (min.) at the AREF pin, and then use  `analogReference(EXTERNAL);`, but the Arduino's supply voltage is likely to be noisier than the internal reference.

Regarding tiggun's suggestion about grounding the V- pin, it isn't clear to me that the mpx12DP will function correctly with V- and ground connected together.

In any case, you can use two or three of the op amps in the four-op-amp LM324 package to make a differential amplifier or an instrumentation amplifier.  See figures 38 and 39 on page 20 of the [LMx24 datasheet](http://www.ti.com/lit/ds/symlink/lm124-n.pdf) mentioned in the question.  Figure 38 shows a differential amplifier; you could, for example, replace R3 with a 50KΩ resistor and R4 with a 1MΩ resistor to get a voltage scaleup of about 21, via the formula shown: Vₒ = (1 + R4/R3)·(V₂-V₁).  Alternately, you can use a small variable resistor as in figure 39 to make a variable-gain instrumentation amplifier.


body:
I need your suggestions and help with my Ping Sensor.
I have an Arduino Uno with a Parallax Ping sensor and a motor.

My ping sensor is set to to start the motor when the nearest object is <= 10cm. That works fine.
Now, I'd like the motor to start only if the values of the sensor are progressing in a decreasing manner i.e 15, 14, 13, 12, 11, 10 but do nothing if the values are progressing in a increasing manner.

I was thinking if I stored the last 3 pings as variables and using an if/else statement but I don't know how to implement it.

How can I implement this, or if you have any other suggestion, please help me.
Thank you

Here is what i have so far:

    /* Ping))) Sensor

       This sketch reads a PING))) ultrasonic rangefinder and returns the
       distance to the closest object in range. To do this, it sends a pulse
       to the sensor to initiate a reading, then listens for a pulse
       to return.  The length of the returning pulse is proportional to
       the distance of the object from the sensor.

       The circuit:
     * +V connection of the PING))) attached to +5V
     * GND connection of the PING))) attached to ground
     * SIG connection of the PING))) attached to digital pin 7

       http://www.arduino.cc/en/Tutorial/Ping

       created 3 Nov 2008
       by David A. Mellis
       modified 30 Aug 2011
       by Tom Igoe

       This example code is in the public domain.

     */

    // this constant won't change.  It's the pin number
    // of the sensor's output:
    const int pingPin = 7;
    const int motorPin = 9;
    //Yomis code
    //int pings[3] = {-1,-1,-1};
    //int i;
    //bool Increasing(int p1, int p2, int p3)
    //{
    //  if(p1 < p2 && p2 < p3){
    //    return true;
    //  }
    //}
    //
    //bool Decreasing(int p1, int p2, int p3)
    //{
    //  if(p1 > p2 && p2 > p3){
    //    return true;
    //  }
    //}
    //
    //end of yomis code
    void setup() {
      // Set up the motor pin to be an output:

      pinMode(motorPin, OUTPUT);

      // initialize serial communication:
      Serial.begin(9600);
    }

    void loop()
    {

      // establish variables for duration of the ping,
      // and the distance result in inches and centimeters:
      long duration, inches, cm;

      // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
      // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
      pinMode(pingPin, OUTPUT);
      digitalWrite(pingPin, LOW);
      delayMicroseconds(1000);
      digitalWrite(pingPin, HIGH);
      delayMicroseconds(2000);
      digitalWrite(pingPin, LOW);

      // The same pin is used to read the signal from the PING))): a HIGH
      // pulse whose duration is the time (in microseconds) from the sending
      // of the ping to the reception of its echo off of an object.
      pinMode(pingPin, INPUT);
      duration = pulseIn(pingPin, HIGH);

      // convert the time into a distance
      inches = microsecondsToInches(duration);
      cm = microsecondsToCentimeters(duration);

      Serial.print(inches);
      Serial.print("in, ");
      Serial.print(cm);
      Serial.print("cm");
      Serial.println();

      delay(1000);

    //        //Yomis code
    //        if (cm <= 10)
    //        {
    //          Serial.println();
    //          Serial.println(pings[0]);
    //              Serial.println(pings[1]);
    //              Serial.println(pings[2]);
    //          Serial.println();
    //          if(Increasing(pings[0],pings[1],pings[2]))
    //          {
    //            int Speed1 = 100;  // between 0 (stopped) and 255 (full speed)
    //            int Time1 = 3000;  // milliseconds for speed 1
    //            analogWrite(motorPin, Speed1);  // turns the motor On
    //          }
    //        }
    //        else
    //        {
    //          analogWrite(motorPin, LOW);
    //        }
    //
    //        //End of yomis code

      if (cm <= 10) {

        int Speed1 = 150;  // between 0 (stopped) and 255 (full speed)
        int Time1 = 2000;  // milliseconds for speed 1

        int Speed2 = 250;   // between 0 (stopped) and 255 (full speed)
        int Time2 = 3000;  // milliseconds to turn the motor off

        analogWrite(motorPin, Speed1);  // turns the motor On
        delay(Time1);                   // delay for onTime milliseconds
    //    analogWrite(motorPin, Speed2);  // turns the motor Off
    //    delay(Time2);                   // delay for offTime milliseconds
      }
      else if (cm > 10) {
        analogWrite(motorPin, LOW);  // turn the motor off
      }
      else {
        Serial.print(inches);
        Serial.print("in, ");
        Serial.print(cm);
        Serial.print("cm");
        Serial.println();

        delay(100);
      }

    }

    long microsecondsToInches(long microseconds)
    {
      // According to Parallax's datasheet for the PING))), there are
      // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
      // second).  This gives the distance travelled by the ping, outbound
      // and return, so we divide by 2 to get the distance of the obstacle.m
      // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
      return microseconds / 74 / 2;
    }

    long microsecondsToCentimeters(long microseconds)
    {
      // The speed of sound is 340 m/s or 29 microseconds per centimeter.
      // The ping travels out and back, so to find the distance of the
      // object we take half of the distance travelled.
      return microseconds / 29 / 2;
    }

title: How to Store the results from a Ping Sensor in a variable

Answers: 4

body:
The general idea of your code is fine, but it can be tweaked to make it more efficient.

Firstly, your function `increasing(int p1, int p2, int p3)` can be simplified to `increasing(int *pingArray)`. This way you pass a *reference* to the function, rather than three `int`s. If you decide later that your `pings` array needs to hold more values you don't have to change the function arguements. However, if you're going to be experimenting with different lengths of the `ping` array you need to make sure you change the code *within the function* to reflect this. An easy way to stay on top of it is with `#define`:

    #define MAX_PINGS 3       // Put this at the start of your code somewhere

    int pings[MAX_PINGS];     // When you come to declare 'pings'
    for (int x=0; x<MAX_PINGS; x++)
        pings[x] = -1;        // Whatever each element is initialised to.

    // Your 'increasing' function
    //   (... and the same for 'decreasing', if you decide to use it!)
    bool increasing(int *pingArray)
    {
        // CODE GOES HERE
        // and it doesn't matter how long pingArray / pings is
        // because you have 'MAX_PINGS' defined.
        return true;
    }

    // You call the 'increasing' function as you'd expect:
    if (increasing(pings))
    { /* stuff */ }

Now to the concentrating:

Your initial work is good but from what I've read on ultrasonic sensors, and from experience with any generic sensor, is that the readings aren't going to be perfect. The real world is a noisy place and you aren't going to get nice, accurate distance readings. Finding the average is a simple technique, but you will need to find an optimal solution yourself. Once you have your nice row of average values you can then determine if the distance is increasing or decreasing or neither.

Thus you have two steps:

# Average the distance
Create an array (`dist`, for now) and use it to find the average distance your sensor is from an object.

    #define MAX_DIST 5

    int dist[MAX_DIST];    // create an array, no need to initialise.
    double distAverage;    // average distance, could be 'int' instead.
    int distIterator = 0;  // 'dist' will be a CYCLIC BUFFER. woooOOOOooo.

    // As you get the distance from your sensor, update 'dist' and
    // then calculate the running average.

    dist[distIterator] = microsecondsToCentimeters(duration);
    distIterator++;
    if (distIterator == MAX_DIST) distIterator = 0;
    distAverage = 0.0;
    for (int x=0; x<MAX_DIST; x++)
        distAverage += dist[x];
    distAverage /= MAX_DIST;

I hope you understand the cyclic buffer principle - if you don't you can google it! A key point about the way the code above is constructed is the use of that `#define MAX_DIST 5`. You can change that single number to anything and your code will change along with it. You will discover that there is an optimum number; I can't tell you what it is (but I recommend it remains odd).

Now that you have a nice *reliable* distance measurement, you need to find if it is increasing or decreasing...

# Average the averages
As you have worked out, you need an array of values to determine if the distance is increasing. Bring in, again, the cyclic buffer.

    #define MAX_DIST 5     // these could also be 'const int's
    #define MAX_AVRG 3     // but my preference is this way

    int dist[MAX_DIST];    // create an array, no need to initialise.
    int distIterator = 0;  // 'dist' will be a CYCLIC BUFFER. woooOOOOooo.
    int distAvrg[MAX_DIST]; // create an array of averages.
    int avrgIterator = 0;  // wwwwoooOOOOooo ? Not this time.

    // There's no single 'distAverage' anymore; the result dumps straight
    //into 'distAvrg[avrgIterator]'...

    dist[distIterator] = microsecondsToCentimeters(duration);
    distIterator++;
    if (distIterator == MAX_DIST) distIterator = 0;
    distAvrg[avrgIterator] = 0.0;
    for (int x=0; x<MAX_DIST; x++)
        distAvrg[avrgIterator] += dist[x];
    distAvrg[avrgIterator] /= MAX_DIST;
    avrgIterator++;
    if (avrgIterator == MAX_AVRG) avrgIterator = 0;

Now you have an array of your averages. Winner.

From here you can create your `increasing`/`decreasing` function. I'll leave most of this up to you, but consider the following:

 - The contents of `distAvrg` may not be perfectly smooth;
 - The longer any of the arrays, the more reliable the average;
 - The longer the array, the slower the response of the 'machine';
 - Using `int` rather than `double` for `distAvrg` may help 'numb' some of the fluctuations in averages;
 - Because `distAvrg` is a cyclic buffer, when analysing it *make sure you start at the correct element!* **HINT:** If you add your increase/decrease function *after* all the code above rather than amongst it, `avrgIterator` will always point to the *oldest* average value;
 - If the `distAverage` array gets beyond three of four elements, you should definitely *pass it by reference* to the relevant functions; this is what I did in the first codeblock I wrote. It's beyond this answer to explain why you should do it other than "it's more efficient". This is a general rule for any large chunk of data, but you'll learn more as you go along.

The simplest algorithm for determining whether the `distAvrg`s are increasing or decreasing is to run through from oldest to newest and count how many *increases* there are and how many *decreases* there are:

    int direction = 0;
    for (x=oldest ... x=newest)
    {
        if (x > x+1) direction++;
        if (x < x+1) direction--;
    }

The above is pseudo-code - you'll have translate it yourself. You end up with a value of `direction` that is a positive number (increase), a negative number (decrease), or zero. The actual value of `direction` will help you determine the speed of the increase/decrease, if it's relevant.

----------
# A possible solution:

> ** EDIT ** As pointed out by @EdgarBonet, `double` and `float` are 'expensive', in that they take up a lot of computing cycles to be dealt with. The Arduino website recommends avoiding them if you can. The alternative is to use scaled `int`s. For example, multiplying the return value from `microsecondsToCentimetres()` by 10 will give you the equivalent of one decimal place's worth of extra precision. No other code needs to change unless you're outputing the value on an LCD or similar and want it in centimeters. Dividing by 10 is conveniently the distance in millimeters, which is why I picked it, but there's no reason you can't scale by a different factor. Just be aware that there is a maximum (and mirrored minimum) value that `int` can hold, but I doubt you're going to hit it unless you scale by an unnecessarily high factor.

Let's say `MAX_AVRG` is `6`. This gives five *changes* between distances to look at. The simplest function for determining an increase is:

    bool increasing(int * DIST)
    {
        int dir = 0;

        for (int x=1; x<MAX_AVRG; x++)
        {
            if (DIST[x] > DIST[x-1])   // change this to < for DECREASE
                dir++;
            else
                dir--;
        }

        if (dir > 0)
            return TRUE;
        else
            return FALSE;
    }

The 'decrease' version is identical, save for the single commented line. The `for` loop starts at the *second* sample and checks against the *previous* sample, which is why `x` starts at 1, not 0 as 'usual'. The return value will be `true` if `distAv` has increased more times than it has decreased, and vice versa for decreasing().

Let's say distAve = { 1, 2, 1, 3, 4, 5 }. In the function:

    distAve   1   2   1   3   4   5
                ^   ^   ^   ^   ^
    start       |   |   |   |   |    dir = 0
    increase   -'   |   |   |   |    dir = 1
    decrease       -'   |   |   |    dir = 0
    increase           -'   |   |    dir = 1
    increase               -'   |    dir = 2
    increase                   -'    dir = 3

    dir > 0 therefore INCREASE.

But what if distAve = { 5, 4, 3, 2, 1, 6 } ? If `increasing()` will now return `false` because there are four decreases vs one increase, except the final distance indicates that the sensed object has ended up at an increased distance than when it started.

    int distance(int * DIST)
    {
        int overallDistance = 0;
        for (int x=1; x<MAX_AVRG; x++)
            overallDistance += (DIST[x] - DIST[x-1]);
        return overallDistance;
    }

Now you have an explicit value for the overall distance change.

body: Okay but why is everyone arguing about const and #define. That's clearly not the real problem that the person who posted the question is asking, so i'm kind of lost. @chaaarlie2. What exactly does averaging the averages do, since the distances have already been averaged to find the correct distance.

body:
I would use subtraction to find a decreasing series
you can subtract the new ping output from the previous one in every loop this way you can scale to a longer series without allocating more memory for the array

assuming you have defined somewhere:

    /*use whatever number you want here*/
    #define SERIES_LENGTH 3

declare globally:

    int prevPingSample;
    int decCount = 0;

than in your loop:

    int pingSample = analogRead(sensorPin) //or however else you sample the sensor
    if (prevPingSample > pingSample)
    { /*if the new reading is smaller than the previous -  the series is decreasing*/
     decCount = decCount + 1;
    }
    if (decCount >= SERIES_LENGTH)
    {
        //move motor code
    }
    else
    {
        decCount = 0;
    }
    //and whats left is to update the previous ping sample for the next loop
    prevPingSample = pingSample;

body:
A simpler solution. Use a variable to detect the trend and another for previous distance. Initialized to false and a very large number respectively.

Once a new distance is available the two variables are updated. If the trend is decreasing and the distance is less than your desired distance activate the motor.


body: Can you use the internal pull-up on an ADC pin? Is it correct usage? Example of hardware usage would be a cadmium photocell between *Ax* and *GND*. Software is the same, except declaring *Ax* as INPUT_PULLUP instead of INPUT.

title: Analog INPUT_PULLUP for resistive sensors?

Answers: 1

body:
> Can you use the internal pull-up on an ADC pin?

Yes.

> Is it correct usage?

No. The exact pullup resistance varies from pin to pin and chip to chip, so depending on it for the high side is problematic at best.

Ideally you should be disabling the digital circuitry on an analog input entirely by writing to the `DIDR0` and `DIDR1` registers appropriately.


body:
I am trying to convert a RC car into autonomous car using Arduino Pro Mini 5v 16 Mhz. I have done this with UNO and Adafruit motor shield 1.0 with 4 gear motors and one micro servo for mounting range finder sensor. That worked fine.

Need to mention here that originally the RC car was using 5 AA cells for 2 motors and its RC reciever which looks like a customized motor shield as well.

I tried to move everything to Arduino Pro Mini 5v, and motor shield v1 to reduce space. Now how I wired everything.

1. Uses 8 AA cells to power the motor shield on EXT-PWR input.
2. From EXT-PWR in motor shield one wire goes to RAW in Pro mini.
3. From Pro Mini, VCC connected to +5v on motor shield.
4. One micro servo having range sensor getting its current from motor shield.
5. Motor shield has to run two motors, 1 for rear wheels and 1 for turning front wheels. (they are small motors look like 3v)

Now when I turn on the power the motor sometimes run and sometimes sound like bee and no movement. That also cause the L293d chip on motor shield becomes very hot and I think I have burnt one yesterday and replaced it from another motor shield. Same for servo it sometimes move or not move but sounds like hmmmmmmmm. The Arduino power light on and red. But sometimes it flickers and other light is also on and off.

At this point I have no idea whats wrong here. I changed the input voltage to lower but no progress. Tried to disconnect the 5v input from Pro Mini to motor shield and give 9v input to motor shield but nothing works. Please suggest best or correct power distribution in this case.

Thanks

Qazi

title: Pro Mini 5v with Adafruit motor shield v1 power sharing problems

Answers: 2

body: I would check each motor without the motor shield to see if the motors are ok. Check the motor shield motor supply, should be around 12 volts with 8 AA cells. You might run a simple test program to see if the motors run full power forward and full power backward with the motor shield. Check the servo with a simple program like the Arduino Knob program. I suspect the Pro Mini 5 volt regulator is overloaded, causing the buzzing sound, but you have to find out why. One possible reason is that you are dropping from 12 volts to 5 volts via the pro mini linear regulator, creating all kinds of heat. The additional load of even a small servo might push the power dissipation spec over the edge.

body: Sounds good, a more capable linear regulator with heat sink. Another possibility is to get a DC to DC converter (buck regulator from 12 volts to 5 volts), that way is more energy efficient than a linear regulator. They cost just slightly more than a linear regulator on ebay, and don't need a heat sink.


body:
I need to put out 5 volts from an Arduino UNO digital pin. I've read that the pins can do approx. 5 volts, but I need to know if it will actually reach 5. I'm also powering a few other devices from the Arduino.

Are the digital pins capable of emitting 5 volts consistently? Are there any better alternatives?
Thanks.

title: Programmed 5 Volt output to power a relay

Answers: 1

body: Your concern for the output capability of the pin should be its current sourcing or sinking capability, not its voltage. Arduino pins typically have a limit of 40ma per pin and a total maximum of 200ma. This is for the Atmega328p (you didn't say which Arduino you're using. You'll need to drive motors or relays or anything else with a substantial current requirement with a driver circuit powered independently of the Arduino itself. That can be with a shield made for the purpose or a circuit you design and build into your project. Motors and relays in particular need snubber diodes to protect the driving circuits from inductive "kickback" or spikes generated in their coils.


body:
I would like to convert an array of bytes, received from serial, to a float.

Let's consider this exemple. I'm sending 0.12 byte-wise from an Android application. The conversion from float to array of bytes in the Android side is handled by this function

    public static byte [] float2Bytes(float value)
        {
            return ByteBuffer.allocate(4)./*order(ByteOrder.LITTLE_ENDIAN).*/putFloat(value).array();
        }

When bytes arrive, they are stored in an array and the assembled.

    hiBytew1 = bufferBytes[9];
    //Serial.println(hiBytew1);
    loBytew1 = bufferBytes[10];
    //Serial.println(loBytew1);
    hiBytew2 = bufferBytes[11];
    //Serial.println(hiBytew2);
    loBytew2 = bufferBytes[12];
    //Serial.println(loBytew2);
    float conAck = assemble(hiBytew1, loBytew1, hiBytew2,loBytew2);

How can I achieve this kind of conversion assuming that bytes are received in the correct order?

title: Assembling a float from an array of bytes

Answers: 1

body:
Just cast the pointer.

    float conAck = *((float*)(bufferBytes + 9));


body:
I am trying to communicate between my PC and Arduino Mega 2560 using this serial [library][1]. It works reliably, however I am having trouble passing messages at a high rate over serial. I set the baud to 460800 bps on both systems, and am using a serial handshake. The Arduino reads the values by parsing a string, however during my testing I cannot parse more than ~240 messages per second. Each message into the Arduino is either of the form "r/n" to reset some variables or "0,0,0\n" where in this case the zeroes are the ints I want to parse, these can change. My Arduino code in the loop is as follows:

    if(Serial.available() > 0){
      resultString = Serial.readStringUntil('\n');
      if(resultString.equals("r")){
        countEnc0 = 0;
        countEnc1 = 0;
        countEnc2 = 0;
      }else{
        int counter = 0;
        int lastIndex = 0;
        for (int i = 0; i < resultString.length(); i++) {
          // Loop through each character and check if it's a comma
          if (resultString.substring(i, i+1) == ",") {
            // Grab the piece from the last index up to the current position and store it
           write[counter] = resultString.substring(lastIndex, i).toInt();
           // Update the last position and add 1, so it starts from the next character
           lastIndex = i + 1;
           // Increase the position in the array that we store into
           counter++;
          }
          // If we're at the end of the string (no more commas to stop us)
          if (i == resultString.length() - 1) {
            // Grab the last part of the string from the lastIndex to the end
            write[counter] = resultString.substring(lastIndex, i+1).toInt();
          }
        }
        analogWrite(8, write[0]);
        analogWrite(9, write[1]);
        analogWrite(10, write[2]);
      }
      Serial.println(String(countEnc0) + "," + String(countEnc1) + "," + String(countEnc2));
    }

I know there are more efficient ways to parse this, however my attempts to use them yield similar results (Using parseInt(), char*, etc). Additionally, I am using 3 interrupts to read sensor values and store them in variables here, and writing the values I acquire to the PWM. As long as I can read and send up to 1000 messages per second that's all I need for now. Many thanks...been banging my head against the wall on this one.

  [1]: https://github.com/wjwwood/serial

title: Parsing Int over Serial Slow

Answers: 3

body:
First off, I would recommend [ `strtok`][1] or even `getline` to parse comma delimited strings.

Secondly, I'm pretty sure no PWM is responsive enough for 1000 updates per second. But for other purposes this data rate might be needed.

To do this, build a custom cache that does the following:

 1. Reads 1000 characters per go, if available, or less.
 2. Parses on the go. From this set up callbacks to you PWM class, so that you can set PWM values while parsing.

Why this? I am not convinced that the sluggishness is due to the `for` parsing data. More likely, it's because you are processing every instruction as you get it.

1000 serial reads with 6 length `for` loops over strings (your case) will be significantly slower than 1 serial read and a 6k length `for` loop.

  [1]: http://www.cplusplus.com/reference/cstring/strtok/

body:
If your bottleneck is really in the parsing (and you should confirm this before you spend any effort to optimize it), eliminate the parsing.

I usually recommend sending ASCII strings on serial channels to make debugging simpler, and I'd still suggest you get everything working this way first, even if you can't make the sample rate you need.

Once you're convinced your system works except for its speed, you can replace the ASCII communication with raw binary. A simple protocol would suffice: 3 or 6 bytes (do you need `int16_t`s?) of data and a 1 byte checksum downstream, and an ACK / NAK byte upstream to trigger a resend if needed, will probably be more than sufficient.

The receiver would only have to confirm the checksum and process the already ready-to-go binary sample values.

body:
The String class is slow. I would get rid of that first. I am confused about whether you are sending or receiving, or both, as your code seems to parse and then send. See this test code here:

    int countEnc0 = 123;
    int countEnc1 = 456;
    int countEnc2 = 789;

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();

      unsigned long start = micros ();
      Serial.println(String(countEnc0) + "," + String(countEnc1) + "," + String(countEnc2));
      Serial.flush ();

      Serial.print ("Time taken = ");
      Serial.print (micros () - start);
      Serial.println (" uS");
      }  // end of setup

    void loop () { }

That replicates the time taken for that one line which echoes the three figures. My results were:

```Time taken = 1632 uS```

OK, yours will be faster at the faster baud rate, but only 4 times as fast.

So, 240 times that and allowing for the faster baud rate gives:

    1632 * 240 / 4 = 97920 µS

That's a fair bit of that second gone (a tenth), without even parsing anything.


body:
I'm trying to compute Johnson resistance noise in a simple resistor circuit. However, since all frequencies contribute equally, I am getting an answer of infinity.

It then dawned upon me that the Arduino ADC probably detect frequencies larger than some cut off given by something called the full power bandwidth. Does anyone know this spec for the Due?

title: Due ADC specs: full power bandwidth

Answers: 0


body:
I've got an application that requires moving to specific points on a file on an SD card, reading, modifying and then writing an update.  The file is fixed size.  The code has no problems moving to the specific offsets required and then reading in blocks of data.

However, when the code does a seek() to the next desired location, then a write() and a flush(), the data is not written.  If my code seeks back to the start of the block just written and reads it back, it does not contain the new data.

The file is definitely open for writing, and the write operation indicates it wrote all the bytes.  No calls are indicating any error.

Since reads and seeks are working I'm assuming this is not a problem with wiring of the device to the Arduino Mega.  The files range from around 100K to almost 2M each, and the code needs to access the entire content of the file, but almost never sequentially.  Writes are almost always non-sequential as well.

Is it necessary to do a close after each write instead of the flush?

Does anyone have any suggestions of things I should be investigating?

Bob

title: Write with SD card; flush versus close?

Answers: 0


body: Hi there i am a beginner and trying to pair some sensors with my arduino. I am looking for some software which will allow me to test my codes in virtual machine also it should be free ...thax in advance

title: Free simulation software for arduino hardware

Answers: 0


body: I have been researching about the reason why we have a second MCU in arduino UNO for a while now. finally i understood that its been use as  USB to serial converter. the question that really bug me now, why is the boot-loader is burn on the main ATmega328 not Atmega16U2 ?

title: Why the bootloader burn on ATmega328 rather than Atmega16U2 in Arduino Uno

Answers: 1

body:
The purpose of the bootloader is to get the firmware through the serial
port and burn it into the flash. The 16U2 has no access to the 328's
flash. The job has to be done in the 328 itself.


body:
my garage door is pretty narrow, about 10 cm (4") on each side of my car's rear mirrors. So every time I drive to garage, I need to go very slowly because I am afraid I might not be lined up correctly.

 I am thinking about using Arduino and some sensors to help me. Output is pretty simple, just two leds, one for each side, showing me if I should turn little right or left to have perfect lineup to center. This I can handle with no problem

 What I am asking for is idea how to measure the alignment of my car. I know how to use ultrasonic sensors for measuring distance. But I am not sure they are suitable for this project, because I want preferably to put arduino and sensors in my garage, not in my car.

Any idea how to work this out ?

title: How to measure direction the car is coming to garage door?

Answers: 3

body: It is very hard to determine position accurately there is a new project on kickstarter called Pozyx, you can look at that but that's expensive, to be honest this sounds like a job for hanging tennis balls or strings or something like that. But if you have a lot of money to blow and you just want a project go for it, you may be able to do this with ultrasonic sensors but I reckon that would be painful. Anyway good luck

body:
It seems like an ultrasonic sensor on each door-post should do it. You need, I'm guessing, 30cm to the sides of your car as its nose enters the doorway. Smooth the sensor reading, compute a difference and display the sign of the differences as right/left lights. Keep a small dead-band around zero-difference or you'll drive the driver crazy!

Do Ultrasonic sensors have the range and accuracy you need for the job? Time for a feasibility study.

Update:
Is 10cm plus the length of a mirror = a couple of feet? But even if so, you have to keep to +/- 10cm of the centerline to prevent striking the mirrors, so you could project your sensors out into the doorway by an amount the still keeps them > 10cm away from the car. You could mount them hinged (like the mirrors are) and padded to limit any damage from the occasional accidental touch.

body: Try to place two distance ranging sensors like ultrasonic or active infrared at the sides of the driveway or garage door. Make sure that their readings are similar so that you know that you are in the center. If one has a higher reading(farther distance) light an led to your right so you know  to go that direction and vice versa. Use communication through xbees, bluetooth, or something similar.


body:
I've looked in several places, and so far can not understand to want to be the GND who is on the board.

There is this documented anywhere?

title: What is GND on board?

Answers: 1

body:
It is the 0V reference for everything else, as well as the power supply return.

"Ground (electricity)" on Wikipedia


body:
I'm not sure about how to properly handle timing readings from serial inside a Python script. I need to read a value every **5 seconds**.

From Arduino I could do,

    Serial.println(value);
    delay(5000); // should I wait here?

Inside Python script I could do,

    import serial
    import time

    arduino = serial.Serial('/dev/ttyACM1', 9600, timeout=5) # should I set timeout?

    while True and arduino.isOpen():

        try:
      value = arduino.readline().strip()
         print value

      time.sleep(5) # should I wait here?

     except KeyboardInterrupt:
      print "\nClosing..."
      arduino.close()

EDIT: Apart from that, the first reading is always wrong, like if there was something in the reading buffer.
I've found out that to solve that I should add `arduino.flushInput()` just after opening the port.

title: Handle reading timing in Python using pySerial

Answers: 1

body:
The answer is that it depends on what you are actually trying to accomplish. If there is nothing else to be done on the Arduino then it is fine to have it sit and wait; on the other hand if there is nothing else for the python script to do then it is fine for it to sit and wait, but there is no reason for both of them wait.

Arduino `delay`s
------

You don't need to deal with the timing delay in python if the Arduino is `delay`ing. According to [the documentation](http://pyserial.sourceforge.net/shortintro.html#readline) `readline` will wait until it has received a value or until the timeout is reached. That said, I would make the timeout slightly longer than the delay on the Arduino side of things.

Note that `readline` will block your program from doing anything else while it waits. As such, It is pretty useful to explore python [`threading`](https://docs.python.org/2/library/threading.html#module-threading) when you are writing a program which collects data over a serial stream unless the program is *only* collecting data.

Python `sleep`s
-----
If there is other stuff to be done on the Arduino (perhaps if you are doing some filtering of the temperature data using the Arduino so as to reduce noise) then it might make more sense for it to push data to the serial stream at the end of each `loop`, and for the python script to only read the data every 5 seconds. In this case you could have python `sleep` and use no delay (or a shorter delay) on the Arduino. You can achieve this behavior without resorting to using `sleep` by using a [`timer` object](https://docs.python.org/2/library/threading.html#timer-objects) to periodically call a function that `open`s the serial stream (possibly flush it), reads the data, processes it, and closes the serial stream.


body:
QUCS is the only open source software which offers simulation (and designing PCB layout [in future]) of electrical circuits. But the problem with QUCS is that it is under development and many important features are not yet available in it.

I want to simulate Arduino Uno board in it for my circuit. Does anyone know how to simulate Arduino or any other micro-controller in it?

**P.S.** Also any other open source software for simulation and PCB designing?

title: How to simulate Arduino?

Answers: 6

body:
Simulating a microcontroller's program is common, but not as part of a circuit, unless you're into Systems on Chips.

## Model the micro interfaces and simulate the peripherals separately ##

Analog systems cannot be modelled accurately by hand calculations alone, therefore simulation is often a necessary step (on top of that, real circuits might behave differently from the model). Non-programmable digital systems are deterministic in their behaviour, but only if the interfaces are correct - tight specifications on impedances and such often mean simulation is required here as well. Generally speaking, for both simulation becomes a must when the system is not dead simple. Microcontrollers on the other hand are sufficiently deterministic not to require any simulation: they do what they're told, except in very very very rare cases (single event upsets from radiation for example). Now, what they're told might allow glitches to happen, but that's a different story*. Therefore, usually the analog, or digital circuits around a microcontroller would be given equivalent interfaces based on the microcontroller's behaviour and physical specifications, and simulated separately.

*: As the code becomes more and more complex, it gets more and more difficult to follow what the microcontroller might do. Unexpected glitches may arise from e.g. concurrent access (though I can't say this is common in the micro realm), or insufficient resources (that is why dynamic allocation [malloc,new] are highly discouraged, so that the resources allocation is known at compilation time) etc. That's usually why tests are required, and step-by-step debugging is used as a means to locate any error that arises. But inherently, microcontrollers are highly predictable and except in certain cases, it is not worth it to go through simulation (do not mix up simulations and tests, tests are always required!).

## Advantages of microcontroller simulators ##

However, microcontrollers simulators do exist. They are particularly helpful to watch what happens inside the microcontroller when the code executes step by step: call stack, watches on variables, interrupt vectors etc. This can also be done on the actual hardware using in circuit debuggers, but simulators are cheaper and are also good to save on EEPROM erase/write cycles and to avoid damaging your micro if you are afraid that the devices around it might be incorrectly configured (some controllers are very expensive, especially if they are qualified for medical, military or aerospace applications). I have seen such ICD's and simulators for Microchip PICs (MPLABX), but there must be equivalents for AVR (the micro which is on the Arduino's), or perhaps even integrated in an arduino-friendly environment (though I doubt it). You might want to take a look [here][1].

## If you've got deep pockets: mixed signal simulators ##

Finally, there are mixed signal simulators which allow you to simulate analog, programmable and non-programmable digital circuits alike; one component will have an analog SPICE model, another a VHDL model, and ADC/DAC blocks will be added automatically by the simulator between those devices depending on the logic input/output technology you specify. Those are extremely expensive (the one I used is Cadence Virtuoso), you don't want to do that unless you're doing an integrated circuit or something critical.

P.S: DesignSpark PCB v3 has LTspice in it. Never tried that feature in there though, I used to use LTspice directly.

*Note that your opening "QUCS is the only open source software [...]" is wrong. There are plenty of simulators out there which are open source. I agree QUCS is a very user-friendly one though.*

  [1]: https://electronics.stackexchange.com/questions/1677/how-can-i-use-avrsim-to-simulate-arduino?rq=1

body:
You can use [123d.circuits.io][1] for simulation and PCB design for Arduino circuits.

See [this one][2] for example.

More generally, a previous answer states that Microcontroller based circuits are not simulated. Maybe that's true when prototyping costs are low (though I doubt it), but in an SoC or complex embedded system, microcontrollers certainly are simulated as part of the overall system.

Sometimes as a highlevel model such as a symbolic simulator or sometimes as a part of the overall mixed-signal simulation environment in which the digital part is usually simulated at RT level.

  [1]: https://123d.circuits.io
  [2]: https://123d.circuits.io/circuits/251828-16led

body: See my blog which will explain all steps at http://tutorial4you.weebly.com/blog/arduino-simulation-on-proteus

body: To add to the list of simulator answers, try out [Micro-Cap 12](http://www.spectrum-soft.com/download/download.shtm). It was a few thousand dollars originally, but the company has ceased operations now and has provided it for free. Pretty cool.

body:
How to simulate Arduino? What is the best Arduino simulator?

Following are the main features of the wokwi arduino simulator

It is free :)

• Supports multiple file projects

• Supports most of the famous Arduino libraries

• Whatever compiles on the Arduino IDE will compile on the simulator

• Supported by all browsers

• Compiles with latest Arduino IDE

• Supports FastLED and many other peripherals

• No download or installation needed

• Easy to share the code and project with just a single click

• Smart - Code Autocompletion, Code auto-formatting are supported

• Provides standard library demo examples

• Project can be compiled on RUN on Mobile browsers as well

• Tries to be closer to real circuits – Example – Button bounce like in real hardware

• Supports Arduino Mega, Arduino Nano, Arduino UNO, ATtiny85

• Supports assembly instruction execution

• Provides LED power and FPS features for FastLED projects

• Supports a plethora of Arduino peripherals for the project – Ultrasonic sensors, Slide switches, NeoPixel matrix, Potentiometer, Servo motors, SSD1306 OLED displays, temperature and humidity sensors, rotary dialer, membrane keypad and more

• Serial monitor is supported as well

Website: https://wokwi.com
------------------
Here are a few examples
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]
[![enter image description here][4]][4]
[![enter image description here][5]][5]
[![enter image description here][6]][6]
[![enter image description here][7]][7]
[![enter image description here][8]][8]

  [1]: https://i.stack.imgur.com/diA67.gif
  [2]: https://i.stack.imgur.com/XlmxY.gif
  [3]: https://i.stack.imgur.com/9IyQW.gif
  [4]: https://i.stack.imgur.com/1iTVS.gif
  [5]: https://i.stack.imgur.com/gR0pW.gif
  [6]: https://i.stack.imgur.com/yT2dq.gif
  [7]: https://i.stack.imgur.com/YcW81.gif
  [8]: https://i.stack.imgur.com/OaBZT.gif

body:
try this : simulIDE

google : simulIDE for arduino picture

supports also : pic tiny atr arduino ..

enjoy !


body:
Hey all I have the ESP8266 module and I have already set it up and it's working good. However, when I run this HTML page code here:

    <html>
     <head>
      <title>ESP8266 LED Control</title>
     </head>
     <body>
     <button id="6894" class="led">Toggle Pin 13</button> <!-- button for pin 13 -->

     <script src="jquery.min.js"></script>
     <script type="text/javascript">
      $(document).ready(function(){
       $(".led").click(function(){
        var p = $(this).attr('id'); // get id value (i.e. pin13, pin12, or pin11)

        $.get("http://192.168.9.60:80/", {pin:p}); // execute get request
       });
      });
     </script>
     </body>
    </html>

I have to send the number 6894 instead of 13 because for some reason its not sending out the correct number. If i send 13 then what it receive is 114. When i send 6894 i receive 689.

My arduino code is this:

    */
    //====================================================================================
    //                                [The SSDI of the current wifi router]
    //                                |              [The password of the current wifi router]
    //                                |              |
    //                                V              V
    String SSIDandPW    = "AT+CWJAP=\"xxxxxxwifi\",\"xxxxxx123\"\r\n";

    //                                      [The STATIC IP of the wifi module]
    //                                      |                [The main IP of the router]
    //                                      |                |              [The default submask]
    //                                      |                |              |
    //                                      V                V              V
    String eIPrIPmask   = "AT+CIPSTA_DEF=\"192.168.9.60\",\"192.168.9.1\",\"255.255.255.0\"\r\n";
    const int ledDimmer = 5;         // Used to dim the LED strip (digital Pin 3)

    SoftwareSerial esp8266(9,10);    // Pin D10 to=> TX on ESP8266 | Pin D9 to=> RX on ESP8266
    //================================= End define WiFi Module =================================
    //==========================================================================================

    void setup() {
      Serial.begin(19200);

      pinMode(13, OUTPUT); //Just for a wifi demo from html page

      //================================ Start Setup WiFi Module =================================
      //==========================================================================================
      esp8266.begin(19200);
      sendData("AT+RST\r\n",                    2000, true); // Reset module
      sendData("AT+CWMODE=1\r\n",               2000, true); // Configure as access point
      sendData(SSIDandPW,                       5000, true); // Pass of current wifi
      sendData("AT+CIPMUX=1\r\n",               2000, true); // Configure for multiple connections
      sendData("AT+UART_DEF=19200,8,1,0,0\r\n", 2000, true); // Set baud of COM
      sendData(eIPrIPmask,                      2000, true); // Default network mask IP
      sendData("AT+CIPSERVER=1,80\r\n",         2000, true); // Turn on server on port 80
      sendData("AT+GMR\r\n",                    2000, true); // Get firmware version
      sendData("AT+CIFSR\r\n",                  2000, true); // Get ip address
      Serial.print("Server is now running!");
      //================================ End Setup WiFi Module ===================================
      //==========================================================================================
    }

    void loop() {
      //=========================================== Start Loop WiFi Module ===========================================
      //==============================================================================================================
      if(esp8266.available()) {                               // check if the esp is sending a message
        if(esp8266.find("+IPD,")) {
          delay(500);
          int connectionId = esp8266.read() - 48;             // subtract 48 because the read() function returns

          esp8266.find("pin=");                               // advance cursor to "pin="
          int retunedNum = (esp8266.read() - 48) * 100;       // get first number (example: 123.. this would be "1")
          retunedNum += (esp8266.read() - 48) * 10;           // get second number (example: 123.. this would be "2")
          retunedNum += (esp8266.read() - 48);                // get last number (example: 123.. this would be "3")
          String closeCommand = "AT+CIPCLOSE=";               // make close command
          Serial.print("returned: ");
          Serial.print(retunedNum);
          Serial.print("----------");
          closeCommand += connectionId;                       // append connection id
          closeCommand += "\r\n";
          sendData(closeCommand,                250, true);   // close connection
          //digitalWrite(retunedNum, !digitalRead(retunedNum));   // toggle pin
          if (retunedNum == 6894) {
            Serial.print("OFF");
            digitalWrite(ledDimmer, LOW);
          } else if (retunedNum == 6904) {
            Serial.print("ON");
            digitalWrite(ledDimmer, HIGH);
          } else if (retunedNum == 689) {
            digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
            delay(1000);              // wait for a second
            digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
            delay(1000);              // wait for a second
          }
        }
      }
      //============================================ End Loop WiFi Module ============================================
      //==============================================================================================================
    }

    //                     [The data/command to send]
    //                     |                  [The time to wait for a response]
    //                     |                  |                [Print to Serial window (true = yes | false = no)]
    //                     |                  |                |
    //                     V                  V                V
    String sendData(String command, const int timeout, boolean debug) {
      String response = "";
      long int time   = millis();

      esp8266.print(command);          // send the read character to the esp8266

      while((time + timeout) > millis()) {
        while(esp8266.available()) {
                                       // The esp has data so display its output to the serial window
            char c = esp8266.read();   // read the next character.
            response += c;
        }
      }

      if (debug) { Serial.print('Returned: ' + response); }
      return response;
    }

And the console output is this:

    14880AT+RST

    OK
    14880
    "qXÑ{ÂB!É
    1Â±þ)ÒBÙa
    +ò“H!a5)�#)ÒÂia%YakN‘ J!ÐCÊ!�
    ÷þˆ2ô
    ready
    14880AT+CWJAP="xxxxxxwifi","xxxxxx123"

    OK
    14880AT+CIPMUX=1

    OK
    14880AT+UART_DEF=19200,8,1,0,0

    OK
    14880AT+CIPSTA_DEF="192.168.9.60","192.168.9.1","255.255.255.0"

    OK
    14880AT+CIPSERVER=1,80

    OK
    14880AT+GMR

    AT version:0.22.0.0(Mar 20 2015 10:04:26)
    SDK version:1.0.0
    compile time:Mar 20 2015 11:00:56

    OK
    14880AT+CIFSR

    +CIFSR:STAIP,"192.168.9.60"
    +CIFSR:STAMAC,"18:fe:34:9b:4e:68"

    OK
    Server is now running!

    returned: 689----------148804 HTTP/1.1
    Host: 192.168.9.60
    Connection: AT+CIPCLOSE=0

    0,CLOSED

    OK

What I really am wanting to do is have a way to send a 10 charater string to the arduino instead of the limited 3 numbers above. I just am not sure what i need to add/modify in order to make it see letters/numbers and only the first 10 that i send.

Any help would be great!

title: ESP8266 wifi module sending data via jQuery

Answers: 1

body:
      int retunedNum = (esp8266.read() - 48) * 100;       // get first number (example: 123.. this would be "1")
      retunedNum += (esp8266.read() - 48) * 10;           // get second number (example: 123.. this would be "2")
      retunedNum += (esp8266.read() - 48);                // get last number (example: 123.. this would be "3")

Your code always expects the pin number to have 3 digits.

In case of 13, it takes a space character as the last digit.
It reads charachters '1', '3' and ' '. Their ASCII codes are 49, 51 and 32. With this, the calculated number is

    (49 - 48) * 100 + (51 - 48) * 10 + (32 - 48) = 114.

With 6894, it just uses the first three digits and ignores the last.

For 1 or 2 digit long number you could just pad it with '0' character i.g. "013".

If you want to read an arbitrary string, you should replace the above code with this code:

    String retunedStr = "";
    for(;;) {
        char c = esp8266.read();
        if (c == ' ')
            break;
        retunedStr += c;
    }

And obviously replace

    Serial.print(retunedNum);

with

    Serial.print(retunedStr);

With this, you should only use letters (A-Z, a-z), numbers (0-9), dash (-) and an underscore (_) for the string.
If you use other characters, you could have problems with the URL character encoding.


body:
I've just bought a new LinkIt ONE IoT prototyping board, and I'm having trouble getting started with it.

I'm working on a mac. I've installed the LinkIt ONE SDK onto my Arduino IDE as specified in the instructions here: http://labs.mediatek.com/fileMedia/download/5fed7907-b2ba-4000-bcb2-016a332a49fd

When I go to upload my first sketch to my board, the sketch compiles and goes through uploading, but before it uploads, it stops uploading and the Arduino IDE perpetually tells me "Uploading...". When I look at the console below, it's telling me this:

    [txd] AT

    [txd] AT

    [medrv]: Time out call back

    [error] time out
    [medrv]: Kill timer, event is AT_TIMEOUT

I've read some forums about an issue similar to this on the MediaTek website, but they don't help with the issue on the Mac. The ability to use LinkIt ONE on a Mac is new only this month, so I believe if we come up with a fix for this issue, it will help lots of people in the future who have this similar problem.

title: Sketch Upload to LinkIt ONE Timeout

Answers: 1

body:
*Disclaimer: I do not have access to one of these devices to test this on.*

Section 3.4.1 of [LinkIt's developer's guide](http://labs.mediatek.com/fileMedia/download/5fed7907-b2ba-4000-bcb2-016a332a49fd) (which you linked to) seems to indicate that it is necessary to install COM port drivers on OS X before you can communicate with the board. The `[txd]` report is communication from your computer to the board, so it seems like you are never establishing a connection. The suggestions in the developer's guide are as follows:

> If you are using a LinkIt ONE development board on Mac OS X 10.10, then a USB driver is required to enable connectivity with and firmware updates on the LinkIt ONE development board. The OS X 10.10 built-in generic CDC ACM USB driver is not compatible with three ports available on the LinkIt ONE development board. The steps to install a custom driver to enable the BROM port for Firmware Updater are as follows:
>
> 1. Extract the content of the zip file available in LinkIt ONE SDK software’s **Driver** folder (see 2.3.2, “Installing LinkIt ONE SDK”) named `MacOS_USB_COM_Driver_BM_xxx.xx.x.zip`.
>
> 2. Run the installation package (`BMCDCACM_Driver_v115.05.0.mpkg`) and click **Next** to install it.
>
> 3. Wait until driver installation has finished, then restart your Mac.
>
> BROM USB driver installation is now complete and you have access to the MTK USB Serial ports.


body:
I have purchased an Arduino Uno R3 board and a LAN shield from these locations:

 - [Arduino UNO R3][1]
 - [Arduino LAN shield][2]

I am trying to configure Ethernet using this sketch:

    #include <SPI.h>
    #include <Ethernet.h>

    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on the shield
    byte mac[] = {
      0x4,0x2,0x45,0x68,0x5E,0x96,0x56
    };

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      delay(5000);
      // this check is only needed on the Leonardo:
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }
      // start the Ethernet connection:
      Serial.println("trying to configure ethernet...");
      while(Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP, retrying after 5 sec");
        // no point in carrying on, so do nothing forevermore:
        delay(5000);
        Serial.println("trying to configure ethernet...");
      }
      // print your local IP address:
      Serial.print("My IP address: ");
      for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        Serial.print(Ethernet.localIP()[thisByte], DEC);
        Serial.print(".");
      }
      Serial.println();
    }

    void loop() {
    }

It generates this output in the Serial Monitor:

    trying to configure ethernet...
    Failed to configure Ethernet using DHCP, retrying after 5 sec
    trying to configure ethernet...
    Failed to configure Ethernet using DHCP, retrying after 5 sec
    trying to configure ethernet...
    Failed to configure Ethernet using DHCP, retrying after 5 sec
    trying to configure ethernet...
    Failed to configure Ethernet using DHCP, retrying after 5 sec
    trying to configure ethernet...
    Failed to configure Ethernet using DHCP, retrying after 5 sec
    trying to configure ethernet...
    Failed to configure Ethernet using DHCP, retrying after 5 sec
    trying to configure ethernet...
    Failed to configure Ethernet using DHCP, retrying after 5 sec
    trying to configure ethernet...

I have captured the LED indicators on video on YouTube, it shows Tx and Rx LEDs glowing occasionally, see [Arduino not detecting the ethernet connection][3].

It looks like the Arduino is not able to connect to the Ethernet... I am using the Arduino IDE 1.6.5 on Windows 7.

Is there any debug tool for Arduino that can be used to figure out this issue?

  [1]: http://www.amazon.in/gp/product/B00H1HR576
  [2]: http://www.ebay.in/itm/W5100-Ethernet-Shield-for-Arduino-Uno-And-Mega-KG027-/121654747580
  [3]: https://www.youtube.com/watch?v=tktkjooh3CA

title: Unable to configure Ethernet using Arduino Uno R3

Answers: 2

body:
<strike>I never used the DHCP feature to assign an IP address for the Ethernet shield, but somewhere in there you have to list the IP of the router that assigns the DHCP.</strike>

In everyday use of the shield, you don't want your router to assign an IP address to your device because every time it connects it might get a different IP address. That means if you want to communicate with it, you need to discover the IP address each time. And communicating with it from the WAN side through a port you open in your router would be impossible.

Try one of the fixed IP address sketches, but select a free IP address in your router's IP range that *isn't*, also, in the router's DHCP IP range (that way the fixed IP address won't interfere with the IP addresses given out automatically).

body:
I use more or less the same code to do my networked widgets and it has been quite reliable in my experience. Do you know if you have a DHCP server on the network segment that the Arduino is on? The absence of a server or a configuration that won't respond to the Arduino seem like the most likely explanation for the problem you're seeing.

The way to troubleshoot this would be to get another machine on the same network segment and watch the traffic with `tcpdump` or Wireshark or a similar tool. If you're running on a "third party" machine (e.g. not the DHCP server) then you'll be able to see the Arduino's side of the DHCP exchange, but I'm not sure if you'll be able to see the server (the Arduino will be broadcasting since it can't know the address of the DHCP server, but I think the server's response is unicast). If you've got a Linux box or some other machine that you can log into where you could run the DHCP server you can watch both sides of the negotiation. But even if you can't get to the server it will help to see if the Arduino is starting the DHCP negotiation.

If you need a fixed IP address on the Arduino, the way to do it is to configure the DHCP server to reserve an address for the Arduino. That way you can have a known address on the Arduino without having to hard code an IP address (which will eventually bite you).


body: I want to use an external clock signal as an interrupt for the Due timer. How do I do that? I could not find any info on this on the net.

title: How to use an external clock with the Due timer?

Answers: 1

body:
Everything you need to know is in the SAM3X datasheet:

http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf

However, as Atmel's datasheets are some of the most cryptic ones around, you'll need to spend quite some time deciphering it.

There's an entire section just on the timers.  It tells you all about how they work, however, relating that to which registers you need to set to get it to do that is not clear (as is normal for Atmel) since the registers are listed elsewhere in that section with no real relationship between them.


body:
I´m trying to insert a binary raw sequence (01010100, 01101000, 01100001) into Arduino. I would like to make 8-led group blink in a loop, showing with light each 8-group binary sequence when: 0=light off and 1=light on.

It´s possible to do this operation with Arduino-uno ?

title: Binary reader with arduino blinking 8 leds

Answers: 1

body:
You just prepend the number in binary with B e.g. B01100100 which is 100 in decimal

    byte sequence[] = {
        B10000000,
        B01000000,
        B00100000,
        B00010000,
        B00001000,
        B00000100,
        B00000010,
        B00000001
    }

And to check the n-th bit from the right in a number you do

    boolean bit_set = number & (1 << (n - 1)) != 0;


body:
I would like to ask if it is possible and how to connect the following module
http://www.ebay.com/itm/TOP-Mini-W5100-LAN-Ethernet-Shield-Network-Module-board-for-Arduino-Best-NEW-/251981053942?pt=LH_DefaultDomain_0&hash=item3aab3dbff6

to the arduino micro

I found some pin layouts but only for Leonardo or Ethernet shield, Uno etc.

Also I've choosen this model because it can be programmed directly in arduino using Sockets API

title: micro arduino and w5100

Answers: 1

body: While it would have been nice to see your research rather then having to spend some time finding this information myself, I did find this http://www.instructables.com/id/Add-Ethernet-to-any-Arduino-project-for-less-than-/ from what I can see this should be compatible to any arduino as long as it has 3 volt pin and 4 i/o pins. While the arduino micro doesn't have a 3v3 pin, as far as I know, that shouldn't be an issue as long as you can drop the voltage from the 5 volt pin, this module should work for you.


body:
My understanding of using dynamic memory on the arduino is that new/delete are not available, only malloc realloc and such C functions, as mentioned here:

[C++ & the AVR][1]

I am creating a library that defines an object type that needs to contain a dynamic list of other objects. In C++ I would define it something like this:

    class Container
    {
    std::vector<otherObjectType> otherObjects;
    };

which obviously does not work in the arduino without the C++ standard library.

My next choice would be to create a dynamic array using new, ie

    otherObjects = new otherObjectType[3]
 {
  { (arguments to constructor...)
  },
  { (arguments to constructor...)
  },
  { (arguments to constructor...)
  }
 };

But this does not work as well, since new is not supported...

finally I could try to use malloc as laid out [here][2], but that also wont work without new.

I am wondering if I should just rewrite everything as structs, since that wont require me to worry about whether the constructor for the object was called when the memory was allocated in malloc.

  [1]: http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_cplusplus
  [2]: https://stackoverflow.com/questions/4956249/using-malloc-instead-of-new-and-calling-the-copy-constructor-when-the-object-is

title: Malloc with Objects in Arduino libraries

Answers: 1

body:
`new` actually does work in arduino. it is defined in arduino/hardware/arduino/avr/cores/arduino/{new.h, new.cpp} using malloc. It is not part of avr-libc though (which your link concerns) and has not always been added by arduino.

Both of these work for me:

    namespace{ //namespace to deal with .ino preprocessor bug
        class foo{
        public:
            int bar;
            foo(int a){
                bar = a;
            }
        };
    }
    ...
    //using new
    foo *a = new foo[3]{{1},{2},{3}};

    //How I would probably do this with malloc
    foo *b = (foo*) malloc(sizeof(foo)*3);
    b[0] = foo(2);
    b[1] = foo(4);
    b[2] = foo(8);

Placement new is not defined right now. I know that copying isn't quite the same, but it should work in most cases.

Of course, if you know exactly how long you want the array to be at compile time, you should probably make it a static/global variable so that you avoid using dynamic memory and the sketch ram usage number will be closer to correct.


body:
I'm trying to upload a hex file to an ATtiny45 with an Arduino. I uploaded the Arduino ISP sketch to my board. I connected the ATtiny as shown below:

![Wiring diagram][1]

Then I go to CMD and type:

    avrdude -c avrisp -p t45 -b 19200 -P COM6 -U flash:w:main.hex:i

And it gives me this error:

    Please define PAGEL and BS2 signals for ATtiny45!

I double checked the connections and i tried to uplad a bootloader with Arduino IDE as written in this article: [Programming Hex-code on an Attiny85 with the Arduino](https://arduinodiy.wordpress.com/2012/09/11/programming-hex-code-on-an-attiny85-with-the-arduino). I can uplad sketches with ArduinoIDE with no error.

  [1]: https://i.stack.imgur.com/25qaC.png

title: Flash a .hex to an ATtiny45 with Arduino

Answers: 1

body:
Googling the error [gives this tutorial][1]. Towards the bottom of the page they say

> You’ll probably get the following message, but don’t worry, the upload should have worked anyway:
>
> *avrdude: please define PAGEL and BS2 signals in the configuration file for part ATtiny85*

So it seems this can be ignored and the part has been programmed!

  [1]: http://highlowtech.org/?p=1229


body:
I'v got this USB/SD card/CompactFlash reader from an old DELL AIO 926 printer, it's a double sided PCB board and that's all i know about it.
I tried to google it but couldn't find anything relevent, how can i tell what voltage it takes and what each wire does and how to interface it with arduino?

![enter image description here][1]

![enter image description here][2]

![enter image description here][3]

  [1]: https://i.stack.imgur.com/bm3zX.jpg
  [2]: https://i.stack.imgur.com/6qnuz.jpg
  [3]: https://i.stack.imgur.com/gNJxF.jpg

It seems to me that it has two sets of 4 wires (red/orange - black - yellow - white) and an extra blue wire, i'm guessing that the black is for GND, red/orange for VCC, yellow/white for SDA/XDA I2C serial bus data transfer, but no clue what the blue wire does, i could've tested this with arduino but i don't want to risk frying the board by using a wrong voltage. any help would be greately appreciated. thanks.

title: How to connect a card reader (extracted from printer) to arduino uno

Answers: 1

body:
I can pretty much categorically say you won't get it working.

I have a similar board here with the same SMSC (now owned by Microchip) chip on it.

The interface is USB plus some other signals.  I have managed to identify the USB portion of the interface on mine, but not the other signals.

The SMSC chip has the option of using an external ROM chip to store its program, and Dell love to do that.  So, it has a custom firmware which means it doesn't get recognized by my computer without Dell's specific drivers installed.  So it's useless.

There's a very very slim chance you may get it working with a USB Host Shield, but unlikely - and at the end of the day, what's the point?  It's just an SD card reader.  Wire an SD card socket direct to the Arduino and save yourself both the headaches of trying to work it out and also the massive pointless expense in buying the hardware you'll need to do the interfacing.


body:
We have an instrument that has analog output of 0-1 volts and we need to convert this to 0-5 volts. What is the best op amp to use for this and how should the resistors be set up? Any help would be greatly appreciated.

Thanks,

Paul

title: 0-1 V input to 0-5 V Output

Answers: 1

body:
Since you used Arduino tag..., you don't need an opamp. Instead you can select ADC reference voltage on your arduino to 1.1V. This way you don't need any additional parts and you get the whole precision range.

    analogReference(INTERNAL1V1);

http://www.arduino.cc/en/Reference/AnalogReference


body:
I'd like to write a code for reversing DC motor rotation direction as follows:

1. Start the motor rotation clockwise (CW).
2. When reach Limit Switch (CW) → motor will stop for 5 sec.
3. after 5 sec. of stopping → the motor will rotate in counter clockwise direction(CCW).
4. When reach Limit Switch (CCW) → motor will stop for 5 sec.

and repeat point 1, 2, 3 and 4...

Actually I wrote a code for reversing the motor direction using **two** limit switches and it is working good. But when I added delay the motor did not stop using the limit Switches and continue to rotate...
If any one can help...
Here is my code for reversing the direction with out delay 5 sec. My limit SWs are connected on Normal Open.

<!-- language: lang-c++ -->

    int sw1, sw2, sw3;
    const int LM1 = 0;
    const int LM2 = 1;
    const int LM3 = 6;
    const int CW = 10;
    const int CCW = 9;
    const int Buzzer = 7;

    void setup() {
      pinMode(LM1, INPUT);
      pinMode(LM2, INPUT);
      pinMode(LM3, INPUT);
      pinMode(CW, OUTPUT);
      pinMode(CCW, OUTPUT);
    }

    void loop(){
      sw3 = digitalRead(LM3);
      sw1 = digitalRead(LM1);
      sw2 = digitalRead(LM2);

      if (sw1 == LOW && sw2 == HIGH) {
        do {
          digitalWrite(Buzzer, HIGH);
          digitalWrite(CW, HIGH);// change the direction of rotation (DOWN Movement)
          digitalWrite(CCW, LOW);

          sw2 = digitalRead(LM2);
        } while (sw2 == HIGH);
      }
      else if (sw1 == HIGH && sw2 == LOW) {
        do {
          digitalWrite(Buzzer, HIGH);
          digitalWrite(CW, LOW);// change the direction of rotation (UP Movement)
          digitalWrite(CCW, HIGH);

          sw1= digitalRead(LM1);
        } while (sw1 == HIGH);
      }
    }

title: reversing DC motor rotation using TWO limit Switches Problem !! need help

Answers: 2

body:
Maybe the code with the 5 second delay is more usefull. Because you are telling us the code you now deliver is supposed to work?

Probably using delay(5000) will work?

body:
Normally you use state machine for this kind of programming: you have a
`state` variable that remembers what you are doing, and depending on the
current state you decide what to do next. Below is an example with two
states. I have embedded a few assumptions about the wiring of your motor
and your switches, which may be wrong, so you have to check the code.

<!-- language-all: c++ -->

    void loop() {
        static enum {MOVING_CW, MOVING_CCW} state;

        switch (state) {
        case MOVING_CW:
            if (digitalRead(LM2) == LOW) {  // hit switch
                digitalWrite(CW, LOW);      // stop
                delay(5000);
                digitalWrite(CCW, HIGH);    // restart
                state = MOVING_CCW;
            }
            break;
        case MOVING_CCW:
            if (digitalRead(LM1) == LOW) {  // hit switch
                digitalWrite(CCW, LOW);     // stop
                delay(5000);
                digitalWrite(CW, HIGH);     // restart
                state = MOVING_CW;
            }
            break;
        }
    }

This will start in the `MOVING_CW` state, but you have to actually start
the movement in `setup()`. It has the drawback of having long delay()s in
the loop, which is undesirable if you have other tasks to perform. These
delays can be removed by “remembering” that you are waiting as two extra
states:

    void loop() {
        static enum {MOVING_CW, MOVING_CCW, STOPPED_CW, STOPPED_CCW} state;
        static unsigned long time_stopped;
        unsigned long now = millis();

        switch (state) {
        case MOVING_CW:
            if (digitalRead(LM2) == LOW) {  // hit switch
                digitalWrite(CW, LOW);      // stop
                state = STOPPED_CW;
                time_stopped = now;
            }
            break;
        case MOVING_CCW:
            if (digitalRead(LM1) == LOW) {  // hit switch
                digitalWrite(CCW, LOW);     // stop
                state = STOPPED_CCW;
                time_stopped = now;
            }
            break;
        case STOPPED_CW:
            if (now - time_stopped >= 5000) {
                digitalWrite(CCW, HIGH);    // restart
                state = MOVING_CCW;
            }
            break;
        case STOPPED_CCW:
            if (now - time_stopped >= 5000) {
                digitalWrite(CW, HIGH);     // restart
                state = MOVING_CW;
            }
            break;
        }
    }


body:
I am using a sensor which delivers a 4 to 20 mA output.
Converting this with a 250 Ohm resistor to ground I convert this to a 1 - 5 V output.

My question how can I change the 0V reference, so I can use the full spectrum
I found a way to change the 5V reference (analogReference()).
Is it possible to change the 0V reference of a input to 1V?

Any other solution to my problem is welcome as well! (As long as it doesn't involve I2C or anything which lowers my looptime drastically)

title: Change input reference to 1 - 5 V

Answers: 1

body:
The ADC is ground-referenced, and there's no way to change that. The question is if that's necessary. The ADC has a 10-bit resolution, that's good for 1024 different levels between 0 and 5 V. If you convert the 4-20mA with a 250 Ω resistor to a 1-5 V range you still can discriminate between more than 800 different values.

If that's not enough you can use a differential amplifier to subtract 1 V:

![enter image description here][1]

By choosing R3 = 1.25 R1 you convert the 0-4 V range to a 0-5 V range.

  [1]: https://i.stack.imgur.com/wV1zG.gif


body:
![high pitch noise][1]

I have an issue with several Leonardo and Micro boards.

On all of my boards, there is a sawtooth of about 690mV ptp @ 4kHz on the 5V supply when powered from Vin (external power).
The frequency changes slightly when changing input voltage from 7V to 12V.

C12 is a capacitor on the Leonardo board that is making the acoustic noise, it is "singing" with the frequency of this sawtooth. It follows the voltage regulator NCP1117 for the 5V power supply generation.

According to the schematics of the Leonardo and micro, the voltage regulator used on these boards should be the NCP1117, but on the boards I have, there is no number printed on this component, so I suspect an alternative was used, with these annoying results...

For a project I have for generating audio signals, this noise was unacceptable, so I cut out the regulator and powered everything with an external LM7805. One should not power the module via USB then as long as the external power is connected!!!

Anyone having the same trouble with these boards?
Other solutions?

(The Leonardo is a genuine Arduino board.)

  [1]: https://i.stack.imgur.com/Moe9T.png

title: Leonardo and micro: high pitch noise when powered from Vin

Answers: 2

body:
It does sound like the regulator is oscillating to me.  That happens when the output capacitor is of the wrong type for the regulator - the ESR is wrong.

My Leonardo, when powered from 12V, is nice and clean.  The regulator has 7CE50Z on it.  I do notice, on the layout of the Leonardo, that the output capacitor is somewhat further away from the regulator than I like to put it - though that shouldn't cause that much of a problem.  800mV is way too much to be considered normal under *any* circumstances.

What is the power source you are using?

body:
Yes, I've had this problem on a number of boards. It seems there are some faulty units coming out of the factory. I've had them replaced by my supplier, but I end up being sent more faulty boards.

It makes any kind of accurate ADC reading impossible.

A quick way to work out if your board has this problem

1. Place a jumper between 3.3v and A0
2. Put an analogRead in a loop and println the result
3. When powered by 5V you'll see a fairly constant value (around 670), varying by 1 or 2
4. When powered by 12V, if you have a faulty board, you'll see varying values, deviating by 50 or more.

There's a couple of solutions/workarounds to the problem listed here: http://forum.arduino.cc/index.php?topic=235729.0.


body:
I'm starting in the arduino world and I'm building an autonomous smart vehicle.

So, after some weeks building and adjusting the vehicle, I got to a point in this project that I want to log it's movements. Talking with a friend, he showed me an Gyro/Accel sensor and I really think that it would be an awesome upgrade to my vehicle

After reading some articles, I'm failing to understand the difference between an **Accelerometer Sensor**, a **Gyro Sensor** and a **Magnetometer Sensor**

So what is the main difference between those sensors?

title: What is the difference between Accelerometer, Gyro, and Magnetometer Sensor?

Answers: 2

body:
The main difference is the way they operate and what they sense.  In other words, they are all very very different things.  Yet they can all measure motion in some way.

* An accelerometer senses both the gravitational pull of the earth and the inertia / momentum of the motion of the device
* A magnetometer senses the earth's magnetic field to get a compass heading.
* A gyroscope senses *changes* in twist and angle.

They can all give information about motion and attitude, but each has both benefits and drawbacks compared to the others.  Some drift more than others, some are slower or lower resolution, etc.

So generally all three are used together to get the benefits of them all and, to some extent, negate the drawbacks of them.

For instance, a gyroscope isn't good at measuring inertia, but it is good at measuring changes in angles.  But those changes in angles drift over time and you lose accuracy.  A magnetometer is good at giving you an exact angle, but it takes longer to get an accurate result, and it's not good at fine changes in angle.  So a magnetometer is used to correct the drift of the gyroscope, and an accelerometer is used to measure inertia.

So to sum up:

* Accelerometer for changes in speed
* Gyroscope for changes in angle
* Magnetometer to correct the gyroscope

body:
The Accelerometer measures total acceleration on the vehicle, including the static acceleration from gravity it would experience even when its not moving.

The magnetometer measures the magnetic field around the robot, including the static magnetic field pointing approximately north caused by the earth. Being placed in/around a metal frame or any large motors, diving over/around underground metal pipes or electrical equipment will all make large and noticeable effects on its measurements.

The Gyroscope measures your instantaneous angular momentum around each axis, basically how fast its rotating. Note that angular momentum is not directly compatible with euler angles, but works out similarly for small angles. Very high quality signal in the short term because there isn't much noise, but since your angular position has to be integrated off of the gyroscope, it will build up error.

Gravity is your best reference for angular position, because it doesn't drift like the gyroscope and since your robot is operating in (and causing) a sea of magnetic disturbances, using north is risky. It will not work if you are experiencing a significant acceleration though.

The simplest code would just use the accelerometer for rotations around x and y, the mag for z, and ignore disturbances. The basic idea is "I know gravity is actually down, but its being measured on the accel X axis, so I must be pitched by some amount". The Better sensor fusion algorithms will use the accelerometer/magnetometer to correct for drift in the gyro, but get most of its information about rotational position from the Gyroscope.

Tracking lateral position using a standard 9-dof IMU is not possible. Only the accelerometer measures lateral motion at all, and it needs to be integrated twice to get position. Error builds so fast your position estimate is complete garbage within seconds.

Tracking angular position is possible because all three sensors measure it in one way or another. Angles are tricky though because they are not commutative. If the gyro measures a 90 degree yaw then a 90 degree pitch from north, you are facing down; if it measures a 90 degree pitch and then a 90 degree yaw from north, your facing east turned on your side. Be careful with the math, or download an arduino IMU library that has it taken care of for you.


body:
I have a robot with an Arduino Mega that gets data from a bluetooth module and sends it to an Arduino Leonardo to activate some functions. It all works amazing but only if the boards are connected to my computer. As soon as I disconnect them and power them from their own batteries, the serial communications seems to stop working. When I connect it to the PC again the communication between the Arduinos begins working.

Does anyone know why this is happening?

The Mega is powered by a 9V battery and the Leonardo by 4x AA (6V). On the Mega I use TX/RX(2) for communication with the BT module and TX/RX(3) for communication to the Leonardo.

title: Serial communication not working between two Arduinos unless connected to computer

Answers: 1

body:
Voltage, Electrical Potential, Potential Difference, Electric Tension - whatever you refer to it as - is the always measured *between two points*.

Generally of course we mean two points within one circuit, and most of the time we mean between something and the circuit's 0-Volt rail; it's implied whenever somebody quotes a voltage, unless they specifiy otherwise.

We always refer to the 0-Volt rail as 'ground', no doubt stemming from the term 'earth', which is literally a connnection into the ground itself. In the case of a battery powered circuit, the 0-volt rail is only 0 Volts *referenced to the rest of the circuit*. In such a circumstance, the circuit's ground is said to be **floating** when referenced to another circuit. Thus, two circuits with independent power supplies and no interconnection cannot be compared to one another in sense of voltage.

This typically doesn't matter, but when you need to interconnect independently-powered circuits you run into a problem. As both grounds are floating, any other voltage on each circuit is referenced to said floating voltage, and therefore is also floating. This makes wired communication between them impossible.

Unless you create a voltage reference between the two.

Simply connect the ground rails of each together; the cicruits are then referenced to one another at 0 Volts. It doesn't have to be the ground rails that are connected - any two points connected together will allow you to reference any point on board A to board B and get a correct potential difference. However, it's pretty useless doing that except in some odd situations.