message:
Check the value of character variable

I'm writing some code for Arduino and I'm not sure if I'm checking the value of this character variable correctly. Can you please tell me if this is correct:

    const char* front = "front";
    const char* back = "back";

    eyeballs(front);
    eyeballs(back);

    void eyeballs(const char* frontOrBack){

    if (frontOrBack == "front") {
        digitalWrite(frontEyes, LOW);}//end if
      else if (frontOrBack == "back") {
        digitalWrite(backEyes, LOW);}//end else*/
    }

body:
Since you are using C strings (array of characters) instead of the C++ String class, you cannot use the == operator.

Instead, you can use the C style [strcmp][1] function, which is also part of the C++ library:

        #include <string.h>
           .
           .
           .

        if (!strcmp(frontOrBack,"front")) {
            digitalWrite(frontEyes, LOW);}//end if
        else if (!strcmp(frontOrBack,"back")) {
            digitalWrite(backEyes, LOW);}//end else*/
        }

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


sender: user

sender: assistant

body:
Another option would be an enum.

    enum
    {
       FRONT,
       BACK
    }
    .
    .
    .
       if (frontOrBack == FRONT)
       {
          // Stuff
       }
       else if (frontOrBack == BACK)
       {
          // Some other stuff
       }


message:
How to properly reverse DC motor direction with 2 limit switchws

Hello i am trying to reverse a dc motor direction upon hitting either limit switch. but noting is working can some one point me in right direction. all example i find use stepper motors and step count.

    const int sw2 = 2;          //Up Limit switch
    const int sw3 = 3;          //Down Limit switch
    const int ic1_2 = 8;        //TA8409S IN2
    const int ic1_1 = 9;        //TA8409S IN1
    const int enable = 10;      //TA8409S Enable (motor)
    int sw2State = 0;
    int sw3State = 0;

    void setup() {
      pinMode(sw2, INPUT_PULLUP);
      pinMode(sw3, INPUT_PULLUP);
      pinMode(ic1_1, OUTPUT);
      pinMode(ic1_2, OUTPUT);
      pinMode(enable, OUTPUT);
      digitalWrite(enable, 1);
      Serial.begin(9600);
    }

    void loop() {
      tilt_up();
    }

    void tilt_up()
    {
    Serial.print("up Started\n");
      digitalWrite(ic1_1, LOW);
      digitalWrite(ic1_2, HIGH);
      sw2State = digitalRead(sw2);
      if (digitalRead(sw2State == LOW)) {
        tilt_down();
        Serial.print("sw2 pressde\n");
      }
    }

    void tilt_down()
    {
      Serial.print("down Started\n");
      digitalWrite(ic1_1, HIGH);
      digitalWrite(ic1_2, LOW);
      sw3State = digitalRead(sw3);
      if (digitalRead(sw3State == LOW)) {
        tilt_up();
        Serial.print("sw3 Pressed\n");
      }
     }

body:
    void loop() {
      tilt_up();
    }

    void tilt_up()
    {
    ...
      if (digitalRead(sw2State == LOW)) {
        tilt_down();
    ...
      }
    }

    ...

    void tilt_down()
    {
    ...
      if (digitalRead(sw3State == LOW)) {
        tilt_up();
    ...
      }
     }

You are recursing here. `loop` calls `tilt_up` which eventually calls `tilt_down` which calls `tilt_up` and so on until you - rather quickly - run out of RAM.

Rewrite so that you are not doing that.

---

Also see what @MikaelPatel told you in [your other question](https://arduino.stackexchange.com/questions/19852/). You have the brackets in the wrong place.

      if (digitalRead(sw2State == LOW)) {

should be:

      if (digitalRead(sw2State) == LOW) {


body:
If you want to reverse the movement you sould remember where you are going. This, along with the brackets correction suggested by @MikaelPatel and @NickGammon, leads to this code:

    boolean moving_up = true;

    void loop() {
     if (moving_up)
      tilt_up();
     else
      tilt_down();
    }

    void tilt_up()
    {
     digitalWrite(ic1_1, LOW);
     digitalWrite(ic1_2, HIGH);
     if (digitalRead(sw2State) == LOW) {
      moving_up = false;
      Serial.println("sw2 Pressed");
      Serial.println("down Started");
     }
    }

    void tilt_down()
    {
     digitalWrite(ic1_1, HIGH);
     digitalWrite(ic1_2, LOW);
     sw3State = digitalRead(sw3);
     if (digitalRead(sw3State) == LOW) {
      moving_up = true;
      Serial.println("sw3 Pressed");
      Serial.println("up Started");
     }
    }


body:
I got it to work!!!
do not know if it is the right way ... but it works. thank you all for your input/advice. here is the new working code:

    /*

     */

    // set pin numbers:
    const int sw2 = 2;           // Down limit
    const int sw3 = 3;           // Up Limit
    const int ledPin =  13;      // Pwr L.E.D
    const int ic1_2 = 8;         // TA8409S IN2
    const int ic1_1 = 9;         // TA8409S IN1
    const int enable = 10;       // TA8409S Enable (motor)

    int sw2State = 0;            // Down Limit State
    int sw3State = 0;            // Up   Limit State

    void setup() {
      // Setting L.E.D and Motor In, Enable pins as an output:
      pinMode(ic1_1, OUTPUT);
      pinMode(ic1_2, OUTPUT);
      pinMode(enable, OUTPUT);
      pinMode(ledPin, OUTPUT);
      // Setting limit switches pins as inputs
      pinMode(sw2, INPUT_PULLUP);
      pinMode(sw3, INPUT_PULLUP);
      // Enables motor
      digitalWrite(enable, 1);
      //Starts program down
      down();
    }

    void loop() {
      // reads the state of the limit switches
      sw2State = digitalRead(sw2);
      sw3State = digitalRead(sw3);

      if (sw3State == LOW) {
        down();
      }
      if (sw2State == LOW) {
        up();
      }
    }

    void up() {
      digitalWrite(ic1_1, LOW);
      digitalWrite(ic1_2, HIGH);
    }

    void down() {
      digitalWrite(ic1_1, HIGH);
      digitalWrite(ic1_2, LOW);
    }

    void err() {
      digitalWrite(enable, LOW);
      digitalWrite(ic1_1, LOW);
      digitalWrite(ic1_2, LOW);
    }


message:
How to change Void with button press

I have 2 buttons and 2 voids (blink_slow) (blink_fast).
i need to be able to press button 1 and blink-slow void will run, then press button 2  and blink fast will run. none of my code works, any idea how i can do this?

    const int btn1 1;
    const int btn2 2;
    const int led  13;

    void setup(){
    pinMode(btn1,INPUT_PULLUP);
    pinMode(btn2,INPUT_PULLUP);
    pinMode(led,OUTPUT);
    digitalWrite(led,HIGH);
    }
    void loop(){
    if(digitalRead(btn2 =LOW)){
    blink_slow();
    }
    if(digitalRead(btn3 =LOW)){
    blink_fast();
    }

    void blink_slow(){
    digitalWrite(led,LOW);
    delay(1000)
    digitalWrite(led,HIGH);
    delay(1000)
    }

    void blink_fast(){
    digitalWrite(led,LOW);
    delay(500)
    digitalWrite(led,HIGH);
    delay(500)
    }

body:
Start by correcting the obvious:

    const int btn1 = 2;
    const int btn2 = 3;
    const int led = 13;

    void setup()
    {
      pinMode(btn1, INPUT_PULLUP);
      pinMode(btn2, INPUT_PULLUP);
      pinMode(led, OUTPUT);
      digitalWrite(led, HIGH);
    }

    void loop()
    {
      if (digitalRead(btn2) == LOW) {
        blink_slow();
      }
      else if (digitalRead(btn3) == LOW) {
        blink_fast();
      }

    void blink_slow()
    {
      digitalWrite(led, LOW);
      delay(1000)
      digitalWrite(led, HIGH);
      delay(1000)
    }

    void blink_fast()
    {
      digitalWrite(led, LOW);
      delay(500)
      digitalWrite(led, HIGH);
      delay(500)
    }

The mistakes where 1) const variable assignment, 2) using pin 1 (TX) is a potential risk if you later what to use Serial for debugging, etc, 3) condition expression, and a lot of formatting. Open your C/C++ book and check the syntax.

Now your turn to improve this!


message:
ESP8266 is not responding

I have ESP8266, FTD232 UART, Linux mint 17.3 OS, Arduino IDE 1.6.7,

Following are the connections:

    External Power source  ESP8266
      3.3 V                  VCC
      GND                    GND
      3.3 V                  CHPD
      3.3 V                  GPIO0

    FTD232 UART  ESP8266
        RX         TX
        TX         RX

Plus FTD232 GND and Power Source GND are connected to make sure that there is a common reference.

I open the Arduino IDE and select Generic ESP 8266 board.

Open Serial Monitor:

AT command, no response..?

I have tried lots of different things found from web, even a new ESP8266, but no response.

Can anybody provide help...?

body:
The ESP8266-01 will boot and show some boot up messages at baud rate 76800 before switching to the default configured baud rate of 9600 or 115200.

Try setting the baud rate to 76800 and reset the ESP8266 to see if you can see the boot up messages first to determine if your circuit is working. You might see something like this:
> ets Jan 8 2013,rst cause:4, boot mode:(3,7)


body:
[![enter image description here][1]][1]
1.What firmware ? AT commands do not work in nodeMcu firmware.
Usually the AT firmware work to 115200 bps.

2.If your FTD232 works at 5V, you will need resistor between Arduino TX and ESP RX. ESP8266 only works at 3.3V.

3.Try esplorer - is a very nice tool to test ESP8266:
http://esp8266.ru/esplorer/

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


message:
Four Fast PWM outputs, in parallel

I need four Fast PWM signals for four different transistors.

I want to use timers 1+2 (pins 3, 11, 9, 10) so it wouldn't interfere with `delay(...)`.

I tried setting the timers to Fast PWM mode, and applied different OCRnA/OCRnB values, but nothing really worked - at most, I managed to get two good PWM signals, *one from each timer*.

How should I deal with `TCCRnA/TCCRnB, OCRnA/OCRnB` to achieve 4 parallel PWM signals?

My latest attempt:

    // Timer 1 Fast PWM setup: TOP=0x00FF, Update of OCRx at BOTTOM (0), TOV Flag Set on TOP
    pinMode(9, OUTPUT); pinMode(10, OUTPUT);
    TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
    TCCR1B = _BV(WGM12) | _BV(CS11) | _BV(CS10); // Divisor 64
    // Timer 2 Fast PWM setup: TOP=0xFF, Update of OCRx at BOTTOM (0), TOV Flag Set on MAX (0xFF)
    pinMode(3, OUTPUT); pinMode(11, OUTPUT);
    TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(CS22); // Divisor 64
    // ...
    int val = 200; // Desired PWM output
    OCR1A = val;
    OCR1B = val;
    OCR2A = val;
    OCR2B = val;

body:
Basically, your question comes down to this:

"How to generate two PWM signals with only one timer."

(Once you've got that figured out, you could set up 6 PWM channels)

Keep in mind that there also are PWM generator IC's, if you don't want to use up all your timers, which can be usefull for other things.

IF you really want to set all outputs to toggle at the same time (based on your code example) why won't you just use one PWM signal, and drive all the 4 devices with the same signal? (Given you're not going to change it)
IF you're going to drive motors, why would you need 4 different PWM signals? It's often enough to only use one PWM signal for the right tires/tracks and one PWM signal for the left tires/tracks.

----------
**Setting the max**

Since we want to generate different PWM signals from one timer, we can't just make the timer overrun (and generate a pulse or switch polarity at that point).
We want to let the timer run to completion over and over, and only change the signal when it reaches a set value.

The datasheet tells us this:

>  The TOP value can be assigned to be the fixed value 0xFF
(MAX) or the value stored in the OCR0A Register. (328P datasheet 15.2.1 Definitions)

**Setting a limit per pin**

We want to set 2 limits on one timer, each timer has an output compare register (OCR), the action will be generated when the timer hits this value.

> The Timer/Counter (TCNT0) and Output Compare Registers (OCR0A and OCR0B) are 8-bit registers. Interrupt
request (abbreviated to Int.Req. in the figure) signals are all visible in the Timer Interrupt Flag Register (TIFR0).
All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK0). (328P datasheet 15.2.2 Registers)

**Extra info on compare**

Below you can read some extra info on the signaling.
What actually will happen, depends on how the WGM

> 15.5 Output Compare Unit
The 8-bit comparator continuously compares TCNT0 with the Output Compare Registers (OCR0A and
OCR0B). Whenever TCNT0 equals OCR0A or OCR0B, the comparator signals a match. A match will set the
Output Compare Flag (OCF0A or OCF0B) at the next timer clock cycle. If the corresponding interrupt is
enabled, the Output Compare Flag generates an Output Compare interrupt. The Output Compare Flag is
automatically cleared when the interrupt is executed. Alternatively, the flag can be cleared by software by writing
a logical one to its I/O bit location. The Waveform Generator uses the match signal to generate an output
according to operating mode set by the WGM02:0 bits and Compare Output mode (COM0x1:0) bits. The max
and bottom signals are used by the Waveform Generator for handling the special cases of the extreme values in
some modes of operation (”Modes of Operation” on page 98).

**Fast PWM**
The actual settings are different per mode/modus, but for fast PWM we have:

    Table 15-3. Compare Output Mode, Fast PWM Mode(1)
    COM0A1 COM0A0 Description
    0      0      Normal port operation, OC0A disconnected.
    0      1      WGM02 = 0: Normal Port Operation, OC0A Disconnected.
                  WGM02 = 1: Toggle OC0A on Compare Match.
    1      0      Clear OC0A on Compare Match, set OC0A at BOTTOM, (non-inverting mode).
    1      1      Set OC0A on Compare Match, clear OC0A at BOTTOM, (inverting mode).

The table tells us we need to set COM0A1 and COM0A0 to 1.

    COM0B1 COM0B0 Description
    0      0      Normal port operation, OC0B disconnected.
    0      1      Reserved
    1      0      Clear OC0B on Compare Match, set OC0B at BOTTOM, (non-inverting mode)

This table tells us we need to set COM0B1 and COM0B0 to 1.

**WGM mode**

If it's all set up, we only need to put the PWM in the right mode.

    Mode WGM02 WGM01 WGM00 Timer/Counter TOP  Update-OCRx TOV-on
    0    0     0     0     Normal        0xFF Immediate   MAX
    1    0     0     1     PWM,P-Correct 0xFF TOP         BOTTOM
    2    0     1     0     CTC           OCRA Immediate   MAX
    3    0     1     1     Fast PWM      0xFF BOTTOM      MAX

So we'll need to set WGM02 to 0 and WGM01 and WGM00 to 1, to use fast PWM.F

**Succes?**

You should now be able to change the PWM's of these pins by setting the output compare registers of these.
Getting the double PWM of the other timer ready, shouldn't be much more different.
Be sure to set the right prescaler. Though it depends on a lot of external things.


message:
Logic level converter 12v to 5v

What is the cheapest and best method to convert 12v(14)<->5V(3.3)? Need to connect Arduino to a car.

I need logical shifter not buck converter to connect Arduino to car 12v circuit. I would like to control electrical equipment of car by Arduino. For example, I want to connect input pin to heater, when heater is on from 12v circuit I get HIGH 12v signal which processes by Arduino, but like everyone knows, Arduino can handle only 5/3.3V. Then Arduino going to change state of equipment by connecting optocoupler/relay/transistor to  button(of elect. equip.) and will act like physical press.
P.P.S I know that more clever to hack and control by CAN bus. But not all eq. are connected to CAN bus and it`s a little bit risky but I'm working on it as well.
I'm looking for best low cost solution. I have found it on [ebay][1] . Will it work like I want? Offer DIY solutions as well.

  [1]: http://www.ebay.com/itm/Level-Shifter-Logic-Level-Converter-12-Channel-5V-to-12V-or-12V-to-5V-/251604416861?hash=item3a94cab95d:g:DUYAAOSwxH1T2d~7

body: Use LM7805 linear voltage regulator to regulate to 5 v , it's all about 2-4$, you need LM chip and 2 capacitors, that's all :) and if you need 3.3 just search for linear voltage regulator


body:
Your safest option is to use an opto-isolator. Connect the LED side in parallel with the load with a suitable resistor, then the transistor side becomes, effectively, a button connected to the Arduino.

As far as the car is concerned you have just connected an LED. As far as the Arduino is concerned you have a button connecting to ground.

It provides complete isolation of the car's electrics from your Arduino.


body:
This might be what you need — a multi-channel level shifter with input and output voltage ranging from 3.3V to 18V:
https://www.ezsbc.com/index.php/featured-products-list-home-page/ls2.html#.WqmSZ2aZNGU

It's no bi-directional: you'll need a couple of boards if you want inputs and outputs from an Arduino to 12V.


body:
Ok, so... I can see your question is a bit obscure, so I'll try to cover a generic approach.

1. **Power** If you need to power the arduino, you can get a cheap car USB adapter. If you want a "solderable" solution, I'd avoid linear regulators (such as a 7805)and go with a cheap switching module. For low power applications I usually buy some modules called mini360 (for instance [here][1] is a link from aliexpress) which are cheap and ok for even some hundreds of milliamps. You FIRST turn the potentiometer to set the output voltage (checking with a multimeter) and THEN connect the arduino to it.

2. **Get status** If you need to get the status of something (e.g. whether the lamp is on or off) you have to analyse the circuit. If you have to detect if either 12V or GND are applied, you can solve the problem with a voltage divider. But if the lamp is always connected to 12V and then the GND side is he controlled one then you will always force a (small) current inside it. If this is the case, maybe an optocoupler is the best solution. If the signal is a PWM maybe you need some filtering, if it is a digital wire maybe it is already at the correct voltage, .... You have to figure out what is the best solution for you

3. **Set status** If you need to control something (e.g. turn on a light) your best bet is to use a 5V relay. There are plenty of them, even modules with the transistor and diode necessary to control them with an arduino.

Here are some ideas and rough schematics for the three points
<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/d8fmw.png)

<!-- End schematic -->

Just one **very big** WARNING: you have to carefully double check that the modification does not blow something up (for instance, you can make a short circuit if the body computer tryes to force a wire to 12V and you close the relay to ground). So... Be very careful, since what you do can break a lot of things, and if you are very lucky the bill can be *only* some couple of thousand dollars (I'll let you figure out what happens if you are not lucky enough)

  [1]: https://www.aliexpress.com/item/1pcs-Mini360-DC-DC-Buck-Converter-Step-Down-Module-4-75V-23V-to-1V-17V-17x11x3/32835208399.html?spm=2114.search0104.3.9.372623d0lCPKb6&ws_ab_test=searchweb0_0,searchweb201602_1_10152_10151_10065_10344_10068_10342_10343_10340_10341_10696_10084_10083_10618_10304_10307_10302_5711211_10313_10059_10184_10534_100031_10103_10627_10626_10624_10623_10622_5722411_10621_10620_5711311,searchweb201603_12,ppcSwitch_5&algo_expid=3bf6a53d-cc3c-479b-b30a-5a108f557776-1&algo_pvid=3bf6a53d-cc3c-479b-b30a-5a108f557776&priceBeautifyAB=0


message:
ESP8266 cannot read DHT22

I am trying to build a WiFi humidity and temperature sensor. My board is a nodeMCU using the ESP8266 connected via USB. The board is working fine with various WiFi examples and various serial examples. Hence I guest my environment is OK.

Now I am trying to connect a DHT22 to read temperature and humidity. To reduce the error sources I boiled down my code to the standard DHT example:

    // Example testing sketch for various DHT humidity/temperature sensors
    // Written by ladyada, public domain
    #include "DHT.h"
    #define DHTPIN 2
    #define DHTTYPE DHT22   // DHT 22  (AM2302)
    DHT dht(DHTPIN, DHTTYPE);

    void setup() {
      Serial.begin(9600);
      Serial.println("DHTxx test!");
      dht.begin();
    }

    void loop() {
      delay(2000);

      float h = dht.readHumidity();
      float t = dht.readTemperature();
      float f = dht.readTemperature(true);
      if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println("Failed to read from DHT sensor!");
        return;
      }

      Serial.print("Humidity: ");
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(t);
      Serial.println(" *C ");
    }

Nevertheless I always get the message "Failed to read from DHT sensor!".

Regarding the hardware I tried connecting the sensor with or without the 10k resistor, tried different DHTs and different pins. To rule out the DHTs I connected them with an Arduino Nano where these are working fine (both with and without resistor and using the same code). The only difference I see is that the Arduino is using 5V while the ESP8266 is using 3.3V - which is nonetheless inside the rating of the DHT.

Any ideas?

body:
I found, that the pin mapping printed at the board of the nodeMCU does NOT match the pin mapping in the library/software.

Check out [this issue/solution][1]. It states the correct pin mapping (e.g. pin 2 is "D4" at the board) and provides also an according workaround. My DHT22s are working now... :-)

  [1]: https://github.com/esp8266/Arduino/issues/584


body: I had been racking my brain for over 16 hours trying to figure out why this library would not work. I tested the DHT on an Arduino and it worked fine but whenever I tried on the nodeMCU it failed to read or gave spurious data. That is untill I saw the above answer that is not mentioned anywhere. The pins for the nodeMCU are not the same as the Arduino. (I thought that by defining the pin it would be using the pin stated) This is false as the library is mapped the Arduino pins so this is something to look out for, for any nodeMCU/ESP8266 beginners.


message:
Using Temperature sensor arduino to trip off an ac device

Using Temperation through arduino to trip off an ac device?

body:
Yes, there are lots and lots of project descriptions similar to yours (if I guesstimate) on the web. Google is your friend.

Here is one [link][1] to an interesting project - if you are interested in brewing beer.

Cheers!

  [1]: http://makezine.com/2014/03/28/arduino-controlled-tec-coolingheating-system-for-beer-fermentation/


message:
Porting my project to multiple Nanos

I'm still fairly new to the Arduino world. I got myself a kit with a clone board  couple of months ago and have successfully prototyped the project and got it to the state I want it to be. I now want to create 5 - 10 working models of what I've done.

I'd seen on Amazon that I could get 5 Nano clones for about £10 and this seemed ideal to me. Until I saw that people were complaining that some Nano's aren't quite a direct replacement for the Uno that I have working. There's some kind of problem with loading the software from the IDE.

I really don't want to do anything more than just load my software onto the Nanos "As Is" using the IDE I already have.

Can anyone recommend what I need to look out for to ensure that the Nanos I buy will work this way please?

body:
> ... people were complaining that some Nano's aren't quite a direct replacement for the Uno

First, I hope you have understood that the Nano and Uno have totally different board formats. The Uno is the classical Arduino format. And the Nano is for breadboards.

Second, (and this will have to be a guess in lack of info or reference in your question) the Nano USB hardware on clones may differ and require another device driver. There might be other component selections to reduce the cost such as alternative a crystal for the oscillator, protection fuse, etc.

Cheers!


body:
The Arduino Uno and Arduino Nano are fairly compatible.

**Problems:**

 - The board layout isn't the same, Nano's won't wield a classic "shield".
 - Nano's don't have a barrel jack.
 - Nano's (usually) have a micro USB connector. While the Uno has another one.

 - But, Nano's are smaller, withouth leaving out the USB connection.

**But wait!**

Microcontrollers of the same family are quite scaleable, Nano and Uno might even have the same micro on it! Be sure your Nano has the same Atmega328(P?) chip as your Uno.
Check if the pins you're using, are accessible on the Nano. Then you should be fine.

There is a little problem with cheap Arduino Nano's, I've bought 2, from 2 different vendors. They we're about 3$.

 - The first one featured a counterfeit FTDI chip. By installing the latest FTDI drivers, my FTDI actually got bricked. I had to undo this by using M_PROG or some EEPROM flashing tool to unbrick the chip, and install older drivers (which didn't corrupt it).
 - The second one featured an CH340G usb-serial chip. I had to download and install the drivers from a chinese website. But Windows wouldn't install unsinged drivers that easily. You have to go into advanced boot options mode and allow installing unsigned drivers.

Getting these Nano's working took me an reasonable amount of time. But they now are working quite well :)
It's something to take into account when buying cheap.

I wouldn't really bother for the alternative crystal, as long as they're 16Mhz. For time-critical behaviour, I wouldn't rely too much on your crystal.


message:
afmotor saying "servo does not name a type"

I have made a sumobot with an arduino, an afmotor shield and a 4-pin ping sensor when I upload my code it keeps giving me this error: "'Servo' does not name a type" here is my code.

```
#include <AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIGGER_PIN  A0  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     A2  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

 //speed variables for the left and right motor
int Lspeed = 180;
int Rspeed = 255;

//declaring the left and right motors and attaching them to
//their corresponding connector on the motor shield
Servo leftMotor;
Servo rightMotor;

void setup() {
  Serial.begin(115200);
  //sets initial speed
  leftMotor.setSpeed(Lspeed);
  rightMotor.setSpeed(Rspeed);
}

void loop() {
  unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
  unsigned int CM = uS / US_ROUNDTRIP_CM;

  if (CM < 15 && CM > 0) {
    int iteration = 0;
    while( iteration == 0){
      leftMotor.run(FORWARD);
      rightMotor.run(BACKWARD);
      iteration = 1;
    }
    delay(600);
  }

  //starts motors going forward
  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);

  Serial.print("Ping: ");
  Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
}
```

  [1]: http://codepen.io/jsmason/pen/EPQbyX

body:
You are creating `Servo` objects instead of `AF_DCMotor` objects. Change this:

    Servo leftMotor;
    Servo rightMotor;

to this:

    AF_DCMotor leftMotor(1);   // Change these numbers to the correct motor numbers
    AF_DCMotor rightMotor(2);  // you are using on the shield


message:
Use command line to upload hex code to teensy.ex

I need a command line implementation for uploading code to Teensy-LC through Windows 8.1 operating system
I know Paul has not released support for command line for Teensy-LC yet but i would like to know if any work has been done by anybody else in this regard.

I asked [this](https://arduino.stackexchange.com/questions/19844/use-command-line-to-upload-program-through-hex-file-to-teensy-lc) and [this](https://arduino.stackexchange.com/questions/18679/is-it-possible-to-create-a-standalone-exe-which-can-burn-the-code-into-a-teensy). But all these solutions include
> sending the hex file to the user.
>
>Asking him to open Teensy.exe
>
> Asking him to upload the hex file into Teensy.ex
>
> Asking him to run teensy_reboot.exe

So is it possible to create an installer of a sort for this purpose which eliminates the user performing all these operations separately and a guided installer simply with Next->Next which does the entire job.

But I suppose that since Command Line installer is not available for windows I don't know if this is possible for impossible.

So if there is any way I can achieve an installer UI for Teensy-LC bootloader that would be perfect

**Other viable option**
If not that is it possible to make the entire process happen with the person not having direct access to the hex file.
Like sending a packaged installer or something
I am not sure how this would happen but if there is any possible way please help me out

body:
This is starting to drift off topic for this site, but the best solution for making an automated programming utility for the Teensy on Windows, short of writing one yourself, would be to use some kind of UI automation framework to automate the process described in [my earlier answer][1]. My favorite one that I have used in the past is [AutoIt][2]. It has tools to inspect applications so that you can programmatically click buttons and fill out fields. There are even ways of having it run programs without them being visible to the user. There are plenty of tutorials on the web on how to use AutoIt so I would suggest googling for that. If you have further questions on how to do that, they would be more appropriate on a site other than Arduino.SE.

  [1]: https://arduino.stackexchange.com/a/19845/11086
  [2]: https://www.autoitscript.com/site/autoit/


message:
List of Arduino board preprocessor #defines

When one selects a board within Arduino IDE, a preprocessor definition is added to one of the behind-the-scenes files.

After a lot of hunting and some good fortune I found that the format of this definition is:

    #define ARDUINO_<PROCESSOR-DESCRIPTOR>_<BOARDNAME>

Some are easy to guess (`ARDUINO_AVR_UNO`, for example), but others are less so. The Pro Micro has '16' or '8' appended to the definition depending on the speed. I do not know if the definition is different for 5V or 3.3V. I haven't managed to guess the definition for the Mega2560, but it isn't anything obvious.

**Question 1**: Is there a list in existence of the possible definitions?

**Question 2**: Is there any distinction, as far as compilation and preprocessor involvement is concerned, between _BoardX_-5V and _BoardX_-3.3V, and how is this distinction defined?

body:
The first blank is the *platform*. This is "AVR" for AVRs, "SAM" for SAM-based Arduinos, etc. This is derived from the platform directory containing the core.

The second blank is the *board*. This comes from the entry in `boards.txt` in the core itself, and is the identifier before the first period.

There is no difference between compilation processes with regards to voltages; any speed difference is given in `F_CPU` and the board itself should not be checked for this.

So there is no definitive list, since the list is of arbitrary size due to its source.


body:
The list of board symbols can be generated by this shell command:

    $ grep board= boards.txt | cut -f2 -d= | sort -u
    AVR_ADK
    AVR_BT
    AVR_DUEMILANOVE
    AVR_ESPLORA
    AVR_ETHERNET
    AVR_FIO
    AVR_GEMMA
    AVR_LEONARDO
    AVR_LILYPAD
    AVR_LILYPAD_USB
    AVR_MEGA
    AVR_MEGA2560
    AVR_MICRO
    AVR_MINI
    AVR_NANO
    AVR_NG
    AVR_PRO
    AVR_ROBOT_CONTROL
    AVR_ROBOT_MOTOR
    AVR_UNO
    AVR_YUN

The boards are defined by the "build.board" property in the [boards.txt][1] file.

    mini.build.board=AVR_MINI

This property is used by the build [recipe][2] together with ARDUINO_-prefix.

    -DARDUINO_{build.board}

Cheers!

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/boards.txt
  [2]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/platform.txt#L52


body:
Mikael has the right answer, but there are multiple boards.txt files depending on the installed boards with board manager,
modifying the command to:

    grep board= `find . -name boards.txt` | cut -f2 -d= | sort -u
and running it from your base Arduino directory collects the whole set.


message:
Read information from Twitch's API and execute actions depending on the output

i'm trying to create a display that notifies me when someone goes live on twitch. I need to acess the API and check if the 'stream' object is null or not. Then, perform an action depending on this.

The address to the API is http://api.twitch.tv/kraken/streams/pedrinholuizf

What can I do? I'm using an Arduino Leonardo with the Ethernet Shield.

body:
Break your problem into small steps and try to identify the success criteria for each step. So you might:

1. Try to set up the Ethernet shield and get it to respond to a ping on your local network.
1. Try to connect to a site outside of your network.
1. See if you can find some examples of using the Twitch API.
1. Try to replicate one of the simple examples.
1. See if you can get the Stream object that you want.
1. See if you can read the value of the object.

If you have a plan and try to follow it you'll be able to tell us what you've been doing and where you got stuck / confused. That is likely to get you better answers – both because we can be more specific and also because we can see that you're "carrying your weight" as we work on the problem.


message:
Irrecvdemo program in or remote library gives fatal error #include<WProgram.h>

Whenever I compile irrecvdemo of or remote library it gives error saying that fatal error saying

> no file or directory exists `#include <WProgram.h>`

    #include <IRremote.h>

    int RECV_PIN = 11;

    IRrecv irrecv(RECV_PIN);

    decode_results results;

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }

    void loop() {
      if (irrecv.decode(&results)) {
        Serial.println(results.value, HEX);
        irrecv.resume(); // Receive the next value
      }
    }

body:
You are using a very old library on a modern IDE.  The file that was called `WProgram.h` in IDE version 0023 and below is now called `Arduino.h`.  You will need to change any references to `WProgram.h` to `Arduino.h` instead.

Well written libraries do this with a #ifdef block:

    #if (ARDUINO >= 100)
    # include <Arduino.h>
    #else
    # include <WProgram.h>
    #endif


message:
Arduino radio communications

I have an Arduino and I am building a space satellite, just for fun. I'm not going to launch it obviously.

I have built all the sensors and everything works. I was looking into communication because if a satellite is in space it needs to send down the data.

Is it possible to have radio communication between two Arduino or an Arduino and something else that are 100km apart, it doesn't need to particle, I'm just wondering if it is possible and how it works. Is it possible without going out to buy shields?

body:
There are three basic factors that control long distance communication:

1. Transmitter Power
2. Receiver Sensitivity
3. Signal Directionality

The more transmission power you have the "louder" your signal is at the receiver.

The more sensitive your receiver the "quieter" the signals it can pick up.

The more directional (focussed) your signal is the more arrives at the receiver and the less gets sent off elsewhere.

So you would think get all three of those and you're laughing, but it's not that simple:

* High power transmission requires high-power power source
* Good focus requires heavy and bulky antennae.

Neither of those are very good on a satellite, since you want it to be as small and light as possible and use as little power as possible.

So in general you have a medium to low power transmitter on the satellite with *reasonable* directionality, and put all the bulk on earth.  That is why satellite dishes are so big.  They give good focus, and the large size captures a lot of the signal making them more sensitive. You can also use very precise electronics to amplify the signal more.

There is, of course, nothing like that in a shield format, so you would have to create your own. The transmitter isn't so hard, since you don't want to have anything too meaty - the hard part comes when you want to make the base station.  If you can afford enough power to transmit a strong enough signal and have it with enough directionality you can use a satellite TV dish (not a little Sky dish, one of the bigger solid round ones - Sky satellites actually have quite powerful transmitters and the massive solar panels to go with it; not really practical for a small home-built satellite).  Getting the receiver and LNB (Low Noise Booster) tuned properly as well is vital - unless you're transmitting at the same frequency as the satellite the dish is intended to receive (which you mustn't or there'll be a lot of annoyed people around - there are specific frequency ranges you are allowed to use) then you will need to ensure the antenna is exactly the right length and that the LNB amplifies and filters the right frequency range.

Once you have got over all those hurdles the receiver is just a simple receiver.

The actual transmitter and receiver circuits themselves can be something fairly off-the-shelf (the lower the frequency the better since that goes further than higher frequencies) - it's what goes between - the antenna and amplifier - that makes it much more special and long range.


body:
Majenko covered several aspects of radio communications between a satellite and a ground station.  An additional factor to consider is that the [azimuth or altitude](https://en.wikipedia.org/wiki/Horizontal_coordinate_system) of a low-altitude satellite changes rapidly as it passes over a ground station.  For example, a satellite 100 km up takes about 86 minutes per orbit and travels at about 7.84 Km/s, and probably would be in view for less than a minute per pass.  [See eg *[Orbit of a satellite Calculator](http://keisan.casio.com/exec/system/1224665242)* at casio.com.]  Unless a phased array is used, and assuming communication is highly directional, the big dish on the ground will need to swing at up to 4.5° per second (about 270° per minute) as it tracks the satellite passing over.  The much smaller antenna on the spacecraft should rotate at the same rate, the opposite direction.

Note, an alternative to radio communications is a tight-beam laser system.  Rather than using big, bulky microwave or UHF antennas to achieve directionality, you would use a small telescope (a few cm of aperture) on the satellite and a larger telescope (as much aperture as you can afford) at the ground station.  Infrared or visible light lasers at each end of the link would be modulated to transmit at a high data rate.  Accurate tracking and aiming might end up being important research projects for this approach.


message:
Converting TinkerKit to native Arduino pins

Over the years, I have acquired many TinkerKit modules for my Arduino Uno. My only issue is that I need to find a way to code using the native syntax, and not the less-powerful TinkerKit variation. To do this, I need to know if TinkerKit maps its 3-pin connector to the Arduino Board's pins (ex: 1, 3, 5). If it does, what are the mappings?

Thanks in advance!

body:
The [TinkerKit Sensor Shield][1] helps understand the mapping. There is also the [TinkerKit Header File][2] with symbol mapping.

  [1]: https://store.arduino.cc/product/T020010
  [2]: https://github.com/TinkerKit/TinkerKit/blob/master/TinkerKit.h


message:
Arduino throwing error while using modbus RS485 code

I have been trying to make a communication with my industrial drive. All I want to do is read a few values of drive, like current, voltage etc.
For that I am using a library:

I don't understand why it's happening. When the same code I have used before and the sketch was uploaded on the board, very well.

Here's the code from an example:

    #include <SimpleModbusMaster.h>

    // led to indicate that a communication error is present
    #define connection_error_led 13

    //////////////////// Port information ///////////////////
    #define baud 9600
    #define timeout 1000
    #define polling 200 // the scan rate

    // If the packets internal retry register matches
    // the set retry count then communication is stopped
    // on that packet. To re-enable the packet you must
    // set the "connection" variable to true.
    #define retry_count 10

    // used to toggle the receive/transmit pin on the driver
    #define TxEnablePin 2

    // This is the easiest way to create new packets
    // Add as many as you want. TOTAL_NO_OF_PACKETS
    // is automatically updated.
    enum
    {
      PACKET1,
      PACKET2,
      // leave this last entry
      TOTAL_NO_OF_PACKETS
    };

    // Create an array of Packets for modbus_update()
    Packet packets[TOTAL_NO_OF_PACKETS];

    // Create a packetPointer to access each packet
    // individually. This is not required you can access
    // the array explicitly. E.g. packets[PACKET1].id = 2;
    // This does become tedious though...
    packetPointer packet1 = &packets[PACKET1];
    packetPointer packet2 = &packets[PACKET2];

    // The data from the PLC will be stored
    // in the regs array
    unsigned int regs[9];

    void setup()
    {
      // read 3 registers starting at address 0
      packet1->id = 2;
      packet1->function = READ_HOLDING_REGISTERS;
      packet1->address = 0;
      packet1->no_of_registers = 3;
      packet1->register_array = regs;

      // write the 9 registers to the PLC starting at address 3
      packet2->id = 2;
      packet2->function = PRESET_MULTIPLE_REGISTERS;
      packet2->address = 3;
      packet2->no_of_registers = 9;
      packet2->register_array = regs;

      // P.S. the register_array entries above can be different arrays

      // Initialize communication settings etc...
      modbus_configure(baud, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS);

      pinMode(connection_error_led, OUTPUT);
    }

    void loop()
    {
      unsigned int connection_status = modbus_update(packets);

      if (connection_status != TOTAL_NO_OF_PACKETS)
      {
        digitalWrite(connection_error_led, HIGH);
        // You could re-enable the connection by:
        //packets[connection_status].connection = true;
      }
      else
        digitalWrite(connection_error_led, LOW);

      // update the array with the counter data
      regs[3] = packet1->requests;
      regs[4] = packet1->successful_requests;
      regs[5] = packet1->total_errors;
      regs[6] = packet2->requests;
      regs[7] = packet2->successful_requests;
      regs[8] = packet2->total_errors;
    }

Also, here is the error I am receiving upon uploading the sketch

    This report would have more information with
      "Show verbose output during compilation"
      enabled in File > Preferences.
    Arduino: 1.0.6 (Windows 7), Board: "Arduino Uno"
    SimpleModbusMasterExample:110: error: 'packetPointer' does not name a type
    SimpleModbusMasterExample:111: error: 'packetPointer' does not name a type
    SimpleModbusMasterExample.ino: In function 'void setup()':
    SimpleModbusMasterExample:120: error: 'packet1' was not declared in this scope
    SimpleModbusMasterExample:127: error: 'packet2' was not declared in this scope
    SimpleModbusMasterExample:136: error: invalid conversion from 'int' to 'HardwareSerial*'
    SimpleModbusMasterExample:136: error: invalid conversion from 'Packet*' to 'unsigned char'
    C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h:143: error: too few arguments to function 'void modbus_configure(HardwareSerial*, long int, unsigned char, long int, long int, unsigned char, unsigned char, Packet*, unsigned int, unsigned int*)'
    SimpleModbusMasterExample:136: error: at this point in file
    C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h: In function 'void loop()':
    C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h:125: error: too many arguments to function 'void modbus_update()'
    SimpleModbusMasterExample:143: error: at this point in file
    SimpleModbusMasterExample:143: error: void value not ignored as it ought to be
    SimpleModbusMasterExample:155: error: 'packet1' was not declared in this scope
    SimpleModbusMasterExample:158: error: 'packet2' was not declared in this scope

body:
The code you are using is the example provided with the SimpleModbusMaster library found on GitHub: [https://github.com/angeloc/simplemodbusng][1]

It appears that the SimpleModbusMaster library isn't installed. This can happen if you install a new version of the Arduino IDE.

To install this library:

 1. Go to the link above and download the zip of the code.
 2. Extract the contents and then copy the folder "SimpleModbusMaster".
 3. Paste the folder into the Arduino/libraries folder located on your computer.  (On my computer it is: `C:\Program Files (x86)\Arduino\libraries`).
 4. Restart the  Arduino IDE. You can go straight to the example code by selecting: `File > Examples > SimpleModbusMaster > SimpleModbusMasterExample`

This procedure compiled for me with no errors.

  [1]: https://github.com/angeloc/simplemodbusng


message:
Read RFID Card Number in Processing over Serial

I have successfully setup up a RFID reader with Arduino Uno and EM-18 Card Reader Module.

Its program for Arduino is below:

    int count = 0; // count = 0

    char input[12];                                         // character array of size 12

    boolean flag = 0;                                       // flag =0

    void setup()
    {
       Serial.begin(9600);                                  // begin serial port with baud rate 9600bps
    }

    void loop()
    {
       if(Serial.available())

    {

    count = 0;

    while(Serial.available() && count < 12)          // Read 12 characters and store them in input array

    {
    input[count] = Serial.read();
    count++;
    delay(5);
    }

    //Serial.print("Card ID - ");

    Serial.print(input);      // Print RFID tag number

    }

    }

But when try to read the code over serial in the program for locking/unlocking mouse in Processing the values of strings don't match.
Hence the mouse doesn't get unlocked.

The program for processing is as below:

    import processing.serial.*;
    import java.awt.AWTException;
    import java.awt.Robot;

    Robot robot;
    boolean locked = false;
    Serial port;
    void setup()
    {
      println(Serial.list()); //Prints available ports

      port = new Serial(this, Serial.list()[36], 9600); //Chooses the first available port
      try
      {
        robot = new Robot(); //Creates robot
      }
      catch (AWTException e)
      {
        e.printStackTrace();
      }
    }

    void draw()
    {
      if (locked == true) robot.mouseMove(0, 0); //If locked, moves mouse to top left corner
      while (port.available() > 0)
      {
        String input = port.readString();
        //println(input);
        if (input.equals("11006F26DC84") == true) locked = false; //If it read my card it will unloack.
      }
    }

    void keyPressed ()
    {
      if (key == 'l')
      {
        locked = true; //Locks it
      }

      if (key == 'u')
      {
        locked = false; //Unlocks it
      }

      if (key == ESC)
      {
        key = 0; //Disables escape as quit
      }
    }

Please point the incorrect syntax and suggest correct one.

body: `input` has to be 13 characters in size; you forgot to include a byte for the null-terminator. Then right before `Serial.print(input)`, you write `input[12] = 0`. Also the argument to `string.equals()` should be a String as well; you must write the statement like this: `input.equals(String("11006F26DC84"));`


message:
How to latch a 200mS LOW pulse?

Trying to latch a 200 mS, LOW event to log the event.  LOW only occurs when external Watchdog timer sends reset pulse to the Arduino.

Is a D Latch suitable for this application?  It has been years since my digital class; help most appreciated.

How would you proceed?

body:
I understand your question to be :  you want to latch (and indicate) whenever an external watchdog timer has reset your Arduino.

D type flip flop (latch) can be used.  You would use the clock input as the trigger. However, most D types clock on a rising edge. You could use an inverter on the input to the clock to get the D type to clock on a falling edge. You would also connect the D (Data) input high (logic 1). Then when your input (event) goes low, the Q output will latch high.  The 200 mS is irrelevant because the latch ocurrs at the change from high to low (low to high on clock input).

You would also need a means of resetting the latch, which many D types have a reset input or a clear input.

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

You could also use a more simple SR latch (set reset latch) using 2 Nand gates.  SR latch changes state when the “set” input goes low (providing that R input was high).  Make the R input go low to reset the latch.

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

POSSIBLE ALTERNATIVE :  If you have some means of operator intervention (or even a switch).  You could have your program light an LED at startup.  Operator (person) could reset LED.  Then afterwards,  any reset (restart of program) would light the LED.

  [1]: https://i.stack.imgur.com/iLDH3.jpg
  [2]: https://i.stack.imgur.com/nAjFT.jpg


message:
Detecting Motion behind a robot

I am building a motion following robot. It has two PIR sensors on the left and right. It has an ultrasonic sensor in the front. When either of the PIR sensors detect motion then it turns to that side.

When both the PIR sensors sense motion then I calculate the distance first( with the ultrasonic sensor, if distance <= 50 cm and > 5 cm then the robot moves forward. But it could mean that the motion is either in the front or in the back. Thus, my robot moves forward even the motion is behind it.

 I need some help devising a method so that when motion is detected behind then the robot will turn back. I tried making the robot turn right when both the sensors detect motion, then it will turn towards the left(i.e. front) or right(i.e. back). But in reality this method is not so practical as it would to a lot of confusion when the intruder we are trying to detect is still in motion. Plz help. A sample sketch would help.

body:
This is a basic problem of only having two sensors.  There is no way that two sensors of this simple type (some motion yes/no) can be used to work out where the motion comes from except when there is a difference between the two sensors.  Anything else is, and always will be, ambiguous.

If you think of it as a circle divided in two, you have only three possible conditions:

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

That is, *left*, *right* or *somewhere*.  Not ideal.

So you need more data to be able to make a decision.  That means more sensors.  The ideal scenario is four sensors - left, right, front and rear.  That gives you many possible scenarios, including:

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

As you can see from that you have a full 360° idea of where the motion is. You can even know how far to the left it is by if the front or rear is also on.  For instance, using sailing terminology, those 8 circles would mean (in order):

1. Motion on the left beam
2. Motion on the port bow
3. Motion dead ahead
4. Motion on the starboard bow
5. Motion on the starboard beam
6. Motion on the starboard quarter
7. Motion dead astern
8. Motion on the port quarter

Also the dead-ahead and dead-astern could be indicated by just the forward or rear sensor on and the left/right sensors both off.  You could even use that fact to give some indication of the distance of the motion depending on the angular coverage of the different sensors.

  [1]: https://i.stack.imgur.com/d2Xeo.png
  [2]: https://i.stack.imgur.com/WPggl.png


message:
Precision voltmeter using Arduino

I am newbie, I need to measure precise voltage in range 0.00-0.80V, two digits precision.

The voltage will not be greater than 1V-1.2V.

I wonder if I need divider or not, I am sure that voltage won't rise above 1.2V.

Can I connect the point to measure directly to analog input, or I still need to use divider? Please explain why.

body:
A divider is used to (as the name suggests) reduce a higher voltage to a lower voltage.  Using a divider on a small voltage will only make it smaller and harder to measure.

To get the most out of your measuring you need to have the *reference* voltage as close to the highest voltage you want to measure as possible.  The highest voltage that can be applied is not dependent on the reference voltage, but the supply voltage, and as 1.2V is way less than 5V (or 3.3V on a 3.3V board) you have no worries there.

So you need to change the reference voltage - the voltage that the ADC uses as its upper *measurement* voltage.  That's simple enough, since many of the Arduino boards include an internal 1.1V analog reference voltage generator that you can switch to (see: [analogReference()](https://www.arduino.cc/en/Reference/AnalogReference))

So when you have switched to the 1.1V analog reference the ADC is capable of measuring 0-1.1V in 1024 steps.  That's 1.1/1023=0.00107V per bit of precision.

The formula is:

    V = ADC / 1023 * Vref

So a reading of 1 would give you 0.00107V - a reading of 2 would be 0.00215V, etc.  That's plenty of resolution to meet your 2 decimal places requirement.

***One thing to note*** though is that the internal 1.1V reference isn't that stable or accurate (or not even there on some chips).  If you need better stability and accuracy then it could pay to use an external voltage reference chip.  These are like a linear voltage regulator but are far more accurate and stable (and can't provide lots of current).  Pick one that is greater than your upper measurement voltage but as close to it as you can get (so just above 0.8V) and feed the output into the external *ARef* pin and switch the analog reference to the `EXTERNAL` mode.

You *could* use a voltage divider on the external ARef pin to provide a low reference voltage, but the stability and accuracy will be no better (and probably worse) than the internal 1.1V voltage reference, so there really is no point.


message:
SoftwareSerial library

How do I rectify this error?
Clearly it says there is some error in the library, so how do I correct it?

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:1: error: expected unqualified-id before 'if'

body:
As you haven't shown the code that produces the error when it's compiled, I can't say for sure what the problem is.  However, here are links to three instances of the same error:

• *[error: expected unqualified-id before 'if'](https://stackoverflow.com/q/8690446)* on stackoverflow

• *[Arduino: error: expected unqualified-id before 'if' (using ping sensor)](https://stackoverflow.com/q/14538210)*, also on stackoverflow

• *[error: expected unqualified-id before 'if'](http://forum.arduino.cc/index.php?topic=26465.0)* on arduino.cc.

In each case, the problem was due to executable code (as opposed to declarations) appearing outside of a function.  You may have put some executable statements outside of `loop()` or `setup()`, etc.


body:
Your copy of the SoftwareSerial library has become corrupted. Why is anyone's guess: maybe your hard drive is dying?

Replacing the file with a good copy will solve the problem. The simplest way to do that is to reinstall the IDE.


message:
Atlas Scientific pH project - serialEvent3 problems

I am trying to get this pH project working and I've noticed that the serialEvent3 never sets the boolean value sensor_string_complete to true.  I am not sure if it is actually capturing the values from the probe.  What I want is for every loop through it should grab a pH value and that is not happening right now.  Most times through the loop the serial3 port is not providing any values.  Here is my code:

    String sensorstring = "";
    boolean sensor_string_complete = false;
    float pH;

    void setup() {
      Serial.begin(38400);
      Serial3.begin(38400); // pH stamp
    }

    void serialEvent3() {                                 //if the hardware       serial port_3 receives a char
      sensorstring = Serial3.readStringUntil(13);         //read the string until we see a <CR>
      sensor_string_complete = true;                      //set the flag used to tell if we have received a completed string from the PC
    }

    void loop() {
      getPh();
      if (sensor_string_complete == true) readph();
    }

    void getPh() {
      Serial.println("we are here");
      Serial3.print("r");
      Serial3.print(13);
    }

    void readph(){
      Serial.println("read ph here");
      if (isdigit(sensorstring[0])) {
        pH = sensorstring.toFloat();
        Serial.println(pH);
      }
      else{
        Serial.println(sensorstring);
      }

      sensorstring = "";
      sensor_string_complete = false;
    }

This returns values such as
we are here
we are here
we are here
read ph here
7.0
we are here
read ph here
7.0
we are here
we are here
we are here
read ph here
7.0

I want this to return these values every loop.  I expect to see:
We are here
read ph here
7.0
We are here
read ph here
7.0

Any help on this would be great.  Thanks so much!

body:
On a typical Arduino, the delay between `loop()` ending and `loop()` running again is a few microseconds.  `Serial.println()` in `getPh()` is interrupt-driven so that call too takes only a few microseconds.  Writing two bytes with `Serial3.print()` at 38400 bps will take about half a millisecond.  In short, there is plenty of time for `loop()` to run several times before  `serialEvent3()` sets `sensor_string_complete`.

To call  `getPh()` once and `readph()` once per `loop()`, instead of

    if (sensor_string_complete == true) readph();

say

    while (!sensor_string_complete) {}
    readph();

This will stall the loop while the pH sensor takes and reports a reading.

Note, in `getPh()` instead of using two separate `Serial3.print()` statements, you can just say `Serial3.print("r\r")`.


message:
Using Bluetooth module HC-05 when Arduino is powered using a battery

I have a project that involves sending messages from an Android device to an Arduino using a bluetooth module. I am using an HC-05 bluetooth module and an Arduino Mega 2560.

It works as long as I power the Arduino to my laptop using a USB cable. However, I need to use an external power source and have been using a 6F22 9V battery connected through the VIN pin for this purpose, without facing any problems. But on connecting the HC-05, it does not even light up.

The Arduino is also connected to four dc motors, five servo motors (all of which are externally powered, only get digital signals from the Arduino), and seven HC-SR04 ultrasound sensors, whcih are powered through the 5V pin.

I have connected the HC-05 to the Arduino as follows:

HC-05   Arduino

VCC      3.3V

GND      GND

TX       RX

RX       TX           through a voltage divider

I am new to all this, and would be grateful for any help. Thank you.

body:
6F22 (PP3) batteries are among the wimpiest of batteries available.  They are not a good choice for anything except extreme low power applications, and anything involving radio transmitters is definitely not an extreme low power application.

Use a better battery.  I would recommend 6 AA batteries (you can get 6xAA battery holders with the same connector as a PP3 battery) which will give you considerably more power than a little PP3.

Either that or a 7.2V "2S" Li-Ion battery pack.


message:
Arduino Due: Interrupt-based ADC hangs processing

I am trying to build an oscilloscope using an Arduino Due and an LCD. I have the LCD running perfectly and started working on using the ADC peripheral to sample signals. Here's what I have so far:

    #define SAMPLE_BUFFER_SIZE 800
    volatile int sample_buffer[SAMPLE_BUFFER_SIZE];
    volatile bool sample_buffer_full = 0;
    volatile int sample_buffer_idx = 0;

    void adcm_init() {
        pmc_enable_periph_clk(ID_ADC); // To use peripheral, we must enable clock distributon to it
        adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST); // initialize, set maximum posibble speed
        adc_disable_interrupt(ADC, 0xFFFFFFFF);
        adc_set_resolution(ADC, ADC_12_BITS);
        adc_configure_power_save(ADC, 0, 0); // Disable sleep
        adc_configure_timing(ADC, 0, ADC_SETTLING_TIME_3, 1); // Set timings - standard values
        adc_set_bias_current(ADC, 1); // Bias current - maximum performance over current consumption
        adc_stop_sequencer(ADC); // not using it
        adc_disable_tag(ADC); // it has to do with sequencer, not using it
        adc_disable_ts(ADC); // deisable temperature sensor
        adc_disable_channel_differential_input(ADC, ADC_CHANNEL_7);
        adc_configure_trigger(ADC, ADC_TRIG_SW, 1); // triggering from software, freerunning mode
        adc_disable_all_channel(ADC);
        adc_enable_channel(ADC, ADC_CHANNEL_7); // just one channel enabled
        adc_enable_interrupt(ADC, ADC_IER_DRDY);            // Data Ready Interrupt Enable
        NVIC_EnableIRQ(ADC_IRQn);
        adc_start(ADC);
    }

    void ADC_Handler(void)  {
        if (!sample_buffer_full) {

            if ((adc_get_status(ADC) & ADC_ISR_DRDY) == ADC_ISR_DRDY) {

                sample_buffer[sample_buffer_idx] = adc_get_latest_value(ADC);
                sample_buffer_idx++;

                if (sample_buffer_idx == SAMPLE_BUFFER_SIZE) {
                    sample_buffer_full = 1;
                    sample_buffer_idx = 0;
                }
            }
        }
    }

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

    void loop() {
        Serial.print("Loop\n");
        if (sample_buffer_full) {
            for (int i = 0; i < SAMPLE_BUFFER_SIZE; i++) {
                Serial.print(sample_buffer[i]);
                Serial.print(" ");
            }
            Serial.print("\n");
            sample_buffer_full = 0;
        }
    }

This was copied and slightly modified from somewhere on the internet (can't remember where, though). I have also studied the docs and this code seems to make perfect sense and it should work.

The idea is for the sampling to be interrupt-based. However, if I set the ADC to freerunning mode and enable interrupts, it just gives up and stops working.

What I mean by that is: on my serial monitor, after pressing reset, all I see are 2 lines saying "Loop" and it just stops there. Normally it should print "Loop" indefinitely, and also print ADC values from time to time.

If I disable interrupts, "Loop" is printed indefinitely, but of course no values are shown. If I disable free-running mode, "Loop" is printed and no values are shown unless the buffer size is 1, in which case the same value is printed over and over (as expected, in that case the interrupt runs only once, right at the beginning).

The CPU clock freq. is 84Mhz, I'm going for the fastest I can get out of the ADC, so a sample is taken (and an interrupt is fired) every 1Mhz. That means 84 clock cycles per interrupt. Don't know for sure if that is enough for the rest of the program to work, but my gut tells me that's not a problem. Besides, I tried with a lower ADC clock value and it still didn't work.

Any ideas? I'm really at a loss here...

body:
In your interrupt handler, `ADC_Handler()`, you set `sample_buffer_full` when the buffer is full.  <s>I don't see anywhere in the code where  `sample_buffer_full` ever gets reset (cleared) once it's been set.</s>

While `sample_buffer_full` is set, it disables the body of the interrupt handler – ie, the handler's structure is

    if (!sample_buffer_full) { ...body of handler... }

– and in particular, prevents `adc_get_latest_value(ADC);` from occurring.  The [source code](https://android.googlesource.com/platform/external/arduino-ide/+/f876b2abdebd02acfa4ba21e607327be4f9668d4/hardware/arduino/sam/system/libsam/source/adc.c?autodive=0///) of `adc_get_latest_value();` is like

    uint32_t adc_get_latest_value(const Adc *p_adc) {
      return p_adc->ADC_LCDR;
    }

which accesses the ADC data register.  According to section 43.6.4 *Conversion Results* on page 1322 of the data sheet, Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf,

>The channel EOC bit in the Status Register (ADC_SR) is set and the DRDY is set. In the case of a connected PDC channel, DRDY rising triggers a data transfer request. In any case, either EOC and DRDY can trigger an
interrupt.
>
>Reading one of the ADC_CDR registers clears the corresponding EOC bit. Reading ADC_LCDR clears the DRDY bit and EOC bit corresponding to the last converted channel.

It appears to me that your code enables interrupts, fills a buffer, sets `sample_buffer_full`, then spins in `ADC_Handler()`.  That is, repeatedly executes `ADC_Handler()` without clearing the EOC bit.

Note, for  oscilloscope applications with a Due, I suggest using DMA buffers instead of one interrupt per conversion.  See [thread #137635](http://forum.arduino.cc/index.php?topic=137635.5), *speed of analogRead*, in forum.arduino.cc for DMA code to read one or two analog channels on a Due at one sample per microsecond.  Also see [edaboard.com/thread283843](http://www.edaboard.com/thread283843.html) and [forum.arduino.cc #186169](http://forum.arduino.cc/index.php?topic=186169.0)

*Edit note:* Although `sample_buffer_full` does get reset, that reset happens after a time-consuming for-loop.  Whether it takes some hundreds of microseconds or a few milliseconds, the for-loop is enough of a delay that at least one more conversion and interrupt will occur before `sample_buffer_full` gets cleared.  One unhandled conversion is enough to lock up the interrupt handler.  Here are some alternative approaches to consider:

• Use a circular buffer, and never stop filling it.  This is ok if you are only interested in the most recent data, rather than a complete waveform record.

• Set or reset `sample_buffer_full` as now; and remove the initial if test from the handler.  Instead, put an `if` before `sample_buffer_idx++;`, to not increment if the buffer is full.

• Turn off ADC's freerun mode.  This is a reasonable thing to do when not taking data.

• Turn off ADC's interrupt when not taking data.  Also reasonable.

• Use multiple buffers.  Reasonable, but by itself doesn't avoid the problem.

• Read the latest value every time the handler executes [for example, say `int datum = adc_get_latest_value(ADC);` as the first statement in the handler] and then only store that value in certain cases.  An easy and effective way to avoid problem.


message:
Transistor slows motor instead of turning it off

I'm new to electrical engineering and I am currently trying to make a motor turn on for one second, turn off for one second, and repeat.

I'm using an Arduino Uno's `digitalWrite()` feature to activate a transistor, allowing the external 9V battery to turn on the motor.

Although everything is responding, instead of the motor turning on and off like I want it to, it spins fast for a second, then spins slower for a second. I would like the motor to stop completely, but cannot figure out how to do that.

Here's the schematic of my circuit:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/EoTLx.png)

<!-- End schematic -->

**Code:**

    void setup(){
      pinMode(9, OUTPUT);
    }

    void loop(){
      digitalWrite(9, HIGH);
      delay(1000);
      digitalWrite(9, LOW);
      delay(1000);
    }

Why isn't the motor completely turning off?

body:
There are multiple things wrong with your drawn schematic:

- The ground symbol is not wrong but really misleading.
- You forgot to add a flyback diode.
- You wired the load the wrong way: the load is placed between the collector and VCC, not between emitter and GND.
- The base resistor is way too high.


body:
I can't make much sense of your diagram-  but this is the correct way to do it:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/cGWWK.png)

<!-- End schematic -->

R1 is low enough that the base gets 10-15mA of drive, sufficient for a few hundred mA of motor current. D1 protects the transistor Q1 when it turns off (from the motor inductance). The emitter of the NPN transistor should be grounded and then the collector will either be near ground or at the 9V level depending on whether it is off or on.

You may have damaged the transistor you are using (due to breaking it down in reverse across the E-B junction) so I would suggest proceeding with a new one. You didn't mention it, but it probably got quite warm.


message:
Arduino MP3 Player

I want to make a MP3 player with arduino. My problem is what board should I use? There is the SparkFun MP3 Player Shield, SparkFun Audio-Sound Breakout - WTV020SD. Then I want to attach a 2.8 TFT touch screen to control volume,change track etc. Can I attach it to for example on top of MP3 player shield?I'm thinking in this one https://www.adafruit.com/products/1651. And finally what speakers can I use with which board? I want some good small speakers, two to be exact.

I don't really need help with electronics and programming. Just need to know wich are the best components that can work with each other without spending a lot of money. Thank you.

Best Regards

body:
I would recommend you the [VS1003][1] chip ($2.30 on ebay) or module ($7 on ebay). It can play MP3, WMA, MIDI, WAV and can record and encode ADPCM. It's even programmable (own filters etc). See [this project][2].

  [1]: http://www.vlsi.fi/fileadmin/datasheets/vs1003.pdf
  [2]: http://arduino-cool.blogspot.com/2012/10/arduino-mp3-player-i.html


body:
I would recommend you do not use speakers but instead send the output to a 3.5mm stereo plug, so you can use headphones or speakers.

Is a 2.8" inch display really necessary?  You could probably get away with a 1" display and at a guess that would use less power.

Another idea may be to look at a Bluetooth interface for sending the sound to the headphones or speakers.

You could also look at a WIFI interface to provide additional control interface and to allow downloads straight to the device.  (ESP8266 would probably be the easiest interface).

Something you didn't mention was the power source.  Are you going to have internal batteries with a USB charging and power socket, so you can hook it to a PC or Batter Pack.


message:
c expected ; before ) token

void GravaFicheiros(CONFERENCIA *co)
    {

     int i, ii, iii;

     FILE *fp;

     fp = fopen("grabameisso", "wt");

     fprintf (fp, "%s\n", co->nomeconf);

     int k = NSessoes(co);
     fprintf (fp, "%d\n", k);

     for (i = 0; i < k; i++)
     {

      fprintf (fp, "%s\n%d\n%d\n", co->sessoes[i].tema, co->sessoes[i].hora, co->sessoes[i].auditorio);

      int a = NArtigos(co, i);

      fprintf (fp, "%d\n", a);

      for (ii = 0; ii < a; ii++)
      {

       fprintf (fp, "%s\n", co->sessoes[i].artigos[ii].titulo);

       int aa = NAutores(co, i, ii);

       fprintf (fp, "%d\n", aa);

       for (iii = 0; iii < aa, iii++)
       {

        fprintf (fp, "%s\n%d\n", co->sessoes[i].artigos[ii].autores[iii].nome, co->sessoes[i].artigos[ii].autores[iii].idade);
       }
      }
     }

     fclose(fp);
     return;

body:
Although you didn't ask a specific question I assume you want to know why there was an error in your code.

One of your for loops is missing a semi-colon.

>     for (iii = 0; iii < aa, iii++) //this line gives the error

Should be:

     for (iii = 0; iii < aa; iii++) //the comma should be a semi-colon

When it says ; expected before token ). It means quite literally that there is a ; missing before a ).


message:
How to use Multiple MPU9250 to Arduino Lilypad

Is it possible to connect more than one or to be specific 5 MPU9250 into 1 Arduino lilypad? How will I set the addresses, and where should I put the pins for SDA and SCL? I hope someone out there could help me on this project.

Cheers!

What if I have this working codes, how will I edit this to connect more than two MPU9250? Please guide me. Thanks.

     #include <Wire.h>
     #include <TimerOne.h>

     #define    MPU9250_ADDRESS            0x68

     #define    MAG_ADDRESS                0x0C

     #define    GYRO_FULL_SCALE_250_DPS    0x00
     #define    GYRO_FULL_SCALE_500_DPS    0x08
     #define    GYRO_FULL_SCALE_1000_DPS   0x10
     #define    GYRO_FULL_SCALE_2000_DPS   0x18

     #define    ACC_FULL_SCALE_2_G        0x00
     #define    ACC_FULL_SCALE_4_G        0x08
     #define    ACC_FULL_SCALE_8_G        0x10
     #define    ACC_FULL_SCALE_16_G       0x18

     // This function read Nbytes bytes from I2C device at address Address.
    // Put read bytes starting at register Register in the Data array.
    void I2Cread(uint8_t Address, uint8_t Register, uint8_t Nbytes, uint8_t*      Data)
    {
    // Set register address
    Wire.beginTransmission(Address);
    Wire.write(Register);
    Wire.endTransmission();

    // Read Nbytes
    Wire.requestFrom(Address, Nbytes);
    uint8_t index=0;
    while (Wire.available())
    Data[index++]=Wire.read();
    }

    // Write a byte (Data) in device (Address) at register (Register)
    void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data)
    {
    // Set register address
    Wire.beginTransmission(Address);
    Wire.write(Register);
    Wire.write(Data);
    Wire.endTransmission();
    }

    // Initial time
    long int ti;
    volatile bool intFlag=false;

    // Initializations
    void setup()
    {
    // Arduino initializations
    Wire.begin();
    Serial.begin(115200);

    // Set accelerometers low pass filter at 5Hz
    I2CwriteByte(MPU9250_ADDRESS,29,0x06);
    // Set gyroscope low pass filter at 5Hz
    I2CwriteByte(MPU9250_ADDRESS,26,0x06);

    // Configure gyroscope range
    I2CwriteByte(MPU9250_ADDRESS,27,GYRO_FULL_SCALE_1000_DPS);
    // Configure accelerometers range
     I2CwriteByte(MPU9250_ADDRESS,28,ACC_FULL_SCALE_4_G);
     // Set by pass mode for the magnetometers
     I2CwriteByte(MPU9250_ADDRESS,0x37,0x02);

     // Request continuous magnetometer measurements in 16 bits
     I2CwriteByte(MAG_ADDRESS,0x0A,0x16);

     pinMode(13, OUTPUT);
     Timer1.initialize(10000);         // initialize timer1, and set a 1/2   second period
     Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt

     // Store initial time
     ti=millis();
     }

     // Counter
     long int cpt=0;

     void callback()
      {
      intFlag=true;
      digitalWrite(13, digitalRead(13) ^ 1);
      }

      // Main loop, read and display data
      void loop()
      {
      while (!intFlag);
      intFlag=false;

      // Display time
      Serial.print (millis()-ti,DEC);
      Serial.print ("\t");

       // _______________
      // ::: Counter :::

       // Display data counter
      //  Serial.print (cpt++,DEC);
     //  Serial.print ("\t");

      // ____________________________________
      // :::  accelerometer and gyroscope :::

     // Read accelerometer and gyroscope
     uint8_t Buf[14];
     I2Cread(MPU9250_ADDRESS,0x3B,14,Buf);

     // Create 16 bits values from 8 bits data

    // Accelerometer
    int16_t ax=-(Buf[0]<<8 | Buf[1]);
    int16_t ay=-(Buf[2]<<8 | Buf[3]);
    int16_t az=Buf[4]<<8 | Buf[5];

    // Gyroscope
    int16_t gx=-(Buf[8]<<8 | Buf[9]);
    int16_t gy=-(Buf[10]<<8 | Buf[11]);
    int16_t gz=Buf[12]<<8 | Buf[13];

     // Display values

    // Accelerometer
    Serial.print (ax,DEC);
    Serial.print ("\t");
    Serial.print (ay,DEC);
    Serial.print ("\t");
    Serial.print (az,DEC);
    Serial.print ("\t");

    // Gyroscope
    Serial.print (gx,DEC);
    Serial.print ("\t");
    Serial.print (gy,DEC);
    Serial.print ("\t");
    Serial.print (gz,DEC);
    Serial.print ("\t");

    // _____________________
    // :::  Magnetometer :::

    // Read register Status 1 and wait for the DRDY: Data Ready

    uint8_t ST1;
    do
    {
     I2Cread(MAG_ADDRESS,0x02,1,&ST1);
    }
    while (!(ST1&0x01));

    // Read magnetometer data
    uint8_t Mag[7];
    I2Cread(MAG_ADDRESS,0x03,7,Mag);

    // Create 16 bits values from 8 bits data

    // Magnetometer
    int16_t mx=-(Mag[3]<<8 | Mag[2]);
    int16_t my=-(Mag[1]<<8 | Mag[0]);
    int16_t mz=-(Mag[5]<<8 | Mag[4]);

    // Magnetometer
    Serial.print (mx+200,DEC);
    Serial.print ("\t");
    Serial.print (my-70,DEC);
    Serial.print ("\t");
    Serial.print (mz-700,DEC);
    Serial.print ("\t");

    // End of line
    Serial.println("");
    //  delay(100);
     }

body:
According to [the datasheet](https://moderndevice.com/wp-content/uploads/2014/09/PS-MPU-9250A-01.pdf) the MPU-9250 can work in either I2C or SPI mode.

When it is in SPI mode you can connect up as many MPU-9250s as you have spare IO pins.  With SPI the clock and data lines are all shared, and each slave device has its own Slave Select line.

In I2C mode it is possible to only use 2 devices at once - the AD0 pin configures which is which device (connect it to GND or VCC to identify the two devices).

Interestingly the MPU-9250 does include an I2C master module for connecting other sensors to it. Theoretically it should be possible to connect the master port of an MPU-9250 to two other MPU-9250s, and each of those could connect to a further two MPU-9250s each, and so on and so forth in a huge tree.  However the programming of such an environment would be an absolute nightmare and not something I would like to undertake.

So in summary: use SPI mode, it's simpler.


body:
> where should I put the pins for SDA and SCL?

Same as on a Uno:

* SDA is on pin A4
* SCL is on pin A5

> Can you suggest me some links that can help me learn more about SPI?

I have [an SPI page](http://www.gammon.com.au/spi) and also one about [I2C](http://www.gammon.com.au/i2c).

There is also a page about SPI on this site: https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino

If you want to use 5 devices, it sounds like Majenko's recommendation is good: Use SPI. You would share MOSI/MISO/SCK between all devices (D11/D12/D13), and give each one a separate SS (slave select) line.


body:
> Is it possible to connect more than one or to be specific 5 MPU9250 into 1 Arduino lilypad?

Yes, that is possible with both SPI and I2C. With SPI you will need MOSI(11), MISO(12), SCK(13), and CSn where CSn is CS0..CS4 are digital pins in output mode for chip select.

With I2C the following pins are needed SDA(A4), SCL(A5), and CSn. The chip select pin is connected to AD0 on the device. AD0 is used for the lowest bit in the I2C address. Addressing is achieved by connecting AD0 to CSn and keeping all high except the one that is addressed. The I2C address is the same for all access. The CSn pin defines which device will response.

The example code below uses the lower address and chip select is put low for the selected device.

    // Chip select pin device#0
    const int CS0 = 4;
    ...
    void setup()
    {
      ...
      // Initiate chip select pin for device#0
      pinMode(CS0, OUTPUT);
      digitalWrite(CS0, HIGH);
      ...
    }
    ...
    void loop()
    {
       ...
       // Select device#0
       digitalWrite(CS0, LOW);
       MPU9250_someFunction();
       digitalWrite(CS0, HIGH);
       ...
    }

> How will I set the addresses, and where should I put the pins for SDA and SCL?

SDA is connected to A4 and SCL to A5.

Using the above given example code (from the question) a rewrite of the I2Cread function could be:

    // This function read Nbytes bytes from MPU9250 device with chip select pin.
    // Put read bytes starting at register Register in the Data array.

    void MPU9250_read(uint8_t CS, uint8_t Register, uint8_t Nbytes, uint8_t* Data)
    {
      digitalWrite(CS, LOW);

      // Set register address
      Wire.beginTransmission(MPU9250_ADDRESS);
      Wire.write(Register);
      Wire.endTransmission();

      // Read Nbytes
      Wire.requestFrom(Address, Nbytes);
      uint8_t index = 0;
      while (Wire.available()) Data[index++] = Wire.read();

      digitalWrite(CS, HIGH);
    }
    ...
    // Read magnetometer data from device#3
    uint8_t Mag[7];
    MPU9250_read(CS3, 0x03, 7, Mag);

Cheers!


body:
If you use I2C, you can use an I2C multiplex chip to handle the arbitration to handle lots of MPU-9250s.  I had a setup with 6x of them going.  I did find however, that the amount of CPU time that it takes for I2C communication is high, so once you get in to that many 9250s, you don't have much CPU time left over for other things.  Using SPI is a bit trickier to get going, but it is wicked fast and also lets you take advantage of the FIFO buffer on the 9250s.

Majenko mentioned using the I2C master functionality on the 9250 to daisy chain - I had also tried that approach before I tried the I2C multiplexer.  I have to say it was a horrible experience.  When you use that I2C master function, you are actually programming the advanced functionality of the 9250 instead of using the Arduino coding in C.  Once it all starts working (if it does), it acts quite flaky.  That functionality on the chip was really designed to enable using an external magnetometer on the 6250 to get 9dof.  Any more complex use than that gets hairy with the interchip timing, and initializing on startup is also rough.

Final answer - put in the time to learn how to use the SPI bus as mentioned in some of the other answers.  Once you get through the learning curve, it can run at up to 20khz communication speed.  SPI is designed for high speed communication.  I2C is designed to be easier to use but for things with lower update rates.


message:
What could I use to vary the temperature of a Heating Pad?

Could I get something like this, a 12v silicone heating pad, and vary its temperature with an arduino somehow?

http://www.banggood.com/Waterproof-Silicone-Flexible-Heating-Pad-6060MM-DC-12V-10W-p-972464.html

My grand plan is to put temperature sensors on it and make it hit a certain temperature, and make it hotter/cooler to try and reach a target temperature.

body:
In principle, I don't see any problems. Your heating pad uses 12V and 10W, which means it would be consuming slightly less than one amp of current. The MOSFET you linked can go up to 5A (needing a heat sink with over 1A).

You could use PWM (there are 6 pins on a Uno that can do that) to provide pulse-width modulation to control the amount of output you give to the heater.

You would, of course, need to measure the heat of the device to work out when to adjust the PWM output. You might look up using a PID algorithm to adjust the PWM output depending on the sensed heat input.

---

## References:

* [tag:pid]
* [tag:pwm]
* [tag:mosfet]
* [tag:sensors]


body:
If you want to control the temperature very accurately, try connecting a shunt resistor (value: <0.1 ohm) in series with the heater. Use an op-amp to amplify the voltage difference on its two terminals and read with Arduino the resulting value. You can calculate with it the actual current and therefore the actual resistance of the heating pad.

The value changes with temperature, you can use the resistance value to measure the surface temperature of the heating pad.


message:
PID tuning help

I'm currently working on a self-balancing robot with an Arduino Uno and a 10DOF ADXL345 sensor. Everything is going fine until I got to this PID tuning part. I've read about it several times but I'm unable to get the desired results. Can somebody give a detailed guide on PID tuning? Thank you.

body:
Maybe you can help yourself with this [tutorial][1] for PID line follower robot. I successfully tuned my PID for line following and had some success with PID for wall following with sonar.

  [1]: http://www.inpharmix.com/jps/PID_Controller_For_Lego_Mindstorms_Robots.html


body:
In real life there is no set equation to find the PID values. At best you'll get close with equations and then need to tune the parameters.

For anyone into PID loops have a read of [this][1].
I've found it to be excellent.

My advice is to:

 - only use P
 - set I & D to 0
 - get it and good as you can by trial and error
 - add I and trial it too

D is for experts really and may cause weird/undesirable jitter.

  [1]: http://controlguru.com/table-of-contents/


message:
Arduino declaring class in h and cpp file Undefined Reference

I am trying to compile my project, but unfortunately get errors.

I created class and separated implementation and declaration (cpp file and h file)

Here they are

**sensor.h**

    #ifndef SENSOR_H
    #define SENSOR_H
    #include <stdint.h>
    #include "Arduino.h"
    // Sensor types
    enum SensorType {
      ANY_SENSOR,
      UNKNOWN_SENSOR,
      WATER_SENSOR,
      TEMPERATURE_SENSOR,
      VIBRATION_SENSOR,
      INTERCOM_SENSOR,
      HUMIDITY_SENSOR,
      PIR_SENSOR,
      SOUND_SENSOR,
      LIGHT_SENSOR
    };
    class Sensor {
      public:
      // Variables declaration
        uint32_t sensorId;
        SensorType sensorType;
        float currentValue;
        bool isEnabled;
        float criticalLowerLevel;
        float criticalUpperLevel;
       // Methods declaration
        Sensor();
        Sensor(uint32_t id,SensorType type,long currentValue,bool isEnabled,long lower,long upper);
        String toString();
        bool isCriticalLevelRised() {
          return (this->currentValue >= this->criticalUpperLevel || this->currentValue <= this->criticalLowerLevel);
        };
        void enable(bool enable);
        void toggle();
        static String convertSensorTypeToString(SensorType sensorType);
    };

    #endif

And cpp file

    #include "sensor.h"
    Sensor::Sensor()
    {
      this->sensorId = 0;
      this->sensorType = UNKNOWN_SENSOR;
      this->currentValue = 0;
      this->isEnabled = false;
      this->criticalLowerLevel = 0;
      this->criticalUpperLevel = 0;
    }
    Sensor::Sensor(uint32_t id,SensorType type,long currentValue,bool isEnabled,long lower,long upper) {
      this->sensorId = id;
      this->sensorType = type;
      this->currentValue = currentValue;
      this->isEnabled = isEnabled;
      this->criticalLowerLevel = lower;
      this->criticalUpperLevel = upper;
    }
    void Sensor::enable(bool enable) {
       this->isEnabled = enable;
    }
    void Sensor::toggle() {
      this->enable(!this->isEnabled);
    }
    String Sensor::toString()
    {
      String response = "";
      response += F("Sensor id is ");
      response += this->sensorId;
      response += '\n';
      response += F("Sensor type is ");
      response += convertSensorTypeToString(this->sensorType);
      response += '\n';
      response += F("Sensor current value is ");
      response += this->currentValue;
      response += '\n';
      response += F("Sensor isEnabled is ");
      response += this->isEnabled;
      response += '\n';
      response += F("Sensor criticalLowerLevel is ");
      response += this->criticalLowerLevel;
      response += '\n';
      response += F("Sensor criticalLowerLevel is ");
      response += this->criticalUpperLevel;
      response += '\n';
      return response;
    }
    String Sensor::convertSensorTypeToString(SensorType sensorType) {
      switch (sensorType) {
        case UNKNOWN_SENSOR:
          return F("UNKNOWN SENSOR");
        case ANY_SENSOR:
          return F("ANY_SENSOR");
        case WATER_SENSOR:
          return F("WATER_SENSOR");
        case TEMPERATURE_SENSOR:
          return F("TEMPERATURE_SENSOR");
        case VIBRATION_SENSOR:
          return F("VIBRATION_SENSOR");
        case HUMIDITY_SENSOR:
          return F("HUMIDITY_SENSOR");
        case PIR_SENSOR:
          return F("PIR_SENSOR");
        case SOUND_SENSOR:
          return F("SOUND_SENSOR");
        case LIGHT_SENSOR:
          return F("LIGHT_SENSOR");
        default:
          return F("UNKNOWN TYPE");
      }
    }

And I got following errors

    ketch/NodeIntercom.ino.cpp.o: In function `sendSensorMessageToMaster(RF24Mesh*, SensorDataMessage*, char, unsigned int, bool)':
    /home/iron/Arduino/What'sHappening/NetworkMaster/additional_functions.h:48: undefined reference to `Sensor::toString()'
    sketch/NodeIntercom.ino.cpp.o: In function `handleSetSensorDataRequest(RF24NetworkHeader*)':
    /home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:97: undefined reference to `Sensor::toggle()'
    /home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:89: undefined reference to `Sensor::enable(bool)'
    sketch/NodeIntercom.ino.cpp.o: In function `SensorDataMessage':
    /home/iron/Arduino/What'sHappening/NetworkMaster/common.h:40: undefined reference to `Sensor::Sensor()'
    sketch/NodeIntercom.ino.cpp.o: In function `__static_initialization_and_destruction_0':
    /home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:35: undefined reference to `Sensor::Sensor(unsigned long, SensorType, long, bool, long, long)'
    collect2: error: ld returned 1 exit status

What I am doing wrong ?
Please help.

**EDIT**

Yes main sketch compiles perfectly where this files are located.

But I don't want to duplicate common files in my all my arduino sketches withing the project, they are the same for whole project. Here my files location

    --ArduinoProjects
    ---NodeIntercom
    ----NodeIntercom.ino
    ---MasterNode
    ----MasterNode.ino
    ----sensor.h
    ----sensor.cpp
    ----common.h

So this files are only located in MasterNode directory

And I tried to include them like this

    #include "/home/iron/Arduino/What'sHappening/NetworkMaster/common.h"
    #include "/home/iron/Arduino/What'sHappening/NetworkMaster/additional_functions.h"

And in common.h I include sensor.h
Also tried to include directly, but still the same

But headers files included as above works perfectly.

What is the right way to solve this problem, I don't want to duplicate this class in each folder whenever I change it.

If there is no way, maybe create symbolic link (I am using linux) ?

**PARTIAL SOLUTION**

Just use symbolic links in the sketch directory and this works perfectly

body:
There is nothing wrong with that class and its code (as far as I can tell) - it compiles perfectly fine.

What is probably wrong is that the IDE isn't picking up the code and compiling it in to your project.

Is this class part of the sketch, or is it a separate library that you are writing?  If the latter you have to ensure that the IDE knows about it, and it can only look for it when you load the IDE, so if you haven't restarted the IDE since creating the library you must do that so it can find the new library.


body:
The Arduino build preprocessing cannot locate the sensor source and header files if they are located in another sketch directory. The files needs to be moved to separate directory if shared (as a library).

    --Sketchbook
    ---NodeIntercom
    ----NodeIntercom.ino
    ---MasterNode
    ----MasterNode.ino
    ---libraries
    ----Sensor
    -----Sensor.h
    -----Sensor.cpp

The Sensor header is included with

    #include <Sensor.h>

in the sketches that needs to use it.


message:
Trouble with large numbers

Probably something stupid, but I can't figure out how to work with these large numbers, then cast the result (which will be small) to an integer. I keep getting negative numbers, which I think means I'm overflowing somewhere.

    int freq = 440;
    int len = 256;
    long timer = 2000000.0 / (freq * len);
    int roundedTimer = int(timer);

I should get 18, but I'm getting -108...

body:
`freq * long`, since they are both integers, are calculated as integers.

`440*256=112640` - in binary that is `1 1011 1000 0000 0000` and trimmed to 16 bits becomes `1011 1000 0000 0000` which is `-18432` and that is where the heart of your problem is.  Unless you explicitly say otherwise the Arduino's compiler does all calculations (except floating point) as 16-bit signed integers.

By casting the values to `long` it forces the compiler to 'overflow' the 16-bit limit and use a 32-bit limit instead:

    long timer = 2000000 / ((long)freq * (long)len);

Another alternative is to define `freq` and `len` to be `long` from the outset instead of `int`.


message:
Calculate OCR2A from audio frequency

I'm working on a Arduino-based synthesizer using [this tutorial](http://makezine.com/projects/make-35/advanced-arduino-sound-synthesis/), specifically using a wavetable and 1-bit DAC. I understand that the value for OCR2A register sets the frequency, but how do I calculate the value?

I've seen [this list of notes](http://cdn.makezine.com/make/35/OCR2A-frequency-table.pdf) which is great, but I want arbitrary frequencies in Hz...

Here's the code I'm working from:

    #include <avr/interrupt.h>

    // sinewave parameters
    #define FREQ 18
    #define PI2 6.283185    // 2*PI saves calculation later
    #define AMP 127         // scaling factor for sine wave
    #define OFFSET 128      // offset shifts wave to all >0 values

    #define LENGTH 256      // length of the wave lookup table
    byte wave[LENGTH];      // wavetable

    void setup() {

      // populate wavetable
      for (int i = 0; i < LENGTH; i++) {
        float v = (AMP * sin((PI2 / LENGTH) * i));
        wave[i] = int(v + OFFSET);
      }

      // set timer1 for 8-bit fast PWM output
      pinMode(9, OUTPUT);       // make timer’s PWM pin an output
      TCCR1B = (1 << CS10);     // set prescaler to full 16MHz
      TCCR1A |= (1 << COM1A1);  // pin low when TCNT1=OCR1A
      TCCR1A |= (1 << WGM10);   // use 8-bit fast PWM mode
      TCCR1B |= (1 << WGM12);

      // set up timer2 to call ISR
      TCCR2A = 0;             // no options in control register A
      TCCR2B = (1 << CS21);   // set prescaler to divide by 8
      TIMSK2 = (1 << OCIE2A); // call ISR when TCNT2 = OCRA2
      OCR2A = FREQ;           // set frequency of generated wave
      sei();                  // enable interrupts to generate waveform!
    }

    void loop() {
      // nothing to do here!
    }

    // called every time TCNT2 = OCR2A
    ISR (TIMER2_COMPA_vect) {   // called when TCNT2 == OCR2A
      static byte index = 0;    // points to each table entry
      OCR1AL = wave[index++];   // update the PWM output
      asm("NOP; NOP");          // fine tuning
      TCNT2 = 6;                // timing to compensate for ISR run time
    }

body:
The equation to calculate it is given in the first article you linked:

[![From linked Makezine article "Advanced Arduino Sound Synthesis"][1]][1]

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

The 2MHz value comes from the factor of 8 prescale on the 16MHz clock and 256 is the size of the lookup table specified by your `LENGTH` define. If you start from a frequency you want to synthesize, just use the above equation to solve for the necessary value of OCR2A. Note that since you have to input integer values to OCR2A, you can't really achieve *arbitrary* frequencies, but you're certainly not locked in to the values given in the supplemental musical note PDF you reference.

So, to solve for OCR2A:

    OCR2A = TCNT2_rate / (desiredFreq * wavetableLength);


message:
Maximum frequency of digital signal in Arduino Uno?

As Arduino Uno has a 16 MHz oscillator but while running program it has less frequency because some of the processing power is used for running the program.
I have used the `delay(1)` but it is giving me around 500 Hz.

**My questions:**

1. Is there any way to achieve more than 500 Hz?
2. What would be the maximum frequency of digital signal for below program?

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

    void setup() {
      pinMode(13, OUTPUT);
    }

    void loop() {
      digitalWrite(13, HIGH);
      digitalWrite(13, LOW);
    }

body:
1. Yes, use the hardware timers.

2. You can achieve 8 MHz.

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

Example sketch which outputs 8 MHz on pin 9 on a Uno:

    #ifdef __AVR_ATmega2560__
      const byte CLOCKOUT = 11;  // Mega 2560
    #else
      const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
    #endif

    void setup ()
      {
      // set up 8 MHz timer on CLOCKOUT (OC1A)
      pinMode (CLOCKOUT, OUTPUT);
      // set up Timer 1
      TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
      TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
      OCR1A =  0;       // output every cycle
      }  // end of setup

    void loop ()
      {
      // whatever
      }  // end of loop

If you change OCR1A you can get lower frequencies. If you change the prescaler you can get lower frequencies again.

See [my page about timers](http://www.gammon.com.au/timers) for more details.


body:
Also, don't forget that there are alternative methods of toggling outputs.

You can use PORTS to do the job.

Here's a good [example][1]. And another [here][2].

And this code is the idea behind it:

    void setup()
    {
      DDRD = B11111111; // set PORTD (digital 7~0) to outputs
    }

    void loop()
    {
      PORTD = B11111111; // set PORTD pins (digital 7~0) high
      PORTD = B00000000; // set PORTD pins (digital 7~0) low
    }

P.S. Don't forget that the port numbering is in reference to the chip pins and not the Arduino pins/legs.

  [1]: http://www.billporter.info/2010/08/18/ready-set-oscillate-the-fastest-way-to-change-arduino-pins/
  [2]: http://tronixstuff.com/2011/10/22/tutorial-arduino-port-manipulation/