# Question
Title: Purpose of extra holes for pins or Arduino clone
I bought this Arduino clone recently and it has lot of extra holes for pins, but some of them I don't know what they do. There was no instruction manual that came with it. Here's a picture of it, I added a red rectangle around the ones I don't know. (4 pins with X1, SCL/SDA, AREF and blank pin in the bottom)

I thought I could use the pins SCL SDA 5V GND with my I2C LCD Display because the names of the pins are the same on it. Could it work? Usually I use analog pins to connect the display, does that mean that by using it some analog pins will be used indirectly? I didn't try connecting it because I don't want it to break.

What do these pins do?

# Answer
> 3 votes
It's what they say they are.

SDA/SCL are I2C - what used to be A4/A5 on the old footprint. On the '328 based boards those are directly linked to the A4/A5 pins.

The blank pin isn't used. The 5V next to it is actually mislabelled and should be labelled "IOREF".

AREF has been there since the very first Arduino boards.

It's the standard "R3" Uno footprint, plus some extra breakouts for the I2C in different forms (probably to go with specific I2C devices they also sell).

All of that is on the Uno's product page if you'd care to read it some time...

The ones by the cheap Chinese USB interface chip will be something to do with that. Maybe RTS/CTS broken out on a header. You can ignore those - they are of no interest at all. In fact, just looking in their direction has a good chance of breaking the USB interface chip. Stay well away.

---
Tags: arduino-uno, pins, clones
---


title: Wifi rssi converting char[] to uint8_t

text:
# Question
Title: Wifi rssi converting char[] to uint8_t
I am trying to get RSSI of a network without connecting to it directly but I get an error " error: cast from 'const char\*' to 'uint8\_t {aka unsigned char}' loses precision \[-fpermissive\]"

```
   char ssid[]="GreenNET";
    long rssi = 0;

    void updateRSSI(){
      rssi = WiFi.RSSI(ssid);
    }

```

I am following this: https://www.arduino.cc/en/Reference/WiFiRSSI except I am not passing password since it is not required `WiFi.RSSI(wifiAccessPoint);`

# Answer
> 1 votes
The argument passed to `RSSI()` must be an integer indicating the array index of the SSID of the WiFi network whose RSSI you want to get. To get that integer, you must first scan for networks.

```
char ssid[] = "greenNet";
byte num_ssids = 0;
long rssi = 0;

num_ssids = WiFi.scanNetworks();
for (byte net = 0; net < num_ssids; net++){
    rssi = WiFi.RSSI(net);
    Serial.print(WiFi.SSID(net)); Serial.print(": ");
    Serial.println(rssi);
}

```

---
Tags: wifi, c
---


title: Mass Storage with Arduino Uno and LUFA

text:
# Question
Title: Mass Storage with Arduino Uno and LUFA
guys ! I want to implement the mass storage example from the LUFA Library to my Arduino Uno, but I do not know where to start. Has anybody done this successfully and could give me a few pieces of advice ?

# Answer
> 2 votes
You start by taking the Uno and putting it aside, and picking up an AVR-based Arduino that has native USB device support such as a Leonardo or Esplora. You can then use the build scripts that come with LUFA to build the code for your device.

---
Tags: arduino-uno
---


title: Delay function not working as intended

text:
# Question
Title: Delay function not working as intended
```
int j;
void setup()
{
   for(j=2 ; j<=9 ; j++)
      pinMode( j , OUTPUT );
   digitalWrite( 2, HIGH );
}
void one()
{
   digitalWrite( 3, HIGH );
   digitalWrite( 4, HIGH );
}
void all_off()
{
   for(j=3 ; j<9 ; j++)
      digitalWrite( j,LOW);
}
void loop()
{
   one();
   delay(1000);
   all_off();
   delay(3000);
}

```

Trying to do a blinking "1" (stopped at 1 before continuing other numbers because of this problem ) with a single-digit 7 segment display. Where pin 2 is comnected to the com pins of the display.

Expected: display 1 for a second , then turn off for 3 seconds.

Reality: display1 for 3 seconds then turn off for a second.

Tried putting the delay functions in the one and all\_off functions but no use.

Tried changing the delay(1000) to delay(7000) , the off time increased.

Tried changing the delay(3000) to delay(1000) , the turn on time changed to 1 second.

The code should work in order, should it not? What is happening? How to fix it?

# Answer
> 1 votes
Without circuit information and part numbers, one can't say for sure what the problem is. However, the symptoms suggest that your LEDs turn on when you pull some pin low, rather than when it goes high. This can happen if, for example, the LED anodes are wired (through a resistor) to V+ and the cathodes are connected to a drive pin. If, however, the cathodes are connected to ground through a transistor, positive-logic should apply, rather than negative logic.

---
Tags: arduino-uno, arduino-ide
---


title: Possible Arduino Uno c++ compiler bug?

text:
# Question
Title: Possible Arduino Uno c++ compiler bug?
I recently gave the students in my Arduino-based programming class a project to write some simple unit tests and fix the bugs that they encountered as they did. The class in question mostly stores a bunch of Arduino-style String objects, with various getters and setters and a couple of constructors.

The test code that they're supposed to write involved creating two instances of the class (on the stack) and verifying that the constructors set the values correctly. When I went through the exercise myself, everything worked.

When the students repeated the exercise, the first object worked. The second object returned empty strings. If they commented out the first object, the second object began working. I couldn't find any obvious mistakes that could explain these failures.

After staring at their code for about ten minutes to make sure I wasn't losing it, I compared Arduino IDE versions to make sure my machine was running the same version. It was.

Next, I unplugged one of their Arduino Uno devices and plugged in my Mega 2560. The exact same source code passed the unit tests as expected. That means the test failures were caused by some subtle difference between the Arduino Uno and the Mega 2560—either in the hardware or in the compiler.

Before I file a bug against the Arduino Uno compiler (v1.6.7, though I don't see anything in the 1.6.8/1.6.9 release notes that imply any compiler changes since then), I wanted to make sure I wasn't missing something subtle. Could somebody take a look at this and see if I missed anything?

I've included a condensed version of the class in question below (with irrelevant bits removed). You can see the complete set of exercises at:

https://sites.google.com/a/cabrillo.edu/cs-11m/schedule/unit-testing-exercises

The tests failed unexpectedly after they added the second `AddressBookEntry` object.

**Class Declaration (partial)**

```
class AddressBookEntry {

  public:
    AddressBookEntry(void);
    AddressBookEntry(String title, String firstName,
                     String middleName, String lastName,
                     String suffix);

    String title(void);
    String firstName(void);

...

  private:
    String _title;      // Mr.
    String _firstName;  // Barack
    String _middleName; // Hussein
    String _lastName;   // Obama
    String _suffix;     // Sr.

    String _addressLine1; // The White House
    String _addressLine2; // 1600 Pennsylvania Ave.
    String _city;         // Washington
    String _state;        // DC
    String _zip;          // 20500
    String _plusFour;     // 0001   (from 20500-0001)

    String _homePhone;    // Unknown
    String _mobilePhone;  // Unknown
    String _workPhone;    // 202-456-1414

```

**Implementation (partial)**

```
#define assert(condition) { \
  if (!(condition)) { \
    Serial.print(__FILE__); \
    Serial.print(":"); \
    Serial.print(__LINE__); \
    Serial.println(": Assertion failed: " #condition); \
    while (1); \
  } \
}

bool AddressBookEntry::runTests(void)
{
  Serial.println("Running tests.\n"); Serial.flush();

  AddressBookEntry testEntry("Mr.", "Jim", "Bob", "Murphy", "Sr.");

  Serial.println(testEntry.title());
  Serial.flush();

  assert(testEntry.title() == "Mr.");
  assert(testEntry.firstName() == "Jim");
  assert(testEntry.middleName() == "Bob");
  assert(testEntry.lastName() == "Murphy");
  assert(testEntry.suffix() == "Sr.");
  testEntry.setMiddleName("Phil");
  assert(testEntry.middleName() == "Phil");

  AddressBookEntry obamaEntry("Mr.", "Barack", "Hussein", "Obama", "");

  assert(obamaEntry.title() == "Mr."); // fails
  assert(obamaEntry.firstName() == "Barack"); // fails
  assert(obamaEntry.middleName() == "Hussein"); // stopped checking here.
  assert(obamaEntry.lastName() == "Obama");
  assert(obamaEntry.suffix() == "");

  Serial.println("All tests passed.\n"); Serial.flush();
}

AddressBookEntry::AddressBookEntry()
{
  _title = "";
  _firstName = "";
  _middleName = "";
  _lastName = "";
  _suffix = "";

  _addressLine1 = "";
  _addressLine2 = "";
  _city = "";
  _state = "";
  _zip = -1; // Deliberate bug
  _plusFour = -1; // Deliberate bug

  _homePhone = "";
  _mobilePhone = "";
  _workPhone = "";
}

AddressBookEntry::AddressBookEntry(String title, String firstName,
                                   String middleName, String lastName,
                                   String suffix)
{
  _title = title;
  _firstName = firstName;
  _middleName = middleName;
  _lastName = lastName;
  _suffix = suffix;

  _addressLine1 = "";
  _addressLine2 = "";
  _city = "";
  _state = "";
  _zip = -1; // Deliberate bug
  _plusFour = -1; // Deliberate bug

  _homePhone = "";
  _mobilePhone = "";
  _workPhone = "";

String str = "";
  Serial.println(str + "title is \"" + title + "\"");
}

String AddressBookEntry::title()
{
  return _title;
}

String AddressBookEntry::firstName()
{
  return _firstName;
}

... // remaining getters are similar

```

**Calling Code (from setup() function)**

```
  Serial.begin(9600);
  AddressBookEntry myEntry;
  myEntry.runTests();

```

# Answer
> 2 votes
> That means the test failures were caused by some subtle difference between the Arduino Uno and the Mega 2560—either in the hardware or in the compiler.

Not a subtle difference - a big difference. The Mega2560 has considerably more RAM than the UNO (8kB compared to 2kB).

All those strings are using RAM. Lots of RAM. Your Mega2560 has enough RAM to cope (just), but the UNO just dumps its stack in a heap all over the floor1 at the mere thought of trying to handle that quantity of string data.

---

1: That's a technical way of describing the stack and the heap meeting and, if there were no protection, colliding into each other.

---
Tags: arduino-uno, programming, arduino-mega, c++, class
---


title: Over voltage protection for Arduino

text:
# Question
Title: Over voltage protection for Arduino
If an external voltage of 7 volts is applied to the external voltage input on the Arduino and the power from the USB port remains connected, is there a protective circuit that will protect the Arduino? Thank you.

# Answer
yes there is. power will be drained from external source(altough 7 volts is around the limit and arduino may switch to usb power) and arduino will still operate at 5v, same as usb. in any case your arduino and usb will be safe.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Intel Edison Program Deleted After Power Off
I just bought a new Intel Edison and flashed the newest Yocto 3.0 image. I uploaded an Arduino program from the Arduino ide which just constantly prints out numbers to serial.

After uploading the code, it works. After I unplug it and plug it back in and wait 2 minutes for it to power on, I open the serial connection and the Edison does nothing like I never uploaded anything.

After some research I found it is a problem with the firmware version 2.5 so I tried 2.1. I tried 2.1 and it still doesn't work. Am I doing anything wrong?

I am using the mini-breakout.

# Answer
I'm having a bunch of problems like this. I went back to 2.1, and that works, but your sketch can't have any code that uses Serial. Serial1 is fine, but not Serial, or else the board hangs and your sketch won't autorun when you aren't connected via USB during reset.
> 0 votes

---
Tags: edison
---


title: EEPROM - Storing Static Data

text:
# Question
Title: EEPROM - Storing Static Data
I'm trying to store four items to EEPROM. I can do one item no problem, I just don't know how to make the jump to multiple items.

My code:

```
#include <EEPROM.h>
char sgrpID[31] = "acpilot's arduino";
char addrID[51] = "123 any street rd";
char zpcdID[11] = "12345";
char gwayID[31] = "what a cool toy!";

void setup()
{
  Serial.begin(9600);
  for (int i = 0; i < 6; i++) {
    EEPROM.write(i, sgrpID[i]);
    EEPROM.write(i, addrID[i]);
    EEPROM.write(i, zpcdID[i]);
    EEPROM.write(i, gwayID[i]);
  }
}

void loop() {
  Serial.println(sgrpID);
  Serial.println(addrID);
  Serial.println(zpcdID);
  Serial.println(gwayID);
  delay(99999);
}

```

I want to be able to call on these in a sketch and post them to a db along with dynamic data of some flavor (TBD).

Am on the right path? Any help, corrections, or general guidance is appreciated. I've moved beyond the "novice" stage of basic Arduino programming but an completely new to EEPROM. If in doubt, SLOWER AND LOUDER is by far the best way to communicate key EEPROM concepts to me.

I have reviewed the Arduino EEPROM library but I was reading Greek. I keep reading it and I'm sure at somepoint I'll recognize a pattrn and start to "get it."

# Answer
> 5 votes
Some things I noticed in your code:

* You are writing everything to the same address (is that intentional?)
* You are only writing the first 6 six bytes of your arrays (I am pretty sure that is intentional)
* You are declaring these arrays to be bigger than what you are putting in them (this is again probably intentional, but I am just guessing)

So here is an example of how I would handle the eeprom:

```
#include <EEPROM.h>

char sgrpID[31] = "acpilot's arduino";
char addrID[51] = "123 any street rd";
char zpcdID[11] = "12345";
char gwayID[31] = "what a cool toy!";

//These are the definitions of what goes where in memory
//You do not want everything to have the same number
const size_t SGRP_ID_EE_START = (0);  //Zero is good address to start
//To get the next address we merely add the size of the first item
//With the address of the first item
const size_t ADDR_ID_EE_START = (sizeof(sgrpID) + SGRP_ID_EE_START);
//And so on and so forth
const size_t ZPCD_ID_EE_START = (sizeof(addrID) + ADDR_ID_EE_START);
const size_t GWAY_ID_EE_START = (sizeof(zpcdID) + ZPCD_ID_EE_START);

//Use this function to write a char array to the EEPROM at
//The address "address" (and the size of "len")
void WriteEepromArray(size_t address,char* arr,size_t len){
  for (size_t x = 0; x < len; x++){
    EEPROM.write(address+x,arr[x]);
  }
}
//Use this function to load your char array with values from
//The EEPROM
void LoadFromEeprom(size_t address,char* arr,size_t len){  //Be aware that this function modifys the data pointed to by "arr"
  for (size_t x = 0; x < len; x++){
    arr[x] = EEPROM.read(address+x);
  }
}

void setup()
{
  Serial.begin(9600);
  //Some sample writes
  //               starting address----array-----size of the array
  WriteEepromArray(SGRP_ID_EE_START   ,sgrpID   ,sizeof(sgrpID));
  WriteEepromArray(ADDR_ID_EE_START   ,addrID   ,sizeof(addrID));
  WriteEepromArray(ZPCD_ID_EE_START   ,zpcdID   ,sizeof(zpcdID));
  WriteEepromArray(GWAY_ID_EE_START   ,gwayID   ,sizeof(gwayID));
  //Use the following to load:
  LoadFromEeprom(SGRP_ID_EE_START,sgrpID,sizeof(sgrpID));
  Serial.println(sgrpID);   //Now it should be loaded

}

```

The comments I hope help....otherwise comment below with what I left out.

---
Tags: arduino-uno, memory-usage, eeprom, memory
---


# Question
Title: Is there a way to pause Program execution?
I understand that Arduino programming is procedural and not so much Object Orientated and also that the Arduino or AVR are only single core processors and any kind of "Multitasking" or "Threading" is emulated at best but I was wondering if there is a way to pause program execution in one area temporarily and give another area control? For example say we have the following class:

```
Class A{
   void Test();
   void ProgramLoop();
}

void A::Test(){
   for (int i = 0; i < 10; i++){
      //Lots of cool stuff going on here but need to give
      //Control to someone else say ProgramLoop()
      Sleep(10);
   }
}

void A::ProgramLoop(){
   Serial.println("In Program Loop");
}

```

Then in the main file:

```
A testClass;

void Setup(){
   Serial.begin(57600);
}

void Loop(){
   testClass.Test();
   testClass.ProgramLoop();
}

```

I know I could do something like:

```
void Loop(){
   if (!testClass.isBusy){
      testClass.ProgramLoop();
   }
}

```

But I am trying to find out if there is a way to control how the program execution gives control? I understand that this is more of a threading topic, thats not what I am trying to get at, I just want to know if this is possible maybe using some sort of built in function or something? Or do my programs have to "Fall Through" being ONLY Procedural?

# Answer
This article gives a great example of multitasking by using FreeRTOS.

I am pasting the sample code snippet which is pretty much self explanatory.

```
#include <Arduino_FreeRTOS.h>

// define two tasks for Blink & AnalogRead
void TaskBlink( void *pvParameters );
void TaskAnalogRead( void *pvParameters );

// the setup function runs once when you press reset or power the board
void setup() {

  // Now set up two tasks to run independently.
  xTaskCreate(
    TaskBlink
    ,  (const portCHAR *)"Blink"   // A name just for humans
    ,  128  // Stack size
    ,  NULL
    ,  2  // priority
    ,  NULL );

  xTaskCreate(
    TaskAnalogRead
    ,  (const portCHAR *) "AnalogRead"
    ,  128 // This stack size can be checked & adjusted by reading Highwater
    ,  NULL
    ,  1  // priority
    ,  NULL );

  // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
}

void loop()
{
  // Empty. Things are done in Tasks.
}

/*--------------------------------------------------*/
/*---------------------- Tasks ---------------------*/
/*--------------------------------------------------*/

void TaskBlink(void *pvParameters)  // This is a task.
{
  (void) pvParameters;

  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);

  for (;;) // A Task shall never return or exit.
  {
    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
  }
}

void TaskAnalogRead(void *pvParameters)  // This is a task.
{
  (void) pvParameters;

  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);

  for (;;)
  {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(sensorValue);
    vTaskDelay(1);  // one tick delay (15ms) in between reads for stability
  }
}

```
> 1 votes

# Answer
If you have used threading before, this library-

https://github.com/ivanseidel/ArduinoThread

makes it very easy to schedule tasks in a controlled manner.

I would put this in a comment, but I don't have enough reputation yet.
> 1 votes

---
Tags: programming, task
---


# Question
Title: Arduino SoftwareSerial - can't get data from NEO 6M-GPS module
I am using Mikael Hart's TinyGPS (v.13) library and example code to talk to my module. The LED on the GPS module is lit and flashing which I assume means it is receiving data from the GPS satellites. The module seller claims that the module has a default baud of 38400.

I'm pretty sure it's wired up correctly:

And my sketch says:

```
SoftwareSerial ss(4, 3);

```

So I read this as Orange (Rx) to pin 4 and Brown (Tx) to pin 3.

Any help appreciated

# Answer
> 2 votes
RX of the Arduino (pin 4, according to the SoftwareSerial statement) goes to the TX of the GPS. Arduino pin 3 (ss TX) goes to the GPS RX.

And you should use pins 8 & 9 instead. That would let you use AltSoftSerial, the best choice when you can't use HardwareSerial (i.e., `Serial`).

If you can't use pins 8 & 9, then NeoSWSerial is a better choice than SoftwareSerial.

And while I'm promoting NeoSWSerial, I'll mention a library I wrote, NeoGPS... It's faster and smaller than all other GPS libraries, and very configurable. It also has several diagnostic programs and a Troubleshooting section in the docs.

---
Tags: gps, tinygps
---


title: Capacitive sensor switch

text:
# Question
Title: Capacitive sensor switch
I am trying to get relays to switch on or off based on if I touch a capacitive sensor, basically a light switch. For some reason, I get two readings that are high capacitive readings when I do a printout. I am not really sure why this is happening. I tried delays in case it was reading my touch too fast but with no luck.

The hardware is basically a 1M resistor between send and receive.

```
// capactitive sensing
#include <CapacitiveSensor.h>
CapacitiveSensor   cs_7_6 = CapacitiveSensor(7,6);
// 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil
const int numReadings = 5;
int index = 0;                  // the index of the current reading
int readings[numReadings];      // the readings from the analog input
int total = 0;                  // the running total
int average = 0;
int relay = A2;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;
boolean lightState = false;
// sound sample
const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
unsigned int sample;
//other
boolean isRelaysOn = false;

// capacitive sensor
void setup() {
  cs_7_6.set_CS_AutocaL_Millis(0xFFFFFFFF);
  // turn off autocalibrate on channel 1 - just as an example
  Serial.begin(9600);
  for (int thisReading = 0; thisReading < numReadings; thisReading++)
    readings[thisReading] = 0;
  // other
  pinMode(relay, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  turnRelayOff();
  Serial.begin(9600);
}

boolean state = false;
boolean lastState = true;
boolean lightTurnedItOff = false;

void loop() {
  Serial.println(capReading());
  if(capReading() >= 3000) {
    Serial.println("threadhold reached");
    lightState = !lightState;
    controlRelay();
  }
}

boolean isOn = false;

void controlRelay() {
  if(lightState == true && isOn == false) {
    turnRelayOn();
    //delay(1000);
  }
  if(lightState == false) {
    turnRelayOff();
    // delay(1000);
  }
}

void turnRelayOn() {
  int delayAmount = 100;
  digitalWrite(relay, LOW);
  delay(delayAmount);
  digitalWrite(relay2, LOW);
  delay(delayAmount);
  digitalWrite(relay3, LOW);
  delay(delayAmount);
  digitalWrite(relay4, LOW);
  delay(delayAmount);
  digitalWrite(relay4, HIGH);
  delay(delayAmount);
  digitalWrite(relay4, LOW);
  isOn =true;
}

void turnRelayOff() {
  digitalWrite(relay, HIGH);
  digitalWrite(relay2, HIGH);
  digitalWrite(relay3, HIGH);
  digitalWrite(relay4, HIGH);
  isOn = false;
}

int capReading () {
  // get average.
  total= total - readings[index];
  readings[index] =  cs_7_6.capacitiveSensor(30);
  total= total + readings[index];
  index++;
  if (index >= numReadings)
    index = 0;
  average = total / numReadings;
  delay(100);
  return average;
}

```

The output doesn't make much sense sometimes either, here are a few samples:

> 11 16 21 22 32 61 74 threadhold reached 6191 threadhold reached 6167 threadhold reached 30 15 11 12
>
> 6 10 17 44 2144 3745 threadhold reached -475 threadhold reached -3129 22 10 12 13
>
> 15 13 7 20 23 725 2726 2735 -6373 -3197 threadhold reached 4127 2714 54 40 43 34 24 27 31

# Answer
In this line:

```
readings[index] =  cs_7_6.capacitiveSensor(30);

```

...you are assigning an "int" the value from a method of type "long".

Likely you will want to change all your types used to track the capacitance value, including the type of your "capReading" method, to "long".
> 1 votes

---
Tags: c++, switch
---


# Question
Title: Arduino with wifi shield and 5AA batteries current draw
Arduino uno with official Wifi Shield take 5 Volts. Arduino lights up as it should when powered but the WiFi shield is dead the l9 doesn't light up but works fine when arduino is connected to usb cable.

I use 5 battery holder 5x1.5V = 7.5 V ; 2000 mAH

```
50 mA - Arduino
300 mA - WiFi shield

350 mA * 5h = 1750 mAh

5xAA = 7.5V ; 2000 mAh

```

Am I missing here something? It should last in the worst case scenario 5 hours with new batteries at 2000 mAH (which I think they have more but I do not have them on me right now).

# Answer
As a general answer, yes. AA alkaline should be more around 2500~3000 mAh depending on quality. 5x AA in series would result in 7.5 Volts and 2500 mAh.

But that's only for almost fully charged batteries. AA batteries can range from 1.6V to 0.8V "dead for most purposes". As they drain, the voltage drops.

What may be happening is that you are powering the Arduino through its power jack, which goes through a diode, causing a 0.7V drop. Then it goes to the linear regulator which has a very high drop out voltage. Or even via the VIN pin, bypassing the diode. But as the battery drains, the voltage drops below the regulator ' s limit.

The Arduino microcontroller can easily work below 5V. The shield might not.
> 0 votes

# Answer
4xAA = 6.0V connected to a standard diode like 1n4001 = ~5.4V (within the specs for an AVR), connect directly to Vdd (+5V on arduino's). Unless there's a reason you need to use a 7.5V pack. Bypass the protection diode & Vreg = less wasted energy on heat/diode drops. IIRC, the WIFI/Ethernet shields can spike to 500mA or so, so that may also be causing extra drain. If your code constantly uses the WIFI radio, it will cause more current spikes as opposed to using the WIFI less in your code. Your avg current will decrease and battery life will go up. You'll save batteries by using 4 instead of 5 and not cause the 5V regulator to drop out and cause power issues by bypassing its input at Vin and connecting the 6V pack with a series diode to drop it to ~5.4V and connecting to +5V on an Arduino. It will also help with Vdrop when the WIFI has a current spike.

Also note that as any battery discharges, it's more of a slope than straight line and then dead, even for lithium packs. look at this link, good info for you to understand. **http://www.powerstream.com/AA-tests.htm**
> 0 votes

---
Tags: power, wifi, battery
---


# Question
Title: Using a phone battery as a power source possible?
**Use**
I am assuming that this is possible for any phone model's battery. I am making this vague on purpose (this isn't for a specific project). The **goal** is to have the most compact and long-lasting battery possible for my arduino projects.

**Note**
I don't care about the cost. This would be for personal use (not selling this or using it for school), so I don't care about patenting or copyright issues.

**Question**
I want to know if this even makes sense for a portable arduino power source option. I want to benefit from newer phones' long battery life, as well as their compact size.

*Also:*
Are there better alternatives to this using different batteries? (I have looked at Nick Gammon's posts over setting sleep cycles to extend battery life (http://www.gammon.com.au/power); If utilizing his methods on different batteries are better than using a phone battery please let me know...)

**If Possible...**
Does it make sense for something like a:

* LED suit (lasting 12 hours)
* Portable gaming system (lasting 8 hours) - similar to: (https://www.adafruit.com/products/2510)
*I Know this is for Raspberry Pi*
* BlueTooth Speaker (lasting 6 hours)

etc...

# Answer
> 1 votes
Sounds like a good solution.

Just note that most cellphones use Lithium batteries. Those are typically around 3.7 volt. They require some special way of charging, or they may **explode** or catch on **fire**. They also get damaged if discharged too much.

These batteries may have some protection circuitry inside them. This would be ideal in your case, as it protects against over-discharge, and accidental shorts.

An alternative would be the cells used in notebooks called 18650s. These are available with protection and without. The advantage is that you have a standard size. You can buy battery holders for them. That way you can easily exchange batteries. You can also combine cells to create higher voltages.

As for the runtime; you can make a rough calculation of it.

# Answer
> 1 votes
I've done this before, but not very practical as a bare "flat-pack" outside its case presents other "issues", the battery "may" catch fire if punctured or shorted too long. (read fire hazard when punctured) Lithium fires are like thermite, you can't put them out, tossing water on it will only make it worse.

Then there's the voltage mismatch (unless you're using a DUE). A POL boost converter is needed for best efficiency to get 5-5.2V from a 3.7V cell. And a specialized charging IC is needed so that you don't overcharge/over-rate the current charging the pack. (constant-voltage/constant-current regulator type is needed). I think Adafruit has a lithium breakout board for the 3.7V lithium cell charger, it's for their lilypad stuff i think.

---
Tags: power, battery
---


title: Arduino + WiFi 101 Gerber Files

text:
# Question
Title: Arduino + WiFi 101 Gerber Files
Is it possible to get the Gerber files for the Arduino Uno r3 and the WiFi 101? I've been teaching myself the SW side of this hobby (with much help from SE Arduino) and I'd like to better understand, or at least get some exposure to, the HW side.

Are the Arduino Uno and WiFi 101 Gerber files available to the general public or are they considered IP? I am under the impression that it is open source but I'm not sure where the OS boundary ends.

# Answer
> 2 votes
On the Arduino UNO and Wifi shield websites in the Documentation section you can download the Schematic (PDF) and PCB layout (Eagle) files. The page already says

> The Uno is open-source hardware! You can build your own board using the follwing files

With the free version of Eagle, you can open it and export to gerber file format.

---
Tags: arduino-uno, wifi, hardware, pcb-design
---


# Question
Title: Arduino uno, 2x parallax continous servos (BOE), wifi shield power draw
I am unable to properly connect those things together with batteries:

```
Arduino Uno
Parallax continuous servo
Arduino wifi shield

```

5xAA batteries are connected through power jack to arduino which I assumed would power both arduino and the wifi shield and then I have 1 9 volt battery to power 2 servo motors.

With this setup it seems like I can only get to run 1 servo at a time.

Here is a picture how it looks like: https://i.stack.imgur.com/7mGKe.jpg

I'm really desperate for any advice/guidance when it comes to powering this thing.

# Answer
> 1 votes
9V batteries can only supply very little current. So two servo's is too much.

Just use another set of multiple AA batteries for the servo's.

---
Tags: arduino-uno, power, wifi, servo
---


# Question
Title: How to implement an alternating current using only two PWM pins on STM32 Nucleo L053R8?
I am an arduino rookie and definitely not an expert in electronics, even if I do know the physics that is behind it. Before burning my object of experience, I prefer to ask my silly question to the community.

Context :

* I do use a bare stm32 based Nucleo L053R8 board which is arduino compatible.
* I want a 1 minute long loop during which I send a 1.5V@20mA impulsion during 1 second and a -1.5V@20mA impulsion 30 seconds later.

Question :

* can I simply use and wire two arduino PWM-able pins only to implement that alternating polarity low current? Or will it fail because of unsinked current?

# Answer
> 2 votes
It's quite hard to understand what you want from your question, it's quite "woolly".

However, I will note:

1. It's not possible to output a negative voltage from a normal microcontroller.
2. Getting a specific voltage (accurately) from PWM requires good filter design and a feedback system to keep the voltage within bounds.

I say it's not possible to output a negative voltage - that is *with respect to ground*. Depending on what you are feeding this voltage into you may not need to reference to ground. In this case it is possible to reference the voltage to another IO pin (steady state, output, not PWM). With it set HIGH the PWM pin's filtered voltage will be below that IO pin's voltage and thus appear, *with respect to that IO pin,* to be negative. With the IO pin LOW it will appear, *with respect to that IO pin,* to be positive.

Once you have filtered your PWM signal you will need the output voltage from it to be monitored by an analog input. That can measure the voltage and make sure that your PWM is set to the right duty cycle. Note that the required duty cycle for any one specific voltage will depend largely on the filtering and the load on the output at the time. You will most likely need some form of PID algorithm to constantly adjust the PWM duty cycle. Also remember that your measured voltage will always be *with respect to groud,* so you will need to subtract your output reference voltage (the output state of your reference IO pin - high or low) from your measured voltage to get the voltage as seen *with respect to the IO pin*.

---
Tags: pwm
---


# Question
Title: Best Actuator to Behavioural Positive/Negative Feedback on Cat
Rhetorical, yet silly question: Given an Arduino to manage, what would be the easiest way, in terms of available actuators (price/availability counts) to:

a) Apply a positive feedback to a cat, in exchange for a good action?

b) Apply a *NEGATIVE* feedback to a cat, like trying to reach forbidden places?

# Answer
> 0 votes
For the negative feedback, you could use a loud, screetching noise. I would suspect, however, that the cat would eventually get used to it and ignore it.

Depending on your cat's tastes, you could use the same hardware for positive feedback - playing, for example, a Mozart tune if that's what your cat is into.

I know, a silly answer, but what can you do with a silly question? ;-)

---
Tags: sensors
---


title: Sampling frequency

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

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

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

My code:

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

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

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

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

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

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

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

            time = millis();

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

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

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

```

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

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

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

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

---
Tags: sensors, c++, arduino-nano
---


title: Use terminal command to verify software

text:
# Question
Title: Use terminal command to verify software
I've seen that it is possible to use terminal command to verify software instead of using the IDE. Something like `arduino --verify lab.ino`. Is there a way to do so on Mac OS?

Thank you

# Answer
> 1 votes
I managed to verify code from terminal by invoking `/Applications/Arduino.app/Contents/MacOS/Arduino --verify lab.ino` BUT this command automatically starts the IDE and exits it afterwards. Even with an IDE instance open it will start a new one. This is annoying since it will switch the active workspace away, but it kinda works. See arduino manpage.

# Answer
> 0 votes
Use AVRDude, and set the `op` field to `v` for verify. E.g.:

```
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbserial-A703114N -b57600 -D -Uflash:v:/var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex:i

```

change `/dev/cu.usbserial-A703114N` to your serial port.

change `/var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex` to your hex file.

More info on avrdude at http://www.nongnu.org/avrdude/user-manual/avrdude\_4.html#Option-Descriptions

Sample output would be:

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

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

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

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

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 2
         Firmware Version: 1.16
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: verifying flash memory against /var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex:
avrdude: load data flash data from input file /var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex:
avrdude: input file /var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex contains 7902 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 3.34s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0002
         0x64 != 0x6a
avrdude: verification error; content mismatch

avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: safemode: Fuses OK (H:00, E:00, L:00)

avrdude done.  Thank you.

```

Notice the `verification error, first mismatch at byte 0x0002`

PS. you need an actual `hex` file, not an `ino` file. Different compilers and different versions of the Arduino IDE can produce slightly different hex files, for the exact same C-program.

---
Tags: mac-os, terminal
---


# Question
Title: Opening webpage using ESP8266 in Arduino
I am trying to open the webpage in ESP8266 via Arduino Mega. I have successfully opened the webpage if I use the **AT command** in the Serial Monitor

The output is perfect

```
+IPD,382:HTTP/1.1 200 OK
Server: nginx
Date: Sun, 08 May 2016 06:44:47 GMT
Content-Type: text/html
Connection: close
Vary: Accept-Encoding
X-Powered-By: PHP/5.5.26
Set-Cookie: PHPSESSID=rnsmo0b4kq07c5mi3mdsu280g4; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

S|R190|W5|O31.0|T0|A24|CLOSED

```

As you can see the output is fine. Now If I issue commands using Arduino Serial1.print() and read the output using following code:

```
 while( Serial1.available() )
 {
     inChar = Serial1.read();
     Serial.write(inChar);
     //delay(1);         //could play around with this value if buffer overflows are occuring
 } // while

```

The output **skips character randomly**

```
+IPD,386:HTTP/1.1 200 OK
Server: nginx
Date: Tue, 17 May wed-y: HP/.5.26
SetCooie:PHPESSD=7kameos5kd7aqcn4e54; pth=
Epirs: hu, 19Nov198 0852:0 GT
ach-Cotro: n-stre,no-ach, mst-evaidate,pos-chck=, pe-ceck0
raga: o-cche
F~SR19|W5O310|T90|ENDLOSD

```

I have tried different values of **delay()** but of no help. My baudrate is **9600** for both arduino Serial and ESP8266 Serial1

Can you please tell me what can be the reason. Thanks

# Answer
> 0 votes
First things first: *never* use a delay when reading from serial.

You are just blindly trying to read data and send it out to another port. That's not going to work unless you know *how much data* you need to read.

And that information is handed to you on a plate - you just need to interpret it.

You are required to read the serial data as it comes in and decide what it means, then do different things depending on that data. For instance, when you read the characters `+IPD` you know you have an IP Data response to be interpreted. Just after that comes a comma, and following that a number. That number is how many bytes you then have to read to get your data. So you keep looking and reading until you have received all the data you should be receiving.

---
Tags: arduino-mega, esp8266
---


# Question
Title: Can this Motor shield support other arduino functions?
http://www.flipkart.com/grab-em-l293d-motor-driver-arduino-shield/p/itmehvzzpzj4wyby?pid=ETYEHVZZFFHRFMFG

I want to ask whether this shield will allow me to use the free pins of arduino for other functions?

# Answer
Yes, this motor shield can allow other components to be used. You just have to make sure that the pins being used by the shield are not used by you for other tasks. Generally all shields are designed such that they do not hamper the productivity of arduino. What use would only a motor driver be? Therefore they ensure that they do not block other pins.
> 0 votes

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


# Question
Title: Program around this while loop not working as expected
```
int i=0;
while(i == 0){
  if(digitalRead(saveSwitch) == HIGH){
    Serial.print("New coordinates saved \n");
    lat1 = gps.location.lat();
    Serial.print("Latitude");
    Serial.println(lat1);

    lng1 = gps.location.lng();
    Serial.print("Longitude");
    Serial.println(lng1);
    i = 1;
  }
}

```

Why isn't leaving the while loop?

# Answer
> Why isn't leaving the while loop?

There's a good chance that the code *is* leaving the `while` loop, repeatedly. However, if the code that's shown is in (eg) the `loop()` function, `i` will be reset to 0 each time the function runs, which will cause the `while` loop to start again.

As noted in Dave X's comment, you can move `int i=0;` to a higher scope. Moving it to file scope, for example, will allow it to retain its value through repeated function calls. For example, if the code shown is in `loop()`, you could put `int i=0;` just before `void loop() {`.

Note, having generically-named variables like `i` declared at a high level is a bad idea, a blunder, a programming faux pas. An alternative is to leave its declaration within `loop()` but add the `static` keyword so that `i` is allocated only once, rather than being reallocated and reinitialized at each execution of `loop()`. For example: `static int i=0;`.
> 0 votes

# Answer
Instead of setting i=1, you could use a 'break' command to break out of the while loop. That way you don't need 'i' at all, you can just do 'while(true)'
> 0 votes

---
Tags: c++
---


title: Connector for I2C sensor

text:
# Question
Title: Connector for I2C sensor
Im about to develop some home automation. It should be possible to connect new sensors to the main computer. Thats a Arduino.

What can be used as a connector for the I2C sensors? It should be customer friendly. So something like RJ11 or USB. What can be used for that?

Is it possible to send data wirelessly from a I2C sensor?

Regards

# Answer
> 2 votes
> What can be used as a connector for the I2C sensors? It should be customer friendly. So something like RJ11 or USB. What can be used for that?

Almost anything you like. Whatever is easy to get hold of and use. You only need 4 wires, and they are all low voltage, so nothing too fancy is needed.

> Is it possible to send data wirelessly from a I2C sensor?

No. But you can connect the I2C sensor to an Arduino then use that with a wireless interface of some form to send the data wirelessly.

One thing for you to know though:

**I2C is not suitable for long distance communications. A few inches to a foot or so is about the limit. Anything longer and you will start running into communication problems. For longer distance communications you need to use a more reliable protocol.**

---
Tags: i2c, wireless
---


# Question
Title: Arduino Pro mini to CH340G Connection problem
I have worked with Arduino UNO but recently I bought a new Arduino Pro mini 5v 16M and a CH340G converter to work with. I have searched google to connect pins but I found examples that explains this way :
GND to GND
VCC to VCC
Converter RDX to Arduino Pro Mini TXO
Converter TDX to Arduino Pro Mini RXI
My problem is that my Arduino Pro Mini (328p) has pins TXD and RXD (not RXI , not TXO) or maybe I have no knowledge about TX,RX, IN and OUT.
Can someone please help me to connect these wires?

# Answer
> 0 votes
Generally, lines with names like TX, TXO, and TDX are for serial-data transmit, and lines with names like RX, RXI, and RDX are for serial-data receive.

Connect transmit on the CH340G board to receive on the Pro Mini, and vice versa.

For typical serial-converter programmers (I don't know specifically about the CH340) you need to connect CTS (Clear to Send, if the programmer has it) to the pin next to BLK on the Pro Mini, and RTS to GRN (DTR). The RTS-to-DTR (Request to Send, Data Terminal Ready) connection lets the programmer auto-reset the Pro Mini to start programming.

See yourduino.com's ProMiniPinout.png diagram.

# Answer
> 1 votes
try reversing the tx/rx lines, if the PRO Mini and serial adapter are chinese, you may want to try using your UNO as ISP programmer. See here for a hint/ex: https://www.arduino.cc/en/Tutorial/ArduinoISP

---
Tags: arduino-pro-mini, convert, ch340
---


# Question
Title: How do I use Microduino (mCookie) on Linux?
I'm interested in getting the mCookie working in Linux — specifically, in Fedora 23. The Arduino IDE (version 1.6.4) is already available. I'm very familiar with Linux, fine with C, and completely new to Arduino.

The tutorials for Windows or Mac describe installing a customized version of the IDE along with drivers. Do I *need* special drivers on Linux? On the projects' GitHub site, I found the examples and a directory called 'avr' which has promising subdirectories like "bootloaders" and "libraries", along with files `boards.txt` and `platform.txt`.

Can I download this stuff and add it to the existing "system" arduino package somehow? How, and what will I need?

# Answer
> 1 votes
First you will need the `arduino` 1.6.x package from `updates`, not the 1.0.x package from `fedora`. Then:

> You will be adding a URL to the new Additional Boards Manager URLs option: https://github.com/wasdpkj/Microduino-IDE-Support/raw/master/package\_Microduino\_index.json

source

This tutorial tells you where and how to add that URL to the preferences, as well as how to actually install the required support files.

---

As of this writing, the platform configuration supplied as part of the above won't work out of the box in Linux; you will also have to edit `~/.arduino15/packages/Microduino/hardware/avr/1.6.7/platform.txt` to:

* replace `compiler.path={runtime.tools.avr-gcc.path}/bin/` with just `compiler.path=/usr/bin/`
* on the line starting `recipe.ar.pattern=`, change `{archive_file_path}` to `{build.path}/{archive_file}`

Hopefully this will be fixed in future versions.

---

You probably also want to prevent ModemManager from probing the serial device with this udev rule, just replace the vendor and product IDs as appropriate:

```
SUBSYSTEM=="usb-serial", ATTRS{idVendor}=="xxxx", ATTRS{idProduct}=="xxxx", ENV{ID_MM_DEVICE_IGNORE}="1"

```

---
Tags: linux, fedora
---


title: Find remote ip address TCP

text:
# Question
Title: Find remote ip address TCP
Found this "Remote IP of TCP Socket" at: https://e2e.ti.com/support/wireless\_connectivity/simplelink\_wifi\_cc3000/f/851/t/380635

I am trying to log the remote ip address of a client. Using Ethernet, I have accomplished remote ip address logging. Trying to do the same with the Adafruit CC3000 library.

**Answer provided; does not respond every time with the correct "client.IP".** When it is wrong; client.IP is always "client.IP: 0.0.0.0.0" which occurs more frequently than the correct "client.IP" of my computer. Why is does this happen? Is there a solution? Answer is on the right track; need additional help, so client.IP is correct every time.

Edit: File modified is Adafruit\_CC3000\_Server.cpp Only change was to the clientIndex value. Will this cause an impact on client connecting? File is contained in "Arduino Stack Exchange.zip" linked in this post and is located in the Adafruit\_CC3000 folder of the zip. Changes are commented.

Modified files with client ip returned. https://drive.google.com/open?id=0Byo8QWKyqAT9TUt4d0FteENQS2s CC3000.zip

William

# Answer
> 1 votes
This function is not built-in so you'll have to modify the library slightly. This is one way to do it, I think:

* Navigate to the `class Adafruit_CC3000_ClientRef` in the file `Adafruit_CC3000_Server.h`. In the class definition, just before the `private` methods and attributes are defined, you will add a new public attribute as follows:

```
uint8_t ip_addr[4];  // assuming a typical IPv4 address

```

It will hold the IP address of each `ClientRef` instance as the connection is accepted.
* Go to `Adafruit_CC3000_Server::acceptNewConnections()` near the end of `Adafruit_CC3000_Server.cpp`. A few lines will be added to get the IP address from the CC3000 and store it temporarily in the appropriate `struct`:

```
static sockaddr tSocketClientAddr;  // file scope
static socklen_t addr_len;

// Accept new connections and update the connected clients.
bool Adafruit_CC3000_Server::acceptNewConnections() {
  bool newClientCreated = false;
  // For any unconnected client, see if new connections are pending and accept
  // them as a new client.
  for (int i = 0; i < MAX_SERVER_CLIENTS; ++i) {
    if (!_clients[i].connected()) {
      // Note: Because the non-blocking option was set for the listening
      // socket this call will not block and instead return SOC_IN_PROGRESS (-2)
      // if there are no pending client connections. Also, the address of the
      // connected client is not needed, so those parameters are set to NULL.
      cc3k_int_poll();
      addr_len = sizeof(tSocketClientAddr);
      int soc = accept(_listenSocket, &tSocketClientAddr, &addr_len);
      if (soc > -1) {
        _clients[i] = Adafruit_CC3000_Client(soc);
        newClientCreated = true;
      }
      // else either there were no sockets to accept or an error occured.
    }
  }
  return newClientCreated;
}

```
* You'll also edit the `getClientRef()` method in `Adafruit_CC3000_Server.cpp`:

```
Adafruit_CC3000_ClientRef Adafruit_CC3000_Server::getClientRef(int8_t clientIndex) {
  if (clientIndex != -1) {
    Adafruit_CC3000_ClientRef newClient =  Adafruit_CC3000_ClientRef(&_clients[clientIndex]);
    // at least 2 (family) + 2 (port) + 4 (ip_addr) bytes expected
    // also check if address is standard ipv4
    if ((addr_len >= 8) && (tSocketClientAddr.sa_family == AF_INET)){
       // copy address into array; in network byte order
       memcpy(newClient.ip_addr, &(tSocketClientAddr.sa_data[2]), 4);
    }
    return newClient;
  }

  // Couldn't find a client ready to read, so return a client that is not
  // connected to signal no clients are available for reading (convention
  // used by the Ethernet library).
  return Adafruit_CC3000_ClientRef(NULL);
}

```

Save all the files.
* Now the address is stored in an array for each client and can be accessed from your sketch. For example, you can access the address in your sketch like this:

In the `loop()` of the the `HttpServer` example:

```
 Adafruit_CC3000_ClientRef client = httpServer.available();
 if (client) {
   Serial.println(F("Client connected."));
   for (int i = 0; i < 3; i++){
     Serial.print(client.ip_addr[i]);
     Serial.print('.');
   }
   Serial.println(client.ip_addr[3]);
   // other code
 }

```

Completely untested. Good luck.

---
Tags: programming, wifi, library, adafruit
---


# Question
Title: DB:NO RESP Using inet.httpPOST on loop()
I'm using SIM900 module + arduino uno + gsmlib.org library.

I'd like to send a string to endpoint on my API , and it worked correctly for the first time when I using `inet.httpPOST` function in `setup()`, but... in `loop()`, when I call that function again, it doesn't work. On serial monitor I get:

```
ATT: ERROR
RIC:
ERROR
DB:STARTING NEW CONNECTION
ATT: SHUT OK
RIC:
SHUT OK
DB:SHUTTED OK
ATT: OK
RIC:
OK
DB:APN OK
ATT: OK
RIC:
OK
DB:CONNECTION OK
ATT: ERROR
RIC:
xxx.xxx.xxx.xxx

DB:ASSIGNED AN IP
status=ATTACHED

http://api.com.br/mystring

ATT: OK
RIC:
OK
DB:RECVD CMD
ATT: CONNECT OK
RIC:
OK
ATT: OK
RIC:
CONNECT OK
DB:OK TCP
ATT: >
RIC:
>
DB:>
ATT: SEND OK
RIC:
SEND OK

DB:SENT

http://api.com.br/mystring

ATT: OK
RIC:
xxx.xxx.xxx.xxx
ERROR
ALREADY CONNECT
DB:NOT CONN
ATT: OK
RIC:
ERROR

ALREADY CONNECT
DB:NOT CONN
ATT: OK
RIC:
ERROR

ALREADY CONNECT
DB:NOT CONN

```

How can I send data to my API continuously on loop() Could someone help me?

Following is my code (SOLVED):

```
#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <inetGSM.h>

InetGSM inet;
TinyGPSPlus gps;
SoftwareSerial serialGps(11, 10);

/**
    setup
*/
void setup() {
  // Serial connection.
  Serial.begin(19200);
  Serial.println(F("Starting App Arduino"));

  // Turn on GPRS
  powerUpGprs();

  // Start configuration of shield SIM900 with baudrate and  connect to internet.
  if (gsm.begin(9600)) {
    Serial.println(F("\nstatus=READY"));

  // Start configuration of shield GPS NEO-6M with baudrate.
  serialGps.begin(9600);

  // Mensure and show memory usage
  Serial.println(F("\nMemory usage"));
  Serial.print(freeRam());
}

/**
   loop
*/
 void loop() {
  serialGps.listen();
  while (serialGps.available() > 0)  {
    if (gps.encode(serialGps.read())) {
      // Get GPS position and send To API
      gsm.listen();
      // if sim900 started, connect to internet
      Serial.print(F("\r\n"));
      Serial.print(F(" CONNECT TO INTERNET \r\n"));

      // GPRS attach, put in order APN, username and password.
      if (inet.attachGPRS("zap.com.br", "zap", "zap"))
        Serial.println("status=ATTACHED");
      else Serial.println("status=ERROR");
      delay(1000);
      // Read IP address.
      gsm.SimpleWriteln("AT+CIFSR");

      Serial.print(F("\r\n\r\n"));
      Serial.print(F(" GET GEOLOCATION & SEND TO API \r\n"));
      // get geolocation
      String geo;
      geo.concat("lat=" + String(gps.location.lat(), 6));
      geo.concat("&lng=" + String(gps.location.lng(), 6));
      geo.concat("&spd=" + String(gps.speed.kmph()));
      geo.concat("&gps.uuid=1");
      // send2Api
      Serial.println(geo.c_str());
      Serial.print(F("\n"));
      gsm.SimpleWriteln("AT+CIFSR");
      inet.httpPOST("api.com.br", 80, "/geolocations", geo.c_str(), "", 100);
    }
  }
}

/**
   mensure memory usage
*/
int freeRam() {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

/**
   Power up
*/
void powerUpGprs() {
  pinMode(9, OUTPUT);
  delay(100);
  digitalWrite(9, HIGH);
  Serial.println(F("\nPower Up SIM900!"));
}

```

Thank You!!!

# Answer
> 1 votes
Like I told you before, you have 2 instances of `SoftwareSerial` active, but you're allowed to listen to only one at a time (implementation rules). So you have to alternate between calling `listen()` on each instance; any data arriving at any port while its not the active port will be discarded. `inet.httpPOST()` worked in `setup()` because you called the function before `begin()`ing `serialGps`. Calling `serialGps.begin()` immediately made `serialGps` the active port, severing communication with the modem.

* Add this line to `SIM900.h` in the library, under the public methods:

```
void listen();

```
* Add this method to `SIM900.cpp`:

```
void SIMCOM900::listen(){
   _cell.listen();
}

```
* Save the files and add `gsm.listen()` right before `gsm.SimpleWriteln("AT+CIFSR");` in `loop()`.
* Re-initialize GPRS, like you did in setup() with attachGprs(), right after gsm.listen() in loop().
* Make `serialGps.listen()` the last statement in loop() immediately after the `inet.httpPOST()` call. Use braces to enclose the body of the while loop.

Hopefully this should solve your problem.

# Answer
> -1 votes
I had similar problem. I have added gsm.begin() method at the end of the loop, and it has solved my problem!!

Seems like you can't send multiple http requests with single gsm session. Relevant parts of setup() and loop() methods are shown below:

```
void setup()
{

Serial.begin(9600);
Serial.println("GSM Shield testing.");

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

}

void loop()

{
   if(started){
      if(inet.attachGPRS("internet.wind","",""))
        Serial.println("status=ATTACHED");
      else
        Serial.println("status=ERROR");

      if(inet.httpPOST(server,port, path,parameters,msg, 50)){
          Serial.println("Data sent to server succesfully!");
      }
      else{
        Serial.println("Failed to send data to the server");
      }
 }

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

};

```

---
Tags: arduino-uno, gsm, softwareserial
---


# Question
Title: How to convert voltage to current from ACS712-20A?
I've been used the ACS712-20A to measure the current flow. Actually I used LIFA program (LabVIEW interface for Arduino).

I used this equation:

current = ((analog read)-2.5 )/ 0.1

But I am still not sure with the result.

Any suggestion?

# Answer
> 1 votes
According to the datasheet you have 100mV per ampere, and a zero offset voltage of Vcc × 0.5.

So assuming you are correctly converting the ADC reading into a floating point voltage the instantaneous current can be calculated with the formula

```
i = (Vadc - 2.5) × 10

```

Or for milliamps,

```
i = (Vadc - 2.5) × 10000

```

If you are measuring a DC current that is then all well and good. However, if you are measuring an AC current things get considerably more complex.

To work out an AC current you need to have the peak-to-peak voltage, not the instantaneous voltage. To get that you need to sample the ADC over a number of cycles and find both the maximum and minimum values. You can then subtract the minimum from the maximum to give you the peak-to-peak voltage. That can then give you the peak-to-peak current.

From that you can then calculate the RMS current.

---
Tags: arduino-mega, voltage-level, current
---


# Question
Title: Arduino Nano clone doesn't fit into breadboard. How can I work around this?
I have bought an arduino nano clone (called funduino) and upon trying to place it into my breadboard to work with it I realised that the pins do not line up with the holes on the breadboard so I simply can't use the funduino...

Does anyone have any recommendations on how I can get around this?

# Answer
> 2 votes
You might be able to use these female to female jumper wires and these headers and hook up the board and breadboard like this:

Note, the square female cable ends may not fit closer than 0.1 inches on center.

A more compact and (possibly) mechanically difficult solution may be implemented using wire-wrap sockets. You may be able to leave the sockets intact and deform the pins to match the breadboard. Or you may need to remove the pins from the plastic in order to accommodate your (different) Nano:

# Answer
> 2 votes
Because of the same issue, I use mine with a miniature breadboard:

---
Tags: arduino-nano, prototype
---


# Question
Title: Can you pass params to an arduino sketch?
I was wondering if there is a way to pass parameters to an arduino sketch at the upload step.

Edit: The reason this would be helpful is because I have a bunch of esp8266 units that need to have details about their specific location but changing variables around per upload feels tedious.

If this is not possible the other solution that I am probably going to try is to have a sketch to just flash these details to eeprom and then read it from there whenever it is needed. Also storing them in eeprom feels a bit better than as literals in these sketches.

# Answer
> 1 votes
Every ESP8266 has a unique MAC address. You could that information to distinguish between the different units.

Something like `if( mac='00:0a:95:9d:68:16' ){ ... }`

# Answer
> 0 votes
Another option, if you can afford the pins, is to install DIP switches or ground-jumpers on a few pins and set / wire a different n-bit code onto each board. Set those pins to INPUT\_PULLUP, read them at setup, and wallah! each board is unique. You can put the lookup table (binary number -\> parameter string, f/ex) in Flash so it doesn't take up scarce RAM.

---
Tags: sketch, uploading
---


title: ESP8266 as I2C client

text:
# Question
Title: ESP8266 as I2C client
I've got an ESP8266 that takes instructions from a web page and sets a series of NeoPixels to flash in different sequences.

I noticed that when the Wi-Fi got data and parsed it, my LEDs would "stutter" as the processor ignored them for a moment while processing the incoming instructions.

So I added a 2nd ESP8266. This one just handles the LEDs. So the 1st ESP gets the Wi-Fi data and parses it. It then sends an interrupt to the 2nd ESP which breaks out of the LED display loop, checks the interrupt pin for HIGH or LOW and sets the LEDS based on HIGH/LOW.

However, I would like to send more data from the Wi-Fi ESP to the LED driving ESP. e.g. Colour data, transition speed, rotation direction etc. All of these settings I can send to the ESP from a web page.

I thought I2C (the wire library) would help but all comments seem to say that the ESP8266 cannot act as a slave so I can't send to it.

So it appears I'm left with Serial comms (the interrupt is over by the time comm start because I realize Serial does not work in an interrupt).

So my questions are:

* Am I right that I2C will not work?
* If I am wrong does anyone have a working end to end example?
* If I am right is there an approved way to do ESP to ESP serial comms?

# Answer
> 1 votes
I assume that you are using the Arduino core for the ESP8266 (https://github.com/esp8266/Arduino)

> Am I right that ic2 will not work?

I am not certain, but I get the same impression as you. It seems that the Expressif SDK only supports master mode.

> If I am right is there an approved way to do ESP to ESP serial comms.

There is no "approved way", but there are many ways you can do it. A direct serial link will give you a simple pipe of data - what you put in at one end comes out the other. It's up to you to decide how you format and interpret that data.

My ICSC library may help you with that - I use it to connect an ESP8266 to an BeagleBone Black through serial: https://github.com/MajenkoLibraries/ICSC

# Answer
> 1 votes
The issue with the ESP8266 is that it is multitasking, and only 80% of the CPU time is available to developers. This manifests as an outage of 100-200us every 500ms or so, which rather complicates all sorts of software serial interfaces, such as I2C, SPI and UART. As a bus master the ESP8266 hides these issues as it is responsible for the bus clock, but as a bus slave it needs to halt data transfer for the duration of these random events.

A typical solution for this inter-CPU issue is to provide an external RAM cache to act as a mailbox, where each CPU will periodically check to see if any actions are outstanding and leave any requested data.

Has anyone explored this option for the Arduino to ESP8266 interface?

# Answer
> 0 votes
> I am not certain, but I get the same impression as you.
> It seems that the Expressif SDK only supports master mode.

Sorry no. Espressif SDK supports Slave Mode too. official the Master works with 50 kHz (CPU 80MHz), and 100 kHz in technical referenz and unofficial in my test with !1.2MHz you must switch then to the 160 MHz CPU and you must work for delays with asm ("nop") 12.5 ns at 80MHz and 6.25 ns at 160 MHz then you can toggle the pins at 80 MHz with 700 kHz and with 160 MHz with 1400 kHz. because there are instruction to the gpio ( toggle output low, "opendrain" clear output with pullup high ) it will be a netto rate of 620 kHz, and 1260 kHz.

best wishes rudi ;-)

---
Tags: i2c, esp8266
---


title: Sending binary data to HTTP server

text:
# Question
Title: Sending binary data to HTTP server
I am new to low level programming.I am trying to send binary data to the http server.At the moment i just fill up the byte array with numbers and send them to the server(eventually i want to send image file). I can see the request in the server log as `2016-05-18T23:30:26.688040+00:00 heroku[router]: at=info method=POST path="/api/users" host=myapp.herokuapp.com request_id=ed2b7852-7021-4642-a663-f9709e1aea70 fwd="99.89.114.63" dyno=web.1 connect=0ms service=2ms status=404 bytes=221`

**Questions**

1.My question is as you can see in the log, what is `bytes=221` i thought if i sent byte array of length 32 i should see 32 bytes(or around 40s).And i made the buffer of length 1024 byte array, still in the server log is `bytes=221`.Are my bytes are even being sent?

2.How would i handle the bytes received on the server side just to be sure `client.write` actually succeeded?(Just in high level...doesn't matter you can guide me in any language,Java,ruby,C,NodeJS)

Here is my code.Thank you in advance.

```
#include <ESP8266WiFi.h>
#define SSID "ssid"
#define PASS_SSID "password"
#define HOST "myapp.herokuapp.com"
WiFiClient client;

byte buffer[32];
int bufOffset = 0;
byte startByte = 0;
byte nextByte = 0;

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

void loop() {

  if (client.connect(HOST,80)) {
           Serial.begin(115200);
           Serial.println("conected to the server");
           String start_request = "";
           String end_request = "";
           start_request = start_request  + "--AaB03x" + "\n"
                                   + "Content-Disposition: form-data; name=\"picture\"; filename=\"cam.jpg\"" + "\n"
                                   + "Content-Type: image/jpeg" + "\n" + "Content-Transfer-Encoding: binary";
          end_request = end_request + "\n" + "--AaB03x--" + "\n";
          client.println("POST /api/users HTTP/1.1");
          client.println("Accept: */*");
          client.print("Content-Type: multipart/form-data; boundary=AaB03x");
          client.println(start_request);

         //Fill the buffer with values
            nextByte = startByte++;
            for(int ii = 0; ii < sizeof(buffer); ii++) {
            buffer[ii] = nextByte++;
        }

          //write it to the server
        int count = client.write(&buffer[bufOffset], sizeof(buffer));

       //end the request
       client.println(end_request);
        client.stop();
       }
      }

```

# Answer
You should forget about MIME, that is only needed if you are sending *multiple* files to the server. Your best bet is to just send these headers, then a blank line, then your data:

```
POST /api/users HTTP/1.1
Accept: */*
Content-Type: application/octet-stream
Content-Length: 123

```

On the other end, you just look at "request.body" and it should have your binary data. (Replace 123 with `sizeof(buffer)`)
> 3 votes

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


# Question
Title: Arduino shuts off and doesn't turn on after couple hours
I use a mega 2560, pir sensor and a SG90 9g Servo motor in my project. Basically while the pir outputs high, the Servo Motor rotates from 0 to 180 degrees.

Here is how everything is wired up:

**PIR sensor:**

Data: pin 24

Vcc: 5 volt

Gnd: Ground

**Servo:**

PWM pin: pin 11

Vcc: 5 volt

Ground: ground

The arduino mega has two 5 volt and ground pins, one next to the analog pins and other at tho bottom bar of pin, where pins 22 and up are. I connected the Servo to the first 5v and gnd and the pir to the second.

My power source is my nexus 5 charger(5v 1.8 or 2 A).

My code:

```
Servo myservo;

    void setup() {
      myservo.attach(11);
     pinMode(24, INPUT);
    }

    void loop() {
     if(digitalRead(24) == HIGH){
       myservo.write(0);
       delay(500);
       myservo.write(180);
       delay(500);
     }
    }

```

All of this works fine for the first ~10 hours. After that the arduino just shuts down. The power led of the arduino isn't lit up. Disconnecting the adapter and reconnecting it or pressing the reset button of the arduino doesn't work. I Have to wait for a couple of minutes with the adapter disconnected and reconnect it. After that it works fine for the next ~10 hours.

Seems like a hardware issue, but I'm not sure what exactly fails and why.

# Answer
I assume your charger is connecting to the USB port of the Mega2560.

That USB port has a *polyfuse* (actually a special type of positive-coefficient thermistor) which is normally rated at around 500mA (polyfuses are a bit woolly with their ratings since they are heat based).

If you are drawing near that limit of current the fuse will be gradually heating up. I would think that after 10 hours it may have reached its threshold temperature and thus switches the power off.

Disconnecting the power and allowing it to cool down would then make the board work again.

How can you test it? Well, next time it switches itself off try bypassing the polyfuse (tweezers would be good to do that with) to see if the power LED turns on again.
> 1 votes

# Answer
`The power led of the arduino isn't lit up.`

The power LED is implemented in hardware, basically, if it's not lit, it won't work.

**Find the problems' (power?)source**

After the 10h operation, your Arduino isn't on anymore.

Does the power supply still have 5V available at that point? Or does your Arduino's chips get hot or short-circuit the supply?

**Exclude as much variables as possible**

You don't know what the problem is, it could be:

* The supply
* The Arduino
* The Servo
* The PIR

Try another supply (preferably through the barrel jack, since it's regulated) (The supply may have some "protection" to avoid it being on too long).

Try another Arduino (unlikely?).

Try no servo & pir connected. (They may draw too much current, so the Arduino shuts down or create electrical noise.)
> 0 votes

# Answer
I'm just going to hazard a guess: Your 5v line isn't staying at 5v because of the servo. They draw massive amounts of power quickly, and can wreck a lot of havoc. Many times electronics "kinda" work after voltage drops, but will lock up or glitch eventually. (To get confirmation that this is the problem, monitor your 5v power with an oscilloscope. Set a trigger at 4.5v and try to capture the voltage drops.)

If that is the problem, you need better isolation on your digital power (running the arduino) and your analog power (running the servo.) Two ideas to try (you may need both):

1) Get a big cap (say 100 uF or more), then put it across your power to the arduino. If it's big enough, it will prevent your 5v from sagging. It may be expensive to get a big enough cap.

2) Instead of connecting your servo directly to 5v, put a small resistor (say 10 ohm) between them. Now when he tries to suck all the power, it will get resistance, which will limit the current. The bigger the resistor the better the isolation, but too big will prevent your servo from working. (And may heat up your resistor).
> 0 votes

---
Tags: arduino-mega, power, servo
---


title: Inherent delay running EEPROM.read()

text:
# Question
Title: Inherent delay running EEPROM.read()
I'm using EEPROM to store long term data for use in sketches (thanks to DarthRubik for the guidance). I store stuff like a location ("Garden") and a device name ("Greenhouse Monitor 02") plus whatever else I'd need to store to help filter through data.

When this information is stored in the sketch itself it is recalled quickly and accurately, is passed via wifi to my PHP, that then posts the data to the relevant fields in my AWS db. Piece o' cake! When I store it in the EEPROM, the extra time required to find it in EEPROM, pull it through the sketch, and then push it through to the db corrupts the data sourced from EEPROM and posts a jumbled mess of characters...if it even makes it to the db at all.

My question is actually simple (I think):
Is it possible to "stage" strings from EEPROM in flash or SRAM vs. pulling cold from EEPROM?

I think PROGMEM plays a role here and I'm looking at examples oh how other sketched employ PROGMEM to better understand how to use it.

I am withholding the code for now because I want to try to implement concepts people may describe before I am just shown the solution...although that would be easier. If I can't figure it out I'll post the code for more direct answers.

# Answer
> When I store it in the EEPROM, the extra time required to find it in EEPROM, pull it through the sketch, and then push it through to the db corrupts the data sourced from EEPROM and posts a jumbled mess of characters...if it even makes it to the db at all.

Are you certain of that? It is incredibly unlikely that mere time will corrupt characters and data as they are read and sent - especially the minuscule amounts of time we are talking here.

> Is it possible to "stage" strings from EEPROM in flash or SRAM vs. pulling cold from EEPROM?

Yes, and you are already doing so, since you can't send direct from EEPROM to WiFi - you have to go via SRAM. You read from EEPROM into SRAM then send from SRAM through WiFi. You just won't be doing it an entire string at once.

> I think PROGMEM plays a role here and I'm looking at examples oh how other sketched employ PROGMEM to better understand how to use it.

No, it doesn't. PROGMEM is for storing strings and other data within your sketch. It has nothing at all to do with EEPROM.

> I am withholding the code for now because I want to try to implement concepts people may describe before I am just shown the solution...although that would be easier. If I can't figure it out I'll post the code for more direct answers.

Without seeing your code no one is really going to be able to help you. I suspect (although I am stabbing wildly in the dark) that your EEPROM reading/writing code is completely wrong and you aren't actually storing the data you expect in the EEPROM, nor reading it back properly. Unless we see your code we can't know what is going on, and so we don't have a cat's hope in hell of diagnosing your problem.
> 3 votes

---
Tags: wifi, eeprom, datalogging, progmem, sram
---


# Question
Title: Arduino IDE unable to see serial connection on OS X El Capitan
For some reason the Arduino IDE is unable to see my Arduino Uno even though it is connected. I have reinstalled the Arduino software, but no luck come of it. I connected the Arduino to my friends mac, who's could see it.. I am very confused and greatly appreciate any help.

Thanks, Shaun

# Answer
> 0 votes
I ran into a similar problem years ago on an ATMega128 (before Arduino) and you just have to be aware of alternative functions for the port. In this case `PD0` is Hardware Serial `RX` which is a receive pin.

Here's some relatively older code based around the same idea:

> Yes, you can use the RX/TX pins as regular IO. Just don't call the Serial.begin() in your code, and make sure you call a pinMode() for them.

from: http://www.societyofrobots.com/robotforum/index.php?PHPSESSID=b928292f91c78b57b5683484af0f635e&topic=12396.msg93239#msg93239

Another interesting post, fourth post: http://www.nerdkits.com/forum/thread/536/ where they disable the serial functionality once the code begins, downside (a above) you will lose serial comms, so it depends on how much you need them.

```
UCSR0B = 0;

```

I'm not sure how successful that would be in today's arduino, I know a lot (if not all) of the prior functionality is maintained, but I haven't used them in a long while.

The pin should become active again as the bootloader will automatically reenable it upon reset (although I haven't personally tested it). It will just make debugging that little bit harder if you need to.

As I mentioned in my comment, if you have another pin available to you, use that instead.

# Answer
> -1 votes
In case someone else has this problem..

Turns out, **you can't be connect to pin D0 whilst using serial.**

---
Tags: arduino-uno, serial, arduino-ide
---


# Question
Title: Can't store time over 9 hours and 10 minutes
I am making a clock on my Arduino Uno using the time library http://playground.arduino.cc/Code/Time

I let the user set a time. Which is then converted to seconds and used in the

```
setTime(s);

```

function. When the value is over 9:10h, the seconds evaluate to 4 294 941 360 seconds (= 1 193 039.27 hours)

A code snippet:

```
void timeChange() {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Change time");
  lcd.setCursor(0, 1);
  lcd.print("00:00");
  int hoursSet    = 0; //Stores the hours added.
  int minutesSet  = 0; //Stores the minutes added.
  String printTime;
  bool timeComplete = false;
  while (!timeComplete) {
    int buttonVal = analogRead(A0);
    if (buttonVal >= 490 && buttonVal <= 520) { //Indicates button 3 is pressed. It's function is to add one hour to the time.
      hoursSet = (hoursSet + 1) % 24; //Adds one hour to the hours.
      delay(100);
    } else if (buttonVal >= 5 && buttonVal <= 10) { //Indicates button 4 is pressed. It's function si to add 5 minutes to the time.
      minutesSet = (minutesSet + 5) % 60; //Adds minutes to the minutes.
      delay(100);
    }

    lcd.setCursor(0,1);
    String strHr = String(hoursSet);
    String strMn = String(minutesSet);
    if(strHr.length() == 2){
      lcd.print(hoursSet);
    } else if(strHr.length() == 1) {
      lcd.print("0");
      lcd.setCursor(1, 1);
      lcd.print(hoursSet);
    }

    lcd.setCursor(2,1);
    lcd.print(":");
    lcd.setCursor(3,1);
    if(strMn.length() == 2){
      lcd.print(minutesSet);
    } else if(strMn.length() == 1) {
      lcd.print("0");
      lcd.setCursor(4, 1);
      lcd.print(minutesSet);
    }
    delay(100);

    if (buttonVal >= 990 && buttonVal <= 1010) { //if button 2 is pressed again, the timecomeplete is set to true, and the script continues.
      timeIsSet = true;
      timeComplete = true;
    }
  }
  lcd.clear(); //Clear the screen
  lcd.setCursor(0, 0);
  lcd.print("The time"); //Print text, move cursor and print the time
  lcd.setCursor(0, 1);
  String strHr = String(hoursSet);
  String strMn = String(minutesSet);
  if(strHr.length() == 2){
    lcd.print(hoursSet);
  } else if(strHr.length() == 1) {
    lcd.print("0");
    lcd.setCursor(1, 1);
    lcd.print(hoursSet);
  }
  lcd.setCursor(2,1);
  lcd.print(":");
  lcd.setCursor(3,1);
  if(strMn.length() == 2){
    lcd.print(minutesSet);
  } else if(strMn.length() == 1) {
    lcd.print("0");
    lcd.setCursor(4, 1);
    lcd.print(minutesSet);
  }
  lcd.print(" is saved!");
  setTime((hoursSet * 3600) + (minutesSet * 60));
  timeIsSet = true;
  delay(5000); //Wait five, seconds then proceed

```

}

Added this to the code:

```
      Serial.print("hours ");
  Serial.println(hoursSet);
  Serial.print("hours in s ");
  Serial.println(hoursSet * 3600);
  Serial.print("minutes ");
  Serial.println(minutesSet);
  Serial.print("minutes in s ");
  Serial.println(minutesSet * 60);
  Serial.print("Combined:  ");
  Serial.println( (hoursSet * 3600) + (minutesSet * 60) );

```

When I input 5:15 it results in:

> hours 5 hours in s 18000 minutes 15 minutes in s 900 Combined: 18900

When I input 9:15 it results in:

> hours 9 hours in s 32400 minutes 15 minutes in s 900 Combined: -32236

So, it looks like the library only holds an Int. But that seems odd, as the function expects seconds.

# Answer
Here's a hint: 32767 seconds is 9 hours, 6 minutes and 7 seconds.

What is the largest value that an `int` can hold?

---

EDIT: I can't add comments on this computer (old browser), so I have to respond to your question here. `time_t` is an unsigned 32-bit value, but all of your input values are signed 16-bit values. When you take a product like 3600\*10, you get a bit pattern of `1000110010100000`, which is 36000 when interpreted as an unsigned value, but is -29536 when interpreted as a signed value.

When assigned to a `time_t`, the value is sign-extended to 32 bits, which makes it `11111111111111111000110010100000`, which is 4294937760 when interpreted as an unsigned value.

If you want to write a statement like

```
time_t x = (hoursSet * 3600) + (minutesSet * 60);

```

you need to type-cast your input arguments to the correct type first:

```
time_t x = ((time_t)hoursSet * 3600) + ((time_t)minutesSet * 60);

```
> 4 votes

# Answer
Changing this:

```
  time_t x = (hoursSet * 3600) + (minutesSet * 60);

```

To this:

```
  time_t x = ((unsigned long)hoursSet * 3600) + (minutesSet * 60);

```

Has solved the problem
> 0 votes

---
Tags: time
---


# Question
Title: Range of Offset Value in pH sensor module?
In finding the pH value of a liquid/Soil, what is the range of Offset voltage value that I can use in my code?

Using / calibrating pH sensor module

I considered the above link as a reference. But I didn't come to know the range of Offset Value...

Here is the logic below to find the value of pH right...

```
avgValue = 0;
for (int i=2;i<8;i++)       // take the average value of 6 center sample
avgValue+=buf[i];

float phValue = (float)avgValue*5.0/1024/6; // convert the analog into millivolt
phValue=3.5*phValue+Offset;

```

What is the range of Offset value can I use in the above/my code?

Thanks in Advance

# Answer
When converting real world sensor measurements into usable data there are several issues to consider:

1. Noise from any number of sources such as (unavoidable?) long cables and power supplies to name two. Consider using exponential averaging to minimize the effects of noise. If the noise if predictable consider sampling only when the noise is absent.
2. Slope of the data is important when converting to known scales. For example the slop of the resistance of a thermistor verses heat may not have the same slope as the temperature in Celsius verses heat. Simply multiply by the appropriate constant to correct for slope error.
3. After you correct for slope the values may still not be correct. When all values are equally less or more then the expected values an offset is required. Simply add or subtract the appropriate constant to correct for offset error.
4. Linearity is often corrected using lookup tables. Linearity is a measure of how closely the sensor tracks the physical value being measured. For example, after slope and offset corrections, a thermistor measurement may appeared curved when compared to the actual temperature in Celsius. For this final correction the sensor measured value is used to index into a lookup table which returns a correction value. Interpolation is used to control the size of the lookup table when space is a consideration.
> 1 votes

---
Tags: arduino-uno, sensors
---


title: IO Control and Configuration

text:
# Question
Title: IO Control and Configuration
I am using Eclipse to program a ATMega2560 and would like to stay away from the Arduino library, While looking through AVR Examples I have seen the syntax

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

PORTD.0 = 1

or

PORTD.DIR = 1;

```

instead of

```
PORTD = 0b11111111;

```

To define and control the Inputs/Outputs when I try to use this syntax I get compiler errors:

```
error: request for member 'DIR' in '*34u', which is of non-class type 'volatile uint8_t {aka volatile unsigned char}'

```

I am sure that I am simply missing a include file or something but I can't figure out what I am doing wrong.

# Answer
> 0 votes
What you're doing wrong is that you're using the wrong compiler. That syntax is for CodeVision or mikroC, but the Arduino IDE uses GCC. Which follows global standards rather than making syntax up.

---
Tags: arduino-mega, avr
---


# Question
Title: How to write IF/Else using a threshold range of values
basically I am trying to write an IF/ELSE statement that triggers a light when a pressure sensor is between two values.

In other words, I want the light to respond ONLY if the analog read is between 400 and 600, as opposed to, say, only being above 400.

Here is the code, any suggestions?

```
int sensor=0;
int threshold=200;

void setup (){
  pinMode(2, OUTPUT);
  digitalWrite(2, LOW);
  Serial.begin(9600);
}

void loop() {
  sensor=analogRead(0);
  Serial.println(sensor);
  if (sensor > threshold) {
    digitalWrite(2, HIGH);
  }
  else {
    digitalWrite(2, LOW);
  }
}

```

# Answer
> 1 votes
To get the light to turn on only when the sensor reading is between two numbers, you should test if the reading is between the two numbers, and if it is, turn on the light.

To test if a value is between two numbers, you could use the `&&` AND operator to see if both conditions are met. For example:

```
if (sensor > loLimit && sensor < hiLimit) {
    digitalWrite(2, HIGH);
} else {
    digitalWrite(2, LOW);
}

```

Here's a shorter way to write that:

```
digitalWrite(2, (sensor > loLimit && sensor < hiLimit));

```

In this form, the expression evaluates to 1, or HIGH, if it is true, and to 0, or LOW, if it is false.

Another approach is to test if `abs(sensor-midLimit) < halfGap`, where `midLimit` is `(loLimit+hiLimit)/2` and `halfGap` is `(hiLimit-loLimit)/2`. Turn on the light if `abs(sensor-midLimit) < halfGap`, else turn it off.

---
Tags: c++
---


# Question
Title: Question about number of sensors for Arduino Mega
What is a good max number of sensors for an Arduino Mega? Since it has like -- 2? -- ground connections, is it better to keep the number of sensors to a minimum amount?

# Answer
It depends on what you want the Arduino to do with them. There is no (not much) penalty for having many sensors connected. Where it begins to matter is when you need to read at rates which, collectively, tax the speed of the processor to meet the total demand. Your project specs will really determine how many sensors make sense. The other place that sensor count might matter is if your project is to be battery powered, and the sensors draw some amount of current even when they're not being used. In a battery powered project, you'll want to be able to power-down everything that isn't being used at a given time, to maximize the system's overall run-time on battery.

The Mega, and I'm assuming you mean Mega 2560, has 50-some odd I/O pins available, so you have a lot of potential connectivity, and I think it's safe to say, the designers intended for them to be used.
> 0 votes

---
Tags: arduino-mega, sensors, arduino-ide
---


# Question
Title: Can you send binary data to arduino AtMega328p?
I was wondering if its possible to send binary data to an Atmega328p. I don't want to send Arduino code or C code just binary. Is it possible to programme the ATmega328p using binary and how?

# Answer
> 2 votes
The serial port is binary data. Because we humans can read text data easier than binary data we mostly send text. This way we only use a very small amount of the possible band with.
The serial monitor translates your input to binary and the binary input of the arduino to text. If you write a program that uses the serialport directly you can communicate in binary without a prolem.

# Answer
> 0 votes
When you upload your sketch using the IDE, it has been converted from C++ into "binary". So yes, it is possible. In fact that is the only way it is done.

> I don't want to send Arduino code or C code just binary.

The job of the compiler is to convert your C code into binary, and that happens automatically.

You an also use `avrdude` to upload a xxx.hex file (a file containing pure machine code).

---
Tags: arduino-uno, atmega328
---


# Question
Title: GPS timestamping of digitized voltages from geophones
I wonder if anyone has written a code for GPS time stamping of voltages from seismic geophone (or any other sensors) digitized by internal or better external ADC connected to Arduino? Since the accuracy of at least 1 millisecond is required I believe using 1 PPS signal of the GPS is the only solution.

# Answer
To tackle the time resolution and accuracy issue you could:

1. Attach the 1PPS signal to an interrupt pin
2. In the interrupt routine record the `millis()` value at the time the 1PPS signal is activated
3. In the main loop do a non-blocking read of the GPS data to find and build up the time string as it is sent from the GPS (shortly after the 1PPS is triggered).

You now know what the `millis()` count was the last time a 1PPS pulse arrived, and you know the current time to within a second. The 1PPS pulse will be at `HH:MM:SS.000` (or as near as damnit) so if you subtract the current `millis()` from your recorded 1PPS `millis()` value it gives you the number of milliseconds since the 1PPS pulse. Add that to the current time, and you have 1ms accuracy in the time: `HH:MM:SS.iii`.
> 1 votes

# Answer
I doubt anyone has written software for your exact situation but you should be able to cobble something together if we break down the problem.

1. You want to read a value from an Analog port (or external ADC)
2. You want to read the time from a GPS.
3. You want to write these two readings to 'somewhere'.

Looking at the Arduino IDE tutorials there are some Analog ones that would be relevant. But the only line you need is `int sensorValue = analogRead(analogInPin);` which reads a value between 0 and 1024 which relates to the output range of your sensor.

Now you want to read from a GPS, looking at the Software Serial Library Examples there is an example of how to setup a second serial port to read the GPS data. The GPS data will arrive once every 2 seconds. The PPS signal will arrive once every 1 second. So I'm not sure how you are going to use this to get millisecond accuracy. To get millisecond accuracy I would use the GPS data to correct a Real Time Clock connected over either the I2C or SPI bus. There are lots of example programs on reading from an RTC over these busses.

Write them to somewhere, well initially I would write them to the hardware serial port, back to you PC via USB, but then you might want to start looking at writing them to a SD card or via WIFI or GSM to a cloud storage solution.

Here are a list of the examples I looked at:

https://www.arduino.cc/en/Tutorial/AnalogInOutSerial# https://www.arduino.cc/en/Tutorial/SoftwareSerialExample# https://www.arduino.cc/en/Tutorial/Datalogger

Hope that helps
> 0 votes

---
Tags: gps
---