message:
Unable to configure Ethernet using Arduino Uno R3

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

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).


sender: user

sender: assistant

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).


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

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.

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.


message:
Binary reader with arduino blinking 8 leds

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 ?

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;


message:
micro arduino and w5100

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

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.


message:
Malloc with Objects in Arduino libraries

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

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.


message:
Flash a .hex to an ATtiny45 with Arduino

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

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


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

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.

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.


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

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

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


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

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);
      }
    }

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;
        }
    }


message:
Change input reference to 1 - 5 V

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)

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


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

![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

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.


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

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?

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.


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

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.

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.


message:
I am having an issue reading a HIGH LOW signal from a pressure switch

I'm trying to read either high or low from a pressure switch, I do have a pulldown resistor attached but even if I plug in a wire with nothing on it i get a false high. I've changed pins, tried adding `INPUT_PULLUP` to the program but it it reads false.

The code i'm using is:

    const int mainPump = 2;
    const int prePump = 3;
    const int idleValve = 4;
    const int chemTankLow = 5;
    const int chemTankHigh = 6;
    int pressure = 8; //7 originally removed const
    const int chemValve = A7;
    const int mem2 = A6;
    const int mem3 = A5;
    const int mem4 = A4;
    const int mem5 = A3;
    int tankLow = 0;
    int tankHigh = 0;
    int pressureFault = 0;
    int lpe = 0;
    int maxlpe = 2;
    unsigned long timer[10]; //number of timers needed
    byte timerState[10]; //store timers
    int goNoGo = 0;
    int readVoltage = 0;
    int var = 0;

    void setup() {

      pinMode(idleValve, OUTPUT);
      pinMode(prePump, OUTPUT);
      pinMode(mainPump, OUTPUT);
      digitalWrite(mainPump, HIGH);
      pinMode(pressure, INPUT);   //removed _PULLUP after input
      pinMode(chemTankLow, INPUT);
      pinMode(chemTankHigh, INPUT);
      pinMode(chemValve, OUTPUT);
      pinMode(mem2, OUTPUT);
      pinMode(mem3, OUTPUT);
      pinMode(mem4, OUTPUT);
      pinMode(mem5, OUTPUT);

      digitalWrite(mem2, HIGH);
      digitalWrite(mem3, HIGH);
      digitalWrite(mem4, HIGH);
      digitalWrite(mem5, HIGH);
      digitalWrite(chemValve, HIGH);
      digitalWrite(idleValve, HIGH);
      digitalWrite(prePump, HIGH);
      digitalWrite(prePump, HIGH);
      digitalWrite(idleValve, HIGH);
    }
    void loop()
    {

           tankLow = digitalRead(5);
       tankHigh = digitalRead(6);

      if (tankLow == LOW && tankHigh == LOW){ //start day tank refill
       digitalWrite(A7, LOW);
      }
      if (tankLow == HIGH && tankHigh == HIGH){
        digitalWrite(A7, HIGH);
      }
      static int state = 1; // initial state is 1, the "idle" state.
      static unsigned long ts;

      switch (state)
      {
        case 1:
        ts = millis();

      if (delayMilliSeconds(1, 6000)){//600000

      digitalWrite(prePump, LOW);

      goNoGo = digitalRead(mainPump);
      if (goNoGo == LOW) {

        digitalWrite(idleValve, HIGH);
      }
        else {
          digitalWrite(idleValve, LOW);
              digitalWrite(mem2, LOW);
        digitalWrite(mem3, LOW);
        digitalWrite(mem4, LOW);
        digitalWrite(mem5, LOW);
        }

            readVoltage= digitalRead(idleValve);
        if(readVoltage==LOW){

        delay(4000); // wait time motors to stablize
        // read the input on analog pin 0:
        int sensorValue = analogRead(A0);
        // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
        float voltage = sensorValue * (4.83 / 1023.0);

        if (voltage >= 2.00)
        {
          state = 2;
        }

        else {
          delay(56000); //on time for test
        //  if (delayMilliSeconds(2, 51994)){
        digitalWrite(mem2, HIGH);
        digitalWrite(mem3, HIGH);
        digitalWrite(mem4, HIGH);
        digitalWrite(mem5, HIGH);

         digitalWrite(idleValve, HIGH);
          digitalWrite(prePump, HIGH);
          digitalWrite(mainPump, HIGH);
        }
        }

    }
    //} for if timer
    break;

        case 2:
           ts = millis();
          digitalWrite(mainPump, LOW);
          digitalWrite(idleValve, HIGH);
           digitalWrite(mem2, HIGH);
            digitalWrite(mem3, HIGH);
            digitalWrite(mem4, HIGH);
            digitalWrite(mem5, HIGH);
            delay(20000);
            state = 3;

            break;

            case 3:

          digitalWrite(mainPump, LOW);
          digitalWrite(idleValve, HIGH);
           digitalWrite(mem2, HIGH);
            digitalWrite(mem3, HIGH);
            digitalWrite(mem4, HIGH);
            digitalWrite(mem5, HIGH);

          pressureFault = digitalRead(pressure);
      if (pressureFault == HIGH){

        state = 4;
      }
       if (millis() - ts > 3600000){
        state = 5;
      }

       break;

       case 4:
       digitalWrite(mainPump, HIGH);
       digitalWrite(prePump, LOW);
       digitalWrite(idleValve, LOW);
          digitalWrite(mem2, LOW);
        digitalWrite(mem3, LOW);
        digitalWrite(mem4, LOW);
        digitalWrite(mem5, LOW);
        delay(3000);
        digitalWrite(mainPump, HIGH);
       digitalWrite(prePump, HIGH);
       digitalWrite(idleValve, HIGH);
          digitalWrite(mem2, HIGH);
        digitalWrite(mem3, HIGH);
        digitalWrite(mem4, HIGH);
        digitalWrite(mem5, HIGH);
        delay(600); //60000
        state = 1;

        break;

        case 5:
        ts = millis();
            digitalWrite(idleValve,LOW);
            digitalWrite(prePump,LOW);
             digitalWrite(mainPump, HIGH);
               delay(60000); //60000 for standard
               digitalWrite(mem2, LOW);
               delay(60000);
               digitalWrite(mem2, HIGH);
               digitalWrite(mem3, LOW);
               delay(60000);
               digitalWrite(mem3, HIGH);
               digitalWrite(mem4, LOW);
               delay(60000);
               digitalWrite(mem4, HIGH);
               digitalWrite(mem5, LOW);
               delay(60000);
               digitalWrite(mem5, HIGH);

               delay(1000);   // leave this time
             digitalWrite(idleValve, HIGH);
             digitalWrite(mainPump, LOW);
           state = 2;
             break;
             default:

             state = 1;

             break;

      } //switch
    } //loop

    int delayMilliSeconds(int timerNumber,unsigned long delaytime){
      unsigned long timeTaken;
      if (timerState[timerNumber]==0){    //If the timer has been reset (which means timer (state ==0) then save millis() to the same number timer,
        timer[timerNumber]=millis();
        timerState[timerNumber]=1;      //now we want mark this timer "not reset" so that next time through it doesn't get changed.
      }
      if (millis()> timer[timerNumber]){
        timeTaken=millis()+1-timer[timerNumber];    //here we see how much time has passed
      }
      else{
        timeTaken=millis()+2+(4294967295-timer[timerNumber]);    //if the timer rolled over (more than 48 days passed)then this line accounts for that
      }
      if (timeTaken>=delaytime) {          //here we make it easy to wrap the code we want to time in an "IF" statement, if not then it isn't and so doesn't get run.
         timerState[timerNumber]=0;  //once enough time has passed the timer is marked reset.
         return 1;                          //if enough time has passed the "IF" statement is true
      }
      else {                               //if enough time has not passed then the "if" statement will not be true.
        return 0;
      }

    }

As for wiring it is as basic as it gets 3.3v pin off the arduino to a pressure switch and then back to the arduino . but i'm not even making it to the switch before i have an issue literally plug in a 3ft wire not connected to anything and it goes to case 4
I've tried setting the code up to go to case 4 if it detects a LOW but hasn't changed my issue.

body:
As a hint.  Start by removing the stuff you added an just try to detect a grounding of your input pin (I'm assuming digitalRead(pressure) is the standard read the digital value of a pin and not some funky function you've written)

Use some code like this to test your hard ware

    int    pressure;

    void setup()
    {
        Serial.begin(9600);  //Start a serial monitor to see the results
        pressure = 4;  // Assumes your pressure input is pin 4
                       // change if need be
        pinMode(pressure,INPUT_PULLUP);  //Sets put to input with pullup
        digitalWrite(pressure,HIGH);      //Activates pullup
    }

    void loop()
    {
         if (digitalRead(pressure))
         {
              Serial.println("Pin is High");
         }
         else
         {
              Serial.println("Pin is low");
         }
         delay(1000);
      }

Now compile, upload and activate the serial monitor.  Every second you will get the read of the pin on the monitor.  See if grounding the pin is detected.  If not, you may have popped the port.

BTW.  3 ft of wire will need some filtering and protection.  That will pick up a lot of noise.

Cheers


message:
Fried two Arduino Nano's but works when powered

It took me about 4 hours to desolder an Arduino Nano I fried and solder on the new one. I'm not exactly sure how but I shorted it somehow while trying to install the nano onto my robot. I could smell a fait burning and the nano no longer powered on or allowed me to upload code via USB.

When I put the second nano on, before properly insulating exposed wire, I fried it again!! This time I actually saw a little smoke and quickly unplugged it. The nano no longer responds to the USB, but...

I have this nano also being powered by an Arduino Uno. When I turned on the battery connected to the Uno, the Nano turned on and everything was working fine!! I was pretty relieved after a short spout of depression! I plugged in the USB to the Nano and I was able to upload code... only with the nano being powered from the Uno. If I turn off the battery to the Uno the Nano doesn't work with USB.

I have no idea what happened exactly and I'm not sure what fried on my Nano but I sure am glad I have this work around instead of replacing the Nano again!

Does anyone know why it's doing this? What did I see smoking? Is it repairable?

body:
Judging by your list of observations:

* Cannot power through USB
* Can power from external source
* Can program through USB

it is most likely that the power feed from the USB to the +5V rail has been interrupted.  There is only one component in that link - the diode D1 (an MBR0520).  That is rated at an absolute maximum constant forward current of 0.5A and most USB ports these days are capable of providing far more than that.  A short circuit on the +5V to ground would draw considerably more current than that diode can handle and the Magic Smoke™ would escape.

The diode is on the underside of the Micro and close examination may show a small crack in the surface of it.  That is if it's still there.  I have used a similar PIC32 based board with 0.5A rated diodes on it, and a short of the power rail when powered from USB caused the diode to completely vaporise (at least I could find no trace of it afterwards).


message:
is any windows application available for accelerometer based computer mouse

I want to make an AIR mouse using Arduino
and accelerometer, for this i used USB to TTL
converter i have done everything successfully
but can anyone tell me how use it in computer.
I mean i don't know how to make computer
application for this mouse. please suggest me
any application for this. And give any idea for
"how can i use Bluetooth for this."


message:
How do I use a 3 legged phototransistor?

I have searched the Internet and found the following circuit to use with my phototransistor but it is not working, I can say so because all analog input i get is 1023 even if i have covered it totally, I have include the phototransistor and the diagram can anyone tell why is it not working!
I used this webpage to check my sensor and it works-[I used this page][1]

I have used 10kohm resistor.

![Image of circuit][2]

[This is my phototransistor][3]

![enter image description here][4]

  [1]: https://learn.adafruit.com/ir-sensor/testing-an-ir-sensor
  [2]: https://i.stack.imgur.com/lGika.jpg
  [3]: http://xmghdm.en.ec21.com/IR_LED_Infrared_LED_IR--3179904_3180358.html
  [4]: https://i.stack.imgur.com/JnfIZ.jpg

body:
A reasonably generic data sheet is [**HERE**](http://www.datasheetarchive.com/dl/Datasheets-SL3/DSASL0044436.pdf)
That is for an AT156 but yours may be an AT138/HT138 based on an ad some years ago from the same seller when they said they had 10,000 for sale.

Basic information here and more in the data sheet.

![enter image description here][2]

  [1]: https://i.stack.imgur.com/qUQZ2.jpg
  [2]: https://i.stack.imgur.com/iMyu8.jpg


body: First that is not even a photo resistor 2nd you have to put one wire positive and the other negitive and the last one plug it into any other gpio pin


message:
is any windows application available for accelerometer based computer mouse

I want to make an AIR mouse using Arduino and accelerometer, for this i used USB to TTL converter i have done everything successfully but can anyone tell me how use it in computer. I mean i don't know how to make computer application for this mouse. please suggest me any application for this. And give any idea for "how can i use Bluetooth for this."

body:
try "remotemouse.exe"
its a open source application you can modify the codes according to your requirement


message:
Common wireless gadget with rotary encoder to connect with Arduino

I'm looking for a common "wireless gadget" with a rotary encoder that can be accessed by an Arduino. Background: I need a portable rotary encoder to create a simple way to control model railway locomotives. The only one I have found so far is a wireless mouse where the scroll wheel can be easily used as rotary encoder.

But they usually are using USB on the PC side which is not that easy to handle by Arduino. Does anybody knows about other common "wireless gadgets"?

body:
That sounds like a candidate for building your own.  It shouldn't be too hard.

There's plenty of low-cost Arduino-compatible wireless modules available.  My choice for this would probably be the nRF24L01 - dirt cheap, reasonable range, well supported.

Attach that to an Arduino Mini or Arduino Nano (for instance) and connect a rotary encoder of your choice.  Write the sketch.

Add another nRF24L01 to your main Arduino to receive whatever you send.

Due to the way the nRF24L01 works you could quite easily have a number of remote modules talking to the Arduino through the same channel.  I'm sure you could think of other things you could do with that wireless channel :)


body:
In addition to @Majenko,

If your device is going to talk to a PC/Laptop (or cellphone!), then HC05 or HC06 bluetooth serial module may be a better fit. You will still need to write software to receive the data, but you won't need another Arduino at the other end.


message:
Using shiftin() and shiftout() with the same circuit - what to consider?

I am designing a smart (or at least I hope so) onboard bicycle light system. The system will have an Arduino (currently prototyping with UNO) and a subsystem composed of a "panel" of buttons and leds.

This panel should stay at the handlebar, connected by multi-wire cable to the Arduino located elsewhere on the bicycle.

In order to read an arbitrary number of push-buttons, I plan to use CD4021 IC with `shiftIn()` function. And, in order to turn an arbitrary number of leds on and off, I plan to use 74HC595 IC and the `shiftOut()` function.

My doubts are: what should I consider in order to do so?

 1. How many wires should I need to connect an arduino to the panel circuit containing the ICs? I believe it is 8 wires (two for the power, three for shifting in [latch, clock, data], and three for shifting out), right?

 2. Can I use any pin I want? Or is it required to use specific pins?

 3. Is that the "right way" of doing this? Any suggestion or improvement is welcome!

body:
I have a post here about using an I2C 16-port port-expander: http://www.gammon.com.au/forum/?id=10945

That would use 4 wires for I2C (power, ground, SDA, SCL) or there is an SPI version which would require an extra wire (power, ground, SCK, MOSI, MISO).

I'm not sure about noise over your cable runs, on a bicycle presumably electrical noise is low, so either one might suit. This is the chip that  Ignacio Vazquez-Abrams mentioned in his comments. Any of the 16 ports can be configured as inputs or outputs as you desire, plus it can raise an interrupt on a change on an input pin.

You might find that the maximum current limits for output may not be adequate for your LEDs (the datasheet says maximum of 25 mA per output pin, plus a maximum of 125 mA for the whole chip). You could work around this with driver transistors on the chip output, but this is more complexity.

There are higher-powered shift registers (eg. TPIC6B595) which can handle more per pin than the 74HC595.

> Can I use any pin I want? Or is it required to use specific pins?

If you want to use I2C there are two specific pins dedicated to the I2C hardware. If you want to use SPI there are dedicated hardware pins as well (different ones) but you can also "bit-bang" SPI if you want.

See:

http://www.gammon.com.au/i2c

http://www.gammon.com.au/spi

>  Is there a through-hole version of that?

All the chips I mention here have through-hole versions.


message:
Increment in switch statement not working

No matter how I rearrange this, the increment compare always returns false....

I have even taken it out of the if, and put it in its own if:

    int buttonFSM(button *ptrButton)
    {
        int i;
        i = digitalRead(ptrButton->pin);
        switch(ptrButton->buttonState)
        {
        case SW_UP:
            if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down
            {
                ptrButton->buttonState = SW_DOWN;
                ptrButton->debounceTics = 0;
                return SW_TRANS_UD;
            }
            ptrButton->debounceTics = 0;
            return SW_UP;
        case SW_DOWN:
            if(i==1 && ++ptrButton->debounceTics == DBNC_TICS) //switch is back up
            {
                ptrButton->buttonState = SW_UP;
                ptrButton->debounceTics = 0;
                return SW_TRANS_DU;
            }
            ptrButton->debounceTics = 0;
            return SW_DOWN;
        }
    }

body:
Looks to me like the path where the if doesn't happen are getting you. You don't show what DBNC_TICS is set to, but I'm assuming it's > 1.

ptrButton->debounceTics will never be greater than 1 because you always:

        ptrButton->debounceTics = 0;


body:
The error is due to wrong expectations on operators precedence:
++ and -> have the same precedence, so they are evaluated left to right.
See http://en.cppreference.com/w/c/language/operator_precedence .

Overall, the lack of parenthesis makes the readability poor.

The code can be improved by dropping the switch and simply checking that the current value is equal to the previous value through the duration of the sampling period.
Then read the value and decide if it's high or low.

But even this might be a poor choice, because it simply samples the value periodically and can miss changes that are not intercepted by the sampling.

Depending on the application, it might be preferrable (certainly it is more precise) to use interrupts on both edges (rising and falling) and a timeout: reset the timer at every interrupt. If the timer expires undisturbed, use the level read at the last interrupt.


body:
<!-- language-all: lang-C++ -->

      if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down
        {
            ptrButton->buttonState = SW_DOWN;
            ptrButton->debounceTics = 0;
            return SW_TRANS_UD;
        }
        ptrButton->debounceTics = 0;

I'm going to agree with user3877595 but explain why, as his/her answer got a downvote.

`DBNC_TICS` has to be > 1, right? Otherwise what is the point?

We want to debounce after "x" ticks, and let's assume that the number of ticks is initially zero.

If `DBNC_TICS` is == 1 then this is always true:

    ++ptrButton->debounceTics == DBNC_TICS

Therefore that test is useless.

If `DBNC_TICS` > 1 then it will not execute the "if" block and execute this instead:

        ptrButton->debounceTics = 0;

So `ptrButton->debounceTics` is back to zero, and we are back to square 1.

Therefore the test will always be false.

> No matter how I rearrange this, the increment compare always returns false....

As stated in the question.


message:
How does the reset button work on the Arduino?

I'm confused about how and when to use the reset button on the Arduino. Do I simply press the button while it is on? Is it simply restarting the board or clearing the uploaded code as well? Currently when I press the button while my Uno is powered it does absolutely nothing.

I have been using this board for many weeks with no problem and just now I have been getting this error:

    avrdude: stk500_getsync()

And I cannot upload code. I tried using the reset button but I see nothing happening on the board, no blink, no flicker, nothing indicating something was reset.

body:
The reset button does pretty much the same as unplugging the board and plugging it back in.  It restarts your program from the beginning.

The same thing happens when you program the board - the USB interface presses the reset button for you.  That then enters the bootloader for a second or two so it can try and program it.

When you reset the board the LED on pin 13 should flash a couple of times while it's in the bootloader before it runs whatever program you have programmed in.  If that LED doesn't flash when you press the reset button then there is a serious fault with your board which will take further diagnostic.

* If you have anything else plugged into the Arduino then unplug it.
* Try powering the Arduino from different power supplies.
* If you have another Arduino or an AVR programmer try re-flashing the bootloader.


message:
how does an 8-bit AVR do 10-bit analog read?

I am building a pH meter and having a real close look into the analog components, and reading the Arduino documentation for `analogRead()`.
https://www.arduino.cc/en/Reference/AnalogRead

I see it says the Arduino, in my case an 8-bit AVR ATmega328 Arduino Uno,
yields a resolution between readings of: 5 volts / 1024 units or, .0049.

My question is whether that is accurate, or even possible. How can an 8-bit MCU provide a 10-bit analog read? how does that work?

Shouldn't the analog read be 2^8 or 256?

body: It can do a 10-bit reading quite simply - because the ADC is a 10-bit ADC.  The CPU register size doesn't dictate what it can communicate with, either internally or externally.  The only thing it dictates is how big a number it can cope with at any one time.  Because of this the 10-bit result of the ADC is spread across two registers - 2 bits in the "high" ADC result register, and 8 bits in the "low" ADC result register.


message:
How to store values inside an empty array and get the average integer? [UPDATED QUESTION]

Goodafternoon,

I want to read values form a microphone (Adafruit MAX9814) connected to the Analog port A0 from Arduino and store the values that are incoming inside an array.

After the values are stored in the array, I want to read out the values and store the number that is repeated most time in a variable. Is this possible and how to achieve this?

I came up with the following:

    const int micPin = A0;
    int soundArray[10];

    void setup() {

      Serial.begin(9600);
      pinMode(micPin, INPUT);

    }

    void loop() {

      int micValue = analogRead(micPin);
      Serial.println(micValue, DEC);
      //delay(400);

      for (int i = 0; i > 10; i++) {
        soundArray[i] = micValue;
        Serial.println(soundArray[i]);
      }
      delay(1000);
      Serial.println("End of for loop");

    }

The problem now is that a value of the microphone will be repeated 10 times. So I will receive 10 times the number 234 for example. See image.

This is not what I want. I want to get different numbers in the array of that moment.
![enter image description here][1]

Hope someone can help me out.
Thanks in advance.

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

body:
The error message is correct. You did not define the size of the array.
You have 3 choices:

1. Declare it with a constant length

    int foo[10];

2. Declare it and initalize it

    int foo[] = {0,1,2,3,4,5,6,7,8,9};

3. Declare it dynamic as pointer and alloc or realloc the mem by yourself (this is not recommended (realloc) because of possible heap memory fragmentation)

    int *foo;
    int size = 10;
    foo = (int*)malloc(size * sizeof(int));
    free(foo);

As reference:
http://www.arduino.cc/en/pmwiki.php?n=Reference/Array


body:
There are three main sorts of "average" used normally in Maths:

* Mean: This is the most common meaning of Average. It is the mathematical average of all the values in the set - the sum of all the values divided by the number of values.
* Mode: This is the "most common" value in a set of values.  For the set {1, 2, 3, 4, 3, 5, 3, 1, 7, 3} the "mode" would be 3 since there are more 3's than any other number.
* Median: This is the middle value of a set of values.  If there are 5 values and they are sorted into ascending order the "median" would be the third (middle) value.

By your comments it sounds like "mode" is what you are after - the most common number in your set of values.

It's quite easy to work out which is the most common number in a set if you are willing to loop through that set enough times.

I have an [Average library](https://github.com/MajenkoLibraries/Average) that can do it for you.  The main part of the `mode()` function of that library looks like this:

    most = _store[0];
    mostcount = 1;
    for(pos = 0; pos < _count; pos++) {
        current = _store[pos];
        currentcount = 0;
        for(inner = pos + 1; inner < _count; inner++) {
            if(_store[inner] == current) {
                currentcount++;
            }
        }
        if(currentcount > mostcount) {
            most = current;
            mostcount = currentcount;
        }
        // If we have less array slices left than the current
        // maximum count, then there is no room left to find
        // a bigger count.  We have finished early and we can
        // go home.
        if(_count - pos < mostcount) {
            break;
        }
    }
    return most;

Basically two loops, one inside the other.  The outer one steps through each number, and the inner one counts the number of times than number appears in the set (actually just from the current outer loop position to the end of the set - no point in counting numbers we've already looked at).  If the count is greater than the current "mode" count then store that as the "mode" count and also store the value as the "mode" value.  Move on to the next number.

To use the Average library it's quite simple:

    const int micPin = A0;

    // We want to be able to store 10 int values here.
    Average <int>sounds(10);

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

    void loop() {
        // Push 10 values into the Average buffer.  Any old values will drop
        // off the bottom.
        for (int i = 0; i < 10; i++) {
            sounds.push(analogRead(micPin));
        }
        Serial.print("Mode value is: ");
        Serial.println(sounds.mode());
        delay(1000);
    }


message:
Pinout of Arduino 9 Axes Motion Shield

I bought an [Arduino 9 Axes Motion Shield][1] without looking at the pinout. I'm worried it won't work with my [Adafruit Motor Shield v1][2].

It seems the 9 axes shield uses I2C, a reset pin and several other pins for the TinkerKit Input, Output and TWI connectors. Does anyone have a list of specific ports used by the shield on the Arduino UNO?

It also seems that my Arduino UNO r1 only has the original analog pins for I2C, while the 9 axes shield uses the new pins next to the digital pins.

_update: I asked support from arduino.org on twitter and on their forums, no reply yet and it seems their twitter account has been suspended. Should have bought a Genuino I guess._

  [1]: http://www.arduino.org/products/arduino-9-axes
  [2]: https://www.adafruit.com/products/81

body:
The I2C pins on the V3 shield are just copies of A4 & A5 - so just run a jumper wire some way.

BTW that Motion shield looks like it only uses 1 interrupt pin in addition to I2C, so you may be ok.

The motor board does have a library at https://learn.adafruit.com/adafruit-motor-shield/downloads and you can look at the code to see what it uses.

I personally use the mpu6050 - same kind of thing, I2C one interrupt but only 6DoF (which is plenty).  The 6050 has been superseded with the 9150, 9DoF.  6050 break out boards sell for $6 (or less).  Actually I put all this together on one piece (http://www.spiked3.com/new-products/)


message:
Strange phenomenon when declaring double

**Consider this question closed, found my answer through the answers I had**

I am trying to make a position profile curve depending on Looptime, accelerationloops,Setposition,Currentposition(position) and velocity.
The curve should look like this:

![enter image description here][1]

Is someone able to check what is wrong with my code?

    float array[30];

    struct Formula {
      int LoopTime = 1000;
      int AccelerationLoops = 11;
      float VelocityLoop = 0;
      float VelocityFactor = 0;
      int TotalLoops = 0;
      float DeltaPosition = 0;
      int Setpoint = 0;
      int Iteration = -1;
      float EndOne = 1.25;
    }Formula;

    float SetPosition = 1404;
    float Position = 0;
    float Velocity = 36;

    void setup() {
      Serial.begin(115200);
      for(Formula.Iteration ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
        ProgFormula();
        Serial.println(Formula.Iteration);
        if(Formula.Iteration >= 0) {array[Formula.Iteration] = Formula.Setpoint;}
      }
      for(Formula.Iteration = 0 ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
        //Serial.println(array[Formula.Iteration]);
      }
    }

    void loop() {
      // put your main code here, to run repeatedly:

    }

    void ProgFormula(){
      if(Formula.Iteration == -1) {
        Formula.DeltaPosition = SetPosition - Position;
        Formula.VelocityLoop = Velocity / (1000 / Formula.LoopTime);
        Formula.TotalLoops = Formula.DeltaPosition / Formula.VelocityLoop + Formula.AccelerationLoops;
        Formula.VelocityFactor = Formula.VelocityLoop * 0.5 / Formula.AccelerationLoops;
        Formula.EndOne = (Formula.VelocityFactor*pow(Formula.AccelerationLoops,2));
      }
      else if (Formula.Iteration >= 0 && Formula.Iteration <= Formula.AccelerationLoops) {
        Formula.Setpoint = Formula.VelocityFactor * pow(Formula.Iteration,2);
      }
      else if (Formula.Iteration > Formula.AccelerationLoops && Formula.Iteration <= (Formula.TotalLoops - Formula.AccelerationLoops)) {
        Formula.Setpoint = Formula.VelocityLoop * Formula.Iteration - Formula.EndOne;
      }
      else if (Formula.Iteration >= (Formula.TotalLoops - Formula.AccelerationLoops) && Formula.Iteration <= Formula.TotalLoops) {
        Formula.Setpoint = -Formula.VelocityFactor * pow((Formula.TotalLoops - Formula.Iteration),2) + Formula.DeltaPosition;
      }
      else {
        Formula.Setpoint = Formula.Setpoint;
      }
    }

  [1]: https://i.stack.imgur.com/VttgJ.jpg

body:
OK, this may not be a proper answer. I'm just having a hard time reading
your code, and I cannot understand why you make it so complicated. If
you know the acceleration profile, computing the position profile is
just a matter of integrating twice. Here is an example, not for Arduino
but for a PC. It should not be very different on an Arduino, you just
wouldn't use `printf()`:

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

    /* Compute position for any acceleration profile. */
    void compute_profile(float (*acceleration)(int), int max)
    {
        float x = 0, v = 0;

        for (int t = 0; t <= max; t++) {
            v += acceleration(t);
            x += v;
            printf("%d\t%f\n", t, x);
        }
    }

    /* Your particular acceleration profile. */
    float VttgJ(int t)
    {
        if (t <  7) return t;
        if (t < 13) return 12 - t;
        if (t < 40) return 0;
        if (t < 46) return 39 - t;
        else        return t - 51;
    }

    int main(void)
    {
        compute_profile(VttgJ, 50);
        return 0;
    }


message:
Counter using Ultrasonic Sensor (self.arduino)

I am doing a pretty simple arduino project that uses a Parallax Ping Ultrasonic Sensor to increment a counter when an object moves past the desired distance. (object leaves, counter goes up, object comes back, this loops forever). My problem is now that every time i run this.. the serial monitor just shows me Count: 1 over and over again and does not increment.
Any help would be appreciated!

example of what i want the Serial Monitor to write:
Count:0
Count:1
Count:2 ....

What it is currently doing:
Count:0
Count:0
Count:0

    const int pingPin = 7;

    void setup() {
      // 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, count;

      // 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(2);
      digitalWrite(pingPin, HIGH);
      delayMicroseconds(5);
      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);
    // count = 1;

     if (inches > 5)
    {
      Serial.print("Count: ");
      Serial.print(count);
      Serial.print('\n');
      delay(1000);
            count++;

    }

    }

    long microsecondsToInches(long microseconds)
    {
      return microseconds / 74 / 2;
    }

    long microsecondsToCentimeters(long microseconds)
    {

      return microseconds / 29 / 2;
    }

body:
Count is a local variable - it gets re-created afresh every time the loop() runs.

Either make it global, or make it static.

These two options look like this:

**Global**

    long count = 0;

    void loop()
    {
      // establish variables for duration of the ping,
      // and the distance result in inches and centimeters:
      long duration, inches, cm;

**Static**

    void loop()
    {
      // establish variables for duration of the ping,
      // and the distance result in inches and centimeters:
      long duration, inches, cm;
      static long count = 0;

Both will do the same job, but the `static` form is preferred since it is always better to keep a variable's scope as narrow as possible.  It is also important to provide a start value for the counter to begin from (0 in this case) otherwise the starting value will be unknown.


message:
How to use Arduino Nano with Arduino Uno

I am using an Arduino Uno and have used up all it's pins so I have plugged up a Nano to a couple of the Uno's pins and using the Uno's 5v and ground to power the Nano. Is this ok?

It's been working fine until recently. My Uno will no longer allow me to upload code but everything still powers fine and runs on the existing code I had uploaded before. The reset button on the Uno does not work so I assume it's bricked, but it does still operate fine on the code it has, as I said.

Anyway, my question, is it ok to run the Nano like this? Is it using too much of the Uno's current... because the Nano's pins are also all being used. I'm no good at regulating current and just want to make sure that the Nano isn't eating up a bunch of current from the Uno by lighting it's LED's and it's other operations.

body:
Be careful not to power any sort of motor directly from an Arduino (or any of it's siblings directly) without a transistor or H-bridge in between, unless you know exactly how much current your motor draws, peak, and how much your arduino can supply on any given pin. The same applies to any other high-draw device too.

If you are using LEDs, make sure you have a resistor in series with the LED - google "LED resistor calculator" to help you figure out which resistor you need.

Also, when you upload the program, it uses two of the pins - rx and tx, should be digital pins 0 & 1 on a Uno (any other, check your docs).


body:
Maybe it is a very good idea to connect Arduino UNO's only one DIGITAL out point among other digital output pins. This pin can trig Arduino Nano's analog input pins so that you can work your task for further you needed. But you have to seperate your shields or your motors or other things. Like this:

![enter image description here][1]

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

By the way, if you get an upload error, please plug out your shileds or motors or LEDs then try to upload your code again into Arduino UNO.


body: try to connect uno and nano with I2C or serial, with I2C it connected to SCA/SDL pin (analog 4/5) or with serial it connected to tx rx. Make sure you use a pull up resistor. From the main site of arduino there's a tutorial in there but forgot to set up a pull up resistor.


message:
BLE Mate 2 bluetooth module to Arduino Uno without FTDI SmartBasic

So I'm trying to hook up this [BLE breakout board][1] to an Arduino Uno. SparkFun has a [hookup guide][2] which seems to be great for someone who has an FTDI SmartBasic that is mentioned in the article. I don't have the SmartBasic board, and would like to see if this is possible without it.

I have hooked up the board to my Uno with the following pinouts:

    GRN -> Reset
    RXI -> RX (tried with TX as well)
    TXI -> TX (tried with RX as well)
    VIN -> Tried 5V and 3.3V
    CTS -> GND
    BLK -> (No Connection)

I use their [example code][3] they have provided, uploaded without the RX and TX pins hooked up because, from what I notice, you cannot upload a program through the USB serial when these ports are in use. So after I upload the program through USB, I power the board with a battery and connect the RX and TX pins to the BLE board.

Has anyone either successfully hooked these up without the use of a SmartBasic? I'm a programmer by trade so I do my best to understand this side of the spectrum.

  [1]: https://www.sparkfun.com/products/13019
  [2]: https://learn.sparkfun.com/tutorials/bc118-ble-mate-2-hookup-guide?_ga=1.207897426.1342547721.1435176975
  [3]: https://github.com/sparkfun/SparkFun_BLE_Mate2_Arduino_Library

body:
So I found out what I was doing wrong, and want to smack myself for it -.-

The answer was to simply hook up the BLK connection (which I guess is also ground) to a GND pin on the Arduino Uno.

Hope this ends up helping someone out.


message:
Timer function without the use of a library

Trying to do my own timer function. I was wondering if there is any other ways to make my code more efficient without the use of a library. I noticed if I only use one timer function, I wont have multiple instances of the timer. My current code works though.

    unsigned long previousMillis1 = 0;
    unsigned long currentMillis1 = millis();
    unsigned long previousMillis2 = 0;
    unsigned long currentMillis2 = millis();
    unsigned long previousMillis3 = 0;
    unsigned long currentMillis3 = millis();

    bool timer1(int preset){
      unsigned long currentMillis1 = millis();

      if(currentMillis1 - previousMillis1 >= preset ){
        previousMillis1 = currentMillis1;
        return true;
      }
      else{
        return false;
      }
    }

    bool timer2(int preset){
      unsigned long currentMillis2 = millis();

      if(currentMillis2 - previousMillis2 >= preset ){
        previousMillis2 = currentMillis2;
        return true;
      }
      else{
        return false;
      }
    }

    bool timer3(int preset){
      unsigned long currentMillis3 = millis();

      if(currentMillis3 - previousMillis3 >= preset ){
        previousMillis3 = currentMillis3;
        return true;
      }
      else{
        return false;
      }
    }

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

    void loop() {
      if(timer1(1000)){Serial.println(1);}
      if(timer2(2000)){Serial.println(2);}
      if(timer3(3000)){Serial.println(3);}
    }

body:
It depends on what kind of efficiency you want. In coding we can often between better execution speed and less memory required. And in the case of Harvard-architected machines such as the AVR devices, which have separate memories for code and data, there may be a further balance between those, too.

But it looks like you're trying to reduce your code space requirement. So notice how alike your three timer functions are. I'd combine those into one, and pass another argument that indicates which timer value to operate on.

Secondly, (and this is probably a bug more than an inefficiency), you have three globals that are not being used (in your example, anyway): `long currentMillis1`, ..2, & ..3. You have redeclared each of those names as a local variable in the respective timer function, which, within that function over-rides (hides) the global declaration. There is no code that uses those globals.


body:
Your code is not bad in terms of efficiency. You have, however,
duplicated code, which is bad in terms of program size, but also makes
the program harder to read and to maintain. A good rule for programmers
is “do not repeat yourself”. Then, when you find yourself writing almost
identical functions, you should try to find a way to merge them into a
single function.

Here it is easy: the only difference between your timer functions is
that they use a different `previousMillis` variable. Also, the name of
the `currentMillis` variable is different, but it being a local
variable, this difference is irrelevant. Then, to merge them into a
single function, you only have to give to this function a _reference_ to
the relevant `PreviousMillis`.

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

    bool timer(unsigned long &last_time, unsigned long period)
    {
      unsigned long now = millis();
      if (now - last_time >= period) {
        last_time = now;
        return true;
      }
      return false;
    }

And you use it like this:

    void loop() {
      static unsigned long previousMillis1;
      static unsigned long previousMillis2;
      static unsigned long previousMillis3;

      if (timer(previousMillis1, 1000)) Serial.println(1);
      if (timer(previousMillis2, 2000)) Serial.println(2);
      if (timer(previousMillis3, 3000)) Serial.println(3);
    }

I took the liberty of making all the `previousMillis` local to `loop()`,
since they are only used there. Making them `static` means their values
are remembered between call to `loop()`, much like global variables.

In plain C you would use pointers instead of references. It is basically
the same, except that with pointers you are _explicitly_ manipulating
addresses, while this is implicit with references:

    bool timer(unsigned long *last_time, unsigned long period)
    {
      unsigned long now = millis();
      if (now - *last_time >= period) {
        *last_time = now;
        return true;
      }
      return false;
    }

    void loop() {
      /* [...] */
      if (timer(&previousMillis1, 1000)) Serial.println(1);
      /* [...] */
    }

The next step in code modularity would be to wrap this timer function,
together with the associated data (`last_time` and `period`), inside a
class:

    class Timer
    {
    public:

      Timer(unsigned long _period)
      : period(_period), last_time(millis()) {}

      bool shouldRun() {
        unsigned long now = millis();
        if (now - last_time >= period) {
          last_time = now;
          return true;
        }
        return false;
      }

    private:
      unsigned long period;
      unsigned long last_time;
    };

Then, you would use it like this:

    Timer timer1(1000);    // period = 1000 ms
    Timer timer2(2000);    // period = 2000 ms
    Timer timer3(3000);    // period = 3000 ms

    void loop() {
      if (timer1.shouldRun()) Serial.println(1);
      if (timer2.shouldRun()) Serial.println(2);
      if (timer3.shouldRun()) Serial.println(3);
    }


body:
You can simplify **a lot** by using arrays. The example code below just uses a single variable (array) to store all the time intervals you are interested in.

<!-- language-all: lang-C++ -->

    const int NUMBER_OF_TIMERS = 5;

    unsigned long intervalStarted [NUMBER_OF_TIMERS];

    void resetTimer (const int whichTimer)
      {
      if (whichTimer < 0 || whichTimer >= NUMBER_OF_TIMERS)
        return;   // sanity clause
      intervalStarted [whichTimer] = millis ();
      }  // end of resetTimer

    // interval in milliseconds
    bool timeUp (const int whichTimer, const unsigned long whatInterval)
      {
      if (whichTimer < 0 || whichTimer >= NUMBER_OF_TIMERS)
        return false;   // sanity clause
      return  millis () - intervalStarted [whichTimer] >= whatInterval;
      }  // end of timeUp

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      Serial.println (F("Starting ..."));
      }  // end of setup

    void loop ()
      {

      if(timeUp(0, 1000))
        {
        Serial.println(1);
        resetTimer (0);
        }  // end of if timer 0 up

      if(timeUp(1, 2000))
        {
        Serial.println(2);
        resetTimer (1);
        }  // end of if timer 1 up

      if(timeUp(2, 3000))
        {
        Serial.println(3);
        resetTimer (2);
        } // end of if timer 2 up

      }  // end of loop

I have allowed for 5 "timers" in the code but only used 3 to be consistent with the original post. You can see that you can have as many as you want (until you run out of RAM) with only an overhead of 4 bytes per "timer".

Two functions are provided. One checks if a nominated interval is up, the other one "resets" the timer by setting its start time to now. The checking function should work correctly even during millis() wrap-around, providing you are not trying to time more than 4294967296 milliseconds in one hit (49.71 days).

Note that the timer numbers are zero-relative, so the first timer is timer 0. You could make them one-relative if you prefer that with a slight adjustment to the two functions.

You could also, if you chose to, put the resetTimer function call inside the timeUp function (if the time is up) so that the timer automatically resets. I didn't do that because I think starting timing, and detecting the end of a period could be two different things. For example, when you boil an egg, you start timing from the time the egg goes onto the boil, not from when you last cooked an egg.


body:
Happened across [this page][1] which explains Arduino timer interrupts with out using any libraries.  The Atmel timer hardware is discussed and the sketches not only control the hardware directly but also include the actual interrupt service routine.  So addresses the OP's question very well.

  [1]: https://oscarliang.com/arduino-timer-and-interrupt-tutorial/


message:
Simple question about && vs ||

I want to skip all `'\r'` and `'\n'` chars and I have IF statment:

    char c = Serial.read();
    if (c != '\r' || c != '\n') { // <- This line interesting
       mAnswer[mAnswerLength] = c;
       mAnswerLength++;
    }

VS

    char c = Serial.read();
    if (c != '\r' && c != '\n') { // <- This line interesting
       mAnswer[mAnswerLength] = c;
       mAnswerLength++;
    }

What is better and what is the difference?

body:
|| means logical OR

&& means logical AND


body:
Think about it "logically" (pun intended...):

You read a character.  Say it's "A".  You then compare it to both '\r' and '\n'.

    char c = Serial.read();
    if (c != '\r' || c != '\n') { // <- This line interesting
        mAnswer[mAnswerLength] = c;
        mAnswerLength++;
    }

That is saying "If A is not CR or A is not LF then add it".  Since it's A and not LF or CR then it's going to add it.  Now imagine it's CR.  "If CR is not CR or CR is not LF then add it".  CR is CR, so the first part will be false.  But CR isn't LF, so the second part is true.  If it's OR, then if either part is true then it will be true.  So since CR is not LF it will add it.

Now:

    char c = Serial.read();
    if (c != '\r' && c != '\n') { // <- This line interesting
        mAnswer[mAnswerLength] = c;
        mAnswerLength++;
    }

That is saying "If A is not CR and A is not LF then add it".  Since it's A and not LF or CR then it's going to add it.  Now imagine it's CR.  "If CR is not CR and CR is not LF then add it".  CR is CR, so the first part will be false.  But CR isn't LF, so the second part is true.  Just as before.  However, if it's AMD, then if BOTH parts are true then it will be true.  So since CR is CR it won't add it.

In summary, the first one will ALWAYS be true since one half is always going to be true.  The second one will ONLY be true if BOTH parts are true.  So the first one just plain isn't going to do what you want.


body:
You can rewrite first condition to be more obvious

    if (c != '\r' || c != '\n') {
as

    if (!(c == '\r' && c == '\n')) {

Which is always true (`c` have only one value), i.e. it makes no sense.


message:
Parallel connection to Wiegand 26bit RFID readers

I have situation where I need to read RFID cards. There is already installed Roger security system, Roger gate control board and two rfid readers in parallel. By default board and RFID readers communicate in RACS(some sort of coded protocol) but at the moment system is configured to communicate in Wiegand26. Earlier I used chinese wiegand26 reader with Arduino with no problem.

With Arduino I need to read card read by RFID readers.
Then I process data and make HTTP POST request.
Arduino is supplied from Roger board ~13.5V DC I do not get anything in arduino, even if I connect RFID readers directly to arduino.

 - CLK is D0 to Arduino Nano pin 2
 - DTA is D1 to Arduino Nano pin 3

This question is not related only to Arduino.

I want to ask is it possible to do? To read data maybe I need some additional electronics?

What i also noticed that when Arduino is connected in parallel the Roger board not always reads the card from RFID readers.

Roger [PR402-BRD][1]
And two readers [PRT62LT][2]
![enter image description here][3]

This is copy of [Electronics.stackexchange][4]

  [1]: http://www.roger.pl/en/products-to-be-discontinued/760-pr402-brd-access-controller.html
  [2]: http://www.roger.pl/en/access-control/readers/proximity-readers-em-125-khz/805-prt62lt-proximity-reader-em-125-khz.html
  [3]: https://i.stack.imgur.com/z7IBI.png
  [4]: https://electronics.stackexchange.com/q/177168/58967

body:
It looks to me like the Wiegand interface is an open-collector interface (like I2C), which is why they can be wired in parallel like that.

As long as the Arduino has both connections set to `INPUT` (not `INPUT_PULLUP` and certainly NOT `OUTPUT`) it shouldn't interfere at all.

By the way, for Wiegand, the two signals are DATA0 and DATA1.  To transmit a 0 the DATA0 line is pulled low. To transmit a 1 the DATA1 line is pulled low.

You should also check that the idle voltage on the lines is indeed 5V as it should be.  Anything more than that could cause the Arduino to chip the voltage to 5V through its internal ESD protection diodes.

Also you must ensure that the Arduino has its ground pin connected to the ground connection of the Wiegand system (which it should be since you are powering it from that).


body:
If you would like to use more than 1 Wiegand reader, technically it should be possible to use **AVR pin change interrupt**. In this case you can use ANY 2 pins, even analog pins.

For example, see http://thewanderingengineer.com/2014/08/11/arduino-pin-change-interrupts/

**UPD:** There is informationon Wiegand timing, might be useful:
http://proxclone.com/wiegand.html


message:
CAN Bus without Transceivers

I am trying to set up a CAN-bus with its two nodes on the same Arduino. By Using an Arduino DUE without any transceivers. As my first experiment, I want to send a message from one CAN unit to the other. But so far I have not been successful to see any signal on the bus. (I am using an Oscilloscope)

**Here is the detail of my effort:**

I have used this(1) library, and I want to run the CAN_EchoTest example(2).
As for the physical layer, I have created a circuit, according to a Method that is suggested here(3), here(4), and here(5). I set the transmission rate to 5Kbps, (lowest possible value provided by the library), to make sure that noise and propagation effects are minimal.

I implemented this mentioned Method to the Arduino board, using the Board's Schematics(6). In other words, I assumed that:

    CANTX1 in the schematics, refers to PIN with the label '53' on the board.
    CANRX1 in the schematics, refers to PIN with the label 'DAC0' on the board.
    CANRX0 in the schematics, refers to PIN with the label 'CANRX' on the board.
    CANTX0 in the schematics, refers to PIN with the label 'CANTX' on the board.

And I assumed the library that I am using configures the mutual PINS (DAC0 and 53), in a way that CAN controllers will be using them exclusively. I am not sure about the pair of diodes that I used: Vishay SS34A.

what is missing/wrong? Please be patient regarding any rookie mistakes. I can Provide further information if requested.

Thank you in advance

  (1) [github.com/collin80/due_can][1]

  (2) [github.com/collin80/due_can/tree/master/examples/CAN_EchoTest][2]

  (3) [www.mikrocontroller.net/attachment/28831/siemens_AP2921.pdf][3]

  (4) [electronics.stackexchange.com/questions/30564/is-a-can-enabled-microcontroller-sufficient-to-drive-a-can-bus][4]

  (5) [www.keil.com/download/files/canprimer_v2.pdf][5]

  (6) [www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf][6]

  [1]: http://www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf
  [2]: http://github.com/collin80/due_can/tree/master/examples/CAN_EchoTest
  [3]: http://www.mikrocontroller.net/attachment/28831/siemens_AP2921.pdf
  [4]: https://electronics.stackexchange.com/questions/30564/is-a-can-enabled-microcontroller-sufficient-to-drive-a-can-bus
  [5]: http://www.keil.com/download/files/canprimer_v2.pdf
  [6]: http://www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf

body:
You will have to play some games to make it work.  CAN is a bus with dominate and recessive states.  This is how it arbitrates.  When a unit starts sending a message and another starts concurrently they will both keep transmitting until one is sending a dominate signal and the other is recessive.  At that point the unit placing the recessive signal on the bus backs off and waits until the bus is idle before re-trying.

You can simulate this with a few transistors (not real CAN but will work).  Monitor the bus with the receive side and drive it with the transistor with a pull up resistor.  When the transistor is on that is the dominate state when the transistor is off that is the recessive state.  This automatically places a priority order to each unit. Also you cannot operate with 1 CAN device, each message has to be acknowledged by another. It is imperative that you receive what you send.  Transceivers are very cheep on eBay and they have the Maxim chip which is very good.
Good Luck,
Gil


message:
Arduino Micro + Max4466 - Noise on A0

I've got an Arduino Micro, and a MAX4466 ECM / AMP breakout board (https://www.adafruit.com/product/1063). I'm powering the Arduino Micro from the USB port.

On the MAX4466 (to the Arduino), I've wired VCC to 3.3v, GND to GND, and OUT to A0. I've also wired 3.3v to AREF.

Using the following code, I'm noticing significant noise spikes on the output, as shown in the graph below.

I'm not entirely sure what I've done wrong here, and would appreciate any input / criticism that could lead to getting a clean signal.
<!-- language-all: lang-cpp -->

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

    void loop()
    {
       Serial.println(analogRead(0));
    }

![enter image description here][1]

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

body:
The OP itself solve it:

> Ok - so I suspected that it was the Arduino at fault.. Turns out it's
> a cheap Chinese clone. After purchasing an official Micro, and wiring
> up the same component, I'm getting a nice clean signal (bar a small
> amount of acceptable noise), which is reflecting input tones
> accurately. Thanks again for all the input!


body: Interesting plot. Gives me the impression that your reference is sagging, consider adding some local storage (tant/ceramic capacitors) across the cpu's power in pins and across the cpu's Reference pin. Would also be interesting to know if adding more delay between measurements would improve performance. Thanks for sharing you issue.


message:
Is it possible to control the speed of DC motors with Arduino's analogWrite() using analog pins?

I'm trying to control the speed of two DC motors that are connected to a dual H bridge. I always used digital PWM pins with `analogWrite()` to change the speed, but since I'm making a project that will be using most of the digital pins, I wonder if I can use analog pins instead.

P.S. I know I can use analog pins as digital pins to free the digital PWM pins, but I'm not interested in doing that.

body:
No, you can't.  As it says in the Arduiuno [reference page][1] for analogWrite(): "The analogWrite function has nothing to do with the analog pins or the analogRead function."

You can use the "analog input pins" (A0..A5) of Arduino for analog input, or as digital inputs or outputs.  They cannot be used for PWM(digital)-output.  Only digital pins, and only those specifically stated for PWM-output, can actually be used for PWM output (unless you go down the path of software-PWM, though I would hesitate to do that for an H-bridge).

  [1]: https://www.arduino.cc/en/Reference/AnalogWrite


body:
You can't do it with the analogWrite function as that is reliant on physical binding beween certain pins and hardware timers inside the AVR. But you can always use [SoftPWM][1] because the the analog pins can generally be used as digital pins just as well.

  [1]: https://www.pjrc.com/teensy/td_libs_SoftPWM.html


body:
You can use multiplexers if you are running out of digital pins or SPI PWM drivers for the motors. There are many multichannel drivers out there like [TLC5940][1], put a power stage after them and you're done.

*Use Soft SPI on the analog pins to control the driver.

  [1]: http://www.ti.com/lit/ds/symlink/tlc5940.pdf


message:
Testing tri-state pin - erroneous results with internal pullup

I'm using an MPC73831 - a LiPo charging IC - in my Arduino project. It has a `status` pin to allow interface to a microcontroller, which uses a tri-state operation to convey three possible states of charging. I don't have the IC and battery yet, but I wanted to write a quick program to test a generic tri-state pin for HI, LO, and HiZ while I'm waiting for it to arrive.

The algorithm I wrote is very simple:

    Set pinTest to input, no pullup.
    Is pinTest high?
        Yes - pinTriState is HIGH, done.
    Set pinTest to input with pullup.
    Is pinTest high?
        Yes - pinTriState is HiZ, internal pullup causes high reading.
        No - pinTriState is LOW, 'cancelling out' internal pullup.

However, I'm not getting the expected results when using the internal pullup resistor - my board is showing correct analysis for HI and LO, but HiZ returns a mixture of HiZ and HIGH. I have tried this on an Uno, a Pro-Micro (32u4) and Uno->Micro and Micro->Uno. All give the same spurious results. I am baffled, therefore some advice would be appreciated. The full code is as below. I have left in code which randomises the time `pinTriState` stays at in a given state to keep `pinTest` guessing, but it's ultimately only an elaborate way of cycling through the three states.

    #define pinTest 2
    #define pinTriState 3

    int state = 0;
    char stateCh = '?';

    int sect1;
    int sect2;
    int sectMax;

    void setup()
    {
        Serial.begin(9600);
        randomSeed(analogRead(A0));
        sect1 = random(1, 20);
        sect2 = random(sect1 + 1, random(sect1 + 2, sect1 + 20));
        sectMax = random(sect2 + 1, random(sect2 + 2, sect2 + 20));
    }

    void loop()
    {
        // PART (1) Code to toggle three states of a tri-state pin
        if (state == 0)
        {
            pinMode(pinTriState, OUTPUT);
            digitalWrite(pinTriState, HIGH);
            stateCh = 'H';
        }
        if (state == sect1)
        {
            pinMode(pinTriState, OUTPUT);
            digitalWrite(pinTriState, LOW);
            stateCh = 'L'
        }
        if (state == sect2)
        {
            pinMode(pinTriState, INPUT);
            stateCh = 'Z';
        }

        // PART (2) Code to determine state of tri-state pin
        Serial.print(stateCh);     // Shows what it *should* be
        pinMode(pinTest, INPUT);
        if (digitalRead(pinTest))
            Serial.println(" - HIGH");
        else
        {
            pinMode(pinTest, INPUT_PULLUP);
            if (digitalRead(pinTest))
                Serial.println(" - HiZ");
            else
                Serial.println(" - LOW");
        }

        (state == sectMax ? state = 0 : state++);
    }

The necessary pins are connected with a single wire. If I upload the code to two boards I remove *PART (2)* on the 'triState' board and *PART (1)* on the 'testing' board. In this case, `stateCh` has no function.

For a single-board setup, I get the following output:

    H - HIGH
    H - HIGH
    ...
    L - LOW
    L - LOW
    ...
    Z - HiZ        <-- the first Z is correct 95% of the time
    Z - HIGH
    Z - HIGH       <-- the remaining Zs are a mixture, biased heavily towards HIGH.
    Z - HiZ
    ...
    H - HIGH       <-- H always gives HIGH
    ...

It makes no difference if I change the operating order of `pinState`. I've thrown in `delay(100);` between almost every other line, again to no avail.

I tried with a 22k, a 33k, and a 47k *external* pullup resistor. The results are perfect. However, this requires an extra Arduino pin to make sure that the pullup is only active when necessary. *Part (2)* becomes:

    // PART (2) Code to determine state of tri-state pin
    Serial.print(stateCh);     // Shows what it *should* be
    pinMode(pinTest, INPUT);
    pinMode(pinPullup, INPUT);    // connected to pinTest via resistor
    if (digitalRead(pinTest))
        Serial.println(" - HIGH");
    else
    {
        //pinMode(pinTest, INPUT_PULLUP);   <-- not anymore
        pinMode(pinPullup, OUTPUT);
        digitalWrite(pinPullup, HIGH);    // pulls pinTest to Vdd
        if (digitalRead(pinTest))
            Serial.println(" - HiZ");
        else
            Serial.println(" - LOW");
    }

Using the extra pin to provide the pullup is a real pain in the ar...duino. I'm cripplingly short of spare pins and I don't see why this is not resolvable with internal pullups. Help?!

body:
The internal pull-up is around 50k. So, install an external pull-**down** (to ground) of a somewhat higher value, like 1M.

Now:

Go to input mode, no pull-up. Get a reading. Turn on the internal pull-up. This should overpower the pull-down. If the reading **changes**, it was tri-state. Otherwise, if the reading doesn't change the external device is overpowering both pull-up and pull-down and you have the actual reading.

You may need a slight delay to allow the low-value pull-down to change the pin state.

---

Amended code to demonstrate:

 <!-- language-all: lang-C++ -->

    // PART (2) Code to determine state of tri-state pin
    Serial.print(stateCh);     // Shows what it *should* be

    pinMode(pinTest, INPUT);
    delayMicroseconds (100);
    byte firstReading = digitalRead(pinTest);
    pinMode(pinTest, INPUT_PULLUP);
    delayMicroseconds (10);
    byte secondReading =  digitalRead(pinTest);

    if (firstReading != secondReading)
      Serial.println(" - HiZ");
    else if (secondReading == HIGH)
      Serial.println(" - HIGH");
    else
      Serial.println(" - LOW");

(Only showing the part that detects the pin state, the rest is the same).

Output:

 <!-- language-all: lang-none -->

    H - HIGH
    L - LOW
    Z - HiZ
    Z - HiZ
    Z - HiZ
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    L - LOW
    Z - HiZ
    Z - HiZ
    Z - HiZ
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    L - LOW
    Z - HiZ
    Z - HiZ
    Z - HiZ
    H - HIGH
    H - HIGH
    H - HIGH

As you can see, working perfectly. I needed a longer delay after turning the internal pullup **off** because the fall time was around 100 µs. This actually sounds reasonable, because the 1 megohm resistor will take time to discharge the capacitance on the pin.

So:

* 10 µs delay after turning the internal pull-up **on**

* 100 µs delay after turning the internal pull-up **off**

---

**Theory for the delays**

The Atmega328 pin is specified as having a maximum capacitance of 10 pF (10e-12). It is considered charged/discharged after 5 time-constants, where `T = R.C`.

Thus for an internal pull-up resistance of 50k and a capacitance of 10 pF, charging should take:

    50e3 * 10e-12 * 5 = 2.5e-006 (0.0000025) -> 2.5 µs

And to discharge through 1M (1e6) ohms, discharging should take:

    1e6 * 10e-12 * 5 = 5e-005 (0.00005) -> 50 µs

My observed results were about 2.5 µS for the charge, but more like 100 µs for the discharge, however I probably had considerable stray capacitance in the wires used in the test circuit.


body:
Another option is to use an analog input pin instead of a digital input pin.

Create a balanced voltage divider using equal high value resistors (say 100KΩ each).  Attach the mid-point to the ADC pin, and one end to each of Vcc and GND.  The incoming status signal goes to the ADC pin:

![enter image description here][1]

Perform an analogRead() on the pin.  You will get one of 3 results:

* Close to 0 = LOW
* Close to 1024 = HIGH
* Close to 512 = HiZ

When the pin is in HiZ the resistors will hold the voltage at around 50% of Vcc.  When the pin goes HIGH it will pull the pin up and override the resistors, giving a high value reading.  Similarly, when the pin goes low, the resistors will be overridden and a low value reading will be given.

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


body: For the 1M pulldown solution, turning off the internal pullup at the end of the pin check routine MIGHT give enough time for the pin to discharge, and it might not if the code can conditionally do very little else between pin checks.  If you want to leave out the 100 us delay, take care to ensure that your code will always do something that takes sufficient cycles for the pin to discharge between checks.


body:
Nick Gammon's answer seems the most straightforward solution to your
problem, given that you cannot spare an analog input. It has however the
drawback of needing a delay of ≈ 100 µs. This may not be an
issue, but I just figured out a scheme that allows a faster read, and
may be of interest to some: instead of pull-ups or pull-downs, put just
a 10 kΩ resistor _in series_ between the MPC73831's output and you
Arduino input. When you want to read the state:

1. Take a first reading with the pin in INPUT mode:
* if you read HIGH, then your MPC is either HIGH or HI\_Z
* if you read LOW, then it's either LOW or HI\_Z
2. Now, switch the pin to OUTPUT, write the _opposite_ of what you just
   read, switch back to input and take a second reading:
* if you read what you just wrote, then your MPC is in the HI\_Z state
* if you read the same as before, then it's either HIGH or LOW.

Here is the implementation of this scheme:

    #define HI_Z 2

    /*
     * Read a 3-state pin.
     * Put a 10 kOhm resistor between the output and input pins.
     */
    int read3state(int pin)
    {
        int reading1 = digitalRead(pin);
        pinMode(pin, OUTPUT);
        digitalWrite(pin, !reading1);
        pinMode(pin, INPUT);
        int reading2 = digitalRead(pin);
        if (reading1 == reading2)
            return reading1;
        else
            return HI_Z;
    }

I have tested this a few 104 times with an Arduino sending to
itself a pseudo-random sequence of LOW, HIGH and HI\_Z. It works
reliably for me.

**Caveat**: This scheme relies on the pin being capacitively coupled to
GND or Vcc, and this coupling being stronger than couplings with other
signals in your circuit. If you fear this might not be the case, you can
put something like 100 pF from the pin to ground, but then you
should better wait a couple of microseconds before taking the second
reading.