body:
I am having a strange issue where if I try and create a TCP connection to my service, it doesn't work. But any other website, such as google, works fine. The serial monitor output is also slightly different, but I cannot see any difference in the code. I am using [this][1] module for communications.

This is the method that I am using:

    void SendPost()
    {
      Serial1.println("AT+CGATT?");
      delay(1000);
      ShowSerialData();

      Serial1.println("AT+CSTT=\"everywhere\"");//start task and setting the APN,
      delay(1000);
      ShowSerialData();

      Serial1.println("AT+CIICR");//bring up wireless connection
      delay(3000);
      ShowSerialData();

      Serial1.println("AT+CIFSR");//get local IP adress
      delay(2000);
      ShowSerialData();

      Serial1.println("AT+CIPSPRT=0");
      delay(3000);
      ShowSerialData();

      Serial1.println("AT+CIPSTART=\"tcp\",\"www.google.com/\",\"80\"");//start up the connection //https://rocky-garden-56471.herokuapp.com/breadcrum/lifecycle/register
      delay(5000);
      ShowSerialData();

      Serial1.println("AT+CIPSEND");//begin send data to remote server
      delay(4000);
      ShowSerialData();

      Serial1.println("{\"device_info\":\"breadcrum-prototype-a\"}");
      delay(500);
      ShowSerialData();

      Serial1.println((char)26);//sending
      delay(5000);//waitting for reply, important! the time is base on the condition of internet

      Serial1.println();
      ShowSerialData();

      Serial1.println("AT+CIPCLOSE");//close the connection
      delay(100);
      ShowSerialData();
    }

Using 'www.google.com' I get an OK upon tcp connection (with an expected error on the data as I try to POST):

    Setup CompleteAT+CGATT?

    +CGATT: 1

    OK
    AT+CSTT="everywhere"

    OK
    AT+CIICR

    OK
    AT+CIFSR

    100.66.4.95
    AT+CIPSPRT=0

    OK
    AT+CIPSTART="tcp","www.google.com/","80"

    OK

    STATE: IP STAAT+CIPSEND

    ERROR
    {"device_info":"breadcrum-prototype-a"}

    AT+CIPCLOSE

    ERROR

But using the address I actually want to post data to (https://rocky-garden-56471.herokuapp.com/breadcrum/lifecycle/register), it cannot connect and I get this:

    Setup CompleteAT+CGATT?

    +CGATT: 1

    OK
    AT+CSTT="everywhere"

    OK
    AT+CIICR

    OK
    AT+CIFSR

    100.66.4.95
    AT+CIPSPRT=0

    OK
    AT+CIPSTART="tcp","https://rocky-garden-56471.herokuapp.com/breAT+CIPSEND

    ERROR
    {"device_info":"breadcrum-prototype-a"}

    AT+CIPCLOSE

    ERROR

This errors on connection, and you can also see that the full address isn't printed out for some reason. Does anyone have any idea what could be causing this issue?

Thanks :)

EDIT:
@Majenko, my previous version did what I believe you are describing. The issue being I got an error that I struggled to resolve so attempted this version. The previous version is:

    void SubmitHttpRequest()
    {
      Serial1.println("AT+CSQ");
      delay(100);
      ShowSerialData();

      Serial1.println("AT+CGATT?");
      delay(100);
      ShowSerialData();

      Serial1.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR, the connection type is using gprs
      delay(1000);
      ShowSerialData();

      Serial1.println("AT+SAPBR=3,1,\"APN\",\"everywhere\"");//setting the APN, the second need you fill in your local apn server
      delay(4000);
      ShowSerialData();

     //Enable GPRS
      Serial1.println("AT+SAPBR=1,1");
      delay(2000);
      ShowSerialData();

      //Query if connection is setup correctly, return IP address if it is
      Serial1.println("AT+SAPBR=2,1");
      delay(2000);
      ShowSerialData();

      Serial1.println("AT+HTTPINIT"); //init the HTTP request
      delay(2000);
      ShowSerialData();

    //Set up bearer profile identifier (NEW PART)
      Serial1.println("AT+HTTPPARA=\"CID\",1");
      delay(2000);
      ShowSerialData();

      Serial1.println("AT+HTTPPARA=\"URL\",\"https://rocky-garden-56471.herokuapp.com/breadcrum/lifecycle/register\"");// setting the httppara, the second parameter is the website you want to access
      delay(3000);
      ShowSerialData();

      Serial1.println("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
      delay(3000);
      ShowSerialData();

      Serial1.println("AT+HTTPDATA=1000,10000");
      delay(3000);
      ShowSerialData();

      Serial1.println("{\"device_info\":\"breadcrum-prototype-a\"}");
      delay(3000);
      ShowSerialData();

      Serial1.println("AT+HTTPACTION=1");//submit the request //0:READ 1:POST 2:HEAD
      delay(10000);//the delay is very important, the delay time is base on the return from the website, if the return datas are very large, the time required longer.
      ShowSerialData();

      Serial1.println("AT+HTTPREAD");// read the data from the website you access
      delay(1000);
      ShowSerialData();

      Serial1.println("");
      delay(100);
    }

But the results I got from this was another error when attempting to post:

    Setup CompleteAT+CSQ

    +CSQ: 18,0

    OK
    AT+CGATT?

    +CGATT: 1

    OK
    AT+SAPBR=3,1,"CONTYPE","GPRS"

    OK
    AT+SAPBR=3,1,"APN","everywhere"

    OK
    AT+SAPBR=1,1

    OK
    AT+SAPBR=2,1

    +SAPBR: 1,1,"19.177.18.205"

    OK
    AT+HTTPINIT

    OK
    AT+HTTPPARA="CID",1

    OK
    AT+HTTPPARA="URL","https://rocky-garden-56471.herokuapp.com/breAT+HTTPPARA="CONTENT","application/json"

    OK
    AT+HTTPDATA=1000,10000

    DOWNLOAD

    ERROR
    AT+HTTPREAD

    OK

EDIT 2:
Following HTTPS commands:

     AT+CSQ

    +CSQ: 18,0

    OK
    AT+CGATT?

    +CGATT: 1

    OK
    AT+SAPBR=3,1,"CONTYPE","GPRS"

    OK
    AT+SAPBR=3,1,"APN","everywhere"

    OK
    AT+SAPBR=1,1

    ERROR
    AT+SAPBR=2,1

    +SAPBR: 1,1,"31.94.203.234"

    OK
    AT+HTTPSSL=1

    OK
    AT+HTTPINIT

    OK
    AT+HTTPPARA="CID",1

    OK
    AT+HTTPPARA="URL","https://rocky-garden-56471.herokuapp.com/breAT+HTTPPARA="CONTENT","application/json"

    OK
    AT+HTTPDATA=100,10000

    DOWNLOAD

    ERROR
    AT+HTTPREAD

    OK
    AT+HTTPTERM

    OK

  [1]: http://linksprite.com/wiki/index.php5?title=SIM900_GPRS/GSM_Shield

title: SIM900 TCP Connection issue

Answers: 1

body:
There is so many things wrong that I don't know where to start.

1. You are trying to use a URL in place of a hostname.
2. You are trying to connect to an HTTPS service which runs on port 443 not on port 80
3. HTTPS is encrypted. You are opening a plain TCP socket to an encrypted service.

Your whole methodology is wrong. You need to use the [SIM900 HTTPS AT Command Set](http://simcom.ee/documents/SIM900/SIM900_HTTPS AT Command Set_V1 00.pdf) to get the SIM900 to perform an HTTPS request on your behalf rather than opening a socket and sending / receiving data.


body:
I'm trying to create a program for my robot, but something is not right.
Here's the code:

    #include <SPI.h>
    #include <Tone.h>
    #include <Wire.h>   // standardowa biblioteka Arduino
    #include <LiquidCrystal_I2C.h> // dolaczenie pobranej biblioteki I2C dla LCD

    //Enums:
    enum Dir
    {
      forward = 1,
      backward = 2,
      left = 3,
      right = 4
    };

    enum State
    {
        movingForward = 1,
        movingBack = 2,
        turningLeft = 3,
        turningRight = 4,
        doingNothing = 5,
        readyToMove = 6 //Potrzebne?
    };

    enum SpeedState
    {
      slowingDown = 1,
      maxSpeed = 2,
      accelerating = 3,
      notMoving = 4
    };

    //Classes:
    LiquidCrystal_I2C lcd1(0x27, 20, 4);

    //Base class for devices
    class Device
    {
        public:
            virtual void Init() = 0;
    };

    //STEPPER::
    class StepMotor: public Device
    {
        public:
            int motorPin;
            int dirPin;
            int sleepPin;

            void Init ( void )
            {
                pinMode(motorPin, OUTPUT);
                pinMode(dirPin, OUTPUT);
                pinMode(sleepPin, OUTPUT);

                toneObject.begin(motorPin);
            }

            void SetSpeed ( int speed )
            {
              toneObject.play(speed);
            }

        private:
          Tone toneObject;
    };

    //VARIABLES:
    int a = 1; //przyspieszenie (przyrost prędkości i jej ubytek przy hamowaniu
    int s_accelerating = 1; //droga przyspieszania [mm]
    int s_braking = 1;  //droga hamowania [mm]

    class Robot
    {
        public:
            static float x;
            static float y;
            static float t;
            static State state;
            static SpeedState speedState;
            static int currentSpeed;
    };

    class MoveOrder
    {
      public:
        static Dir direction;
        static int distance;
        static int speed;
        static int distanceRemaining;
        static int distanceMade;
    };

    //FUNCTIONS:
    void SetInterrupt ( void )
    {
        noInterrupts();           // disable all interrupts
        TCCR5A = 0;
        TCCR5B = 0;
        TCNT5  = 0;
        OCR5A = 310;            // compare match register 16MHz/256/2Hz   400 okolo 6.4ms  380-6.1ms 300-4.9ms
        TCCR5B |= (1 << WGM12);   // CTC mode
        TCCR5B |= (1 << CS12);    // 256 prescaler
        TIMSK5 |= (1 << OCIE1A);  // enable timer compare interrupt
        interrupts();             // enable all interrupts
    }

    void SetSpeed ( int speedValue )
    {
       //currently empty
    }

    void setup()
    {
        SetInterrupt();
    }

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

    }

    ISR(TIMER5_COMPA_vect)
    {
        if (Robot::state != doingNothing)
        {
            if (Robot::state == movingForward || Robot::state == movingBack )
            {
              if (MoveOrder::distanceMade < s_accelerating)
                {

                    Robot::currentSpeed += a;

                    SetSpeed(4);

                }
            }
        }
    }

Compilation returns this:

    Arduino:1.6.10 (Windows 10), Płytka:"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

    C:\Users\Marcin\AppData\Local\Temp\ccU9OfJk.ltrans0.ltrans.o: In function `__vector_21':

    ccU9OfJk.ltrans0.o:(.text+0x812): undefined reference to `Robot::state'

    ccU9OfJk.ltrans0.o:(.text+0x816): undefined reference to `Robot::state'

    C:\Users\Marcin\AppData\Local\Temp\ccU9OfJk.ltrans0.ltrans.o: In function `__vector_47':

    ccU9OfJk.ltrans0.o:(.text+0x820): undefined reference to `MoveOrder::distanceMade'

    ccU9OfJk.ltrans0.o:(.text+0x824): undefined reference to `MoveOrder::distanceMade'

    ccU9OfJk.ltrans0.o:(.text+0x82e): undefined reference to `Robot::currentSpeed'

    ccU9OfJk.ltrans0.o:(.text+0x832): undefined reference to `Robot::currentSpeed'

    ccU9OfJk.ltrans0.o:(.text+0x838): undefined reference to `Robot::currentSpeed'

    ccU9OfJk.ltrans0.o:(.text+0x83c): undefined reference to `Robot::currentSpeed'

    collect2.exe: error: ld returned 1 exit status

    exit status 1

I noticed that when I comment these lines:

            Robot::currentSpeed += a;

            SetSpeed(4);

errors are gone. Why?

title: A lot of "undefined reference" errors

Answers: 1

body:
Because you have only *declared* the class static variables; you never *defined* them.  For the `Robot` class, you must have:

    class Robot
    {
        public:
             ...
    };

    float      Robot::x;
    float      Robot::y;
    float      Robot::t;
    State      Robot::state = doingNothing;
    SpeedState Robot::speedState = notMoving;
    int        Robot::currentSpeed;

    void setup()
    {

Ditto for other classes.  (Dangit, Mikael!  :) )


body:
Hey I'm very new to Arduino. I don't have very much knowledge in electrical engineering either.

My project: an EL wire working on Arduino. Since the Arduino can only support 5V and the wire needs 120V, how can I make sure that it works? (I assume the voltage provided by the Arduino is not high enough for the EL wire to operate.)

title: How to increase voltage of Arduino?

Answers: 2

body: In this case, you can use relays. You can give your supply voltage (120v as you said) to EL via relays. And you can switch ON and switch OFF your EL by controlling relays with Arduino.

body:
There are two ways of tackling this.  You can either switch the low-voltage DC power to the EL wire inverter (which is safe and easy) or you can switch the high voltage AC power out of the inverter (which is harder, more dangerous, but does allow you to route the power to different EL wires for animation).

The former can be arranged in just the same way as switching any heavy load from an Arduino - with an N-channel MOSFET as a low-sided switch, or a combination of N- and P-channel MOSFETs as a high-side switch. You could add further isolation with a relay should you wish. BJTs could be used instead of MOSFETs but MOSFETs are better at switching higher currents from low current sources.

For switching the high-voltage side you will need a TRIAC circuit. While it is possible to switch a TRIAC direct from the Arduino it is preferred to opt-isolate the system from the Arduino both for safety and ease of switching at higher voltages.

The most common opto-isolator to use is the MOC3041 Opto-Isolated Triac. This is used to switch the gate of a higher voltage / power TRIAC to switch the load.

[![enter image description here][1]][1]

In that circuit the "220V" comes from the EL inverter, and the LOAD is the EL wire itself. Each EL wire you want to switch would use a copy of that circuit, but can (power permitting) use the same inverter as the source.

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


body:
In my project Arduino provides value range between 0-1024. I need to convert this serial value to a standard µSiemens value to measure emotional stress.

Can anybody point me to an answer that would give an appropriate equation for the conversion?

title: How to convert Arduino GSR values to microsiemens?

Answers: 1

body:
A Siemens (aka a Mho) is a unit of conductance, the inverse of resistance.

You have a measure of the voltage (A/D value) between the pads so you can find voltage. You'll also need to know the current between the pads.
Convert your A/D reading into voltage and use that and the current to find resistance (using Ohm's law), and the reciprocal of the resistance is in Siemens. 1 Siemens == 1,000,000 uSiemens.

[https://en.wikipedia.org/wiki/Siemens_(unit)][1]

  [1]: https://en.wikipedia.org/wiki/Siemens_(unit)


body:
I am brand new to the arduino board and I am trying to build a simple IR proximity sensor. I bought a handful of emitters and detectors from amazon here:

https://www.amazon.com/gp/product/B01HGIQ8NG/ref=oh_aui_detailpage_o02_s00?ie=UTF8&psc=1

I am about to pull my hair out and shoot my board with a 12 gauge shot gun if I don't figure this out soon. Can someone point me to a good SIMPLE tutorial that uses ONE emitter and ONE detector and ONE LED. All i can find are a bunch of complex circuits with multiple sets of sensors or a buzzer or whatever else and anything that is as simple as that has no information on schematic or code. Can someone please post a tutorial link?

title: build simple IR sensor with 220 ohm and 1000 ohm resistors

Answers: 1

body:
You could always start out attempting a simple IR detector circuit.

Google Arduino IR detector brings up several tutorials, such as [this one from the Instructables website][1]

You would have to change the buzzer in tutorial for an LED and resistor in series.

  [1]: http://www.instructables.com/id/ARDUINO-Burglar-Alarm-Using-Infrared-Emitter-Detec/?ALLSTEPS


body:
Have an AES-128 implementation I'd like to install on an ATTiny85 for embedded use but need to come up with a way to **communicate with it from a PC** as you would do via Serial on Arduino Uno. For example, I'd like to stream 16 bytes of plaintext and get back 16 bytes of ciphertext (or signature hash, etc.).

The faster the transfer rate, the better obviously, but it would of course need to fit on the remaining space on an ATTiny85.

Any thoughts or working examples out there (i.e. I2C for PC, etc.) without incurring a lot of extra hardware cost?

title: Serializing data created by ATTiny85 for use on PC

Answers: 3

body:
So thanks to Ignacio Vazquez-Abrams' tip, it looks like I'll be able to accomplish this with [V-USB](https://www.obdev.at/products/vusb/index.html):

> V-USB is a software-only implementation of a low-speed USB device for
> Atmel’s AVR® microcontrollers, making it possible to build USB
> hardware with almost any AVR® microcontroller, not requiring any
> additional chip.

**Requirements:** AVR microcontroller with at least 2 kB of Flash memory, 128 bytes RAM and a clock rate of at least 12 MHz.

Taken from [ATTiny85's Datasheet](http://www.atmel.com/images/atmel-2586-avr-8-bit-microcontroller-attiny25-attiny45-attiny85_datasheet.pdf):

> - 8K Bytes of In-System Programmable Program Memory Flash
> - 512 Bytes In-System Programmable EEPROM (enough for third-two 16-byte keys)
> - 512 Bytes Internal SRAM

Looking forward to trying it out :)

body:
> Any thoughts or working examples out there (i.e. I2C for PC, etc.) without incurring a lot of extra hardware cost?

Yet another alternative is to use the Display Data Channel (DDC) on the PC. This is 5V and I2C. Unfortunately not all PC video boards support I2C. Please see the [reference][1] for further details.

I2C is supported on ATtiny by the USI module.

Cheers!

  [1]: http://www.instructables.com/id/Worlds-Cheapest-I2C-I-Squared-C-Adapter/?ALLSTEPS

body:
> need to come up with a way to communicate with it from a PC

would be difficult to make an uart out of usi?


body:
I have an ESP8266-01. I followed the instructions on this

http://yaab-arduino.blogspot.com/2015/12/flashing-esp8266-firmware-arduino.html?m=1

 exactly. When I start the firmware update the TX and RX pins blink rapidly along with the blue light on the ESP.

Then the terminal spits out "chip sync error" and disconnects.

I would like this to work because buying a ftdi cable isn't an option right now.

title: Esp8266 firmware update with uno "chip sync error"

Answers: 2

body: I run the same problem too and took me countless hours to figure this error out. The problem seems the Baud rate starts at 115200 while the COM port is set to 9600. What I did is I checked the Device Manager and find the COM port, right clicked to properties and to the Port Settings Tab, I changed the Baud Rate to 115200 and flash the firmware again. And it works!

body: just after compilaion starts in the arduino ide , press and hold the flash button and then press the reset button , now release the reset button and finally release the flash button, this is how the esp goes into flash mode.this will work


body: I am making a project with several modules and libraries involved. I just tested the SD lib example, and got a binary at ~14KB  - way too much. I'd like the SD bits to go below 8KB, since it's just for logging from an NFC and RTC module. I notice some 'stabs' debug bits in my Makefile, and wonder if I could do something with that. Besides that, perhaps the experts here can recommend a smaller library for my SD bits, so I won't exceed my ~27KB flash capacity. I am using the SD example for creating/deleting files. Ask me to clarify if needed.

title: most effective ( progsize/speed ) SD card usage

Answers: 1

body:
For AVR + SDCard you should check [FatFs][1] from Chang. It is widely used and proven C library. You can [tweak the configuration][2] file to get minimal size (8K shall be easy). Check wrapper library for Arduino [here][3] (6K with default options).

There is also even smaller version called [Petit FAT][4] (2-4K) but it doesn't support file delete feature.

  [1]: http://elm-chan.org/fsw/ff/00index_e.html
  [2]: http://elm-chan.org/fsw/ff/en/config.html
  [3]: https://github.com/greiman/PetitFS
  [4]: http://elm-chan.org/fsw/ff/00index_p.html

If you would like to get smallest possible code, there is option to use Atmel Studio for programming Arduino boards, but you will loose the convenience of Arduino libraries (re-implement the libraries or find AVR versions of them, work with registers directly etc).


body:
I'm working on a code based on [PaletteCrossfade.ino][1] example. But I found the motion speed too fast. It's stated in this:

      static uint8_t startIndex = 0;
      startIndex = startIndex + 1; /* motion speed */
      FillLEDsFromPaletteColors(startIndex);
      FastLED.show();
      FastLED.delay(1000 / UPDATES_PER_SECOND);
    }

    void FillLEDsFromPaletteColors( uint8_t colorIndex) {
      uint8_t brightness = 255;
      for( int i = 0; i < NUM_LEDS; i++) {
        leds[i] = ColorFromPalette( currentPalette, colorIndex + sin8(i*16), brightness);
    colorIndex += 3;

Since the startIndex defined in `uint8_t`, it cant be lower than 1. So I used float and set it to 0.2 in my code. Which seems to work, and animation slowed down. However I'm not sure how is that float value added into the `ColorFromPalette` function.

[Its documentations states][2]:
> CRGB  ColorFromPalette (const CRGBPalette16 &pal, uint8_t index,
> uint8_t brightness=255, TBlendType blendType=LINEARBLEND)

To my understanding it accepts only integer, and also int based sin8 being added to float value. So, what exactly happens there? Is this method viable, or is there any better way to slow down the animation?

I'm thinking about adding a millis() based delay and only increasing the colorindex every 2-3 seconds or so.

  [1]: https://gist.github.com/kriegsman/1f7ccbbfa492a73c015e
  [2]: http://fastled.io/docs/3.1/group___colorutils.html

title: FastLED int + float problem

Answers: 2

body:
The code you have seems to fill the lights with a colour and change every nth of a second.  You could control that to change every 1ms to 2^16ms (which is 65 seconds) just by changing the FastLED.delay() value.

sin8() might return a float or I suspect an int, but colourIndex is an uint8_t so that is a whole number.  All it is doing is picking a colour, based on some scheme.  If the value passed to the function is a float i.e. 1.611 then it will be converted to an int by taking just the whole number part, in this case 1.  It does not round up.

Its not clear what you are trying to do.

If you are trying to slow the rate that the LEDs change colour, you need to change the delay statement.

If you want to smooth the transition between colours you need to change in the area of the sin8 statement, but what you change it to will depend on what your palette is loaded with.

Hope that helps, if not please can you try and describe what it is you are tying to achieve.

body:
In order to change the update rate you have to change it.

You have two choices in ColourPalette example:

1st:
# LINE 10

    #define UPDATES_PER_SECOND 100 // higher number means more frames a second
2nd:

# LINE 58

    FastLED.delay(1000 / UPDATES_PER_SECOND); // change it to:
    FastLED.delay(2000); //2000ms means 0.5 frame per second or 1 frame every two seconds


body:
i'm trying to find out the capacitance value using the time constant of the RC ciruit. so i followed the technique on the below link.

http://www.gammon.com.au/forum/?id=12075

Now, it's working fine.. but still i need wider range so i want to know the full core logic of that program like how the capacitance formula has been derived out in those program?

thanks in advance...

title: how to find find out capacitance using time constant?

Answers: 1

body:
The key concept is this line:

> ... we find the point where the voltage reaches 63.2% ...

The time constant τ is how long it takes for a capacitor to charge up to 63.2% of the supply voltage. That is governed by both the capacitance (C) and the resistance (R). τ=RC. That is one of the basic formulae you should know as an Electronic Engineer.

If you know R (which you do because you chose it at 10KΩ) and you know τ (which you do because you measured it) then you can calculate C (τ/R).

Since τ, C and R are tied together like that it is possible to change the balance of C and R and keep τ the same. For instance, a 10KΩ resistor and a 47nF capacitor would give the same τ as a 1KΩ resistor and a 470nF capacitor. Also the same τ as a 100kΩ resistor and a 4.7nF capacitor.

You can easily change the range without having to change your time measurement system by changing the resistor to give a different scale.


body:
I'm using a modified version of Arduino Zero Bootloader. I am trying to write software to automatically detect which USB device the bootloader is currently running on in order to execute bossac.

I have noticed a few unique characteristics when using "lsusb -v". Things like "bDeviceClass" is always 2. and "bDeviceSubClass" is always 0; However, I do not feel confident in using these traits to identify the bootloader. Is there any clear indication of bootloader so I can find the correct ttyACM#?

title: Identifying Bootloader ttyACM# device

Answers: 1

body:
The only things you have at your disposal are what is in `lsusb -v`. Using those you can craft a `udev` rule to create a symlink to a unique device name. I do that with all my boards so that they all get a unique name.

Here is one of my rules:

    ATTRS{idVendor}=="2341", ATTRS{idProduct}=="0042",
      ATTRS{serial}=="95336333635351F091B1", KERNEL=="ttyACM*",
      MODE="0660", GROUP="plugdev", SYMLINK+="board/arduino/mega2560"

That links `/dev/board/arduino/mega2560` to whatever `/dev/ttyACM*` node got created when it was plugged in.  That is in `/etc/udev/rules.d/50-boards.rules`

More on udev here: http://playground.arduino.cc/Linux/Udev

A useful command is `udevadm info -a -n /dev/ttyACM0` which lists all the attributes for that device which you can then use in the `udev` rule.


body:
I hope I can get some help on how getting this to work.

I have multiple Sensors (32 of these) I want to read their values. I am using a master multiplexer HC4051 connected to 4 slave multiplexers, this is my wirings:

[![enter image description here][1]][1]

I have  tested it using one single multiplexer and it workes as intended, but when adding the slaves, I cannot getting it to work, I am not sure how to code it.

When using this code :

    // 74XX4051 ADDRESS PINS :
    #define  M_S0 2
    #define  M_S1 3
    #define  M_S2 4

    #define  S_S0 7
    #define  S_S1 6
    #define  S_S2 5

    // 74XX4051 ANALOG PIN :
    #define  Z 0

    void setup(){

            // CONFIGURE ADDRESS PINS
            pinMode(M_S0, OUTPUT);
            pinMode(M_S1, OUTPUT);
            pinMode(M_S2, OUTPUT);

            pinMode(S_S0, OUTPUT);
            pinMode(S_S1, OUTPUT);
            pinMode(S_S2, OUTPUT);

            // CONFIGURE SERIAL
            Serial.begin(57600);
    }

    void loop () {

    int value;

            // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER
            for ( byte count = 0; count < 8 ; count++ ) {

                    // SET THE ADDRESS
                    digitalWrite(M_S0, bitRead(count, 0) );
                    digitalWrite(M_S1, bitRead(count, 1) );
                    digitalWrite(M_S2, bitRead(count, 2) );  // => 000 - Y1-Z

                    // LOOP THROUGH ALL THE ADDRESSES OF THE SLAVES
                    for ( byte count_1 = 0; count_1 < 32 ; count_1++ ) {

                        digitalWrite(S_S0, bitRead(count_1, 0) );   // => 000,000,000,000 => Z1, Z2, Z3, Z4
                        digitalWrite(S_S1, bitRead(count_1, 1) );
                        digitalWrite(S_S2, bitRead(count_1, 2) );

                        // READ THE ANALOG VALUE
                        value = (bitRead(count_1, 2),bitRead(count_1, 1),bitRead(count_1, 0));

                    }

                    // READ THE ANALOG FOR THE MASTER ADRESSE
                    value = analogRead(Z);

                    // SERIAL OUTPUT
                    // print : ### value
                    Serial.print(bitRead(count, 2));
                    Serial.print(bitRead(count, 1));
                    Serial.print(bitRead(count, 0));
                    Serial.print(' ');
                    Serial.println(value);

                    delay(100);
            }

    }

I am only getting random readings really (The reading LED for the moisture sensor does not switches on when the reading is done)
What I am doing wrong ?

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

**update:**

Thanks for the answer, I still cant get it work.

I updated my code as suggested :

    // 74XX4051 ADDRESS PINS :
    #define  M_S0 7
    #define  M_S1 6
    #define  M_S2 5

    #define  S_S0 2
    #define  S_S1 3
    #define  S_S2 4

    // 74XX4051 ANALOG PIN :
    #define  Z 0

    void setup(){

            // CONFIGURE ADDRESS PINS
            pinMode(M_S0, OUTPUT);
            pinMode(M_S1, OUTPUT);
            pinMode(M_S2, OUTPUT);

            pinMode(S_S0, OUTPUT);
            pinMode(S_S1, OUTPUT);
            pinMode(S_S2, OUTPUT);

            // CONFIGURE SERIAL
            Serial.begin(57600);
    }

    void loop () {

      int value;

      // LOOP THROUGH ALL THE ADDRESSES
        for ( byte count = 0; count < 32 ; count++ ) {

        digitalWrite(M_S0, HIGH); //TURN THE SENSOR ON FOR READING
        digitalWrite(M_S1, HIGH);
        digitalWrite(M_S2, HIGH);
        digitalWrite(S_S0, HIGH);
        digitalWrite(S_S1, HIGH);
        digitalWrite(S_S2, HIGH);

        // SET THE ADDRESS BITS
        digitalWrite(S_S0, bitRead(count, 0) );   // Slave A0
        digitalWrite(S_S1, bitRead(count, 1) );   // Slave A1
        digitalWrite(S_S2, bitRead(count, 2) );   // Slave A2

        digitalWrite(M_S0, bitRead(count, 3) );   // Master A0
        digitalWrite(M_S1, bitRead(count, 4) );   // Master A1
        digitalWrite(M_S2, bitRead(count, 5) );   // Master A2
        delay(50);

        // READ THE ANALOG VALUE
        value = analogRead(Z);

        digitalWrite(M_S0, LOW); //TURN THE SENSOR OFF WHEN READING IS DONE
        digitalWrite(M_S1, LOW);
        digitalWrite(M_S2, LOW);
        digitalWrite(S_S0, LOW);
        digitalWrite(S_S1, LOW);
        digitalWrite(S_S2, LOW);

        // SERIAL OUTPUT
        Serial.print(count, BIN);
        Serial.print('\t');
        Serial.println(value);
      }

      delay(3000);
    }

1- All my sensors are in the air, so i should expect a "0" reading. but i'am getting really random reading from the serial monitor every cycle ! (only 28 sensors are connected for now to the multiplexer - does it make any interference ?)

2- I added

    digitalWrite(M_S0, HIGH); ....... digitalWrite(M_S0, LOW);

to only power the sensor when taking a reading, but it doesnt work. When having my sensor into the water, the LED is lighten all the time.

title: How to code for cascading multiplexers?

Answers: 0


body:
I would like to control a pump.
The pump rating is 12 volt 60watts.
The pump mfg says to use a 12 volt power supply of 5 - 12 amps but AT LEAST 5 amps. This pump has a pressure turn off at 116 psi and the mfg states that the pump will not make maximum pressure with less than 5 amps.

So the question becomes, to be able to switch this pump on and off based on some sensor reading what would be considered best practice:
transistor, MOSFET, or relay?

title: switch pump on with transistor, mosfet, or relay

Answers: 2

body:
* Transistor - Big voltage drop between C-E @ 5A (depends on type but it will be about 2V). Power dissipitation is voltage drop times current so about 24Watts. You must be careful with inductive load - induced high voltage must be supressed. Usual way is using anti-parallel fast diode over load.

* Mosfet - Voltage drop can be really small, so it might be possible to use it without heatsink. Big Gate capacity needs strong driver to charge and discharge. If not, slow switching causes huge losses (again voltage drop times current). For inductive load it's same as for transistor.

* Relay - It must be selected carefully as switch-off causes electric arc (= burning contacts) and because of DC current it's burning for much longer time than AC.

body:
The problem with a MOSFET is that at 5A you might find that the arduino output pin can't deliver enough voltage to the gate of the MOSFET to get it to fully turn on.

For the transistor, it is possible to use a transistor however it is probably best to construct it as a high side switch as opposed to a low side switch. This is to deal with potential problems that may arise with disconnecting the ground from the pump whilst running.
[This is a good article which explains why low side switching can be bad][1]

The best possible solution in this circumstance would be to use a relay connected to a NPN transistor which switches the low side of the relay. This isolates the delicate arduino electronics from the pump.

[![enter image description here][2]][2]

  [1]: http://jeelabs.org/2012/11/11/low-side-switching/
  [2]: https://i.stack.imgur.com/xMxjg.png


body:
I am working on an autonomous robot in my summer vacations. I am currently working on running the motors of my robot in a closed loop. In order to do so, I have to interface **two Quadrature encoders** of the motors with the Arduino Due that I have. My motor encoder have **3200 Edges per Revolution**. I have read the Atmel SAM3x8E datasheet and have successfully tested one encoder in Arduino IDE. It appears that TIOA0 and TIOBO are used to read PHA and PHB of of one Encoder which correspond to Pin 2 and 13 of Arduino Due. I am not using Index pin (TIOB1).

[![enter image description here][1]][1]

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

It seems that I can only interface 1 quadrature .Is their any way I can use Quadrature decoder to read 2 encoders instead of one. As I have stated earlier I am not using the index pin. So, maybe there might be a way to decode to encoders using the three available pins as shown in the above diagram. I don't want to use Interrupts to do this job.

Here's is the link of SAM3x Manual:
http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf

Link of Motor that i am using:
www.pololu.com/product/2824

title: Reading Two Quadrature Encoder using a single Arduino Due

Answers: 1

body:
According to [Quadrature Decoder QDEC for SAM3/4 Devices_ApplicationNote_AT11483][1] and referenced excel sheet with [Device to No of QDEC channels][2] it seems to have two of them. However in DUE almost none of interesting devices are wired to headers completely (Extmem, SD interface,...)

However TIOA6 and TIOB6 should be on pins 5 and 4

Pin configuration should be something like this:

      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT);
      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT);

And TC0 is pretty much same as TC2, so just copy&paste and change TC0 to TC2

Full config:

      REG_PMC_PCER0 = PMC_PCER0_PID27 | PMC_PCER0_PID28 | PMC_PCER0_PID29;
      REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

      PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB25B_TIOA0, PIO_DEFAULT); // arduino pin 2
      PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB27B_TIOB0, PIO_DEFAULT); // arduino pin 13

      REG_TC0_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
      REG_TC0_RC2   = F_CPU / 128 / 1;
      REG_TC0_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
      REG_TC0_BMR   = TC_BMR_QDEN | TC_BMR_SPEEDEN /*| TC_BMR_EDGPHA*/;
      REG_TC0_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC0_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC0_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); // arduino pin 5
      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT); // arduino pin 4

      REG_TC2_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
      REG_TC2_RC2   = F_CPU / 128 / 10;
      REG_TC2_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
      REG_TC2_BMR   = TC_BMR_QDEN | TC_BMR_POSEN /*| TC_BMR_EDGPHA*/;
      REG_TC2_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC2_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC2_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

  [1]: http://www.atmel.com/Images/Atmel-42706-Quadrature-Decoder-QDEC-for-SAM3-4-Devices_ApplicationNote_AT11483.pdf
  [2]: http://atmel.force.com/support/servlet/fileField?id=0BEG0000000HRvP


body:
I have installed Domoticz on Raspberry Pi and bought an RfxCom 433MHz emitter/receiver.
It works well for example with Chacon DiO 54781 door sensor.
I want to create my own sensor with Arduino that would be recognized by Domoticz as a native RF 433MHz device.
In first place, I want to make a flooding sensor, I also need an On/Off information.
I would like to implement X10 protocol because it seems to be the simplest one.

title: Send RF 433MHz data to Domoticz RfxCom with protocol X10 from Arduino Nano

Answers: 1

body:
I finally found a documentation about RF X10 protocol:
[X10 RF Receiver.pdf][1]

With following Hardware :

 - Arduino Pro Mini 5V         (4€)        https://www.amazon.fr/gp/product/B00QPUEFNW/ref=oh_aui_search_detailpage?ie=UTF8&psc=1
 -   RF 433MHz emitter/receiver  (3€) (Note: only the emitter is used)       https://www.amazon.fr/HDigiWorld-metteur-cepteur-commande-Arduino/dp/B00JTQI39G/ref=sr_1_3?s=computers&ie=UTF8&qid=1470813610&sr=1-3&keywords=433
 -   3 wires : VCC, GND, Signal (on Arduino pin 2)

I've created the following working code for Arduino Nano :

    /*
    * Custom sensor (base code)
    *
    * Emission in RF 433MHz with the X10 protocol for Domoticz
    *
    * Hardware :
    * Arduino Pro Mini 5V   (4€)  https://www.amazon.fr/gp/product/B00QPUEFNW/ref=oh_aui_search_detailpage?ie=UTF8&psc=1
    * RF 433MHz emitter/receiver  (3€)  https://www.amazon.fr/HDigiWorld-metteur-cepteur-commande-Arduino/dp/B00JTQI39G/ref=sr_1_3?s=computers&ie=UTF8&qid=1470813610&sr=1-3&keywords=433
    *  Note: only the emitter is used
    * 3 wires : VCC, GND, Signal (on Arduino pin 2)
    *
    * Documentation found for RF X10: http://www.printcapture.com/files/X10_RF_Receiver.pdf
    *
    * Example of malformed data received in RfxMngr in mode "nodec" (before this code was correctly debugged) :
    *
    *  Packettype        = UNDECODED RF Message
    *  UNDECODED NEC:1C515C86F0
    *
    *
    * Correct data that is now receveived by RfxMngr with this program :
    *
    *------------------------------------------------
    *  Packettype    = Lighting1
    *  subtype       = X10
    *  Sequence nbr  = 13
    *  housecode     = D
    *  unitcode      = 1
    *  Command       = On
    *  Signal level  = 7  -64dBm
    *------------------------------------------------
    *  Packettype    = Lighting1
    *  subtype       = X10
    *  Sequence nbr  = 14
    *  housecode     = D
    *  unitcode      = 1
    *  Command       = Off
    *  Signal level  = 7  -64dBm
    *------------------------------------------------
    */

    const int pin_emit = 2;   // Signal pin for RF433 emitter
    const int pin_led = 13;   // Internal LED : it will be ON when the "On" command is sent in RF, and OFF the the "Off" command is sent (changed each 60s)

    const unsigned int X10_A1_ON = 0x00;
    const unsigned int X10_A1_OFF = 0x20;

    const unsigned int X10_address = 5;  // this is Housecode. In my case 5 results in "D" house code
    unsigned int X10_data = X10_A1_ON;  // command. I have implemented only On/Off for unit code 1

    void setup() {
      pinMode(pin_led, OUTPUT);
      pinMode(pin_emit, OUTPUT);
      digitalWrite(pin_emit, LOW);
    }

    /**
    * Bit to 0 : 1.125ms between rising edges, so before next bit
    */
    void X10_sendBit_zero()
    {
      digitalWrite(pin_emit, HIGH);
      delayMicroseconds(555);       // Arbitrary value: I took around 1.125ms divided by two for the "VCC" state.
      digitalWrite(pin_emit, LOW);
      delayMicroseconds(570);       // Total 555+570 : 1125µs = 1.125ms
    }

    /**
    * Bit à 1 : 2.25ms entre les "rising edges"
    */
    void X10_sendBit_one()
    {
      digitalWrite(pin_emit, HIGH);
      delayMicroseconds(555);       // Arbitrary value: I took around 1.125ms divided by two for the "VCC" state.
      digitalWrite(pin_emit, LOW);
      delayMicroseconds(1695);      // Total 555+1695 : 2250µs = 2.250ms
    }

    void X10_send8bits(unsigned int data)
    {
      // - Send the 8 bits, and then the complementary of the 8 bits.
      // from documentation: "Within each byte, bit7 is received first and bit0 last"
      int mask = 0x80;
      for(int i = 0; i < 8; i++)
      {
        int bit = mask & data;
        if (bit == 0)
          X10_sendBit_zero();
        else
          X10_sendBit_one();

        mask = mask >> 1;
      }
    }

    /**
    * Sending a byte consists of sending this byte, and then sending the opposite of the same byte.
    * As we send the opposite as well as the data, the total duration is always the same : 8 * (1.125ms+2.250ms) = 8 * 3.375 = total of 27ms
    */
    void X10_sendByte(unsigned int data)
    {
      X10_send8bits(data);
      X10_send8bits(~data);
    }

    /**
    * Send a complete X10 packet
    *
    * Total duration :
    * (9ms + 4.5ms) + (27ms + 27ms) + 0.555ms + 40ms = 108.055 ms
    *  from doc: "It appears, from articles on the 'net, that other people have seen a range from 95 msec to 116 msec for various transmitters and that standard X-10 transceivers can tolerate timing variations of 30-35% from nominal."
    */
    void X10_sendState_once(unsigned int data)
    {

      // - Header
      digitalWrite(pin_emit, HIGH); // "Burst" de 9ms
      delayMicroseconds(9000);
      digitalWrite(pin_emit, LOW); // Silence de 4.5ms
      delayMicroseconds(4500);

      // - Data
      X10_sendByte(0x50); // - Address
      X10_sendByte(data); // - Data

      // - Send a last rising edge to validate last bit
      digitalWrite(pin_emit, HIGH);
      delayMicroseconds(555);       // Arbitraty value (but always the same), for "VCC" state.

      // - Footer
      digitalWrite(pin_emit, LOW); // Silence de 40ms pour signifier la fin de l'émission
      delayMicroseconds(40000);

    }

    /**
    * Send a complete packet multiple times (this X10 protocol has not ACK))
    * From doc: "Most X-10 RF transmitters send a minimum of five copies of the code separated by 40 msec silences although some can send single bursts."
    *
    *  5 times 108.055ms = 540.275 ms, half a second
    */
    void X10_sendState(unsigned int data)
    {
      // - "clean" to be sure to have a zero for the first rising edge on init
      digitalWrite(pin_emit, LOW);
      delay(1);

      // - Send 5 time complete packet
      for(int repeat=0 ; repeat<5 ; repeat++)
        X10_sendState_once(data);

    }

    void loop() {

      if(X10_data == X10_A1_ON)
        digitalWrite(pin_led, HIGH);
      else
        digitalWrite(pin_led, LOW);
      X10_sendState(X10_data);
      delay(60000);              // 1 minute

      // - I change state each 60 seconds to see changes in Domoticz
      if(X10_data == X10_A1_ON)
        X10_data = X10_A1_OFF;
      else
        X10_data = X10_A1_ON;
    }

By changing House code and data, it is now possible to create our own RF sensors.

  [1]: http://www.printcapture.com/files/X10_RF_Receiver.pdf


body:
I called HTTP web service on Arduino Uno, now i am trying to store the data in SD card. But as soon as i compile the program, it shows LOW MEMORY error and no data stored in SD card.
Any one can help?

title: Low memory error using SD card

Answers: 2

body: Try Arduino mega. It has more memory 8 KB RAM, 256 KB flash memory.

body: Try to use properly  kind of variables for example if u r using Int in a value can would  use byte of try to put some serial.println(F("wherever  you can print "))  for running  on sram instead of  stack memory.


body:
The Arduino documentation says **if(Serial)** always returns 1, except for the case where Leonardo USB serial connection delays becoming ready.

(Leonardo has two USB IDs, and switches between them for boot loader and Serial USB.  After boot loader finishes and kicks off the program, it takes a while for the USB master (e.g. your PC) to process the disconnect of the boot loader USB device and the connection of the Serial USB device.  Thus the need for a wait.)

Now "*Serial*" is a static external instantiation of the *Serial_* class (defined as ***extern Serial_ Serial;***).

The c++ rules, as I understand them, do not allow a constructor to return a value, nor may the class name (which is also the constructor name) be used as a member (function) name in the class.

"*Serial*" cannot be defined in class *Serial_*, or the **if(Serial)** syntax would have to be **if(Serial.Serial)**.

"*Serial*" cannot be defined outside the **class Serial_,** or it will conflict with (i.e. hide) the definition of *Serial* as an instantiation of *Serial_*.

___So how does the Arduino IDE do it?___

All I can think of is that the magic pre-scanner does something...  But what exactly, pray tell?

title: How does if(serial) work, a c++ question

Answers: 1

body:
It's not the constructor that's returning the value, it's the `bool` operator:

Uno:

    HardwareSerial::operator bool() {
        return true;
    }

Leonardo:

    Serial_::operator bool() {
        bool result = false;
        if (_usbLineInfo.lineState > 0)
            result = true;
        delay(10);
        return result;
    }

When you use the object in a setting where a boolean value is expected of it (e.g., `if`, `while` etc.) the `bool()` operator is called (if it exists) and that value is used.

More specifically, the `bool()` operator is called when the object is being *cast* to a `bool` type, either implicitly (as in `if...`) or explicitly (as in `... = (bool)Serial;`).

More on C++ class operators here: http://en.cppreference.com/w/cpp/language/operators


body:
Lately I was asking myself about the possibility of measuring a potentiometer resistance with Arduino.

My questions are:

1. Is it possible?
2. If it's possible, what kind of restriction does the Arduino have with the resistance value measured?

title: A question about resistance measurement with arduino

Answers: 2

body:
_The question isn't explicitly clear, this answer is based on having a single known value pot and wishing to know its resistance at any one point rather than trying to find an unknown resistance entirely_

You can't measure resistance directly. What you can do however is measure the voltage across a potentiometer.
There is a really good example provided by arduino [which can be found here][1].

Now, it is possible to turn this into a resistance value with a little bit of editing to the code

    int potPin = A0;    // Select the input pin for the potentiometer
    int potR = 1000;    // This is your max potentiometer resistance in Ohms
    int val = 0;        // Variable to store the value coming from the sensor
    float voltage;      // This is the voltage from the wiper of the pot
    float resistance;   // This is the resistance of the pot at the wiper

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

    void loop() {
      val = analogRead(potPin);                      // Read the value from the pot wiper
      voltage = val * (5.0 / 1023.0);                // Convert the value into a voltage
      resistance = (voltage / 5.0) * potR;           // Convert the voltage into a resistance
      Serial.print("Voltage = ");
      Serial.print(voltage);                         // Print the voltage
      Serial.println("V");
      Serial.print("Resistance = ");
      Serial.print(resistance);                      // Print the resistance
      Serial.println("R");
      delay(1000);                                   // Add a little delay
    }

As for your second question, it can do as high a resistance as you want. As long as you update the potR value in the code with the resistance of your pot (e.g. 1000000 for a 1MOhm pot)

_I'm an electronics engineer by trade so my code could probably be cleaned up and made more efficient, this is just a starting point_

  [1]: https://www.arduino.cc/en/Tutorial/ReadAnalogVoltage

body:
If you know Ohm's Law (which you should) and you realise that the ADC measures voltage, you should be able to work it out from there. But I will go into minute detail for you to ensure you understand.

Ohm's Law defines the relationship between Voltage (V), Current (I) and Resistance (R).

    R = V/I

To find one unknown value (in your case R) you need to know the other two values.  That is, the current flowing through the resistor, and the voltage dropped across the resistor.

We have no way of directly measuring current, but we can measure voltage using the ADC. So if we can somehow measure a voltage and use that to calculate the current then we have two of the three values and we can calculate the third. However, calculating the current requires that we know the resistance - and that is what we are wanting to find out.

So we need to then provide a *known* resistance that we can measure the voltage across, and thus find the current flowing through it. First a couple of reminders of basics:

* Current flows the same through all resistances connected in series
* The sum of all voltages dropped across resistors in series equals the total voltage across all the resistors.

So if we put two resistors in series and apply an fixed voltage across it (5V in our case) a single current will flow through them both. With that two voltages will be dropped across the resistors - and those two voltages will add up to 5V.

If we have one known resistor and one unknown resistor and we know the voltage dropped across both resistors then we can calculate the current that is flowing through the known resistor. And that current is the same current that is flowing through the unknown resistor. And since we know the voltage drop across that resistor we can then calculate its resistance using that voltage and the current we have just calculated.

Here's the circuit I just described:

[![enter image description here][1]][1]

Vin us 5V. Let's have R1 as, say, 10KΩ (a common enough value). R2 we don't know.

Using the ADC of the Arduino we measure a value of 681. First we convert that into a voltage:

    Vout = 681 / 1024.0 * 5.0
         = 3.325V

So we know that R2 has 3.325V dropped across it, and since all the voltages must add up to 5V we know that R1 has (5 - 3.325) 1.675V dropped across it.

So the current (I=V/R) through R1 must be (1.675 / 10,000) 167.5µA (0.0001675A).

Now we can calculate the resistance of R2 since R=V/I and V is 3.325 and I is 0.0001675, so R must be 19850Ω - or pretty much 20KΩ.

That's the long-hand version from a current-based perspective. However there is a short-cut.

Since the output voltage is a simple ratio of the input voltage defined by the ratio between the resistors we can use that to create a much simpler formula.

From the example above the output voltage is two thirds the input voltage - and R2 is two thirds the total resistance (R1+R2). The two match perfectly.  So we can use a simple ratio calculation to give us the resistor.

For instance, the ratio formula:

    Vout = R2 / (R1 + R2) * Vin

(that's R2 as a proportion of the total resistance multiplied by the input voltage)

When rearranged to get R2 gives us:

    R2 = R1 * (1 / ((Vin / Vout) - 1))

So taking the voltage we measured above (3.325) and the known resistor (10,000Ω) and the input voltage (5V) and substituting those values into the formula, we get:

    R2 = 10,000 * (1 / ((5 / 3.325) - 1))
       = 10,000 * (1 / (1.504) - 1)
       = 10,000 * (1 / 0.504)
       = 10,000 * 1.984
       = 19840

Or pretty much 20KΩ. (Note: the discrepancy in the results is purely due to rounding errors. Use higher precision values and you get better results).

You have to have a rough idea of the kind of order of magnitude of resistor you are trying to find, though, in order to select an R1 of a comparable value so that the voltage Vout is large enough to measure accurately.

Also you need to be aware that the input to the ADC has quite a (relatively) low impedance (can be very crudely thought of as a resistor between the input and ground) which is measured in the low mega-ohm range. This can have an impact on the values you read with the ADC if your resistors are too high, since this impedance will be in parallel to the resistor R2, so you'd actually be measuring the resistance of both R2 and the ADC's input in parallel. To measure very high resistances you should first buffer the ADC through a *voltage follower* with a very high (tens or hundreds of tera-ohms) impedance input.

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


body:
To start, I am a software guy, so I am not too clued up on the electronics side of things. My question is: I have a number of Arduino shields and would like to power them with a portable power source, and therefore would like some advice on what to use without frying any electronics.

This is a list of the current equipment that will require power:

 - [Arduino Mega 2560][1]
 - [SIM900 GPRS/GSM Shield][2]
 - [Sparkfun GPS Logger Shield][3]
 - [Sparkfun Wifi Shield - ESP8266][4]

The shields will be stacked on top of each other.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560
  [2]: http://linksprite.com/wiki/index.php5?title=SIM900_GPRS/GSM_Shield
  [3]: https://www.sparkfun.com/products/13750
  [4]: https://www.sparkfun.com/products/13287

title: Powering multiple Arduino shields

Answers: 2

body:
All the shields are 5v compatible. So no need to worry about 3.3v.

But there may be a chance of insufficient current if you use a battery to the power-jack of arduino mega (due to the internal voltage regulator). I'd suggest you cut a USB cable and solder the +5(red color) wire to VIN on the mega and ground(black wire) to GND pin. And use a 'power bank', which is used for mobile phones.

body:
Your stack will need quite a lot of current - most probably more than the Arduino can supply itself.

You will need to provide your own regulated 5V supply - either from a USB port (convenient if you are by a computer) - as long as it can supply more than 500mA of current (you need a Charging Downstream Port *CDP* for that) or from some external regulated 5V power supply, such as a mobile phone charger.

That 5V supply should be connected direct to the 5V pin of the Arduino's power header.

One thing to note: the headers themselves are only rated for up to 1A. If you need more than 1A throughout the entire stack it could be worth connecting the 5V power supply direct to the 5V pins of ALL the shields in the stack. Also do the same with the GND pins to the negative of the power supply. That way the high current doesn't need to flow through the pins themselves.


body:
I've recently gotten my hands on an Arduino (or rather a Genuino, but the overall architecture should be the same) UNO. I'm now using that Arduino to test how data is transmitted from a USB to Serial Connector to the Arduino.

I've already verified that data transmission from Arduino to the PC is possible, by using hTerm and PySerial. However, whenever I send data from Pyserial or hTerm, it doesn't show up in the Arduino serial terminal. Also, I'm using SoftwareSerial to set up a secondary serial terminal to see what the Arduino receives. (I'm using the standard serial port to send data to the terminal, and the SoftwareSerial Port to connect to the USB to Serial Connector.)

Here's my code so far:

Python side:

<!-- language: lang-python -->

    import serial
    import time
    import sys
    import struct
    ser = serial.Serial('COM3', 9600, timeout=0)
    time.sleep(10)
    while 1:
        print(ser.write(struct.pack('>B', 0)))
        time.sleep(2)
        print(1)
        sys.stdout.flush()

The Arduino side looks like this, and is essentially the default example:
https://www.arduino.cc/en/Tutorial/SoftwareSerialExample

<!-- language: lang-cpp -->

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11); // RX, TX
    void setup() {
      // put your setup code here, to run once:
      if (Serial) {
        Serial.end();
      }
      Serial.begin(9600);
      while (!Serial) {
        ;
      }

      Serial.println("Godnight moon!");

      mySerial.begin(9600);
      mySerial.println("Hello, world?");
    }

    void loop() {
      // put your main code here, to run repeatedly:
      mySerial.listen();
      if (mySerial.available() > 0) {
        Serial.println("Hello User");
        Serial.println(mySerial.read());
      }
    }

The Terminal never prints "Hello User". Also, no other signals are being printed. By removing the if-condition, I get a whole lot of "Hello User" and "-1" in the Arduino IDE serial monitor.

Concerning my setup:

I've got an USB to Serial converter, which is connected as "COM3". On the other side, I have an Arduino UNO which is connected via USB to the same computer. The TX pin of the converter is connected to the RX pin of the Arduino and vice versa. Also, Ground is connected to Ground. Furthermore, I use Jupyter/IPython notebook to run my Python script, and the default Arduino IDE to compile programs for my Arduino. In the case there I received data from the Arduino, I used the script specified in the URL provided, which is very similar to the one I'm already showing here. Also, `ser.write()` is replaced by `ser.read(1)`, so that it reads one byte at a time. My system is Windows 7 (64 Bit).

Edit: Here is an established connection between hTerm (a serial terminal) and the Python script while using com0com as a port emulator.
[![A successful communication between the Python script and hTerm][1]][1]

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

title: Arduino-Pyserial communication on Python 3, Windows machine: Pyserial.write() doesn't seem to do anything

Answers: 2

body:
What do you think should come out?

I'm no expert with Python but you seem to be using struct pack, which I think prepends a number of bytes to the data to generate a 4 byte word.  You are using NULL, 0 to pack the structure.  When Serial.println() encounter a NULL it will assume that is the end of the string.  So you seem to be printing a zero byte string.

Oh and Serial.read() only reads one byte of data, so there is an issue with that too. I suspect that the write call has a similar issue, you normally need to supply a size parameter because its binary data.

Does that make sense?

body:
When you run your python code, do you see the things you are sending on the screen there?

I think you need to be calling  ser.open().


body:
When compiling I get the error
'as: unknown option »-mmcu=avr5« exit status 1'

I succeeded now using your piece of advise. Thank you so much.

title: IDE 1.6.10 on LinuxMint 17.3 Cinnamon

Answers: 1

body: Delete or rename the old "Arduino15" directory located at /home/(username)/.arduino15    (a.k.a. ~/.arduino15) and re-install 1.6.10.


body:
I have LED bar graph on pins 2-11. Eventually I want to use a voltage divider to figure out the amount of voltage left in a power supply. Currently, this script should set the number of LEDs on the bar graph based on `round((v_actual/v_reference)*10)`, I am just using some placeholder numbers in the mean time to test this portion of the script e.g. `v_actual` of 5 and `v_reference` of 10. However, the `convert` variable *keeps printing 0*. I've checked that the other variables were passing and they are. What is the issue here?

    #include <Wire.h>

    int ledBarNum = 10;    // # of leds
    int vref = 10;     // max voltage of power supply

    void setup(){
      pinMode(2, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);
      pinMode(6, OUTPUT);
      pinMode(7, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(11, OUTPUT);
    }

    void loop() {

      ledBarSetup(5);
    }

    void ledBarSetup(int v) {

      // logic vref=8; vactual or v = 4; (4/8)*10 = 2
      // e.g. number of leds we need to light up to represent the total amt left

      Serial.println(v);
      Serial.println(vref);

      int convert = round((v/vref)*10);

      Serial.println(convert);

      ledBar(convert);

    }

    void ledBar(int n) {

      int startingPin = 2;

      for (int thisPin = 2; thisPin < ledBarNum; thisPin++) {

        if (thisPin <= n) {

          digitalWrite(thisPin, HIGH);

        } else {

          digitalWrite(thisPin, LOW);

        }

      }

    }

title: LED bar graph script not working

Answers: 1

body: Both `v` and `vref` are integers, which means that integer division will be performed. if `v` is ever less than `vref` then the result will be 0. Multiply first, then divide.


body:
I have been working on an arduino program, which has gotten rather large. I am close to hitting the 32k limit on Flash for my ATmega328p. I would like lower my program size by saving some of my many string literals into EEPROM.

All of the example programs on the EEPROM page suggest loading them in at runtime, in which case they would take up flash memory anyways! What I am wondering, is if there is a way to write to EEPROM from my PC, THEN load the arduino program which will access those values. Do I need some external hardware to do this?

Thanks for your help!

-sam

title: Set EEPROM from PC before program

Answers: 3

body:
I think here is a confusion about the three types of memory. EEPROM, FLASH and SRAM are completely separate. EEPROM is like your file storage. FLASH contains you program and static values. SRAM is the memory the program is working with.

Static values are loaded from FLASH into SRAM upon start unless you declare your static content not to load automatically by using the according Macro `PROGMEM`. In that case it does not eat up your SRAM until you manually read it from FLASH into SRAM. `#include <avr/pgmspace.h>` is used for this ([pgmspace.h][1]).

EEPROM is not loaded automatically and therefore must be read explicitly. `#include <avr/eeprom.h>` contains all the functionality ([eeprom.h][2]).

I'm not sure about the Arduino IDE but with avrdude you can program the EEPROM separately without having the values been predefined in your program. The [third example][3] in the AVRdude manual shows how to flash the program, eeprom and fuses at once.

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html
  [2]: http://www.nongnu.org/avr-libc/user-manual/group__avr__eeprom.html
  [3]: http://www.nongnu.org/avrdude/user-manual/avrdude_6.html

body:
The simplest way would be to have **two** sketches.

One that will store all the strings into EEPROM.

After that you can upload the second actual sketch that uses the values stored in EEPROM.

You only need to upload the first sketch if any of the strings change.

There is a way to upload a hex directly to the EEPROM using avrdude, but you'd have to use the commandline, and also have some way of generating this hex file containing all these strings.

body:
You don't need two sketches:

    #include <avr/eeprom.h>

    char e2str[] EEMEM = "Hello, world!\n";

    void setup()
    {
        Serial.begin(9600);
        uint8_t *ptr = reinterpret_cast<uint8_t *>(e2str);
        while (true)
        {
            char c = eeprom_read_byte(ptr++);
            if (c == '\0') break;
            Serial.write(c);
        }
    }

    void loop() {}

Compile (Sketch>Verify/Compile) the source above and you should find file named `<sketch-name>.ino.eep` in project's build directory.

For Arduino Nano, you can just run `avrdude` with `-U eeprom:w:<path-to-eep-file>:i` option before Sketch>Upload.

For Arduino Uno, however, you must first program it's EEPROM using programmer, since Optiboot doesn't support writing to EEPROM. <s>Or you can burn it with Arduino Nano bootloader once (Tools>Board>Arduino Nano, Tools>Processor>ATmega328, Tools>Burn Bootloader) and then use the procedure for Arduino Nano.</s> (Arduino Uno and Nano bootloaders use different baud rates).


body:
I've written a program which allows me to use my `Arduino Uno` to send a `PWM` to an **Electronic Speed Controller**. 5 seconds after startup the ESC is sent a config via `PWM` to signal the low to high `PWM` range to be used by the ESC. Then I can type into the `Serial Monitor` a single digit 0-9 to pick the `PWM` I want to send to my ESC. *(n\*2 = pwm)*

This works great when running code for *one* ESC, but adding code for a *second* ESC causes significant issues (I only have one ESC plugged in). When I send a `serial` command to specify `PWM` rate, my ESC only receives the `PWM` change *sometimes*. About 2/3 times it ignores the PWM change and keeps spinning at the same rate it was already at.

***What's going on here?***

# Code

**WorkingESCSoftware** *(main file of .eno)*

    #include <SoftwareServo.h>
    #include "TestClass.h"

    int val;    // variable to read the value from the analog pin
    int stage = 0;

    TestClass t, t2;

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

      t = TestClass();
      t.setPin(3);
      t2 = TestClass();
      t2.setPin(5);
    }

    void loop()
    {
      t.loop();
      t2.loop();
    }

**TestClass.h**

    class TestClass {
      private:
        SoftwareServo servo;
        bool _initialized = false;

        int PWM_MAX = 180;
        int PWM_HIGH = 170;
        int PWM_MEDIUM = 80;
        int PWM_LOW = 40;
        int PWM_OFF = 25; // has to be between esc config off (stop) and low (slow spin)
      public:
        TestClass();
        void setPin(int);
        void loop();
    };

    TestClass::TestClass() {
      Serial.println("cycle lipo power to esc");
    }

    void TestClass::setPin(int pin) {
      this->servo.attach(pin);
    }

    void TestClass::loop() {
      //  Serial.println("loop");

      // 5 seconds after power, send PWM range to ESC
      if(millis() > 5000 && this->_initialized == false) {
        this->_initialized = true;

        Serial.println("esc setup");
        this->servo.write(PWM_MAX);
        delay(5);
        this->servo.write(PWM_OFF);
        delay(5);
        Serial.println("esc ready");
      }

      char r = Serial.read();
      String inStr = String(r);
      if(r > -1) {
        Serial.print("serial in: ");
        Serial.println(inStr);
      }

      use h, m, l, o, or 0-9 to control PWM of ESC
      if(r <= -1) {
        // void
      } else if(inStr == "h") { // high
        Serial.print("HIGH: ");
        Serial.println(PWM_HIGH);
        this->servo.write(PWM_HIGH); // highest spinning (same as 160?)
      } else if(inStr == "m") { // medium
        Serial.print("MED: ");
        Serial.println(PWM_MEDIUM);
        this->servo.write(PWM_MEDIUM);
      } else if (inStr == "l") { // low
        Serial.print("LOW: ");
        Serial.println(PWM_LOW);
        this->servo.write(PWM_LOW);
      } else if (inStr == "o") {
        Serial.println("OFF");
        this->servo.write(PWM_OFF);
      } else if (inStr.toInt() >= 0 && inStr.toInt() <= 9) {
        int val = inStr.toInt() * 20;
        Serial.println(val);
        this->servo.write(val);
      }

    //  SoftwareServo::refresh();
      this->servo.refresh();
    }

title: Problems with running multiple ESC

Answers: 1

body:
You have two copies of your program sharing one physical resource, the serial port input to the Arduino.  It is by chance which of the two copies will receive and process the input data.  So this approach will not work dependably.

[Semiphoras][1] are often used when sharing hardware among several programs.  However you are not only sharing hardware, but also the data being sent to the Arduino.  And the data will only be sent once.

In this case, you need to handle the data once in code that is separate from the 2 instantiations of the ESP class.  That is, you need to process the received data once and pass that processed data to the appropriate instantiation of the ESP class.

  [1]: https://en.wikipedia.org/wiki/Semaphore_(programming)


body:
I have the following system:

[![enter image description here][1]][1]

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

As a master, I have an Arduino UNO Chip, more specifically an Atmel MEGA328P. The important thing is that this microcontroller has only one hardware Serial port, and that port is used to communicate with a WiFi adapter.

The problem I'm facing with is that I want to receive data from a Compass and a GPS modules. Booth send data via Serial protocol. The 328p Chip have only one serial which is busy!

**I can't use SoftwareSerial as I don't want any delay on master board!**
I can't also use Arduino Mega2560 which have 3 Serial ports as its sizes are too big.

So there are are my approaches:

1. Using MCP4725 I2C DAC for Compass, but what we do with GPS?
2. Using and intermediate Arduino UNO Chip?
On that chip I could use Software serial but how to transfer data to MASTER using only digital and analogic pins? Maybe using 10 pins to implement a parallel transfer?
3. Perhaps there is possible to convert Compass and GPS data to analogic then transfer to MASTER?

Anyway, what possibilities would I have to play around?

title: [Arduino UNO]Receive Serial Data from multiple sources

Answers: 2

body: I think softserials are working based pinchange interrupt. This wont make you any significant delay i hop.Or you should go gps or wifi modules with SPI or IIC interface.

body:
[This answer](https://arduino.stackexchange.com/questions/26240/which-pins-of-an-arduino-uno-can-be-used-as-tx-and-rx-pins-for-connecting-to-gsm/26277#26277) summarizes the possibilities:

1) `HardwareSerial` is always best.  You are using that for WiFi.

2) [`AltSoftSerial`](https://github.com/PaulStoffregen/AltSoftSerial) is the best software serial library, but it requires pins 8 & 9.  Very efficient and non-blocking!  Strongly recommended for the GPS connection.

3) [`NeoSWSerial`](https://github.com/SlashDevin/NeoSWSerial) is next best, but it supports only 9600, 19200 and 38400.  It is non-blocking on receive, so it could be used for the GPS connection.

4) `SoftwareSerial` is the worst.  :P  Not suitable for the GPS connection, as you have discovered.

I'll also mention my GPS library, [NeoGPS](https://github.com/SlashDevin/NeoGPS).  It is smaller and faster than other libraries, and there are examples that show how to make it run *during* the RX character interrupt, saving even more time.  It can also be configured for just the messages and fields that you actually use, saving RAM, program space and execution time.


body:
I want to do WiFi GeoChaching box. I'll use cheap ESP01, but problem is it will work in forest 24/7 in cycle of 1 min of work 5 in deep sleep and waiting for those who will find that.
How I can get power?

title: Power ESP01 in forest

Answers: 1

body:
I think that in this case you will need multiple solutions for generating the power.

 1. You need to know how much power you need.  This depends on you solution, I can't help there.
 2. You need a backup battery, ideally one that doesn't mind constant trickle charge and deep discharge.  Sealed lead acid are probably the best.
 3. Your battery must have enough power over a long enough time.
 4. You need a power generator, wind, solar, water, chemical. And they should all have a common interface so you GeoCache is modular, so the GeoCaches can be plugged into any of the power sources, maybe even more than one source.

The problem with the power source is it is going to be a visual clue to where the cache is, probably also an audio clue.
The battery, if SLA, is going to be a great big lump that could be dangerous if damaged.
The caches are not going to be cheap, just because of the power source and battery, so I hope you have deep pockets.

Rather than looking for a ESP01+BT4 module look for any microprocessor with BT built in, it maybe a better way to go.


body:
I've been asked to do a small project using an Ada BlueFruit board. It has a [ATMega32U4][1]. The 32U4 [comes from the factory with a bootloader pre-installed][2]. I've never used an Arduino before, but I have used AVR a bit in the past. Is the Arduino bootloader actually the one that came pre flashed from the factory? Does it even matter if it's the same bootloader as far as Flip is concerned?

Can I use the Flip batchisp utility to load my application code? We don't have a programmer handy and I don't want to muck up the bootloader on the board.

It's my understanding that the Arduino IDE tool chain does a bit of preprocessing "behind your back". I'd much rather continue writing straight AVR code in Atmel Studio. Is there anything I need to take into account when writing my application code? For example, do I need to do anything when compiling my app code, or when uploading it, to ensure it doesn't try to write to the memory addresses in the bootloader's range?

[1]: http://www.atmel.com/devices/ATMEGA32U4.aspx
[2]: http://www.atmel.com/Images/doc7618.pdf

title: Is the Arduino bootloader really the Atmel bootloader? Can I use Flip to upload?

Answers: 3

body:
>  Is the Arduino bootloader actually the one that came pre flashed from the factory?

You would have to ask Adafruit that.

> It's my understanding that the Arduino IDE tool chain does a bit of preprocessing "behind your back". Is there anything I need to take into account when writing my application code?

The things you are talking about is generation of function prototypes, that sort of thing. It's nothing you really need to worry about.

> For example, do I need to do anything when compiling my app code, or when uploading it, to ensure it doesn't try to write to the memory addresses in the bootloader's range?

No, it would be crazy for the IDE to overwrite the bootloader. Then you wouldn't be able to use it again. In fact, to change the bootloader needs special hardware. You need to connect a programmer to the ICSP pins.

---

> I just want to know if I need to do anything special during linking to ensure there's no memory address conflicts

I doubt you need to worry about that, as long as you ensure that whatever tool you are using knows to allow room for the bootloader.

> and if I can use the Flip tool to upload

I don't see why not. Or you could use the dfu-programmer as I describe in my post [How to flash the USB chip on the Arduino Uno](http://www.gammon.com.au/forum/?id=11635&reply=2#reply2).

body: Arduino uses a different (second) bootloader, next to the DFU one that build into the 32u4.

body:
> I'd much rather continue writing straight AVR code in Atmel Studio.

The Arduino IDE allows you be lazy about #includes and forward references to functions, but it won't get in your way if you choose to write correct code.

I write standard C/C++ and switch back and forth between Eclipse (no over-helpful pre-processing) and the Arduino IDE. The Arduino IDE knows better; it just CYA (covers your assumptions :) in case you don't.


body:
I am working to read two quadrature encoders using a single Arduino DUE, as part of my summer vacations project. According to the following link
http://atmel.force.com/support/servlet/fileField?id=0BEG0000000HRvP, the SAM3X8E has 2 quadrature decoders in it. Now I am not being able to understand how can I initialize this second quadrature decoder. According to **Quadrature Decoder QDEC for SAM3/4 Devices_ApplicationNote_AT11483**  _Pg16_ we have to first configure the IOPINS for QDEC1. I have to do that same task in Arduino IDE instead of Atmel Studio.

This is the code that I have found and works well to read encoder using QDEC0. However, I now need to read the encoder using the second quadrature decoder, whose input pins are TIOA6 , TIOB6 which correspond to Pin 5 and 4 of Arduino DUE. After reading the Atmel SAM3X datasheet, I think I should change "TC0" with "TC2" to make the second decoder work. However, this doesn't work. I think it does not work because channel 2 is busy in time base calculations.
In Application Note _5.52_ **QDEC Speed Measurement Mode** point 2 says to Initialize TC0, TC1, TC2. If I wanted to used other encoder which timer instance will be used.

    /*
    ** Quadrature Encoder on Arduino Due in "Speed Mode"
    ** Will not work on other Arduino types because of a specific hardware requirement.
    **
    ** @bungle99 / 2014-02-28
    **
    ** Many thanks to @Designservicecorp (notably post #32 and post #42) that gave me the base to work from.
    **
    ** Uses *hardware* to do the heavy lifting of interpreting the Encoder output, which gives it significant
    ** advantage over other Arduino's for this use case. Eg many people have reported their Unos maxing out
    ** or skipping counts when interpretting high RPMs, whereas people using the Due in hardware mode have
    ** reported better success with high RPMs.
    **
    ** This particular example puts the hardware into "Speed" mode, whereas other examples in this thread use
    ** "Position" mode (see posts 32, 42). The one example in the thread that attempts Speed calcs uses Position
    ** Mode and uses an interrupt on the Z Index axis to manually apply a time period (needed to caculate speed)
    ** on each rotation.
    **
    ** This code below has been used in tests (using Lego NXT and a gear train for driving / comparison) to
    ** ~3,500 RPM with a 1,024 PPR Encoder (4 x 1,024 Edges). The Arduino didn't seem to struggle and the
    ** numbers (eg RPM) matched fairly closely with the Lego (eg as a sanity check, the calcs in the code look
    ** correct).
    **
    ** I bought one of these encoders, which seems ok;
    **
    **   * http://proto-pic.co.uk/rotary-encoder-1024-p-r-quadrature/
    **
    ** Great service from proto-pic. The encoder specs are officially
    **
    **   * http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Robotics/E6B2Encoders.pdf
    **
    ** But look an awful lot like this one too (which is easier to read)
    **
    **   * http://www.ia.omron.com/product/item/e6b27032r/index.html
    **
    ** Note that this Encoder is rated at 5V min. I've successully powered it off the 5V Arduino pin header,
    ** and it doesn't work off the 3.3V one. At 5V, the outputs need to be run through some resistors to bring
    ** them into tolerance of the Arduino inputs.
    **
    ** The inputs are 2 and 13 (and optionally A6 for the index).
    **
    ** The test hardware (some Lego NXT servos and gear train) was unable to turn any faster (more gears
    ** stalled the servos) - eg the Arduino Due was not the limiting factor. At this speed, the Due Hardware
    ** is dealing with approx 238,000 edges per second.
    **
    ** This example offloads the speed calculation onto the hardware, meaning no interrupt is required.
    ** In addition, the index is not required either, so it allows speeds to be seen even for rotations that
    ** don't pass the index marker (for example, slow rotations needing a speed before a complete rotation).
    ** That said, index is available if you want it and the docs suggest you can still use it (and others) as
    ** interrupt if you wish.
    **
    ** NB There appears to be a myriad of features on the Chip that have not been touched. Eg you can still add
    ** interrupts to this code to do other things; eg passing the Z index, direction changes. There are also
    ** filters available if your encoder suffers from noise (eg vibrations). All this is available to play with
    ** another day :)
    **
    ** Code appears to work, but no guarantees. Understand it. Test it. Feedback to the group. YMMV. Don't blame
    ** me if it doesn't work or expolodes!
    */

    const int ENCODER_EDGES_PER_ROTATION = 3200;  // this depends on your encoder
    const int ENCODER_SAMPLES_PER_SECOND = 10;        // this will need to be tuned depending on your use case...
    const int LOOP_DELAY_MS = 1 * 1000;               // ... as will this (see comments in main code)

    void setup() {

      Serial.begin(115200);
      delay(10);

      // Setup Quadrature Encoder
      // http://www.atmel.com/Images/doc11057.pdf
      // Section 37 p869
      // Section 37.6.14 p885
      // Section 37.6.14.2 p890 Position and Rotation Measurement
      // Section 37.6.14.5 p891 Speed Measurement (what this is about)

      REG_PMC_PCER0 = PMC_PCER0_PID27
                    | PMC_PCER0_PID28
                    | PMC_PCER0_PID29;

      // Setup a channel in waveform mode (eg an input into the encoder to trigger the time based sampling)
      // Note some of the choices here impact calculations below and if you change them, you need to change
      // the next section to suit.
      // Section 37.7.11 p906 (also refer to Section 37.6.14.5 p891 for detail of what to set)
      REG_TC0_CMR2 = TC_CMR_TCCLKS_TIMER_CLOCK4
                   | TC_CMR_WAVE
                   | TC_CMR_ACPC_TOGGLE
                   | TC_CMR_WAVSEL_UP_RC;

      // Now define the sample period, using the clock chosen above as the basis
      // Note that REG_TC0_CMR2 above is using CLOCK4; this is an 128 divisor. You need to change the
      // divisor below if you change the clock above. You could change the input clock and the RC mode to
      // suit your app (eg how many pulses are you  expecting - depends on encoder type
      // and slowest/normal/fastest rotation speed and what you want to do with the result).
      // Section 37.6.14.5 p891 notes you need to set this up, otherwise 0 comes out all the time :-)
      REG_TC0_RC2 = F_CPU / 128 / ENCODER_SAMPLES_PER_SECOND;

      // Setup a channel in capture mode
      // Section 37.7.10 p904 (also refer to Section 37.6.14.5 p891 for detail of what to set)
      REG_TC0_CMR0 = TC_CMR_ABETRG
                   | TC_CMR_LDRA_EDGE
                   | TC_CMR_LDRB_EDGE
                   | TC_CMR_ETRGEDG_EDGE
                   | TC_CMR_CPCTRG;

      // Enable features, noting Speed not Position is chosen
      // Section 37.7.2 p895 (also refer to Section 37.6.14.5 p891 for detail of what to set)

    // 37.7.2 TC Block Mode Register
      REG_TC0_BMR = TC_BMR_QDEN
                  | TC_BMR_SPEEDEN
                  | TC_BMR_EDGPHA; //Pg 896

    /*EDGPHA: EDGe on PHA count mode
    0: edges are detected on both PHA and PHB.
    1: edges are detected on PHA only.*/

      // Set everything going
      REG_TC0_CCR0 = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC0_CCR1 = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC0_CCR2 = TC_CCR_CLKEN | TC_CCR_SWTRG;
    }

    void loop() {

      int iIndexCount = REG_TC0_CV1;  // Don't need this, but manual notes its available
      int iSpeedPPP = REG_TC0_RA0;    // This is what we're really after (speed in Pulses Per sample Period)

      // which we can convert to rps or rpm easily
      double dSpeedRPS = ((iSpeedPPP / (ENCODER_EDGES_PER_ROTATION * 1.0)) * ENCODER_SAMPLES_PER_SECOND);
      double dSpeedRPM =  dSpeedRPS * 60;

      Serial.print("Speed ppp: ");
      Serial.print(iSpeedPPP);
      Serial.print(", ");
      Serial.print("Speed rps: ");
      Serial.print(dSpeedRPS);
      Serial.print(", ");
      Serial.print("Speed rpm: ");
      Serial.print(dSpeedRPM);
      Serial.print(", ");
      Serial.print("Indexes: ");
      Serial.print(iIndexCount);
      Serial.print(". ");
      Serial.println();

      // Slow down the main loop noting the Encoder can update independently in the background (we're
      // effectively polling it to find out the latest and greatest info on each loop around).
      delay(LOOP_DELAY_MS);
    }

Additionally I wanted to ask what is the difference between REG_TC0_CMR2 REG_TC0_CMR0 and REG_TC0_CMR1 ? Two of them are used in the above code.

Motor with Encoder I am using is:
[![enter image description here][1]][1]

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

title: How to configure 2nd Quadrature Decoder IO pins in Arduino IDE

Answers: 1

body:
TC blocks are pretty much identical (except TC1 doesn't have wired some signals to pins)

So you have to copy registers containing `*_TC0_* =` and replace TC0 to TC2.

Plus PC25 and PC24 should be set to its alternate function PIO_PERIPH_B. Something like this:

      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT);
      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT);

Also TC6, TC7 and TC8 clocks must be enabled by:

    REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

And TC_CMR0..2 are Channel Mode Registers for one of three timers/counters in one TC block. Again, these are the same, but WAVE mode dependent.

[![TC_CMR WAVE=0][1]][1]

[![TC_CMR WAVE=1][2]][2]

Full configuration:

      REG_PMC_PCER0 = PMC_PCER0_PID27 | PMC_PCER0_PID28 | PMC_PCER0_PID29;
      REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

      PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB25B_TIOA0, PIO_DEFAULT); // arduino pin 2
      PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB27B_TIOB0, PIO_DEFAULT); // arduino pin 13

      REG_TC0_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
      REG_TC0_RC2   = F_CPU / 128 / 1;
      REG_TC0_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
      REG_TC0_BMR   = TC_BMR_QDEN | TC_BMR_SPEEDEN /*| TC_BMR_EDGPHA*/;
      REG_TC0_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC0_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC0_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); // arduino pin 5
      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT); // arduino pin 4

      REG_TC2_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
      REG_TC2_RC2   = F_CPU / 128 / 10;
      REG_TC2_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
      REG_TC2_BMR   = TC_BMR_QDEN | TC_BMR_POSEN /*| TC_BMR_EDGPHA*/;
      REG_TC2_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC2_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC2_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

  [1]: https://i.stack.imgur.com/kRDgl.png
  [2]: https://i.stack.imgur.com/amN6y.png


body:
I am trying to port a simple project I have working in an Arduino UNO to a NodeMCU but I am stuck as I am using the analog gpio to receive the input from some buttons, I am always getting always low values (between 0 and 5) while in the working arduino sketch I get values from 0 to 1023.

I have tried deactivating the wifi while trying to retrieve the values, but I got no luck trying that, as I have read that sometimes the NodeMCU A0 gpio malfunctions when the wifi is not sleeping.

I am setting up the gpio in the setup method like this:

    void setup(void){
        pinMode(sensorPin, INPUT_PULLUP);
        ...

And my sensorPin variable is declared in the beginning of the sketch

    int sensorPin = A0;
Any ideas why when I read the value in the NodeMCU I don't get the same behaviour as in an Arduino board?

title: NodeMCU : Input pullup in A0

Answers: 1

body:
As stated by Majenko in the comments, I thought that all MCUs analog gpios had a pullup resistor built in, so I have been able to solve the problem using an external pullup, in this case connecting a 10K resistor like in the diagram:

[![enter image description here][1]][1] .

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

Special thanks to Majenko for his time and patience. Cheers!


body:
I have following code (and it works great!) for SHT75 Sensirion sensor.
<!-- language-all: lang-cpp -->

    /*
     * Example code for SHT1x or SHT7x sensors demonstrating blocking calls
     * for temperature and humidity measurement in the setup routine and
     * non-blocking calls in the main loop.  The pin 13 LED is flashed as a
     * background task while temperature and humidity measurements are made.
     * In addition, the sensor may be placed in low resolution mode by
     * uncommenting the status register write call in setup().
     */

    #include <Sensirion.h>

    const uint8_t dataPin =  2;            // SHT serial data
    const uint8_t sclkPin =  3;            // SHT serial clock
    const uint8_t ledPin  = 13;            // Arduino built-in LED
    const uint32_t TRHSTEP   = 3000UL;     // Sensor query period
    const uint32_t BLINKSTEP =  250UL;     // LED blink period

    Sensirion sht = Sensirion(dataPin, sclkPin);

    uint16_t rawData;
    float temperature;
    float humidity;
    float dewpoint;

    byte shtState = 0;
    byte ledState = 0;

    unsigned long curMillis;               // Time interval tracking
    unsigned long trhMillis = 0;
    unsigned long blinkMillis = 0;

    void setup()
    {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);
      delay(15);                           // Wait at least 11 ms before first cmd
    //  sht.writeSR(LOW_RES);                // Set sensor to low resolution
      sht.measTemp(&rawData);              // Maps to: sht.meas(TEMP, &rawData, BLOCK)
      temperature = sht.calcTemp(rawData);
      sht.measHumi(&rawData);              // Maps to: sht.meas(HUMI, &rawData, BLOCK)
      humidity = sht.calcHumi(rawData, temperature);
      dewpoint = sht.calcDewpoint(humidity, temperature);
      logData();
    }

    void loop()
    {
      curMillis = millis();

      if (curMillis - blinkMillis >= BLINKSTEP) {    // Time to toggle the LED state?
        ledState ^= 1;
        digitalWrite(ledPin, ledState);
        blinkMillis = curMillis;
      }

      switch (shtState) {
      case 0:
        if (curMillis - trhMillis >= TRHSTEP) {      // Start new temp/humi measurement?
          sht.meas(TEMP, &rawData, NONBLOCK);
          shtState++;
          trhMillis = curMillis;
        }
        break;
      case 1:
        if (sht.measRdy()) {                         // Process temperature measurement?
          temperature = sht.calcTemp(rawData);
          sht.meas(HUMI, &rawData, NONBLOCK);
          shtState++;
        }
        break;
      case 2:
        if (sht.measRdy()) {                         // Process humidity measurement?
          humidity = sht.calcHumi(rawData, temperature);
          dewpoint = sht.calcDewpoint(humidity, temperature);
          shtState = 0;
          logData();
        }
        break;
      default:
        Serial.println("How did I get here?");
        break;
      }
    }

    void logData() {
      Serial.print("Temperature = ");   Serial.print(temperature);
      Serial.print(" C, Humidity = ");  Serial.print(humidity);
      Serial.print(" %, Dewpoint = ");  Serial.print(dewpoint);
      Serial.println(" C");
    }

 How can I extend it for **_two_** sensors (by using of another pins, of course)?

title: Sensirion library for SHT7x humidity sensor

Answers: 1

body: You simply create a second instance of the object with different pins and store the result in a different set of variables. Any extra logic of when to do what is purely down to you.


body:
I have a MQ135 gas sensor from keyestudio, and a light sensor from a chinese manufacturer. They are both on their own PCB with resistors, small eeprom and a variable pot.

Turning the variable pot fine tune the calibration of the sensor, but is there anyone who could explain me exactly what is it doing? Does it have an effect on signal amplification? or only adding more or less resistance to the signal output by the light sensor in order to fine tune the reading ?

title: What is the variable pot exactly for in arduino sensors boards?

Answers: 2

body:
It's for sensitivity adjustment.

[![enter image description here][1]][1]

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

body: If the resistance is higher, your LDR (light sensor) will respond in smaller increments or decrements to the same light changes. Analog inputs have 10 bit (0-1023) resolution, which is fine, but LDRs can be tricky (their sensitivity varies), so a pot is useful for prototyping the resistance you need to wire it up with in your project.


body:
I have a project where I'm looking to power 120 RGB LEDs in a strip (WS2812B).

Obviously an Arduino Micro cannot supply this amount of current so I'm looking to use an external 5V/4A switching power supply (wall-wart) to power the LED's as well as the Arduino.

My question is, can I just split the power from the wall-wart providing 5v_reg directly to the 5V pin on the Arduino Micro and 5v_reg to the LEDs Vss?

It it necessary to use extra bypass capacitors in this case?

title: External power supply?

Answers: 1

body:
> My question is, can I just split the power from the wall-wart providing 5v_reg directly to the 5V pin on the Arduino Micro and 5v_reg to the LEDs Vss?

Yes. As long as it is a clean regulated 5V supply.

> It it necessary to use extra bypass capacitors in this case?

No.


body:
Can I power my Arduino using a 5V/2A adapter by connecting it through the USB port?

More precisely, I have to run a module requiring 200mA but the aim is to make the laptop independent.

title: Supplying power to arduino by 5V and 2A adapter

Answers: 2

body:
I'm not quite sure what the second half of your question is saying, but:

> can i power my Arduino by 5 volt 2 amp adapter by connecting it through the usb port

Yes, you can.

body: Amps are not "forced" through a circuit like volts are. A closed circuit draws as much power (in amps) as it needs, so the only problem you could ever have is having too *little* current and not too much. Seeing as your module draws 200ma 2 amps to power it is plenty.


body:
I am having a very weird and frustrating issue with this ESP01. I am creating a shield on protoboard, and everything checks out as far as I can tell. I am using a 3.3v voltage divider (1k and 2.2k) from arduino TX to ESP RX.

When I connect the ESP straight to the arduino Mega 2560, it works fine. When I connect the ESP to my protoboard, the blue led stays lit. Now here's he weird part.

I broke out the protoboard header with jumpers to the ESP, 3.3v to vcc and ch_pd, gnd to gnd in my header. Bypassing the logic voltage divider on my protoboard results in a working ESP8266.

While still powered up, I moved the Tx/Rx to the header, through the voltage divider, and it still works! But when I disconnect USB from the Arduino, then reconnect, the blue led stays lit, until I bypass the voltage divider, connect to the ESP, then connect back to the divider.

I am currently testing my code with a simple serial relay sketch, ESP on Serial3.
I have nothing else connected to ESP besides vcc, ch_pd, gnd, tx and Rx.
I am connecting to the arduino and ESP on 115200 baud. The ESP replies without garbage on 115200 when connected straight to Serial3 rx/tx

I thought insufficient power may have been an issue, using the mega's 3.3v for vcc, so I built a voltage regulator circuit converting a 9v battery to 3.3v (well 3.75, using an LM317T with R1=330ohm/R2=660ohm because it's what I had on hand) and there was no change in performance, besides the LEDs being slightly brighter. The ESP still functioned with RX/TX straight to the mega while connected to the 3.75v supply.

I know pics would help a lot, and I can post some later tonight after work. My wife, sensing my frustration, told me to set everything down and go to work so I wouldn't break anything, so I am asking around for possible fixes for when I get home.

I appreciate any and all replies, and will provide any necessary clarification.

Thanks,
Vl4d

title: EPS8266 ESP-01 Blue led stays lit unless 3.3v logic divider is bypassed, works when reconnected

Answers: 2

body:
A wiring diagram would help.

Also, measure the 3.3v regulator's output, especially under load; 9v batteries are best in low-drain long-life applications like smoke detectors. Another supply, perhaps Arduino's 5v supply, might be a better source for the 3.3v regulator.

body: I would also check the ground on the components. All of the ground pins need to be connected together. IC's get flakey with grounding issues.


body:
I would like to connect a headphone jack to my Arduino and make it as an output. I mean I would simply send some simple beeps.

I know that there is a breadboard friendly headphone jack, but I don't know how to wire it. I really don't know if I can simply connect the Arduino to the headphone jack, or I will need some resistors, etc. Will I need some voltage measurements?

Also, can I do this simply by connecting the parts of the jack ( right, left, GND) to the Arduino?

So could you please help me with this?

title: How to connect Arduino to headphone jack?

Answers: 2

body:
[This][1] project connects the headphones directly to a digital pin.  Here is the schematic:

[![enter image description here][2]][2]

I would, however, be more cautious and add a limiting resistor.  The output of an Arduino pin should be limited to 20mA as stated [here][3]. So, using

> V=I*R
>
> 5 = 0.02 * R
>
> R = 5 / 0.02
>
> R = 250ohms

So I would add a ~250ohm resistor in series with the head phone.  Especially if I were debugging my code.  That is, in case I accidentally left the output pin high for an extended period of time.

The head phones should have some DC resistance.  If the sound is not loud enough you might measure that DC resistance of the head phones and subtract it from the 250 ohm resistance calculated above and use a limiting resistor of that value instead.

  [1]: http://www.echanter.com/home/howto-build
  [2]: https://i.stack.imgur.com/oWNwS.png
  [3]: https://www.arduino.cc/en/Main/ArduinoBoardUno

body:
I had the same problem and here how I figured out a solution,

Assume your stereo jack is connected to the folowing pins;
Pin 9 = Left stereo
Pin 10 = Right stereo
GND = Ground

The solution relies on using arduinos inner circuitry.
Pin 9 and Pin 10 are our pins to control left and right stereo sounds.
We need a third pin which will be the main output source for stereo both(left and right) condition.

Say this pin be Pin8.
Connect Pin8 to Pin9 and Pin10 by two resistors of 1kOhm or similar depending on your sound level choice.

When you seet pin8 mode to OUTPUT, pin 9 and pin 10 modes to INPUT, and when you play a tone  at pin8 as tone(pin8,duration,frequency) will play stereo on the headphone.

On the other hand if pin9 is set to OUTPUT and pin10 set to INPUT, playing tone at pin8 will flow the current through right pin of the stereo jack, right sound.

Similarly if pin10 is set to OUTPUT and pin9 is set to INPUT,and tone played at the pin8 send the current through left stereo jack connected to pin9, left sound is played.

Hope this helps.