body:
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.

title: using enums in functions

Answers: 2

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


body:
    #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();
                  }
                 }
                }
               }
              }

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

Answers: 1

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.


body:
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

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

Answers: 2

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.


body:
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

title: The most practical plug socket

Answers: 1

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.


body:
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/

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

Answers: 2

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


body: Could anyone help me for a good free arduino uno simulation software for windows.Hope I get an answer.

title: Arduino uno simulation software for windows

Answers: 1

body:
Autodesk offers a service called 123D Circuits which works in a web browser provided you have an Autodesk account. It allows you to construct (simple) virtual circuits and run code on a virtual Arduino Uno. Regrettably, it doesn't offer very much in the way of diagnostics tools, isn't open source, and won't work offline. The advantage of a service like this is that it requires no installation and is functional for simple setups with a few components. It can be found at [123d.circuits.io][1]

  [1]: http://123d.circuits.io


body:
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();

           }
    }

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

Answers: 1

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


body:
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.

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

Answers: 1

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


body: 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.

title: How to use Arduino Pro Mini without Programmer

Answers: 1

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


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

title: Sampling frequency

Answers: 1

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.


body:
I am using an Arduino Mega board with a SIM900 GSM.

My goal is to be able to text the GSM with a value of two digits (ex: 79) and then store that value as a variable in the code. I know how to set up the Mega and the GSM in terms of wiring and initialization of ports, but how would I write a short function to test the incoming values and save them to a variable?

I thought about testing each bit individually, storing each one as a separate variable, and then adding them for the total. For example, if the GSM received "#79" as a text I stored the value 7 as an integer variable named `One` and the value 9 as an integer variable named `Two`. Then I did

    Total = (One*10)+Two.

I am posting my code below that used this method, although it has not proved to be useful. If anyone has any suggestions I would greatly appreciate it.

<!-- language: c -->

    #include <SoftwareSerial.h>   //GSM Library

    int Max_temp;
    float threshold;

    SoftwareSerial SIM900(18, 19);
    String destinationNumber = "+17186578989";
    String outMessage1 = "Please enter the maximum desired room temp";
    char inchar; // Will hold the incoming character from the GSM shield when user texts it
    int M_one;
    int M_zero;
    void GSM_SEND_MAX();
    void GSM_RECEIVE_MAX();

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

    //GSM setup:
      Serial1.begin(19200);  // wake up the GSM shield
      delay(20000); // give time to log on to network.
      Serial1.print("AT+CMGF=1\r"); // set SMS mode to text
      delay(100);
      Serial1.print("AT+CNMI=2,2,0,0,0\r"); // blurt out contents of new SMS upon receipt to the GSM shield's serial out
      delay(100);
    }// end void set up()

    void loop()
    {
      GSM_SEND_MAX();
      GSM_RECEIVE_MAX();
    }// end void loop ()

    /////Functions
    void GSM_SEND_MAX()
    {
      Serial.println("sending text");
      Serial1.begin(19200);
      delay(20000); // give time to log on to network.
      Serial1.print("AT+CMGF=1\r");
      delay(1000);
      Serial1.println("AT + CMGS = \"" + destinationNumber +"\"");
      delay(1000);
      Serial1.print(outMessage1);
      delay(1000);
      Serial1.write((char)26); //ctrl+z
      delay(1000);
      Serial.println("send text");
    }//end GSM_SEND_MAX funtion

    void GSM_RECEIVE_MAX()
    {
      //If a character comes in from the cellular module...
     while (Serial1.peek() != '#' )
       {
        inchar=Serial1.read();
        Serial.print("bad char ");
        Serial.println(inchar);
        delay(500);
       }// end while #1

     inchar=Serial1.peek();
     Serial.println("out of loop 1");
     Serial.println(inchar);

     while (Serial1.available() != 0) //While #2 reads incoming char
     {
        Serial.println("in loop 2");
        inchar=Serial1.read();

    if (inchar=='#')
      {
      delay(10);
      Serial.print("got #");
      M_one=Serial1.read();

      if (M_one >= 0 )
      {
      delay(10);
      Serial.println();
      Serial.print("got M_one");
      Serial.print(M_one);
      M_zero=Serial1.read();

          if (M_zero >= 0)
          {
              Serial.println();
              Serial.print("got M_zero");
              Serial.print(M_zero);

           }//end m_zero

      }//end m_one
      Max_temp = (M_one *10) + M_zero;

      Serial.println();
      Serial.print("Max_temp=");
      Serial.print(Max_temp);

      } //end if (inchar==#)

     }// end while #2 loop
    }//end GSM_RECEIVE_MAX function

title: Arduino GSM receiving text and then storing value as a variable in code

Answers: 0


body:
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.
    }

title: Arduino motor rotation

Answers: 1

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


body:
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?

title: exchanging data between two hc05 bluetooth modules

Answers: 1

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


body:
I want to be able to display what I am seeing on the serial monitor onto the LCD keypad shield I have connected to my Arduino UNO. Can someone possibly write the the code ontop of this for me?
I'm very new to coding so I apologies if it's hard for anyone to understand what i'm asking for.

    int ledPin = 13; // LED is attached to digital pin 13
    int x = 0; // variable to be updated by the interrupt

    //variables to keep track of the timing of recent interrupts
    unsigned long button_time = 0;
    unsigned long last_button_time = 0;

    void setup() {
      //enable interrupt 0 which uses pin 2
      //jump to the increment function on falling edge
      attachInterrupt(0, increment, FALLING);
      Serial.begin(9600);  //turn on serial communication
    }

    void loop() {
      digitalWrite(ledPin, LOW);
      delay(500); //pretend to be doing something useful
      Serial.println(x, DEC); //print x to serial monitor
    }

    // Interrupt service routine for interrupt 0
    void increment() {
      button_time = millis();
      //check to see if increment() was called in the last 250 milliseconds
      if (button_time - last_button_time > 250)
      {
        x++;
        digitalWrite(ledPin, HIGH);
        last_button_time = button_time;
      }
    }

title: How do I display serial monitor on LCD keypad shield?

Answers: 0


body:
I have a few questions related to GPRS/GSM SIM900 Shield not working with Arduino.

To keep it short I have a list of concrete questions:

 1. Is the Arduino GSM library compatible with the [Geeetech GPRS/GSM SIM900 Shield][1]?
 2. On the board the green LED blinks every 3 seconds which I have read
    means that it is connected. However, when I try to use any of the
    GSM examples, in regard to internet, I either get error messages or
    simply no progress in the program. For instance, in the `testGPRS`
    sketch it sits stuck at the port where it says "Connecting GSM
    network...". And in the `bandManagement` example sketch it can't find
    the current band,as well as the modem not responding, well basically nothing works, except that the
    shield itself indicates it is connected to a network.

The SIM card I'm using is data exclusively and can't be used for voice calls or SMS. It has no pin code and works as my secondary SIM card (it shares the same subscription as my primary card).

Edit:
I have now tested the SMS capabillities of the board with another simcard, that works with no problems, seems only the internet won't work.

  [1]: http://eud.dx.com/product/geeetech-gprs-gsm-sim900-shield-board-for-arduino-green-844377853#.VxXuxTCF6hd

Answers: 0


body:
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!

title: Convert uint8_t array to ascii character for serial transmission

Answers: 2

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

body: Try changing Baud Rate. Most of the time garbage like this happens because of difference in baud rates of transmitter serial device and receiver serial device.


body:
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 :(

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

Answers: 3

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.


body:
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?

title: Using IR Sensor to sense movement?

Answers: 2

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/


body:
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

title: ESP8266 sending GET Request and getting 408 Timeout error

Answers: 1

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.


body:
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?

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

Answers: 1

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.


body:
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

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

Answers: 2

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.

body:
It is not a problem in serial connection. I have experienced this problem when I was trying to make a biped robot using 12 servos. It is the programming bug where Arduino does not use its timers properly. You can say that it is arduino limitation.
There are two main solutions :
1). Use Raspberry Pi instead of arduino.
2). Secondly you can make a small servo controlling shield of TLC5940 IC + servo controlling library...  Here is he Link: http://bildr.org/2012/03/servos-tlc5940-arduino/


body: 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?

title: Accelerometer IoT

Answers: 3

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/


body:
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 ?

title: Wi-Fi from Arduino to computer serial COM

Answers: 2

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


body:
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

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

Answers: 1

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.


body: I use an atmega328 with fdti cable wired at rx/tx and i want to connect a zigbee s2 at diferrent pins. I have tried to use  SoftwareSerial library but i would like to use the xbee library too. Is there a way to use both libraries? If there is no way doing this, is it a problem to connect both fdti cable and zigbee at the same rx/tx? In the future, in opposition to fdti cable i will use a micro usb avr.

title: Atmega328 xbee and softaware serial libraries

Answers: 0


body:
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.

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

Answers: 1

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.


body:
I'm using SimpleSDaudio (http://www.hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio) to play wav files. The connections are as follows:

MISO pin 12

SCK pin 13

SS pin 4

MOSI pin 11

Speaker pin 9

    /*
     Simple SD Audio bare minimum example, plays file EXAMPLE.AFM from root folder of SD card.

     This example shows how to use the SimpleSDAudio library for audio playback.
     You need:
     - An Arduino with ATmega368 or better
     - An SD-Card connected to Arduinos SPI port (many shields will do)
       -> copy EXAMPLE.AFM on freshly formated SD card into root folder
     - A passive loudspeaker and resistor or better: active speakers (then stereo output will be possible)

     Audio signal output is at the following pin:
     - Arduino with ATmega328       (many non-mega Arduinos): Pin 9
     - Arduino with ATmega1280/2560 (many mega Arduinos)    : Pin 44

     Using passive speaker:
        Audio-Pin --- -[100 Ohm resistor]- ---- Speaker ---- GND

     Using amplifier / active speaker / line-in etc.:
        Audio-Pin --||--------------[10k resistor]----+----[1k resistor]---- GND
                  100nF capacitor                   to amp

     See SimpleSDAudio.h or our website for more information:
     http://www.hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio

     created  20 Jan 2013 by Lutz Lisseck
     */
    #include <SimpleSDAudio.h>

    void setup()
    {
     // Open serial communications and wait for port to open:
      Serial.begin(9600);
       while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      // Using F("...") to avoid wasting RAM
      Serial.print(F("\nInitializing SD card..."));

      // If your SD card CS-Pin is not at Pin 4, enable and adapt the following line:
      // SdPlay.setSDCSPin(10);

      if (!SdPlay.init(SSDA_MODE_FULLRATE | SSDA_MODE_MONO | SSDA_MODE_AUTOWORKER)) {
        Serial.println(F("initialization failed. Things to check:"));
        Serial.println(F("* is a card is inserted?"));
        Serial.println(F("* Is your wiring correct?"));
        Serial.println(F("* maybe you need to change the chipSelect pin to match your shield or module?"));
        Serial.print(F("Error code: "));
        Serial.println(SdPlay.getLastError());
        while(1);
      } else {
       Serial.println(F("Wiring is correct and a card is present."));
      }

      Serial.print(F("Looking for on.wav... "));
      if(!SdPlay.setFile("hi.wav")) {
        Serial.println(F(" not found on card! Error code: "));
        Serial.println(SdPlay.getLastError());
        while(1);
      } else {
       Serial.println(F("found."));
      }

      Serial.print(F("Playing... "));
      SdPlay.play();
      while(!SdPlay.isStopped()) {
        ; // no worker needed anymore :-)
      }
      Serial.println(F("done."));
      SdPlay.deInit();
    }

    void loop(void) {

    }

The problem is when playing the wav files. It plays with a lot of static. I've tried adding a 1k resistor between the speaker and gnd but that just lowered the overall volume. I resampled the wav files in itunes to 32khz, 8bit, mono. If I lower to 16khz then the audio volume becomes very low and the song just plays extremely fast. Here is a google drive link to one of the sounds:
https://drive.google.com/file/d/0B3yAl4G-mcC4dlppN3dtczJvT1k/view?usp=sharing

I really need help. I'm not sure what to do!

title: SimpleSDaudio giving a lot of static from speaker

Answers: 0


body:
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

title: Am I multiplexing my LEDs correctly?

Answers: 2

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.


body:
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.

title: Retrieve value from ThingSpeak using ESP8266 with Arduino setup

Answers: 1

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.


body:
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?

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

Answers: 2

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


body:
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

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

Answers: 5

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


body:
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.

title: keypad code is not working and produces wrong numbers

Answers: 1

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


body:
I'm running into a bizarre problem. I've got a custom board using an Atmega328P, running off the internal oscillator. From Atmel studio, I've successfully uploaded the standard optiboot bootloader (`optiboot_atmega328.hex`) and burned the appropriate fuses (`hfuse = 0xDE`, `lfuse = 0xE2`, `extended_fuse = 0x05`). As per an arduino forum post, I added the following entry to `boards.txt`:
<!-- language-all: lang-cpp -->
    atmega328_384_8.name=ATmega328 Optiboot @ 38,400baud w/ 8MHz Int. RC Osc.

    atmega328_384_8.upload.protocol=arduino
    atmega328_384_8.upload.maximum_size=30720
    atmega328_384_8.upload.speed=57600
    atmega328_384_8.upload.tool=avrdude

    atmega328_384_8.bootloader.low_fuses=0xE2
    atmega328_384_8.bootloader.high_fuses=0xDE
    atmega328_384_8.bootloader.extended_fuses=0x05
    atmega328_384_8.bootloader.path=optiboot
    atmega328_384_8.bootloader.file=optiboot_atmega328.hex
    atmega328_384_8.bootloader.unlock_bits=0x3F
    atmega328_384_8.bootloader.lock_bits=0x0F

    atmega328_384_8.build.mcu=atmega328p
    atmega328_384_8.build.f_cpu=8000000L
    atmega328_384_8.build.core=arduino
    atmega328_384_8.build.variant=standard

Note here, I've modified the upload speed to 57600 baud to "fool" it into the right upload speed given an 8MHz oscillator.

I can now successfully upload sketches from the Arduino IDE (1.6.3) on the lab windows machine, but when I try from my Mac (various IDE versions have been tried), I get the following protocol error:

`avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0`

Here's the full trace:

    /Applications/Arduino-1.6.8.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino-1.6.8.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbserial-AH02F0KI -b57600 -D -Uflash:w:/var/folders/db/hw2v9r6j7qj_w9gh3qkhh_580000gr/T/build53eb1895270295360d41549eaf6e0624.tmp/sketch_apr19a.ino.hex:i

    avrdude: Version 6.0.1, compiled on Apr 14 2015 at 16:30:25
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/Applications/Arduino-1.6.8.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/Users/npisenti/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/cu.usbserial-AH02F0KI
             Using Programmer              : arduino
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega328P
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PC2
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : Arduino
             Description     : Arduino

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x00

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x00
             Hardware Version: -1538883332
             Firmware Version: 6291456.-1538883332

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x00

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0
             Vtarget         : 322122165.6 V
             Varef           : 275608114.4 V
             Oscillator      : 0.001 Hz
             SCK period      : 368336.6 us

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x00
    avrdude: stk500_initialize(): (a) protocol error, expect=0x14, resp=0xe0
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

    avrdude: stk500_disable(): protocol error, expect=0x14, resp=0xe0

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

On Windows, the "successful" full trace from avrdude is:

    Sketch uses 1,974 bytes (6%) of program storage space. Maximum is 30,720 bytes.
    Global variables use 192 bytes of dynamic memory.
    C:\arduino-1.6.3\hardware\tools\avr/bin/avrdude -CC:\arduino-1.6.3\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM10 -b57600 -D -Uflash:w:C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex:i

    avrdude: Version 6.0.1, compiled on Mar 30 2015 at 14:56:06
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "C:\arduino-1.6.3\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM10
             Using Programmer              : arduino
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega328P
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PC2
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : Arduino
             Description     : Arduino
             Hardware Version: 3
             Firmware Version: 4.4
             Vtarget         : 0.3 V
             Varef           : 0.3 V
             Oscillator      : 28.800 kHz
             SCK period      : 3.3 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.01s

    avrdude: Device signature = 0x1e950f
    avrdude: reading input file "C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex"
    avrdude: writing flash (1974 bytes):

    Writing | ################################################## | 100% 0.77s

    avrdude: 1974 bytes of flash written
    avrdude: verifying flash memory against C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex:
    avrdude: load data flash data from input file C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex:
    avrdude: input file C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex contains 1974 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 0.86s

    avrdude: verifying ...
    avrdude: 1974 bytes of flash verified

    avrdude done.  Thank you.

In both cases, I'm using the FTDI friend from Adafruit; at first I figured it must be a driver issue, but I've installed the latest FTDI drivers and doesn't seem to help. Besides, I can successfully get text dumped from the ucontroller onto the serial port from a sketch previously uploaded on the windows machine.

Any help would be greatly appreciated!

title: avrdude/stk500 protocol error

Answers: 1

body:
I managed to figure this out after hours of searching. I wanted to flash the new Nano bootloader to my Nano, but it would fail with the same error as you.

For some reason, after Arduino 1.8.5, AVR boards with "Arduino as ISP" were changed so that they no longer work for me.

The solution for me was to revert `programmers.txt` to what it was on 1.8.5, i.e. change the `arduinoasisp` lines to:

```
arduinoasisp.protocol=stk500v1
arduinoasisp.speed=19200
arduinoasisp.program.protocol=stk500v1
```

This uses the stk500v1 protocol instead of the arduino protocol (you can see the `-carduino` option in your command line) and makes everything work for me.