# Question
Title: Problems connecting Adafruit Feather M0 to network
I'm trying to connect my Adafruit Feather M0 board to an existing WiFi network. Whenever I use the "ConnectWithWPA" example sketch, I receive "Attempting to connect to WPA SSID: "MyNetwork" " in the serial window, where "MyNetwork" is the SSID for the WiFi I wish to connect to. The network never gets connected. The WiFi I want to connect is WPA, password protected. When I connect the feather to an open network (one without a password) it does in fact get connected. The problem only occurs when I try to connect to a network with SSID and password.

Does anyone know what the problem may be?

```
#include <SPI.h>
#include <WiFi101.h>

#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the WiFi radio's status

void setup() {
  //Configure pins for Adafruit ATWINC1500 Feather
  WiFi.setPins(8,7,4,2);
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  // attempt to connect to WiFi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid, pass);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid); //, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.print("You're connected to the network");

 }

void loop() {
  // check the network connection once every 10 seconds:
  delay(10000);
  }

```

# Answer
I was able to get the Feather board communicating with my WiFi network after I updated my Arduino IDE and firmware. Hope this helps anyone else facing this problem.
> 0 votes

---
Tags: arduino-ide, wifi, adafruit
---


title: Connecting to network with wifi shield

text:
# Question
Title: Connecting to network with wifi shield
I just bought a WiFi shield and I cannot connect to my wireless network (WPA2).

* I used the sketch from the Arduino site for connecting to WPA network and put my SSID and password on but it doesn't connect (I know the credentials are correct as I used my phone to connect with these WiFi credentials).
* When I read the serial monitor it just keeps trying to connect. The WiFi-shield board error light is red
* I checked my network settings and my block level is at is lowest (NAT only).

**Why can't I connect?**

# Answer
> 1 votes
In the loop:

```
// attempt to connect to Wifi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

```

Can you add `Serial.print(status);` before the delay so you can see if any of these arise:

* WL\_IDLE\_STATUS = 0
* WL\_NO\_SSID\_AVAIL
* WL\_CONNECT\_FAILED
* WL\_CONNECTION\_LOST
* WL\_DISCONNECTED

They are defined in `wl_definitions.h`

# Answer
> 0 votes
I was facing the same issue using the Feather M0 board from Adafruit. After updating the Arduino IDE as well as the IDE's libraries and firmware, I was able to connect to WiFi.

---
Tags: arduino-uno, shields, wifi
---


# Question
Title: How to pass 'Serial' as an input argument in Arduino function?
I have one integer value which I should pass through Serial1, Serial2, Serial3, and Serial4 after performing some algebraic operation on this integer. For this algebraic operation, I made a function and input arguments is an integer and Serial number. Simple code is given below: *(I deleted every extra part of my code to make easy to understand)*

```
String stringG; int d1; int d;

#include<SoftwareSerial.h>
//Software Serial #1: Rx = digital pin 10, Tx = digital pin 11
SoftwareSerial Serial4(10, 11);

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

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0)
  {
     String  XX = Serial.readString();
    int d1 = XX.toInt();
    Serial.println(d1);
    int yy;
    yy = compareFunction (d1, Serial4);
    Serial.println("Now the final values are:");
    Serial.println(d1);
    Serial.println(yy);
  }

}
int compareFunction (int d, String Serialx)
{

  int ZZ = Serialx.readString(); // I will receive some values from motor using serial4
  //to avoid long code I deleted unnecessary parts
  // I will use ZZ and d values and output will be yy
  return yy;
}

```

As you see in `compareFunction` I receive value using Serial (it may be 1,2,3 or 4) So I have to pass `Serial as an input argument` in this function. If I can't pass `Serial` then I have to write 4 functions each for Serial1, 2, 3 and 4 which I want to avoid. Is it possible? How can I do it? when I tried with above code it shows error

> exit status 1 could not convert 'Serial4' from 'SoftwareSerial' to 'String'

# Answer
> 9 votes
The `Serial` object is the end of a chain of classes, each with a different set of functionality.

```
Print -> Stream -> HardwareSerial => [Serial]

```

Since you are *reading* from it the best class to use is `Stream` since that is the one that is the one that contains the reading functionality.

You should pass it *by reference* or as a *pointer* since you don't want to copy the object.

```
int compareFunction (int d, Stream &Serialx)
{

  int ZZ = Serialx.readString(); // I will receive some values from motor using serial4
  //to avoid long code I deleted unnecessary parts
  // I will use ZZ and d values and output will be yy
  return yy;
}

```

By using `Stream` you can use any object type that also uses `Stream` in its class inheritance chain - even things like a WiFi socket connection.

This behaviour is called polymorphism and is one of the more powerful features of classes in C++ (and other OO languages).

---
Tags: serial, arduino-mega, softwareserial
---


# Question
Title: Arduino force feedback vibration gamepad
I'm projecting a gamepad with Arduino Micro. I'm using the Arduino Joystick Library.

I'm building this gamepad for racing games so I need to catch signal like `hit_the_wall`, `hit_another_car`.

I wonder how the PC game output the signal of the vibration/force feedback and send throw USB to the gamepad.

I already know that the gamepad drivers and the game have to support this function, but I'm completely lost about how I can catch the input to trigger the vibration engine with Arduino.

I was thinking something about (pseudocode):

```
input = Serial.read();

if(input == hit_something_signal){

   digitalWrite(engine, HIGH);

}

```

Now my question is which is this magic `hit_something_signal`?

**UPDATE**

I'm reading the PID document and I notice on page number 24 the register addresses to implement the force feedback.

```
;Start Force Feedback command definitions
USAGE_PAGE (Physical Interface) 05 0F
;Effect Report Definition
 USAGE (Set Effect Report) 09 21
 COLLECTION (Logical) A1 02
 USAGE (Effect Block Index) 09 22
 LOGICAL_MAXIMUM (127) 25 7F
 REPORT_SIZE (7) 75 07
 REPORT_COUNT (1) 95 01
 OUTPUT (Data,Var,Abs)
 .......

```

In the Joystick.cpp file I notice the HID implementation:

```
// USAGE_PAGE (Generic Desktop)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x05;
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;

// USAGE (Joystick - 0x04; Gamepad - 0x05; Multi-axis Controller - 0x08)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;
tempHidReportDescriptor[hidReportDescriptorSize++] = joystickType;

// COLLECTION (Application)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0xa1;
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;

// REPORT_ID (Default: 3)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x85;
tempHidReportDescriptor[hidReportDescriptorSize++] = _hidReportId;
.......
......

```

Do you think should be possible to implement the force feedback part? I do not need to catch all the forces, but run the vibrator engine every time the game sends and input of every kind of force.

The problem is that I'm not an expert about low-level programming and drivers. Do you have any idea?

# Answer
> 1 votes
That library has no support for vibration.

The HID report descriptor has to include the correct OUTPUT items for the PC to send the vibration instructions to the Arduino - and of course the library has to be able to handle that incoming data - none of which is implemented.

So you can't unless you massively expand that library. And that takes intimate knowledge of USB and HID protocols.

---
Tags: usb, library, arduino-micro, joystick
---


# Question
Title: Is the Arduino Due compatible with a Dual VNH5019 Motor Driver Shield?
I'm planning on buying an Arduino Due and there is a shield I would like to attach to it. I have seen a lot of things saying that some shields are **not** compatible with Arduino Due... I was wondering if the Arduino Due is compatible with the Dual VNH5019 Motor Driver Shield.

This is where I'm buying it from if you need any extra information on the items:

Answers greatly appreciated! If you need any specifications let me know.

# Answer
ok so I went ahead and bought the arduino due and officially tested it out and the Arduino Due **is** compatible with the Dual VNH5019 Motor Driver Shield!

hope this helps!
> 0 votes

---
Tags: arduino-due, arduino-motor-shield
---


# Question
Title: Reconnect to I2C with a different address (ATTiny85)
My project requires to reconnect to an I2C bus as a slave. I can't reset my ATTiny physically because I2C + my project + a pin to trigger the reset isn't possible due to the limited amount of pins available on the ATTiny85. I searched the reference and different forums. If there was an answer to my question, I couldn't find one.

Thanks in advance.

(I want to try to make a plug-and-play kind of experience with a product. I want the chip to join with a defined address (100 or so), get a new address from the master and then reconnect to the I2C bus).

# Answer
> 1 votes
You only need to reinit the I2C slave.

The TinyWireS lib I found lets you just call `TinyWireS.begin()` with the new slave address. Though it doesn't have a way to stop the I2C connection. But the lib is hackable enough that with the ATTiny's specsheet you can add an end() to it.

However I believe that it may be better if the newly connected ATTiny acts as a master first and requests a free address from a known fixed slave acting as a dhcp server.

---
Tags: i2c, attiny, eeprom, reset, wire-library
---


# Question
Title: How to organize my Arduino projects' structure for easy source control?
It's been a long time I've been looking for a good answer to this question.

Typically, any Arduino project but the simplest one will include:

* The main source code file `MyProject.ino`
* Libraries specific to the project (`MyProjectLibrary1.h`, `MyProjectLibrary1.cpp`...)
* Third-party libraries (generally free open source, added manually to Arduino libraries directory)
* Schematics, PCB diagrams
* Documentation
* ...

All this makes it hard to keep the whole code and doc of one project under Source Code Management (e.g. on Subversion, Git or GitHub).

Managing source control of your project means managing the version of all files used by the project including 3rd-party libraries.

Now for a single project, I need to define a directory structure that:

* Includes all project files as described above
* I can entirely commit to a Source Code Management tool (including 3rd-party dependencies)
* I can checkout anywhere on my hard drive and build the project from there (does it have to be a single location as imposed by Arduino IDE)
* I can zip into a self-contained archive that I can send to a friend for him to build as easily as possible (no extra manual download)

What I find particularly tricky with Arduino projects is the management of external libraries dependencies. Java projects developers have maven repositories for that and that helps a lot in managing all external deps. But we don't have an equivalent system for Arduino libraries.

I would be interested to know how other Arduino project makers deal with these aspects in their own projects.

Also note that I am open to changing my development process, including my IDE (currently I use Eclipse with the Arduino plugin most of the time, and then I ensure my projects can also work directly with the Arduino IDE).

# Answer
Here is the way I finally decided to follow for my projects.

# Arduino-CMake

The first important decision I made was the choice of a build tool that could work for my environment (Windows) but was not limited to it (I want my projects easily reusable by other people).

I have tested various open source Arduino make tools:

* **Guyzmo Makefile** (suggested by @zmo answer): this is just a standard Makefile handcrafted for Arduino builds; this is a Unix Makefile but there is a good port of **Unix make for Windows**; still, unfortunately this Makefile works only for Unix, of course it could be adapted for Windows, but I wanted a tool that works "out of the box".
* **Arduino-Makefile** (suggested by @adnues answer): this a more advanced project, based on Unix Makefile, that aims to be easily reusable by all Arduino projects; it is documented as working on Mac, Linux and Windows, but Windows support proved wrong in my first experiments (many dependencies on Unix shell).
* **Graduino** (not suggested by any answer): this build tool is based on well-known gradle build tool from the groovy world; the tool seems quite well done but requires some (little) groovy/gradle knowlegde, and has only little documentation; I decided not to go with it due to the burden of installing groovy and gradle just for it (I'd like to avoid too many pre-requisites to people who want to build my projects on their environments).
* **Arduino-CMake** (not suggested by any answer): this seems the best of all, it has a long history, has many supporters and maintainers, is very well documented, comes with simple examples and also has a few good tutorial blog posts on the Web, e.g. here and there. It is based on CMake, a "Cross-Platform Make".

I have also found **ArduinoDevel**, another Arduino build tool -which I have not experimented- that can generate **Unix Makefiles** or ant `build.xml` files; that one seemed interesting but a bit limited in terms of functionality.

Finally I decided to go with **Arduino-CMake**:

* it was easy to setup: just install **CMake** on your machine and copy Arduino-CMake in some directory that is easily accessible (through relative paths) from your projects directories.
* the examples worked out of the box for me (just followed the comments in `CMakeLists.txt` configuration file to adapt properties that needed to for my environment, e.g. Arduino type, serial port)
* you can organize your projects any way you want
* it can generate configuration files for various build tools out there (I have only tested **Unix Makefiles** though), including Eclipse projects.
* in the generated make, several targets get created to support:

+ libraries build
    + programs build
    + program upload to boards
    + serial monitor launch
    + and a few others I have not tested yet

# Project Structure

Since Arduono-CMake does not impose any directory structure for your project, you can choose the one that fits you best.

Here is what I've done personnaly (that still requires further refinement, but I'm happy with it now):

I have decided to put all my projects under a common `arduino-stuff` directory (which I commit to github as a whole, I know I could use ***git submodules*** for a better organisation on github, but had no time to check that yet).

`arduino-stuff` has the following content:

* `build`: that's a directory where cmake and make will generate all their stuff (makefiles, cache, object files...); this one does ot get committed to github
* `cmake`: that one is just a copy (unmodified) of Arduino-CMake cmake directory. This one gets on github so that it's easier for someone who wants to build my projects
* `CMakeLists.txt`: that's the "global" CMake configuration that declares all defaults for my environment (board, serial port) and the list of build target subdirectories
* `TaskManager`: this is my first project based on Arduino-CMake, this one is a library with examples; this idrectory also contains a `CMakeLists.txt` that states the targets for the project

# Points to improve

The current solution is not perfect though. Among improvements I see (that's rather for Arduino-CMake project to include these improvements if they see fit):

* Feature to copy a library directory from the current project to the Arduino libraries directory
* Feature to upload a library to github
* Feature to download a library from github
> 20 votes

# Answer
My way of organizing an arduino project is quite simple, all my project are git repositories so that there is at least the following:

I have a preference using my favorite editor and a Makefile which I have crafted to work against most use cases (and I even improved on that one that I'm going to share soon).

For the libraries, I prefer to keep them as their own repositories and use git submodule to include them to the project. As many libraries written by the community are shared as git repositories, that's a good generic solution. Then, within the Makefile, I just have to add the libraries path I want to include in the LOCALLIBS variable.

Though, for some projects, it makes sense to encapsulate the libraries into a hardware abstraction layer library crafted for the project, then I prefer to use a path such as:

* `project`
    + `project.ino`
    + `Makefile`
    + `project_hal_lib`
        - `library1`
        - `library2`
        - `library3`
        -

Though, with arduino 1.5.x a new way to specify libraries is offered, that will offer a way to create and build arduino projects the same way we already do with pipy and virtualenv in python, i.e. you define the set of libraries you need and they get downloaded.
> 36 votes

# Answer
The simplest way to do this is to copy the header and code files of the library into your source directory and include them.

```
myproject/
    myproject.ino
    somelib.h
    somelib.cpp

```

In your code, you can do `include "somelib.h"`

The down side to this is that the libraries must be in the same folder, not sub folders, so it makes your directory look messy.

---

Regarding the directory structure of my entire project, including schematics and documentation, mine usually looks like this:

```
myproject/
  schematics/ - eagle files or whatever you may have
  docs/       - include relevant datasheets here
  test/       - any test cases or other code to test parts of the system.
  myproject/  - since Arduino code must be in a directory of the same name
    myproject.ino
    ...

```
> 25 votes

# Answer
Git submodules are extremely powerful when it comes to organizing multiple nested repositories. Handling multiple libraries from different sources, and even handling parts of your own project which may be stored at different sources becomes easy with git submodules.

## Directory Structure

A way to organize your projects would be:

* **projectA** \- Parent Directory

+ **projectA** \- Source code directory containing Arduino code

    1. projectA.ino
        2. header.h
        3. implementation.cpp
    + **docs** \- Your main documentation directory
    + **schematics** \- these may be maintained separately on a separate Git repo or part of the same repo
    + **libs** \- This will contain your third party libraries.

    1. libA - These may be maintained as third party repositories
        2. libC - ...
    + **license**
    + **README**
    + **Makefile** \- Necessary to handle dependencies across directories

## Workflow

You would follow your normal cycle of make changes, add and commit as far as the main repository is concerned. Things get interesting with the sub-repositories.

You have the option of adding a repository into the parent directory of your main repository. This means that any part of you directory structure, i.e. docs, schematics, etc. can be maintained as a separate repository and continuously updated from.

You can do this using the `git submodule add <repo.git>` command. To keep it up to date, you can use `git submodule update <path>`.

When it comes to maintaining multiple third party libraries within your repository such that each can be version controlled in itself or each can be kept up to date if need be, git submodule again saves your day!

To add a third party repo to **libs**, use the command `git submodule add <lib1.git> libs/lib1`. Then, to maintain the library at a fixed point in the release cycle, checkout the library and make a commit. To keep the library up to date, use the command `git submodule update <path>`.

Now, you can maintain multiple repositories within a main repository as well as multiple third party libraries in their independent stages of release.

# Versus Single Directory Approach

While the single directory approach is the simplest, it is not possible to version control parts of a directory without a lot of pain. Hence, the simple approach fails to accomodate different repositories with varying states in the project.

This approach allows maintaining multiple repositories but brings in the need for a Makefile to handle the compilation and linking process.

Depending on the complexity of your project, the optimal approach can be selected.
> 21 votes

# Answer
```
MyProject
|_MyProject
  |_MyProject.ino
  |_data
  |  |_documentation
  |  |_PCB
  |  |_schematics
  |_src
     |_MyProjectLibrary1
     |_ThirdPartyLibrary

```

## MyProject folder (repository root)

The reason I suggest the seemingly redundant `MyProject` root folder is that you mentioned using GitHub. When you download (rather than clone) the contents of a GitHub repository the branch or tag name is appended to the repository name (e.g. `MyProject-master`). The Arduino IDE requires that the sketch folder name match the sketch file name. If you open an .ino file that is in a folder that does not match the sketch name the Arduino IDE prompts you create an appropriately named sketch folder and move the sketch to that folder. In addition to this not being a very good initial experience for the user, the greater problem is that the Arduino IDE may not copy all the other associated files to the newly created folder, which could cause the program to no longer compile. By putting the sketch in a subfolder you avoid GitHub altering the name of the sketch folder.

If the GitHub file name thing is not an issue for you then the redundant root folder is not necessary.

## data folder

I recommend using the `data` subfolder for your non-code files because the Arduino IDE has a special treatment of subfolders of that name. They are copied to the new location when you do a **File \> Save As...**. Subfolders of any other name are not.

## src folder

The `src` subfolder has the special property of allowing recursive compilation. This means that you can leave the libraries in that folder and include them from your sketch like this:

```
#include "src/MyProjectLibrary1/MyProjectLibrary1.h"
#include "src/ThirdPartyLibrary/ThirdPartyLibrary.h"

```

The Arduino 1.5 Library format folder structure is also supported, you only need to adjust your `#include` statements accordingly.

Note that only Arduino IDE 1.6.10 (arduino-builder 1.3.19) and newer support recursive sketch compilation.

Unfortunately some libraries use the incorrect `#include` syntax for local file includes (e.g. `#include <ThirdPartyLibrary.h>` instead of `#include "ThirdPartyLibrary.h"`). This still works when the library is installed to one of the Arduino `libraries` folders but does not work when the library is bundled with the sketch. So some libraries may require minor edits to use this way.

I greatly prefer this to the alternative of dumping all the library files in the root of the sketch folder because that is messy and every library file will be shown in the Arduino IDE as tabs when you open the sketch (Of course any source files you do want to be editable from the Arduino IDE should be placed in the sketch root folder).

Being able to use bundled libraries in place is also in line with another of your goals:

> send to a friend for him to build as easily as possible

Removing the requirement to manually install libraries makes the project much easier to use.

This will also avoid any chances of conflict with other versions of library files of the same name that may be previously installed.
> 9 votes

# Answer
You could use the makefile https://github.com/sudar/Arduino-Makefile for compiling Arduino codes. You don't necessarily need the IDE.
> 4 votes

# Answer
Probably really late to the game but it's a popular enough question to answer using slightly different methods than those posted already.

If you need to maintain compatibility with Arduino IDE directly you could use something like the one I outlined here:

https://gitlab.com/mikealger/ExampleArduinoProjectStructure/tree/master/ExampleSketchBook

I based most of this off the notes of Arduino -- Project structure and build process, and some tips I have picked up over the years.

I really don't know why this is so hard to find via Arduino pages directly, it seems silly coming from a semi professional background that the build process is so obtuse.

best of luck out there

----edited link to the project structure notes i used as they have been erased they are now here
> 2 votes

---
Tags: project, version-control
---


# Question
Title: Arduino Uno to Arduino Uno Word.doc file transfer
I have written a 2 sets of code for the transmitter and receiver section. I am trying to send a word document file from 1 arduino uno to the next arduino uno through serial TX and RX. The file is initially loaded into a micro sd card module at the transmitter section. I would like to transfer that file to the receiver section's sd card module. I am able to receive an empty word document at the receiver section. There is no information in the document. I would like some help with this. I will attach the transmitter and receiver code below.

Transmitter code:

```
#include <SD.h>
#include <SPI.h>

File fileIn;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
   while (!Serial){
    ; //  wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  if(!SD.begin(4)){
    Serial.println(F("Initialization failed!"));
    return;
  }
  Serial.println("Initialization done.");
  if(!SD.exists("student.txt")){
    fileIn = SD.open("student.txt", FILE_WRITE);
    fileIn.println(F("abc.txt"));
  }
  fileIn = SD.open("student.txt", FILE_READ);

  while(fileIn.available()){
    Serial.write(fileIn);
  }
  delay(1000);
  fileIn.close();
}

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

}

```

Receiver code:

```
#include <SD.h>
#include <SPI.h>

File fileOut;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial){
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  if(!SD.begin(4)){
    Serial.println(F("Initialization failed!"));
    return;
  }
  Serial.println("Initialization done.");
  if(SD.exists("student2.txt")){
    SD.remove("student2.txt");
  }
  fileOut = SD.open("student2.txt", FILE_WRITE);

  while(fileOut.available()){
    Serial.write(fileOut);
  }
  delay(1000);
  fileOut.close();
  Serial.println("It worked!");
}

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

}

```

# Answer
> 1 votes
```
  while(fileOut.available()){
    Serial.write(fileOut);
  }

```

This doesn't quite do what you think it does.

Instead you should send the file length first and then do:

```
for(unsigned long size = 0; i< fileLength; i++){
    Serial.write(fileOut.read());
}

```

You should also investigate some kind of rate limiting to avoid overwhelming the reciever and having to drop some bytes.

---
Tags: arduino-uno, serial, spi, sd-card
---


# Question
Title: Can an accelerometer be used to detect heart sound?
I've recently come across accelerometer and how it can detect electrical mechanical response. I was wondering can it be used to detect heart sound? Lets say you attach the device close to your chest (where heat lies) and detect sounds and send it over bluetooth? LPMS-B2 OEM

# Answer
> 2 votes
An accelerometer detects motion (acceleration) of the physical device.

If you can convert the sound of the heart into physical vibration then the accelerometer can detect that vibration.

Converting the tiny amount of sound the heart produces into a large enough vibration for the accelerometer to detect would entail (realistically) using a microhone, amplifier, and speaker, with the accelerometer attached to the speaker cone.

So while theoretically yes, you can do it, practically why would you when you can just use the microphone and amplifier that you'd be using anyway. It's pointless.

So in reality: no, you can't.

---
Tags: arduino-uno, bluetooth, sound
---


title: Auto Fish Feeder

text:
# Question
Title: Auto Fish Feeder
Good day, I am new to Arduino, but have made some nice projects work. I have a n issue with a Auto fish feeder. I have used a servo that I modified to run 360. I am having a issue when the Nano board starts. It runs the time I have set between feeds, and then it stops. If I set it to feed every 10 sec, it starts up and run for 10sec and then the LED flashes and it stops. From there it works perfect. But if I lose power and it comes back, its going to feed for 10sec and that will kill the fish.

Here is my sketch I am using now, please can someone look at it and tell me where I am going wrong. I just want it not to run when it starts up, or just for the to that it feeds, not continues like now for 10sec, or 12 hours !!!

```
//--Setting Vars

   //Fish Feeder Vars.
int pinOutMotor = 3;
int pinOutLed = 5;
int pinInButton = 2;
int MotorRunDuration = 1000;
float AutoWaitDurationHours = 0.;
//--Program Vars
unsigned long currentMsSinceStart = 0;
unsigned long msValueAtLastRun = 0;
float HoursSinceLastRun = 0;
int buttonValue = 0;

void setup() {
  Serial.begin(9600);             //Turns on serial monitor.
  pinMode(pinOutMotor, OUTPUT);   //Is controlled by a 3906 npn transistor to switch the motor off and on.  When program started I need to add a line to turn off motor when program was started.
  pinMode(pinInButton, INPUT);    //Manual feed.
  pinMode(pinOutLed, OUTPUT);     //Shows motor is on when lite.
}

void loop() {
  //HoursSinceLastRun = AutoWaitDurationHours - 0.05; //this will make it run 3 minutes after turned on.

//Fish Feeder
  //get miliseconds since program start and calc.
  currentMsSinceStart = millis();
  HoursSinceLastRun = (currentMsSinceStart - msValueAtLastRun) / 10000; //10000 millis= 10 seconds.  To change the time to vary feeding times set for 12hrs type in 43200000 or 6hrs tyoe in 21600000.
  //check for button press
  buttonValue = digitalRead(pinInButton);
  if(buttonValue == HIGH){  //had to change state because of button from LOW to HIGH.
    //run motor for button press.
    RunMotor();
    Serial.println("Feed Fish Manually");  //serial print funtion completed by button

  } else if(HoursSinceLastRun > AutoWaitDurationHours){
    RunMotor();
    msValueAtLastRun = currentMsSinceStart;
    Serial.println("Feed Fish Auto");      //serial print funtion completed by auto wait duration hours
  }
  //slow the loop down so it isn't running at full CPU Utilization for nothing.
  delay(50); //delay 1/20th of a second.
}

void RunMotor(){
    analogWrite(pinOutMotor, 0);   // turn on motor
    analogWrite(pinOutLed, 80);        // turn on green led to show motor is on.
    delay(MotorRunDuration);   // wait for motor run duration to expire
    analogWrite(pinOutMotor, 255);    // turn off motor
    analogWrite(pinOutLed, 0);        // turn off green led to show motor is off.
}

```

# Answer
If I correctly understand, your problem is really with the restart, that will always feed the fish.

You can use the EEPROM to save the last time you feed the fish. You also need a RTC to get the real time.

Every time you feed the fish, you also write in the EEPROM the current hour:minutes (from the RTC). When you restart, you read your last feed from the EEPROM and uses it to initialize `msValueAtLastRun`. You have to change your time recording to hh:mm instead of millis from start.

You code looks OK, only missing debouncing the button.

You can also use a NodeMCU, and get your time via NTP.
> 1 votes

---
Tags: arduino-nano, motor, servo, arduino-pro-mini, sketch
---


# Question
Title: Solid-state relay boards: Can they be used to switch audio signals?
So I tried to use one of those widely available solid-state relay boards to switch some 12V power, and I found out the hard way that they are not designed to switch DC current. They use some sort of variac that only works when AC voltage is applied. Do I have that right??

So I got this other project where I need to multiplex some audio signals in a mixer board, and I was already planning on using those solid-state relays before I learned all this. If I send audio through these relays, is it going to work as planned? Will I suffer any noticeable delay, signal degradation or attenuation?

# Answer
> 1 votes
A solid-state relay seems to be the totally wrong tool for the job. The image you posted shows it is intended to switch 240V AC. So it is designed to switch something like a 240V light on and off.

Relays in general are things designed to connect one thing to another (eg. power to a light). They just aren't designed to switch audio signals.

> I need to multiplex some audio signals in a mixer board, and I was already planning on using those solid-state relays before I learned all this

The expression "when the only tool you have is a hammer, everything looks like a nail" springs to mind.

There are chips designed to multiplex analog signals (as I describe on this page). That would be closer to what you need.

However that chip (the 74HC4067) is a "choose one input from many" sort of design. It isn't going to let you fade one audio signal in or out (neither would the relay for that matter).

# Answer
> 0 votes
No. SSRs are completely wrong for switching audio.

Consider using the CD4066 chip. But be aware that will mean you'll need to ask a whole bunch of new questions I'm sure.

I hope this answer helps you.

---
Tags: relay
---


# Question
Title: Boil water inside a small container with an arduino
I am currently working with a sciene/electronic project where i need "steam". In order to create steam i need to boil water and i plan to boil it inside a very small container \[around 5cmx5cmx5cm\]. What i want to do is to control this with an arduino but I am very unsure on what step i currently need to make. Are there any "heating-up" modules out there? Or would I need to order a mini-mini kettle and connect that to my arduino?

I am very grateful for every advice i can get because as u can tell i am a bit confused as of right now!

# Answer
> 0 votes
Try to find a boiler pot on electricity (I doubt you can heat water to boiling temperature with like 5V (unless you use many amperes).

Use a relais to switch it on with an Arduino.

Use a temperature sensor (0-150 degrees or so) to decide when to switch it off.

Warning: Get first some electrical knowledge before you start with \>200 volts projects since it can be deadly. And boiling water can be devestating for skin and your Arduino.

---
Tags: arduino-uno
---


title: Is an Arduino capable of running 24/7?

text:
# Question
Title: Is an Arduino capable of running 24/7?
I'm making a simple Arduino web server and I want to keep it turned on all the time. So it must endure to stay working continuously.

I'm using an Arduino Uno with a Ethernet Shield. It's powered with a simple outlet power supply 5V @ 1A.

My Questions:

* Will I have any problems leaving the Arduino turned on all the time?
* Is there some other Arduino board better recommended for this?
* Are there any precautions that I need to heed regarding this?

# Answer
> 61 votes
You shouldn't have any issues keeping it on all the time, however, some thing to consider is any counters you may have, like the use of `millis()`.

From the Arduino docs on millis:

> This number will overflow (go back to zero), after approximately 50 days.

So for projects that are on for long periods of time, you may not see an issue immediately but something like this could pop up and cause errors down the road.

# Answer
> 34 votes
A couple of things to keep in mind (outside of @Sachleen's mention of `millis()`):

* Like any electronics, heat can be disruptive. The micro-controller itself isn't likely going to be a huge issue from the perspective of heat, but other components like the power supply might cause issues.
* If your code uses `EEPROM.write()`, be aware that the EEPROM in your Uno's ATmega328P is only rated for 100,000 writes.

# Answer
> 12 votes
Running the Arduino 24/7 Shouldn't be a problem.

But be sure that you have a case that allows for ventilation and you keep it in a well ventilated area. Just like computers, if you do not keep them in an environment that can keep them cool, they will not stay cool.

Server load also should be a thing to consider, the more load there is on the server the more processing it has to do, and the more heat it will generate.

# Answer
> 12 votes
Keep in mind that the flash and EEPROM have limited lifetimes (about 10,000 and 100,000 write cycles respectively) so if you're doing a lot of writing to those, they may become corrupted. In a test I did, an external EEPROM took about 3 days to start becoming corrupted.

# Answer
> 9 votes
We've been running our Arduino-based RFID access system at Bloominglabs Hackerspace in Bloomington IN since late 2011 and aside from a couple power outages and software updates it runs around the clock, no problem. More recently we added a networked thermostat, same deal - it's running round the clock.

# Answer
> 6 votes
Arduinos can run without issues for a really long time, though depending on local conditions and the intensity of computation you may have to attach heat sinks.

In addition, keep it well ventilated.

It depends on the program being used, too, if your server is serving a page every now and then, it shouldn't be an issue, but if you expect constant traffic then the Arduino may heat up quickly.

You'll also want to ensure stability of power supply, when running benchtop experiments with an Arduino this isn't a big issue, bit it can become an issue if transforming power from the mains for a permanent fixture.

# Answer
> 4 votes
I've never ran an Arduino for that long, but there shouldn't be a problem. One thing to watch out for is the input voltage.

While an Arduino is capable of handling 7-20v as input anything over 12v can overheat after longer periods of time and cause board damage. As a quick recommendation to avoid any overheating of the Arduino I would keep the voltage as close to 7v as possible.

# Answer
> 4 votes
I'd like to mention an issue that doesn't come up very often but can cause long term issues. Memory Leaks and Heap Fragmentation. Almost nobody mallocs in embedded stuff, but if you do, do it right.

# Answer
> 4 votes
I built a simple power monitor with my first Arduino. It is powered via USB from a web-server that in turn is powered via a quite substantial battery backup (which does not have notification abilities).

It is also connected to a mobile phone charger plugged into a non-UPS power socket.

So if the power dies the Arduino sends a message to a little program running on the server. The server program in turn sends me an email notification.

It was installed in late September 2013, on the 23rd March 2014 - I got my first email!

So I have not seen a problem (it does not use millis() ) but it does sample the power every 5 seconds.

# Answer
> 2 votes
Is an Arduino capable of running 24/7?

This is a reliability question. In reliability, there are a lots of things to consider.

1. The software. There are more robust softwares. There are less robust softwares. For instance, for critical applications, dynamic memory allocation is discouraged, as it might lead to memory fragmentation. Unfortunately, Arduino heavily relies on dynamic memory allocation. This problem is exacerbated as most of the Arduino board have a very limited RAM.
2. The libraries. Many Arduino libraries do have bugs (even those built-in in the Arduino package, as simple as WString!). In normal operation, such bugs may not appear at all. However, you can't hope that "everything will be fine" and that "the user" (or subsystem) will act as predicted. Libraries could also have their limits (i.e. not properly bugs). For instance, many users already cited the millis() function, which resets after 50 days. This, if not handled correctly, might lead to severe bugs.
3. The reliability of the hardware (not even talking about cheap Arduino clones...). Here a new class of subquestions opens. I will cite only a very limited subset.
    * Are the Arduino Boards designed for reliability? (e.g. what's the
    reliability of the used capacitors? and other components?)
    * Robustness against EMI ? I wouldn't rely on that: most of Arduino boards have just two layers, and lack of a proper ground/power plane.
    * EEPROM (this is both software and hardware). Is your software using the EEPROM? Is implementing some algorithm to prevent cycling (repeated write/erase on the same cells)?
    * Flash memory retention time. Retention time decreases with temperature, and also with the number of programming cycles.
    * Ionizing radiation. Yes, even if the probability is VERY low, at least at sea level, the probability of radiation-induced single-event upset is not zero, and it adequate countermeasures should be taken (especially taken into consideration that the RAM has no hardware error detection) in critical applications.
    * The quality of the power supply.
    * The operating environment. A 25-°C controlled environment, or in a black box over the roof (70°C under the sun in summer)? The higher the temperature, the faster all the degradation mechanisms.
    * ...

Still, you should not be surprised if your arduino will work flawlessy for many years. But this does not ensure that every arduino will.

Some countermeasures will increase the reliability:

* Use the watchdog: it's better to reset a non responsive system, than having a stuck/misbehaving one.
* Avoid using any library that uses memory allocation.
* Implement (if you use the EEPROM) an algorithm to preserve it!
* Good power supply.
* Avoid harsh evironments (high temperature, high humidity, large and continuous thermal cycles, etc).

# Answer
> 0 votes
It certainly can run 24/7. I either use 5V to the 5V pin, or a 7808 to the Vin pin to offload the vreg. Ideally it would be 6.5V, but I don’t have such supplies. You may want a decoupler cap on 5V though, to soak any minor spikes when powering up your supply.

Any hardware attached which runs at 5V, I feed with a 7805. You can use LM317s or LM350s in lieu of 78XXs, but you’ll need a few resistors for those, perhaps trimpots.

---
Tags: arduino-uno, web-server, ethernet
---


# Question
Title: How to monitor 12 V LiPo charging from Arduino
What's the safest way to determine a lithium-ion polymer battery's discharge and charging state using an Arduino?

I see a ton of 12 V LiPo batteries like **this** being sold on eBay and elsewhere.

They have a built-in charger, and I'd like to use one to power an Arduino, but the Arduino needs to know "when" the battery needs to be charged, and "when" the battery is fully charged. Unfortunately, the battery doesn't expose any pins or LEDs or other outputs that I could tap into.

I've found a few LiPo charging circuits specifically designed for the Arduino, but they all can only handle 3.7 V cells.

I'd like to avoid having to disassemble the battery or modify it to allow me to monitor its state. Is there an easier way, like connecting a battery lead to an analog pin and measuring voltage, or using a coulomb counter?

# Answer
> 1 votes
If you want to buy something off the shelf that will provide power for an Arduino, try a power bank - they have USB out, and are also charged via USB. I found that I had to put a 100 Ohm resistor to stop mine going to sleep, but it's +5V native.

A 100 ohm resistor (0.25 watt at least!) draws 50mA, so a 5200mAH powerbank like http://www.dx.com/p/universal-5200mah-external-li-ion-battery-charger-power-bank-w-led-indicator-usb-cable-pink-362725#.VQneCnWjlIc would leak it empty in 104 hours. If you use at least 50mA at all times, then this isn't needed - I think an Arduino draws 35mA already, so you should get away with a 300 Ohm resistor, drawing 16mA. Some experimentation might be needed.

# Answer
> 0 votes
Use a 10V zener diode. Check it’s voltage drop, and use that in your analogRead logic.

Get the full voltage with a DMM, and also the low cut-off voltage.

---
Tags: arduino-uno, battery
---


title: Getting wrong value from Serial.read()

text:
# Question
Title: Getting wrong value from Serial.read()
I have an RGB LED, connected to my UNO R3 and would like to turn on the written color in the serial by following a table (1 for red, 2 for blue, 3 for green...) and I also want to make that if this LED is already turnt ON, I want it to turn OFF. The problem I have is that when I use Serial.read() it always returns a -1 value. Why is that? I leave you the code here and in case you see something wrong please tell me. Thank you very much.

```
#define RED 7
#define GREEN 4
#define BLUE 2
  String ledcolour[] = {"RED", "BLUE", "GREEN", "YELLOW", "PURPLE", "WHITE"}; //array to match the number typed to the LED colour
  char ledstatus[] = {0, 0, 0, 0, 0, 0}; //0 if the LED is OFF and 1 if it's ON
  String ledvaluefix[] = {"HIGH", "LOW"}; //if the ledstatus[] value is 0 it will write HIGH and if it's already ON it will write LOW
  char ledstatusfix[] = {1,0}; //to update in ledstatus[] if the LED is ON or OFF
  int led = Serial.read();
void setup() {
  pinMode(RED,OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE,OUTPUT);
  Serial.begin(9600);
  Serial.println("Type the LED's colour you want to turn on following this table:");
  Serial.println("RED=1");
  Serial.println("BLUE=2");
  Serial.println("GREEN=3");
  Serial.println("YELLOW=4");
  Serial.println("PURPLE=5");
  Serial.println("WHITE=6");
}

void loop() {
  if (Serial.available()){
    Serial.println(led);
    loop();
   if (led <= 6 && led >=1){ //Checks if value is within 0-6
    if (led <=3){ //Classifies in primary or mixed colours (understand primary as just having to turn ON one single LED)
      if (ledstatus[led-1] == 0){//checks if the LED was OFF
        digitalWrite(led-1,HIGH);//turns the typed LED to HIGH
        char ledstatus[led-1] = {1};//updates the array to set the LED is now ON
        confirmer();//sends a serial confirmation message
      }else{//if it was already ON
        digitalWrite(led-1,LOW);//turns the typed LED to LOW
        char ledstatus[led-1] = {0};//updates the array to set the LED is now OFF
      }
    }else{//if it's not a primary colour
      Serial.println("YOU CHOSE " + ledcolour[led-1] + ", WHICH IS A MIXED COLOUR");
    }
    }else{//if the value is not valid (not between 0 and 6)
      Serial.println("SORRY, THE INTRODUCED VALUE IS NOT VALID");
      Serial.println("PLEASE, TRY AGAIN");
    }
  }
}
 int confirmer(){
    Serial.println("YOU CHOSE THE " + ledcolour[led-1] + " LED");//sends the serial message confirming it's been turned ON
   }

```

# Answer
> 1 votes
This

```
 int led = Serial.read();

```

is execute before `setup()` and `loop()`, just one time. All initializations outside any function are execute before the start of the program. You have not execute `Serial.begin` yet.

You probably want to read inside the `loop` ...

**Edit:**

Second problem: you are calling `loop` recursively

```
void loop()
{
    if(Serial.available()) {
        Serial.println(led);
        loop();

```

When a byte in available in the serial port, you will call `loop`. As you never read the serial port, `Serial.available` will still return \> 0, and you will enter in a never ending recursion.

---
Tags: arduino-uno
---


# Question
Title: How to use a rotary encoder on NodeMCU with Arduino code?
I have a standard 5 ping rotary encoder (3 pins for encoder, 2 pins for button). I'm trying to get a working code that manages to read the rotary encoder.

I began with the code I found here: http://bildr.org/2012/08/rotary-encoder-arduino/

My problem is that the interrup method never being called. I read that all the GPIO pins on NodeMCU support interrupts (except D16). Here's my code:

```
volatile int lastEncoded = 0;
volatile long encoderValue = 0;

long lastencoderValue = 0;

int lastMSB = 0;
int lastLSB = 0;

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

  pinMode(D0, INPUT);
  pinMode(D3, INPUT);

  digitalWrite(D0, HIGH); //turn pullup resistor on
  digitalWrite(D3, HIGH); //turn pullup resistor on

  attachInterrupt(D0, handleInterrupt, CHANGE);
  attachInterrupt(D3, handleInterrupt, CHANGE);
}

void handleInterrupt() {
  int MSB = digitalRead(D0); //MSB = most significant bit
  int LSB = digitalRead(D3); //LSB = least significant bit

  int encoded = (MSB << 1) |LSB; //converting the 2 pin value to single number
  int sum  = (lastEncoded << 2) | encoded; //adding it to the previous encoded value

  if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;

  lastEncoded = encoded; //store this value for next time
}

void loop() {
    Serial.print("Encoder: ");
    Serial.println(encoderValue);
    delay(1000);
}

```

# Answer
> 1 votes
Different RotaryEncoders work in different ways. Mine connects the two outputs sequentially to the `Gnd` or `+` inputs, depending on the rotation direction. The resultant phase changes need to be detected and decoded by the processor.

I took your code and ran it on a LoLin NodeMCU using my 5-pin RotaryEncoder.

I connected (NodeMCU to RotaryEncoder):

* `D0` to `Clk`;
* `D3` to `DT`;
* `GND` to `GND`; and
* `3V` to `+`.

I ran the code, and it worked: the printed value went up when I rotated it in one direction, and down when it rotated in the other. The "bounce" was terrible though - getting just a single increment or decrement for one "detent" was difficult; I typically got 2-4.

Because of my encoder, I was able to remove the two `digitalWrite(..., HIGH);` lines and it continued to work. Perhaps that's what your problem is? Did you connect the `+` input? You mention the two switch pins: perhaps there's only one switch pin, that connects to the `Gnd` pin?

---

## EDIT: The code!

So I went away and wrote a RotaryEncoder polling library, rather than the interrupt code that the original question was based on. The idea is that you can poll a rotary encoder (relatively) infrequently, and stil "catch" the transitions as it rotates. Of course this won't work if you poll it *too* slowly - your mileage may vary!

But here are three files:

* The header and library source for the RotaryEncoder module; and
* An example usage of the module.

RotaryEncoder.h:

```
//
// RotaryEncoder.h
//
// This library manages a Keyes KY-040 Rotary Encoder by sampling the
// appropriate pins when requested. It is NOT interrupt driven, so you'll need
// to sample often.
//
// The encoder has five pins in a 0.1" row, so you can directly plug it into
// an Arduino's data-pin sockets. The sequence of pins matches the order of
// parameters in the constructor - use ascending (or descending) numbers for
// ease.
//
// If you pass in NoPin for gnd, vcc, or sw (the switch), then that parameter
// is ignored. You'll need to organise those pins yourself! Of course, NoPin is
// not valid for dt or clk.
//

#ifndef RotaryEncoder_h
#define RotaryEncoder_h

class RotaryEncoder {

public: // Typedefs and enums

   typedef byte Pin;

   typedef signed char OptPin;

   enum Pins : OptPin {
      NoPin = -1
   }; // Pins

public: // Methods

   // Define which pins to use for the various functions.
   // If Optional Pins are "NoPin", then they won't be initialised
   RotaryEncoder(OptPin gnd, OptPin vcc, OptPin sw, Pin dt, Pin clk);

   // Start RotaryEncoder with optional maxBias (call Rebias() periodically)
   void Begin(byte maxBias=1);

   // Returns true if switch is currently pressed
   bool Switch() const;

   // Returns 0 for no change, +ve for clockwise, -ve for counter-clockwise
   int Get();

   // Call this periodically to reduce the bias
   void Rebias(int delta=1);

private: // Variables

   const OptPin gndPin;

   const OptPin vccPin;

   const OptPin swPin;

   const Pin dtPin;

   const Pin clkPin;

   byte maxBias;

   byte bias;

   bool clk;

   bool dt;

}; // RotaryEncoder

#endif // RotaryEncoder_h

```

RotaryEncoder.cpp:

```
//
// RotaryEncoder.cpp
//

#include <Arduino.h>
#include "RotaryEncoder.h"

RotaryEncoder::RotaryEncoder(OptPin gnd, OptPin vcc, OptPin sw, Pin dt, Pin clk) :
               gndPin(gnd),
               vccPin(vcc),
               swPin(sw),
               dtPin(dt),
               clkPin(clk),
               maxBias(1),
               bias(1),
               clk(false),
               dt(false) {
} // RotaryEncoder::RotaryEncoder(gnd, vcc, sw, dt, clk)

void RotaryEncoder::Begin(byte maxBias) {
   this->maxBias = maxBias;
   if (gndPin!=NoPin) {
      pinMode(gndPin, OUTPUT); // Let's power the device,
      digitalWrite(gndPin, LOW);  // Power -ve with 0
   } // if
   if (vccPin!=NoPin) {
      pinMode(vccPin, OUTPUT); // ,with both - and +
      digitalWrite(vccPin, HIGH); // Power +ve with 1
   } // if
   if (swPin!=NoPin) {
      pinMode(swPin, INPUT_PULLUP); // They pushed it!
   } // if
   pinMode(dtPin,  INPUT); // One half
   pinMode(clkPin, INPUT); // The other half
} // RotaryEncoder::Begin(maxBias)

bool RotaryEncoder::Switch() const {
   return swPin!=NoPin ?
          digitalRead(swPin)==LOW :
          false;
} // RotaryEncoder::Switch()

int RotaryEncoder::Get() {
   bool clkNew = digitalRead(clkPin);
   if (clk!=clkNew) {
      clk = clkNew; // Clock's changed; sample data
      bool dtNew = digitalRead(dtPin);
      if (dt!=dtNew) {
         dt = dtNew; // Data's changed; remember it!
         if (clk) {  // Only pay attention to Clk Low-High
            int temp = bias;
            bias = maxBias;
            if (dt) {
               return -temp;
            } // if
            else {
               return +temp;
            } // else
         } // if
      } // if
   } // if
   return 0;
} // RotaryEncoder::Get()

void RotaryEncoder::Rebias(int delta) {
   if (bias<=1) {
       return;
   } // if
   bias -= bias>delta ? delta : bias-1;
} // RotaryEncoder::Rebias()

```

RotaryBlinker.ino:

```
//
// RotaryBlinker
//
// This example changes how fast the built-in LED blinks by using the
// RotaryEncoder library.
// It starts with an intermediate value (80h).
// * If you rotate it left, it slows down (then it jumps to the fastest).
// * If you rotate it right, it speeds up (then it jumps to the slowest).
// The jumps are because there is no logic to handle wrap-around - an exercise
// for the reader!
//
// Also note that a bias feature has been included. The faster you turn the knob, the
// exponentially quicker the rate changes. This is done by setting a fast rate on
// every detent, then when the millisecond has changed it re-biases the knob lower.
//
// To handle the knob correctly, it needs to INCREASE the time interval when
// dialling LOWER - hence you'll see a negative number in the code.
//
// It also checks for the switch. If it's pressed, it simply turns the LED full on.
//

#include <RotaryEncoder.h>

// Choose pins that are convenient for the RotaryEncoder's pins
#if defined(ESP8266)

const byte LED = D5;                   // No built-in LED! Choose... this one!
const unsigned baud = 115200;
const RotaryEncoder::OptPin GND = -1; // Use GND pin
const RotaryEncoder::OptPin VCC = -1; // Use V+ pin
const RotaryEncoder::OptPin SW  =  D4; // Switch
const RotaryEncoder::Pin    DT  =  D3; // Data
const RotaryEncoder::Pin    CLK =  D2; // Clock

#elif defined(ADifferentBoard) // Put the board's definition here

// And then change these assignments
const byte LED = LED_BUILTIN;
const unsigned baud = 57600;
const RotaryEncoder::OptPin GND =  8; // Need 0V
const RotaryEncoder::OptPin VCC =  9; // Need +V
const RotaryEncoder::OptPin SW  = 10; // Switch
const RotaryEncoder::Pin    DT  = 11; // Data
const RotaryEncoder::Pin    CLK = 12; // Clock

#else // Arduino Uno default

const byte LED = LED_BUILTIN;
const unsigned baud = 57600;
const RotaryEncoder::OptPin GND =  8; // Need 0V
const RotaryEncoder::OptPin VCC =  9; // Need +V
const RotaryEncoder::OptPin SW  = 10; // Switch
const RotaryEncoder::Pin    DT  = 11; // Data
const RotaryEncoder::Pin    CLK = 12; // Clock

#endif // Boards

// Tell library which pin does what. Note Optional Pins can be -1
RotaryEncoder encoder(GND, VCC, SW, DT, CLK);

// Setup the board for these definitions
void setup() {
    Serial.begin(baud);
    pinMode(LED, OUTPUT); // Want to see it working

    encoder.Begin(10); // Start, with a re-bias of 10
} // setup()

bool ledON = false;  // Current LED state
byte repeat = 0x80;  // How quickly to restart, in ms
byte count = repeat; // Count down 'til next time!

unsigned last = 0;   // Last time millis() was recorded

void loop() {
    // Have switch override pulsing - turn it hard ON
    if (encoder.Switch()) { // Hard override!
        ledON = false; // Pretend LED is now OFF
        digitalWrite(LED, HIGH);
    } // if
    else {
        int value = encoder.Get(); // Returns positive for clockwise turn
        repeat += -value;   // We want to INCREASE time to slow down blinking
        if (value!=0) {     // Did it change?
            Serial.print(value);    // Print latest value
            Serial.print('=');
            Serial.println(repeat); // Print new result
        } // if
    } // else

    // Is it time to blink the LED again?
    unsigned latest = millis();
    if (last!=latest) {
        last = latest;
        encoder.Rebias();    // Re-bias encoder, to decelerate rotation
        if (--count==0) {    // Reached zero yet?
            ledON = !ledON;  // Yes! Toggle LED
            digitalWrite(LED, ledON ? HIGH : LOW);
            count = repeat;  // Count for next time
       } // if
    } // if
} // loop()

```

# Answer
> 0 votes
did you try a different pin? (D2, D1) should work.. Seems like D0 does not have interrupt https://opensprinkler.com/wp-content/uploads/2016/03/NODEmcuPinOut.png

also there is a rotary encoder library so try using that ..

The library i use is able to work without interrupts Encoder by Paul Stoffregen available from Arduino Library Manager or https://www.pjrc.com/teensy/td\_libs\_Encoder.html

---
Tags: esp8266
---


title: Change Arduino Clock Speed

text:
# Question
Title: Change Arduino Clock Speed
I want to run an arduino board at a slower - but more accurate - clock speed. What (if anything) needs to be changed in the arduino code/libraries in order to achieve this? Normally the boards I use run at 16MHz, but I wish to derive a 10MHz clock from a GPS timing module and run the ATMEL processor off the 10MHz timing clock.

# Answer
You have to change `F_CPU` only - You can add new board into the boards.txt with correct clock speed. EDIT: Aparently millis counter will be drifting much more then expected due to "rounding" errors.

The bootloader on the other side needs to be recompiled with correct `F_CPU` and reflashed, if you want it working at the same baud rate (plus it's possible to change fuses to use external clock source instead of crystal). Otherwise you have to try reduced speed (also configured in board config).

You can use MCUdude/MiniCore as inspiration. It supports many clock speeds (but 10MHz doesn't)
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Set clockspeed of Arduino Pro Micro a. k. a. AtMega32u4
Is it possible to change clock speed when running sketch?

Low-power lib drops the current consumption from 20mA to 9.5mA at 8MHz, it is still too much. Is there a way how to set clockspeed (for example) to 1MHz, go to sleep, after interrupt wake up, set clockspeed back to the 8Mhz (for 3v3), do some stuff and then go sleep again?

Thanks

# Answer
Absolutely. The built-in prescaler can dynamically change the clock speed for most of the systems on the chip (USB still needs to run at full speed in order to operate properly).

```
#include <avr/power.h>

 ...
clock_prescale_set(clock_div_32);
sleep();
clock_prescale_set(clock_div_1);
 ...

```

See the datasheet and AVR Libc documentation for more details.
> 1 votes

---
Tags: power, interrupt, sleep, oscillator-clock, atmega32u4
---


title: Increase Serial Rx buffer

text:
# Question
Title: Increase Serial Rx buffer
I am working with an Arduino Due and I am having some issue with the serial Rx buffers size. I am using a GSM module and some of the replies to the Arduino exceed the number of bytes I can store in the buffer at once.

I have read about ways to increase the buffer size by modifying the Arduino default install files but I cannot take this route as my code may then be compiled on a machine with standard buffer sizes in the default install files and the module would not work correctly.

I am not sure if it is possible but I was hoping that someone might know how to increase the serial buffer size using the source code. If I can do it this way the buffer would always be the size I have specified.

# Answer
> 1 votes
Use timer interrupts to read and store the data from serial. Lets assume you are receiving data at baud rate of 115200 in default configuration (8data bits, 1 stop bit), 115200/9=12800 bytes per second, approximately 80 micro seconds for every byte, create a timer interrupt that is called once every 2 millisecond(Choose best time for your application making sure that receiver buffer does not overflow), In 2milli seconds 25bytes of data will be available in the buffer. So you can read data in batches of 25 each. From the interrupt read and store the available data from the buffer.

---
Tags: serial, arduino-due
---


title: Individual control of multiple RGB leds

text:
# Question
Title: Individual control of multiple RGB leds
I'm trying to control several RGB leds individually. So far I've been able to control multiple RGB leds using only 3 PWM outputs using NPN transistors as shown here (pic below).

I would like to control each led individually in order to display different colors in each led. If I used the Arduino Mega, which has 12 PWM pins I could only control 4 different groups of leds using the approach mentioned above. It would be nice to be able to control them using the Arduino Uno or other boards with less PWM pins.

What would be a good solution for this? I've been taking a look to shift registers using ShiftPWM and solutions like the TLC5940 but I haven't got enough experience to tell which way would work better.

# Answer
> 1 votes
Here is a 1/2 software 1/2 hardware solution:

You actually have 6 pwm pins (from the silk screen notation in your picture). So you can control 2 RGB LEDs independently. If you added 4 more transistors that are used to gate the common 5v going to each of the 4 RGB LEDs you could control them in pairs. That is, you could turn on 2 independently controlled RGB LEDs and let the 6 PWM outputs control the brightness and color of each of the 2 for, say, 100ms. Then you could turn those off and turn on the other 2 independently controlled RGB LEDs for 100ms. During the switch, you would change the PWMs for the 2nd set of RGB LEDs. The draw back to this approach? You may start noticing the LEDs flickering. You may have to adjust the rate which you switch between the two pairs of LEDs. And, of course, it may not work as you expect it to.

Totally different approach:

You can use programmable RGB LEDs:

And use this Arduino software library. These types of RGB LEDs have the PWM build in. The Arduino sends out serial data to the first LED which strips off its RGB data. Then sends the data to the next RGB LED which does the same. So you can control many RGB LEDs using a single pin on your Arduino.

# Answer
> 0 votes
There is an alternative that gives you more PWM pins when using an Arduino Uno. You need a 74HC595 shift register which has eight additional output pins. By default, these pins are not PWM capable, however, with a library that I have developed they are.

You can then easily replace your `analogWrite` calls with something like that `sr.set(i, val);`. The parameter `i` indicates with shift register pin you want to update and `val` is a PWM value (from 0 to 255).

---
Tags: arduino-uno, arduino-mega, led, pwm, rgb-led
---


# Question
Title: Using Li-Poly battery to run UNO + Adafruit data logger
I want to power Arduino UNO+Adafruit data logger (https://www.adafruit.com/product/1141) with a 3.7V 2000mAh Li-Poly battery. I am providing an excitation voltage of 3V, through one of the digital pins and a potential divider arrangement, to a sensor which is providing output signal in analog (voltage) form. I am using ADC to read that voltage. My question is, since the battery voltage is going to drop during its operation, would the voltage output from the digital pin, and thus the potential divider, also drop? Could this voltage drop also affect the reference for the ADC?

# Answer
> 1 votes
You can't run the Arduino UNO directly from 3.7V.

You can use a boost regulator to step up to 5V and feed that into the 5V pin - in which case your question becomes null and void, since you are running at 5V, not 3.7V.

Or you can perform some hardware and/or fuse modifications and run the board directly from 3.7V into the 5V pin:

* You will have to change the surface mount resonator to an 8MHz one instead of the normal 16MHz, or
* Switch the clock to use the internal RC oscillator by reprogramming the fuses.

Either way you will then have to also modify the board configuration in the IDE to run at the new clock speed.

So given all that the simplest thing to do is to invest in a 5V boost regulator. Personally I'd suggest the LiPower Shield from Sparkfun. It also has a "fuel gauge" chip to monitor the batter charge.

Either that or scrap the Uno and invest in a development board that is designed to run from a Li-Poly / Li-Ion / LiFePO4 battery.

---
Tags: sensors, battery, adc, analogreference
---


title: ESP8266 Websocket issue

text:
# Question
Title: ESP8266 Websocket issue
I realize it might be dumb question, but I've been at it for a few hours and I'm going nowhere. I am trying to figure out the standard Websocket library, however I have an issue casting the uint8\_t to a String, so I can work with it easily, how do I do that and is it even possible? What I want to do is, get the payload from the main function as shown in the standard library and give it as a parameter to a function I have. This is the part I need, this is part of the switch statements in the standard library.

```
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {

   switch(type) {
     case WStype_DISCONNECTED:
     Serial.printf("[%u] Disconnected!\n", num);
   break;
   case WStype_CONNECTED:
    {
      IPAddress ip = webSocket.remoteIP(num);
      Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);

      // send message to client
      webSocket.sendTXT(num, "Connected");
    }
   break;
   case WStype_TEXT:
      Serial.printf("[%u] get Text: %s\n", num, payload);
      move(payload);

```

# Answer
you can't cast it. payload is an array of received bytes and length is the size of received data in that array. if the bytes are characters and you would know that there is one more position allocated in that array, you could put a 0 to payload\[length\] and by cast to char\* it would become a zero terminated string. but you can't know if there is that one byte allocated, so you must copy the payload to your buffer of chars and set a zero at the end.
> 1 votes

---
Tags: esp8266, arduino-ide
---


# Question
Title: Using typedef to declare a buffer type which then to pass by reference as function argument
I'm new to Arduino, but I'm a C/C++ veteran (not to mention some other languages).

Now I was under the impression that the code I'm typing into the Arduino IDE was a C or C++ dialect. However, just now I ended up puzzled because the compiler wouldn't swallow either of the following:

```
#define RFID_SIZE 5
#define CSUM_SIZE 1
typedef unsigned char rfidbuf_t[RFID_SIZE+CSUM_SIZE];

```

or my first attempt:

```
#define RFID_SIZE 5
#define CSUM_SIZE 1
typedef byte rfidbuf_t[RFID_SIZE+CSUM_SIZE];

```

Now I figure that a `#define` ought to be cheaper than a constant, so that's why I went for defines. The fact that `#include` is supported suggested to me there'd be a `cpp` in the Arduino development environment as well.

What struck me as odd was the fact that I get to see the error only on the next code line (not on the line with the `typedef`):

```
rfid_serial.ino:6:18: error: ‘rfidbuf_t’ was not declared in this scope
rfid_serial.ino:6:29: error: ‘code’ was not declared in this scope
rfid_serial.ino: In function ‘bool ReadRFIDTag(byte (&)[6])’:
rfid_serial.ino:15:33: error: ‘bool ReadRFIDTag(byte (&)[6])’ redeclared as different kind of symbol
rfid_serial.ino:6:6: note: previous declaration ‘bool ReadRFIDTag’
rfid_serial.ino: In function ‘void loop()’:
rfid_serial.ino:96:21: error: ‘ReadRFIDTag’ cannot be used as a function

```

The code I came up with was an attempt at optimizing the way this works. In particular I noticed that `String` (a class, it seems?!) Increases the size of my code quite a lot. So I thought a reference to the buffer would be a sensible choice here.

Here's the complete code:

```
#include <SoftwareSerial.h>
#define RFID_SIZE 5 // the code size (digits) of the RFID tag.
#define CSUM_SIZE 1  // the csum size (digits) of the RFID tag.
typedef byte rfidbuf_t[RFID_SIZE+CSUM_SIZE];

SoftwareSerial RFID(2, 3); // RX and TX

void setup()
{
  RFID.begin(9600); // start serial to RFID reader
  Serial.begin(115200); // start serial to PC
}

/* From: https://efxa.org/2013/05/23/simple-function-implementation-for-parsing-rfid-tags-in-arduino/ and adjusted. */
bool ReadRFIDTag(rfidbuf_t& code)
{
  byte value = 0;       // temporary data received from RFID reader.
  byte checksum = 0;    // checksum data of RFID tag received.
  byte bytesRead = 0;   // number of received data from RFID reader.
  byte tempByte = 0;    // temporary value used for checksum calculation.

  bool handled = false; // flag indicating if an RFID tag was handled.

  // if there are any data coming from the RFID reader.
  if (RFID.available () > 0)
  {
    // check for the STX header (0x02 ASCII value).
    if (0x02 == (value = RFID.read ()))
    {
      // read the RFID digits & the checksum digits.
      while (bytesRead < (RFID_SIZE + CSUM_SIZE))
      {
        // if there are any data coming from the RFID reader.
        if (RFID.available () > 0)
        {
          // get a byte from the RFID reader.
          value = RFID.read ();

          // check for ETX | STX | CR | LF.
          if ((0x0D == value) || (0x0A == value) || (0x03 == value) || (0x02 == value))
          {
            // stop reading - there is an error.
            break;
          }

          // convert hex tag ID.
          if ((value >= '0') && (value <= '9'))
          {
            value = value - '0';
          }
          else if ((value >= 'A') && (value <= 'F'))
          {
            value = 10 + value - 'A';
          }

          // every two hex-digits, add byte to code.
          if (bytesRead & 1 == 1)
          {
            // make some space for this hex-digit by shifting
            // the previous hex-digit with 4 bits to the left.
            code[bytesRead >> 1] = (value | (tempByte << 4));

            if (bytesRead >> 1 != 5)
            {
              // if this is checksum byte, calculate the checksum (XOR).
              checksum ^= code[bytesRead >> 1];
            }
          }
          else
            tempByte = value;

          // ready to read next digit.
          bytesRead++;
        }
      }

      // handle the RFID digits & the checksum digits.
      if (bytesRead == (RFID_SIZE + CSUM_SIZE))
      {
        // check if the RFID code is correct.
        if (code[5] == checksum)
        {
          // set that the tag was handled.
          handled = true;
        }
      }
    }
  }

  return handled;
}

void loop()
{
  rfidbuf_t buf = {0};
  if(ReadRFIDTag(buf))
  {
    Serial.println(buf[0]); // TODO
  }
}

```

Is it impossible to use `typedef` the same I'm used to from C and C++? Because what I am attempting isn't all too unusual in C or C++ code, but of course references only exist in C++.

Does it mean I should rather into working with `avr-gcc` directly? I was under the impression that the Arduino IDE is basically built atop `avr-gcc` and `avrdude` (and possibly other backend programs).

# Answer
Your version of the IDE (1.0.5) is incredibly ancient (just because it's in APT doesn't mean it's up to date - only that at some point within the last 20 years someone submitted it).

That version suffers from the problems that Ignacio describes in his answer. More modern versions (we're up to version 1.8.5 now...!) use a different build system which is far more intelligent about how it lays out its function prototypes.

Go to the Arduino website and download the latest version and you won't have these kind of problems and have to work around them with strange things like unnamed namespaces.
> 2 votes

# Answer
The Arduino IDE (un)helpfully copies function declarations towards the top, but fails to handle custom types properly. The solution is to hide the declarations in an unnamed namespace.

```
 ...
typedef byte rfidbuf_t[RFID_SIZE+CSUM_SIZE];

namespace {
  bool ReadRFIDTag(rfidbuf_t& code);
}
 ...

```
> 1 votes

---
Tags: programming, c++
---


# Question
Title: Arrays, and for loops... faster to use together, or not to use?
I'm a 4th year EE undergrad, so I'm more of a hardware guy than software. But concerning best programming techniques, is it "better" (more efficient/and/or equally effective) to use for loops when trying to change several items in an array by the same mathematical operation?

--OR--

Is it best to list each item out and have each operation performed by the rate at which the primary "void loop" cycles?

I'm using a Teensy 3.2 board and trying to get a DSP reverb effect working. I have an array of 8 delay tap lines, each with a different time multiplier. I'm trying to determine if it will take more time to process a for loop for each delay-tap line, versus multiplying each element in my array without the additional loop. I need to minimize processing time at all costs to avoid additional system lag.

Sample code:

```
  //Set delay times
  for(int i = 0; i < 8; i++)
  {
    delay1.delay(i, pot1*pauses[i]);
  }

```

versus

```
  delay1.delay(0, pot1*pauses[0]);
  delay1.delay(1, pot1*pauses[1]);
  delay1.delay(2, pot1*pauses[2]);
  .
  .
  .

```

**EDIT** Added sample code.

# Answer
> 2 votes
Have a look at the compiler output.

**The Loop option**

The first alternative produce a preface (setting things) and the loop itself.

*Preface*

```
40201803:   21c9        s32i.n  a12, a1, 8
40201805:   3109        s32i.n  a0, a1, 12
40201807:   00a0c2          movi    a12, 0

```

*loop*

```
4020180a:   202cc0          or  a2, a12, a12
4020180d:   01ccc2          addi    a12, a12, 1
40201810:   ff8585          call0   4020106c <delay>
40201813:   f38c66          bnei    a12, 8, 4020180a <_Z6XYtestv+0xa>

```

**The unfolded option**

While the unfolded version is:

```
40201823:   020c        movi.n  a2, 0
40201825:   3109        s32i.n  a0, a1, 12
40201827:   ff8445          call0   4020106c <delay>
4020182a:   120c        movi.n  a2, 1
4020182c:   ff83c5          call0   4020106c <delay>
4020182f:   220c        movi.n  a2, 2
40201831:   ff8385          call0   4020106c <delay>
40201834:   320c        movi.n  a2, 3
40201836:   ff8345          call0   4020106c <delay>
40201839:   420c        movi.n  a2, 4
4020183b:   ff8305          call0   4020106c <delay>
4020183e:   520c        movi.n  a2, 5
40201840:   ff8285          call0   4020106c <delay>
40201843:   620c        movi.n  a2, 6
40201845:   ff8245          call0   4020106c <delay>
40201848:   720c        movi.n  a2, 7
4020184a:   ff8205          call0   4020106c <delay>

```

So, the loop execute 4 instructions per each array element, while the unfolded version had only 2 instructions per array element.

But you are trading speed for space and and risking an error while coding the same repetitive thing.

However, GCC (the 'Arduino' compiler) can unfold the loop by itself, so you still can write a loop but execute a sequence. Look at Tell gcc to specifically unroll a loop

**Real numbers**

I run a sketch (Arduino UNO) to time loop vs unfolded. The times for 1,000 execution of each method are:

```
loop:     6524us
unfolded: 3808us

```

Quit a difference!

Sketch

```
int pause[8] = {1, 2, 3, 4, 5, 6, 7, 8};
typedef int (*fn)(void);

void setup() {
  Serial.begin(9600);
  while(!Serial);
  Serial.println();

  Serial.print("Timing loop: ");
  Serial.print(time(met1));
  Serial.println(" us");

  Serial.print("Timing unfolded: ");
  Serial.print(time(met2));
  Serial.println(" us");
}

void loop() {

}

int time(fn f) {
  unsigned long start = micros();
  int x = 0;
  for (int i = 0; i < 1000; i++) {
    x = f();
  }
  unsigned long dif = micros() - start;
  return dif;
}

int met1() {
  int sum = 0;
  for (int i=0; i < 8; i++) {
    sum += pause[i];
  }
  return sum;
}

int met2() {
  int sum = 0;
  sum += pause[0];
  sum += pause[1];
  sum += pause[2];
  sum += pause[3];
  sum += pause[4];
  sum += pause[5];
  sum += pause[6];
  sum += pause[7];
  return sum;
}

```

# Answer
> 0 votes
> is it "better" (more efficient/and/or equally effective)

depends on your definition of "better", or "efficient", ...

for example unrolling a loop is typically more efficient speed-wise, but less so space-wise. or vice versa.

on top of that, you have other potential definitions for "efficiency", like readability, etc.

---
Tags: array, teensy, speed
---


# Question
Title: How do I combine a variable and characters into a string with Arduino?
I am building some sensors with Arduinos, which each have a unique integer address from 1-9 (This address is an int variable stored in a struct 'Matrix', the variable name is Matrix.Address). The sensors will all be connected to a PLC via SoftwareSerial (BitBanging) through an RS232 converter. Since all of the Sensors will be connected to the same RX & TX ports on the PLC, I need a way to address each sensor through a unique string.

My plan is the following:

\*If the PLC wants a reading from sensor #1, it will send the string: "1,read" All of the sensors should receive this string, but I only want the sensor with address '1' to respond.

\*What I am trying to do is come up with a line of code similar to the following:

```
    if (plcCommand == (Matrix.Address + ",read<CR>")) {
  mySerial.print(GenerateEquation());

```

Basically, I need to insert that 'Matrix.Address' variable into a string which will be compared to the incoming string.

It seems like a very simple thing to do, but I am having trouble coming up with a solution.

Any help would be appreciated!

# Answer
> 1 votes
You're thinking backwards. Instead of building up one string and comparing it to another, you should instead be splitting down the string you are being sent and dealing with the different parts of it separately.

Say you are being sent the string `32,read\r`. Instead of making another string `32,read\r` and comparing it to what you have received you should instead be splitting the incoming string up.

That way you then have a string containing `32` which can be converted to an integer, and a string containing `read`. It now becomes very simple to do your comparisons without messing with building strings in RAM wasting precious memory.

# Answer
> 0 votes
> it will send the string: "1,read"

Fairly simple:

1) the dumbest would be to use serial print to print the number, and then ",read".

2) a close 2nd (in terms of dumbness) is to use s/printf(): simple but costly on a mcu.

3) a smarter approach is to convert the number to a string - you can use standard c routines if your compiler supports them, or hand-roll your own.

4) if the number of sensors are limited, a look-up table or a switch/case statement would work well.

# Answer
> 0 votes
> If the PLC wants a reading from sensor #1, it will send the string: "1,read" All of the sensors should receive this string, but I only want the sensor with address '1' to respond.

Is your question about sending the "1,read". If you're using a serial line like you say then there is no difference between sending that as a single string in one print command or sending first the number and then the text part using two print commands back to back. The exact same thing will end up going out over the wire either way. So just use two separate print commands.

---
Tags: serial, string
---


title: SIM900A A6 module Arduino +CME error 58

text:
# Question
Title: SIM900A A6 module Arduino +CME error 58
I've recently bought a SIM900A A6 GSM module. Whenever I send a command it gives an error: +CME error 58.

Does anybody know what this means and how to solve it?

# Answer
Your sim card is probably protected by a PIN. Easiest way to get it working is to put the SIM into a normal phone and remove the PIN protection.
> 1 votes

# Answer
I had the same error. My error was using the incorrect baud rate. Set the baud rate to 115200. Also, ensure that "Both NL & CR" option is selected for new line options. After changing those settings, I had to reboot the A7, and wait for all the status messages to complete before I could send the AT command.
> 0 votes

---
Tags: compilation-errors
---


title: Why char 0x80 == 0xFFFFFF80?

text:
# Question
Title: Why char 0x80 == 0xFFFFFF80?
As far as I know a char is an 8 bit variable

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

void loop() {
  char x = 0x80;
  if(x != 0x80){
    Serial.println(x, HEX);
  }

  delay(1000);
}

```

# Answer
> 4 votes
To illustrate the reasons better let's look at the actual content of the data.

`0x80` is `0b10000000` in binary. A `char` is a *signed* variable, which means that the most significant bit is the sign bit, with *two's complement* representation

So in 8-bit signed representation the value `0b10000000` is a sign bit and zero value - which is -128 in decimal notation, which is "-128 + the 7 least significant bits", or -128 + 0 in this case.

When you print a signed value on the Arduino as HEX there is no 8-bit specific function for it. Neither is there a 16 bit function. However there is a 32-bit signed function, which is the closest match available. So the compiler performs *type promotion* to 32-bit signed, then represent it as hexadecimal.

Now -128 in signed 32-bit is calculated in the same way - take the value of the most significant bit, negate it, and add the value of all the other bits to it. With 32-bits the value of the most significant bit, in decimal, is 2147483648, so negate that into -2147483648. Now we need to make that into -128, so we need the difference between the two to add to it. That's 2147483520.

So you get the MSB + 2147483520, which in hexadecimal, is 0xFFFFFF80.

Of course, the compiler doesn't go through that whole routine - instead it uses something called *sign extension*. This method basically means copying the sign bit from the original smaller (char) type into every bit to the left of it in the larger type:

```
                           10000000 8 bit signed
                  11111111 10000000 16 bit signed
11111111 11111111 11111111 10000000 32 bit signed

```

All those are -128 in two's complement, just stored in different size variables. So when you come to print it, that is just what you get - the two's complement representation of -128 in the variable size that has been accepted by the print function.

You might find this site useful for experimentation and furthering your understanding of variable data storage.

# Answer
> 2 votes
Sign extension. Try this:

```
void loop() {
  char x = 0x80;
  if(x != (char) 0x80){
    Serial.println(x, HEX);
  }

```

Before any operation involving different types, the lower ones must be promoted to higher ones.

The constant 0x80 is an integer value, so `x` must be promoted to `int` before the test. The first bit of an `int` value is the sign bit. Sign bit is extended (copied to the left side bits). So `x` become 0xFFFFF80 and then you compare it against 0x0000080.

Every time you put a *char* where an *int* is excepted the same thing happen.

See? Programming is hard, programming in C is harder, programming in C++ is the hardest.

C is full of traps.

# Answer
> 2 votes
char is signed so `0x80` is really `-0x80` (`==-128`). When promoted to a higher width the sign gets copied into the new bits `0xffffff80` (still `==-128`).

if you put unsigned in front of char you won't get that issue (though may encounter others).

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

void loop() {
  unsigned char x = 0x80;
  if(x != 0x80){
    Serial.println(x, HEX);
  }

  delay(1000);
}

```

---
Tags: data-type
---


# Question
Title: I fried my arduino. Can I upload code wirelessly?
So, I'm a complete arduino newbie. I left a live wire close to my arduino and part of it burnt (underneath the USB output). The LED that indicates power still turns on when I plug it into my computer, and a simple LED circuit on my breadboard, when hooked up to the arduino, still works. The only thing that's wrong is that my computer doesn't recognize the Arduino serial port any more, so I can't upload any code onto it.

I also own a bluetooth HC-05 module. Is there any way I could upload code onto my Arduino wirelessly, using that? Or am I better off just buying a new one?

# Answer
> 1 votes
If the main MCU is still functioning fine then yes, sure you can.

The only caveat is that you may have to manually reset the Arduino at the right moment in order to enter the bootloader for programming.

* Connect the bluetooth module to TX/RX/GND (TX-\>RX, RX-\>TX)
* Configure the bluetooth module to work at the bootloader baud rate (115200 baud) - you may need to wire it to your PC to manage this part.
* Connect a virtual COM port to it and program through that.
* Press RESET just as it's about to run AVRDUDE in the IDE.

# Answer
> 0 votes
You did not say which Arduino you are using.

Most Arduinos abstract the complexities of the USB interface, format and protocol by using a 2nd processor on the Arduino board. If damaged, you will essentially have to replace this function. It is unlikely that a Bluetooth radio will act similar enough to do this.

If the main processor and supporting circuitry is not damaged, it would be easier to program the Arduino from another Arduino such as described here.

# Answer
> 0 votes
It sounds like you have fried the Atmega16U2 which is programmed as a USB-to-serial converter, as seen in the picture below.

You can still program the Atmega328P microcontroller using the ICSP and an appropriate Atmel programmer such as the Atmel Ice or the AVRISPmkII. Alternatively you can use another Arduino Uno as a In-System Programmer.

I cannot say about using a bluetooth HC-05 module,however I imagine it would be a fair bit of effort and hence would be easier to buy a new one. Keep the current one though because you can use the new one as an in-system programmer as per the link above.

---
Tags: wireless, upload
---


# Question
Title: Does 12v 5A power supply is okay to operate motor shield external power
I am new to arduino.  Recently purchased motor shield V1.0 which have two l293 and can run 4 DC motors simultaneously. But here the problem comes: when I purchased the shield I was not aware that it can only supply 2A peak current. However, my DC motor rating is 12v 5A. So I purchased a 12v 5A power supply. But now I am not sure to operate shield with external power of 12v 5A.

Does it works or will it burn?

# Answer
The shield will "burn". You need a shield that can provide minimum 5A *per channel* to run a 5A motor.

However, your motors *aren't 5A*. They have a stall current of 300mA, which is well within the capabilities of the motor shield, and the 5A power supply you have would barely even notice they were there.
> 1 votes

---
Tags: arduino-uno, arduino-motor-shield
---


# Question
Title: Arduino Mega 2560 not recognized/overloaded
I pulled my Arduino set out of storage yesterday and was very upset to find that it is not working for some reason. Before I explain the problem, let me explain the situation.

Hardware (all DFRobot):

Arduino Mega 2560

Arduino Mega 2560 4x-platform breakout board

GPIO Expansion Shield V1.0

I/O Expansion Shield V7.1

8 Channel 5V Relay Board

4 LED/Resistor set up

1 digital speaker

1 digital humidity/temperature tester

7 analog chemical air chemical testers

The whole project:

LED Portion:

Relay Portion:

Sensor Portion:

Pin Connections:

In this 4th photo, the two analog pin sets in use right in front are the ones I remove in order to gain control again. if those are plugged in then it doesnt work. It has nothing to do with those pins specifically, If I remove any two it works again, those ones are just easiest to remove to get it to work:

Explanation of project:

This is basically a test station, where I can hook up what ever I want and see how it works and then move onto another peripheral piece of hardware and make them interact. I went with the 4x-platform breakout board as to maximize I/O space. Once a project is done, I Velcro band them together as to not get them confused and move on.

Explanation of problem:

When I plugged the Arduino into my PC the first time, the lights came on the Arduino and then after about 15 seconds it powered down and the lights went off. My PC did recognize it while it was powered up and the port option under tools in the Arduino IDE was available and I could select the port. After the power down and problems I realized something must be up.

I considered the fact that maybe the Velcro was constricting the wires and causing them to short circuit through the rubber insulation, but couldn't find any info on that online.

After this I decided to cut the PC out of the equation and try just plugging it into the wall, 1st, via USB to 5V1A wall charger, it stayed on for a few seconds and then turned off, 2nd with a 5V2A wall charger, same scenario, 3rd via the barrel jack with the same wall chargers, with no success.

I undid all of the wire bundles to rule out a short circuit, which it did. I then found out after much trial an error that if I removed any 2 of any analog or digital wires, the lights would stay on and it would work.

Now, with two cables removed so it did not lose power, I plugged it into my PC and am now able to program it again and see it in the port in the IDE, but as soon as I plug in another 2 analog or digital peripheral devices it will lose all power and stop working.

I also tried plugging my DFRobot Beetle micro-controller in with the same USB cable and it worked perfectly. I also tried resetting the micro-controller, to no avail.

Conclusions so far:

A short between rubber insulation at 5v is extremely unlikely

one would think that if a mega board was designed to have so many I/O pins you could actually connect to all of them with out any problem.

Since this happened on both the PC and wall charger scenarios, and the problem seems to be associated when disconnecting any 2 sensors, the problem is most likely at the micro-controller level.

Questions:

are all the peripheral devices draining the board so much that the USB port on the PC or wall chargers cant handle it?

How do I provide enough power to the board if this is the problem?

Or is this simply faulty board?

If it is a faulty board, what causes this and how do you avoid it?

Just to clarify, looming the wires together into bundles is OK right?

Finally, any help would be really appreciated, this is the first time this has happened and it sucks.

# Answer
First off, that is one heck of a rig. I'm impressed to the point of "I gotta get me one of those."

Bundling your wires shouldn't have the kind of impact you are seeing, unless there are bare wires touching. You might get induction interference, but not a total shut down.

From what I can see here, it looks like there's so much stuff connected to the Arduino that it's probably starving it for power. You should look into using power rails for Gnd and +5v.

You will also need to check if you are supplying it with enough amps, too. Your computer's USB port only supplies 0.5A, unless it happens to be USB3, then it's 0.9A. Even your 5V1A PSU might not be enough. Consider finding a 2-5 amp wall wart to do some more testing with. There are usually spec sheets with components, so you'll need to add all the power draw for all the components, including the Arduino, and make sure you have more than enough to meet that calculated power draw. Exceeding it by at least 10-20% is usually considered good practice, even for a test rig.

Consider powering your rig's new power rails with the extra PSU even when the Arduino is plugged into your computer. As long as you make sure you aren't trying to take power from the computer and the PSU at the same time with the same component, you should be fine. (Don't cross the streams.)

There could be a short or feedback loop somewhere in your sensors that's causing the extra drain. There are so many wires here that it'd be easy to hook up something backwards. Along with the number of wires, the bundling doesn't let SE-us help you track that down.

You might want to look at the direction your pins are facing. It was an odd situation for me, but having two of the metal clips facing each other was enough for a short. In your "Relay Portion:" pic, they are all facing the same way, which is good. See if there are places where that's not the case and fix it. Like I said, it was an odd situation, but it's a phantom problem you can avoid.
> 0 votes

---
Tags: arduino-mega
---


# Question
Title: Trying to determine the phase difference between two square signals
I have been looking for the phase difference between two square signals and this is the code:

```
#include <avr/io.h>
#include <avr/interrupt.h>

void setup() {
  //Serial.begin(9600);
  pinMode(2, INPUT);    //set pins 2 and 3 as inputs and 11 as output
  pinMode(3, INPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

  cli();           // disable all interrupts
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);  //set up timer2 to generate a PWM
  TCCR2B = _BV(CS20);    //set prescalar value to 1
  //TCCR1A = 0;
  //TCCR1B = _BV(CS20);
  //TCCR1B |= (1 << CS12); //256 values
  TCNT2  = 0;
  sei();             //enable all interrupts

  attachInterrupt(digitalPinToInterrupt(2), t1_ISR, RISING);     //enable interrupt service routines on pins 2 and 3
  attachInterrupt(digitalPinToInterrupt(3), t2_ISR, RISING);

  //Serial.print(OCR2A);
  //Serial.print(OCR1A);

}

volatile uint8_t t1, t2;

void loop() {
  if (t2 == t1)
  {
    OCR2A = 0;
    OCR2B = 0;
  }
  //compare time that one signal goes high to time the other signal goes high
  else if (t2 > t1)
  {
    OCR2A = (t2 - t1); //output PWM based on phase difference on pin 11
    OCR2B = 0;
  }
  else if (t2 < t1)
  {
    OCR2B = (t1 - t2);  //output PWM on pin 11
    OCR2A = 0;
  }
}
}

void t1_ISR() {         //interrupt if signal on pin 2 goes high and store counter
  t1 = TCNT2;           //value to variable t1
}

void t2_ISR() {         //interrupt if signal on pin 3 goes high and store counter
  t2 = TCNT2;           //value to variable t2
}

```

I want to operate the input pulses at 40 kHz, how can I do this and read the difference of phase? I am using the Arduino Mega2560

# Answer
There are a few things very wrong here.

First problem: you are clocking Timer 2 with the prescaler set to 1. This means the timer will roll over every 256 CPU cycles. Your input signal, on the other hand, has a period of 25 µs, which is 400 CPU cycles (I am assuming a 16 MHz Arduino). Unless you know beforehand that the phase difference is within some window less than 16 µs wide, your readings will be ambiguous.

You have to make sure the rollover period of your timer is larger than the period of the input signal. This means either using a larger prescaler (8 should do), which will decrease your phase resolution, or using a 16-bit timer instead of an 8-bit timer.

Second problem: you are using a *signed* integer type for the timer readings. This makes little sense. Worse: you are computing differences like `t2-t1`, which can overflow. Signed integer overflow is undefined behavior in C++, and invoking it is *always a bug*.

You should declare `t1` and `t2` as unsigned, i.e. either `volatile uint8_t`, or `volatile uint16_t` (if using a 16-bit timer). Then you don't get overflows: you get instead a well-defined rollover behavior.

Third problem: you are doing comparisons like `if (t2 > t1)`. This, again, makes no sense, if only because the timer is repeatedly rolling-over to zero. You should instead just compute `t2-t1` and work your way from that.
> 1 votes

# Answer
> how can I do this and read the difference of phase?

a few simple ways:

1) poll the input signals: For example, once a pin has gone high, wait for the other pin to go high as well.

2) xor the input signals: wait for the XOR of both inputs to go high, wait for it to go low. essentially the 1st approach;

3) use interrupts: once the first signal goes high, start a timer; once the 2nd signal to go high, stop the timer.

4) use input capture: ...

...
> 1 votes

---
Tags: programming, atmega2560
---