# Question
Title: Does an I²C IO Expander needs additional resistors for outputs?
I have following setup (see also schematic in the end)

Arduino Nano is connected via I²C to the PCF8575C (link) IO Expander. Both, SCL and SDA have 10kOhm pull-ups to 5V. The Expander pins are connected to a MOSFET-driver that turns on/off 12V LED stripes. The Expanders Bus address is set via Expanders A0-A2 pins to 0 (0x20). The MOSFET driver pins have to be pulled to logic 1 (above 2.2V) in order to turn on the stripe.

Currently Arduino runs an blink example, that turns all Expander IO pins on/off every second (using Arduino Wire Library), but the **MOSFET-driver does not turn on/off any Stripe.**

I can manually turn on Stripes by connecting MOSFET-driver pins to Arduinos 5V (or 3.3V)

The power supply to the IO Expander is O.K.

By measuring the resistance between GND and IO pins of the Expander, I can see that it alternates every second (so I²C communication to the Expander works also)

**Curious thing:** While measuring this resistance (holding the multimeter test leads) to GND and to the IO pin of Expander, the MOSFET-driver turns the Stripes on and off! When I take the test leads away it stops working! **Magic?!**

**What am I missing?** Do the output pins of the PCF8575C need some extra pullup/pulldown resistors or something else?

Thank you in advance!

Schematics:

# Answer
Yes, according to the datasheet (which should always be your first port of call for any chip) the outputs are Open Drain. That means you require a pullup resistor, exactly as if the outputs were simple buttons.
> 2 votes

# Answer
Think of the oped drain output (or open collector) as a pin that connects to ground when the device is on. If you connect the anode of an LED to plus and connect the kathode to the open drain pin, then you do not need a pull-up resistor (you may need a current limiting resistor though)

The test leads of the Ohmmeter produce a current to masure resistance, it also provides a current path to ground if the that's where you placed one of the leads. This would explain the **Magic**

More here about open collector outputs.
> 0 votes

---
Tags: i2c, pins, communication, mosfet, pull-up
---


title: GSM and NFC not working together

text:
# Question
Title: GSM and NFC not working together
I have an Arduino Uno board, Seeed Studio NFC shield v2.1 and, an Arduino GSM shield stacked UNO -\> NFC -\> GSM, therefore, all the wires are going into pins in the GSM.

I have successfully created a program that measures various sensors on my attached breadboard and then prints them to serial and sends text depending on conditions. I have today added the NFC shield to the middle of the stack (so as to avoid unplugging all the pins in the GSM), now when I run any NFC program, the default ones provided on the serial I get the message "Didn't find PN53x board". However, if I unplug the GSM from on top of it the NFC programs run fine, reading and writing tags.

Is it just that the NFC and GSM will not work together or am I missing something.

Main code

```
// Include the GSM library
#include <GSM.h>

#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess;
GSM_SMS sms;

int buttonPin = 13;
int buttonState = 0;
int buttonPressed = 0;
int trigPin = 11;
int echoPin = 12;
long duration, cm, inches;
int greenLED = 6;
int redLED = 8;
int buzzerPin = 10;

int pressurePin = A5;
int force;

const int inputPin = A0;
unsigned int inputSample;
const int inputWindow = 100;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(inputPin, INPUT);
  startUp();
  //setupText();

}

void loop() {
  button();
  delay(100);
  if (buttonPressed == 1)
  {
    pressure();
  }
  else if (buttonPressed == 2)
  {
    distance();
  }
  else if (buttonPressed == 3)
  {
    sound();
  }
  else if (buttonPressed == 4)
  {
    pressure();
    distance();
    sound();
  }
}

void sound()
{
  // two variables for minimum and maximum values in window
  unsigned int inputMax = 0;
  unsigned int inputMin = 1024;

  // loop for the window
  for (unsigned int i = 0; i < inputWindow; i++)
  {
    // read in a single value
    inputSample = analogRead(inputPin);
    // get the minimum and maximum value
    inputMin = min(inputMin, inputSample);
    inputMax = max(inputMax, inputSample);
  }
  // send the values on serial
  Serial.print("Min: ");
  Serial.print(inputMin);
  Serial.print("  Max: ");
  Serial.print(inputMax);
  Serial.print("  Diff: ");
  int Diff = inputMax - inputMin;
  Serial.print(Diff);
  Serial.println();
  if (Diff > 30)
  {
    alarm();
    sendText();
  }
  delay(250);
}

void pressure()
{
  force = analogRead(pressurePin);
  Serial.print("The force is: ");
  Serial.println(force);
  delay(250);
  if (force > 400)
  {
    alarm();
    sendText();
  }
}

void distance()
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  int echo = pulseIn(echoPin, HIGH);
  int trig = pulseIn(trigPin, HIGH);
  Serial.println(duration);
  Serial.println(echo);
  Serial.println(trig);
  cm = (duration/2) / 29.1;
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  delay(100);
  if (cm < 5)
  {
    alarm();
    sendText();
  }
}

void alarm()
{
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,300);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,300);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,300);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,300);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
}

void button()
{

  buttonState = digitalRead(buttonPin);

  if (buttonState == HIGH)
  {
    buttonPressed ++;
    digitalWrite(greenLED, HIGH);
    noise();
    delay(2000);
    digitalWrite(greenLED, LOW);

  }

  Serial.println(buttonPressed);
}

void startUp()
{
  digitalWrite(greenLED, HIGH);
  noise();
  digitalWrite(greenLED, LOW);
  delay(500);
  digitalWrite(greenLED, HIGH);
  noise();
  digitalWrite(greenLED, LOW);
  delay(500);
  digitalWrite(greenLED, HIGH);
  noise();
  digitalWrite(greenLED, LOW);
  delay(500);
  loop();
}

void noise()
{
  tone(buzzerPin, 1000);
  delay(1000);
  noTone(buzzerPin);
}

void sendText()
{
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("MESSAGE SENT");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    delay(4000);
//  char remoteNum[20];
//  Serial.println(remoteNum);
//  // sms text
//  char txtMsg[200];
//  Serial.println("SENDING");
//  Serial.println();
//  Serial.println("Message:");
//  Serial.println(txtMsg);
//
//  // send the message
//  sms.beginSMS("07123456789");
//  sms.print("HELP");
//  sms.endSMS();
//  Serial.println("\nCOMPLETE!\n");
}

void setupText()
{
  // initialize serial communications and wait for port to open:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("SMS Messages Sender");

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      notConnected = false;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized");
}

```

Code to be added when at a later date

```
#include <SPI.h>
    #include "PN532_SPI.h"
    #include "PN532.h"
    #include "NfcAdapter.h"

    PN532_SPI interface(SPI, 10); // create a PN532 SPI interface with the SPI CS terminal located at digital pin 10
    NfcAdapter nfc = NfcAdapter(interface); // create an NFC adapter object

    void setup() {
        Serial.begin(9600); // begin serial communication
        Serial.println("NDEF Reader");
        nfc.begin(); // begin NFC communication
    }

    void loop() {

        Serial.println("\nScan an NFC tag\n");
        if (nfc.tagPresent()) // Do an NFC scan to see if an NFC tag is present
        {
            NfcTag tag = nfc.read(); // read the NFC tag into an object, nfc.read() returns an NfcTag object.
            tag.print(); // prints the NFC tags type, UID, and NDEF message (if available)
        }
        delay(2000); // wait half a second (500ms) before scanning again (you may increment or decrement the wait time)
    }

```

Edit: Added code

# Answer
> 2 votes
You have a resource conflict between your breadboard sensors and the NFC shield.

```
int buttonPin = 13;    <= This is SCK
int trigPin = 11;      <= This is MOSI
int echoPin = 12;      <= This is MISO
int buzzerPin = 10;    <= This is chip select

```

You will have to use different pins for your sensors.

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


# Question
Title: what is the right way to parse JSON to Arduino?
i am trying to Turn an LED from a hosted website, though Arduino using the CC3000 wifi shield. It is working as it should. but i have to questions about optimising my code :

1) the Part where i parse my JSON is kind of sloppy, what is the right way to Parse the code so i can turn the LED on and off when clicking on the website buttons ?

2) i need to keep the arduino connected to the website, so i can always control the LED. Do i need to close the connection at the end ? if so, how can i activate the connection only when clicking the button on the website to active the LED.

```
#include <ArduinoJson.h>

// Include Libraries
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>

// Define Pins
#define ADAFRUIT_CC3000_IRQ   3
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10

// Define Variables
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER);

#define WLAN_SSID       "MyWeb"
#define WLAN_PASS       ""
#define WLAN_SECURITY   WLAN_SEC_UNSEC // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2

uint8_t dhcpTimeout;

#define host "mygarden.comli.com" // Your domain
uint32_t ip;
String path   = "/light.json";
int port = 80;

int pin = 9;

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

  pinMode(pin, OUTPUT);
  pinMode(pin, HIGH);

  // Connect to Wifi
  cc3000.begin();
  Serial.println(F("Initialising the CC3000"));
  if (!cc3000.begin())
  {
    Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
    while(1);
  }

  /* Delete any old connection data on the module */
  Serial.println(F("Deleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  // Connect to Network
  beginning:
  Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID);
  cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY);
  Serial.println(F("Connected"));

  //Wait for DHCP to complete
  Serial.println(F("Requesting DHCP"));
  while (!cc3000.checkDHCP()) {
    delay(500);
    Serial.print(F("."));
    dhcpTimeout ++;
    if (dhcpTimeout == 60) {
      Serial.println(F(""));
      Serial.println("DHCP Timeout! Attempting to reconnect.");
      dhcpTimeout = 0;
      goto beginning;
    }
  }
  Serial.println(F(""));
  Serial.println(F("DHCP complete"));

  //get website IP
  ip = 0;
  Serial.print(host); Serial.print(F(" -> "));
  while (ip == 0) {
    if (! cc3000.getHostByName(host, &ip)) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }
  cc3000.printIPdotsRev(ip);
  Serial.println("");
}

void loop(void) {

  Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);

  client.print(String("GET ") + path + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: keep-alive\r\n\r\n");
  delay(500); // wait for server to respond

  Serial.println(F("----------"));
   while (client.connected()) {
    String response = "";
    bool begin = false;
      while (client.available() || !begin) {
      char c = client.read();
      if (c == '{') {
        begin = true;
      }
      if (begin) response += (c);
      if (c == '"}') {
        break;
      }
      delay(1);

      }
      int start = response.indexOf("light\":\"") + 12;
      int end = start + 3;
      String LED_Control = response.substring(start, end);

      if (LED_Control == "onn") {
        digitalWrite(pin, HIGH);
        Serial.println("LED ON");
      }
      else if (LED_Control == "off"){
        digitalWrite(pin, LOW);
        Serial.println("led OFF");
      }

   }

  delay(1000);
  Serial.println(F("\n\nClosing the connection"));
  client.close();
  cc3000.disconnect();

}

```

And this is my JSON output

```
{"light": "off"}

```

# Answer
> 3 votes
Assuming that `String response` will contain the json `{"light": "off"}` and your program is ready to use the ArduinoJson library (`#include <ArduinoJson.h>` on top), a simple solution could be:

**Step1** \- declare and initialize `StaticJsonBuffer` object.

```
StaticJsonBuffer<80> jsonBuffer;

```

**Step2** \- deserialize the json from `response`.

```
JsonObject& root = jsonBuffer.parseObject(response);

```

**Step3** \- if the deserialization doesn't succeed, warn and break,

```
if (!root.success())
{
  Serial.print("parseObject(");
  Serial.print(response);
  Serial.println(") failed");
  break;
}

```

**Step4** \- otherwise, use json object to get the `LED_Control`.

> Is the json will really contain `{"light": "onn"}` or is a typo ?

```
String LED_Control = root["light"];

if (LED_Control == "onn") {  // 'on' or 'onn' ??
    digitalWrite(pin, HIGH);
    Serial.println("LED ON");
}
else if (LED_Control == "off"){
    digitalWrite(pin, LOW);
    Serial.println("led OFF");
}

```

# Answer
> 0 votes
If the response from the web server is just a boolean value, the 'right' way would IMHO be to return e.g. just a 0 and 1 instead of JSON encoded data. That saves you from parsing JSON on the Arduino completely. Instead you can simply read one character of the response and check for '0' or '1'.

HTTP is a request-response based protocol and not suitable for staying connected to the server. If you need immediate reaction from the Arduino to server-side changes and your web server supports WebSockets, you could use any of the WebSocket libraries for the Arduino. Otherwise, you can use HTTP and poll the web server at a set interval to get the current value of the switch. And if you don't implement HTTP keep-alive, you will have to close the TCP connection and make a new connection for each HTTP request.

---
Tags: arduino-uno
---


# Question
Title: arduino web client uploading data to mysql database
I have got this quick sketch that post data to mysql db using php add.php module.

```
#include <SFE_BMP180.h>
#include <SPI.h>
#include <Ethernet.h>
#include<dht.h>
dht DHT;

// You will need to create an SFE_BMP180 object, here called "pressure":
SFE_BMP180 bmp;

#define DHT11_PIN 2

double tempInC;
int humidity;

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);
char server[] = "192.168.1.3";

EthernetClient client;
byte php_server[] = {192 , 168 , 1 , 3};

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000; // READING INTERVAL

String data;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  if (bmp.begin()) {
    Serial.println("BMP init Success");
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }

  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");
  data = "";
}

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  char status;
  status = bmp.startTemperature();
  if (status != 0) {
    delay(status);
    status = bmp.getTemperature(tempInC);
  }
  else Serial.println("error retrieving temperature measurement\n");

  humidity = DHT.humidity;
  data = "?temp1=" + String(tempInC) + "&hum1=" + String(humidity);

  if (client.connect(server, 80)) {
    Serial.print("connected. My IP is ");
    Serial.println(Ethernet.localIP());
    client.println("POST /arduino/add.php HTTP/1.1");
    client.println("Host: 192.168.1.3");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.print(data);
  }
  else {
    Serial.println("connection failed");
  }
  Serial.println(data);
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
  if (client.connected()) {
    client.stop();  // DISCONNECT FROM THE SERVER
  }
  delay(300000); // WAIT FOR A WHILE BEFORE SENDING AGAIN
}

```

but its not updating the database, using the below **add.php** file from arduino **web-client.ino**

```
<?php
        include("connect.php");

        $link=Connection();

        $temp1=$_POST["temp1"];
        $hum1=$_POST["hum1"];

        $query = "INSERT INTO `tempLog` (`temperature`, `humidity`)
                VALUES ('".$temp1."','".$hum1."')";

        mysql_query($query,$link);
        mysql_close($link);

        header("Location: index.php");
?>

```

i checked in mysql prompt which is also the result displayed if I open the server url : 192.168.1.3/arduino/index.php

```
mysql> select * from tempLog;
+---------------------+-------------+----------+
| timeStamp           | temperature | humidity |
+---------------------+-------------+----------+
| 2016-11-28 11:50:37 |           0 |        0 |
| 2016-11-28 12:30:25 |           0 |        0 |
+---------------------+-------------+----------+
2 rows in set (0.00 sec)

```

I don't know how the first entry got created but second one I created by manually executing the url 192.168.1.3/arduino/add.php?temp1=26.64&hum1=18

the index page is showing he data from db as shown above in sql, that means connection is established and mysql and table is fetched from correct db. i.e. *arduinoSensorData* in my case.

my serial monitor window got updated:

```
BMP init Success
connecting...
connected. My IP is 192.168.1.131
?temp1=26.64&hum1=18
connected. My IP is 192.168.1.131
?temp1=26.64&hum1=18
connected. My IP is 192.168.1.131
?temp1=26.57&hum1=18

```

which means arduino is not able to put data to db using add.php

# Answer
I came to learn in my php code posted above, I am using `$_POST` variable when I should rather be using `$_GET`

In the PHP script, there are $\_GET and $\_POST variables that contain the data passed to the script, depending on the method used to to activate the script.

so using `$temp1=$_GET["temp1"];` and `$hum1=$_GET["hum1"];` fixes the problem.
> 1 votes

---
Tags: arduino-uno, ethernet
---


# Question
Title: What programming practices should be adopted while coding sketches for Arduino?
What are some of the best programming practices that can be adopted while coding sketches for Arduino, so that it uses the least memory and performance should not suffer from memory outage, and still the code be robust?

From the link: https://www.arduino.cc/en/Products/Compare

I have learned that the Uno has 32 KB of Flash memory. The maximum available is in the MEGA with 256 KB. I think Uno and Mega are the most widely used by people.

# Answer
> 5 votes
Paul covered the most important points. This answer is intended to be a complement to his.

First, you should keep in mind the general rules, which are more important than the more specific ones. The general rule for saving RAM is: be aware of what you are storing, and do not store anything you do not really need. The general rule for saving flash is: be aware of what you are doing, and do not do anything you do not really need.

Now, a few specific tips:

Use the `const` qualifier for declaring constants (e.g. `const int ledPin = 13;`). The compiler will optimize-out the storage of the constant and use immediate addressing instead.

Use `PROGMEM` for arrays of constants.

Whenever possible, use static memory (globals and `static` locals) rather than heap allocation (`malloc()` and `new`). This will prevent memory fragmentation and make the memory usage more predictable (only the stack holds dynamic memory): you know at compile time, rather than run time, whether you are low in RAM.

For the same reason, prefer C strings (`char *`) over `String` objects.

Use the C99 types `int8_t` and `uint8_t` whenever 8 bits are enough for your integer variables.

Use the `static` qualifier for functions that will be used only in the same source file, especially for functions that are called only from one place. This gives the compiler more optimization opportunities.

If you need to optimize, use `avr-nm` to know what is consuming your precious RAM.

# Answer
> 3 votes
Keep in mind that RAM is even less. 32KB is a fair lot of code, since C/C++ is highly efficient. "Don't save \**** in RAM."

If you need to load images into a display, save the images on an SD card. And "stream" it to the display. You can read and transmit the bytes one by one, or 10 by 10 or something.

Also, if you need long strings, you can use the "flashStringHelper" to store the string in flash memory. For example: `println(F(”Error message: Couldn't connect to server));`. By using `F()` around the string, you save valuable bytes.

Not using Arduino code, but pure AVR-C/C++, can save you a little also. (Will also save the bootloader piece of memory, if you program directly with a programmer.)

If you use Arduino, know how it works. The Arduino serial library uses ~256 or 500 bytes (I believe) as a buffer. You can change this if you need it for other applications.

Keep in mind that your saving technique depends on what resources are low. If you need to do a lot simultaneously, it's better to write non-blocking code.

But also remember: Don't optimize unless it's actually needed! Or, actually set measurable and realistic requirements, optimizing something to be "as fast as possible" can take infinite amounts of time... Run a google search on "premature optimization" as the old folks in the field like to call it.

---
Tags: programming, c++, sketch, flash, sketch-size
---


title: Data acquisition/logging question

text:
# Question
Title: Data acquisition/logging question
I want to use an Arduino Uno for a data-acquisition purpose.

Normally adhoc data acquisition boards can record each sample at a desired sampling rate. So that I can plot all the samples recorded. I want to do the same sort if thing with Arduino.

I want to record 30 minutes of analog voltage input at 4kHz sampling rate and record all the samples taken to a PC.

And at the end I want to be able to plot the data with all samples not the averages ect.

Is there an easy workaround for this?

# Answer
Here is a program I wrote that follows an approach somewhat similar to Michael Stachowsky's answer:

* The ADC is configured with the prescaler set to 128 (just like the Arduino core does), which gives a 104 µs conversion time, significantly shorter than the 250 µs sampling period you want. The first conversion takes longer, and it is discarded.
* It is also configured an auto-trigger mode, and the timer 1 overflow flag is selected as its trigger source.
* The timer 1 is configured to loop every 500 × 8 = 4000 CPU cycles (clocked at F\_CPU / 8, with TOP = 499), which provides the required 250 µs sampling period. It is set in a PWM mode even though the PWM outputs are not used, simply because in this mode the overflow flag is set every time the timer loops.
* An interrupt is triggered every time an ADC conversion is complete. The interrupt service routine clears the timer overflow flag (this is required because the ADC is triggered by the rising edges of this flag), saves the result in a global variable and sets a global flag.
* The main loop waits for that flag and sends the data through the serial port, in binary, LSB first:

+ the sample number modulo 64 (6 bits)
    + the sample value (10 bits).
* The serial port runs at 115.2 kb/s, it can then transmit the two bytes of data in about 174 µs, which is less than the sampling period.
* The sample numbers, and a 16-byte preamble can be used as a sanity check by the receiving end.

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

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

    // Transmit preamble.
    for (int i = 0; i < 16; i++)
        Serial.write(0xff);

    // Start the ADC.
    ADMUX  = _BV(REFS0)   // reference = Vcc
           | 0;           // input = ADC0
    ADCSRA = _BV(ADEN)    // enable the ADC
           | _BV(ADSC)    // start first conversion
           | _BV(ADPS0)   // prescaler = 128,
           | _BV(ADPS1)   // ditto
           | _BV(ADPS2);  // ditto

    // Wait for the first conversion to complete.
    loop_until_bit_is_set(ADCSRA, ADIF);

    // Wait for the preamble to be fully transmitted.
    Serial.flush();

    // Stop timer 1.
    TCCR1A = 0;
    TCCR1B = 0;

    // Configure the ADC in auto-trigger mode.
    ADCSRA |= _BV(ADATE)   // enable auto-trigger
            | _BV(ADIF)    // clear interrupt flag
            | _BV(ADIE);   // enable interrupt
    ADCSRB  = _BV(ADTS1)   // trigger source = timer 1 overflow
            | _BV(ADTS2);  // ditto

    // Configure Timer 1.
    ICR1   = 500 - 1;     // period = 500 * 8 CPU cycles
    TCCR1A = _BV(WGM11);  // mode 14: fast PWM,
    TCCR1B = _BV(WGM12)   // ... TOP = ICR1,
           | _BV(WGM13)   // ... overflow flag set on TOP
           | _BV(CS11);   // clock at F_CPU / 8
}

volatile uint16_t reading = 0xffff;
volatile bool reading_available;

ISR(ADC_vect)
{
    TIFR1 |= _BV(TOV1);    // clear timer overflow flag
    uint16_t x = reading;  // work on a copy of the reading
    x &= ~0x03ff;          // remove previous ADC value
    x |= ADC;              // add current ADC value
    x += 0x0400;           // increment sample number
    reading = x;
    reading_available = true;
}

void loop()
{
    // Wait for a reading to be available.
    while (!reading_available) ;

    // Grab a copy.
    uint16_t x = reading;
    reading_available = false;

    // Transmit, LSB first.
    Serial.write(x >> 0);  // low byte
    Serial.write(x >> 8);  // high byte
}

```

How you deal with the data on the receiving end (save to file, skip preamble, check sample number consistency, extract sample values, plot them...) is up to you. You can use whatever language and tools you want. It is *not* an Arduino-related question.

**Addendum**: More about the binary format used.

There is a preamble consisting of 16 `0xff` bytes. This can be useful because it is not uncommon to get in one file a mix of data from two different runs of the program. The buffering of the serial port on the PC can lead to this happening. If you do not want that preamble, remove the two lines right after the “Transmit preamble.” comment.

Then there is a continuous stream of 16-bit unsigned integers (`uint16_t`), transmitted LSB first (i.e. little endian). The byte order can be changed by swapping the two `Serial.write()` by the end of the program.

Each of these integers contains an ADC reading in the lower 10 bits and a sample number in the upper 6 bits. The sample number can be extracted by right-shifting (`x >> 10` in C) and could be used as a sanity check (the number should increment by 1, modulo 64, from one sample to the next). The ADC reading can be extracted by masking out the sample number (`x & 0x03ff`).

If you do not want the sample numbers, you can simplify the ISR to:

```
ISR(ADC_vect)
{
    TIFR1 |= _BV(TOV1);    // clear timer overflow flag
    reading = ADC;         // read the ADC result
    reading_available = true;
}

```

and remove the (now useless) initialization of the `reading` variable.
> 1 votes

# Answer
This question is actually two or three different questions.

To the first: is it possible to record 30 minutes of data with an arduino uno at 4KHz: no. Assuming even that you are only taking 1 byte of data at a time, the uno only has 2K of RAM, so you'd be out of RAM in under a second.

To the second: can you instead send this data to a PC at the desired rate: possibly, depending on how much data you are taking. If it's just a single analog channel, then you can most likely do it. Anything more and I doubt it. The problem is that you'll simulutaneously have to read the analog at the correct time AND send the data to the PC, presumably over the serial. As long as you use Serial.write, NOT Serial.print, then your UART should be more than fast enough at high baud rates to handle a single channel with minimal overhead. However, that would mean that you have to reconstruct the data on the PC, but that's the third question, to which I shall turn shortly.

If you need absolute real-time operation, then you need to use timer interrupts, which are not native to the Arduino libraries, if I recall correctly. However, a quick google for "Arduino timer interrupt" leads me here: http://playground.arduino.cc/Code/Timer1, which is where you should start.

In terms of plotting the data: that's not an Arduino problem, that's a problem for whatever you choose to use to collect and analyze your data. I suggest Excel, since it's relatively common, or Google Sheets, since it's free. If you have access to Matlab, though, that's a much more powerful program. Either way, that is off topic for this forum.
> 0 votes

---
Tags: datalogging
---


title: Using 2D servo array in my class

text:
# Question
Title: Using 2D servo array in my class
I need to use a servo library in my class.
I read this question - Use object of other class within class and it works fine for my LCD application, but now I need to use a 2D servo array in my class. I made one approach, it worked, but I think it is bad programming approach, what is right way to solve my problem?

1. My main file

```
#include <SoftwareServo.h>
SoftwareServo servo[5][5];
Servolib Servoarray;

void setup(){
  blah blah blah

```
2. My cpp file

```
#include "Vending.h"
#include "Arduino.h"
#include <SoftwareServo.h>

Servolib::TurnSevo(){
  for(int row=0;row<5;row++){
    for(int collum=0;collum<5;collum++){
      servo[row][collum].attach(Object[row][collum]);
      servo[row][collum].write(0);
    }
  }
}

```
3. my .h file

```
#ifndef Vending_h
#define Vending_h
#include "Arduino.h"
#include <SoftwareServo.h>

class Servolib:SoftwareServo{
public:
  void TurnServo();

private:
  SoftwareServo servo[5][5];
  int Object[5][5]={
    {42,21,20,19,18},
    {37,41,36,38,35},
    {31,33,30,34,39},
    {67,28,66,29,65},
    {56,63,55,64,54}
  };
};
#endif

```

So this code worked, but please give me better solution.

# Answer
You can indeed use pointers, but passing multi-dimensional arrays is a bit of a pain in C(++).

There's a pretty good explanation here.
> 0 votes

---
Tags: servo, array, class
---


# Question
Title: How does Arduino determine whether the given condition provided to it is true or false?
I want to understand how does the microcontroller determine that the conditions provided to it in the input are true or false. eg:

```
if (someVariable > 50)
{
  // do something here
}

```

Then how does Arduino determine if the value that I put in \`somevariable' is larger than 50 (as apposed to less than or equal to 50)?

# Answer
In general terms comparisons are usually performed, at the low level of assembly language, using subtraction.

In assembly language when you perform a subtraction there are flags in the status register that may or may not get set depending on what has happened. These include the Zero flag and the Carry flag.

If you are comparing A to B then you subtract B from A and see what happened by examining the flags.

For instance, if your variable contains 30 and you compare it to 50 you subtract 50 from 30. Because the result "passes through" zero the Carry flag is set. You can then do a "Jump if Carry Set" call.

If you should have 50 in your variable and you compare it to 50 the subtraction ends up with the Zero flag set since the result is exactly zero. It is then possible to do a "Jump if Zero Set" call.

If you have 60 in your variable and compare it to 50, the subtraction results in 10, which doesn't set either flag. That is actually slightly harder to work out (depending on architecture) since you are then wanting to compare two flags (Carry and Zero) and see if neither of them are set. So it is common for the compiler to optimize it so that the condition is reversed (`a > b` is the same as `!(a <= b)` for instance).

Of course, some architectures have actual comparison instructions (often `CMP`) which compares two registers and sets or clears the different flags for you. For instance, the ATMega328P has the instructions:

* `CPSE` \- Compare, Skip if Equal
* `CP` \- Compare
* `CPC` \- Compare with Carry
* `CPI` \- Compare Register with Immediate

`CPI` would be the most logical choice in the example you give - compare the contents of a register (variable) with an "immediate" value (an "immediate" value is a constant value):

```
CPI $r3, 50

```

According to the instruction set manual the comparison is, surprise surprise, performed as a subtraction, and what happened during the subtraction sets the different flags. To make life simpler the instruction set has a number of branch instructions which look at the different flag combinations and jump to another address if they match:

* BRLT - Branch if the result of the previous comparison was A \< B
* BRLE - Branch if the result of the previous comparison was A \<= B
* BRGT - Branch if the result of the previous comparison was A \> B
* BRGE - Branch if the result of the previous comparison was A \>= B
* BREQ - Branch if the result of the previous comparison was A == B
* BRNE - Branch if the result of the previous comparison was A != B

There are more as well for other special comparisons. You can read up all about them in the AVR instruction set manual.
> 7 votes

# Answer
Just to complement Majenko's answer with an example, I tried the following:

```
volatile int someVariable;
void do_something_here();

void foo()
{
    if (someVariable > 50)
    {
      do_something_here();
    }
}

```

and the compiler generated the following assembly (comments mine):

```
foo:
    lds r24, someVariable      ; load variable into registers, LSB
    lds r25, someVariable + 1  ; and MSB
    sbiw r24, 51               ; subtract 51
    brlt .L1                   ; if (result < 0) goto .L1
    jmp do_something_here      ; do_something_here()
.L1:
    ret                        ; return

```

The `sbiw` instruction means "subtract immediate from word". It subtracts a 6-bit immediate value from a 16-bit value contained in a register pair (r25:r24 in this case). It is one of the very few 16-bit instructions of this mostly 8-bit CPU.

As you see, the compiler did some optimization and changed the code to something looking more like:

```
if (!(someVariable - 51 < 0))
{
    do_something_here();
}

```

It is also worth noting that the `brlt` instruction (branch if lower than) tests the sign flag of the status register, which is the exclusive OR of the negative flag (result \< 0) and the overflow flag. This way the result of the comparison is correct even if the subtraction overflows.

Note also that this is only an example. The generated assembly would be different if you use another type than `int` (a wider or smaller or unsigned integer), or an explicit constant greater than 62.
> 5 votes

---
Tags: programming
---


# Question
Title: Arduino Simulator for Windows that can be detected by Arduino IDE through a Virtual COM Port
Hello is there an Arduino Simulator for Windows that can be detected by Arduino IDE through a Virtual COM Port?

I've seen simulator online but I can't seem to find a simulator that can be programmed using the Arduino IDE through a Virtual COM port.

# Answer
> 2 votes
One of the option is using Proteus simulator with Arduino library. You can build the program via Arduino IDE, then export the compiled binary (.hex file). Proteus also provided virtual terminal feature (not Virtual COM).

---
Tags: arduino-uno, arduino-mega, simulator
---


# Question
Title: Can a motherboard be a simple circuit between arduino uno and a set of devices (ie: motors)
**Reason for question:** My son is working on a project to build a robot controlled by an arduino uno. This question is more about terminology than process, but since terms are very important at this level, I rather ask some expert advice - I have not found any input on the internet about this!

**Question:** What is the correct technical name (if any) of the circuit board that acts as the interface between the arduino-uno (a micro-controller) and the motors (the external devices)? According to the definition of a motherboard\*, this "interface" circuit board would act as a very basic motherboard, as it would "allow communication" between the components, but it would not contain expansion slots, so should it be called something else?

**Background on project:** The robot will be very basic. A body will be made of plastic legs and motors for joints; an Arduino-uno will provide the logic for motor movement; and a custom circuit board (hence my question) will act as the interface between the uno and the motors, providing electricity from a dedicated source to the motors.

We are just missing the proper terminology to use for this "interface" board and I cannot find any concrete info online or on books. If I get good terms in this post, then we can do further research on those terms. Thanks.

https://en.wikipedia.org/wiki/Motherboard

# Answer
I would call it an "interface" or "driver" board. You don't need to get too hung up on the exact name.

The word "shield" is one of the Arduino-peculiar words (like "sketch" for "code") which now has a generally-understood meaning. That meaning is, something that plugs directly onto the Arduino board, with the pins on the shield matching the sockets on the Arduino board.

Whilst a shield is a quick and easy way of getting started (because you don't need to wire anything) they can have their disadvantages. One being, what if you want two different functions, like a motor driver and an Ethernet interface? Two shields, one on top of the other? What if they both use a certain pin for different purposes?

I made up a radio-controlled car, see photo:

The only shield I used was a generic "put whatever you want onto it" shield, which let me mount some MOSFETs, a radio receiver board, and other components, as required by the design. There is a Uno underneath it, not particularly easy to see. Adjacent on the right is a motor driver board. A LiPo battery is slung underneath.

This kept things reasonably compact, without requiring a specific purpose-made shield which only does one thing.

> and a custom circuit board (hence my question) will act as the interface between the uno and the motors, providing electricity from a dedicated source to the motors.

It sounds like your project is similar to my car. Just assemble things in a way that makes sense to you.
> 1 votes

# Answer
In the Arduino ecosystem these boards are called 'shields'.

Arduino describes a shield as:

> Shields are boards that can be plugged on top of the Arduino PCB extending its capabilities.

For example, there is an Arduino Motor Shield which sounds very similar in purpose to the board that your son is making.
> 0 votes

# Answer
"Interface board" works as a general term, as @alex had mentioned already.

The word "motherboard" would work if it's larger than each of the components that plug into it.

The word "daughter board" would work if it's smaller than what it plugs into.

Please don't use the word "shield" when referring to extension boards, interface boards, daughter boards, and such. The word "shield" in this connection was popularized by Arduino marketing. (More detailed discussion about "shield" in connection with Arduino.)
> -1 votes

---
Tags: arduino-uno, motor, shields, hardware, electronics
---


# Question
Title: Arduino - stepper motor wrong steps number
I just bought a new stepper motor (400 steps for revolution, 0.9°/step) and I would like make a turn of 180° by 200 steps, but it doesn't work as expected. It looks like the motor needs only 110 steps to make a turn of 180° and I don't know the cause. The driver motors is the Keyes L298. It is wired to my Arduino UNO rev3.

In order to clarify, please see the image below:

The code is as follows:

```
#define negativeSteps -55
#define positiveSteps 55
#define Speed 7500

int motorPin1 = 11;
int motorPin2 = 10;
int motorPin3 = 9;
int motorPin4 = 8;

int steps;
unsigned int tmp2;

byte modeR[] = {B00001001, B00001010, B00000110, B00000101};
byte modeF[] = {B00000101, B00000110, B00001010, B00001001};

void setup() {

  Serial.begin(115200); //Opens serial connection at 115200 baud.

  pinMode(11,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);

  pinMode(3,OUTPUT);    // Enable pin motorA
  pinMode(2,OUTPUT);    // Enable pin motorB

  digitalWrite(2,HIGH);
  digitalWrite(3,HIGH);
}

void loop()
{
    while (Serial.available())
    {
      char cmd = (char)Serial.read();
      if (cmd == 's')   while(1) Seek();
    }
}
void motorR(){
  int bitMask=B00001111; // bitmask to modify only last 4 bit

          for (int id = 0; id <4; id++) {
            PORTB = (PORTB &~bitMask) |  modeR[id];
            while (tmp2++<Speed);
            tmp2=0;
          }
}
void motorF(){
  int bitMask=B00001111; // bitmask to modify only last 4 bit

          for (int id = 0; id <4; id++) {
            PORTB = (PORTB &~bitMask) |  modeF[id];
            while (tmp2++<Speed);
            tmp2=0;
          }
}
void Seek() {
  steps = negativeSteps;      //Init Steps
  while (1)
  {

    while (steps<positiveSteps) //  starts from "negative" steps to "positive" steps ( -55 to +55)
    {
       if (steps<0) motorF(); // if steps = 0 it will change the direction
       else motorR();

      Serial.println(steps);
      steps++;
   }
 }
}

```

# Answer
> 2 votes
You're driving the stepper too fast, unintentionally though.

The while loop you use to delay is likely optimized out by the compiler:

```
while (tmp2++<Speed);

```

Easiest way to fix would be to declare **tmp2** as a *volatile* variable when you declare it up in the top of your program. Thusly:

```
volatile unsigned int tmp2;

```

This will inform the compiler that **tmp2** might possibly change at any time and not to optimize it away. It's more complicated than that really, but it'll fix your issue in a single tweak.

Better, would be to use the **delay()** function, to pause execution for some specified **milliseconds**, much like you're attempting to do with the empty while loop.

You're using an UNO, so probably running at 16Mhz, so your delay of 7500 loops is technically about 5 instructions long, multiplied by 7500... so 37,500 instructions executed, and at approximately 16,000,000 instructions per second, that's (37500/16M) that's about 2.34 milliseconds. So maybe a **delay()** of 3-5 milliseconds would be useful.

Basically, you're trying to step the motor too fast, and it can't keep up. Mass, inertia and all that stuff are involved too.

Try replacing the while statements with delays, start with big delays (25 or so), and work lower as long as stepper motion is consistent. As you said, 200 steps **should** be 180°.

replace:

```
while (tmp2++<Speed);

```

with:

```
delay(Speed);

```

and change **Speed** to an appropriate value (25 or so to begin with, play with it!).

There are many improvements to your code which could be discussed, but you need to crawl before you walk, before you run. Get THIS code working, then finesse it.

---
Tags: motor, stepper, l298n
---


# Question
Title: RFM69HCW 915 MHz radio module: Sending a stream of int values rather than char[ ]
I'm trying to send a stream of int values (0-4096) from one arduino to another using an RFM69HCW module.

Here's my main code:

```
#include <RFM69.h>
#include <SPI.h>
#define NETWORKID     0   // Must be the same for all nodes
#define MYNODEID      1   // My node ID
#define TONODEID      2   // Destination node ID
#define FREQUENCY     RF69_915MHZ
#define ENCRYPT       true // Set to "true" to use encryption
#define ENCRYPTKEY    "TOPSECRETPASSWRD" // Use the same 16-byte key on all nodes
#define RFM69_CS      10
#define RFM69_IRQ     2
#define RFM69_IRQN    0  // Pin 2 is IRQ 0!
#define RFM69_RST     9
#define IS_RFM69HCW   true
#define USEACK        true // Request ACKs or not
#define LED           9 // LED positive pin
#define GND           8 // LED ground pin
#define PULSEPIN      0 // Heart Rate Monitor at pin A0

RFM69 radio = RFM69(RFM69_CS, RFM69_IRQ, IS_RFM69HCW, RFM69_IRQN);
String pulsearray;
bool recHR = true;
unsigned long oldtime = 0;
int interval = 5000;
static int readtime = 3000;
static int sampletime = 10; // 1000/this is the thing
static int txinterval = 1000; // delay between transmissions

void setup() {
  initSerial();
  initLed();
  initRadio();
}

void loop() {
  unsigned long newtime = millis();
  if (!recHR && newtime - oldtime >= interval) {
    recHR = true;
    oldtime = newtime;
    Serial.println("recording HR now");
  }

  while (recHR) {
    unsigned long newtime = millis();
    if (newtime - oldtime >= sampletime) {
      readhr();
    }
    if (newtime - oldtime >= readtime) {
      recHR = false;
      oldtime = newtime;
      Serial.println("stopped reading HR");
    }
  }
}

```

And the function I'm using:

```
void readhr() {
  for (int i = 0; i < 20; i++) {
    int pulse = analogRead(PULSEPIN);
    pulsearray = pulsearray + pulse;
    pulsearray = pulsearray + '\n';
    Serial.println(pulse);
  }
}

```

The library function sendWithRetry() requires the following arguments:

```
bool RFM69::sendWithRetry(uint8_t toAddress, const void* buffer, uint8_t bufferSize, uint8_t retries, uint8_t retryWaitTime)

```

**I would like a way to set up a buffer which can be transmitted in multiple packets during the 5 second analogRead() downtime.** Using a string as my buffer doesn't work when I try to transmit the first n (\<60) characters in the String. I've also tried using a char\[ \] as my buffer (a lot more troublesome when storing int values) but it still gives the same error:

```
exit status 1
no matching function for call to 'RFM69::sendWithRetry(int, String&, unsigned int)'

```

# Answer
You need to send the address of a buffer and the size, in bytes, of that buffer. What that buffer consists of is neither here nor there.

If you have an array of 10 ints you have a 20 byte buffer (since one int is 2 bytes on an 8-bit Arduino).

So you just pass it the address of the buffer (which as an array it is already just an address) and the size of that buffer:

```
int values[10];
// whatever to fill the array
RFM69::sendWithRetry(20, values, 20, 4, 1000);

```

As long as the array is statically created (e.g., a global variable with a fixed number of entries) you can use `sizeof()` to get the size in bytes:

```
RFM69::sendWithRetry(20, values, sizeof(values), 4, 1000);

```

As long as you receive at the other and using the same type of buffer it should be completely transparent.

To keep the system cross-platform and able to run on an Arduino that is either 8 or 32 bits and have them completely interoperable it is best to use variables with a fixed size. Instead of `int` use `int16_t` which is always 2 bytes and signed on every platform everywhere:

```
int16_t values[10];

```

Or use `uint16_t` if you want it unsigned.
> 0 votes

---
Tags: string
---


# Question
Title: Alternative distance-meter, HC-SR04 doesn't work very well
On door to my room there is HC-SR04 that triggers led-wave. The shorter the distance, the faster the led-wave (8 leds).

The circuit works fine in synthetic tests – moving hand or flat object towards the sensor generates gradually accelerating wave.

However, when placed on door to detect approaching persons it generates short correct (\<=170 cm) impulses and the wave starts and immediately stops, again starts, etc. I guess HC-SR04 isn't good enough to detect people.

Are there any alternatives to this sensor that will correctly detect human approaching?

# Answer
Try to find where the error comes from.

I suggest loading up a piece of code that outputs the measurements to through the serial terminal.

* You should typically filter out any values that are \> 200cm (since it's out of range).
* You should take the average of a few readings, to be more accurate and less error-prone.
* Find why some readings are weird, is the object fuzzy (may absorb the ultrasound)?

If all fails, you may look at IR distance sensors (SHARP) like:

https://www.adafruit.com/product/164

or

https://www.adafruit.com/product/1568

Alternatively, you could use a combination of (multiple) IR and ultrasonic sensors. But I doubt you really need that mount of accuracy.

You could also go for a Raspberry Pi + camera and openCV, but that's a whole other matter.
> 0 votes

# Answer
In general the HC-SR04 is controlled using `pulseIn()`.

When there is nothing within range for the sensor to detect it usually has to wait for `pulseIn()` to time out. That can take up to a second by default. While that is happening the rest of the sketch cannot do anything.

You can reduce the timeout in the `pulseIn()` function, but it's still not going to be perfect - you'll still get a delay which will interrupt your LED sequences.

The ideal way will be to create a "free running" distance sensor system - use a timer to periodically start a ping, and use the Input Capture module of the ATMega to measure the time between the start and end edges of the returning pulse. Everything will happen asynchronously to the rest of your sketch then.

I am not aware of any libraries for Arduino boards, but I have one for the PIC32 based chipKIT boards that I use. It can't ever work on AVR based boards, but you can use it to see the general concepts and how things fit together.
> 1 votes

---
Tags: sensors, hc-sr04
---


# Question
Title: How time intensive or how long can an ISR be?
I would like to code my ISR to be time intensive or interrupt the main program for atleast 1 or more seconds. My goal is to verify that if I am reading a sensor in the main loop, would it stop reading the sensor when the code is interrupted and for how long. I have trying to call various functions from the ISR like to turn on the motor but everything is instantaneous.

# Answer
> How long can an interrupt be?

If you don't want anything else to happen, then as long as the time between successive interrupts.

> would it stop reading the sensor when the code is interrupted and for how long.

While the interrupt is running nothing else can happen in software. Absolutely nothing. Only one thing ever happens at once - either your main loop or the interrupt. For the entire duration of your interrupt everything else is put on hold.

That includes things that rely on other interrupts to function, such as serial communications, `millis()` and `delay()`, etc. That means using such functions from within your interrupt handler is a big no-go.

It is generally very very bad practice to have an interrupt blocking for more time than absolutely necessary (a few milliseconds or even less). If you need to have things taking a long time then you should consider breaking them down into smaller operations and doing different sections at different times through different means.
> 2 votes

# Answer
Does the delay() function not work for you? It should halt all other processing, whether in ISR or not; so if you call it inside your ISR, your ISR would remain active for as long as the delay.

Of course, ISR should **not** be long like this. Perhaps there is a better way to code your test. Perhaps a variable that the sensor-reading code checks; if it's set to 1, don't read the sensor, and if it's 0, it's okay to read the sensor, etc.
> -2 votes

---
Tags: arduino-uno, interrupt, isr
---


# Question
Title: Arduino Sending faster/more data to a web server
I'm working on a project that reads vibration on a building using an accelerometer and displaying it's data on a web server. The plan is to read 10 samples/second from the accelerometer and send that data every 5 seconds to a web server using arduino yun.

So there would be 10(samples/sec) x 5(seconds) x 3(3 axis - x,y,z) = 150 data points that will be sent to the webserver, I tried this with the client.get() command but it cannot send that much data to a web server, I also tried POST request but i've had trouble with the sending it multiple times since it needs to have a delay.

What are the other options that I can do in order to achieve this? Any suggestion would help and please if you think my question is bad or not stated properly don't report me, I'm still new here in stack exchange. Any help/suggestion is much appreciated

## Arduino Code for POST request

```
#include <Bridge.h>
#include <HttpClient.h>
#include <YunClient.h>

//IPAddress server(192,168,1,200);
byte php_server[] = {192,168,1,9};

YunClient client;
String data = "", datax="", datay="", dataz="";
unsigned long ts_0 = 0, tr_0 = 0, t_read = 100;
int counter=0;

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

}

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

  if((millis()-tr_0>=t_read)) {

    if(counter<49) {
      counter++;
    }
    else if(counter == 49) {
      //Serial.print("sent");
      String dat = "0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12";

      send_to_ws(dat);
      Serial.println(dat);

      counter = 0;
    }
    tr_0=millis();
  }
}

void send_to_ws(String data) {
  if(client.connect(php_server, 80)) {
    Serial.println("Connected");
    client.println("POST /arduino/add.php HTTP/1.1");
    client.print("Content-Length:");
    client.println(data.length());
    Serial.println(data.length());
    Serial.println(data);
    client.println("Connection: Close");
    client.println("Host:192.168.1.9");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println();
    client.println(data);
  } else {
    Serial.println("Connection error");
  }
}

```

Serial monitor output when running this sketch, It prints it in the serial monitor but only blank data is being pushed in the database of the server

# Answer
> 1 votes
Option 1. Send a single message from the client to the server. This message should contain all 150 points of data.

Option 2.
Send the data in a format other than as a string. Base64 encoding of the raw numeric values would be ideal, but its going to add extra load to the CPU. Depending on the range of the data (0-359) and the resolution (use 2 DP) you might be able to use just 4 bytes for each data point. Because you are using a fixed length value to represent each point you no longer need separators in you data so a single reading goes from 21 bytes to 12 bytes.

Option 3. Hand off the data to a second processor that is dedicated to sending the data. The Yun would write the data into a shard circular buffer and the other processor (possible another Yun or an ESP8266) would read the data from the buffer, convert it and write it to the server.

I can't say which is best, because I don't know enough about you system, but if you could expand on your details we should be able to narrow it down.

---

After reading you answer above. If you ranges are 0-10 with two DPs then I would look at option 2 first. If each reading can range from -9.99 to +9.99 you take the absolute value and multiply by 100 and write that as a 2 digit hex number to your message body.

```
uint8 number = ((reading < 0) ? 0x80 : 0x00);  // Set the high bit for negative.
number += (abs (reading) * 100);
messageBodyString += String (number, HEX);

```

That will give you 2 bytes per point, and a 300 byte (+overhead) message should be transferable within 5 seconds.

---

Here is some quick code to explain the encoding and decoding

```
unsigned int Encode(const float& value)
{
    unsigned int result = (value < 0) ? 0x80000000 : 0x00000000;// Work out and set the sign bit
    result |= (unsigned int)abs(value * 100.0);             // Get the absolute value (ignore sign) and multiply
    return result;
}

float Decode(const unsigned int& value)
{
    const bool isNegative = ((value & 0x80000000)  != 0);       // Get the sign bit
    float result = (float)(value & 0x7FFFFFFF);                 // To remove the sign bit
    result /= 100.0;                                            // Divide to return to the original number of dps.
    if (isNegative)
        result = 0 - result;
    return result;
}

```

# Answer
> 1 votes
Personally for this kind of frequency of data I wouldn't even consider sending it via HTTP. The extra bulk of the HTTP protocol makes the transfer way too slow.

Instead I would set up a UDP-based gateway server which accepts UDP messages from your sensor system and stores the data directly into the database (or wherever you are storing the data) for the website to display it at its leisure.

Yes, it is more complex to create since you need to write the UDP server gateway software. However you then completely remove the massive overheads of a text-based bulky protocol like HTTP.

# Answer
> 0 votes
You can use 2d Array for this and send all data at once in 5 Sec. It Read all 3 Axis data each 100Ms and make a matrix of 50 X 3 = 150 Values and then Print it in Serial Port. You can use this in your code to send data to server in desirable format.

```
int Xaxis=A0;
int Yaxis=A1;
int Zaxis=A2;
int axisMatrix[50][3];
void setup(){
    Serial.begin(9600);
    pinMode(Xaxis,INPUT);
    pinMode(Yaxis,INPUT);
    pinMode(Zaxis,INPUT);}

void loop(){
        for (int i = 0; i <= 50; i++) {
            axisMatrix[i][1]=analogRead(Xaxis);
            axisMatrix[i][2]=analogRead(Yaxis);
            axisMatrix[i][3]=analogRead(Zaxis);
            delay(100);}
        for (int i = 0; i <= 50; i++) {
            Serial.print(axisMatrix[i][1]);
            Serial.print(",");
            Serial.print(axisMatrix[i][2]);
            Serial.print(",");
            Serial.print(axisMatrix[i][3]);
            Serial.print(",");
            Serial.print("\n");
        }}

```

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


# Question
Title: Is the analogread function averaging the samples taken by the ADC?
In many development boards the analog voltage data which is sampled by the ADC can be sent to the serial port. But the data speed I see on the serial port by HyperTerminal or Serial monitor is much slower than the sampling rate.

Lets take Arduino as an example. As far as I understand the analogread() function samples an analog input at 10kHz rate. It means 10000 samples taken per second.

But when I use the Serial Monitor it seems the data speed which we see as upcoming/flowing line by line per second on Serial Monitor is much slower.

Is that because the analogread() is averaging the samples before the data is sent to the serial port?

# Answer
> 4 votes
If you have a loop that calls analogRead() to take a reading, and then serialPrint() to send the reading, each pass through the loop will take at least the sum of the time for those two functions calls together.

When you first call serialPrint(), it returns in uS, as it doesn't actually *send* data, but puts it into the 64 deep transmit buffer, to be sent in the background. If the transmit buffer is emptying slower than you are filling it (at 9600 baud, it's sending roughly one character per mS, so you can send at most 100 off 10 character messages per second) then eventually when called, it will find not enough space in the transmit buffer for the whole message, and will *Block*, that is not return, until there is enough space. Each call to serialPrint() will now take 10mS (assuming 10 characters at 9600 baud). That's what slows your loop down.

To send faster, choose a higher baud rate, and reduce the number of characters in the message.

# Answer
> 4 votes
> As far as I understand the analogread() function samples an analog input at 10kHz rate.

No, it samples an analog input at *once per invocation*. This means that if it is run 10000 times within a second (assuming it can be run that many times within a second) then *the code* is sampling at 10kHz. But if it's run only twice per second then the code is sampling at 2Hz.

---
Tags: adc, serial
---


# Question
Title: `servo.attach()` paralyzing (one) motor on L298N
I have 2 DC motors (well, 4; but each pair is controlled by the same "signals") connected via a L298N, which is connected to the Arduino. In addition, I have a servo motor connected to the Arduino.

---

When I run the following program (in reality, it's a bigger program; however, I've managed to chiseled it down to the following):

```
#include <Servo.h>

const int servoPin = 3;
Servo servo;

const int LMotorsSpeedPin = 5;
const int RMotorsSpeedPin = 10;
const int LMotorDirectionBit1Pin = 7;
const int LMotorDirectionBit2Pin = 6;
const int RMotorDirectionBit1Pin = 8;
const int RMotorDirectionBit2Pin = 9;
const int MotorSpeed = 150;

void setup()
{
  // 1
  pinMode(servoPin, OUTPUT);
  servo.attach(servoPin);

  // 2
  pinMode(LMotorsSpeedPin, OUTPUT);
  pinMode(RMotorsSpeedPin, OUTPUT);
  pinMode(LMotorDirectionBit1Pin, OUTPUT);
  pinMode(LMotorDirectionBit2Pin, OUTPUT);
  pinMode(RMotorDirectionBit1Pin, OUTPUT);
  pinMode(RMotorDirectionBit2Pin, OUTPUT);

  // 3
  digitalWrite(LMotorDirectionBit1Pin, LOW);
  digitalWrite(LMotorDirectionBit1Pin, HIGH);
  analogWrite(LMotorsSpeedPin, MotorSpeed);

  // 4
  digitalWrite(RMotorDirectionBit1Pin, LOW);
  digitalWrite(RMotorDirectionBit1Pin, HIGH);
  analogWrite(RMotorsSpeedPin, MotorSpeed);

  // 5
  delay(10000);
}

void loop() {}

```
* `1` Sets up servo.
* `2` Sets up L298N pins.
* `3` Sets up left motor data.
* `4` Sets up right motor data.
* `5` Tests the code above for 10 \[s\].

---

I assume that you'll need some experience with the L298N; however, here's the gist.

`*MotorsSpeedPin` sends each motor what speed (`MotorSpeed` 0-255) they must go (via PWM). Data into a pair of `*MotorDirectionBit*Pin` tell each motor what direction to go (i.e. back `01`, stop `00` `11`, right `10`).

---

When I run the program above, only the left motor runs. However, if I comment out `1` (which essentially renders the servo useless), both left and right motors start to work.

I find this problem quite odd. What does the servo code have to do with the motor code (and only one at that!)?

# Answer
> 4 votes
The Servo library uses Timer 1 to create the servo control signal. That means it can run the servo on any pin or combination of pins, and at the 50Hz speed that a servo likes best.

However, pins 9 and 10 also use Timer 1 to create the PWM signal.

It can't do both.

As soon as you start using the Servo library you lose PWM on pins 9 and 10.

So what can you do about it? Simply move your pins around to different pins. You can't use 9 and 10 for PWM, but you can use them for the servo. So put your servo on pin 10 and your right motor speed control on pin 3 and all should be happy.

---
Tags: arduino-uno, motor, servo, debugging, l298n
---


title: How to make battery last for months?

text:
# Question
Title: How to make battery last for months?
I have a simple circuit: detect that a person is walking towards the circuit (with HC-SR04), measure distance, light diodes (a wave effect) according to that distance – the closer, the faster the led wave.

When no person detected, sleep longer:

```
LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);

```

When person detected, sleep shorter (so that diodes can be often turned on/off):

```
LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF);

```

Without LowPower use – `delay()` used instead – the current taken is `15 mA`. This is with diodes off. After using LowPower – it's still `~15 mA`. This is very disappointing. I've expected the battery to last at least for 3 months, but it (9V) was drained within hours. Am I missing something?

Also a curiosity: the execution was fully blocking itself on LowPower calls, I've had to add short `delay()` before the calls, then they don't block execution.

```
#include <LowPower.h>
#include <NewPing.h>

#define trigPin 13
#define echoPin 12

NewPing sonar(trigPin, echoPin, 250);

// Defines speed of LEDs traversal
int delayTime = 40;

// Current led
int currentLED = 0;

// Direction of travel over LEDs
int dir = 1;

// Stores the last time LEDs were changed
unsigned long timeChanged = 0;

// Stores the last time sensor was read
unsigned long timeOfQuery = 0;

// LEDs
byte ledPin[] = { 4, 5, 6, 7, 8, 9, 10, 11 };

// Stores if any diodes are on
int leds_used = 1;

// Stores if wave is active
int off = 1;

// 5 last distances, circular buffer;
long distances[7] = { 400, 400, 400, 400, 400, 400, 400 }, currentDistance = 0;

// Last chosen distance
long distance = 400;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  for (int x = 0; x < 8; x++) {
    pinMode(ledPin[x], OUTPUT);
  }
  timeChanged = millis();
}

void loop() {
  long duration, cur_time, cm;

  cur_time = millis();

  /* Read distance when off, or when some time passed */
  if (off || (!off && (cur_time - timeOfQuery) > 100)) {
    timeOfQuery = cur_time;

    cm = sonar.ping_cm();
    if ( cm == 0 ) {
      cm = 400;
    }

    distances[(++currentDistance) % 7] = cm;
    // At least 1 proper distance?
    off = 1;
    for (int i = 0; i < 7; i++) {
      if (distances[i] <= 200) {
        off = 0;
        // Remember minimum distance
        if (distances[i] < distance) {
          distance = distances[i];

        }
      }
    }
    delayTime = distance;
  }

  if (!off) {
    // Check whether it has been long enough
    if ((cur_time - timeChanged) > delayTime) {

      // Turn off all of the LEDs
      for (int x = 0; x < 8; x++) {
        digitalWrite(ledPin[x], LOW);
      }

      // Turn on the current LED
      digitalWrite(ledPin[currentLED], HIGH);

      // Mark that diodes are being used
      leds_used = 1;

      // Increment by the direction value
      currentLED += dir;

      // If we are at the end of a row, change direction
      if (currentLED == 7) {
        dir = -1;
      }
      if (currentLED == 0) {
        dir = 1;
      }

      // Store the current time as the time we last changed LEDs
      timeChanged = cur_time;
    }

    // Shorter delay when sleeping
    delay(5);
    LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF);
    //delay(50);
  } else {
    if (leds_used) {
      // Turn off all of the LEDs
      for (int x = 0; x < 8; x++) {
        digitalWrite(ledPin[x], LOW);
      }
      currentLED = 0;
      dir = 1;
      leds_used = 0;

      // Store the current time as the time we last changed LEDs
      timeChanged = cur_time;
    }

    // Longer delay when sleeping
    delay(10);
    LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);
    //delay(200);
  }

  /*
    if (distance >= 200 || distance <= 0) {
      Serial.print(distance);
      Serial.println(" Out of range");
    }
    else {
      Serial.print(distance);
      Serial.println(" cm");
    }
  */
}

```

**Update**: The board is Arduino UNO.

# Answer
> 3 votes
The Arduino UNO always consumes current mainly because:

* it has 2 MCU, the ATmega328 which you can power down, and an ATmega16u2 for USB communication which is never powered down.
* in addition, the voltage regulator is permanently leaking some current

To be honest, I am surprised your UNO consumes *only* 15mA, on my boards, it is rather near 40-50mA.

Also, a 9V battery is probably the battery with the smallest charge capacity.

I would suggest you:

1. work on a breadboard with just the ATmega328,
2. power it with two 1.5V batteries (AA or AAA)
3. and run @8MHz

That should already reduce current consumption.

You may even try smaller MCU (e.g. ATtiny84A) which consumes less current than the ATmega328 in the same conditions.

Finally, I **highly recommend** Nick Gammon's blog on that topic. It includes many good tricks to help you with current consumption.

---
Tags: power, battery, hc-sr04
---


title: Lcd display shield, no characters

text:
# Question
Title: Lcd display shield, no characters
So, I've been trying to make an Lcd display shield I got from ebay to work with arduino. Using this very simple code:

```
#include <LiquidCrystal.h>

#define RSPin 8
#define EnablePin 9
#define DS4 4
#define DS5 5
#define DS6 6
#define DS7 7

#define LCDColumns 16
#define LCDRows 2

LiquidCrystal lcd(RSPin, EnablePin,DS4,DS5,DS6,DS7);

void setup()
{
  lcd.begin(LCDColumns, LCDRows); //Configure the LCD
  lcd.setCursor(0,0);
  lcd.print("Hello, World!");
}

void loop()
{

}

```

Actually I've tried several simple examples, checked pins physically to make sure I'm using the right order, But no luck. backlight is on, no characters at all. Am I missing something? Or should just contact the seller to send another shield.

# Answer
So, after some close inspection I noticed that the blue potentiometer wasnt soldered in correctly. Also, its needs to be turned quiet a lot to have some effect. Might replace it completely. But now it works!
> 1 votes

---
Tags: lcd
---


# Question
Title: How to send Multiple decoded IR signals in one script
My final goal is to use my Arduino microcontroller as an "automatic remote". For now I would like to know how to send decoded NEC protocols one after another in a script.

I am using the Nano V 3.0 with a IR led I salvaged from an old remote. I used a VS838 and a 338R IR receiving module to decode the signals, both work 100%

I know how to send one protocol in a loop.

e.g

```
#include <IRremote.h>

IRsend irsend;

void setup()
{
}

void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(0x10676897, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

```

I also know how to send the same protocol repetitively.

(Although it won't work in the loop I reckon it'll work in the final script)

e.g

```
#include <IRremote.h>

IRsend irsend;

void setup()
{
}

void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(0xFFFFFFFF, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

```

However, I would like to include `106722DD`, `10676897` ,`10678877` and send them in one single C++ Script.

I was thinking something like calling each script through a loop might suffice but I have no idea how to do it in C++

Any help will be appreciated.

# Answer
> 2 votes
I'm not 100% certain what you are asking, so sorry if there is superfluous info in here.

Given that:

```
void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(0x10676897, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

```

Sends a single command twice as one burst I think what you want to do is this:

```
void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(106722DD, 32);
        delay(40);
        irsend.sendNEC(10676897, 32);
        delay(40);
        irsend.sendNEC(10678877, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

```

If that works it could be generalised into:

```
// New function to send 'items' codes which are held in the array 'data'
void sendMulti (const uint8_t& items, const uint32_t* data)
{
    for (int i = 0; i < 2; i++)
    {
        for (uint8_t itemIndex = 0; itemIndex < items; ++itemIndex)
        {
            irsend.sendNEC(data[itemIndex], 32);
            delay(40);
        }
    }
    delay(5000); //5 second delay between each signal burst
}

void loop () {
    static const uint8_t MaxItems = 3;
    uint32_t  data[MaxItems] = {106722DD, 10676897, 10678877};

    sendMulti(MaxItems, data);
}

```

Then you could move onto reading the codes from serial or a network, etc.

---
Tags: c++, ir
---


title: How to use breakpoints for debugging

text:
# Question
Title: How to use breakpoints for debugging
Breakpoints are a great way to see how the compiler runs to your code. Now my question is, is there a possibility to use breakpoints when you debug your code?

# Answer
As noted in Majenko's answer, the Arduino IDE doesn't provide a breakpoint mechanism but Atmel Studio does support breakpoints.\[\*\]

However, if you have a switch and an LED, you can track the progress of your program in a way that provides some of the benefits of breakpoints. You would add a subroutine, say `BPReport()`, that via serial output or an LCD reports values of critical variables, then lights the LED and waits until the switch has been pressed and released, with debounce. Call your `BPReport()` routine whereever you want an unconditional breakpoint. For conditional breakpoints, you can have a routine `BPReportIf(cond)` which calls `BPReport()` if `cond` is true. If you don't want to output via serial, you might use several LEDs or an LCD, and you might use several switches if you want external break controls (for example, `cond` could be a test of one of the extra switches).

\[\*\] Some hardware debuggers modify downloaded code each time breakpoints are added, changed, or removed. That usage will wear out flash memory more rapidly than just occasionally downloading to it. If a chip has been heavily used for such debugging, don't use that chip in a production system.
> 9 votes

# Answer
Though Majenko his answer is correct there are some other options.

As to the real hardware debugging as stated by majenko I would say:

1. Install and use a real IDE, such as Atmel Studio or the arduino eclipse plugin called sloeber (I'm author), and
2. Use a full hardware debugger or hardware that has it on board like the Arduio zero or hardware using other debugging technology like the ESP8266 that allows USB debugging

An other debugging option from a completely different category is to organize your code so that decision logic (hardware independent) and action (hardware dependent ) are completely separated.

Then compile your sketch as a local program and debug the "decision logic" on your local machine. This method does not allow for "hardware debugging". This method also enables unit testing.

Note that your local machine is probably a 32 or 64 bitter and most Arduino's are 8 bitters which will result in differences in data types which is an extra attention point when using this method.
> 4 votes

# Answer
The Arduino-Debug library provides a simple on-target debugger for Arduino sketches. Debug command are added directly to the sketch. A debugger command shell is started on break-points and assertions.

The screen-shot above shows the example sketch run on an Arduino Mega with Serial output monitor used by application and Serial1 used for the debugger shell.

**Sketch Debug Commands**

* ASSERT(cond) Check assert condition. If false the debug shell is called. The sketch cannot continue.
* BREAKPOINT() The debug shell is called.
* BREAK\_IF(cond) The debug shell is called if the condition is true.
* CHECK\_STACK(room) Check that there is room (bytes) on the stack. If false the debug shell is called.
* DEBUG\_STREAM(dev) Use the given stream device for debug session. Typically Serial.
* OBSERVE(expr) Print the expression to the debug stream.
* OBSERVE\_IF(cond,expr) Print the expression to the debug stream if the condition is true.
* REGISTER(var) Register a variable for access from the debug shell. Debug Shell Commands

**Debug Shell Commands**

* *?VARIABLE* Print variable address and value.
* *@VARIABLE* Print pointer variable address and reference value.
* *backtrace* Print simple call-stack.
* *commands* Print list of commands (see also help).
* *data* Print contents of data area, i.e. global variables.
* *go* Leave debug shell and continue execution of sketch.
* *heap* Print contents of heap, i.e. dynamic allocated data.
* *help* Print list of commands.
* *memory* Print memory status.
* *quit* Stop sketch.
* *stack* Print contents of stack, i.e. call frames, arguments, return addresses.
* *variables* Print list of registered variables.
* *where* Print source code file and line where debug shell was called.

All debug shell commands can be abbreviated to single character commands. Please see the README for further details; installation details, example sketch and benchmarking.
> 4 votes

# Answer
Not in the Arduino IDE.

You need to:

1. Install and use a real IDE, such as Atmel Studio, and
2. Use a full hardware debugger

There is no provision for debugging through the UART/USB interface using the bootloader.
> 3 votes

---
Tags: debugging
---


# Question
Title: How does an 8bit MCU make use of data-types over 8bits?
how does an 8bit MCU handle 16bit output? How does an 8bit MCU store values higher than 8bits? I am using an attiny, on an adafruit trinket. and other 8bit MCUs. http://www.atmel.com/devices/attiny85.aspx I was doing some things with uint32\_t datatypes, when it hit me, that it would seem like uint32\_t would be an incompatible datatype. Even 2Byte data type like int seems peculiar. "int stores a 16-bit (2-byte) value" considering the MCU is 8bit.

I saw this link, that sounded like it would have more info, but its pages are incomplete. http://playground.arduino.cc/Code/DatatypePractices

So how does that work? How does an 8bit MCU make use of data-types over 8bits?

# Answer
The basic answer is that the processor does math in 8-bit chunks, so it takes more instructions than it would on a 32-bit processor.

A good answer is found in EE.SE
> 3 votes

# Answer
Actually a 1-bit MCU could be used to execute code (e.g. C/C++) with N-bit numbers. Not very fast as it will require *O(N)* operations for addition and subtraction.

To better understand this for the 8-bit AVR MCU used in Arduino I recommend reading the Instruction Set Description Manual, AVR/GCC Wiki and assembler code listings for some sketches. This will reveal the secret(s) behind this "alien technology/magic".

Cheers!
> 1 votes

---
Tags: arduino-uno, programming, arduino-ide, data-type
---


# Question
Title: Store floats in and reading them from flash
How do I store floats in flash and how do I read them from there? (I need a look-up table for pairs of float values.)

The storing part doesn't seem to be so difficult as this compiles:

```
PROGMEM float value1 = 1.23456;

```

But how do I read them? Do I need to copy them byte by byte to a float variable, or is there a better way? (I am using an Arduino ATmega 328p with 4-byte floats.)

# Answer
> 4 votes
There is a helper macro in avr-libc that is designed just for this purpose:

```
#define pgm_read_float_near(address_short) __LPM_float((uint16_t)(address_short))

Read a float from the program space with a 16-bit (near) address.

Note
    The address is a byte address. The address is in the program space.

```

Use it like:

```
PROGMEM float pi=3.141592653;  // constant value in flash
float diameter = 24.332154;    // variable user value

float circumference = diameter * pgm_read_float_near(&pi);

```

# Answer
> 2 votes
I realize that the OP asked about a single value, but I thought I'd add info on retrieving from an array.

```
const float pmdata[] PROGMEM = {1.0, 2.0, 3.0};

```

then retrieve thusly:

```
float val = pgm_read_float(&pmdata[idx]);

```

---
Tags: flash, float, arduino-mini
---


# Question
Title: Which library to choose? <Wire.h> or "Wire.h"?
I know that in C++, to include a library, you either put the library name in `<x>` or `"x"`. Now, I believe that this was because of a major change in the C++ language a some time ago.

Now, in Arduino, there are 2 types of `Wire` (I2C) library : `<Wire.h>` and `"Wire.h"`.

Which one is the right one?

I've seem people using both, and they both seem to work.

# Answer
> 4 votes
The proper distinction is exactly what paths are searched for the include files.

`<...>` searches the "system" paths, while `"..."` searches both the system an "local" paths.

From the GCC manual:

> **`-I dir`**
>
> Add the directory dir to the list of directories to be searched for header files. Directories named by `-I` are searched before the standard system include directories. If the directory dir is a standard system include directory, the option is ignored to ensure that the default search order for system directories and the special treatment of system headers are not defeated . If dir begins with `=`, then the `=` will be replaced by the sysroot prefix; see `--sysroot` and `-isysroot`.
>
> **`-iquote dir`**
>
> Search dir only for header files requested with `#include "file"`; they are not searched for `#include <file>`, before all directories specified by -I and before the standard system directories. If dir begins with `=`, then the `=` will be replaced by the sysroot prefix; see `--sysroot` and `-isysroot`.

Note that the Arduino IDE only uses `-I`, so there is little to no distinction between `<...>` and `"..."`.

Commonly the main usage of the distinction is to use `<...>` to include system or library headers, and `"..."` to include headers that are part of the actual sketch / application, since the "current directory" is automatically added as a local include path.

# Answer
> 4 votes
http://en.cppreference.com/w/cpp/preprocessor/include

```
#include <filename>

```

> The intent of this syntax is to search for the files under control of the implementation. Typical implementations search only standard include directories. The standard C++ library and the standard C library are implicitly included in these standard include directories. The standard include directories usually can be controlled by the user through compiler options.

```
#include "filename"

```

> The intent of this syntax is to search for the files that are not controlled by the implementation. Typical implementations first search the directory where the current file resides and, only if the file is not found, search the standard include directories as with (1).

So basically it's intent is to give some idea of where the file should be. I, myself use "" for files that are inside the directory of my program. And \<\> for files or libraries that are in my path or other external locations.

---

This question is also more related to programming in general as Arduino specific.

Also see: https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename

---
Tags: c++, i2c, library, wire-library
---


# Question
Title: Why can't my .cpp file have a class of the same name?
I made a new Arduino IDE `project ABC`, and am given `ABC.ino`. Then I create a `XYZ.h` and `XYZ.cpp`.

---

`ABC.ino`:

```
#include "XYZ.h"

void setup() {}
void loop() {}

```

`XYZ.h`:

```
#ifndef XYZ
#define XYZ

#include "Arduino.h"

class XYZ { };

#endif

```

`XYZ.cpp`:

```
#include "Arduino.h"
#include "XYZ.h"

```

---

When I try to compile this, I get some error:

```
In file included from sketch/XYZ.cpp:2:0:
XYZ:8: error: abstract declarator '<anonymous class>' used as declaration
 };
 ^
exit status 1
abstract declarator '<anonymous class>' used as declaration

```

---

However, when I rename my class to something other than the file name, like `XYZa`, the compilation succeeds.

---

**Why can't I have the same name class as the file?**

I've done C++ projects (independent of Arduino) via `Xcode` and `nano`, and this has never been a problem.

# Answer
> 2 votes
```
#define XYZ
...
class XYZ { };

```

After preprocessing, what do you think that ends up as?

# Answer
> 3 votes
```
#define XYZ

class XYZ { };

```

The first line tells the "C preprocessor" (called before C and C++ compilers) to replace `XYZ` with nothing everywhere it happens, hence after preprocessing, and before compiling, that code becomes:

```
#define XYZ

class  { };

```

This is where C++ compiler complains. It has nothing to do with your file name.

Among C and C++ programmers, it is commonly admitted that header files should be protected by macros named after the file name **including the extension**:

```
#ifndef XYZ_H
#define XYZ_H

```

If you use this practice, you won't have this problem anymore.

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


# Question
Title: How do I write the codes in #define in an IR Receiver circuit?
So I'm trying to turn an ON LED OFF or an OFF LED ON using a TV Remote. In the #define line, I write the hex code received from pressing the designated button on the TV remote. However, during compilation, an error saying `unable to find numeric literal operator 'operator""DE74847'` appears. I've scoured the web and can't come up with a solution.

```
#include <IRremote.h>
#include <IRremoteInt.h>
int ledPin = 13;
int IRPin = 3;

#define code1 0575

IRrecv irrecv(IRPin);
decode_results results;
void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn();
  pinMode(ledPin, OUTPUT);
}
void loop()
{
  if (irrecv.decode(&results))
  {
  unsigned int value = results.value;
  int ledState  = digitalRead(ledPin);
  switch(value)
  {
    case code1:
    if (ledState = HIGH)
    {
      digitalWrite(ledPin, LOW);
    }
    else
    {
      digitalWrite(ledPin, HIGH);
    }
    break;
  }
  }
  else
  {
    digitalWrite (ledPin, LOW);
  }
   unsigned int value = results.value;
  Serial.println(value);
    irrecv.resume();
}

```

Here's the code. Please help.

# Answer
> 3 votes
Your problem is that you don't know how to form hexadecimal numbers.

In your code (in future, if you have an error in the code please post the code that is causing the error, not something else entirely - it makes it nigh on impossible for people without my psychic abilities to answer your question) you have defined a macro containing what you think is a hexadecimal number. In fact it's just a random string of characters and the compiler doesn't know what to make of it:

```
#define code1 DE74847

```

So in your switch construct, when `code1` gets replaced with the content of the macro, you end up with:

```
switch (value) {
    case DE74847:
        ....

```

The compiler has no idea what a DE74847 is.

Numbers other than decimal numbers (0-9 and the decimal point) are identified by the use of a prefix:

* `0b...` is binary
* `0` is octal (in your completely different code you have the number 0575, which is actually octal, and represents the decimal value 381)
* `0x` is hexadecimal.

So adding `0x` to the start of your hexadecimal value will tell the compiler to treat it as hexadecimal:

```
#define code1 0xDE74847

```

---
Tags: ir
---


title: RF signal boosting

text:
# Question
Title: RF signal boosting
I'm working on a quadcopter project. The quadcopter will be quite autonomous, but sometimes I'll need to send some messages to it. So I built a simple, one-way RF communication system based on two simple 433 MHz modules.

It works, but when the propellers of the quadcopter approach the take-off speed it begins having trouble in receiving the RF messages, and after a certain speed it stops working.

I suppose this is due to the electrical noise produced by the four little brushed motors. Yesterday I increased a little the transmitter's voltage, and that increased a little the minimum antenna-antenna distance with the motors on, but that is far from enough.

What else could I do to increase the transmitter's power?

Thanks in advance

Noè

P.S.: Here are my RF modules:

# Answer
As has been mentioned adding an antenna to the "ANT" pin on the transmitter will help. You need to get the length right though, but it's easy to calculate.

Best is to use single-core insulated wire (0.6mm is a good choice).

To calculate the right length you first need to know your frequency. Then you convert that to the wavelength, and then cut your wire to a quarter of that length.

Wavelength is `c/f` where `c` is the speed of light (in m/s), and `f` is the frequency.

So for 433MHz you have a wavelength of (299792458/433000000) 0.69m.

A quarter of that is 0.173m (17.3cm), so cut your wire to that and solder it on.

For 315MHz the wavelength is (299,792,458/315000000) 0.95m, so an antenna length of 0.238m or 23.8cm.

This is known (unsurprisingly) as a *quarter wavelength antenna* and is the most efficient length for a simple wire antenna.

Whether it will be strong enough to penetrate the noise from the motors is anyone's guess.

You can also add small capacitors (0.1µF ceramic) across the terminals of the motor and between the terminals and the body, to absorb some of the EMI which may help to allow more signal through - as shown here.
> 1 votes

# Answer
I have been using RF modules for different projects that involves using motors. And I have never experienced something like that. Since the motors a significant quantity of current to take off, I recommend using another power supply for the electronic part of the drone and use the actual battery just for the motors.
> 0 votes

---
Tags: rf
---


# Question
Title: How come `MyClass.MyStaticMethod()` doesn't work, but `Serial.begin()` does?
`MyProject.ino`:

```
#include "MyClass.h"

void setup()
{
  Serial.begin(9600);
  // MyClass.MyStaticMethod();
  MyClass::MyStaticMethod();
}

```

Both uncommented lines work, but the commented (when uncommented, of course) results in this error: `expected unqualified-id before '.' token`.

Now, I know this is because of the incorrect scope-resolution. Yet, how come `Serial` manages to call static functions without the need to use `::` to correction to scope-resolution.

**How come `MyClass.MyStaticMethod()` doesn't work, but `Serial.begin()` does?**

# Answer
> 2 votes
`.` is used to call a method on a class *instance* whereas `::` is used to call a static method within a class itself.

There is no `Serial` class - `Serial` is merely an instance of the `HardwareSerial` class.

```
#if defined(UBRRH) && defined(UBRRL)
  HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);
#else
  HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
#endif

```

If you want to use `.` then you have to instantiate your class and not use a static method:

```
class MyClass {
    static void myStaticMethod() {
    }
    void myMethod() {
    }
};

MyClass Fred;

// ...

Fred.myMethod();
MyClass::myStaticMethod();

```

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


# Question
Title: How can I use a BlueSMIRF Silver (RN-42) as a HID Keyboard (on IOS)?
I've got a BlueSMIRF Silver (RN-42) Bluetooth module. I am trying to create a basic keyboard I can play with on an iPad Air.

At the moment barely manage to get the module to pair with OSX but only through using Bluetooth Setup Assistant and using "**Passcode Options...use a specific code**".

With this option, the module pairs, but the connection resets about every 5 seconds.

On iPad it tries to use a generate number really fast and fails straight away, being unable to connect.

I noticed there is a BlueSMIRF HID version, but from what I can tell, the hardware is the same, just the firmware is different. I've gone through the whole Bluetooth Data Module Command Reference & Advanced Information User’s Guide(pdf link) manual and from what I can gather, even though I have Silver firmware burned onto my module, I should be able to set and use the HID profile (from the default SPP):

> Roving Networks modules shipped with firmware version 6.11 and higher support the HID profile. You do not need special firmware if your module is running firmware 6.11 or higher.

and my module reports version as:

```
Ver 6.15 04/26/2013
(c) Roving Networks

```

I've also gone through the Bluetooth HID Profile(pdf link) guide from Roving Networks, but the same information is present in Chapter 5 of the advanced user's guide mentioned above.

I've setup the following settings (with commands used):

* HID Profile (`S~,6`)
* Device discovery and pairing is set to automatic, without using GPIO6(`SM,6`)
* HID Flag is set to Keyboard (`SH,0000`)
* Authentication is set to open (`SA,0`)

I've also tried the inquiry scan(`SI,0800`) and page scan(`SJ,0800`) windows to maximum in the hope it would increase the odds of successful pairing and made sure I rebooted the module and checked the settings again.

I have used the same module with the SPP profile just fine, but I'm still fairly new to Bluetooth and this is the first time I try to use the HID profile.

**How can I use the BlueSMIRF Silver as a basic Bluetooth Keyboard for an iPad Air ?**

# Answer
> I should be able to set and use the HID profile (from the default SPP)

Unfortunately, your assumption is incorrect. From the same documentation you quoted, the previous sentence says:

> To use Roving Networks’ Bluetooth HID profile, you must use a special build of firmware, version 6.03 or later.

Poorly phrased, this does mean that you need to have two things:

1. A **special HID** firmware
2. Version 6.03 or later

Your BlueSmirf Silver only complies with the second condition; it does not have the special HID firmware (also note that the Rovnix command reference does not address a specific variant of the BlueSmirf, but speaks generally about all of the variants).

The **SPP protocol** (Serial Port Profile) is used for emulating a serial cable, and functions as a substitute for the physical RS-232 connection, **but cannot stack pure HID profile on top of it**. In order for you do talk HID, you will need the HID firmware.

As a side note, the HID version comes with SPP and you can switch between the two modes interchangeably, I have been using the HID version for a while now and it works fine (including the pairing with iOS).

Another misfortune is that it does not appear that *Roving Networks* officially support any re-flashing of the BlueSmirf firmware, so unless you are willing to reverse the hardware, this is off the table as well.
> 2 votes

# Answer
In the comments on SparkFun's product page for RN-42, gskelly indicates there is a flag in the v6.15 firmware that allows you to switch back and forth easily:

> Actually, since this includes the v6.15 firmware, you don’t need to re-flash the module to switch between HID and SPP. It can now be done using AT commands as follows:
>
> ```
> S~,6    // Enable HID on reboot
> R,1     // Reboot
> S~,0    // Enable SPP on reboot
> R,1     // Reboot
>
> ```
> 2 votes

# Answer
I know I am late to the party but for others searching this topic:

"S~,6" command does work for switching to HID profile but it requires the reboot command "R,1" otherwise it won't take.

I send these commands from the microcontroller to RN42 whilst the RN42 is in command mode, just to be clear.
> 0 votes

---
Tags: arduino-uno, bluetooth, keyboard
---