# Question
Title: Capacitive "keys" press event registration issues
Seeing as this is my first post I would like to thank everyone ahead who take their time to delve into my whimsical code, whoever you may be, be merciful ;)

For one of my uni projects, I would like to make a physical interface that can be operated via touch "keys" that rely on the human capacitance effect. I have relentlessly researched it (as much as feasible in my time as a student for this project) and even created a working prototype with 4 unique keys.

As you will see in my code below, I am using the capacitiveSensor.h library, which I could unfortunately not find much documentation about other than a few videos and tutorials that build upon it.

I tried deciphering the workings of it by looking at its code to see if I can manipulate it for my own biddings but quickly realized it is beyond my skill to understand.

The problem I am facing right now is that while the touch keys work, they trigger each other because of the capacitance build up when one of the keys is being pressed or when the hand is close to other keys while pressing a key.

Essentially, I am looking for an algorithm that will reduce processing time & effort for the Arduino as the one I have implemented below slows it down way too much to be of any use for my project.

Sorry for the long post, here is my current code:

```
#include < CapacitiveSensor.h >
#include < pitches.h >

CapacitiveSensor cs_4_2 = CapacitiveSensor(4, 2); // 10M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
CapacitiveSensor cs_4_3 = CapacitiveSensor(4, 3); // 10M resistor between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil
CapacitiveSensor cs_4_5 = CapacitiveSensor(4, 5); // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor cs_4_6 = CapacitiveSensor(4, 6);

# define COMMON_PIN 4 // send pin
# define CAP_THRESHOLD 450 // overall threshold
# define NUM_OF_KEYS 4 // Number of keys that are on the keyboard
# define noteDur 50 // duration of note
# define BUZZER_PIN 12 // The output pin for the piezo buzzer
# define noMulti 0.9 // incremental factor per key
# define overkill 5 // register no touch after this cap factor is exceeded

// This macro creates a capacitance "key" sensor object for each key on the piano keyboard:
# define CS(Y) CapacitiveSensor(COMMON_PIN, Y)

CapacitiveSensor keys[] = {
CS(2), CS(3), CS(5), CS(6)
};

void setup() {

Serial.begin(57600);

// Turn off autocalibrate on all channels:
for (int i = 0; i < NUM_OF_KEYS; ++i) {
keys[i].set_CS_AutocaL_Millis(0xFFFFFFFF);
}

}

void loop() {

// needs to be repeated here to work in THIS scope
long sensor01 = cs_4_2.capacitiveSensor(30); // pin 2 is cap sensor, pin 4 is "common send"
long sensor02 = cs_4_3.capacitiveSensor(30);
long sensor03 = cs_4_5.capacitiveSensor(30);
long sensor04 = cs_4_6.capacitiveSensor(30);

Serial.println("");
Serial.print("key1");
Serial.print("\t");
Serial.print("key2");
Serial.print("\t");
Serial.print("key3");
Serial.print("\t");
Serial.print("key4");
Serial.println("");
Serial.print(keys[0].capacitiveSensor(CAP_THRESHOLD));
Serial.print("\t");
Serial.print(keys[1].capacitiveSensor(CAP_THRESHOLD));
Serial.print("\t");
Serial.print(keys[2].capacitiveSensor(CAP_THRESHOLD));
Serial.print("\t");
Serial.print(keys[3].capacitiveSensor(CAP_THRESHOLD));

// algo for key 1
if (keys[0].capacitiveSensor(CAP_THRESHOLD) > CAP_THRESHOLD &&
keys[1].capacitiveSensor(CAP_THRESHOLD) < keys[0].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[2].capacitiveSensor(CAP_THRESHOLD) < keys[0].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[3].capacitiveSensor(CAP_THRESHOLD) < keys[0].capacitiveSensor(CAP_THRESHOLD) * noMulti) {
Serial.print("key pressed on sense1");
Serial.println("");
tone(BUZZER_PIN, NOTE_A7, noteDur);

}

// algo for key 2
else if (keys[1].capacitiveSensor(CAP_THRESHOLD) > CAP_THRESHOLD &&
keys[0].capacitiveSensor(CAP_THRESHOLD) < keys[1].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[2].capacitiveSensor(CAP_THRESHOLD) < keys[1].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[3].capacitiveSensor(CAP_THRESHOLD) < keys[1].capacitiveSensor(CAP_THRESHOLD) * noMulti) {
Serial.print("key pressed on sense2");
Serial.println("");
tone(BUZZER_PIN, NOTE_B7, noteDur);

}
// algo for key 3
else if (keys[2].capacitiveSensor(CAP_THRESHOLD) > CAP_THRESHOLD &&
keys[1].capacitiveSensor(CAP_THRESHOLD) < keys[2].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[0].capacitiveSensor(CAP_THRESHOLD) < keys[2].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[3].capacitiveSensor(CAP_THRESHOLD) < keys[2].capacitiveSensor(CAP_THRESHOLD) * noMulti) {
Serial.print("key pressed on sense3");
Serial.println("");
tone(BUZZER_PIN, NOTE_C7, noteDur);

}
// algo for key 4
else if (keys[3].capacitiveSensor(CAP_THRESHOLD) > CAP_THRESHOLD &&
keys[1].capacitiveSensor(CAP_THRESHOLD) < keys[3].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[2].capacitiveSensor(CAP_THRESHOLD) < keys[3].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[0].capacitiveSensor(CAP_THRESHOLD) < keys[3].capacitiveSensor(CAP_THRESHOLD) * noMulti) {
Serial.print("key pressed on sense4");
Serial.println("");
tone(BUZZER_PIN, NOTE_D7, noteDur);

}

}

```

# Answer
> 1 votes
You might experiment with the code shown at the end of this answer. It is fairly responsive, in the sense that readings are taken reasonably quickly (several per millisecond), which should leave a good deal of time available for other processing.

In this code, all of the pins that are on the same port are sampled at the same time. For example, pins 2,3,5,6 on an Uno are all on port D so their four pads can be tested all at the same time. But if the pins list includes pins from `k` different ports, sampling will take up to `k` times as long as when sampling from a single port. For example, on a Mega2560, pins 2, 3, 5 are on port E and pin 6 is on port H, so this code's execution time when processing buttons on pins 2,3,5,6 is about twice as long on a Mega as on an Uno.

\[*Edit:* For Uno port-to-pin assignments, see an Arduino Uno Pinout Diagram. On such diagrams, labels like `ADC0 PCINT8 14 A0 23 PC0` show the Arduino digital pin reference number (eg, 14), analog pin label (eg, A0), its various functional designations (ADC0, PCINT8, and PC0, meaning analog input pin 0, pin-change-interrupt pin 8, and bit 0 of port C), and the physical pin number (23). For hardware level information about Uno ports, see Atmel's document #8271. Use Google images similarly to find other-model diagrams, eg Mega 2560 pinouts.\]

You may need to tune some of the constants to fit your own circuitry or switch-function requirements. I'm not able to tell from the question what resistor sizes you are using or what your circuit is. For preliminary tuning, enable the `secondly()` function and disable `testChange()` functions. If your circuit is similar to that shown below but uses higher resistances, you may need to increase `nsamp`, `IsHighCount`, and `preSamp`.

Here is the general idea of circuitry I used:

In the above, "Drive" refers to pin 4. "Sense 1" ... "Sense j" (with j=4) refer to pins 2, 3, 5, 6, as in your example code. The capacitors illustrated are tape-covered aluminum-foil pads, eg 22 x 44 mm and the resistors are 440 KΩ each (two 220 KΩ's in series). Those resistor values produce an RC time constant of a few dozen microseconds when a button isn't touched, and a couple hundred microseconds when a button is touched.

Here is some example output:

```
2 on  199 7587
2 off 179 7702
1 on  196 10798
1 off 154 10802
1 on  253 10900
1 off 180 10924
2 on  219 18097
2 off 166 18134
3 on  214 21105
3 off 155 21385
3 on  227 24312
3 off 72 24535

```

In that output, the first column is switch number. The last column is the current reading of `millis()` at time of printing. The third column is total counts accrued from 12 sets of contact readings. The simple-minded on/off algorithm used in the `testChangeA()` function is that a contact is on when its 12-sample count exceeds 180. One could also add calibrations, adaptive threshholds, debouncing, etc to the code.

Here is the code (which was run on an Uno, but I tested most of it on a Mega also, and it should run ok on other Arduinos as well since the direct port accesses are computed via functions like `portInputRegister`, `portModeRegister`, etc in `countPins7()` setup before it calls `portSampler7()` to run the test.

```
/* Via serial port, tell the current time when capacitive readings on
 various digital pins show a button has been "pressed" or "released".
 JW - 25 Dec 2015

 See eg refs at http://playground.arduino.cc/Code/CapacitiveSensor and
 http://www.arduino.cc/en/Reference/PortManipulation and
 http://garretlab.web.fc2.com/en/arduino/inside/arduino/Arduino.h/digitalPinToPort.html

 */
#include <Streaming.h>      // provides nicer syntax for printing
// Set upper size on pins count per sample; #samples saved per reading;
//  #samples tossed; threshold for Button-is-on; #samples per set; etc
enum { nbits=8, nsamp=40, preSamp=1, SettleDown=90 };
enum { IsHighCount=15, SampleSets=12, IsHighTotal=IsHighCount*SampleSets };
void setup() {
  Serial.begin(115200);     // initialize serial port
}
//-----------------------------------------------------------
// portSampler7(): Sample a port nsamp times and return the results.
// Inputs:  drivePin, portCode, pinsMask, preWait.  Constant nsamp.
// Output:  array of nsamp samples.
// This version takes 8 cycles per sample, and as inputs switch
// on after about one RC time constant, on a 16MHz Arduino an
// m-count result (that is, a bit clear in m of the nsamp readings)
// suggests RC is about m/2 + preWait/2 us.
void portSampler7(uint8_t drivePin, uint8_t portCode, uint8_t pinsMask,
          uint8_t preWait, uint8_t *samples) {
  volatile uint8_t *pin, *port, *ddr;
  // pin, port, and ddr are pointers to registers with volatile
  // contents: input port, output port, direction register.
  pinMode(drivePin, OUTPUT);
  digitalWrite(drivePin,LOW);
  pin =  portInputRegister (portCode); // eg points to PIND
  port = portOutputRegister(portCode); // eg points to PORTD
  ddr =  portModeRegister  (portCode); // eg points to DDRD
  *port &= ~pinsMask;        // Turn off our pins
  *ddr  |= pinsMask;         // Make our pins be outputs, briefly
  for (uint8_t i=0; i<SettleDown; ++i) *pin;  // Delay to let pins settle low
  *ddr &= ~pinsMask;         // Make our pins be high-impedance inputs
  digitalWrite(drivePin,HIGH); // Turn on driver pin
  for (uint8_t i=0; i<preWait; ++i) *pin;  // Baseline Delay
  for (uint8_t i=0; i<nsamp; ++i) // Take and store nsamp readings
    samples[i] = *pin;
}
//-----------------------------------------------------------
/* Sample a pins-list and report results in counts array.  Eg,
   pinsList can look like "2,3,4,5,6" or "2,4,5,12,9,23,17,7"
   etc.  A list may contain digits and commas only.  Pins may be
   listed in any desired order.  Elements of counts will be in
   list-order.  Eg, in the "2,3,4,5,6" example, counts[0] is the
   count for pin 2, counts[1] is the count for pin 3, etc.  A
   larger count implies longer rise time and larger capacitance.
   Use preWait to suppress baseline-level counts (and to reduce
   sample array size) by waiting a while before beginning to sample.
 */
uint8_t countPins7(uint8_t drivePin, char *pinsList,
           uint8_t *counts, uint8_t preWait) {
  uint8_t pnum, pomask, pocode, potem, i, j, mul;
  uint8_t sampl[nsamp], pim[nbits], pat[nbits], bout=0, nat=0, pcon;
  char *c, cc;
  int usedPorts=0;  // To track which ports are done
  for (c=pinsList, counts[0]=pcon=0; *c; ++c) // Zero the counts array
    if (*c < '0' || *c > '9') counts[++pcon] = 0;
  // In each pass, group bit numbers by port and sample the port
  while (nat<pcon) { // Each loop pass sets one bit in usedPorts
    pnum = pocode = pomask = bout = pcon = 0;
    c = pinsList;
    while ((cc=*c++)) {  // Loop until c is at end of string
      if ('0' <= cc && '9' >= cc) {
    pnum = 10*pnum + cc - '0';
    if ( *c < '0' || *c > '9') { // See if pin # is complete
      potem = digitalPinToPort(pnum);  // Get port #, in range 1 to 12
      if (!(usedPorts & (1<<potem))) { // Is potem's port already done?
        if (!pocode)           // If pocode not set, set it
          pocode = digitalPinToPort(pnum);
        if (pocode == potem) {  // Process pin if it's in current port
          pomask |= (pim[bout] = digitalPinToBitMask(pnum));
          pat[bout++] = pcon; // Save location of pin's bit in results
        }
      }
      pnum = 0; // Clear # accumulator
      ++pcon;   // Count pin numbers
    }
      }
    }
    // Now pomask is a mask for all bits to be read from port pocode
    // and we are ready to sample current port
    portSampler7(drivePin, pocode, pomask, preWait, sampl);
    usedPorts |= 1<<pocode;       // Mark the port finished
    // Count up # of zeroes (ie rise times) in sampled bits
    for (j=0; j<bout; ++j) {
      int count;
      uint8_t m=pim[j];
      for (count=i=0; i<nsamp; ++i)
    count += sampl[i] & m;
      counts[pat[j]] += nsamp - count/m;
    }
    nat += bout;        // Count number of pins done so far
  }
  return pcon;          // Return # of pins processed
}
//-----------------------------------------------------------
// secondly() will report counts at start-of-second
void secondly() {
  uint8_t counts[nbits], j, nc;
  if (millis()%1000) return;    // Wait for start-of-second
  nc = countPins7(4, "2,3,5,6", counts, preSamp);
  Serial << "Counts: ";
  for (j=0; j<nc; ++j)      // Marshal output
      Serial << counts[j] << " ";
  Serial << " t=" << millis() << endl;
  while ((millis()%1000)==0) {}; // Await end-of-millisecond
}
//-----------------------------------------------------------
uint8_t ostate[nbits] = {0};
void testChange1() {
  uint8_t counts[nbits], j, nc, s;
  nc = countPins7(4, "2,3,5,6", counts, preSamp);
  for (j=0; j<nc; ++j) {
    s = counts[j] > IsHighCount;
    if (s ^ ostate[j]) {
      Serial << j << (s? " on  " : " off ") << counts[j] << " " << millis() << endl;
      ostate[j] = s;
    }
  }
}
//-----------------------------------------------------------
void testChangeA() {
  uint8_t counts[nbits], j, k, nc, s;
  int sumcount[nbits]={0};
  for (k=0; k<SampleSets; ++k) {
    nc = countPins7(4, "2,3,5,6", counts, preSamp);
    for (j=0; j<nc; ++j) {
      sumcount[j] += counts[j];
    }
  }
  for (j=0; j<nc; ++j) {
    s = sumcount[j] > IsHighTotal;
    if (s ^ ostate[j]) {
      Serial << j << (s? " on  " : " off ") << sumcount[j] << " " << millis() << endl;
      ostate[j] = s;
    }
  }
}
//-----------------------------------------------------------
// Take samples of rise times at  designated pins.  When a pin's
// time changes from small to large, report rising edge; or
// when it changes from large to small, report falling edge.
void loop() {
  //secondly();
  //testChange1();
  testChangeA();
}

```

---
Tags: programming
---


# Question
Title: Array of strings - how to determine the number of elements present
I would like to use an array of strings which I define as follows:

```
char* CommandQueue[]={"FirstCommend", "SecondCommend", "ThirdCommand", "Cmd4", "Cmd5"};

```

The purpose of this array is to hold commands ("strings of various lengths") that the Arduino will receive through a serial port. Those commands will be interpreted by calling appropriate callback functions to act on them. The CommandQueue is supposed to line up the commands in a sort of "buffer".

Initially the "CommandQueue" array does not contain any elements and gets populated during the runtime of the project. The array will continuously be interrogated and once a command is interpreted (and the corresponding function executed) the command will be eliminated from the queue.

How can I determine how many elements (i.e. strings) or commands are present in the array? The sizeof() function will not be helpful because the individual elements can be of different lengths.

Thanks in advance for your help or comments.

# Answer
> 2 votes
You can't know how many items are in an array simply because an array has a fixed size, and there is no such thing as "not an entry".

The closest you can have is a fixed size array and only some entries in it are valid - those that aren't valid have a special value to say "this is not a valid entry". For `char` pointers it's normal to use `NULL` as the "not a valid entry" value.

The drawback of this approach though is that you can never store more items than there are slots for, and finding out how many valid or invalid entries there are and shuffling them around when you remove the first entry is both a tedious and time consuming task.

Better in this situation to use a *circular buffer* which is a fixed size array but you remove the concept of a "first" entry. Instead you have a "head" and a "tail" value which is the locations in the array where you read from (remove the oldest) and write to (add after the newest). It's how the serial port on the Arduino deals with incoming and outgoing data - as data arrives it is added to a circular buffer and you then read from that buffer.

To help work with circular buffers I wrote a small template class:

# Answer
> 1 votes
Do you need to know how long the command queue is, or just if there are still elements in it? This seems like a case where you might be better off using a different data structure – a linked list seems like an obvious possibility. If you're not familiar with linked lists, this article may be helpful. Otherwise, I think you'll need to keep track of the number of elements in the queue for yourself.

If you do use an array, it will need to be declared with a fixed length, something like:

```
 char * CommandQueue[MAX_QUEUE_LENGTH];

```

The `sizeof` operator would tell you the length of the array, but not the number of items in it (the length of the array is the number of character pointers defined by MAX\_QUEUE\_LENGTH). The code to manage the command queue as an array could get pretty messy, especially if you need to execute the commands in order.

If instead you use a linked list then each command is added to the list at the end as it comes in, and when you execute commands they are pulled from the head of the list. If you need to know the length of the queue you could either update it as you add and remove commands, or you could iterate over the list and count the number of items in the list.

# Answer
> 1 votes
A very useful macro is membersof().

```
#define membersof(x) (sizeof(x) / sizeof(x[0]))

```

You will find in defined in large libraries and frameworks for C/C++. For your example above the number of elements is:

```
const int COMMAND_QUEUE_MAX = membersof(CommandQueue);
...
for (int i = 0; i < COMMAND_QUEUE_MAX; i++) ...

```

A dynamic set would require a max length and null terminated or simply a counter.

```
const int COMMAND_QUEUE_MAX = ...;
char* CommandQueue[COMMAND_QUEUE_MAX] = { ....., NULL };

for (char** cpp = CommandQueue; *cpp != NULL; cpp++) {
  char* name = *cp;
  ...
}

```

Or even better use a Queue data type:

```
Queue<char*, COMMAND_QUEUE_MAX> CommandQueue;
...
char* cp;
while (CommandQueue.dequeue(&cp)) ...

```

Cheers!

---
Tags: string
---


title: Nokia 5110 Screen Pixel by Pixel

text:
# Question
Title: Nokia 5110 Screen Pixel by Pixel
I have got this LCD screen

I'd like to be able to decide every pixel status of the screen. Do I need to work directly with the buffer or is there another method?

# Answer
> 5 votes
The 5110 Nokia LCD display is based on PCD8544. It is not possible to read the device display memory. The controller has only serial data input.

Typically a graphical device driver for that display will use an offscreen bitmap (buffer). To check the pixel status you would need to check the status in the offscreen bitmap.

Some device drivers use only text and copy font bitmap directly to the display memory. In that case you cannot check the status of the pixel (if the text is not buffered).

---
Tags: programming, lcd
---


# Question
Title: RobotLinking 18B20 pinout and circuit board weirdness
I have a Dallas Semiconductors 18B20 temperature sensor on a RobotLinking board. It's part of the RobotLinking 37 Sensors Kit. The board has a LED to indicate activity. It resembles this:

Here's what's weird. All the guides I can find for the 18B20 say that the pin order is GND, DQ, VDD. That should mean pin 1 goes to GND, pin 2 goes to a GPIO, and pin 3 goes to 3.3V or 5V (this one can take either). Yes, I am looking at the sensor's pins from its bottom.

If I do this, the board's LED is lit solidly. I get 0 degree readings, the same as if no device was connected. (Infinite resistance?)

To make this work, and get valid temperature readings, I have to hook it up this way: sensor GND to the GPIO, sensor DQ to GND, and sensor VDD to 5V or 3.3V. The LED only flashes when the temperature is actually read.

Here's a twist: if you look at the circuit traces on the RobotLinking board, it looks like the paths between the male breadboard connectors and the sensor's pins 2 and 3 are reversed. This means if you think you are connecting to pin 3 via the male connectors, you are in fact connecting to pin 2, and vice versa. The path from pin 1 on the sensor to the male pin 1 where it plugs into the breadboard is straight, so pin 1 probably means pin 1.

When I described the above connections I made, I accounted for this apparent circuit pathing weirdness.

Another twist is in the manual, the sensor is soldered to the middle leads. My sensor is instead on the furthest leads from the pins, like in the attached image.

The manual with this kit didn't explain any of this. I'm at a loss to understand my observations. For a generic sensor kit for n00bs, why would one want the pins on the bottom of the circuit board not correspond to the pinout of the sensor?

# Answer
> 1 votes
From the look of the board, it is designed to support multiple devices. I'd suspect that the three sets of holes give different mappings of the device pins to the board pins. Could it be that the sensor is soldered into the wrong set of holes?

If you have a meter or can see the traces you could look to see if the middle set of holes is wired the way you would expect. If that is a photo of your board, it looks like you have enough length in the leads on the sensor to move it to the middle holes.

---
Tags: arduino-uno, sensors, temperature-sensor
---


# Question
Title: Debugger with Breakpoint and Variable read/set capability
Is there any free/open or commercial/paid Arduino IDE Sketch Debugger (not Atmel chip factory standard tool set) with Breakpoint and Variable read/set capability?

I read about VM on web. Is there any similar product?

# Answer
> 1 votes
There is something quite close to what you are asking. You need either the (more expensive) ICEMKII (iirc) or the (cheaper) AVRDragon. Then it's possible to use it with gdb.

In practice the AVR supports only one breakpoint, so what happens is that the binary in flash will be dynamically patched. This will slightly reduce the life of the AVR, but I think it's fairly acceptable. One can always use Arduino UNO with the original DIP package for AVR, mounted on a socket. Then it's sufficient to replace the burnt microcontroller and keep the rest (but it's hundreds of thousands of programming cycles before the AVR fails).

# Answer
> 1 votes
There is an on-target debugger in Cosa and a port of the library for Arduino/AVR. It allows conditional and unconditional break- and observation points, simple call back-trace, variable read, memory status check, memory dump, etc.

The debugger is implemented as a small command handler that is executed on the target (Arduino). A set of macros are used to mark break-points, variables to observe, etc.

Please see the debugger demo sketch for more details.

---
Tags: variables, ide
---


# Question
Title: Where am I supposed to get an I2C BUFFER_LENGTH defined?
I am using a BLE nano - as soon as I try to include I2Cdev.h and compile, I get this error:

```
Arduino\libraries\I2Cdev\I2Cdev.cpp:276:62: error: 'BUFFER_LENGTH' was not declared in this scope

```

How should I fix this? I imagine I can hard-code it in and guess around as to the value (32 seems common), but I think I am missing something else as far as it using the right libraries for the hardware, so how can I check/fix that if it is indeed the case?

# Answer
> 1 votes
BUFFER\_LENGTH is set in I2Cdev.h depending on the target. BLE nano is not directly supported (what I can see).

Cheers!

---
Tags: programming, i2c
---


title: arduino beginner documentation help

text:
# Question
Title: arduino beginner documentation help
I plan to buy these 2 products to begin to play with arduino to learn.

1. Board with LCD touch
2. Yun board expansion

I have a mega 2560 which i bought with a starter kit and i love to play with. I have not played with the shield yet. I understand some shields can be used together, some not. and some with modification on the board and in the code.

I can't find pins specification for the touch screen and the support on the website doesn't respond.

If some one can help me find specifications for the touch screen, or help me choose some shields that will allow me to use a USB host, wifi, and a touchscreen it will be nice.

Thanks all.

# Answer
The link you posted describes a TFT LCD Touch screen unit with the SPFD5408 controller, referenced in this Instructable for use with the Mega. You might start there and migrate to the Yun once you get the screen working.
> 0 votes

---
Tags: arduino-mega, shields, arduino-yun
---


# Question
Title: What causes a "blip" in LED brightness with sequence of 254, 255, 0, 1 brightness values?
I am seeing a "blip" in LED brightness when trying to fade a red LED on an Arduino UNO.

This code demonstrates the "blip" seen in brightness right after a 254, 255, 0 sequence. When the brightness is then set to 1, the actual brightness is much higher for a short period of time. The blip is not seen during the entire delay interval, just at the beginning.

I see the blip every time except for the very first cycle, before the 255 to 0 transition has ever happened.

My best guess is that there is a PWM "accumulation" that is not seen when the brightness is set to zero, but it is used when the brightness is set to a non-zero value.

```
/*
 FadeBlip
 Derived from Fade.ino.
 */

int led = 9;
int brightness = 0;
int fadeAmount = 1;
int skipBegin = 5;
int skipEnd = 254;

// If you try a shorter delay, you must make the skip range smaller
// to pick out the blip.  If you try a longer delay, the blip is not
// as bright.
int delayms = 1000;

void setup()  {
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  delay(1000);  // give us time to bring up serial monitor
}

void loop()  {
  Serial.println(brightness);
  analogWrite(led, brightness);

  brightness = brightness + fadeAmount;

  // skip the boring middle values
  if (skipBegin < brightness && brightness < skipEnd)
    brightness = skipEnd;

  if (brightness > 255)
    brightness = 0;

  delay(delayms);
}

```

# Answer
The Why does an LED sometimes flash when increasing brightness? question does exactly describe my problem (except for the substitution of pin 11 for pin 9). That question refers to this post at forum.arduino.cc which gives the beginnings of an answer.

The problem is caused by the fact that `analogWrite(led, 0)` does not use PWM, it just sets the pin to LOW. So when you call `analogWrite(led, 0)`, the value in the Output Compare Register (OCR) is left at 255. When you call `analogWrite(led, 1)`, the OCR value is changed to 1, but due to double-buffering this doesn't take effect until the next timer cycle begins. So for a fraction of the current timer cycle the output pin is left at HIGH.

The solution is to either avoid calling `analogWrite(led, 0)` or to explicitly set the OCR value to 0 when `analogWrite(led, 0)` is called. This will only work if another call to `analogWrite()` is not made in the current timer cycle. Given that the default timer cycle takes 32 microseconds, this is unlikely to happen. 32 microseconds = 256 (ticks per timer cycle) / 16MHz (clock ticks per second) * 2 (default timer prescale factor).

For pin 9, the solution was to add these lines immediately after the `analogWrite()` call:

```
if (brightness == 0) {
    OCR1A = 0;
}

```

For other pins, use the correct Output Compare Register. For the Arduino UNO they are:

```
+-------------+----------+-------+
| Arduino Pin | Chip Pin | OCR   |
+-------------+----------+-------+
|           3 |        5 | OCR2B |
|           5 |       11 | OCR0B |
|           6 |       12 | OCR0A |
|           9 |       15 | OCR1A |
|          10 |       16 | OCR1B |
|          11 |       17 | OCR2A |
+-------------+----------+-------+

```

Of course this solution will need to be modified if you have changed anything related to timers such as the PWM mode.

The solution given by the forum.arduino.cc post indicated that the Timer/Counter Control Register (TCCR) needed to be modified in addition to setting the OCR value. This modification was to configure the PWM mode, but the PWM mode would have already been correctly configured by any previous call to `analogWrite()` for that pin.

Others have suggested that calling `analogWrite(led, 1)` before `analogWrite(led, 0)` would be a simpler solution, but that still results in a flash, albeit shorter.

Resources:

* LED fade malfunction (random flash) (forum.arduino.cc/index.php?topic=360468.msg2486781)
* hardware/arduino/cores/avr/arduino/wiring\_analog.c
* Secrets of Arduino PWM (www.righto.com/2009/07/secrets-of-arduino-pwm.html). There is a more recent copy of this article at arduino.cc (www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM), but that copy has the useful graphics stripped out.
* Arduino Timers and Interrupts (arduino-info.wikispaces.com/Timers-Arduino)
> 1 votes

---
Tags: arduino-uno, led
---


# Question
Title: embedXcode: Link Error using an Arduino library (Servo.h) within a header file
For various reasons, I am moving from the Arduino IDE to Xcode using the embedXcode plugin. The code in question compiles and uploads fine from the Arduino IDE, so I think the issue is related to library definitions in embedXcode. The board I am using is an Arduino Mega 2560 (actually it is a Freetronics EtherMega).

The error thrown is:

```
Command /Applications/Xcode.app/Contents/Developer/usr/bin/make failed with exit code 2

```

More specifically:

```
    5.3-LINK                    Builds/embeddedcomputing.elf

/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++ -o Builds/embeddedcomputing.elf Builds/main.cpp.o Builds/embeddedcomputing.a -Os -w -mmcu=atmega2560 -Wl,--gc-sections  -LBuilds -lm
Builds/main.cpp.o: In function `Robot::Robot()':
main.cpp:(.text._ZN5RobotC2Ev[Robot::Robot()]+0x5e): undefined reference to `Servo::Servo()'
Builds/main.cpp.o: In function `Robot::begin()':
main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0x5a): undefined reference to `Servo::attach(int)'
main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0x64): undefined reference to `Servo::write(int)'
main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0xea): undefined reference to `Servo::write(int)'
main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0x112): undefined reference to `Servo::write(int)'
main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0x132): undefined reference to `Servo::write(int)'
Builds/embeddedcomputing.a(HB25MotorControl.cpp.o): In function `HB25MotorControl::HB25MotorControl(unsigned char)':
HB25MotorControl.cpp:(.text._ZN16HB25MotorControlC2Eh+0x14): undefined reference to `Servo::Servo()'
Builds/embeddedcomputing.a(HB25MotorControl.cpp.o): In function `HB25MotorControl::begin()':
HB25MotorControl.cpp:(.text._ZN16HB25MotorControl5beginEv+0x42): undefined reference to `Servo::attach(int, int, int)'
HB25MotorControl.cpp:(.text._ZN16HB25MotorControl5beginEv+0x58): undefined reference to `Servo::writeMicroseconds(int)'
Builds/embeddedcomputing.a(HB25MotorControl.cpp.o): In function `HB25MotorControl::stop()':
HB25MotorControl.cpp:(.text._ZN16HB25MotorControl4stopEv+0x12): undefined reference to `Servo::writeMicroseconds(int)'
Builds/embeddedcomputing.a(HB25MotorControl.cpp.o): In function `HB25MotorControl::moveAtSpeed(int)':
HB25MotorControl.cpp:(.text._ZN16HB25MotorControl11moveAtSpeedEi+0x44): undefined reference to `Servo::writeMicroseconds(int)'
collect2: error: ld returned 1 exit status
make: *** [Builds/embeddedcomputing.elf] Error 1
Command /Applications/Xcode.app/Contents/Developer/usr/bin/make failed with exit code 2

```

Robot.h contains a robot class which defines a Servo (for a turret) and two HB-25 MotorControl objects (which control the drive motors). The HB25MotorControl is a custom library that I have written for the Parallax HB-25 Motor Controller. It also uses the Servo library.

To answer the obvious questions:

1. Yes I have `#include <Servo.h>` in my HB25MotorControl library. You can see the library code by following the link above. It is also included in the main sketch.
2. I have compiled, linked and uploaded other sketches which use Arduino and custom libraries in Xcode using the embedXcode plugin.
3. My embedXcode Makefile definitions include the Servo library and the HB25MotorControl library. See extract below.

APP\_LIBS\_LIST = Wire Servo SoftwareSerial

USER\_LIBS\_LIST = NewPing Time DS3232RTC HB25MotorControl

Any suggestions on how to fix this error and get my code to build in Xcode would be greatly appreciated.

# Answer
> 1 votes
I ended up contacting the developer of the embedXcode plugin. He was very helpful and provided the fix within a day. The cause of the issue is apparently the Arduino IDE has changed its library structure in the latest release.

The next version of embedXcode (release 4.1.4.) will include a fix for this, however if you can't wait until then you need to open ArduinoAVR\_165.mk (located in the Makefiles group in Xcode) in your project and add the following line:

```
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/$(BUILD_CORE),$(APP_LIBS_LIST)))

```

After you add this line, the file should look like this:

```
# Two locations for Arduino libraries
#
APP_LIB_PATH = $(APPLICATION_PATH)/libraries
APP_LIB_PATH += $(APPLICATION_PATH)/hardware/arduino/$(BUILD_CORE)/libraries

avr165_20 = $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%,$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/utility,$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src,$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/utility,$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/$(BUILD_CORE),$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/arch/$(BUILD_CORE),$(APP_LIBS_LIST)))

```

Note that each project has its own ArduinoAVR\_165.mk file, so you will have to make this change in each project until you update to the new release.

---
Tags: arduino-mega
---


# Question
Title: How to Send Live Sensor Data to iOS Custom Apps with BLE
I am looking for a Bluetooth Low Energy (BLE) device that could send live sensor data from Arduino to iOS custom apps, not the app that is already in the app store. I would like to create my own apps to receive the sensor data. Or are there any other ways to achieve it?

# Answer
> 1 votes
I would expect this to be pretty straight forward. Off hand, I can't think of anything that would be a major roadblock to creating your iOS apps. It seems like there are two problems you'll need to solve:

1. Finding a BLE chip that is relatively easy to integrate with an Arduino, and
2. Selecting the tools that you'll use on the iOS side to develop your app.

Since I haven't done this my self, I started off looking on the Arduino side – mostly because it seemed like the problems there would be larger. I searched on Google using the terms:

`aruduino ble`

I found quite a few candidates that look promising, here are some of the better ones:

* Bluefruit LE - Bluetooth Low Energy (BLE 4.0) - nRF8001 Breakout - v1.0 – I put this one on the top of my list because the price is pretty reasonable (\< $20 US) and Adafruit tends to do a good job of supporting their products with tutorials and at least a basic library that demonstrates the functionality of the device.
* Redbear Labs \- I don't know anything about Redbear, but they do well in Google searches and appear to have several products, including a BLE shield, that might do what you want.
* BLEduino \- this is a Kickstarter, and while it looks interesting, a *very* quick investigation didn't reveal a source where you can buy one.

The choice of devices will partly depend on what your ultimate goal is. Something like the BLEduino will give you an all-in-one package to build your project around. The downside of this is that you may be spending money on functionality that you don't need/want to duplicate. A breakout board like the Bluefruit LE gives you a smaller device and possibly more flexibility at the expense a bit more work to get up and running.

Next you'll need to select development tools. I started by searching with the terms:

`ble swift ios`

I got a number of promising results, including:

These first three look like good starting points for "getting your bearings," the following two are specific to actual boards.

---
Tags: arduino-uno, bluetooth, communication, mac-os
---


title: Reading SPI between an MCU and NRF24L01

text:
# Question
Title: Reading SPI between an MCU and NRF24L01
I have a remote control that has an STM32 MCU and sends data via NRF24L01. What I would like to do is clone the data sent when buttons are pressed by reading what is being sent to the RF24 and then replicating these messages with my own "remote".

I have tried sniffing the data wirelessly with my Pro Mini and NRF24L01. I have everything plugged in correctly, the BasicExample seems to be running fine, but when I run a promiscuous channel activity sniffer, I don't get any wireless data, not even running wifi and bluetooth near the NRF. Pro Mini is 5V and NRF sniffer is powered by an external 3.5V battery with cap on VCC-GND, ground is common to Pro Mini. I have also tried the WireShark approach, but with 0 packets found.

Therefore I want to try it directly wired to the remote. I don't have a logic analyzer handy. How would I read the data? By just connecting MISO and CS to an arduino and running an SPI reader? What would be the best way to do this? I have the Pro Mini and many Teensy boards ready.

# Answer
That was an interesting challenge. There are some obstacles to consider when trying to use RF sniffing:

1. What channel is used? (128)
2. What bit-rate is used? (250K-1M-2M)
3. How many address bytes? (3-5 byte)
4. How many bits in CRC? (1-2 byte)
5. Auto-Acknowledgement? (1 bit)
6. etc.

Without any info on the remote NRF configuration this is tedious to break. Probing the hardware signals (MISO, MOSI, SCK, SS) on the remote NRF chip with a logic analyzer seems (much) easier.

Cheers!
> 1 votes

---
Tags: arduino-pro-mini, spi, nrf24l01+
---


# Question
Title: How can I make Arduino IDE use Atmel's provided toolchain? (Linux/Ubuntu)
I have an Arduino based board using ATmega168PB, but so far only Atmel's provided toolchain supports this microcontroller. I can download the toolchain from Atmel's website, but I am not sure how to make the Arduino environment use it.

# Answer
In the directory for the new core create a new `platform.txt` and give the entry for `compiler.path` the location of the `bin/` directory containing the Atmel toolchain.

```
compiler.path=/path/to/bin/

```
> 3 votes

---
Tags: arduino-ide, compile, ubuntu, avr-toolchain, command-line
---


title: Problem Uploading to arduino uno board

text:
# Question
Title: Problem Uploading to arduino uno board
I have an arduino uno. Whenever I try to upload code to the arduino I get this error.

```
avrdude: ser_open(): can't open device "/dev/cu.usbserial-AL01EI7I": Device not configured

ioctl("TIOCMGET"): Inappropriate ioctl for device Problem uploading to board.
See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

# Answer
> 1 votes
The error message is telling you that avrdude failed to open the device and read the modem status (basically the information about whether a device is present and ready on a serial line). The most likely causes of this are:

1. Using the wrong serial port (Tools \> Port in the Arduino IDE).
2. The IDE not recognizing the board.
3. Using a power only USB cable.

The Arduino IDE seems to remember the device that your board was last connected through, but on some Unix flavored OSes the device name depends, in part, on method of connection – which port, hub or no hub, etc. So if you change the board or the port you plug it into, the name changes.

So, the very first thing to do is to look under Tools \> Port in the Arduino IDE to see if there is another device present. Also confirm that you're using a USB cable with data wires. There are "power only" USB cables…

Failing that, check to see if the OS sees the board. On OS X you would go to the Apple menu and choose About this Mac and then look at at the System Report to see what devices have been detected on your USB busses. I'd be surprised if there wasn't something similar on Linux (and Windows too for that matter). If you're comfortable on the command line you could look in `/dev` for devices with similar names.

If the board is present, but not seen by the Arduino IDE, try restarting the IDE and/or plugging and unplugging the USB cable. Sometimes it helps to plug the cable into a different port.

---
Tags: arduino-uno, uploading
---


# Question
Title: What phone carriers are available in the USA that are compatible with a sim900 breakout board
I was wondering what carriers are compatible with a sim900 breakout board. I know it needs a GSM network (AT&T,T-mobile,?) but what networks can I use?

It needs a 850/ 900/ 1800/ 1900 MHz frequency to work but who offers that frequency? I personally could not find what frequency cell phone companies offered. From how I understand it is that T-Mobile definitely will work.I have heard several different answers about companies like AT&T and I have seen discussion about sprint (which I don't understand because they are a CDMA carrier).

I have also heard that there are other carriers (Vondafone, nextel,Ting) that might be more cost effective for people like me who are only going to be using the text messaging.

Can someone please set me straight on who I can use.

# Answer
> 1 votes
SIM900 should be compatible with both AT&T and T-Mobile. T-Mobile uses 1900Mhz for 2G and AT&T uses 850Mhz and 1900Mhz. Although both carriers are upgrading to 4G, they still support 2G devices. My personal experience is that most quadband 2G devices still work with AT&T and T-Mobile and there is no technical reason why SIM900 shouldn't work. However, there can be issues with incompatible data plans that are compatible only with their own devices. You need to be careful when selecting the contract and buying the sim card.

Nextel and Ting uses Sprint's network which is CDMA and thus wouldn't work. However Vodafone seems to be using T-Mobile's network and may work.

---
Tags: gsm
---


# Question
Title: Measuring voltage on an analog pin - What do I need to know about amperage?
I'd like to measure the voltage at a test point on a stepper motor driver chip with an arduino. The voltage at this point controls the amperages to the phase coils and is adjusted to trim the driver.

I have a common ground with the driver already, I'd like to wire the drivers v-ref point to an analog input to drive an LCD showing the output amp number so I can adjust the driver.

The issue I am worried about is that with the hardware I have to test with a properly trimmed driver is pushing 0.84A.

Is this safe to do without killing the arduino board?

# Answer
> 3 votes
Yes. The only thing you need to be concerned about is the voltage. It needs to be less than the Arduino Vcc.

The voltage sense circuit (analog inputs) typically have a high impedance and should draw a negligible current from the circuit being sensed. I didn't have much luck finding the actual spec for any of the AVR chips, but I did find this answer to the question on Electronics.StackExchange – where they say "hard to tell, the specs are incomplete, but 10 KΩ seems like a reasonable guesstimate/assumption" (I paraphrase). The reasoning is interesting and worth a read.

---
Tags: arduino-uno, analogread, voltage-level, safety
---


# Question
Title: Link to an project for remotely turning off light switch?
I want to build a contraption using an arduino that allows me to turn off my light from across the room. I plan to use a solenoid to move the lights switch up and down. I'm sure I'll have some specific questions later on but to start with, has anybody made or seen a similar project? All I'm really looking for is a link to a project (unless you're willing to give advice/suggestions). Thanks!

# Answer
### MicroBot Push: a robotic finger for your buttons...

https://www.indiegogo.com/projects/microbot-push-a-robotic-finger-for-your-buttons#/

### The Robotoic Light Switch

http://hackaday.com/2015/11/06/the-robot-light-switch/

### Wifi controlled light switch

https://hackaday.io/project/5141-wifi-controlled-light-switch
> 1 votes

# Answer
This isn't exactly what you asked for, but may be a better idea.

Light switches are electrically just switches. Either two points are connected or they are not. In this case they are meant to be mechanically actuated by humans.

Instead of making a electrically controlled contraption that mechanically activates the existing switch, you could more easily use a electrically-activated switch directly. Such things are called *relays*, and are quite common and readily available. You can easily get a relay that can be actuated from 5 V that can switch 120 or 240 Vac at a few amps.

Put the relay in parallel across the switch if you want the switch to be able to override the light on, and in series if you want the switch to be able to override the light off.

To allow both the relay and the switch to toggle the light on/off independently, each needs to be a SPDT (single pole double throw) switch or relay. Actually, you'll have a hard time finding a relay that isn't at least SPDT. Ordinary wall switches aren't, but ones meant for multiple switches to control the same light are, like you often find at the top and bottom of the same set of stairs.
> 2 votes

# Answer
Various types of light switch actuators. Which is it?
> 0 votes

---
Tags: home-automation
---


# Question
Title: Read a String from serial to debug the AT commands sent to my GPS shield
I want to extract an AT command's response (via serial port) to find out if the GPS shield is working as it should be.

I used:

```
  if(Serial.available()>1){
     String response = Serial.read();
     Serial.println(response);
  }

```

Normally the response to AT is OK but it keeps telling me that it cannot convert `int` to `String` .... can someone help?

# Answer
`if (Serial.available() > 1)` is wrong. Always use `if (Serial.available())` in such cases. Also it seems you are communicating with the GPS shield using Hardware Serial. However, the Arduino also uses the same serial port for communicating with the PC via the USB connection. So what you have basically is:

* Arduino TX, PC RX and GPS RX are all connected
* Arduino RX, PC TX and GPS TX are all connected

So anything the Arduino writes to the Serial port using `Serial.println()` is received by both the PC and the GPS shield. And the other hand, responses from the GPS shield and commands sent from the serial monitor all arrive at the same Arduino pin. So when you use `Serial.read()`, assuming you used the serial monitor to send the command, you will end up receiving your own command (like some sort of echo), and according to your program, you use `Serial.println()` to send the command again which is received by both PC and GPS shield, with the GPS shield responding to the same command again. All undesirable.

TLDR; use SoftwareSerial instead for the GPS shield. Connect the GPS shield TX to pin 2 and its RX to pin 3 and use this code:

```
    #include <SoftwareSerial.h>

    SoftwareSerial gps(2,3);   // pin 2 = RX, pin 3 = TX

    void setup(){
        Serial.begin(57600);
        gps.begin(57600);    // change to your baud rate, if not auto-baud
    }

    void loop(){
        while (Serial.available())     //used to send commands from PC
            gps.write(Serial.read());   // to gps
        while (gps.available())        // used to read responses from gps
            Serial.write(gps.read());  // to PC
    }

```

So the Arduino forwards everything it receives from the PC monitor (commands) to the shield and sends everything it receives from the shield (responses) to the PC to be displayed in the serial monitor.
> 2 votes

# Answer
Serial.read() returns a byte (a single character), you've told the compiler that response is a string. It doesn't know how to deal with the difference…

What you want to do it to read the response in a loop until you've got it all.

Here's an example.
> 0 votes

---
Tags: arduino-uno, serial, gps
---


# Question
Title: iterate through values in an array of strings to print
I (think I) am trying to iterate through the values of an array and print the string to a tft. I have declared the array of 4 strings, and that works fine. But when I try to print it, I get garbage. Am I missing a nuance of print? Or do I just not understand how to use arrays and strings...?

The code is as follows:

Declarations:

```
//Active System
char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};
int activeSystem = 0;
String displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "off"

```

Use (note the fake if statement for the question)

```
  if(systemNeedsToBeCycled){
    activeSystem++;
    displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "Fan"
    tft.print(displayActiveSystem);
  }

```

Instead I get random characters most of the time, sometimes nothing.

In case its a memory thing, please know that:

Sketch uses 26,480 bytes (92%) of program storage space. Maximum is 28,672 bytes. Global variables use 1,126 bytes (43%) of dynamic memory, leaving 1,434 bytes for local variables. Maximum is 2,560 bytes.

# Answer
If the variable `activeSystem` exceeds the length of the array, it's out of bounds, at which point the behavior is undefined.
In your case you get "garbage data", which is actually just data in memory after the array.

Because the is no implicit check for array bounds, you need to check them yourself.
> 0 votes

# Answer
I think this is the correct way to create an array of C strings:

```
    char * hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
    int activeSystem = 0;
    char * displayActiveSystem = hvacSystems[activeSystem];

    if(systemNeedsToBeCycled){
        activeSystem++;    // make sure to set a bound for this variable
        displayActiveSystem = hvacSystems[activeSystem];
        tft.print(displayActiveSystem);
    }

```

Since strings are basically stored as char pointers so an array of strings is an array of char * variables. Or you could create an array of Arduino strings:

```
    String hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
    int activeSystem = 0;
    String displayActiveSystem = hvacSystems[activeSystem];

    if(systemNeedsToBeCycled){
        activeSystem++;    // make sure to set a bound for this variable
        displayActiveSystem = hvacSystems[activeSystem];
        tft.print(displayActiveSystem);
    }

```
> 1 votes

# Answer
I am not sure I understand 100% but here is my best shot. If the below is wrong the issue is not due to being out of memory. Try this

```
//Active System
char hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
// or char hvacSystems[4] = {"Off", "Fan", "Cool", "Heat"}
int activeSystem = 0;
String displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "off"

if(systemNeedsToBeCycled){
    activeSystem++;
    displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "Fan"
    tft.print(displayActiveSystem);
}

```

Your line

char hvacSystems\[4\]\[5\] = {"Off", "Fan", "Cool", "Heat"};

You are attempting to create a two dimensional array here. Essentially a 4x5 table. With your code if you do

tft.print(hvacSystems\[0\]\[1\]);

It should give you "Off". Basically you made a table that looks like

0{"Off", "Fan", "Cool", "Heat", null}

1{null, null, null, null, null}

2{null, null, null, null, null}

3{null, null, null, null, null }

Arrays: https://www.arduino.cc/en/Reference/Array 2d Arrays:

http://forum.arduino.cc/index.php?topic=220385.0
> 0 votes

# Answer
The problem does not appear to be what you think it is, because I can't reproduce it.

See this:

```
//Active System
char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};
int activeSystem = 0;

String displayActiveSystem;

bool systemNeedsToBeCycled = true;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  displayActiveSystem = hvacSystems[activeSystem]; // <-- Should now be String "off"

  Serial.println (displayActiveSystem);

  if(systemNeedsToBeCycled){
    activeSystem++;
    displayActiveSystem = hvacSystems[activeSystem]; // <-- Should now be String "Fan"
    Serial.println (displayActiveSystem);
    }
  }  // end of setup

void loop ()
  {

  }  // end of loop

```

Output:

```
Off
Fan

```

Please post a complete sketch that reproduces the problem. The placement of variables, and their type, might influence the result.

I used Serial.println() to show the variable contents, which are what you expected.

---

Possibly this will work better:

```
tft.print(displayActiveSystem.c_str ());

```
> 0 votes

---
Tags: arduino-yun, string, adafruit
---


# Question
Title: arduino resets or hangs after providing power to DHT22
I'm developing a low power project based on Atmega328p which among other things uses a DHT22 to measure air humidity. DHT22 spec says that it consumes 50uA when idle. This is too high for me (I'm aiming at sub 10uA consumption for the whole device when in sleep mode) so I've figured out that I'll just power it from one of Atmega328p pins. This will give me the ability to turn it off or on at software level. DHT22 consumes only 1.5mA during measurement so I should be fine (a single Atmega's pin can safely provide up to 20mA). I've set up a following test circuit:

The red wire powers DHT22, the blue one is for data transfer, the black one is GND and the 4.7k is a pull-up resistor.

My problem is that after I turn on the DHT22 using just:

```
digitalWrite(4, HIGH);

```

the Atmega either resets or hangs or... successfully turns on the DHT22 and keeps working, but that happens about 10% of the time. My suspicion is that there is some current spike in the moment of supplying power to the DHT22. Unfortunately I don't have an oscilloscope to confirm this.

I've added a 220 ohm resistor between VCC pin of DHT22 and the pin 4 on the Arduino and it solved the problem. My question is: will it work like this reliably? Are humidity readings reliable when voltage is not stabilized (but stays within 3.3-5.5V range as required by the datasheet)? I could of course use a transistor to turn it on/off, but I'd like to keep it as simple as possible.

Why DHT22's datasheet doesn't mention this current spike? Here it is for reference: http://www.adafruit.com/datasheets/Digital%20humidity%20and%20temperature%20sensor%20AM2302.pdf

# Answer
The sensor is a large capacitive load. You need to improve decoupling of the CPU power supply.

A 10 uF between 5V and GND will help for the current spike and the resistor in series with the sensor will not be an issue (50 uA on 250 Ohm makes only 12.5 mV voltage drop once the sensor is started).
> 2 votes

# Answer
The previous answers regarding adding decoupling capacitors are good.
You don't have to be concerned about the voltage drop across your 220 ohm resistor. MAC's answer states that only 12.5mv drop at 50uA (when not measuring).
**During measurement**, 1.5mA will result in 0.33v drop across the 220 ohm resistor. This should be noted, but is not a problem. The DHT22 data sheet shows that it will accept any supply voltage between 3.3v and 6v.
Looks like you have a good design.
> 0 votes

# Answer
Decoupling capacitors do help, as mentioned in the other answers.

Also, to get a good reading, after powering up your digital pin 4, a delay of maybe 100-500ms may be required to allow the DHT22 to stabilize. For better results, you can also perform multiple readings (call delay(dht.getMinimumSamplingPeriod()) between the readings) and average them.

It looks like you are using an Arduino Uno. For further power savings, you might consider using a Pro Mini and performing some hardware modifications. For software power saving techniques, there is no better resource than Nick Gammon's Power saving techniques for microprocessors.
> 0 votes

---
Tags: sensors
---


# Question
Title: Arduino Uno ADC behavior in free running mode
I'm using my ATmega328P to sample an analog signal in free running mode. The ADC clock frequency is set to ÷128. I've read that a single analog conversion lasts 13 clock cycles. I would like to know if the number of clock cycles changes if I make the ADC trigger an interrupt after every conversion (ADIE bit set to one). Or will the ADC still use 13 clock cycles and start again on the 14th?

If ADIE is set to zero (no interrupts) will the result of the conversion still be written to ADCL and ADCH? And at what time of the 13 clock cycles is this result written to those registers? This is important to me so I can calculate how much time I have to read those registers.

Would it be possible to set ADIE to zero and instead use a timer interrupt to read ADCL and ADCH every ~1 millisecond. Or am I missing something important?

# Answer
You may want to take a look at Amanda Ghassaei's tutorials on Arduino DSP techniques or the FFT/FHT code at the Open Music Labs. Both use the Arduino ADC in free running mode. Amanda's code uses interrupts, the Open Music Lab code sits in a tight loop waiting for the conversion to complete.

Based on the Open Music Lab code I can say, yes, the conversion is still written to ADCL and ADCH regardless of the interrupt setting in ADIE. I can't tell from your question how concerned you are about cycle counts, but I don't think you'd see a significant change using interrupts (I'd expect it to be zero). But using interrupts you'll take a hit as you enter and return from the ISR.

As I mentioned in the comment, take a look at Amanda Ghassaei's code. She toggles pin 12 which creates a spike in the trace if you have a scope attached to pin 12 (or a logic analyzer). That will give you a very easy way to determine the actual time to handle the conversion.
> 2 votes

---
Tags: atmega328, analogread, adc
---


# Question
Title: detecting presence inside - PIR or ultrasound?
<sup>(I am professionally a software guy working in the GCC compiler with MELT, so I am fluent in software, but much less in hardware - I did use a solder for a 74LS00 nand gate based stuff in the 1990s. This is my first Arduino project)</sup>

My first Arduino project would be to automate the lights and the fan in my inhouse WC toilet in Paris (France) suburb. I bought several Arduino Nano v3 boards. I'm thinking of driving with a relay a low voltage 12v LED lightbubble. I want to detect human presence in the toilets. I'm thinking of some PIR sensor, but I am afraid that PIR won't detect anything if the temperature is above 37°C (or about 100F), which is unusual in Paris (France) but may happen a few days per year (I've got no air conditioning). Is my worry correct, or can a PIR still work with very warm outside temperature? Should I use an ultrasound detector instead?

# Answer
PIR sensors work fine and are probably easier to program for than ultrasonic sensors. For example, this tutorial on a PIR sensor sold by Adafruit has a datasheet at the bottom that says:

> Operating Conditions Operating Temperature -20 ˚C to +70 ˚C
>
> Storage Temperature -30 ˚C to +80 ˚C
>
> Operating Voltage 3 to 10 V at Rs = 47 kΩ

You can try to find and check the datasheet for the sensor you intend to purchase to determine if it will work.
> 3 votes

# Answer
One thing to be wary of with PIR sensors is that they only detect *moving* heat. That means that your light would turn on as you enter the toilet, but would turn off again when the sensor fails to detect movement. That will be once you're sat on the toilet and reading the newspaper. To keep the light on you would need to flail your arms around to keep the sensor on, and thus the light on.

So from that perspective alone the ultrasound would possibly be a better option since it can detect the presence of anything within its cone of sound - as long as that something is big enough, like a human body.

A third option that you haven't mentioned is infra-red beams. Depending on how big the toilet is you may be able to just have one IR beam passing through the room, and when someone is in the room that beam will be broken. Only works in small cubicles though. For larger rooms you may need either a mesh of beams to cover the whole room, or a dual-beam in-out counting arrangement on the entrance (two beams, one before the other. If beam A breaks before beam B then someone has entered - if beam B breaks before beam A then someone has left. When there are 0 people in the room then turn the light off).
> 1 votes

---
Tags: sensors, arduino-nano, gcc
---


# Question
Title: Use of additional i/o ports in Arduino Mega
I'm a newbie in Arduino and I bought an Arduino Mega instead of the Uno. I want to know what the so-called additional i/o pins do. Are they the same with PWM and SPI? What can they do?

# Answer
**Firstly some background info on the Arduino Mega:**

I haven't used the Mega, but I've used the Uno, and have worked with a variety of ATmega microcontrollers.

First thing you need to know is that the Arduino Mega (or any other Arduino) is a board that uses the Atmel ATmega microcontrollers. The specific microcontroller used on the Mega is the ATmega1280 ATmega2560.

So if you are keen to learn more about your Arduino, a good place would be to look at the datasheet of the microcontroller itself. Just google ATmega1280 ATmega2560 datasheet.

However this might be a fair bit complicated, since you are new to the Arduino and microcontroller world.

A good place to start would be the Arduino website itself (but I suppose you've already looked at it).

**Now, regarding your question:**

I'm not sure what you are referring to as "additional i/o pins", but here's a quick rundown on what I/O pins are and used for.

As you may know I/O pins are used by the microcontroller to talk to the outside world. On the ATmega chips, most of these are GPIOs (General Purpose I/Os) that can be programmed to receive or send digital signals. Of these GPIOs some are used for PWM, and some may be used for some communication protocol. And of course there are analog input & reference pins, voltage supply, ground etc.

You can find all this information in the datasheet I linked above.

If you are curious how Arduino has routed the pins, you can have a look at the schematic of the Arduino Mega here.

If you also have a look at the Arduino website, they have a very good description on what each pin does: Arduino Mega.

Look at "Inputs and Outputs".
> 0 votes

# Answer
Additional I/O pins means more inputs and outputs. Therefore, you can have more signals. There are also some more specialized pins. For example, there are more PWM pins, more TX and RX pins for serial communication and more analog read pins.
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Python PySerial with Arduino fails byte check
I'm struggling with my first steps with Python and PySerial. I have one Arduino which reads impulses from an electricity power meter, passes the counts over to another Arduino over an RF link and then sends the data over to an Raspberry Pi. The Arduino to Arduino communication works well. However the last step of passing this to the RPi fails.

The MeterValue from the Arduino side is an unsigned Long (32 bits) and therefore split in 4 pieces of 8-bit transmissions plus a frame start and frame end:

```
[0x01] Frame start
[0xMeterValueByte0]
[0xMeterValueByte1]
[0xMeterValueByte2]
[0xMeterValueByte3]
[0x04] Frame end

```

This is my Arduino code continuously sent to the RPi in debug purpose :

```
void loop() {
//static test loop
Serial.write(0x01); //start frame
Serial.write(0x00);
Serial.write(0x00);
Serial.write(0x02);
Serial.write(0x04); //end frame
delay(3000);

}

```

This is my Python code:

```
Import serial
ser = serial.Serial('/dev/ttyACM0',9600)
print("Connected to: " + ser.portstr)

inputbuffer=[]
inputbuffer = [0 for i in range(10)]

while True:
    if ser.inWaiting() > 0:
        inputbuffer = ser.read(1)
        print "Byte received"
        print "Inputbuffer[0]: " + hex(ord(inputbuffer[0]))

        j = inputbuffer[0]
        print "j= " + hex(ord(j))

```

This check of the "j" parameter somehow fails:

```
        if (j == 0x1): #look for start of frame
            print "Start found\n"
            print "Filling buffer\n"
            while ser.inWaiting() < 5: #hold here until 5 bytes arrived
                pass #proceed here
            inputbuffer +=ser.read(5) #read 5 bytes

            if inputbuffer[5] == 4: #check that the message has frame end
                RXval = inputbuffer[1]
                RXval |= (inputbuffer[2] << 8)
                RXval |= (inputbuffer[3] << 16)
                RXval |= (inputbuffer[4] << 24)
                print "RXval: ", RXval
            else:
                print "RX error, no frame end\n"
        inputbuffer = []

```

This is the Python output:

```
Connected to: /dev/ttyACM0
Byte received
Inputbuffer[0]: 0x1
j= 0x1
Byte received
Inputbuffer[0]: 0x0
j= 0x0
Byte received
Inputbuffer[0]: 0x0
j= 0x0
Byte received
Inputbuffer[0]: 0x2
j= 0x2
Byte received
Inputbuffer[0]: 0x4
j= 0x4

```

And then it repeats. Obviously the Python code doesn't realize j == 1. How should I handle the checking of the received bytes?

# Answer
> 2 votes
I think the problem is that you can't count ;)

Spot the difference:

```
0: [0x01] Frame start
1: [0xMeterValueByte0]
2: [0xMeterValueByte1]
3: [0xMeterValueByte2]
4: [0xMeterValueByte3]
5: [0x04] Frame end

```

and:

```
0: Serial.write(0x01); //start frame
1: Serial.write(0x00);
2: Serial.write(0x00);
3: Serial.write(0x02);
4: Serial.write(0x04); //end frame

```

Your receiver is looking for a pattern of 6 bytes, but your Arduino sketch is only sending a pattern of 5 bytes.

Your check for the start character is simple enough - you solved it fine a few lines above:

```
print "j= " + hex(ord(j))

```

But you forgot to do something similar for the check:

```
if (j == 0x1):

```

That should really be:

```
if (ord(j) == 0x1):

```

---
Tags: serial, python
---


# Question
Title: How much power can the Teensy 3.2 deliver to external components?
Can a teensy 3.2 deliver enough power to properly activate multiple servos by chance?

# Answer
> 2 votes
No. You should provide your own regulator or supply for the servos specified voltage.

This might be an original design, or an off-the-shelf "battery eliminator" intended for an R/C vehicle of similar needs.

Note that the teensy regulator's maximum input voltage is fairly low, and may be in the range of what more powerful servos expect, ie, you might be able to run the teensy regulator off of the servo supply.

Be sure to consider the possibility of brownouts - multiple active or stalled servos can consume a lot of power, and if your upstream supply is not "stiff" enough this can result in the voltage dropping low enough that control electronics misoperate or reset - granted that is less likely with the teensy than with a 5v MCU using a regulator with a higher voltage dropout.

---
Tags: power, teensy
---


# Question
Title: Declare for loop as an array of variables
My goal is to store the variable in the for loop as an array rather than as a single 'ultrasoundValue'. Can some one help me structure the code?

I have this code:

```
int ultraSoundSignalPins[] = {5,7};
int tx = 4;
char *pingString[] = {"Ping1 ","Ping2 "}; // just something to print to             indicate direction

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

void loop()
{

 unsigned long ultrasoundValue;
 for(int i=0; i < 2; i++)
 {
   ultrasoundValue = ping(i);
   Serial.print(pingString[i]);
   Serial.print(ultrasoundValue);
   Serial.print("cm, ");
   delay(500);

 }
}

//Ping function
unsigned long ping(int i)
{
 unsigned long echo;

 pinMode(ultraSoundSignalPins[i], OUTPUT); // Switch signalpin to output
 pinMode(tx, OUTPUT);
 digitalWrite(ultraSoundSignalPins[i], LOW); // Send low pulse
 digitalWrite(tx, LOW);
 delayMicroseconds(2); // Wait for 2 microseconds
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Send high pulse
 digitalWrite(tx, HIGH);
 delayMicroseconds(5); // Wait for 5 microseconds
 digitalWrite(ultraSoundSignalPins[i], LOW); // Holdoff
 pinMode(ultraSoundSignalPins[i], INPUT); // Switch signalpin to input
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Turn on 0pullup resistor
 echo = pulseIn(ultraSoundSignalPins[i], HIGH); //Listen for echo
 return (echo / 29.1); //convert to CM then to inches
}

```

# Answer
You don't even have to add any lines, just modify a couple!

```
unsigned long ultrasoundValue [2]; //creates an array of unsigned longs of size 2

```

...and inside your for loop:

```
ultrasoundValue[i] = ping(i);

```

It appears you are acquiring 2 separate ultrasound values. If you'd like to store multiple sets of these 2 values, you could use a two-dimensional array:

```
unsigned long ultrasoundValue [10][2]; //an array of 10 pairs of long unsigned values

```

...and you could modify your for loop to have a pair of nested for loops:

```
 for (int i = 0; i < 10; i++)
 {
   for (int j = 0; j < 2; j++)
   {
      ultrasoundValue[i][j] = ping(j);
      //do whatever else
   }
 }

```
> 1 votes

# Answer
Make `ultrasoundValue` an array and use `i` as the index to it? Just like you have with all your other arrays?

You obviously know how to use arrays, since you have already been using them throughout your code.
> 0 votes

---
Tags: array
---


title: Clearing SRAM in loop()

text:
# Question
Title: Clearing SRAM in loop()
Very broad question here. I don't know exactly what the problem is but I'll edit this post as we narrow down the possibilities.

I think I'm running into memory constraints.

I'm running a sketch that records two temperature values every 60 seconds and transmits them to an AWS RDB via wifi. It works well for about two hours then stops. I don't know if it's a memory constraint but I suspect that it is. What other common problems (often overlooked by newbies) can cause a sketch to end after a couple hours of run-time?

Is there a simple way to add an instruction to a loop to clear the SRAM?

Arduino UNO + WiFi 101

Edit #1 12/24/2015:
It's the WiFi board. It happily remains connected to my phone's hotspot but only lasts an hour or two on my home network. Working on root cause...any ideas are welcome!

Edit #2 12/25/2015:
Tried to Wifi.disconnect() and reconnect with no luck. Why do some networks kick the board off while others work just fine? Will look into the watchdog.

# Answer
The problem was solved with a "soft restart" loop. Posts #10 and #11 are all I needed: http://forum.arduino.cc/index.php?topic=49581.0
> 1 votes

# Answer
Could you provide your sketch? At the rate you mentioned, 2 hours is merely 240 values and this shouldn't even matter since you are probably reassigning values to the same variables and not storing them in some growing array. Perhaps your WIFI shield merely gets disconnected from the network. How do you mean the sketch stops? Like you no longer receive the values in the database? More info is needed.
> 0 votes

---
Tags: arduino-uno, wifi, sketch, memory-usage, sram
---


title: HardwareSerial - check for overflow

text:
# Question
Title: HardwareSerial - check for overflow
The SoftwareSerial library has a built-in Overflow function, but the Serial library does not. Is there a simple way to check for a data buffer overflow on a hardware serial port?

# Answer
A look at `HardwareSerial_private.h` shows incoming bytes are always read (interrupt-based), regardless of what your code is doing. So we can't set up a hardware interrupt to notify us when the chip's RX register has overflowed, because such an interrupt would depend on overflow flags but these flags never become set because, like I said, bytes are always read. It also shows that while all incoming bytes are read, not all are added to the 64-byte Serial buffer i.e. a byte may be read but if the buffer is full, nothing else happens; it is simply read to clear hardware flags. So the only (direct) way I can think of is to constantly poll `Serial.available()` in `loop()` to check if the number of bytes available for reading is equal to 64. If this condition yields TRUE, then you may safely conclude that the Serial buffer is full and about to overflow. This should suffice:

```
    void loop(){
        //your code
        if (Serial.available() == SERIAL_RX_BUFFER_SIZE){ // Just to be general, 64 bytes in most cases
            //buffer is overrun, do what u will
        }
    }

```

You could make some changes to `HardwareSerial_private.h` to get something like the overflow() method of SoftwareSerial. The relevant lines are:

```
    if (i != _rx_buffer_tail) {
        _rx_buffer[_rx_buffer_head] = c;
        _rx_buffer_head = i;
    }

```

The snippet above ensures that the current write position is not equal to the tail of the ring buffer (i.e. if we are about to overwrite a character in the buffer), before writing the incoming byte to the buffer. An `else` block could be added to set some global variable to indicate overflow. This global variable would have to be cleared when `Serial.read()` is called.
> 6 votes

---
Tags: serial, softwareserial
---


title: SIM800 or SIM900 library for Arduino

text:
# Question
Title: SIM800 or SIM900 library for Arduino
I have a SIM 800L module which I am using to send /receive SMS calls.

I just wanted to know whether there is any library suitable for the SIM800 for arduino. I don't need GPRS functionality . I see mostly the arduino shield library but not sure whether it works with the SIM800 module bought from aliexpress.

Can someone help me in get me a library which can be used for the SIM800 .I have tried a lot but not getting a simple library for the same.

Actual Issue :

I am able to make it work with the AT commands using the Serial3 in the arduino MEGA. But when i started integrating with the existing project of ESP8266 and DS3231 somehow the Serial3 read() is not working properly. I tested with Serial3.readString()/ Serial3.read() and all. The CNMI for the SIM800 is 2,3,0,0 which is to direct the incoming message to the Terminal. If my project is having a simple loop with only Serial3.read, then all messages contents are read properly. If I include the other Serial2 readings which is for the ESP8266, then I am not able to read the full messages from Serial3.I have tried with timer to read serial from the Serial3 for 3-5 secs but now way it is working.

# Answer
Most likely, the Serial3 buffer is being overrun because you are not reading fast enough. That is why when you use a simple loop, everything works and you get the whole message; very little time passes between reads. The simplest solution to this is to increase the size of the Serial buffer to, maybe, 256 bytes. Search for `HardwareSerial.h` in your Arduino installation and look for the `#define`d variable `SERIAL_RX_BUFFER_SIZE` in the file near the top. Change its value to 256 and save. This should provide enough buffer space to store the entire SMS until you read it. Alternatively you could change your CNMI settings to push only SMS notifications, which are a lot smaller in size, to the Arduino. Then you can parse the notifications, extract the SMS index and then request the SMS from the SIM800 using the index whenever you wish, making sure to read quickly (you will need to craft a `while` loop to do this efficiently, with timeouts and all).
> 1 votes

---
Tags: gsm
---


# Question
Title: How do I connect multiple pinhole cameras and take photos and video at the press of a button?
I am trying to set up a 4 cameras which can take videos/photos at the press of a button.

Things which I will need:

1. 4 micro cameras(the ones which are very small in size) with good shutter speed and sensor. The cameras will often travel at 20 to 30mph. So I guess good shutter speed is needed.
2. 2 Push buttons. One will start and stop taking pictures really fast, and the other will do the same for video
3. Battery which can last atleast taking 5 images/1 min of video recording.
4. 4 Microsd cards and the connectors. Is there anyway I would be able to set up a common adapter to all these cards, so when connected to a computer it will show up as 4 different drives?

So I think I can make the set up using this: http://www.arducam.com/ But can it take images really fast. I couldn't see any information regarding this. It should be able to take like 4 images per second. Also it would be awesome if this set up can somehow support taking videos.

Now another thing I need is a push button which will start taking the photos and stop taking it.

This whole thing should operate from a battery.

Mostly I want to know is the list of products which will work or the specs to look for when choosing the products. Also I would like to know if this is the best way to go for a project like this. This thing will be more like a toy, so I don't want to use really expensive parts for this. Also I don't want a gopro. I want to make this whole set up myself.

Let me know if you need to know more details about this.

# Answer
> 1 votes
Arduinos and Cameras do not mix well at all. It's all down to the sheer quantity of data involved in pictures.

Take for instance a typical VGA image - 640x480 pixels at 24-bit (3 byte) colour depth. One single picture requires 640x480x3 = 921600 bytes just to store it.

Add to that the fact that most small cameras include hardware JPEG compression which the Arduino really has no hope of being able to handle, and you just can't do anything with it.

Most camera modules use a system called CSI-3 (Camera Serial Interface version 3) for streaming the raw data from the CCD elements into the target. That allows for high speed data transfer of the whole frame at a speed that is able to support video. If you think about video as 25 frames per second, and raw data, that means that the data is being transferred from the CCD elements in total at arouns 22 MiB/s - there is absolutely no way that an Arduino can deal with that kind of data. So cameras that attach to an Arduino have their own controller chip that compresses the image to JPEG and streams it out through a much slower interface - typically RS232. All the Arduino can then do is tell the camera "Take a picture for me" at which point an image is captured and compressed, and then the Arduino receives the JPEG data through serial (slowly) and stores it on an SD card (also slowly). It can't do anything else with it.

To crunch those numbers - assume that the compressed VGA image from the camera's processor chip is 100,000 bytes (I took a typical photo, scaled it to 640x480 and saved it with 90% JPEG compression and it was roughly that size). At 9600 baud you get 960 bytes per second. 100,000 / 960 = 104 seconds.

That is how long it would take to transfer one single image through the Arduino.

If the camera has a higher speed UART, say 115200 baud (11520 Bps), that would then give you 100,000/11,520 = 8.7 seconds.

So no, using an Arduino to control cameras in that way just isn't possible.

Instead you need a system that can talk CSI-3 directly - something with a direct camera connection, such as the Raspberry Pi. Another alternative is any embedded computer with enough processing power and USB ports to connect cheap USB webcams to. Again the Raspberry Pi would do - especially the newer version 2 with the quad core processor.

---
Tags: arduino-uno
---


# Question
Title: Arduino Uno - why doesn't memory leak crash the program?
I wrote this test program:

```
void loop()
{
    digitalWrite(13,1);
    delay(300);
    digitalWrite(13,0);
    delay(300);
    void *a = malloc(10000000000000000000000000000000000000000);
}

```

Curiously, the LED keeps blinking and so it means the loops continues.

My question is how can it continue when it runs out of heap memory like that?

# Answer
> 3 votes
`malloc()` by itself generally doesn't *crash* a program. It attempts to allocate the requested amount of memory, and if it can it will. If it can't (there isn't enough memory available) then it won't allocate anything and will just return NULL.

By trying to allocate more memory than you have it will just fail every time and no memory will be allocated - thus you don't actually have a memory leak, so your program doesn't fail.

The main reason for crashing is a phenomenon called *stack smashing* where the memory area used by `malloc()` (known as the *heap*) and the memory area for the stack (used by local variables and for storing the contents of registers during function calls) collide with one another and one corrupts the other. For instance, if the *return address* of the current function in the stack is corrupted, when the function finishes it will return to the wrong memory location and who knows what may happen then? Wrong instructions will be executed for sure.

For instance, try this program out instead:

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

void loop() {
    char *a = (char *)malloc(10);
    if (a != NULL) {
        Serial.println("Allocated 10 bytes");
    } else {
        Serial.println("Allocation failed");
    }
}

```

If all goes well you should see lots of "Allocated 10 bytes" followed by some "Allocation failed". Since the memory is now full there is a chance that it may now crash as the stack and heap collide - in which case you would expect to see the "Allocation failed" messages stop.

# Answer
> 0 votes
Allocating memory doesn't really do much to it except for (typically) writing some bookkeeping information into its header - a portion the caller doesn't (isn't supposed to...) see. In particular, that bit of memory doesn't become unavailable for anything (other than further allocation).

Malloc maintains a buffer between the stack pointer location and the heap, from which it will not allocate. This tends to ( \<--- note "weasel words") prevent a heap vs. stack collision

If the stack grows down into memory that was already allocated, the stack will over-write the data in some allocated block. It is impossible to say what effect that will have on further program operation without knowing a whole lot more about the program, and quite possibly, about the contents and timing of any data that has yet to be received.

If the heap grows upward into the stack, and program writes into that allocated block, it will be over-writing parts of it's own stack with, again, unpredictable (without a lot more information) results.

A simple test program that merely allocates lots of small blocks will have a good chance of running forever, or at least until the `malloc()` call returns a NULL pointer when it is out of memory to allocate. At that point, if the test program is checking for the NULL return, there is a good chance the program can print its message and end normally. But if the program blindly writes into the memory `malloc()` returns, and writes through the eventual NULL pointer, then low-memory will get corrupted. Low memory is typically the location of the interrupt vector table (and the Arduinos' AVR processors are no exception), some interrupt is likely to get vectored to somewhere other than its proper service routine, and abnormal program operation will result; most likely, a crash.

---
Tags: memory-usage
---


title: Could not read ID via SWD with Arduino

text:
# Question
Title: Could not read ID via SWD with Arduino
So I'm trying to read a bit of data via SWD. I've tried two chips as target - LPC1110 and STM32F030F4 (the first of them I used for other schematic, but I've reset the flash to make sure the pins are not configured improperly).

I use Arduino as a host. I wire D3 to SWCLK and D4 to SWDIO (with pull-up to 3.3V line). I fail miserably with both chips - i.e. when I expect some ACK be read - it only shows HIGH state on the line all the time.

Here is my code. Could anyone have a look and tell where I went wrong:

```
int swdck = 3;
int swdio = 4;

void setup() {
  pinMode(swdck, OUTPUT);
  digitalWrite(swdck, HIGH);
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
  Serial.begin(9600);
}

// write some bits from X (least significant first) to SWD
void clockOut(int x, int bits) {
  pinMode(swdio, OUTPUT);
  while (bits > 0) {
    digitalWrite(swdck, LOW);
    digitalWrite(swdio, (x & 1) ? HIGH : LOW);
    delay(1);
    digitalWrite(swdck, HIGH);
    delay(1);
    bits--;
    x >>= 1;
  }
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
}

// read some bits from SWD, least significant first
int clockIn(int bits) {
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
  int i, res;
  res = 0;
  for (i = 0; i < bits; i++) {
    digitalWrite(swdck, LOW);
    delay(1);
    if (digitalRead(swdio) == HIGH) {
      res += (1 << i);
    }
    digitalWrite(swdck, HIGH);
    delay(1);
  }
  return res;
}

void loop() {
  int x;
  // unlock sequence though it probably is not needed
  clockIn(26); clockIn(26); // more than 50 clocks
  clockOut(0xE79E, 16); // command to switch to SWD
  clockIn(26); clockIn(26);

  clockOut(0x25, 7); // 0b0100101 - request to read Debug-port-0, i.e. ID
  x = clockIn(5); // there should be ACK bits somewhere... but I get 0x1111
  clockIn(26); clockIn(26); // perform more readings for case anything is returned
  Serial.println(x);
  delay(1000);
}

```

# Answer
I am not a SWD expert; it is several years since I read the spec. So I apologise if you are way ahead of me.

I believe ARM's SWD documentation, e.g. "ARM® Debug Interface v5 Architecture Specification" (ARM IHI 0031A) says that transfers are fixed length, starting with an 8 bits request.

The code:

```
void clockOut(int x, int bits) {
  pinMode(swdio, OUTPUT);
  while (bits > 0) {
    ...
    bits--;
    ...
  }
  ...
}

```

is invoked with `clockOut(0xE79E, 16)`

A packet request is 8 bits, followed by a response from the target. So this doesn't appear to follow the protocol.

Similarly `clockOut(0x25, 7)` appears to send 7 bits, which also looks wrong, and may explain why the read fails.

Further, there should be a 'turnaround bit' after sending the packet.

This code:

```
void clockOut(int x, int bits) {
  pinMode(swdio, OUTPUT);
  ...
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
}

```

looks like it is setting up to do that, however, it also needs to signal another clock pulse, e.g.:

```
void clockOut(int x, int bits) {
  pinMode(swdio, OUTPUT);
  ...
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
  /* signal a clock pulse */
  digitalWrite(swdck, LOW);
  delay(1);
  digitalWrite(swdck, HIGH);
  delay(1);
 }

```

A SWD read should return 33 bits, so `x = clockIn(5);` looks a bit fragile.

Even so, it should get the three ACK bits. It should leave another pile of bits unread, which is what I mean by fragile.

However, `x = clockIn(5);` might be incorrect because of the short `clockOut(0x25, 7)` and lack of a turnaround bit.

Small points:

* I'd change that `clockOut` `while` loop to be a `for` loop like `clockIn` to make it clear that it is running for a specific 'count' (bits) of bits to be transferred.
* `delay(1)` seems to be a long time between bits. I don't remember any timing restrictions. However, I would expect the transfers to run 10-100x faster.
* IMHO `clockIn(26); clockIn(26);` seems to be an unnecessarily obscure way to generate the 50 cycle connection/reset sequence. I'd probably have a slightly simpler function than `clockIn` which only generates the connection/reset sequence.

Edit:
The statement `res += (1 << i);` in `clockIn` works.

However, I had to read it a couple of times to recognise that it is assembling a binary value, and not doing some tricky arithmetic. It is more common to use bitwise operators to assemble a binary value. It is only a small point of style, however `res |= (1 << i);` might be more clearly constructing a binary value, than `res += (1 << i);` because it can only ever effect one bit, and never many bits.
> 1 votes

---
Tags: programming
---


title: Cheap 2-5mb memory to use with arduino

text:
# Question
Title: Cheap 2-5mb memory to use with arduino
I'm looking for a storage solution for small files that would be moved into a small sensor running arduino-like processor.

Ideally the single memory unit would be cheap (in 1-10 cents range), but the memory can be very limited (several megabytes).

The closest I've got so far is small SD Memory card, but the smallest 4GB ones cost several dollars (at least bought in quantities \< 100). Anything else I should be looking at?

# Answer
I assume that, if this is a cost sensitive item, you need a reliable supply of multiples (so looking for small SD cards on e-bay isn't a viable solution).

Does it need to be non-volatile storage? If it does't you may be able to find small 8-bit wide RAM chips at a pretty good price. If it needs to be non-volatile, you might look at individual flash chips. I found this one, an 8-bit by 512 KB Serial-SPI flash chip for £0.19 (about $0.28 US) in single units and £0.176 if you can by 100 at a time. I would expect DRAM chips and chips with a simpler interface to be less expensive (but you might end up spending more on interfacing the chips so it might end up as a wash).

If you're able to consider a variety of processor chips it might be worth looking for something that has adequate storage on chip. That might be the most cost effective way to get the space.
> 1 votes

# Answer
On ebay you can buy 2nd hand Nokia SD cards from old mobile phones which are 128MB or so and very cheap.
> 0 votes

---
Tags: flash
---


# Question
Title: How can I reference an object from another file?
I am trying to write some code to make it easy to add different buttons to a touch screen. I need each object to be a different object of class 'touchButton'. I'd like to be able to run a `touchButton.Draw` function, which in turn will run LCD library commands. Is there a way I could do that? Here is my source code:

TouchScreen.ino:

```
#include "touchButton.h"
#include <UTFT.h>
#include <UTouch.h>
#include <avr/pgmspace.h>
UTFT    myGLCD(ITDB32S, 38, 39, 40, 41);
UTouch  myTouch( 6, 5, 4, 3, 2);
extern uint8_t SmallFont[];

void setup() {
  myGLCD.InitLCD();
  myGLCD.setFont(SmallFont);
  myGLCD.clrScr();
  myTouch.InitTouch();
  myTouch.setPrecision(PREC_MEDIUM);
  myGLCD.fillScr(51, 51, 51);
  //what I want to be able to do:
  //touchButton Button1 (10, 10, 20, 20, 'p');
  //Button1.Draw();
}

void loop() {
}

```

touchButton.h

```
#ifndef touchButton_h
#define touchButton_h
#include "Arduino.h"
class touchButton {
  public:
    touchButton(int x, int y, int xs, int ys, char use);
    void Draw();
    int x1;
    int y1;
    int xsize;
    int ysize;
    char use;
    boolean toggle = false;
};
#endif

```

touchButton.cpp

```
  #include "Arduino.h"
  #include "touchButton.h"
  touchButton::touchButton(int x, int y, int xs, int ys, char myuse) {
    x1 = x;
    y1 = y;
    xsize = xs;
    ysize = ys;
    use = myuse;
  }

  void touchButton::Draw() {
    switch (use) {
      case 'p':
      //this is what I would like to have called from the main file.
      //myGLCD.drawRoundRect(x1, y1, x1+xsize, y1+ysize);
        break;

       default:
        break;
    }
  }

```

# Answer
> 2 votes
The best way is to provide the myGLCD object as a parameter to the constructor:

```
touchButton::touchButton(UTFT &glcddev, int x, int y, int xs, int ys, char myuse) {
  x1 = x;
  y1 = y;
  xsize = xs;
  ysize = ys;
  use = myuse;
  glcd = &glcddev;
}

```

Then in your header you provide a:

```
private:
  UTFT *glcd;

```

Your library code then uses the glcd pointer to the object:

```
glcd->drawRoundedRectangle(...);

```

Note the use of `->` since `glcd` is a *pointer* to the object (as created by the `&` operator when it was assigned in the constructor).

Of course, as Miagma mentions, you need to ensure that anywhere that references any UTFT functions or objects has the UTFT.h header included or it won't know what you're talking about.

You can also do the same with the UTouch class - pass that object as a parameter, then each widget can have its own routine to deal with the touch events.

You can see all this kind of thing in action in the same context in the Widget class of my DisplayCore system for chipKIT boards:

# Answer
> 2 votes
The simplest solution (ignoring possible improvements) is to add the following to touchButton.cpp.

```
#include "Arduino.h"
#include "touchButton.h"

// Extern reference to the LCD instance
#include <UTFT.h>
extern UTFT myGLCD;

touchButton::touchButton(int x, int y, int xs, int ys, char myuse) {
  x1 = x;
  y1 = y;
  xsize = xs;
  ysize = ys;
  use = myuse;
}

void touchButton::Draw() {
  switch (use) {
    case 'p':
      myGLCD.drawRoundRect(x1, y1, x1+xsize, y1+ysize);
    break;

   default:
    break;
  }
}

```

There are several improvements such as passing the UTFT instance reference as parameter, moving myGLCD to a separate .h/.cpp file, etc.

An example of "extern" object reference may be found in HardwareSerial.h.

Cheers!

# Answer
> 0 votes
I'm not 100% certain I understand what you mean. It's clear that you understand object-oriented code and some of the murkier aspects of c++, judging from what you wrote.

I apologize if you already know this (and I'm guessing you do) or if this is completely off base, but your code should already work. That is, you defined your class in your header, implemented it in the .cpp file, and then instantiated it in the .ino file. If you want to operate on it in another file, you could declare the variable as an "extern" data type, which is rather dangerous, or pass it as a reference to a function in another file.

However, I don't believe this is what you mean. From reading your code, I feel that you're asking how you can execute function "x" from another object every time you create a button.

If this is the case, it's definitely possible. myGLCD looks like it's an object (can't read it at the moment), which is good. What you can do is declare your touchLCD class as a derived class of whomever myGLCD belongs to -adding the appropriate header of course:

```
#include <Parent Class Name.h>

class touchLCD : public <Parent Class Name>.

```

If the functions you want are public or protected, then you can access them without restriction. Here you have a few options. The easiest would probably be calling the function from within the constructor. If you don't have access to the desired function, you'll have to define your class as a friend class.

Hope this helps.

# Answer
> 0 votes
You are asking a question that can be considered as the classical:

"is a" vs. "has a"

If you want, you can find more details here.

On this specific case, I sort of agree with Majenko, that proposes to pass the address of the LCD object to each button, but I would prefer a different implementation where the pointer is stored in a static field shared by all the instances of touchButton, because you are always referring to the same object. That will of course change if you have more than 1 LCD.

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


# Question
Title: Re-use smartphone/tablets parts like a camera
For learning and hacking purposes, I plan to study and use parts from smartphones and tablets like Galaxy or iPhone. They are really efficient and pretty cheap...

Did anybody do this before? If yes, can anybody tell me what kind of connector is this one on the galaxy camera, Galaxy Tab S 10.5 Front Facing Camera (Wi-Fi), and whether it can be found for attaching it to an Arduino project?

Edit: Someone else asked a similar question here, How to reuse quality camera from old / broken phone.

# Answer
The connector on the flex circuit from that camera was made by Hirose (it has an HRS logo on it), and might be in the BM10, BM14, or BM20 series. You can measure the pin spacing, stacking height, etc. to check which series it's in. For example, the Hirose BM14 series of FPC to board connectors has pins at 0.4 mm Pitch and 0.8 stacking height.

Mouser.com carries a 24-pin BM14 connector that might mate or match with the pictured connector. For other photos of Hirose FPC connectors, see google images for **hirose fpc**.

While you probably can find a matching connector (via careful measurement and perhaps some trial and error) and build an interface, it may be difficult to use the camera once it's hooked up. Most Arduino models have too little RAM to support image processing. A Yun might do it, a Tre, or some other micro entirely, eg Beagle or Raspberry.
> 9 votes

# Answer
*(summary of comment thread)*

I **strongly recommend** against trying to use any of these smartphone camera replacement parts. While they are cheap, this is because the signal they output is nigh impossible for you to use, even if you knew its specifications, which is unlikely given proprietary parts often have proprietary, non-public protocols. Even if you did have it, you'd likely have to implement a linux kernel extension for Raspberry Pi yourself to support it. Far more work than it's worth.

If you actually want to do image processing, there is a clear recommendation: **the Raspberry Pi camera interface**. RasPis have a special flex socket on the board for a camera, and you can buy cameras which work with the `raspivid` etc. commands included in raspbian with no extra setup. This allows you to use OpenCV or similar image processing libraries, or write your own, without having to worry about bitbanging obscure camera protocols.

No-name camera boards can be bought from eBay or similar sites for less than US$20, and they support 30fps 5 MP image/video capture to the Raspberry Pi natively and easily. Just search for "Raspberry Pi camera".

### *However...*

If you're *really* sure you're up to the challenge of hacking a proprietary camera module, you'll want to do thorough research finding the exact protocol specifications for these camera chips first, and try to find ones that are the most common, for the highest chance of compatibility, and likelihood of others having made progress on using them. Good luck!
> 3 votes

---
Tags: hardware
---