message:
Programming Problem with a hand gesture controlled robot; the analogwrite() function doesn't work

So I recently tried to make a hand gesture controlled robot but ran into some programming error. Here are the specs:

For the transmitter module, I used the following:

   *Arduino Nano 3.0 as the Microcontroller development platform
   *Grove 3 axis digital accelerometer 16g for sensing hand gesture
   *RF transmitter 433 Mhz (Transmitter: JMR-TX1)
   *Power source: 7.2V rechargeable battery unit to power up the Arduino Nano

For the robot, I used the following:
  *Pololu Chassis
  *Two DC geared motors, compatible wheels
  *L293D Dual DC motor controller module
  *Arduino Nano 3.0
  *RF receiver 433 Mhz (Receiver: RXB6)
  *Power source: 7.2V rechargeable battery unit to power up the Arduino Nano

I hooked up all the parts carefully. I uploaded the code entitled "Transimitter_code" to the transmitter. I uploaded a code called "Receiver_test" and used serial monitor to see if the robot's arduino received data from the transmitter, the data I wanted to receive was the angle that the accelerometer was tilted on x and y axis measured by the accelerometer. Fortunately, the Arduino was receiving data wirelessly and displaying it in the serial monitor, which means my basic concept was ok. You can see the code attached to this thread. P.s. You will need three libraries: Wire.h, VirtualWire.h and ADXL345.h to run the codes. You can google them up and get them for free. **See the code for the transmitter below:**

    /* Code for the transmitter of the mind controlled bot */

    #include <Wire.h>
    #include <ADXL345.h>
    #include <VirtualWire.h>

    ADXL345 adxl; //variable adxl is an instance of the ADXL345 library
    int ledPin = 13; //a sign when the transmitter is working

    int TX_PIN = 11;// Tell Arduino on which pin you would like to Transmit data NOTE should be a PWM Pin
    int TX_ID = 3; // Transmitter ID address

    typedef struct roverRemoteData// Data Structure
    {
     int    TX_ID;      // Initialize a storage place for the outgoing TX ID
     int    x1;// Initialize a storage place for the first integar that you wish to Send
     int    y1;// Initialize a storage place for the Second integar that you wish to Send
    };

    void setup() {
     vw_setup(2000);//Bits per second
     pinMode(ledPin,OUTPUT);
     vw_set_tx_pin(TX_PIN);// Set Tx Pin
     Serial.begin(9600);//Initialise the serial connection

     adxl.powerOn();

    //set activity/ inactivity thresholds (0-255)
    adxl.setActivityThreshold(75); //62.5mg per increment
    adxl.setInactivityThreshold(75); //62.5mg per increment
    adxl.setTimeInactivity(10); // how many seconds of no activity is inactive?

    //look of activity movement on this axes - 1 == on; 0 == off
    adxl.setActivityX(1);
    adxl.setActivityY(1);
    adxl.setActivityZ(1);

    //look of inactivity movement on this axes - 1 == on; 0 == off
    adxl.setInactivityX(1);
    adxl.setInactivityY(1);
    adxl.setInactivityZ(1);

    //look of tap movement on this axes - 1 == on; 0 == off
    adxl.setTapDetectionOnX(0);
    adxl.setTapDetectionOnY(0);
    adxl.setTapDetectionOnZ(1);

    //set values for what is a tap, and what is a double tap (0-255)
    adxl.setTapThreshold(50); //62.5mg per increment
    adxl.setTapDuration(15); //625us per increment
    adxl.setDoubleTapLatency(80); //1.25ms per increment
    adxl.setDoubleTapWindow(200); //1.25ms per increment

    //set values for what is considered freefall (0-255)
    adxl.setFreeFallThreshold(7); //(5 - 9) recommended - 62.5mg per increment
    adxl.setFreeFallDuration(45); //(20 - 70) recommended - 5ms per increment

    //setting all interrupts to take place on int pin 1
    //I had issues with int pin 2, was unable to reset it
    adxl.setInterruptMapping( ADXL345_INT_SINGLE_TAP_BIT,   ADXL345_INT1_PIN );
    adxl.setInterruptMapping( ADXL345_INT_DOUBLE_TAP_BIT,   ADXL345_INT1_PIN );
    adxl.setInterruptMapping( ADXL345_INT_FREE_FALL_BIT,    ADXL345_INT1_PIN );
    adxl.setInterruptMapping( ADXL345_INT_ACTIVITY_BIT,     ADXL345_INT1_PIN );
    adxl.setInterruptMapping( ADXL345_INT_INACTIVITY_BIT,   ADXL345_INT1_PIN );

    //register interrupt actions - 1 == on; 0 == off
    adxl.setInterrupt( ADXL345_INT_SINGLE_TAP_BIT, 1);
    adxl.setInterrupt( ADXL345_INT_DOUBLE_TAP_BIT, 1);
    adxl.setInterrupt( ADXL345_INT_FREE_FALL_BIT,  1);
    adxl.setInterrupt( ADXL345_INT_ACTIVITY_BIT,   1);
    adxl.setInterrupt( ADXL345_INT_INACTIVITY_BIT, 1);
    }

    void loop()
    {
    struct roverRemoteData payload;
    payload.TX_ID = TX_ID; // Set the Radio Address
    int x, y, z;
    adxl.readXYZ(&x, &y, &z); //read the accelerometer values and store them in variables  x,y,z
    payload.x1 = x;
    payload.y1 = y;
    vw_send((uint8_t *)&payload, sizeof(payload)); // Send the data
    vw_wait_tx();// Wait for all data to be sent
    if ((x>80) || (x<-80) || (y>80) || (y<-80))
    {
    digitalWrite(13, HIGH); //ledpin indicator
    }
    else
    {
     digitalWrite(13, LOW);
    }
    delay(100);

    }

Now, I tried to use the received data to control the motion of the bot, that is: run the motors in specific direction. However, this time, the code seems to have some problem. **Here's the code for the robot**:

    /* Mind controlled car - Car's code */

    #include <VirtualWire.h>

    int RX_PIN = 11;// Tell Arduino on which pin you would like to receive data NOTE should be a PWM Pin
    int RX_ID = 3;// Recever ID address
    int TX_ID;

    typedef struct roverRemoteData// Data Structure
    {
    int    TX_ID;      // Initialize a storage place for the outgoing TX ID
    int    x1;// Initialize a storage place for the first integar that you wish to Send
    int    y1;// Initialize a storage place for the Second integar that you wish to Send
    };

    void setup() {
    pinMode(5, OUTPUT); //in 1
    pinMode(6, OUTPUT); //in 2
    pinMode(9, OUTPUT); //in 3
    pinMode(10, OUTPUT); //in 4
    Serial.begin(9600);
    vw_setup(2000);// Setup and Begin communication over the radios at 2000bps( MIN Speed is 1000bps MAX 4000bps)
    vw_set_rx_pin(RX_PIN);// Set RX Pin
    vw_rx_start();

    }

    void loop() {

    struct roverRemoteData receivedData;
    uint8_t rcvdSize = sizeof(receivedData);//Incoming data size
    vw_wait_rx();// Start to Receive data now
    if (vw_get_message((uint8_t *)&receivedData, &rcvdSize)) // Check if data is available
    {
    if (receivedData.TX_ID == RX_ID) //Check if the radio signal recieved matches the ID of the Reciever
    {
      if (((receivedData.x1 < 80) && (receivedData.x1 > -80)) && ((receivedData.y1 < 80) && (receivedData.y1 > -80))) //halt
      {
        halt();

      }
      else if (((receivedData.x1 < 80) && (receivedData.x1 > -80)) && (receivedData.y1 > 80)) //forward
      {
        int a = receivedData.y1;
        goForward(a);

      }
      else if (((receivedData.x1 < 80) && (receivedData.x1 > -80)) && (receivedData.y1 < -80)) //backward
      {
        int b = -receivedData.y1;
        goBackward(b);

      }
      else if ((receivedData.x1 > 80) && ((receivedData.y1 < 80) && (receivedData.y1 > -80))) //left
      {
        int c = receivedData.x1;
        goLeft(c );

      }
      else if ((receivedData.x1 < -80) && ((receivedData.y1 < 80) && (receivedData.y1 > -80))) //right
      {
        int d = -receivedData.x1;
        goRight(d);

      }
      }
      }
      }

      void goForward(int y)
      {
      analogWrite(5, y);
      analogWrite(6, 0);
      analogWrite(9, y);
      analogWrite(10, 0);
      delay(50);

      }

      void goBackward(int z)
      {
      analogWrite(5, 0);
      analogWrite(6, z);
      analogWrite(9, 0);
      analogWrite(10, z);
      delay(50);

      }

      void goLeft(int w)
      {
      analogWrite(5, w);
      analogWrite(6, 0);
      analogWrite(9, 0);
      analogWrite(10, 0);
      delay(50);

      }

      void goRight(int x)
      {
      analogWrite(5, 0);
      analogWrite(6, 0);
      analogWrite(9, x);
      analogWrite(10, 0);
      delay(50);

      }

      void halt()
      {
      analogWrite(5, 0);
      analogWrite(6, 0);
      analogWrite(9, 0);
      analogWrite(10, 0);
      delay(50);

      }

**I wanted to use the analogWrite() function to control the speed of the motor. However, the code does not work at all if I use the analogWrite() function within the goForward(), goBackward(), goLeft(), goRight() functions to control the speed of the motor, only one of the motors keeps rotating at a certain speed without responding to the transmitter. Surprisingly, if I use digitalWrite() to control the motors, they work fine, instantly responding to the change in direction of the transmitter. P.S. I connected my motors to PWM pins of the Arduino.**

**What's the problem?**

body: VirtualWire uses timer1, which would disable PWM on pins 9 and 10.


sender: user

message:
Compile Error for Arduino Mega

I am using the Arduino IDE 1.6.0,
There is a project that has compiled both for Due and Mega on another computer. But on my machine, it only compiles for Due. When compiling  for "Mega or Mega 2560", I get the following error:

>/Arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld: skipping incompatible /Arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/lib/libc.a when searching for -lc
    /Arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld: cannot find -lc
    collect2: error: ld returned 1 exit status
    Error compiling.

My newbie guess is something is wrong with AVR libraries. But how to solve it? Also could someone please explain what `-lc` is, which cannot be found? At first glance it looks like an option.

sender: assistant

body:
So what I did that solved the problem was, I downloaded the latest Arduino IDE, titled "**Windows ZIP file** for non admin install". Then I unzipped the download, and I copied all of the files of the new IDE and pasted them into the old installation. But I did not replace anything. i.e. For each file that existed, I kept the old file.

~400 new files were copied. Now it compiles without error.

BTW since this has been a blind workaround, I will not accept this as the final answer.


body:
tldr; `-lc` means "link with the `libc.a` library"

The compiler takes your source code (`*.c`, `*.ino`) and produces "object" files ending in `*.o`.

The linker takes those compiled modules and links them all together to make the final executable, linking symbols in one file (such as variable references and function calls) with the definitions in the others (the actual variables and functions). But it also takes libraries - predefined collections of object files - and links those in as well, if necessary.

Libraries are files of the form `lib*.a` (`a` is for "archive"), and are distributed by software vendors as easy containers for their modules. The compiler/linker itself also uses them as the implementations for languages features such as `printf()` and `digitalWrite()`. The most fundamental library is `libc.a` - the library containing the standard C implementation.

When you want to get the linker to use a library, you give it the `-l` option, with the library name appended (not including the `lib` prefix and `.a` extension). In short, `-lc` means "link with the `libc.a` library".

But if your development machine has support for numerous processors, there will be a number of `libc.a` files on it - how does the linker know where to look? Another linker option is `-L` (note uppercase), which defines the directories to look in to find libraries. The linker will look through the directories in turn until it finds the referenced library.

If you attempt to link modules that have been compiled for different processors, you will get linker errors when it does a sanity check. The reason your fix worked is because it now uses the correct directories to find what it is looking for.


body:
I think you have included some libraries in the sketch. The problem is that one of the libraries doesn't support the Arduino Mega.

As a solution, I suggest you to comment out the libraries one by one and then try to compile the program. If code runs successfully,try to install that library with other versions. Don't forget to remove the previous library.


message:
How to run stepper motor at its maximum speed

I am running a stepper motor using arduino and IC l293d. What is the maximum possible speed of rotation that I can achieve with the IC and what should be the applied voltage for the same? Earlier, I got the optimum rotation with a step size of 30 at 7V. I want to increase the step size. What should I do?

body:
As [this link][1] states:

> Stepper motors are normally used for positioning, and are not known
> for their speed.

However, the link is to an on line stepping motor speed calculator.

As for the size of the step, this is a function of the way the stepping motor is built.  Some controllers / stepping motor combinations can do half steps or micro steps.  Disable these feature for the fewest number of steps per revolution.

These are some of the basic concepts which deal with practical stepping motor applications.  As speed increases, other factors come into play.  For example, resonance and inductance.

In [this paper][2] resonance is discussed:

> If a rigidly mounted stepping motor is rigidly coupled to a
> frictionless load and then stepped at a frequency near the resonant
> frequency, energy will be pumped into the resonant system, and the
> result of this is that the motor will literally lose control.

The paper also discusses the effect of the stepper motor's coil inductance:

> An important consideration in designing high-speed stepping motor
> controllers is the effect of the inductance of the motor windings. ...
> The inductance of the motor winding determines the rise and fall time
> of the current through the windings. ...

  [1]: http://www.daycounter.com/Calculators/Stepper-Motor-Calculator.phtml
  [2]: http://homepage.cs.uiowa.edu/~jones/step/physics.html


body:
The speed of the stepper motor (assuming you measure it in RPM) will depend on many factors. I am not sure how the "30 step size at 7V" you mention is relevant.

IMHO, the most important parameters are

1) physical parameters of motor (steps per revolution, rated voltage, motor intetia)

2) Load on the motor

3) software implementation

Normally you shouldn't be able to affect 1( if you are looking like most arduino's developers you should be looking at things like [this][1]. i.e. 200 steps per revolution, 5-12VDC and a few tens to hundreds of g*cm^2 or motor inertia.) or 2 (although with higher loads lower velocities can be achieved, normally you select the motor based on the load and not vice versa).

Therefore you are left with Software implementation. Things here can get messy very quickly depending on how experienced you are and what you want to do.
e.g. The arduino Stepper library is simple and you can set parameters but it is blocking (i.e. you can't do anything else until movement is completed, or interrupts are used).

If you want to get your hands dirty (and your head messed up ;-/ ) you can looks at

- Arduino timers

- micros(), and millis() for updating the steps yourself. (Have a look at [here][2] and [here - shameless plug][3])

- pin registers (for increasing speed) [here][4].

My experience is that normally you can get up to 150 [rpm] easily. Theoretically you should be able to go higher but the uC should be doing pretty much nothing else.

  [1]: http://www.oddwires.com/nema17-stepper-motor-for-arduino/
  [2]: http://www.mauroalfieri.it/elettronica/motor-shield-r3-arduino.html
  [3]: https://bitbucket.org/npapnet/ard.lib.bipolarsteppermotorasync
  [4]: http://tronixstuff.com/2011/10/22/tutorial-arduino-port-manipulation/


message:
How do I reset an ESP8266 with an FTDI and no reset button?

I assume that it has something to do with the reset pin on the ESP8266, but I cannot find a step-by-step usage of the pin online.

body:
Pull the reset pin up by connecting it to 3.3v with a 10k ohm resistor, then to reset the ESP you temporarily ground the pin, bringing it down to 0v/GND.
I'd recommend putting in a button for that :)


message:
How to include <SPI.h> outside the .ino file

As I understand, Arduino IDE considers two paths for the libraries:

first,

> "C:\Program Files\Arduino\libraries"

and second, the "libraries" folder next to the schetchbook.

I have a configuration.h file, that I include in the main file, `Test.ino`, like this:

    #include <configuration.h>

and in the `configuration.h` file I try to include `SPI.h` like this:

    #include <SPI.h>

But I get the following error:

    fatal error: SPI.h: No such file or directory

It seems that I am obliged to include `SPI.h` only from the ino file. But why?
And how can I do what I want here? do I have to change IDE?

P.S: the software is large and I am improving maintainability.

body:
> It seems that I am obliged to include SPI.h only from the ino file. But why? And how can I do what I want here? do I have to change IDE?

The background is how the Arduino IDE pre-processor works together with the GCC AVR compiler and build tools.

The compiler needs to know the include path to the libraries. This is created by the pre-processor by scanning the ino file and searching the known libraries. A compiler command line is built with the include paths to the located libraries.

If you move the library includes to a configuration file the IDE pre-processor will not be able to locate the libraries and create the include paths. The pre-processor does not recursively scan library files.

Cheers!


body:
See my answer [How the IDE organizes things](https://arduino.stackexchange.com/a/13182/10794). There is no easy way to avoid having to put an include in the main .ino file, unless you write your own build process (or perhaps use another toolchain).

I think you could put SPI.h (and other things, like Wire.h) in the main .ino file, even if they aren't used due to your configuration parameters. The linker would strip them out because the modules were not referenced.


body:
The IDE has to be explicitly told each and every library that you use. It also has to be told each and every library that every library that you use uses. And so on.

The Arduino IDE only looks in the INO files. As a result: if the library is not included in the main INO file then the IDE doesn't know that you intend to use it, and so it doesn't look for it.
Only when it's in the INO file will the IDE actually look for where that library is located and append the right flags (-I...path...) to the compilation commands to be able to get at the files for it.

Further, it is only then that it actually knows that it should compile the source code for a library. Without that knowledge, even if you explicitly point to the header file with a relative path, the IDE won't know that it should compile and link the source code.

There is no way around it, it's just the way the IDE works. The only option is to change to a different IDE that has more intelligence and can recursively deep-scan the libraries to maintain a list of prerequisites (such as my popular [UECIDE](http://uecide.org) IDE).


message:
does eeprom_write_block function of avr.eeprom.h writes a NULL terminated string or we have to manually null terminate it

http://www.nongnu.org/avr-libc/user-manual/group__avr__eeprom.html

I am trying to figure out that if we use `eeprom_write_block` function or `eeprom_update_block` function do we need to manually null terminate it?

I came across [this tutorial on avr-freaks][1] where in one comment it is said that you have to read the strings and null terminate them but there is no word about writing. Couldnt get anything the avr-libc manual as well.

**UPDATE**

I have reserved some parts of eeprom using `EEMEM`  and they are strings. I am not sure how long the string would be except that it would be smaller than a max value. Now When I would read the string back from the eeprom I would just be reading the maximum number of bytes as again I would have no idea of the size of the string. If the eeprom has a null value at the end of the string when writing to it, the read string will have that null at the correct place.

**Situation**

I am saving mobile numbers of users as:

    uint8_t EEMEM users[numberOfUsers][maxChar4Number];

Now when I get a number parsed and then save it to eeprom

    #define eepu(message, EEADDR, BLKSIZE) eeprom_update_block((const void *)message, (void *)EEADDR, BLKSIZE);

    eepu(user, users[0], strlen(user)); //strlen(user) will be less than the maxChar4Number

 This will write the number to eeprom. When I read the i would be reading maxChar4Number bytes and a number could have been shorter than that length.

  [1]: http://www.avrfreaks.net/forum/tut-c-using-eeprom-memory-avr-gcc

body:
Since one normally does not know how long a character string is, we need a way to convey this information.  One technique used to avoid confusion is to add a NULL character (which is a zero) to the end of the string.  Another is to explicitly state how long the string is.

In the case of the function eeprom_write_block() talked about [here][1], we see that we are formally passing not only a pointer to the string but also the size of the string.

  [1]: http://playground.arduino.cc/Code/EEPROMWriteAnything


body: If you write a block which happens to be null-terminated, then reading it back should be fine. I do that when I want to save a filename in EEPROM. Just declare a suitable length (allowing room for the null terminator) and write the entire block to EEPROM.


message:
Controlling a NC connection from two sources?

I'm trying to control a garage door opener. The button that lets you open the door from the inside is a NC connection (press the button and it goes to "open" and makes the motor run).

I want to keep that AND add another source (an Arduino w/ an RF module) that taps in to this.

Is there some sort of splitter I'd add to the garage door button wires to do this?

body:
Are you certain that your existing circuit is NC?

The typical garage door opener button is a momentary switch. Many third party remote devices, including two that I have installed, tap directly into this circuit. Because the contacts short across the existing switch, activating one, two or three is insignificant. These switches are connected in parallel.

It would be a good idea to use an external isolation circuit to the Arduino, either a relay or SSR in order to ensure that there is no "injected" power from your circuit to the garage door circuit.

If your circuit is indeed an NC type, you would connect your new relay or SSR in series, using the device's NC connections. The locations for tapping into the circuit would be where your existing button resides or where those two wires engage your garage door mechanism.

I suppose my older garage door opener is NO, while newer models would use a different architecture, aka NC.


message:
Potentiometer on motor for position control

I am using a wiper motor as a rotor. I am trying to get it to at least point in different azimuths (compass azimuths eg. 180 degrees) In order to do this, I am thinking about attaching a potentiometer on the axle inside the motor housing to see where the motor is pointing.

So lets say the pot gives me a range of 0-1023. If I divide 1023 by 360 i get 2.84. So lets say the pot gives the Arduino a 1, I can relate that to 2.84 degrees?

Also, what if the motor is pointing at 350 degrees, and I want it to point at 2 degrees. Instead of it turning around 348 degrees, it just cross pass 360 and go to 2 degrees.  How would a pot handle going over a single step? If the motor passed a single step would it consistently give me a 1023 reading?

I am trying to get a wiper motor to have a known position 360 degrees around.

body:
> So lets say the pot gives the Ardunio a 1, I can relate that to 2.84
> degrees?

Yes, if the pot goes from 0 to 1023 in 360 degrees of rotation, and it can rotate continuously. That sounds unlikely - f/ex, thinking about how a pot is made, how will it get from its maximum resistance to its minimum resistance in 2.8 degrees?

> Instead of it turning around 348 degrees, it just cross pass 360

Smart software. :) You would need to read the pot, decide which direction of rotation will get from the current position to the new position, and select that direction in the motor drive circuit.

Update:
A pot doesn't really "output" anything; it is a variable-resistor, whose resistance can be measured by placing it in a known electric circuit and using an Arduino A2D input to measure a voltage in that circuit which depends on the resistance of the pot. The reading you get is a 10-bit integer. If you divided that by 1024, you'd have a pure fraction representing the measured voltage as a fraction of the A2D's full-scale voltage, which you select as INTERNAL (1.1v internal reference voltage), or EXTERNAL and apply a reference voltage to the chip's Aref pin. Usually that is the power-supply voltage, and in any case must not exceed the power-supply voltage.

So, back to reality, if you use the EXTERNAL reference with Aref connected to +5v, then the A2D readings would mean:

<pre>
 A2D  Volts  Mag.Azimuth
   0   0       0
 256   1.25   90
 512   2.5   180
 768   3.57  270
1023   4.99+ 359.6
</pre>

In this case you probably don't care about the measured voltage, only it's relationship to 5v, which the A2D already gives you. That relationship equals the pot's relationship to 1 full rotation. So the azimuth, Az, you're seeking:

Az/360 = A2D / 1024, and

Az = (A2D * 360)/1024


body:
> I am trying to get a wiper motor to have a known position 360 degrees around.

There might be a few possibilities.

First there **are** continuous rotation potentiometers on the market. They seem expensive though and I can't comment on how accurate they are.

Second, **if** your device is only ever going to turn through say ten revolutions then go back, you could just get a multiturn pot that will handle that range of turns. (Depends what you're building of course - for example I've heard of servo winches for model sailboats that use this method.)

Thirdly, and I accept this may not be a good answer to your question, but have you thought about using incremental encoders instead? In theory they could be more accurate too. The hardware is quite easy but a bit more programming is required to make these work...


message:
HM-10 discovery issue

i am not able to detect any android device on my bluetooth HM-10 module which is connected to arduino. i am able to see my bluetooth module on my android phone. but i want to see android phones on arduino serial monitor for that i used AT+DISC? command. it shows AT+DISCS and than AT+DISCE with a 2 second interval. help me to solve the issue
thanks in advance

body:
The HM-10 is a BLE-only device.

Android phones do not normally transmit BLE advertisements, so there is normally nothing about an Android phone for it to discover.

The exception would be if you have software on a late Android version with the capability, which you have set up to intentionally transmit BLE advertisements, or else if software you put on your Android phone is actively responding to advertisements you had the HM-10 transmit.

Essentially, you are expecting something that his not normal behavior, but will only be achieved by adding your software on *both* devices.


message:
Not getting data from GPS

When I run FullExample program from TinyGPS++, I get following types of entries,

    Sats HDOP Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum
              (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail
    ---------------------------------------------------------------------------------------------------------------------------------------

    0    9999 ********** *********** **** 07/01/2016 07:32:50 689  ****** ****** ***** ***   ******** ****** ***   75128 0         0
    0    9999 ********** *********** **** 07/01/2016 07:32:51 857  ****** ****** ***** ***   ******** ****** ***   75389 0         0
    0    9999 ********** *********** **** 07/01/2016 07:32:52 864  ****** ****** ***** ***   ******** ****** ***   75642 0         0
    0    9999 ********** *********** **** 07/01/2016 07:32:53 870  ****** ****** ***** ***   ******** ****** ***   75895 0         0
    0    9999 ********** *********** **** 07/01/2016 07:32:54 878  ****** ****** ***** ***   ******** ****** ***   76148 0         0

Other details:

GPSBaud = 9600;

RXPin = 11;

TXPin = 10

Module: GY-NEO6MV2

body:
That is a ***perfect*** printout of a GPS system that can see **zero** satellites.

The fact that the timestamps are one second apart shows that you have correctly interfaced with the GPS device. Now, the GPS device has to 'interface' with the satellites!

Many people don't realise two things:

1. The GPS antenna really does need a clear view of the sky. A tiny view through a window may show one or two satellites, but you need a minimum of three, and preferaby four or more at a number of points around the sky to get a fix.
2. If the GPS unit has been completely powered off (called 'cold'), when it first powers on it has NO idea where anything is. It simply listens for any signal anywhere until it "hears" the current time. It can then guess where satellites might be, and listens for updates on satellite positions.

All of this listening, guessing and waiting takes time before it can start to actually lock on to satellites and start to get a fix. This time could easily be 90 seconds or more - you need to be patient. Check your GPS device specifications for "cold start" times.

### Edit
I'm impressed! The GY-NEO6MV2 that you list has a cold-start of 27 seconds - but that assumes it has a clear view of the sky.


body:
The GPS actually seems to be getting some data: the date and time.
Which means it can be used to set the time (and date) in a clock if the timezone is known without needing a fix (useful inside).


message:
Arduino i2c communication between another arduino and a sensor

Can the following scenario exist?
[![enter image description here][1]][1]
Microcontroller 1 sends a code to microcontroller 2 to start reading sensor data. Then Microcontroller 2 reads sensor data from sensor and sends it back to microcontroller 1.

If such a scenario is possible, then how would the pseudo code for microcontroller 2 receive-event be?

Need help with this badly!!

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

body:
>Can the following scenario exist?
Yes. Such a scenario is called *Multi-Master*.

>If such a scenario is possible, then how would the pseudo code for microcontroller 2 receive-event be?

MCU 2 would just be set up as any other slave. It waits, as normal, for an instruction in whatever for you like. Once it receives that instruction in then switches into master mode and makes a normal request exactly as you would from MCU 1 if you wanted it to read the sensor.

* On receive:
    * Set "run as master flag"
    * Disable slave mode

In loop:

* If "run as master flag" is set:
    * Perform request to get data from sensor
    * Clear "run as master flag"
    * Enable slave mode

Running a multi-master system does have its own set of caveats and things you have to watch out for. You can read more about it here:

* https://www.hackster.io/chipmc/arduino-i2c-multi-master-approach-why-and-how-93f638


message:
I want to play a sound based on my ultrason sensor reading

The idea is to play the tone that is given by the center value read it by the center ultrasound sensor.

The code that is in Arduino is this one:

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

    #include NewPing.h

    #define PING_CENTER  2  // Arduino pin tied to both trigger and echo pins on the ultrasonic sensor.
    #define PING_RIGHT  3
    #define PING_LEFT  4
    #define PING_MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
    #define buzzerPin = 10

    long buzzerFreq1; // The frequency to buzz the buzzer
    unsigned int BUZZ_FREQ_MAX = 2500; // Maximum frequency for the buzzer
    unsigned int US_MAX = 2023; // Maximum value for ultrason sensor
    int c1;

    NewPing sonar2(PING_CENTER, PING_CENTER, PING_MAX_DISTANCE); // NewPing setup of pin and maximum distance.
    NewPing sonar3(PING_RIGHT, PING_RIGHT, PING_MAX_DISTANCE);
    NewPing sonar4(PING_LEFT, PING_LEFT, PING_MAX_DISTANCE);

    void setup() {
      Serial.begin(9600);
      pinMode(buzzerPin, OUTPUT); // set pin for buzzer output
    }

    void loop() {
      buzzerFreq1 = (center * BUZZ_FREQ_MAX) / US_MAX;
      buzz(buzzerPin,buzzerFreq1,10);
      // tone(buzzerPin, center);
      delay(500);  // Wait 500ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
      unsigned int center = sonar2.ping() / US_ROUNDTRIP_CM; // Send ping, get ping time in microseconds (uS) and convert it to centimeters (cm)
      unsigned int right = sonar3.ping() / US_ROUNDTRIP_CM;
      unsigned int left = sonar4.ping() / US_ROUNDTRIP_CM;
      // Serial.println("Distance: " + String(distanceInCms) + "cm");

      Serial.println(center);
      Serial.println(right);
      Serial.println(left);

    }

     // buzz(buzzerPin, buzzerFreq1, 10);
     void buzz(int targetPin, long frequency, long length) {
     // int c1 = center;
      buzzerFreq1 = (center * BUZZ_FREQ_MAX) / US_MAX;
      long delayValue = 1000000/frequency/2;

      int numCycles = frequency * length/1000;

      for (int i=0; i < numCycles; i++){
        digitalWrite(targetPin,HIGH);
        delayMicroseconds(delayValue);
        digitalWrite(targetPin,LOW);
        delayMicroseconds(delayValue);
      }
    }

And I receive the following error that I have no idea how to solve it.

    ultrason_onewire_sound.cpp: In function ‘void setup()’:
    ultrason_onewire_sound.cpp:26:11: error: expected primary-expression before ‘=’ token
    ultrason_onewire_sound.cpp: In function ‘void loop()’:
    ultrason_onewire_sound.cpp:38:8: error: expected primary-expression before ‘=’ token
    ultrason_onewire_sound.cpp: In function ‘void buzz(int, long int, long int)’:
    ultrason_onewire_sound.cpp:48:18: error: ‘center’ was not declared in this scope

body:
`#define buzzerPin = 10` shouldn't have an `=` in it.

With the `=` `pinMode(buzzerPin, OUTPUT);` will turn into `pinMode(= 10, OUTPUT);` by the pre-processor. Which would give the error, complaining about an `=` token, you got.


body: You should use arduino built in tone command to play sounds with a buzzer, it will simplify your code and your errors.


message:
Append to .h file through arduino code

I'm at the stage where I can #include headerFiles.h into my arduino sketches.

I'm just beginning to wonder whether it's possible to append strings that are concatenated from integers which are analogRead from sensors to a .h file?

It'd make the arduino a lot more portable and would negate having to buy an SD card module.

How would the data be extracted? EEPROM is too small for datalogging past what you'd rack up in text over a reading every minute for a few hours.

Any clever clogs got ideas for this?

body:
Header files are part of your source code. The result of a build is a set of ones and zeros which are sent to your arduino and written in its Flash memory (the program space). The way you put these zeroes and ones together is completely up to you. You could write C and/or C++ code (where you have header files), you could write assembly code or you could write the zeroes and one directly on the disk, if you are crazy enough.
Header and Source files live only in the world of the developer and its toolchain, Arduino doesn't know they exist at all.

That being said, if you want to store log data you could use a SD card like you said, or send it over the network, or you could use a serial connection. But I'm sure there are plenty of other options.


body:
Header files are used to "encapsulate" functionality of your code. When you #include a header file, what you are actually doing is, as perhaps an oversimplification, "pasting" the code from that header file into your sketch above where the main code you've written in that file resides. You can then call on functions defined in the header file. Usually, at this level, you are using header files to include useful code that other programmers have contributed to a "library" that has some functionality that makes your life easier -- UART or Wire for communication, or perhaps being able to write to one of Adafruit's LCD displays with a single function call.

Programmers will also write their own header files to improve readability of their code -- for example, by encapsulating all code related to a particular functionality, perhaps troubleshooting, in one file. Another header file in the same program might, a bit ironically, be dedicated to input/output functions (but in the sense that it handles the reading and writing of data on some storage medium, such as an SD card). Header files can also #include other header files (if you're careful about how you do so).

However, header files are not usable "input/output." The compiler will read it all as one program and flash it to the Arduino just like any other code you have written.

http://www.learncpp.com/cpp-tutorial/19-header-files/


body:
> I'm just beginning to wonder whether it's possible to append strings that are concatenated from integers which are analogRead from sensors to a .h file?

No, you have the wrong end of the stick here. You can't **write** to a .h file, certainly not on the Arduino, because it is running independently of the development environment.

> It'd make the arduino a lot more portable and would negate having to buy an SD card module.

An SD module, like the one below, only costs about $US 15, and then you can write gigabytes of data to it, and then easily move the SD card to your PC to process it.

[![SD card module][1]][1]

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


message:
Driving single-character alphanumeric (16-segment) displays

I would like to drive three sixteen-segment displays (https://www.sparkfun.com/products/retired/9934) using an Arduino Micro. These displays would output an alphabetic character that a user would scroll through using rotary encoders, and constitute a subsystem of a larger project where the user enters a "combination" made from the three letters to "unlock" functionality in the larger device.

The best option, if it could be called that, is this retired product from SparkFun: https://www.sparkfun.com/products/retired/10103 that would allow me to drive the displays without a huge wiring mess, and spares me a lot of pins on the Micro to use on the rotary encoder. Unfortunately, the product is retired because the A6282 IC it was based on reached end of life, so even the schematics available on the product page aren't much use to me.

I am aware that four-character 16-segment displays are available, but for "aesthetic" reasons I am constraining myself to using single-character 16-segment displays. I do wonder how possible it would be to run three or four individual 16-seg displays from one of those LCD backpacks, but I don't think that would be trivial to do (I'd need to, probably, fabricate some sort of printed circuit board that spaced each display as far out as I need them to be, hook the pins of each display into a key matrix, and then at that point it'd be substantially easier to just get a MAX6954 (https://www.maximintegrated.com/en/app-notes/index.mvp/id/3212) and try to figure that out). It would be very clumsy to prototype.

So, I'm looking for a solid method of prototyping this "combination entry" subsystem and its 16 segment displays without needing to put each dial and alphanumeric display on its own AVR or something.

body:
If you need additional IO lines, a typical “LCD backpack” supplies at most eight additional lines of IO; [16-channel TLC59116 LED Driver Board](http://www.ebay.co.uk/itm/16-Channel-I2C-PWM-LED-Driver-Board-TLC59116-Arduino-/182090762992?ssPageName=STRK:MESE:IT) as mentioned by Majenko would be more elegant than using several backpacks.

You might try an approach like the following to see if it works well enough.

Use 16 IO lines to pull down 16 segment lines.  Use three IO lines to drive three digit-select PNP or PFET transistors for digit multiplexing.  Use pin-change interrupts on two IO lines to read rotary encoder (RE) data.  Use one input to read the RE pushbutton.  Use one IO line to notify the bigger unit of success.  Total 23 IO lines.

In operation, your code will need to implement a state machine that frequently refreshes the multiplexed digits while keeping track of digit values, selected digit, etc.  Each time you click the RE have your sketch go on to the next digit.  To tell the user which digit is working, blink the selected digit a couple of times after the RE press.  Each time that selection wraps around to the first digit, check if the combination is correct.

If you feel it's necessary to have three different digit-setting knobs, vs clicking through to each digit, you could use one less IO line by using three pots instead of one RE.  The pots would be read in analog.  A6 and A7, IIRC not usable for output lines, could be used as analog inputs for two of the pots.


body:
The other answers give great suggestions, but to add to them you could consider the MAX7219 driver chip. I have a [page about using it](http://www.gammon.com.au/forum/?id=11516). It can drive a 8x8 pixel display (like one alphanumeric character) or 8 x 7-segments displays (a 7-segment display usually has a decimal place so that is really an 8-LED display).

Example of 64-pixel display:

[![64 pixel display][1]][1]

Example of 8 x 7-segment displays:

[![8 x 7-segment display][2]][2]

Those displays come as a unit (2 x 4 digits) but there is nothing stopping you running wires to individual 1-digit displays if you want to.

Here is a possible schematic:

[![MAX7219 schematic][3]][3]

If you are running to individual displays you just parallel-up the anodes (A to G, plus DP) and run a "digit" line to the cathode of each display.

---

That will only take 3 signals from your processor (MOSI, SCK, SS) plus power and ground.

---

I notice you are talking about 16-segment displays and not 8-segment displays, but the chip allows any bit patterns to be sent out, so you could consider a 16-segment display to be the same as 2 x 8-segment displays. You would just have to make up a suitable bit-pattern to show each digit.

The MAX7219 also handles the requirement for constant-current driving of the LEDs.

  [1]: https://i.stack.imgur.com/emQHR.jpg
  [2]: https://i.stack.imgur.com/Cnt78.jpg
  [3]: https://i.stack.imgur.com/2s6UC.png


message:
Can you output to D+ and D- so that Arduino Uno can be used as a USB device?

My project is basically a set of 5 audio signals (analog) that get altered slightly by Arduino Uno. I convert to MIDI and would then output it to USB, so that it can be used in a program of my choice on the computer. I found a vaguely similar project online with a guide. In that project they write a serial to a MIDI out, and then plug that into a computer. I'm fairly sure I can't just use the TX and run that into the USB, that wouldn't work. So I'm looking for an alternative method.

body:
Not with an Uno, no. You can only use USB Serial (CDC/ACM) through the on-board USB chip[1].

Your best bet is probably with a Teensy 3 (or 3.1 or whatever they are up to now) which has built-in support for USB MIDI emulation.

----

1: I believe there is MIDI firmware for the USB chip on the Uno, but installing that requires a hardware programmer and then breaks the normal sketch upload.


body:
As noted in Majenko's answer, an Uno would require some non-trivial modifications before it would be usable as you want.

Some Arduino models – Leonardo and early Pro Micros – were based on ATmega32U4 chips instead of ATmega168 or ATmega328 chips.  The 32U4 has USB support built in.  The [Mouse and Keyboard](https://www.arduino.cc/en/Reference/MouseKeyboard) libraries allow interacting with a host computer such that from the host the Arduino looks like a mouse or keyboard.


body:
The simpler thing would be to output the MIDI through the serial port, and then convert that into MIDI voltage levels like this:

[![MIDI tx][1]][1]

Then plug that into a suitable MIDI-to-USB adapter. However I would have thought that that extra step (converting to MIDI voltage and back again) would be unnecessary. Can't your computer read MIDI directly from serial? I mean, the Uno has a USB interface. If you send MIDI data at 31250 baud, how is the program on the PC going to know it isn't a real MIDI device on the USB port?

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


message:
Connect 2 Arduino UNOs via Bluetooth? (HC-05 and HC-06)?

So I've researched this topic a lot online, but haven't found what I'm looking for. Before I tell you this, I'll give you guys an idea of what I'm trying to accomplish. Please understand that I'm an extreme beginner to Arduino, and that I've only been at this for a month or so, but plan on doing so much more.

My friend and I are building an RC car. We have an Android phone that has a downloadable application which connects to the Bluetooth HC-06 module that is on the Arduino UNO. We have configured our circuit, and it works fine! I want to go a step above and beyond, though.

My goal is to build a physical, handheld controller or remote (literally plopping everything on a breadboard), and connect that controller or remote to our car using Bluetooth. We have an HC-05 and HC-06 module, and the HC-06 is on the car. Now comes the doubt.

I understand how the android application sends characters through to the RC Car via Bluetooth; that's pretty straightforward as the two pieces are paired (using Android's Bluetooth Settings). What I don't understand is how to pair the two HC-05 and HC-06 Bluetooth modules. There isn't too much help online, I feel. I've looked and people have shown that they connect, but they don't explain the theory, so to speak.

What I want to understand is:

1. How the two HC-05 and HC-06 modules pair, and
2. How can I read input from one (remote controller) and execute an action on the other (RC car). From the app-to-Arduino, I was using `Serial.available()` to see if the Serial had any characters sent over from the application. I can't see how I can do that with HC-05 to HC-06 pairing, however. This concept is hard for me to grasp.

Any help is greatly appreciated. Thank you!

body:
1. Have a look at this for how to pair them http://www.martyncurrey.com/connecting-2-arduinos-by-bluetooth-using-a-hc-05-and-a-hc-06-pair-bind-and-link basically you need to use the AT mode.

2. As far as I know you will be using the serial connection to communicate, but if you are using UNOs debugging becomes a bit more difficult, because you can't use serial for debugging.


body:
For this you just have to pair the both bluetooth modules with each other.!
For this use AT commands.

You can find those here:
https://www.rcscomponents.kiev.ua/datasheets/hc_hc-05-user-instructions-bluetooth.pdf.

For pairing use MAC address of one module and hardcode it in second module using AT commands.
Now from theory point of view for pairing between any two bluetooth modules,there are some handshaking signals which are processed and if they are correctly processed then the device gets paired.
Its very hard to debug. But for that purpose use software serial


body:
You need to set HC-05 to master, and this done by soldering pin 34 of BT and connecting it to digital pin on Arduino to enter AT command. Then after powering the Arduino, you need to put pin 34 high. This way it will enter AT command. In serial monitor, follow these AT commands:

<!-- language: none -->

    AT+cmode=0
    AT+ROLE=1 // THIS WILL SET THE BT AS MASTER
    AT+INIT
    AT+LINK= ????,??,??????  // REPLACE ?... WITH HC-06 MAC ADDR


message:
rs485 and serial ISP

I made a couple of arduino mini pro and esp8266 pcbs with an rs485 transceiver just to find out that I forgot to think about in-system-programming:

Assuming that I don't need to disable the transceiver i tied *RE/DE to gnd/vcc. It turned out that id *do* need disable the transceiver (at least the receiving part) in order to be able to program the mcu because otherwise the transceiver disrupts the serial data.

But I don't want to lose one pin for this (which in case of an esp8266 are rare) and I don't want to use jumpers because I really like the workflow without.

Is this even possible?

EDIT: The transceiver is an SP3485.
Currently it is connected like:

    Mini Pro     SP3485
    A-rx ------  RO
    GND  --1k-- *RE   A  ---- somwhere else
    Vcc  --1k--  DE   B  ----        "
    A-tx ------  DI

Which blocks serial programming because of a) the "echo" and b) holding A-rx line high.

If I connect `*RE --1k-- Vcc` and `DE --1k-- GND` I can ISP the Arduino, but now I obviously can't use the transceiver anymore.

body:
I'm not sure why you used an RS-485 transceiver if you were only going to permanently enable the two halves? You've basically turned the RS-485 multi-drop into an RS-422 balanced pair-of-pairs. Ah well!

So you wired the transceiver to TX and RX on the ESP8266? And you want to still use those pins to reprogram it, by going "behind" the transceiver and temporarily connect them to your FTDI/whatever? Yeah, sorry: that's not going to work.

The `*RE` pin and `DE` pin only affect the balanced side of the transceiver. The `RX` and `TX` pins on the logic side are still an output and input respectively, regardless of the state of the two Enable pins.

That means that to reprogram, you're going to have to connect your development machine to the balanced side of the transceiver, and you won't have to worry about the Enable pins. Look for RS-422 USB cable adapters - they're out there!


body:
I can't understand the purpose of connecting *RE/DE to GND/Vcc. With
this setup, the driver inside the transceiver is always enabled, and
it's always driving the A/B pair. Meaning the device at the other end of
the link cannot drive the pair itself without making a collision.
Basically you have a simplex link, where the Pro Mini is always the
sender.

The normal way to connect an RS-485 transceiver is to have DE driven by
a GPIO pin of the MCU. You pull this pin HIGH when you want to talk, and
leave it LOW the rest of the time so you can hear other devices talking.
The *RE pin is connected either to GND (if you want to hear the echo of
what you say) or to DE (if you don't).

That being said, you are correct in that the transceiver may cause
problems when uploading the firmware on the Pro Mini. One possible
solution is to put a resistor between RO and A-RX. The TX of the FTDI
cable should have a low output impedance and be able to overpower that
resistor. Another option is to use ICSP (in-circuit serial programming)
instead of going through the bootloader. It would be easier if you can
put an ICSP header on your board.


message:
Problem with DHT11 and DS18B20 temperature sensors

I am trying to connect to my Arduino Uno board two temperature sensors: DHT11 and DS18B20. The problem is with the DHT11 sensor: apparently there's an error with reading the temperature every two measurements.

Here's what I get on the serial monitor (temperature 1 is from the DHT sensor):

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

As I am new to this, I was wondering what the problem may be. I have read about the one wire interface used by the DS18B20, but I noticed that the DHT is not using the same protocol.

If I use the DHT11 alone, it works perfectly fine.

Also, I am using 4k7 pull-up resistors for both sensors.

Here's the code:

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

    dht DHT;

    #define ONE_WIRE_BUS 8
    #define DHT11_PIN 7

    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);

    void setup(void) {
      Serial.begin(9600);
      Serial.println("Dallas Temperature IC Control Library Demo");
      sensors.begin();
    }

    void loop(void) {
      int chk = DHT.read11(DHT11_PIN);
      sensors.requestTemperatures();
      Serial.print("Temperature1: ");
      Serial.print(DHT.temperature);
      Serial.print(" Temperature 2 : ");
      Serial.println(sensors.getTempCByIndex(0));
    }

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

body:
There appears to be several DHT sensor Arduino libraries available:

 - [niesteszeck/idDHT11][1]
 - [adafruit/TinyDHT][2]
 - [adafruit/DHT-sensor-library][3]

You might try an alternate library to see if that solves your current problem.  Note, some if not all of these libraries need to know which DHT model you are using.

Before going through the DHT and OneWire source code line by line looking for conflicts, try to narrow down what is causing the problem:

 1. Try only instantiating the OneWire class and skip calling the read method within the class.

If this works, then the conflict likely resides in the OneWire read method and not in the OneWire initialization code (that is, the OneWire's Constructor).

 2. Calling the DHT read method multiple times consecutively to see if the problem resolves it self.

Actually, you have done this and exposed a curious patter of good-bad-bad-good-bad-bad... which is worth looking into.  The point here is that if only the 1st call to the DHT read method after a call the the OneWire read method was bad, then there might be a setup problem in the DHT read method.

 3. Call the DHT Destructor, the DHT Constuctor then make the call to the DHT read method every time you read the DHT sensor.

This is a test case only and an extreme measure.  What you are doing here is re-initializing the DHT library (driver) every time you use it.  If this works it points to an initialization problem where the DHT library is initialization something which should probably be re-initialized again inside the DHT read method.  As the OneWire library is using the same "something" (resource).

One last thing, the OneWire example I looked at here:
[PaulStoffregen/OneWire][4]
...did not use the DallasTemperature library.  I doubt this will make a difference, but it is usually best to keep your code simple and avoid unnecessary complexities.

Added later...

As pointed out in the comments, it turns out the DHT11 only takes new readings every few seconds.  Guessing, the DHT11 library you are using either knowingly returns an unreasonable value of -999.0 until this time passes.  Or is returning exactly what the DHT11 reports which, again, is an unreasonable value of -999.0.

In [this DHT11 library][3], there is code:

    boolean DHT::read(bool force) {
      // Check if sensor was read less than two seconds ago and return early
      // to use last reading.
      uint32_t currenttime = millis();
      if (!force && ((currenttime - _lastreadtime) < 2000)) {
        return _lastresult; // return last correct measurement
    }

...which returns the last good value for 2 seconds after a DHT11 "real reading" should the library user call upon it faster then the DHT11 can respond.

  [1]: https://github.com/niesteszeck/idDHT11
  [2]: https://github.com/adafruit/TinyDHT
  [3]: https://github.com/adafruit/DHT-sensor-library
  [4]: https://github.com/PaulStoffregen/OneWire/tree/master/examples


body: To confirm the answers above, in my case https://github.com/adafruit/TinyDHT library worked fine with Arduino Uno, while http://playground.arduino.cc/Main/DHTLib refused to work. Same setup with DHT11 and DS1820.


body: DHT11 can only be read every 1 second. See manual.


message:
Using two digits to display a number using TM1637 and a 4-digit display

I decided to build a digital clock using a *[4-Digit Display][1]* (TM1637) from Grove.

For that, I have been using the *[DigitalTube library][2]* by Grove for the TM1637 controller.

My idea is to use the two first digits of the display (left to right) to display the hour and the two last digits to display the minutes. However, managing displays is difficult and all the libraries I have found for the previously mentioned controlled can only display one number per digit.

Here you have an example:
Using `tm1637.display(1,2);`, lets you display a "2" in the second digit (L to R), using `tm1637.display(0,3);` lets you display a 3 on the firt digit and etc.

As I said, I want to display the hour on the first two digits and the minutes in the two last digits.
I've have readed all the examples coming with the *DigitalTube* library but nothing was useful.

**Note**: I'm using the *DS3231* for managing the time with a RTC.

I don't know if you undestand my question. If not, let me know please.
*Arduino UNO R3.*

  [1]: http://www.seeedstudio.com/wiki/Grove_-_4-Digit_Display
  [2]: http://www.seeedstudio.com/wiki/File:DigitalTube.zip

body:
Using `tm1637.display(digit#, value);` calls, you can display a two-digit number using division to isolate the tens digit and mod to isolate the units digit.  For example, if `hour` and `mins` have hour and minute values, respectively, consider code like:

    tm1637.display(0, hour/10);
    tm1637.display(1, hour);
    tm1637.display(2, mins/10);
    tm1637.display(3, mins);

Code like the above is suitable in cases where values don't exceed 99, and where displaying a leading zero is ok.

If you don't want to display the leading zero when hour is less than 10, add an `if` test and blank the first digit in that case.


message:
Bluetooth module as MCU?

**Can I use Bluetooth Low energy devices as micro controllers directly instead of communicating to Arduino** e.g. HM-10/11 or even HC-05/06 ? If so **what are limitations** e.g. can  I hook sensors or control other stuff like LEDs or transistors with PWM ?

----------

*I have built a motion sensor, which consists of Arduino, Bluetooth Low energy HM-11, battery and sensor itself. It worked just fine, but one guy told me that Arduino may be completely unnecessary and that Bluetooth module could replace its functionality !
I then started digging for information, and either it's impossible or I am terrible at googling. Everything I found was info about some kind of development kits for HM-10/11, also pin outs of those boards. They do have some IO pins, which can mean it's possible, but I found no tutorials nor examples on how to program those boards and use with other components.*

body:
All bluetooth modules will need some sort of mcu to handle the requirements of the protocol stack, and it seems common that there will be at least a couple of GPIO which can be used directly if your sensor requirements are simple. At the other end of the spectrum, you will find there are also mcus with a full set of peripherals - enough to support a couple of sensors and a small display for example. Remember, the wearables market is likely bigger than the hobby electronics market.

Limitations are most likely to be in the area of ease of use (as you hint at with your question), and possibly the toolchain which you would need to use (unlikely to be arduino compatible). Also, the bluetooth stack typically takes a reasonable proportion of these wearables focused devices, so there is not a big amount of ram/flash or CPU cycles to spare even if you opt for a part which is more than 'just' a serial-to-bluetooth bridge.


message:
How to read and write EEPROM in ESP8266

I need to know how I can write integer values in EEPROM and retain the value on power on.

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

    char *Red = strstr(myTestUrl, "/R");
    if (Red) {
      int RedValue  = atoi(Red + 2);
      analogWrite(12, RedValue);
      Serial.println("Red :");
      Serial.println(RedValue);
    }

I want to write `RedValue` in EEPROM. How can it be done?

body:
Use `#include <EEPROM.h>`

    EEPROM.begin(size); //Size can be anywhere between 4 and 4096 bytes.
    EEPROM.write(0, RedValue);   // To store in 0th Location
    EEPROM.commit();


body:
`EEPROM.write(pos, val)` writes one byte (`val`) at the address giving by `pos`. An "int" in ESP8266 takes 4 bytes, so it's a little more complicated, because EEPROM works in bytes, not ints.

Here is a code for writing one int `val` at some position `pos` in the EEPROM:

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

    void eeWriteInt(int pos, int val) {
        byte* p = (byte*) &val;
        EEPROM.write(pos, *p);
        EEPROM.write(pos + 1, *(p + 1));
        EEPROM.write(pos + 2, *(p + 2));
        EEPROM.write(pos + 3, *(p + 3));
        EEPROM.commit();
    }

and, of course, you need to read it back:

    int eeGetInt(int pos) {
      int val;
      byte* p = (byte*) &val;
      *p        = EEPROM.read(pos);
      *(p + 1)  = EEPROM.read(pos + 1);
      *(p + 2)  = EEPROM.read(pos + 2);
      *(p + 3)  = EEPROM.read(pos + 3);
      return val;
    }

In Arduino you call `EEPROM.begin()`, but in ESP8266 you have to call `EEPROM.begin(n)`, where `n` is the total number of bytes you will need.

And remember that EEPROM have a short life span (by number of writes). You must minimize the number of writes!

EEPROM is permanent; you don't need to do nothing.


body:
While `EEPROM.read` and `EEPROM.write` are valid methods, it's like mopping the floor with a toothbrush. Use `EEPROM.put` and `EEPROM.get` instead.

For example:

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

    #include <EEPROM.h>

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

      uint addr = 0;

      // fake data
      struct {
        uint val = 0;
        char str[20] = "";
      } data;

      // commit 512 bytes of ESP8266 flash (for "EEPROM" emulation)
      // this step actually loads the content (512 bytes) of flash into
      // a 512-byte-array cache in RAM
      EEPROM.begin(512);

      // read bytes (i.e. sizeof(data) from "EEPROM"),
      // in reality, reads from byte-array cache
      // cast bytes into structure called data
      EEPROM.get(addr,data);
      Serial.println("Old values are: "+String(data.val)+","+String(data.str));

      // fiddle with the data "read" from EEPROM
      data.val += 5;
      if ( strcmp(data.str,"hello") == 0 )
          strncpy(data.str, "jerry",20);
      else
          strncpy(data.str, "hello",20);

      // replace values in byte-array cache with modified data
      // no changes made to flash, all in local byte-array cache
      EEPROM.put(addr,data);

      // actually write the content of byte-array cache to
      // hardware flash.  flash write occurs if and only if one or more byte
      // in byte-array cache has been changed, but if so, ALL 512 bytes are
      // written to flash
      EEPROM.commit();

      // clear 'data' structure
      data.val = 0;
      strncpy(data.str,"",20);

      // reload data for EEPROM, see the change
      //   OOPS, not actually reading flash, but reading byte-array cache (in RAM),
      //   power cycle ESP8266 to really see the flash/"EEPROM" updated
      EEPROM.get(addr,data);
      Serial.println("New values are: "+String(data.val)+","+String(data.str));
    }

    void loop()
    {
      delay(1000);
    }

**UPDATE**:  If you want to understand how the "EEPROM" is emulated in the ESP8266, you might want to reference [https://github.com/esp8266/Arduino/tree/master/libraries/EEPROM][1], specifically, `EEPROM.h`.

Also, `EEPROM.end` is not needed, it simply clears the local byte-array cache of the flash/EEPROM from RAM.  It serves on other function.

  [1]: https://github.com/esp8266/Arduino/tree/master/libraries/EEPROM


body:
I use 2 separate functions in my code on ESP8266 - one with `EEPROM.put()`, one with `EEPROM.get()`.

I had `EEPROM.begin(sizeof...);` only in `EEPROM.put()` function and `put` worked.
But it took me quite a while, until I found out, that it must be used before `EEPROM.get()` as well.


body:
Method using the number of letters.

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

    #include <ESP8266WiFi.h>

    const char* SSID = "R360"; //MAX 32
    const char* PASSWORD = "HFDYUK64323246"; //MAX 32

    #include <EEPROM.h>

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

      EEPROM_ESP8266_GRABAR(SSID, 0); //Primero de 0 al 32, del 32 al 64, etc
      EEPROM_ESP8266_GRABAR(PASSWORD, 32); //SAVE

      Serial.println();
      Serial.println(EEPROM_ESP8266_LEER(0, 32));//Primero de 0 al 32, del 32 al 64, etc
      Serial.println(EEPROM_ESP8266_LEER(32, 64));

      WiFi.begin(EEPROM_ESP8266_LEER(0,32).c_str(), EEPROM_ESP8266_LEER(32,64).c_str());

    }
    //
    void loop() {}
    //
    void EEPROM_ESP8266_GRABAR(String buffer, int N) {
      EEPROM.begin(512); delay(10);
      for (int L = 0; L < 32; ++L) {
        EEPROM.write(N + L, buffer[L]);
      }
      EEPROM.commit();
    }
    //
    String EEPROM_ESP8266_LEER(int min, int max) {
      EEPROM.begin(512); delay(10); String buffer;
      for (int L = min; L < max; ++L)
        if (isAlphaNumeric(EEPROM.read(L)))
          buffer += char(EEPROM.read(L));
      return buffer;
    }


message:
Understanding flow of current with pull-up and pull-down circuits

I am new to all of this and was trying to figure out what was happening with pull-up/pull-down circuits.  I think I understand what happens when the board handles the pull-up/pull-down but I wanted to try to build the circuits.  I got help from another forum.  Once I made the circuits, I found that I don't understand the path that the voltage is traveling.  I have 2 examples with multimeters attached.

Pull Up

I understand the press of the button connect circuit to ground.  But why does the voltage everywhere go down to zero when it is connected to ground?  Does it have something to do with the multimeter can't read the voltage because the current is taking the path of least resistance - which I have read is a myth?
[![Pull Up Circuit][1]][1]

Pull Down

When compared to the Pull Up, why does the voltage go to 5 before the yellow wire when the button is pushed?  Isn't it connected to the ground again which seems like it should cause the same scenario as the Pull Up where they all read zero.  Or does the resistor before ground have something to do with this.
[![Pull Down Circuit][2]][2]

I know nothing about electronics.  Some information and links where I could find more information would be great.  Thanks.

All the gifs are screen recordings from circuits I built with circuits.io.  I want to get into making somethings but wanted to practice first before I spent any money.

  [1]: https://i.stack.imgur.com/UC7RO.gif
  [2]: https://i.stack.imgur.com/sBxdS.gif

body:
It's very hard to read your circuit, because there are wires everywhere. However this is effectively what a switch and a pull-up resistor looks like:

[![Pull-up resistor][1]][1]

Due to the pull-up, pin 8 on the Arduino (which the switch is connected to) is normally pulled-up to 5V if the switch is open.

When you close the switch pin 8 becomes 0V, thus your meter reads 0V.

---

On the other hand, with a pull-down resistor, the circuit looks like this:

[![Pull-down resistor][2]][2]

Now pin 8 is normally zero volts with the switch open, and when closed pin 8 is connected to 5V to pin 8 becomes 5V.

---

See [my tutorial on switches](http://www.gammon.com.au/switches) for more details.

---

>  What happens with the flow of current and the resistor to make one example read high and the other low.

Imagine a door with a spring on it to close it. The spring is like a pull-up (or pull-down) resistor (depending on whether you are trying to keep the door closed or open).

The spring *gently* pulls the door shut. However if you barge out of it with a handful of pizzas in your hand your override the spring. In the absence of the spring the door would just flap in the breeze, sometimes opening and sometimes closing.

The point is, a person is strong enough to force the door open, despite the spring. Similarly if you close the switch you override the pull-up (or pull-down) resistor.

---

> Where does the 5V go when the switch is closed.

It flows through the resistor to ground (or 5V depending on which one you are talking about).

---

> When the switch is open in the pull up example - is voltage going through the resistor? From what I'm reading online, in the pull up case voltage isn't traveling through the resistor until the button is pressed.

Voltage doesn't "go through" a resistor, current does.

---

With the switch open, effectively a tiny amount of current goes through the resistor to pin 8. It is a "high impedance" input which means it puts a very small load on the input. Thus there is a very small voltage drop over the 10k resistor, and almost the full 5V is presented to the input pin for reading.

To work out the exact amount, we can look at the datasheet which says that the maximum leakage current through an I/O pin at 5V is 1 µA. Now using Ohm's Law we can find the voltage drop over the 10k resistor:

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

    V = I * R
    V = 0.000001 * 10000
    V = 0.01 V

Thus with 5V at the 5V pin of the processor, and a (maximum of) 1 µA consumed at pin 8, it will therefore have 4.99 V at the pin, which therefore reads `HIGH`.

---

With the switch closed, then we use Ohm's Law to calculate the flow through the resistor:

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

    I = V / R
    I = 5 / 10000
    I = 0.0005 A

Thus 0.5 mA flows through the resistor with the switch closed. This is not enough to damage the resistor, or make a significant load on the 5V line.

---

I think you are getting confused (as I did when I was young) that a big resistance (like 10k) must "resist" a lot of voltage. It is easy to think that after going through 10k resistance there can't be much "voltage" left.

The fact is, though, that the voltage on the other end of a resistor is proportional to *not only* the resistance (R) but *also* the current (I). This is Ohms's Law (`V = I * R`)

So, if the current is very small (as is the case with an input pin) then the voltage drop over a resistor - even a large one - is very small.

So, the idea of a pull-up resistor is, that with no external influences (like a switch) then after passing through 10k resistance, there is still 5V at the other side.

Let me issue you with a challenge. Find a voltage source (eg. a battery). Measure it with your multimeter. Let's say you have a 5V source which is the Arduino 5V pin. Now get a 10k resistor. Put it in series with the 5V source. Now measure it on the other side of the resistor. Depending on the quality of the meter (and thus how much current it takes to measure a voltage) you will get very close to the same voltage reading. In my case I had 5V on one side of the resistor, and 4.99V on the other side. This is exactly what my calculations above predicted.

  [1]: https://i.stack.imgur.com/j29Ek.png
  [2]: https://i.stack.imgur.com/N8zGN.png


message:
PWM output voltage too high

I'm experimenting with PWM with the code below, but (according to my analog multimeter) the voltage on the output pins reach up to 5V whilst the largest `analogRead(IN1)` value is only around 700:

    const int EN1 = 5;
    const int EN2 = 6;
    const int EN3 = 7;

    const int IN1 = 9;
    const int IN2 = 10;
    const int IN3 = 11;

    // SPWM (Sine Wave)
    // const int pwmSin[] = {127, 138, 149, 160, 170, 181, 191, 200, 209, 217, 224, 231, 237, 242, 246, 250, 252, 254, 254, 254, 252, 250, 246, 242, 237, 231, 224, 217, 209, 200, 191, 181, 170, 160, 149, 138, 127, 116, 105, 94, 84, 73, 64, 54, 45, 37, 30, 23, 17, 12, 8, 4, 2, 0, 0, 0, 2, 4, 8, 12, 17, 23, 30, 37, 45, 54, 64, 73, 84, 94, 105, 116 };

    /// SVPWM (Space Vector Wave)
    //const int pwmSin[] = {128, 147, 166, 185, 203, 221, 238, 243, 248, 251, 253, 255, 255, 255, 253, 251, 248, 243, 238, 243, 248, 251, 253, 255, 255, 255, 253, 251, 248, 243, 238, 221, 203, 185, 166, 147, 128, 109, 90, 71, 53, 35, 18, 13, 8, 5, 3, 1, 1, 1, 3, 5, 8, 13, 18, 13, 8, 5, 3, 1, 1, 1, 3, 5, 8, 13, 18, 35, 53, 71, 90, 109};
    const int pwmSin[] = {128, 132, 136, 140, 143, 147, 151, 155, 159, 162, 166, 170, 174, 178, 181, 185, 189, 192, 196, 200, 203, 207, 211, 214, 218, 221, 225, 228, 232, 235, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 248, 249, 250, 250, 251, 252, 252, 253, 253, 253, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 253, 253, 253, 252, 252, 251, 250, 250, 249, 248, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 248, 249, 250, 250, 251, 252, 252, 253, 253, 253, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 253, 253, 253, 252, 252, 251, 250, 250, 249, 248, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 235, 232, 228, 225, 221, 218, 214, 211, 207, 203, 200, 196, 192, 189, 185, 181, 178, 174, 170, 166, 162, 159, 155, 151, 147, 143, 140, 136, 132, 128, 124, 120, 116, 113, 109, 105, 101, 97, 94, 90, 86, 82, 78, 75, 71, 67, 64, 60, 56, 53, 49, 45, 42, 38, 35, 31, 28, 24, 21, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 8, 7, 6, 6, 5, 4, 4, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 8, 7, 6, 6, 5, 4, 4, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 21, 24, 28, 31, 35, 38, 42, 45, 49, 53, 56, 60, 64, 67, 71, 75, 78, 82, 86, 90, 94, 97, 101, 105, 109, 113, 116, 120, 124};

    int currentStepA;
    int currentStepB;
    int currentStepC;
    int sineArraySize;
    int increment = 0;
    boolean direct = 1; // direction true=forward, false=backward

    //////////////////////////////////////////////////////////////////////////////

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

      setPwmFrequency(IN1); // Increase PWM frequency to 32 kHz  (make unaudible)
      setPwmFrequency(IN2);
      setPwmFrequency(IN3);

      pinMode(IN1, OUTPUT);
      pinMode(IN2, OUTPUT);
      pinMode(IN3, OUTPUT);

      pinMode(EN1, OUTPUT);
      pinMode(EN2, OUTPUT);
      pinMode(EN3, OUTPUT);

      digitalWrite(EN1, HIGH);
      digitalWrite(EN2, HIGH);
      digitalWrite(EN3, HIGH);

      sineArraySize = sizeof(pwmSin)/sizeof(int); // Find lookup table size
      int phaseShift = sineArraySize / 3;         // Find phase shift and initial A, B C phase values
      currentStepA = 0;
      currentStepB = currentStepA + phaseShift;
      currentStepC = currentStepB + phaseShift;

      sineArraySize--; // Convert from array Size to last PWM array number
    }

    //////////////////////////////////////////////////////////////////////////////

    void loop() {

      analogWrite(IN1, pwmSin[currentStepA]);
      analogWrite(IN2, pwmSin[currentStepB]);
      analogWrite(IN3, pwmSin[currentStepC]);

      if (direct==true) increment = 1;
      else increment = -1;

      currentStepA = currentStepA + increment;
      currentStepB = currentStepB + increment;
      currentStepC = currentStepC + increment;

      //Check for lookup table overflow and return to opposite end if necessary
      if(currentStepA > sineArraySize)  currentStepA = 0;
      if(currentStepA < 0)  currentStepA = sineArraySize;

      if(currentStepB > sineArraySize)  currentStepB = 0;
      if(currentStepB < 0)  currentStepB = sineArraySize;

      if(currentStepC > sineArraySize)  currentStepC = 0;
      if(currentStepC < 0) currentStepC = sineArraySize;

      /// Control speed by this delay
      delay(10);
      Serial.println(analogRead(IN1));
    }

    void setPwmFrequency(int pin) {
      if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
        if(pin == 5 || pin == 6) {
          TCCR0B = TCCR0B & 0b11111000 | 0x01;
        } else {
          TCCR1B = TCCR1B & 0b11111000 | 0x01;
        }
      }
      else if(pin == 3 || pin == 11) {
        TCCR2B = TCCR2B & 0b11111000 | 0x01;
      }
    }

If `analogRead(IN1)` is just around 700 max, shouldn't the voltage be around 3.5V (700/1023 * 5V)? How come the output voltage is so high?

Any help would be appreciated.

body:
It seems that you misunderstand how pwm works.
Pwm is the modulation of duty cycle, so the pin are outputting square waves 0-5v at the same frequency, but varying the time it's low and the time it's high. Your multimeter probably is only displaying high intervals, instead your analog read probably has filters and calculates the efficient voltage of the sine wave (divide max for sqr(2)).


message:
Two Identical Potentiometers, two different results

quick question.  I have two 10 turn precision potentiometers and I tested both when I bought them a few weeks ago, both worked as expected.  However now that I have epoxied one of them into my project and wired it up, I don't get any resistance.  I get a max reading all the time regardless of where the dial is set.  So then I pull off the wiring and do the same setup with the other potentiometer and I am still getting expected results.

What could be the reasoning for the sudden difference in readings? Could the first one have gone bad, and if so how often does this happen and how can I avoid it in the future?

Everything falls within recommended specs of the pot and neither has been really used at all.

body: Trimmers have a really low current rating, so if you hadn't protect it enough, maybe you have broken it. Always remember a pull up resistor of 10k or more.


body:
Multi turn pots range in size from about sugar cube dimensions:

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

...to weighing a pound or more:

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

It would be easy to imagine epoxy entering a small plastic multi turn pot and "freezing" the parts within.  If this is what happened, try using a faster curing glue or mount the pot on a Printed Circuit Board (PCB) and glue the PCB.

  [1]: https://i.stack.imgur.com/NcQAE.jpg
  [2]: https://i.stack.imgur.com/cFC8S.jpg


message:
Passing array to library function

I'm trying to pass an array to a library (written in c++) but the error:

    undefined reference to `MyLib::arrayTest(int*)'
    collect2: error: ld returned 1 exit status
    Error compiling.

Is being produced.

My Code Is As Follows:

Testing.ino:

    MyLib test = MyLib(5,4,6);

    void setup(){
        int arr[10];

        test.arrayTest(arr);

        Serial.println(arr[0]);
    }

MyLib.h:

    class MyLib {
        public:
            MyLib(int x, int y, int z);

            void arrayTest(int* n);

MyLib.cpp:

    void arrayTest(int* n){
        n[0] = 15;
    }

Any help is greatly appreciated :)

body:
This function:

    void arrayTest(int* n){
        n[0] = 15;
    }

is lacking the class qualifier:

    void MyLib::arrayTest(int* n){
        n[0] = 15;
    }


message:
Arduino UNO suddenly stops responding

I wrote this simple script to control a servo over serial comm -

    #include <Servo.h>
    Servo steeringServo;
    char data = ' ';

    void setup() {
      steeringServo.attach(9);
      Serial.begin(115200);

    }

    void loop() {
      if(Serial.available()){
        data = Serial.read();
      }

      if(data =='L'){
        steeringServo.write(50);
      }
      else if(data == 'R'){
        steeringServo.write(135);
      }
      else if(data == 'S'){
        steeringServo.write(90);
      }

    }

It was working fine, I was sending values through a python script. I turned my Arduino off and after a while I come back and reconnect all stuff exactly the way it was, but now my Arduino isn't responding! I tried sending values through the serial monitor to the above sketch but nothing happens! I tried another code which takes values over serial comm and that didn't work as well. The Arduino just receives the values but doesn't do what its supposed to when it receives.

Not only this, I tried uploading the sweep sketch and that didn't work either. Everything is connected exactly the way it was when stuff was fine.

What has gone wrong with my Arduino?

**UPDATE**
The Arduino works fine if the values are sent through my script.

**UPDATE 2**
The Arduino works fine if the values are sent through puTTY.

body:
You never reset `data`. Every time you enter `loop`, data keep the last value you read.

You don't need to test `data` in every `loop`, only after you read something:

    void loop()
    {
     if(Serial.available()) {
      data = Serial.read();

      if(data =='L') {
       steeringServo.write(50);
      } else if(data == 'R') {
       steeringServo.write(135);
      } else if(data == 'S') {
       steeringServo.write(90);
      }
     }

I'm afraid that there are additional problems with the servo library: some implementations (looking at Servo-master) disable interrupts, which mess with your Serial port.


message:
Using an External ADC with Arduino

For my project I have to measure a  signal of the order of few microvolts.
As we know the least an Arduino can measure is ~5mV, due to its 10bit ADC and 5V reference voltage.

A solution to this problem can be to use an external ADC (16bit, I think will do).

Can you please guide me on this problem.Is it possible to use a external ADC,if yes how should I.Any other simple solution ?
Thank You

Anupam

body:
Yes, if you have a 0 to 30 mV signal that you need to measure to an accuracy of 2 microvolts, you'll need an ADC with an effective number of bits (ENOB) of at least 13.9 bits and an amplifier to make the signal to match the range accepted by the ADC.
Most ADCs pretty much require some sort of op-amp or differential amplifier between such low-level input signals and the ADC input pins.
A few ADCs have a differential amplifier already built in -- that makes things a lot easier to get working, but I don't know if any of such ADC available would meet the other requirements of your project.

I don't know any way to make such high-resolution measurements other than using a dedicated external ADC chip.

You'll want to read the ADC datasheet -- some of them, and so far all the microcontrollers I've seen that claim to have a built-in "16 bit ADC", have an effective number of bits (ENOB) worse than the 13.9 ENOB you need at the sampling rates I typically use.

Adafruit has a very nice tutorial describing how to connect the 12-bit ADC ADS1015 or [the 16-bit ADC ADS1115 to an Arduino][1].

The Arduino playground has a brief tutorial describing connecting a 12-bit ADC MCP3208 or a [13-bit ADC MCP3304 to an Arduino][2].

I see from the Arduino blog and other sites that people have connected some even higher resolution ADCs to an to an Arduino board, including
the 24-bit Linear LTC2440 ADC;
the 18-bit LTC2400 ADC (24 bit at 5 samples per second); and
the 24-bit ADC TI ADS1220.

* Arduino blog. ["Archive for the ‘ADC’ Category"][3]
* Peter Oakes. ["Arduino UNO, Using precision ADCs and DACs"][4]. (video tutorial: connecting the 24-bit ADC TI ADS1220 to an Arduino).
* Martin Nawrath. ["Connect a LTC2400 High Precision 24 Bit Analog to Digital Converter ... to the Arduino"][5]
* John Boxall. ["Tutorial – Arduino and the TI ADS1110 16-bit ADC"][6].

Sounds like a fun project.
Good luck.

EDIT:

* Steve Luce. [The LTC2440 24 BIT ADC and the Arduino Uno][7].

Everyone that uses an ADC needs some antialiasing filter between the signal and the ADC.

People that measure very faint signals usually need some sort of amplifier between the signal and the ADC.
You may find the list of suggested op amps on p. 7 of the [AMP03 datasheet][8] useful.

Because historically ADCs were expensive (and high-resolution ADCs were unavailable), people have developed many clever tricks for processing signals before feeding the processed signal into a relatively low-resolution ADC.
(Lock-in amplifiers, chopper amplifiers, manual precision gain adjustment, manual precision offset adjustment, heterodyning, etc.)

Have you tried asking "What sort of amplifier do I need to measure ((something)) with a 16-bit ADC" at https://electronics.stackexchange.com/ to learn some of those tricks that specifically apply to ((something))?

  [1]: https://learn.adafruit.com/adafruit-4-channel-adc-breakouts/assembly-and-wiring
  [2]: http://playground.arduino.cc/Code/MCP3208
  [3]: http://blog.arduino.cc/category/ic/adc/
  [4]: http://www.youtube.com/watch?v=PrvhkhadL5g
  [5]: http://interface.khm.de/index.php/lab/interfaces-advanced/connect-a-ltc2400-high-precision-24-bit-analog-to-digital-converter/
  [6]: http://tronixstuff.com/2013/07/02/tutorial-arduino-and-the-ti-ads1110-16-bit-adc/
  [7]: http://www.steveluce.com/24bits/Applications of the LTC 24 bit ADC.html
  [8]: http://www.mouser.com/ds/2/609/AMP03-879217.pdf


message:
How to make "IF "Temperature exceeds" logic to work in same arduino code

I have the below code working from https://www.youtube.com/watch?v=Y30iEOxl1To - to receive temperature & humidity as an sms when i give a missed call to a specific number (sim on the gsm shield)

The above code is like on demand sms. I also want to alter this code so it can automatically send me another sms if the temperature exceeds a threshold.

Please help.

Below is the code...

    #include "SIM900.h"
    #include <SoftwareSerial.h>
    #include "call.h"
    #include <DHT.h>
    #include "sms.h"

    SMSGSM sms;
    #define DHTPIN 7
    #define DHTTYPE DHT22

    CallGSM call;
    boolean started=false;
    char sms_text[160];

    DHT dht(DHTPIN, DHTTYPE);

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

        if (gsm.begin(9600))
        {
            Serial.println("\nstatus=READY");
            started=true;
        }
        else
            Serial.println("\nstatus=IDLE");
    }

    void loop()
    {
        float humidity, temperature;
        String smsText ="";
        if(temperature>29)
        {
            switch (call.CallStatus())
            {
                case CALL_NONE: // Nothing is happening
                    break;

                case CALL_INCOM_VOICE : // Yes! Someone is calling us
                    Serial.println("RECEIVING CALL");
                    call.HangUp();
                    delay(1000);
                    humidity = dht.readHumidity();
                    temperature = dht.readTemperature();
                    delay(1000);
                    smsText = "Temperature: "+String(temperature,1)+"C Humidity: "+String(humidity,1)+"%";
                    smsText.toCharArray(sms_text,160);
                    //Serial.println(smsText);
                    sms.SendSMS("+91**********",sms_text);
                    break;

                case CALL_COMM_LINE_BUSY:  // In this case the call would be established
                    Serial.println("TALKING. Line busy.");
                    break;
            }
            delay(1000);
        }
    }

body:
The code below will check if the temperature goes above 29 degrees. It also check whether the temperature was below 29 previously, to prevent it from sending an SMS every second, for as long as it's above 29 degrees C.

    #include "SIM900.h"
    #include <SoftwareSerial.h>
    #include "call.h"
    #include <DHT.h>
    #include "sms.h"

    SMSGSM sms;
    #define DHTPIN 7
    #define DHTTYPE DHT22

    CallGSM call;
    boolean started=false;
    char sms_text[160];

    DHT dht(DHTPIN, DHTTYPE);

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

        if (gsm.begin(9600))
        {
            Serial.println("\nstatus=READY");
            started=true;
        }
        else
            Serial.println("\nstatus=IDLE");
    }

    float previousTemperature = 0;
    void loop()
    {
        float humidity, temperature;
        humidity = dht.readHumidity();
        temperature = dht.readTemperature();
        delay(1000);

        // check if temperature has raised to above 29 degrees
        if(temperature>29 && previousTemperature<=29)
        {
            sendSMS(temperature, humidity);
        }
        previousTemperature = temperature;

        // check for incomming call
        switch (call.CallStatus())
        {
            case CALL_NONE: // Nothing is happening
                break;

            case CALL_INCOM_VOICE : // Yes! Someone is calling us
                Serial.println("RECEIVING CALL");
                call.HangUp();
                delay(1000);
                sendSMS(temperature, humidity);
                break;

            case CALL_COMM_LINE_BUSY:  // In this case the call would be established
                Serial.println("TALKING. Line busy.");
                break;
        }

        delay(1000);
    }

    void sendSMS(float temperature, float humidity)
    {
        String smsText ="";
        smsText = "Temperature: "+String(temperature,1)+"C Humidity: "+String(humidity,1)+"%";
        smsText.toCharArray(sms_text,160);
        //Serial.println(smsText);
        sms.SendSMS("+91**********",sms_text);
    }


message:
Interfacing pc mouse (serial port DB-9)

So I`ve got that mouse with serial connector. It is named serial so it should be easier to connect than even a ps2 mouse, right?

I can`t find any instruction on it. Or should I see instruction on ps2 mouse and plug in the same wires?
Btw mouse has only 4 wires connected inside, as usual PS2 mouse. I want to connect it the same way as ps2 mouse to get easy readings of rotary encoder.
[![serial mouse][1]][1]

UPD1: I`ve tried to connect it like a PS2 mouse according to this schema with no success. So either a mouse is dead or it uses some kind of different connection?
[![PS2 to serial mouse][2]][2]

  [1]: https://i.stack.imgur.com/KJXmu.jpg
  [2]: https://i.stack.imgur.com/t12O8.gif

body:
A serial mouse is designed to connect to a PC's true serial port - it's an actual RS-232 device using ±5V. As such it won't connect directly to the Arduino's `RX`/`TX` pins, you'll have to go through an RS-232 transceiver chip.

It also gets its power from the `RTS` line, but I never knew what the current draw of one of those things was - be careful trying to power it from the Arduino!

Different mouse manufacturers used different protocols. The original standard used a three-byte protocol at 1,200 bps 7N1. The encoding had the following properties:

* The leading bit of the first byte of the packet was set - all future bytes had the leading bit cleared.
* The first byte had the buttons' states, and the most significant bits of the X and Y deltas;
* The X delta was encoded in the second byte;
* The Y delta was encoded in the third byte.
> http://paulbourke.net/dataformats/serialmouse/

Other manufacturers added things like extra buttons and scroll wheels that didn't fit in the packet structure. So they modified the protocol, but stuck with some features of the original:

* The data rate was (usually) still 1,200 bps, although sometimes they used 7N2 or 8N1 instead.
* The leading bit was still used to indicate start of packet;
* The X, Y (and Z) wheels still indicated deltas.
> http://www.cpcwiki.eu/index.php/Serial_RS232_Mouse


message:
Strange behaviour with using max

I have this really simple code.
Let's say I have a variable X.
Then all I want to do is create a random value R, if R > X then I want X to become R.
But for some reason, my `n_of_buttons_pressed` climbs up and then sometimes drops back to lower values. I can not wrap my head around how it could get a lower value then a previous value.

    #define N_OF_BUTTONS 60

    int n_of_buttons_pressed;

    void setup() {
      Serial.begin(9600);
      Serial.println("start");
    }

    void loop() {

      n_of_buttons_pressed = (int) max(random(0, N_OF_BUTTONS), n_of_buttons_pressed);

      Serial.print("n_of_buttons_pressed:");
      Serial.print(n_of_buttons_pressed);
      Serial.println();

      delay(100);

    }

body:
The `max()` “function” is actually a macro defined in `Arduino.h` as

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

    #define max(a,b) ((a)>(b)?(a):(b))

This expands in your code into something like

    buttons_pressed = random(0, N_OF_BUTTONS) > n_of_buttons_pressed) ? \
                      random(0, N_OF_BUTTONS) : n_of_buttons_pressed

The problem with the macro is that it evaluates at least one of its
arguments twice. In this case, if the test is true, the variable
`buttons_pressed` gets assigned _another_ pseudo-random number.

The way around this is to store the pseudo-random number in a variable,
to avoid `random()` being evaluated twice:

    int pseudo_random = random(0, N_OF_BUTTONS);
    buttons_pressed = max(pseudo_random, n_of_buttons_pressed);


message:
How can I include examples in library?

I have written a library for Arduino, `my_library`, consisting of `my_library.h` and `my_library.cpp`, both included in `my_library` folder. Actually the library is recognized from IDE Arduino and works fine.

I want to add some examples, let's say `Example1` and `Example2`. How is that possible?

Should the examples be included in `my_library` folder?

or should be included in another folder inside `my_library` folder?

I tried several combinations but none worked. Do I miss something?

body:
You need to create a folder called "examples" in your library folder. Within there, each in its own folder, you place your examples.

For example:

    MyLib/
    MyLib/MyLib.h
    MyLib/MyLib.cpp
    MyLib/examples/
    MyLib/examples/Example1/
    MyLib/examples/Example1/Example1.ino
    MyLib/examples/Example2/
    MyLib/examples/Example2/Example2.ino

Be sure to name the example's folder the same as the name of the example.


message:
Getting negative results from calculations

I'm trying to proportion potentiometer value to analog pin value. Like 1024 to 255.

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

    int readVolumePot() {
        int val = analogRead(potVolumePIN);

        Serial.print("VOL");
          Serial.println((val * 255/1024));

          return (val * 255/1024);
      }

As potentiometer turns I got irrelevant values.

    VOL3
    VOL3
    VOL3
    VOL17
    VOL-16
    VOL-16
    VOL-21
    VOL-1
    VOL-10
    VOL-3
    VOL-4
    VOL11
    VOL8
    VOL13
    VOL17
    VOL15

In Arduino's [website][1] they say

> some constant calculations may overflow (e.g. 60 * 1000 will yield a
> negative result).

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

Notwithstanding, I cannot find an appropriate way to convert the potentiometer value to analog pin value.

body:
`analogRead()` returns a number from `0` to `1023`, and you want to convert that to a range from `0` to `255`? One easy way would be to simply divide the reading by `4`.

On a more general note, given that the numbers will (should!) never be negative, there's a flavour of `int` called `unsigned int`. By using that:

    unsigned int val = analogRead(...);

you can cover a range from `0` to `65535` instead of `int`'s `-32768` to `32767`. That will give you a little more head room - but not enough to multiply the maximum value `1023` by `255` first.

There's also another type `long`. That covers the range from -2 to 2 billion (and a bit), while `unsigned long` goes from 0 to 4 billion (and a bit) - but that uses a LOT of processing for the poor Arduino to work with.


message:
HUGE deviation in Sharp IR sensor values if other pins are defined in void setup()

I wrote this code for a project -

    int sensorpin = A5;
    int val = 0;
    double avgval = 0;
    int E1 = 11;
    int brake = 12;
    char data = ' ';

    void setup()
    {
      Serial.begin(115200);
      pinMode(E1, OUTPUT);
      pinMode(brake, OUTPUT);
      pinMode(sensorpin, INPUT);
    }

    void loop()
    {

      if (Serial.available()>0){
          data = Serial.read();
        }

      val = analogRead(sensorpin);
      avgval = average(val);
      double volt = (avgval*5)/1023;
      Serial.println (avgval);
      Serial.println(volt);
      delay(1000);

      if (data == 'G'){
        analogWrite(E1, 255);
        digitalWrite(brake, LOW);
      }

      if( volt > 1.5 && volt < 1.75 ){
        digitalWrite(brake, HIGH);
      }
    }

    double average(double adc){
      int n = 1;
      double avg = 0.00, sum = 0.00;
      while(n<=23){
        sum = sum + adc;
        avg = sum/25;
        n++;
      }
      return avg;
    }

The code works fine, except for the fact that the Sharp IR sensor (GP2Y0A710K0F) outputs values which are wrong (by a HUGE distance), **ONLY** if in the `void setup()` function, the commands -

    pinMode(E1, OUTPUT);
    pinMode(brake, OUTPUT);

are left *uncommented*. If I comment the above two statements, the sketch works fine.

What on earth is wrong here? I can't make out anything.

body:
Not sure why commenting out those two lines makes a difference.  I think we need to see a schematic to resolve this.

However...

You do not use "pinMode" to setup an analog input!

Look at the examples on the ["analogRead" page][1].  Notice there is no setup needed for the analog pin.  Just call "analogRead" like you are doing and everything should be fine.

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


message:
Uno timer 2 set up

I am trying to use Timer2 in an Uno in fast PWM mode.  Can someone explain how to set up the TCCR2A & B registers?

Currently I have:

      TCCR2A |= _BV(WGM21) | _BV(WGM20);
      TCCR2B &= ~_BV(WGM22);

      TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
      TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
      TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

I would like to have the inverted value on TCCR2B, but I think it can be inverted using OCR2B ^= 255, correct?  This is to have a varying signal on Pin11 and its inverse on Pin3, the signal is generated by varying the OCR2B value.

Thanks

body:
If you want to get two complementary PWM signals, you have to set _the
same_ value to both output compare registers. This is necessary to have
the two signals in phase. You also have to configure one PWM in
non-inverting mode and the other in inverting mode. For example:

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

    TCCR2A = _BV(COM2A1)  // non-inverting PWM on OC2A
           | _BV(COM2B0)  // PWM on OC2B:
           | _BV(COM2B1)  //    inverting mode
           | _BV(WGM20)   // fast PWM
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(CS10);   // clock at F_CPU / 1
    OCR2A  = 84;          // duty cycle ~ 1/3
    OCR2B  = 84;          // same signal, complemented

Checked on the scope: when pin 3 goes high pin 11 goes low and
vice-versa.