message:
Confusion with ATmega328P and 3.3V/8MHz

Firstly, I have tried to set the bootloader to be 8MHz internal oscillator.

I have tried the board setup from here - https://github.com/oshlab/Breadboard-Arduino.

And also the `breadboard-1-6-x.zip` setup from here - http://www.arduino.cc/en/Tutorial/ArduinoToBreadboard.

Burning the bootloader in both cases seems to work, with fuse settings of `-Uefuse:w:0x05:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xE2:m` (using Arduino IDE 1.6.7):

    avrdude: 1 bytes of efuse written
    avrdude: verifying efuse memory against 0x05:
    avrdude: load data efuse data from input file 0x05:
    avrdude: 1 bytes of efuse verified
    ...
    avrdude: 1 bytes of hfuse written
    avrdude: verifying hfuse memory against 0xDA:
    avrdude: load data hfuse data from input file 0xDA:
    avrdude: 1 bytes of hfuse verified
    ...
    avrdude: 1 bytes of lfuse written
    avrdude: verifying lfuse memory against 0xE2:
    avrdude: load data lfuse data from input file 0xE2:
    avrdude: 1 bytes of lfuse verified

When I try and run the test sketch (below) at these voltages:

- 3.3V it fails (tried multiple 3.3V sources, all fail).
- 4.23V (3xAA rechargeable batteries) it works.
- 4.8V (3xAA alkaline batteries) it works.
- 5V it works.

To try and determine if it was my power sources or the bootloader that was the problem I uploaded this test sketch on my ATmega328P, an Arduino Nano (all Nanos are 16MHz?) and a 16MHz Arduino Pro to see if the red LED (with 100 Ohm resistor for ATmega328P) lights up in about the same time. This test sketch also does not work at 3.3V, and must be run at 5V to work.

(*edit*) When running this test sketch at 3.3V I see **no** 3.3V logic level on **any** output pin with my multimeter.  When running at 4.23, 4.28, 5V I see this logic level on all output pins.

(**update**) When connecting the +ve of the LED directly to 3.3V, the LED lights up.  So the 3.3V source has enough power to light the LED directly.

So I assumed that because my ATmega328P circuit has no crystal in it (and the Nano and Pro Mini are 16MHz), these loops would execute in different amounts of time?  But no, the loops *do* execute at the same speed (3 and a bit seconds) - so is my Nano/Pro Mini underclocked, or my ATmega still running at 16MHz but without a crystal??  Rather confused.

Thanks.

(**update**) I tried a second ATmega328P, same problem.

(*code edited to use 14 output pins*)

    void setup() {
      for (int p=0; p<14; p++) pinMode(p, OUTPUT);
    }

    void loop() {
      // waste some time.
      int y = 0;
      for (int i = 0; i < 11; i++) {
        for (int j = 0; j < 11; j++) {
          for (int k = 0; k < 101; k++) {
            y+=analogRead(A0);
          }
        }
      }
      for (int p=0; p<14; p++) digitalWrite(p, y % 2);
      for (int p=0; p<14; p++) digitalWrite(p, HIGH);
      delay(1000);
      for (int p=0; p<14; p++) digitalWrite(p, !(y % 2));
      for (int p=0; p<14; p++) digitalWrite(p, LOW);
      delay(1000);
    }

body:
If you are using an LED to indicate that your sketch is running, then that may be the problem.

For example, if you have a fairly average red LED, it might have a forward voltage of 2.0v @ 20ma (refer to your spec sheet for your particular LED). Putting these values into the [LED calculator][1], it would tell you that you need a 150 ohm resistor. You might have tested this, and seen the LED light up.

Then, if you drop the voltage to 3.3v, your LED might be either very dim, or (more likely!) not light up at all. Putting 3.3v into the same web page, it shows you need a smaller resistor, 68 ohm, for the same LED.

P.S. - I just noticed your paragraph about the green LED - a "true green" LED might have a voltage drop of 3.3v, which means for 5v you would need a 100 ohm resistor (as described in your paragraph); for a 3.3v supply you would need a 1 ohm resistor instead. This is pretty certainly your problem

  [1]: http://led.linear1.org/1led.wiz


sender: user

sender: assistant

body:
If you are powering your circuit off a cell battery, you might find that your battery cannot supply enough current. To test this, use a multimeter to measure the voltage of the battery, while your circuit is connected (and possibly, or possibly not, running). If the voltage drops below 2.7v (as defined by your fuses - use the [AtMel Fuse Calculator][1] page to see what your fuses mean), your chip will shut down, causing the voltage to rise back, turning the chip back on, and round it goes.The battery may even take a while to recover (I think last time this happened to me, it took about 10 seconds -I thought I'd destroyed the battery).

This is fairly common issue with motors (which draw a lot of power), but depends on your exact battery, and the exact load.

If this happens, you might get away with using multiple batteries in parallel (connect all the + sides together, to the + side of your circuit; all the - sides together to the - side of your circuit). Most battery holders are in series, which means they boost the voltage instead; you will have to do your own wiring for this.

  [1]: http://www.engbedded.com/fusecalc/


body:
It was a brownout fuse problem.

Changing `boards.txt` from:

`atmega328bb.bootloader.extended_fuses=0x05`

to

`atmega328bb.bootloader.extended_fuses=0x02`

solved it for me (*).

The chip and red LED now work at 3.01V  (1xAA alkaline and 1xAA rechargeable) and 3.19V (2xAA alkaline).

(*) not sure why I had to invert the bits (`0000 0010`=0x02 versus `0000 0101`=0x05) when compared to the tables below.

-----

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

  [1]: https://i.stack.imgur.com/TZjQh.jpg
  [2]: https://i.stack.imgur.com/kedG0.jpg


body:
Hy all,

I´m facing the same issue. Had an ATMEGA328P-PU with 8Mhz Oscillator on a breadboard that did not work with 3.3V (stabilized) as a supply. At 5V things work as expected.

Finally I got things running with extended fuses set to xxxxx110, which sets BOD to 1.8V. I coud verify that my ATMEGA328P-PU does not run with fuses set to xxxxx101 = 2,7V (max. 2.9V). The supply is about 3.4V and has blocking condensators, so it cannot be a supply issue.

Best regards, Eckehard


message:
Are there any detail examples of Si4463

Recently, I bought two [Si4463][1] chips, but I don't know how to use them. It seems complex. I'd like to know if there are any examples of an Si4463 used with an Arduino?

  [1]: https://www.silabs.com/Support Documents/TechnicalDocs/Si4464-63-61-60.pdf

body:
I've looked at the data sheet for this and I think it is the wrong choice of device for a beginner.  Can I suggest that you start by looking at a relatively simple DPI interfaced device, such as a sensor or RTC.  This will teach you the basics of sending commands via the Wire library.  You might even get the hang of it just by looking at existing libraries.

I can't find a library, so you are going to need to write your own.  The library will need a begin function which initialises you class and a write and read function, which write and read from an address.

    void begin(void);
    uint8_t read(const uint8_t& address);
    void write (const uint8_t& address, const uint8_t& bytesOfData, const uint8_t* pData);

You will need to flesh those functions out, but that's it.  If you want to make you library more useable read the datasheet and create wrapper functions for each of the registers that can be accessed.

    // This instruction requires 10 buts spread over two bytes.
    void writeFrequencyOffset (const uint8_t& highByte, const uint8_t& lowByte)
    {
      write (0x73, lowByte);
      write (0x74, highByte);
    }

The process of creating friendly wrappers is a tedious operations, just reading the data sheet and translating that into code.


body:
This seems to be the Chip used on the RFM24. Have a look on the RadioHead Library:

[http://www.airspayce.com/mikem/arduino/RadioHead/classRH__RF24.html][1]

I normally use the same libs for the RFM69 (Semtech SX1231) with my [Whisper Node][2] and works fine. I would expect the same for the RFM24.

Btw, getting a silicon and building the Radio can be quite complicated. You might would consider starting with a Dev Kit or an assembled module.

Also, I don't think HopeRF produces RFM24 anymore, can't find on their site (http://www.hoperf.com/rf_transceiver/). If you just need it for a single project and does not intent to build a product of that, might be better chose a different/more popular option. Will be easier to find support for it on the Internet.

  [1]: http://www.airspayce.com/mikem/arduino/RadioHead/classRH__RF24.html
  [2]: https://talk2.wisen.com.au/product-talk2-whisper-node-avr/


body:
The Si4463 IC from Silicon Labs is a great communication chip with very good sensitivity. However, its onboard MCU uses SPI as a communication interface to communicate with an external microcontroller.

In a module such as an HC-12, an STM8SF103F3 microcontroller which is programmed to act as an SPI to UART bridge. HC-12 modules lets you control all of the internal functionality of the Si4463, even using AT+ commands for things like adjusting baud rate and transmission power. Unfortunately, the code doing the SPI to UART bridging is proprietary, which leaves you at a disadvantage if you're trying to use the Si4463 chips to build a real product.

But perhaps, if you have purchased something like the RFM26W module, or you simply have a bare-bones Si4463 IC to work with, then you will need to communicate with it via the SPI pins. It must be noted that there is no standard Arduino library available for communicating with the Si4463's SPI pins.

Working with SPI pins can get a bit complicated as you're trying to sync the clockwork. If you want to get your hands dirty, then you could go ahead and have a look at the [Si4463][1] datasheet and look at the SPI timing parameters on page 16.

Fortunately, there is a Si4463 library project on GitHub which you can look into and perhaps modify the code to fit your needs.

Here is the GitHub page for the Si4463 Arduino library made by zkemble:

[https://github.com/zkemble/Si446x][2]

Here is the blog post where he explains it in more detail:

[http://blog.zakkemble.net/si4463-radio-library-avr-arduino/][3]

Here is the documentation for the said library:

[https://zkemble.github.io/Si446x/_si446x_8h.html][4]

  [1]: https://www.silabs.com/documents/public/data-sheets/Si4463-61-60-C.pdf
  [2]: https://github.com/zkemble/Si446x
  [3]: http://blog.zakkemble.net/si4463-radio-library-avr-arduino/
  [4]: https://zkemble.github.io/Si446x/_si446x_8h.html


message:
Need to buy a new breadboard?

I'm new to Arduino and haven't done any education in electrical engineering before, so this might be a very dumb question.

I'm busy with a project to control two servo motors with Arduino. Now yesterday I connected the wires incorrectly to the breadboard, so the wires started smoldering. I didn't connect the resistor correctly, so I guess that might have been the problem.

Now I replaced the wiring, but it's not working and I don't know if the software might be the problem or the breadboard need to be replaced as well. I cannot see anything wrong with the breadboard, but it was warm so I don't know if it might be burned from the inside? The wiring of the servomotors seems to be okay, so I guess that I don't need to replace those I hope.

Any tips about how to check everything is still working?

Or might it be a good idea to buy an LED and add it to the breadboard to ensure it's okay?

EDIT:
I guess I found some code to check that the servomotors are still okay. Just add them directly to the Arduino and run some code: [Sweep][1]

One other question: one of the servomotors doesn't have a black, red and yellow cable but a red, brown and orange. How can I know which ones the same as yellow, red and black?

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

body:
To answer your last question (for 99%):

    red = +
    brown = gnd
    orange = pwm (speed)

To test: try measure resistance with multimeter, gnd and + should have the lowest resistance.

And to be save: buy a new breadboard, a bad partly melted breadboard, or pieces of solder spoiled, is a nightmare.

Otherwise you can test with a multimeter the resistance of your breadboard for columns (close to 0) and rows 1.


body:
Not all servo motors have the same color cables, that's the manufacturers choice, although they should be standardized. You can test them with a multi-meter, low resistance is usually ground, slightly higher one is usually is usually the power, the other will be the signal. Breadboards are generally cheap and if you suspect yours is not functioning properly, buy a new one. I have two of these and they work very well for $10. [MPJA powered breadboard][1]

  [1]: http://www.mpja.com/Powered-830-Point-Breadboard/productinfo/30176+TE/

Additionally, if you have a motor driver shield, they usually have a three pronged port for your servo cable to connect to. Try that as well.


body:
You could check the connections of the breadboard, using a multimeter (set to continuity check) and wires in the breadboard holes, with the + and - leads, from the meter, at either end of each row/column of connections, following the diagram below:

[![Breadboard connections][1]][1]

It might be a bit tedious, but it should only take thirty minutes maximum, and would give you peace of mind as well as saving you four Euros...

If you say that it was working before and now is not, then maybe the breadboard is damaged. However, it is unlikely that the whole breadboard is... try moving your components to a different part of the breadboard.

The breadboard could possibly get warm, as servos *can* use a fair bit of current, and breadboards aren't really designed for power circuitry. You *may* be better off using an **Arduino Servo shield** and connecting the servos directly to that, rather than using the breadboard. Why are you using a breadboard - can you, as [Majenko states][2], provide a schematic diagram?

Answering the last part of your question - Taking the graphics from [my answer][3] to https://arduino.stackexchange.com/questions/20931/code-to-control-servo-with-shield, to show the different colours for the four different connector types:

Futaba and Airtronics connectors

[![Futaba and Airtronics connectors][4]][4]

Hitec and JR Radio connectors have the same pin out:

[![JR Radio and HiTec connectors][5]][5].

This means that the red, brown and orange leads go to a *JR Radios connector*.

  [1]: https://i.stack.imgur.com/mgQVL.png
  [2]: https://arduino.stackexchange.com/questions/23257/need-to-buy-a-new-breadboard#comment-44152
  [3]: https://arduino.stackexchange.com/questions/20931/code-to-control-servo-with-shield/20942#20942
  [4]: https://i.stack.imgur.com/Sy2RH.gif
  [5]: https://i.stack.imgur.com/Kjs4s.gif


message:
Detection of DS18B20, arduino Mega

I just bought a DS18B20 temperature sensor. I can't detect the device when i run this code :

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

    // Data wire is plugged into pin 10 on the Arduino
    #define ONE_WIRE_BUS 10

    // Setup a oneWire instance to communicate with any OneWire devices
    // (not just Maxim/Dallas temperature ICs)
    OneWire oneWire(ONE_WIRE_BUS);

    // Pass our oneWire reference to Dallas Temperature.
    DallasTemperature sensors(&oneWire);

    void setup(void)
    {
      // start serial port
      Serial.begin(9600);
      Serial.println("Dallas Temperature IC Control Library Demo");

      // Start up the library
      sensors.begin();
     }

     void loop(void)
    {
      // call sensors.requestTemperatures() to issue a global temperature
     // request to all devices on the bus
      Serial.print(" Requesting temperatures...");
      sensors.requestTemperatures(); // Send the command to get temperatures
      Serial.println("DONE");

      Serial.print("Temperature for Device 1 is: ");
      Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
        // You can have more than one IC on the same bus.
        // 0 refers to the first IC on the wire

    }

Here are my connections:
[![enter image description here][1]][1]
and output on Serial Terminal is:

      "Temperature for Device 1 is: -127.00 Requesting temperatures...DONE"

I also tried to detect the address of my device but with no success.

I am using an arduino Mega 2560, i have read in some forms that maybe it has something to do with Clock speed or something like that.

I appreciate your help.

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

I mainly followed this tutorial : http://www.hobbytronics.co.uk/ds18b20-arduino

body:
In the [Tutorial][1], which you are following, it says,

> So we will use the 2 wire method. Simply connect both the GND and VDD
> pins to 0V (yes both)

and it shows:

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

but I think you are missing this step, because i can't see any connection like that here:

[![enter image description here][3]][3]

  [1]: http://www.hobbytronics.co.uk/ds18b20-arduino
  [2]: https://i.stack.imgur.com/b9Tc4.jpg
  [3]: https://i.stack.imgur.com/M0C5H.png


body:
I attached VDD to GND and set it up so the 4K7 resistor was connecting the 5V to the data line - at first it didn't work, then I swapped it around as if the VDD and data lines from the sensor were switched - which it turned out they were.

Might be the case with your one.


message:
using enums in functions

Given the following enums

    enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
    enum class CrossingZoneState: uint8_t {
     CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
     CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
     CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
    };

Where RELAY_OFF = HIGH, HIGH is #define HIGH 0x1 which I assume is a C++/Arduino constant? because I didn't define it. And RELAY_ON = LOW, LOW is 0x0

in the following function I get the error that follows.

    CrossingZoneState CheckEntrySensor(uint8_t esp) {
     //esp, short for entry sensor pin
     if (digitalRead(esp) == HIGH)
     {
      state = CrossingZoneState::CROSSINGZONE_CLEAR;
      return state;
     }
     else if (digitalRead(esp) == LOW)
     {
      state = CrossingZoneState::CROSSINGZONE_OCCUPIED;
      return state;
     }
     // if the digital read errs, return the current state so it re-runs
     return state;
    };

    boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState relayState)    {

     int testInt = 0;
     if (relayState == RelayState::RELAY_OFF)
     {
      testInt = 1;
     }
     digitalWrite(relayNumber, relayState);
     if (digitalRead(relayNumber) == testInt) {
      return true;
     };
     return false;
    };

I tried having RelayState be an enum class as well but was getting similar type errors. Here is the error from VS2015 with the code shown above.

> Compiling debug version of 'ModelRRXingStateMachine' for 'Arduino/Genuino Uno'
ModelRRXingStateMachine.ino:11:55: error: 'RelayState' has not been declared
:boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState relayState)
ModelRRXingStateMachine.ino:2:1: error: 'CrossingZoneState' does not name a type
:CrossingZoneState CheckEntrySensor(byte esp)
Error compiling project sources

I'm not a professional programmer and am new to C++, usually writing in C# or VB.Net so I'm not sure what the compiler is looking for here, both enums are declared and one is declared with a type. Also, the VS code editor is showing no errors, the errors shown above show up in the error window when I try to build.

body:
For one thing, you are using the variable state without defining it. Moreover, you have not declared the functions CheckEntrySensor() and throwRelayAndCheckStatus() . When you define a function without first declaring it, the arduino preprocessor builds its own declarations, but often does so in a defective way. This is one of the idiosyncracies of the arduino environment versus a plain C++ compiler.

The following compiles:

    enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
    typedef enum RelayState RelayState_t ;

    enum CrossingZoneState {
        CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
        CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
        CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
    };
    typedef enum CrossingZoneState CrossingZoneState_t ;

    CrossingZoneState_t CheckEntrySensor(uint8_t esp) ;
    boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState_t relayState) ;

    CrossingZoneState_t CheckEntrySensor(uint8_t esp)
    {
      CrossingZoneState_t state ;
        //esp, short for entry sensor pin
        if (digitalRead(esp) == HIGH)
        {
            state = /*CrossingZoneState_t::*/CROSSINGZONE_CLEAR;
            return state;
        }
        else if (digitalRead(esp) == LOW)
        {
            state = /*CrossingZoneState::*/CROSSINGZONE_OCCUPIED;
            return state;
        }
        // if the digital read errs, return the current state so it re-runs
        return state;
    }

    boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState_t relayState)    {

        int testInt = 0;
        if (relayState == /*RelayState::*/RELAY_OFF)
        {
            testInt = 1;
        }
        digitalWrite(relayNumber, relayState);
        if (digitalRead(relayNumber) == testInt) {
            return true;
        };
        return false;
    }

Or, if you want to avoid the use of typedef, you can use the following:

    enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
    enum CrossingZoneState: uint8_t {
        CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
        CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
        CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
    };

    enum CrossingZoneState CheckEntrySensor(uint8_t esp) ;
    boolean throwRelayAndCheckStatus(uint8_t relayNumber, enum RelayState relayState) ;

    enum CrossingZoneState CheckEntrySensor(uint8_t esp) {
        enum CrossingZoneState state ;
        //esp, short for entry sensor pin
        if (digitalRead(esp) == HIGH)
        {
            state = CROSSINGZONE_CLEAR;
            return state;
        }
        else if (digitalRead(esp) == LOW)
        {
            state = CROSSINGZONE_OCCUPIED;
            return state;
        }
        // if the digital read errs, return the current state so it re-runs
        return state;
    }

    boolean throwRelayAndCheckStatus(uint8_t relayNumber, enum RelayState relayState)    {

        int testInt = 0;
        if (relayState == RELAY_OFF)
        {
            testInt = 1;
        }
        digitalWrite(relayNumber, relayState);
        if (digitalRead(relayNumber) == testInt) {
            return true;
        };
        return false;
    }


body:
The solution was to move the enum declarations to a header file, due to the fact this was a VM add-in issue which will be resolved once they've implemented arduino version 1.6.8.

Adding this code to a header file and removing it from the main file resolved the issues and the code builds and runs.

    // ModelRRCrossing.h

    #ifndef _MODELRRCROSSING_h
    #define _MODELRRCROSSING_h

    #if defined(ARDUINO) && ARDUINO >= 100
     #include "arduino.h"
    #else
     #include "WProgram.h"
    #endif
    #pragma once
    // Arduino Digital I/O pin numbers for MEGA
    //note: digital pins 30-45
    //MEGA is a MUST for this project
    enum {
     Relay1 = 30, Relay2 = 31, Relay3 = 32, Relay4 = 33, Relay5 = 34, Relay6 = 35,
     Relay7 = 36, Relay8 = 37, Relay9 = 38, Relay10 = 39, Relay11 = 40,
     Relay12 = 41, Relay13 = 42, Relay14 = 43, Relay15 = 44, Relay16 = 45
    };

    enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
    enum class CrossingZoneState : uint8_t {
     CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
     CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
     CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
    };

    #endif


message:
Programming problem I need both if else cases to work but only else loop is running

#include <SoftwareSerial.h>
    #include <Servo.h>
    Servo myservo1, myservo2, myservo3;

    int bluetoothTx = 14;
    int bluetoothRx = 15;

    SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

    void setup()
    {
    myservo1.attach(9);

    //Setup usb serial connection to computer
    Serial.begin(9600);

    //Setup Bluetooth serial connection to android
    bluetooth.begin(9600);
     }

    void loop()
      {
        if(bluetooth.available()>0)
         {
          if(bluetooth.available()>=4)
           {
            char buffer[4];
              for(int i=0;i<4;i++)
             {
              buffer[i]=bluetooth.read();
             }
           int incomingValue = atoi(buffer);

          if(incomingValue>=1000 && incomingValue<=1360)
            {
               unsigned int servopos = bluetooth.read();
               unsigned int servopos1 = bluetooth.read();
               unsigned int realservo = (servopos1 * 256) + servopos;

             if (realservo >= 1000 && realservo < 1360)
              {
                  int servo1 = realservo;
                  servo1 = map(servo1, 1000, 1360, 0, 360);
                  myservo1.write(servo1);
                  Serial.println("servo 1 ON");
               delay(10);
                }
               }
              }
             if(bluetooth.available()==2)
              {
                char inbit=bluetooth.read();
                if(inbit=='A'||inbit=='D');
               {
                char myval= bluetooth.read();
                if(myval== 'A')
                {
                  myservo1.attach(9);
                }

                 if(myval== 'D')
                  {
                   myservo1.detach();
                  }
                 }
                }
               }
              }

body:
There are so many things wrong with that program I can't begin to sort it out.

Here's some of the most glaringly obvious errors:

    if(bluetooth.read() >=0 && bluetooth.read() <=360)

Read a character. Check it's at least 0. Read a second character. Check it's less than 360.  Since characters are between 0 and 255 that will always succeed if there is one character of any form to read (if there is no characters to read you get -1).

    else if(bluetooth.read()=='A'||'B'||'C'||'D'||'E'||'F');

Read another character and compare it to 'A'. This if is true if the character read is A. It also succeeds if B, or if C or if D, etc. That's not "if it's equal to C", just "if C". C is a character literal, so it's equivalent to a number. Any number that is not 0 is TRUE, therefore it's equivalent to:

    if character is A or TRUE or TRUE or TRUE...

Which of course is just true, so it will always succeed regardless.

    char myval= bluetooth.read();
    if(myval== 'A')

Read yet another character from bluetooth (I sure hope there are enough there...) then compare it to a list of characters that are the same as you looked at above. You're comparing a *new* character this time, not the one you compared with the list a few lines beforehand.


message:
Arduino continually resets when connected to external power supply, but not USB

I'm working on a seemingly simple Arduino project which plays a sound and flashes an LED when provoked by some trigger.

**The problem:**

When powered by an external power supply, the Arduino continually resets after playing ~1/4 seconds of audio. When powered from USB, it works fine (however the LED, being powered from the external power supply, of course does not work here).

**Wiring diagram**:

[![wiring diagram][1]][1]

**Parts list**:

 - Arduino Pro Mini 5V
 - Adafruit MAX98306 3.7W amplifier
 - Sparkfun FemtoBuck LED Driver
 - 4 Ohm 3W speakers
 - 3W LED

I am using a 9V 1A power supply. Again, when no speakers are connected, the Arduino and LED work as intended. It's only when a speaker is connected that the board resets over and over again. Playing roughly 1/4 of a second of audio and then resetting implies to me that there's insufficient current, however, the problem persists even after using a 2.5A power supply.

**Things I have tried:**

 - Increasing the power supply to 12V 2.5A
 - Desoldering the LED driver (even with the LED driver removed, the board still resets)
 - Checking continuity and staring at the wiring for long periods of time while scratching my head

Overall, I'm at a loss as to why it would work when powered via USB instead of through my external power supply.

What am I doing wrong? Any insights are greatly appreciated!

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

body:
Most likely lack of current - lack of current able to be provided by the Mini. The audio is powered from the onboard regulator on the Mini, which has limited current capacity.

If too much current is drawn it will either get too hot and go into thermal shutdown until it cools down enough, or it will drop the output voltage, making things reset and crash.

Power the audio system from an external 5V regulator.


body: your power supply may be faulty. try a another power supply which can supply more current and common the GND of arduino and power suply..it may have internal short circuit or lack of current.


message:
The most practical plug socket

I am starting some Arduino's projects with different sizes (very small based on Arduino Nano and bigger using Arduino Mega). These projects will be manipulated by students and they will connect and disconnect many times the wires. I will try to not use breadboard if I can. In order to develop very versatile projects, the idea will be to use very useful plug sockets. Currently I have no idea of which kinds of plug sockets I can use.

Do you have any idea about the existing plug sockets (from 2 to 6/8 wires) and which one it is preferable to use?

**Complements:**

 - Some shields and components I already have and want to use have sometimes some plugs sockets (similar to [this][1]) but sometimes only some classical pins
 - I want also to build my own shields by integrating plug sockets to the arduino or to another shield
 - Some parts will be also composed by small electrical circuit on which I want to integrate plug sockets aswell
 - I will also use LiPo batteries (for example [this one][2] which have a connector I can't buy currently because I don't know the reference)
 - Communications will be also achieved using SPI and I2C

  [1]: http://boutique.semageek.com/fr/280-grove-base-shield-v2.html?adw=1&gclid=Cj0KEQjwrte4BRD-oYi3y5_AhZ4BEiQAzIFxn5xRoul9Pb_uKKQ_Tahm-_D9FlSqx8guNvUjOANcEHgaAlzR8P8HAQ
  [2]: http://eud.dx.com/product/hubsan-h107-a05-3-7v-240mah-li-ion-polymer-battery-black-844217433

body:
Ok, so more info from the OP:

* non-electrical engineering students needs a prototyping platform
* minimize possible damages, support hot plug-and-play
* not too expensive

## Dedicated connector

I suggest using standard subD9 connectors. Sensors shall have male pins, while the control board female socket (this makes very hard to do accidental short circuits on the control board). We were using these connectors in a daily basis in a lasershow system, and I was very statisfied. Inexpensive, easy to solder, works with a wide range of cables or separate wires.

In many cases, you can integrate the sensor into the housing of the connector. For example, an IR receiver, an accelerometer, etc. fits well.

You can use off-the-shelf serial cable extenders which makes it very versatile.

Since it is a D shaped connector, there is only one possible way to connect a sensor to the mainboard, and we're golden.

## Dedicated connector light

NSL25 and NSG25 are my favorites:
http://www.soselectronic.hu/?str=371&artnum=4927&name=nsl-25-2-g
http://www.soselectronic.hu/?str=371&artnum=4934&name=-nsg-25-2

Although these are inexpensive wire to board connectors, it is very hard to misconnect them. Criping is a PITA, but you can purchase pre-crimped connectors with wires such as http://www.soselectronic.hu/?str=371&artnum=6175&name=-p-35003
One 3 wire female connector with wires costs about 50 USD cent.

Note though that in this case, the control board has the male connectors. By accidentally dropping a coin to the connector, or using a screwdriver, it is easy to run into short circuits. This leads us to the next plan...

## Any inexpensive connector with proper electric protection

Probably the most inexpensive solution is to use standard headers and pins. Here you may also wish to buy ready made cables, than start crimping yourself:
http://www.soselectronic.hu/?str=371&artnum=6171&name=-p-2543

This however opens up a can of worms of misconnection:

 * connection by one or multiple pin off
 * connection in reverse direction
 * shorting the pins on the board

Against sorting, you shall have a multifuse on the power pins, say, 250mA. On each IO pin, you shall have a series resistor of 470 ohm, this ensures that no miswiring can destroy the Arduino.

On the sensor-side, things are a little more tricky. You need a shottky (or an equivalent P fet diode) to ensure that reverse polarity connection will not destroy your sensor. If the sensor has output pins, also use a series 470 ohm resistor.

Considering all the hassle, using a standard subD9 connector is a way easier:

* it has enough dedicated pins for I2C, SPI, and a generic IO for dumb sensors
* the pins can handle more current, and there are more pins you can connect in parallel to have enough power for small motors
* it is impossible to misconnect (once all sensor sockets use identical wiring)

## Don't forget ESD protection

In any case, it is a good idea to have some sort of ESD protection whenever you have connectors, and wires, and rough external world.

Have at least a TVS diode on the power pins (say, an 5.8V or 6V unidir TVS will do). On IO pins you can use a simple series resistor, or you can opt for a TVS.

During hot plug and play, it may happen that sensitive sensors get powered in a strange way. E.g. first 5V then the sensor output is getting connected, but no GND for a short moment. Some sensor may get damaged in this case. Use diodes to fix this.

For sensors requiring sudden current peaks (e.g. WIFI, or a motor), add at least 470uF/16V electrolyte capacitor right to the sensor end of the connector. This way once the sensor is connected to a long extension wire, you still have acceptable power to use in sudden current peaks.

Some sensors (e.g. IR receivers) are sensitive to power glitches. Consult their datasheet, use the suggested RC filtering network on the power pins.


message:
Arduino Digital Input. Trigger HIGH by 12V to 36V

I want to build a small circuit that will switch a LED on (for arguments sakes) when the cars ignition gets switched on. But I want to make it versatile so I can work with between 12V - 36V (Cars, Trucks, etc). What would be the best to read the Ignition status via the arduino. Know I have thought of an idea by working with voltage divider. Basically taking the principal of reading voltage [Instructable Example][1] and working from there. Any thoughts?

  [1]: http://www.instructables.com/id/Arduino-Reading-Analog-Voltage/

body: you can use transistor bias circuit, opto-couples circuits, op amp circuit or a simple relay circuit, to get 5V output signal when 12V-36V signal is triggered.


body:
Even easier:

* input - series 220 ohm resistor, and a 78L05 voltage regulator (check for maximum voltage). This allows you handling like 4..30V and get a solid "1" on digitalRead. (4V input makes like 3V output which is still logic high).


message:
Receiving serial data in acsii, how to split it.

Hello I want to know how to split an incoming serial message that comes in this format CxxxLxxx, x=number, so i can take the 3 numbers after the C and save them and then take the 3 numbers after the L and also save it, i have a code for this but it doesn't always work, can anyone tell me where I´m wrong or is the approach I´m taking is not the right one. Thanks.

    int value = 0;
    int channel;
    int x;
    String str;
    int y;
    String str1;
    int le;

    void loop()
    {
    if (Serial.read() == le)
    { }
      else
           {
            str = Serial.readStringUntil('C');
            str1 = Serial.readStringUntil('L');
            channel = Serial.parseInt();
            value = Serial.parseInt();
          DmxSimple.write(channel, value);
          le = Serial.read();
          Serial.println();

           }
    }

body:
This:

    if (Serial.read() == le)
    { }

looks very suspicious - sometimes it can read the C or L and therefore render the rest of your code useless.

Also Serial.parseInt shall be avoided - it returns the first thing which looks like a number, and will not wait for all three numbers.

However, your problem is likely the DMX write speed. While the DmxSimple.write is getting executed, no new incoming message can be processed. Depending on your actual Arduino board and chip, there is some buffer, but the solution is not rocket-proof at all.

You can:

 * make a solid protocol between the PC and the Arduino, i.e. the PC sends one command, arduino sends it out over the DMX, and Arduino answers an OK to the PC. The PC will not send out any new command unless it has received an OK first.
 * avoid these ad-hoc mess, i.e. serial-reads and serial.printlns here-and there.

For example, if you change the protocol so: CxxxLxxxE (E stands for end) you can utilize readStringUntil to read the input until a separator, and then use the toInt method to actually convert the read data to integer:

    void loop() {
        strDummy = Serial.readStringUntil('C');
        strC = Serial.readStringUntil('L'); // xxx from CxxxL
        strL = Serial.readStringUntil('E'); // xxx from LxxxE
        channel = strC.toInt();
        value = strL.toInt();
        DmxSimple.write(channel, value);
    }

###After learning that it is not possible to change the protocol, here is a new plan
    int channel;
    int value;
    void loop() {
        if (Serial.read()=='C') { // wait for a C
            channel=Serial.parseInt(); // parse till first non-number
            value=Serial.parseInt(); // parse till first non-number
            DmxSimple.write(channel, value);
        }
    }

See https://www.arduino.cc/en/Tutorial/ReadASCIIString for a tutorial. Note that Arduino Serial commands are pretty confusing sometimes :) for example, parseInt will actually consume one non-number character implicitly after parsing a number.

Also note that this solution works well if the command is sent as one batch. If you are trying to send the command manually, e.g. from a terminal window, character by character, parseInt may time out. Consider increasing the timeout to 10 seconds or more by https://www.arduino.cc/en/Serial/SetTimeout


message:
Arduino sketch taking forever to upload, followed by multiple issues

I am using Arduino Uno board with Windows 10. From the tutorials on Arduino website, I am trying to upload the following code:

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      int sensorValue = analogRead(A0);
      Serial.println(sensorValue);
      delay(1);
    }

It had undergone a series of issues:

First,
`avrdude: ser_open(): can't open device "\\.\com3"`

I searched for his issue, and found that most common solution id to go to device manager and change the name of the port, then unplug and plug again the arduino board. I did that

Second,

    C:\Program Files (x86)\Arduino\hardware\tools\axr\bin\avr-ar:
    unable to rename 'core.a'; reason: file exists\\

I thiught it could be a memory problem. I used the reset button on the board, and repeated steps from the solution to the first problem. I tried to upload the code again.

But now, I am not getting any error message. But the problem is that it is taking forever to upload the code. I see `Uploading...` status since a long while. The green progress bar is also complete, but no uploading completed till now.

Any help to understand and solve this will be appreciated.

body:
When the Arduino IDE says its uploading but never uploads, it is most likely a COM port issue. Try plugging the Arduino in a different port and make sure you change the port in the IDE. The problem seems to be you have changed the Arduino port, but not in the IDE. The Arduino IDE registers the previous port as open and tries to upload the program to that port. Go to `Tools > Serial Port` and it should list the ports(example):

    COM 2
    COM 3
    Arduino Uno at COM 4
    •COM 4
Every time you unplug and replug the Arduino you should check your ports and select the appropriate one ( It usually says `Arduino *type* at COM *port number*`

    COM 2
    COM 3
    •Arduino Uno at COM 4
    COM 5


message:
How to use Arduino Pro Mini without Programmer

I'm a software engineer, but I'm not too skilled at understanding hardware design yet. I'm trying to learn how to use an Arduino Pro Mini board without the programmer connected, so I can actually make fun toys, etc. Currently, the software will only run when connected to the programmer (or at a minimum with the SCK pins connected to each other). I have been searching online for days, and I think I need a crystal or resonator hooked up somehow, but I can't figure out how to hook them up (which pins). I bought 5 16 MHz ceramic resonators, and I have them right here with me, but I can't find the answers online how to hook it up and have the board run stand alone. Any ideas? Thank you in advance.

body:
You might be on the wrong track.

You do need a crystal (or not, it depends on), and an Atmel programmer if you want to program an empty chip.

However, all Arduino boards come with a chip pre-programmed with a bootloader.
Then it is rather easy: you need an FTDI cable to connect the board to a PC. Then run Arduino IDE on the PC. (The FTDI cable is actually an USB-to-serial converter.)

The Arduino IDE lets you edit a C like code, complile it to binary, and send it out via the FTDI cable to the serial port (Rx, Tx) of the board. The microcontroller on the board comes with a bootloader. Bootloader is a small program which runs at power up, and will receive the data from the computer and put your program to the microcontroller. Then your program will run on the microcontroller.

So, you don't need an external programmer.

---

On the other hand, you may consider picking a different Arduino board. Arduino Micro, or Pololu A-star Micro (for half of the price of the Arduino Micro) offers a board with a direct USB connection. All you need is one USB cable.

These boards come with a much better microcontroller (32u4) which has a hardware USB connection (allowing you to make a mouse or a keyboard, and control PC (such as buttonbass.com) from your gadget).


message:
Sampling frequency

I am an undergraduate student at a public university in Maryland. I am currently doing a project with an arduino and I came across a problem that I could not figure out after several days of researching. Regarding my project, I am trying to collect 6 data (acceleration and gyration in x,y,z) from an accelerometer/gyroscope sensor at a desired constant rate (trying to make it 1000 Hz, so about 1000 sets of the 6 data per second) into a SD card. However, I could not make the arduino do this; I am able to collect the data, but not at a constant sampling frequency of 1000 Hz. Could someone help me set the sampling frequency at 1000 Hz please. Here are some of the information of the sensors and arduino I am using:

1. Arduino nano
2. MPU-6050 gy-521 accelerometer/gyroscope - http://playground.arduino.cc/Main/MPU-6050
3. SD card reader - http://www.aliexpress.com/item/SD-Card-Reader-Module-for-Arduino-ARM-Read-and-Write-Free-shipping/526750081.html?spm=2114.12010108.1000023.4.JkncUu&spm=2114.12010108.1000023.4.JkncUu

Also, I have posted my code. Thank you in advance for the help.

My code:

 #include <Wire.h>
 #include <LiquidCrystal.h>
 #include <SPI.h>
 #include <SD.h>
 unsigned long time;
 #include "I2Cdev.h"
 #include "MPU6050.h"
 MPU6050 accelgyro;
 #define OUTPUT_READABLE_ACCELGYRO

 const int sdcard = 7;
 int num;
 int16_t ax,ay,az,gx,gy,gz;
 LiquidCrystal lcd(10, 9, 5, 4, 3, 2); //12 is 10 and 11 is 9

 void setup()
 {
  Serial.begin(115200);
  lcd.begin(16, 2);
  pinMode(8, INPUT_PULLUP);
  Serial.print("Initializing SD card...");
  if (!SD.begin(sdcard))
  {
   Serial.println("initialization failed!");
   return;
  }
  Serial.println("initialization done.");
  accelgyro.initialize();
 }

 void loop()
 {
  lcd.setCursor(0,0);
  lcd.print("Push button");
  lcd.setCursor(0,1);
  lcd.print("to start");
  int sensorVal = digitalRead(8);
  if (sensorVal == 0)
  {
   delay(500);
   num = 1;
   collect();
  }
 }

 void collect()
 {
  File myFile = SD.open("test.txt",FILE_WRITE);
  myFile.println("Begin:");
  myFile.print("x-axis  ");
  myFile.print("y-axis  ");
  myFile.print("z-axis ");
  myFile.print("\n");

  Serial.println("Begin:");
  Serial.print("x-axis: ");
  Serial.print("\t");
  Serial.print("y-axis: ");
  Serial.print("\t");
  Serial.print("z-axis: ");
  Serial.print("\n");

  if(myFile)
  {
   while (num == 1)
   {
    accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
    lcd.setCursor(0,0);
    lcd.print((double) ax/16384*9.81);
    lcd.setCursor(7,0);
    lcd.print((double) ay/16384*9.81);
    lcd.setCursor(0,1);
    lcd.print((double) az/16384*9.81);
    lcd.setCursor(7,1);
    lcd.print(time);

    time = millis();

    Serial.print("Time: ");
    Serial.println(time);
    Serial.print(ax);
    Serial.print("\t");
    Serial.print((double) ax/16384*9.81);
    Serial.print("\t");
    Serial.print(ay);
    Serial.print("\t");
    Serial.print((double) ay/16384*9.81);
    Serial.print("\t");
    Serial.print(az);
    Serial.print("\t");
    Serial.print((double) az/16384*9.81);
    Serial.print("\n");

    myFile.print("Time: ");
    myFile.println(time);
    myFile.print(ax);
    myFile.print("\t");
    myFile.print(ay);
    myFile.print("\t");
    myFile.println(az);

    int sensorVal = digitalRead(8);
    if(sensorVal == 0)
    {
     delay(500);
     num = 0;
     Serial.println("STOPPED");
     myFile.println("STOPPED");
     Serial.print("\n");
     myFile.print("\n");
     myFile.close();
     lcd.clear();
     lcd.setCursor(0,0);
     lcd.print("Stopped");
     delay(2000);
    }
   }
  }
 }

body:
You will not remotely be able to achieve 1000 Hz operation of a loop which performs so many time consuming operations.  Even leaving out the possibility of substantial delay on some attempts to write to the SD card, your serial output alone could never keep up.  A 115200 baud serial implementation can only transmit on the order of 11 thousand characters per second, which means there is only time for 11 or so per your hoped interval, and you produce far more than that.  (And buffering is irrelevant if you are continually producing data faster than you can transmit it)

If you want to achieve a high sampling rate, you are going to have to pare the code down to the bare minimum required functionality and analytically or experimentally determine how much time each portion takes.

If you want regular samples, you are also going to have to study the rate at which the sensor produces them - you may actually want to consider letting the sensor be the timing master, and simply record the samples as they become available.

And you will need to study the SD card writing process and determine its possible worst-case delay.  To overcome that, you may find that you have to collect your samples in an interrupt and use most of your available RAM to buffer them across the worst-case card delays.  If the data you need to store is only a few megabytes, you might consider an SPI flash for its more *deterministic* timing behavior.


message:
Arduino motor rotation

I am a beginner in Arduino. Below is my code to propel the fans of my motor. This happens in a clockwise direction but I wish to change the direction of rotation.

How can I modify it?

<!-- language: c -->

    // Declare the pin for the motor
    int motorPin = 9;

    void setup() {
      // Define pin #9 as output
      pinMode(motorPin, OUTPUT);
    }

    void loop() {
      // Turn motor on
      digitalWrite(motorPin, HIGH);
      // Wait 250 ms
      delay(250);
      // Reanimate motor
      digitalWrite(motorPin, HIGH);
      // Wait 250 ms
      delay(250);
      // Turn motor off.
    }

body:
I guess you have a DC motor in use. Likely a FET drives it on port 9.

This arrangement is enough to start or stop the motor, however to change direction, you need to swap the two wires on the motor.

I guess you may perfer to do this in software - and for that you need to replace the simple FET driver with a H-Bridge. H-Bridge is an arrangement of electric switches which allows you swapping motor polarity, and it usually comes pre-assembled to a chip.

There are a vast amount of h-bridge motor driver chips to choose from. Google for "pololu motor driver", or "adafruit motor driver".

You can find all the further details in the Arduino examples on the web, e.g.:

https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing/overview


message:
exchanging data between two hc05 bluetooth modules

Iam working with gyroscope and Iam trying to send its values from one bluetooth(HC-05) module to another bluetooth module but the data exchange is not happening and I have used 2 arduino boards to do it.

Is there a simple way to do it?

body:
I think there is no simple answer for that. First you have to pair 2 HC-05 modules. To do so, you have to configure one HC-05 as slave, and other HC-05 as master.

**Steps for SLAVE:**

 1. Be sure to select correct Baudrate in your Terminal Emulator (Arduino IDE or Terraterm etc.) for your module. There is no default baudrate... Different manufacturers set the baudrate on their HC-05's differently... 9600 and 38400 are good starting points.
 2. Enter AT mode, by providing high level(3.3V or 5V) signal on KEY pin(PIO11)
 3. Note the values of `AT+PSWD?`, `AT+NAME?` and `AT+ADDR?`(let's say 1111:22:123456) commands. You might set the password to 1234 for easy remembering. Issue `AT+PSWD=0000`...
 4. Be sure to set the module to slave mode by issuing `AT+ROLE=0` command.

**Steps for MASTER:**

 1. Be sure to select correct Baudrate in your Terminal Emulator (Arduino IDE or Terraterm etc.) for your module. There is no default baudrate... Different manufacturers set the baudrate on their HC-05's differently... 9600 and 38400 are good starting points.
 2. Enter AT mode, by providing high level(3.3V or 5V) signal on KEY pin(PIO11)
 3. Reset the module to its original state by issuing `AT+ORGL` command.
 4. Remove the previous parings(if any) by issuing `AT+RMAAD` command.
 5. Set same password as slave by issuing `AT+PASSWD=0000` command.
 6. Change the role to master; `AT+ROLE=1`
 7. Set connecting mode to any address it sees; `AT+CMODE=1`
 8. Initialize the SPP profile lib ; `AT+INIT`
 9. Be sure that you see the slave HC-05 module, `AT+INQ` command will list the modules you see.
 10. Be sure that you see address of the slave module(1111:22:123456).
 11. Last of all enter `AT+LINK=1111,22,123456`(note the commas).

With these steps you should exchange data...


message:
Convert uint8_t array to ascii character for serial transmission

I am trying to send packets of via bluetooth data that include 6 bytes read from a sensor and stored in a uint8_t array. Instead of sending over the data as numerical digital, I would like to send the ASCII character of each of the bytes. I am doing this to reduce the size of my data packets and make it easier to interpret the incoming data.

 uint8_t* temp = readBufferData(FIFO);

 for (int i = 0; i < 6; i++)
 {
  Serial.write(temp[i]);

 }
Read buffer data returns a pointer to a uint8_t array read from a FIFO buffer.
When I use Serial.print, I get the following output, which makes sense.
22163226094255
One question is, when I use Serial.print on a single character, is it transmitted a single byte, or is it actually sending the decimal digital of the number, anywhere from 1-3 bytes?

When I use the Serial.write, however, I get something like the following
DÿÂ?ÁÏ?ÌÆ?Ûµ?Ë½?ÔÀ?Ð¿?ÃÕÓÑËÐTÿÀ?Ï3ÿÉ?¹4ÿÐ?Ê<ÿ½?µfÿ¼?ìNÿÐ?×Â?ÊÚ?×¿?Å
Also, these data display much more slowly on the screen, than normal.

How can I send each uint8_t value by sending over the corresponding ASCII character for serial transmission?

Thanks!

body:
You don't "convert" anything. A character is just a human representation of an 8-bit value.

Instead you just need to change what the compiler thinks the data represents (from a human perspective).  The simplest way of doing that is to either cast the uint8_t values to be char values, or to write each one individually as a raw value.

The latter way:

    myBluetoothSerial.write(myData[0]);
    myBluetoothSerial.write(myData[1]);
    myBluetoothSerial.write(myData[2]);
    myBluetoothSerial.write(myData[3]);
    myBluetoothSerial.write(myData[4]);
    myBluetoothSerial.write(myData[5]);

Or, with a loop:

    for (int i = 0; i < 6; i++) {
        myBluetoothSerial.write(myData[i]);
    }

or using a built-in variant of write that does the loop for you:

    myBluetoothSerial.write(myData, 6);


message:
Burning servos like crazy, what am I doing wrong?

For some reason my servos keep burning out.

My code is simple, if condition, rotate to 0 degrees, else rotate to 180.

However, what that does to the motor is keep it in a constant struggle to stay in rotation 0 or 180, when there is no movement in between. Sure enough, leave it running for 1 hour, the motor burns out.

    if (!strcmp("1",output)){
     myservo.write(0);
    }
    else {
     myservo.write(180);
    }

Is there something like myservo.release or something? I presuming i need to get the servo in to position, then release it so it doesnt try to stay in position.

Please help, i've burned through 4-5 of them so far, it's not fun :(

body:
Some servos are actually not able to do full 0..180 rotation - or to rephrase it better, the standard 0.5ms and 1.5ms pulse will force them to a position which can not be reached. Therefore the motor keeps on rotating in a constant struggle.

* change 0 to something like 20, and 180 to something like 150
* check that the motor has stopped once reaching 20 or 150. I.e. it does not produce any sound, and if you touch the motor body it is not producing any vibration (so no constant stuggle)


body:
Ensure your voltage source matches the motors specs and that your wiring to the arduino or driver shield is correct and try the code I've posted which has worked for me to test servos.

    #include <Servo.h>  // servo library
    // You can control a maximum of twelve servos on the Uno
    // using this library. (Other servo libraries may let you
    // control more). Note that this library disables PWM on
    // pins 9 and 10!

    Servo servo1;  // servo control object

    void setup()
    {
      //  Attach the servo1 object to digital pin 4.
      servo1.attach(4);
    }

    void loop()
    {
      int position;
      // Change position at full speed:

      servo1.write(90);    // Tell servo to go to 90 degrees
      delay(1000);         // Pause to get it time to move
      servo1.write(180);   // Tell servo to go to 180 degrees
      delay(1000);         // Pause to get it time to move
      servo1.write(0);     // Tell servo to go to 0 degrees
      delay(1000);         // Pause to get it time to move

      // Change position at a slower speed:
      // Tell servo to go to 180 degrees, stepping by two degrees

      for(position = 0; position < 180; position += 2)
      {
        servo1.write(position);  // Move to next position
        delay(20);               // Short pause to allow it to move
      }

      // Tell servo to go to 0 degrees, stepping by one degree

      for(position = 180; position >= 0; position -= 1)
      {
        servo1.write(position);  // Move to next position
        delay(20);               // Short pause to allow it to move
      }
    }


body:
I wanted to answer my own question:
I had purchased some really cheap servos from AliExpress. These are not good. They burn out really fast, which has been confirmed by some friends of mine that had purchased the same servos.
The voltage was correct, it was 5V. When using more quality servos that cost $15 I did not see any of these issues.
Do your self a favor. Do not get servos from AliExpress. Get them from DFRobot or some other more reputable website.


message:
Using IR Sensor to sense movement?

I was wondering if I could use a IR sensor with my Arduino to detect if someone is present in front of it.

Like, the emitter should emit continuously and if the receiver drop connection it should do something.

Will this work fine? or the emitter wide angle and a human body in front of it wont drop the signal?

body:
This works quite fine !
The "hardest" part is isolating the IR beam and especially the receiver with anti-reflective paint or paper (ie : a small hole in a cardboard)

You can make this by two (at least) ways :

- [IRled]         [human]          [IRreceiver]
- [IRled and receiver pointing the same way]       [human]        [mirror]

The second way is what you find in auto-flushing toilet rooms. But if the human is wearing quite reflective clothes, this will fool the receiver.
This is great for long-range detection, but if you need a smaller range, go for the 1/.


body:
This will work fine. The easiest way to do this is using **IR Sensor Module**.

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

This will give you a digital output of whether there is someone in front of sensor or not. Use can use it as an Edge Trigger to detect Humans passing by.

You can buy one. They are both cheap and easily available.

Or you can [create your own][2].

  [1]: https://i.stack.imgur.com/roE8n.jpg
  [2]: http://www.instructables.com/id/DIY-Infrared-Sensor-Module/


message:
ESP8266 sending GET Request and getting 408 Timeout error

I am using esp8266 to send a **GET** Request but I am getting 408 Timeout error.

Here is a screenshot of my output.

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

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

body:
I assume you're doing all this from the serial monitor. You can't use escape sequences like `\r` in the serial monitor entry box. Everything you enter is evaluated as a string of separate ASCII characters; `\r` is just a backslash character followed by lowercase r. To send a HTTP request, you make the serial monitor send the `\r\n` for you.

 - First set the serial monitor to `BOTH NL & CR` permanently; it will serve you well for commands and HTTP requests as it appends `\r\n` to everything you send.
 - Count the number of bytes in the your HTTP request, including the carriage return and newline characters. I count 61 characters in your request.
 - Use this count in `AT+CIPSEND`
 - Type the first line of your request, and stop right before the first `\r\n`, and click Send. Because of your setting, the monitor will now send what you typed *with* `\r\n` suffixed to it.
 - Type and send each line of the request, just like you sent the first line, until you've sent the last line.
 - Since there is an additional `\r\n` after the last line, you click Send again, without typing anything. And since the module requires `\r` to indicate the end of the data packet, you click Send one last time.

Hopefully, this should give you the right results.


message:
Send a file from PC to Arduino using HC-06 module

I want to send a file from my Laptop using its own Bluetooth transmitter to Arduino. Arduino has HC-06 module as receiver.Arduino has SD Card fore store the file.
I was able to send bytes using Python application.
How to send a file using a Python application to Arduino?

body:
- Open the file in `rb` mode in your Python code.

- Since the Arduino SoftSerial RX buffer is 64 bytes in size, sending 60 bytes per packet to the Arduino is okay. You basically call `out = file.read(60)` in python to read 60 bytes from the file and then write these bytes to the Arduino with `ser.write(out)`. You can have the python program wait for acknowledgement from the Arduino, perhaps indicating how many bytes it actually received (after a given timeout period) or what byte was last received. This is just very minor error detection.

- The Arduino saves the 60-byte packet to an array and writes everything at once to a file on the SD card, that you've already opened.

- After receiving acknowledgement from the Arduino, the Python program reads the next 60 bytes and forwards to the Arduino like before. Continue till the file is exhausted. You could send some sort of signature byte to inform the Arduino that no more bytes are coming and to close the file. Alternatively, a timeout period can be used.

Note: It'll be more efficient if you wrote to the SD card in chunks, where the chunk size is a factor of the card's sector size. 64 bytes is the highest you can do with the default RX buffer size, but thats living dangerously as you risk buffer overflow if anything goes bump.
This can be avoided though, by reading bytes from the RX buffer and into your own array, as soon as they arrive.

 Chunks of 32 bytes is safer but it will naturally take longer to send the whole file. Test and judge for yourself.


message:
Having a problem to control digital servo with HC-06 bluetooth module

There are two problems to control digital servo(HD-1810MG) and HC-06 bluetooth module connection.

1. When I put a specific number to servo(in the video, I put 45), it shakes too much and shows useless movements before get to the right angle. I have no clue why this happens. Should I add more code to control it correctly?

This is my code.

    #include SoftwareSerial.h
    #include Servo.h

    Servo myServo;
    int TxD = 10;
    int RxD = 11;
    SoftwareSerial bluetooth(TxD, RxD);

    void setup() {
      myServo.attach(9);
      Serial.begin(9600);       // start serial communication at 9600bps
      bluetooth.begin(9600);
    }

    void loop() {
      if (bluetooth.available()>0)
      {
        int servopos = bluetooth.read();
        Serial.println(servopos);
        myServo.write(servopos);
        delay(100);
      }
    }

2. I used Nexus 5X and apk app to pair with HC-06. It pairs well at the first time of connection, but it loose connection after servo moved once. Application said it is connected with bluetooth, but HC-06's LED is blinking(which means disconnected). How can I maintain connection with HC-06?

This is my board.
[![arduino board image][1]][1]

And I made apk app using MIT App Inventor 2.

I'm so new to arduino and I'm not in major of engineering. Please give me an advice!

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

body:
 1. let have a look at following line of code:

        int servopos = bluetooth.read();

    I think that you are thinking that if you type in **1** in your
    Bluetooth application. **bluetooth.read()** will pass that **1** to
    **sevopos**. But, that's what not happens. What actually happens is that it will pass the **ASCII** value of whatever you type in you
    app, to integer. So, if you have typed in **1**, it will pass **49**
    to **servopos**.

    > I put 45

    Now, think about it. when you type in **4** of this **45**,

        bluetooth.available()>0

    becomes **true**.

        int servopos = bluetooth.read();

    **bluetooth.read()** will pass **52** (ASCII of **4**) to **servopos**. Next,

        myServo.write(servopos);

    **myservo** will move your servo to lets say **52** degrees. and then there will be a **delay**.

    Now, when you type in **5** of this **45**, the procedure will be
    repeated and your servo will be moved again by **53** degrees.

    Now, you might be wondering that why **4** and **5** sepratly? Well,
    all these intructution are being executed in **MHz**s. and secondly,
    you, yourself has programmed that **if** loop you read just **once
    character**. Yes, it will read **character by character**.
 2. > but it loose connection after servo moved once

    I think your servo is drawing too much current from Arduino Board
    which results in a drop in net voltage. And hence your HC-05 (kind
    of) tuns off. This is what happens most of the time.


message:
Accelerometer IoT

I am not sure if I am in the right place. I would like to build a device (as small as possible) that has an accelerometer and can talk to my phone via bluetooth. Im not asking anyone to build this for me. I would just like some starting help. Can you tell me the parts that I would need to accomplish this?

body:
you will need:

 1. **Arduino Mini** (can also use **Uno**/**Mega**/**Pro**....)
 2. **Bluetooth Module** (mostly used: **HC-06**/**HC-05**)
 3. **Accelerometer** (mostly **MPU-6050**)
 4. Few **wires**.

If you want to carry this device around, you will need a **battery** to power this circuit.


body:
Your smallest solution would not involve a conventional "Arduino" at all, but rather something like an nRF51822 Bluetooth Low Energy chip/module, which in addition to being a radio is a processor in its own right capable of running custom software built in a variety of ways, including one that extends the Arduino IDE to support it.

Basically, you need the nRF51822 or similar chip, an accelerometer, and whatever solution for powering the two you decide upon.

In terms of conventional bluetooth vs. BLE the choice depends not only on technical merits, but also on which phone you want to connect to.  If you want to connect to an iphone, you are basically locked into BLE as the bluetooth stack there is restricted to approved devices.  On the other hand older/cheaper Android devices may not support BLE, or support it poorly, while their conventional bluetooth does not have the approval restrictions of iOS.


body:
If you want Arduino programming AND you have physical size limitations, you may want to checkout RFDuino.

[http://www.rfduino.com/][1]

They have a variety of breakout boards that make rapid prototyping easier.

I should say however that while I have purchased one of these, I have yet to get around to using one. Others with more experience may want to chime in.

  [1]: http://www.rfduino.com/


message:
Wi-Fi from Arduino to computer serial COM

I am somewhat new to the Arduino world and so far having fun. I am making a gardening watering system for my first project. I am at the final stages of completion and want to add a Wi-Fi module on the Arduino to send to my computer and display via serial COM the soil moisture and other relevant measurements I have going.

Now my question is, is it possible the simple analog information from my Arduino to my computer's serial COM with the Wi-Fi module ?

body:
I would recommend using Bluetooth, as Bluetooth communication is
mostly done by using **COM** Ports.

You can use **HC05**/**HC06** **Bluetooth** Modules with Arduino.
You can easily pair your PC with these Bluetooth Modules.

Now, you write an application in any programming language to get &
send data to your Arduino via Bluetooth COM ports.


body:
you can use ESP8266 with ESP-LINK firmware.

There is nothing to it.Check out [github.com/jeelabs/esp-link][1] for documentation, examples and such.

Connect ESP8266 to Arduino URXD:
connect to TX of microcontroller UTXD:
connect to RX of microcontroller GPIO0:
connect to RESET of microcontroller GPIO2:

optionally connect green LED to 3.3V (indicates wifi status) And that about it. Everything else is done over WiFi

  [1]: http://github.com/jeelabs/esp-link


message:
Can't retrieve data from X-NUCLEO-IKS01A1 using I2C protocol

So I bought this nucleo expansion board, the X-NUCLEO-IKS01A1, and on the package it says it is compatible with Arduino Uno.

My goal here is to read data from any sensor on this board. (When I can read one, I can probably read the others too using the same structure)

Here's my code.

    #include <Wire.h>

    #define ADDRESS 0x1E
    #define REGISTER 0x16

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

    void loop() {
      // put your main code here, to run repeatedly
      Serial.println(I2CreadByte(ADDRESS, REGISTER));
      delay(5000);
    }

    uint8_t I2CreadByte(uint8_t address, uint8_t subAddress)
    {
      uint8_t data; // `data` will store the register data

      Wire.beginTransmission(address);
      Wire.write(subAddress);
      Wire.endTransmission(true);
      Wire.requestFrom(address, (uint8_t) 1);

      data = Wire.read();
      return data;
    }

This should return the temperature in 2's complement. But all it returns is a 1 (I can guarantee you it's not that cold in my room).

I have the board plugged on my Arduino.

Can anyone tell me what I'm doing wrong?

Here's the datasheet for the sensor I'm trying to communicate with.

[Datasheet][1]

The sub addresses are on page 33 and the I2C explantation on 27. It's called the LSM6DS0.

Thanks sooo much in advance.

  [1]: http://www2.st.com/content/ccc/resource/technical/document/datasheet/6e/09/28/0b/01/06/42/24/DM00101533.pdf/files/DM00101533.pdf/jcr:content/translations/en.DM00101533.pdf

body:
You're using a wrong slave address. From the datasheet:

> The Slave ADdress (SAD) associated to the LSM6DS0 is 110101xb. The SDO/SA0 pin can be used to modify the less significant bit of the device address. If the SDO/SA0 pin is connected to a voltage supply, LSb is ‘1’ (address 1101011b), else if the SDO/SA0 pin is connected to ground, the LSb value is ‘0’ (address 1101010b). This solution permits to connect and address two different inertial modules to the same I2C bus.

This means your sketch should contain:

    #define ADDRESS 0x6A  // if SDO pin is pulled down

or:

    #define ADDRESS 0x6B  // if SDO pin is pulled up

It's also a good idea to check if there's actually anything in the Wire buffer (with `Wire.available()`) before you attempt reading.

Finally, I suggest you read both `OUT_TEMP_H` and `OUT_TEMP_L` registers, in order to calculate the temperature correctly. The datasheet says the temperature output is zero at 25 degrees Celsius and that the sensitivity is 16 LSB/C. This means you have to read both registers, combine their results to get a 16-bit signed integer (`OUT_TEMP_H` is the MSB), divide it by 16 to get the temperature offset, and add the result to 25 degrees Celsius to get absolute temperature.


message:
Oddness with #define and #ifdef in a sketch

I'm putting together a simple sketch to read a few sensors and have come across some odd behaviour associated with `#define` and `#ifdef`.

Here are some snippets from my code:

    // Defines
    //#define DEBUG 1
    #define ACCELEROMETER 1
    #define GYROSCOPE 1
    #define GPSSYSTEM 1
    #ifdef GPSSYSTEM
      unsigned int Mth=0;
      unsigned int Day=0;
      char TMZ[2];
    #endif

With this snippet the rest of the sketch compiles, but with this:

    // Defines
    //#define DEBUG 1
    #define ACCELEROMETER 1
    #define GYROSCOPE 1
    //#define GPSSYSTEM 1
    #ifdef GPSSYSTEM
      unsigned int Mth=0;
      unsigned int Day=0;
      char TMZ[2];
    #endif

The compile fails, claiming that the error is in some functions further down.

BTW, `Mth`, `Day` and `TMZ` are not used anywhere yet, not are they defined anywhere else.  What is even more odd is that the error messages are announcing the erroneous line numbers to be about 12 lines removed from where they really exist in the sketch, and have no association with the declarations here.
Now, this gives a clean compile:

    // Defines
    //#define DEBUG 1
    #define ACCELEROMETER 1
    #define GYROSCOPE 1
    #define GPSSYSTEM 1
    //#ifdef GPSSYSTEM
      unsigned int Mth=0;
      unsigned int Day=0;
      char TMZ[2];
    //#endif

as does this:

    // Defines
    //#define DEBUG 1
    #define ACCELEROMETER 1
    #define GYROSCOPE 1
    //#define GPSSYSTEM 1
    //#ifdef GPSSYSTEM
      unsigned int Mth=0;
      unsigned int Day=0;
      char TMZ[2];
    //#endif

I've been chasing this weirdness for a day now and am getting nowhere.

body:
> The **#ifdef** Directive you are using is one of Conditional
> Directive.
This directive checks whether the identifier is currently defined.

In general, it has following syntax:

    #ifdef identifier newline

For Arduino, you can modify your **#ifdef**s to following code:

    #if defined(GPSSYSTEM)
        //Code here
    #endif

> Explaining your code snippets behaviors:

In your first code snippets, **GPSSYSTEM** has been defined by following line of code:

    #define GPSSYSTEM 1

Now, For this code snippets, **#ifdef GPSSYSTEM** is **true**, and following variables are defined.

But, when you comment this **#define GPSSYSTEM 1** line in your 2nd code snippets, **GPSSYSTEM** is no more defined and so **#ifdef GPSSYSTEM** is **false**, and thus following variables are not defined which result in compilation errors in your code.

Following same logic, behavior of your 3rd and 4th code snippets can be explained easily.


message:
Am I multiplexing my LEDs correctly?

I am new to electronics. I have a good amount of programming under my belt however.

I want to know if I am multiplexing correctly or not. My intended output is how I want it, but I am not sure if I implemented it how it's supposed to be, i.e. am I potentially damaging my equipment.

I have 6 RGB LEDs hooked up to my arduino, let's called them L1 - L6.

I have each R, G, and B pin on L1 - L3 connected in parallel, and the same for L4 - L6. Then I have ground on L1 and L4 connected in parallel, and the same for L2 to L5, and L3 to L6.

So this gives me 6 pins to supply voltage to, to which I put a 220 ohm resistor in each one. Then it gives me 3 different spots for ground.

My question is about the ground. How should I control the different 'pins' for ground.

This is what I have right now, and it works, but I don't know if this is dangerous to my equipment for some reason.

I have the 3 ground pins connected to the Arduino in 3 different pins, 7, 4, and 2.

In `Setup()` I configure these 3 pins as outputs, and I later found out in order to keep them all 'off' I need to set them all to high.

So then in order to turn L1 on to red, I need to turn its red pin to high, but turn its ground pin to low, then L1 turns on.

Using this same technique, I am able to get every LED to every desired color. So I mean it works. But why is this? Is this how I should be doing it? I understand LEDs polarity matters, but why would supplying its cathode with voltage make it turn off? That's the part I'm worried about, am I destroying my LEDs by doing this?

Any and all help much appreciated!

Here is how I have it all wired up for clarity.

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

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

body:
LEDs are not powered by a particular voltage level, but by the **voltage difference** between anode and cathode. That's why you need to drive cathode pins (7, 4, and 2) LOW to switch the LEDs ON and HIGH to switch them off. A truth table could help:

    ╔═══════╦═════════╦══════════════════════════╦═══════════╗
    ║ anode ║ cathode ║ voltage anode to cathode ║ led state ║
    ╠═══════╬═════════╬══════════════════════════╬═══════════╣
    ║ LOW   ║ LOW     ║ 0V                       ║ OFF       ║
    ╠═══════╬═════════╬══════════════════════════╬═══════════╣
    ║ LOW   ║ HIGH    ║ - 3.3V                   ║ OFF       ║
    ╠═══════╬═════════╬══════════════════════════╬═══════════╣
    ║ HIGH  ║ LOW     ║ + 3.3V                   ║ ON        ║
    ╠═══════╬═════════╬══════════════════════════╬═══════════╣
    ║ HIGH  ║ HIGH    ║ 0V                       ║ OFF       ║
    ╚═══════╩═════════╩══════════════════════════╩═══════════╝

Your schematic looks safe to me, but be aware that if you decide to illuminate L1, L2 and L3 to the same color simultaneously (e.g drive red line HIGH and pins 7, 4, and 2 LOW), your LEDs will not have uniform brightness. Only one of the cathode pins should be LOW at a time, otherwise you will end up in the situation described [here](https://electronics.stackexchange.com/q/22291/72179).


body:
> So I mean it works. But why is this?

It works because the LED inside the RGB LED, all three of the LEDs inside have the characteristic of a diode, this means it will allow current flow in one direction, but will stop, or restrict it in the opposite direction. *Also are you asking why it works because of your specific wiring?*

>  Is this how I should be doing it?

Yes, how you are doing it is fine. Although I would suggest you use NPN transistors to drive your cathodes of the LEDs.

 - This will at least remove any worry of applying 5v to the cathode.
 - It will also reduce the amount of current your I/O pins have to handle.
 - You should also move the resistors from the cathodes to the anodes as this is more reliable and pretty much the norm.

> I understand LEDs polarity matters, but why would supplying its cathode with voltage make it turn off?

This works because of the theory of the p-n junction, (inside construction of a diode), this means that because of the construction of the diode it requires the voltage on the Cathode to be at a lower potential. So that means when you set the output `HIGH` the 5v on the anode and the 5v on the cathode "stop" current flow because it stops the breakdown within the p-n junction.

> That's the part I'm worried about, am I destroying my LEDs by doing this?

No you are not, the LED acts as a diode and when the potentials are the same, current doesn't really flow and thus doesn't do anything to the LED.


message:
Retrieve value from ThingSpeak using ESP8266 with Arduino setup

I just started learning ESP8266 and in my first project I am successfully able to send data to ThingSpeak.com using ESP8266 with following code:

    uploadData() {
      String apiKey = "ESDS8678890SDDS";
      String myData = "45.5"; // example of data to send
      if (espClient.connect(server,80)) {
        String postStr = apiKey;
        postStr +="&field1=";
        postStr += String(myData);
        postStr += "\r\n\r\n";
        espClient.print("POST /update HTTP/1.1\n");
        espClient.print("Host: api.thingspeak.com\n");
        espClient.print("Connection: close\n");
        espClient.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
        espClient.print("Content-Type: application/x-www-form-urlencoded\n");
        espClient.print("Content-Length: ");
        espClient.print(postStr.length());
        espClient.print("\n\n");
        espClient.print(postStr);
        Serial.print(postStr);
        Serial.print("My Data: ");
        Serial.print(myData);
        Serial.print("\n");
      }
      espClient.stop();
    }

But I have no idea how to retrieve data from ThingSpeak using ESP8266.

    // Using XXXXX here as my channel is private
    GET https://api.thingspeak.com/channels/XXXXXX/fields/1.json?results=2

I think I have to use the above GET string to get the fields data. But I don't know how to create the request string.

Help would be appreciated.

Thanks.

body:
Connect to the server as usual with `espClient.connect()`. The following request should return a JSON object containing your channel description and the first 2 entries in your feed:

    espClient.println("GET /channels/CHANNEL_ID/feeds.json?results=2 HTTP/1.1");
    espClient.println("Host: api.thingspeak.com");
    espClient.println("Connection: close");
    espClient.println();

If it's a private channel, then you must supply your Read API key like this:

    espClient.println("GET /channels/CHANNEL_ID/feeds.json?api_key=<your API key>&results=2 HTTP/1.1");

Notice that I use `println()` and not `print()` in order to implicitly terminate each request line properly. You should end each line not with `\n` but with **`\r\n`**. You only need to type this yourself if you use `print()`.

To read the returned JSON data:

    while (espClient.available() == 0);  // wait till something comes in; you may want to add a timeout here

    unsigned long lastRead = millis();  // keeps track of last time a byte was read
    while (millis() - lastRead < 2000) {  // while 2 secs havent passed since a byte was read
      while (espClient.available()) {
        Serial.print(espClient.read());
        lastRead = millis();   // update last time something was read
      }
    }
    client.stop();  // close socket

To parse the JSON string, you either get a library from GitHub or you parse the string yourself.


message:
How can one use the SPI hardware on the Arduino Nano?

I recently prototyped and programmed a system that used some SPI sensors on an Arduino Uno. I wanted to get the size down a bit, so I was thinking I might buy an Arduino Nano and re-wire my system around that. The problem is that I have seen mention of SPI not working on the Nano. From the [Nano product page](http://www.arduino.cc/en/Main/ArduinoBoardNano):

> These pins support SPI communication, which, although provided by the underlying hardware, is not currently included in the Arduino language.

Yet I have also seen mention of SPI working on this board, or at least people saying that it should. Someone asked a [similar question](https://stackoverflow.com/questions/16055842/arduino-nano-is-spi-supported) on Stack Overflow and was told that it should work with the same level of support as I2C, even if it isn't built in to the core framework. But that answer does not definitively answer the question of whether SPI _does_ work, and it doesn't explain any caveats that one may come across. In [this question](https://arduino.stackexchange.com/questions/13946/nrf24l01-pa-not-working-with-arduino-mega-works-with-nano), the OP's premise is that their SPI device works on the Nano but not on other boards; this seems to be a strong indication that SPI _does_ work.

I figured it would be worth it to buy a Nano 3 and see if it worked. SPI devices did not work on that board, including the same radio module mentioned in the question linked to above. So, I am inclined to believe the Arduino product page when they say it isn't supported. But that still isn't satisfactory, and it is the opposite conclusion from that of the other questions: **The hardware is all there and the software framework is in place, so what does one need to do to make SPI work on the Arduino Nano?** Why is it that some sources say it works while others say it doesn't?

body:
In [this][1] Nano schematic, I see MOSI, MISO & SCLK on pins J1-14, J1-15 & J2-15.

On [this][2] page I see a SPI library.

The Nano is not specifically listed in the latter link.  However the Nano and other Arduino boards are similar.

  [1]: https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf
  [2]: https://www.arduino.cc/en/reference/SPI


body:
Yes, the Nano supports SPI when used with a modern Arduino version, and no, you do not have to do anything special to utilize it on this board.

The information you found that seems to suggest something to the contrary is simply a result of the fact that that the web page for the Nano is sadly out of date date and does not reflect the current state of the Arduino libraries which support SPI on this processor and hence board.

In terms of components, the Nano it is very nearly just a form-factor shrink of the discontinued Duemilanove, and in the current version updated to an an ATmega328p it has capabilities essentially comparable to an Uno, differing primarily the in the USB interface which has nothing to do with SPI.

In terms of what is wrong with the web page, if we examine [archive.org][1]'s records for the page of the comparable Duemilanvoe, on [September 15th, 2010][2] it said:

>SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI communication, which, although provided by the underlying hardware, is not currently included in the Arduino language.

But a few days later on [September 26th, 2010][3] it had been changed to say:

>SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI communication using the SPI library.

Although the page for that once-flagship product was updated to reflect SPI support nearly six years ago, they've not yet made a corresponding correction to the Nano page.  But as the difference is in the software and the same software is used in either case, the addition of SPI support to the Duemilanove was also automatically an addition of that support to the Nano.

  [1]: http://archive.org/web/
  [2]: http://web.archive.org/web/20100915105411/http://www.arduino.cc/en/Main/ArduinoBoardDuemilanove
  [3]: http://web.archive.org/web/20100926114439/http://arduino.cc/en/Main/ArduinoBoardDuemilanove


message:
Create own apache web server on Arduino Uno... just like you can on a raspberry pi?

I was wondering if I could create my own apache web server on my Arduino Uno, just like I did on my raspberry pi - https://www.raspberrypi.org/documentation/remote-access/web-server/apache.md

Anyone have any idea about this? From my research it seems like I cant achieve the same results on an arduino uno.

Thanks

body:
You can only make a very, very, very basic webserver, that won't be able to handle more than a few requests per second.

You also need to add something like an ethernet shield, and probably an SD card reader. Which would make it about the same price as a Pi.

It's possible, but very limited, not practical in most cases, and not that much cheaper.


body:
No you can't. Apache (or any web server of similar functionality) will require:

- tens to hundreds of megabytes of RAM
- about 50 megabytes of storage
- an actual operating system

Perhaps you can get the required storage with the SD shield, but it's practically impossible to get enough RAM or run a suitable OS on arduino.


body:
I do recall someone actually managing to run Linux on an Arduino. It was quite impressive, involving a very large amount of external DDR RAM and bit-banging the interface to it. Basically emulating a virtual computer within the Arduino.  I can't find the original post though - it's been lost in time...

So yes, technically it is possible to run Linux, and thus Apache, on an Arduino.

Is it recommended to even think about trying to do something like this though?

Certainly not.

The Arduino is a microcontroller, not a computer. It is designed for controlling things (hence its name) not for general computing tasks.

It can, though, run its own web server software - that is, you can connect some form of network interface (Ethernet, WiFI, etc) and implement a very very basic web server. It can't really do much, and all interactivity has to be hard coded into it in C++. There doesn't (yet) exist any simple scripting engine or anything like that (PHP, etc) and you are very limited on how much you can implement (lack of memory) as regards anything fancy.

In general a web server running on an Arduino is used as a back-end to a proper web server and interacted with using Ajax calls or other similar methods.  More commonly though a web interface is shunned in favour of much lighter weight protocols or *push* technologies like MQTT.


body:
Yes, you can make a web server.  [Here][1] is the tutorial.

You do not need Apache to create a web server.

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


body:
While you can't make an apache web server with an Arduino Uno, you can if you access the linux module of the Arduino Yun board. I in fact did this and with some testing realized that it can't handle more than a few packet requests per second.
Although a raspberry pi is much cheaper and more capable than a re-programmed Yun if you want a "Mainstream" server
(Namely one Arduino Yun is $75.00 while a Raspberry Pi model 3 B is $35.00 at the time of this writing.)


message:
keypad code is not working and produces wrong numbers

I have the following issues:

1) When i press for example number 7 on the keypad it shows a different number on the serial monitor
2) The servo motor works for any combination of 4 numbers.

Code:
/*http://openhwdesign.comLock system using a Keypad
*/

    #include <Password.h>
    #include <Keypad.h>
    #include <Servo.h>
    #pragma GCC diagnostic ignored "-Wwrite-strings"
    Servo myservo; //declare servo
    Password password = Password( "5523" );

    const byte ROWS = 4; // declare the rows of the keypad
    const byte COLS = 3; // declare the columns of the keypad

    // Define the Keymap

    char keys[ROWS][COLS] = {
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'*','0','#'}
    };

    byte rowPins[ROWS] = {2,3,4,5}; // Connect keypad’s pins to these Arduino pins.
    byte colPins[COLS] = {6,7,8}; // Connect keypad’s pins to these Arduino pins.

    // Create the KeyPad
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

    void setup(){
    Serial.begin(9600);
    myservo.write(0);
    pinMode(11, OUTPUT); //The green led is set as an output.
    pinMode(12, OUTPUT); //The red led is set as an output.
    myservo.attach(13); //The servo is connected to the digital pin 13.
    keypad.addEventListener(keypadEvent); //Add an event listener for the KeyPad

    }

    void loop(){
    keypad.getKey();
    myservo.write(180); //why? what happens if you comment it? ###########################
    //delay(5);
    }

    void keypadEvent(KeypadEvent eKey){
    // When the KeyPad will be pressed, the results will appear on the serial monitor.
    switch (keypad.getState()){
    case PRESSED:
    Serial.print("Enter: ");
    Serial.println(eKey);
    delay(10);

    switch (eKey){
    case '*':
    checkPassword(); // Will check the password.
    delay(1); // Delay used for stability.
    break;

    case '#':
    password.reset(); //Will reset the password
    delay(1); // Delay used for stability.
    break;

    default:
    password.append(eKey); //Append any keypress that is not a ‘#’ nor a ‘*’.
    delay(1);
    }
    }
    }
    void checkPassword(){

    if (password.evaluate()){ //If the combination inserted is equal to the combination saved, the servo’ll rotate.
    Serial.println("Accepted");
    //delay(5000);
    delay(10);
    myservo.write(50); //was 140
    delay(5000);

    digitalWrite(11, HIGH); //Turn the green led on.
    delay(500); //Wait 5 seconds.
    digitalWrite(11, LOW); //Turn the green led off.

    //break; // remove if trial did not work #####################try#####################
    }
    //break; // remove if trial did not work ##########################################
    else{ //If the combination inserted isn’t equal to the combination saved, the servo will not rotate.
    //delay(5000); delays response
    Serial.println("denied");
    delay(10);
    //delay(5000);
    myservo.write(20); // was 50
    digitalWrite(12, HIGH); //Turn the green led on.
    delay(5000); //Wait 5 seconds. was 500 ///
    digitalWrite(12, LOW); //Turn the green led off.

        }
    }

Thank you.

body:
The first thing you need to do is just look at what the problem is.  Create a new sketch and paste this code into it.

    #include <Keypad.h>

    const byte ROWS = 4; // declare the rows of the keypad
    const byte COLS = 3; // declare the columns of the keypad

    // Define the Keymap
    char keys[ROWS][COLS] =
    {
     {'1','2','3'},
     {'4','5','6'},
     {'7','8','9'},
     {'*','0','#'}
    };

    byte rowPins[ROWS] = {2,3,4,5}; // Connect keypad’s pins to these Arduino pins.
    byte colPins[COLS] = {6,7,8}; // Connect keypad’s pins to these Arduino pins.

    // Create the KeyPad
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

    void keypadEvent(KeypadEvent eKey)
    {
     // When the KeyPad will be pressed, the results will appear on the serial monitor.
     switch (keypad.getState())
     {
     case PRESSED:
      Serial.print("Enter: ");
      Serial.println(eKey);
      delay(10);
      break;
     }
    }

    void setup()
    {
     Serial.begin(9600);
     keypad.addEventListener(keypadEvent); //Add an event listener for the KeyPad
    }

    void loop()
    {
     keypad.getKey();
     delay(20);
    }

You should recognise it, its a reformatted version of your code (pretty code is easier to debug), but with only the keypad bits in.

Now load that onto your hardware and write down what number is shown when you press 1 three times.  Do it three times just to make sure its the same number and you haven't got something totally obscure happening. Repeat for the other 11 buttons.

If 7 and 3 always give you 3 and 6 then you have got your row and column wires crossed.
If 7 always gives you 1 and 9 always gives you 3 then the wires for row 4 and 2 are crossed over. etc
If you can't work out the patter post your findings and I'm sure someone will solve the puzzle.

As for problem 2, don't even go there until you know what you are typing. :)

Hope that helps