# Question
Title: What is preventing my code from checking the number of pushbutton values for a correct/wrong answer?
My code is supposed to generate a random number and then display it in binary using four LEDs. After you press it, it waits for two seconds before checking your number of pushbutton presses to see if they equal the random number, and it turns the green/red LED on accordingly and restarts the loop.

It doesn't do that, and also it counts multiple pushes if you keep the button pressed in, since it reads the pushbutton as being "on".

Code:

```
//VARIABLES:
const int ledPin1 = 2;
const int ledPin2 = 3;
const int ledPin3 = 4;
const int ledPin4 = 5;
const int buttonPin = 6;        //push button
const int ledPincorrect = 8;   //green LED that switches on for correct answer
const int ledPinfalse = 9;    //red LED that switches on for wrong answer

int randomNumber = 0;
int buttonState = HIGH;
int buttonPushCounter = 0;             //counter for button presses
int lastButtonState = HIGH;             //previous state of the button
int getal;
int i;                              //for the ConvertBinary function, i serves as a variable for the LED's
unsigned long Timer;               //Timer, switches on after buttonstate = LOW, and after 2 seconds the game restarts
long lastDebounceTime = 0;         // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers
int ledState = HIGH;
int remember;

void setup()
{
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(ledPincorrect, OUTPUT);
  pinMode(ledPinfalse, OUTPUT);
  Serial.begin(9600);
  randomSeed(analogRead(0));
  buttonState = digitalRead(buttonPin);
  Timer = millis(); // unsigned long Timer = millis();

}
void loop()
{
  if (randomNumber == 0) {
    Serial.print("lets start with random");
    getal = random(1, 16);
    Serial.print("random is: ");
    Serial.println(getal);
    randomNumber = 1;
  }

   int remember = getal;
   for (int i = 2; i < 6; i++) {
   remember = remember / 2;
      if (remember % 2 == 1){
       digitalWrite (i, HIGH);
      }
     else ((digitalWrite(i, LOW)));
    }

    // reading the button state

    // read the state of the switch into a local variable:
    int reading = digitalRead(buttonPin);

    if (reading != lastButtonState) {
      lastDebounceTime = millis();
      if (reading == LOW) {                    // if (reading == LOW) ????
        buttonPushCounter++;
        Serial.println("on");
        Serial.print("number of button pushes:  ");
        Serial.println(buttonPushCounter);
        Timer = millis();
        lastButtonState = buttonState;

      } else {
      // if the current state is LOW then the button wend from on to off:
      Serial.println("off");
    }

      if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
      lastButtonState = reading;
    }

    if (Timer >= 2000UL) {
      if (buttonPushCounter == getal) {
        digitalWrite(ledPincorrect, HIGH);
        digitalWrite(ledPinfalse, LOW);
        digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4, LOW);
      randomNumber = 0;
      buttonPushCounter = 0;
      }
      else {
        digitalWrite(ledPinfalse, HIGH);
        digitalWrite(ledPincorrect, LOW);
        digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4, LOW);
      randomNumber = 0;
      buttonPushCounter = 0;
      }
}

    }
}

}

```

# Answer
Let us start with the simplest issue in your code:

```
Timer = millis();
...
if (Timer >= 2000UL) {
...
}

```

After 2000 ms this is always true (for about 49 days)?

Cheers!

Please format your code if you expect anybody to take the time to read it and help.
> 1 votes

---
Tags: arduino-uno, programming
---


title: Esp8266 Arduino smart connect

text:
# Question
Title: Esp8266 Arduino smart connect
Below i have an example of a temperature sensor.What i need to be able to set the username an password dynamically before connecting to my home router.It would ask me for the ssid and password for example.example. Ive seen a couple of posts about this with no definitive code to show how it would work.If anyone has experience with this could they comment here please.

```
#include
#include
#include
#define ONE_WIRE_BUS 8
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

#define SSID "[YOUR_SSID]"
#define PASS "[YOUR_PASSWORD]"
#define IP "184.106.153.149" // thingspeak.com
String GET = "GET /update?key=[THINGSPEAK_KEY]&field1=";

void setup()
{
  Serial.begin(9600);
  sensors.begin();
  Serial.println("AT");
  delay(5000);
  if(Serial.find("OK")){
    connectWiFi();
  }
}

void loop(){
  sensors.requestTemperatures();
  float tempC = sensors.getTempCByIndex(0);
  tempC = DallasTemperature::toFahrenheit(tempC);
  char buffer[10];
  String tempF = dtostrf(tempC, 4, 1, buffer);
  updateTemp(tempF);
  delay(60000);
}

void updateTemp(String tenmpF){
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += IP;
  cmd += "\",80";
  Serial.println(cmd);
  delay(2000);
  if(Serial.find("Error")){
    return;
  }
  cmd = GET;
  cmd += tenmpF;
  cmd += "\r\n";
  Serial.print("AT+CIPSEND=");
  Serial.println(cmd.length());
  if(Serial.find(">")){
    Serial.print(cmd);
  }else{
    Serial.println("AT+CIPCLOSE");
  }
}

boolean connectWiFi(){
  Serial.println("AT+CWMODE=1");
  delay(2000);
  String cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  Serial.println(cmd);
  delay(5000);
  if(Serial.find("OK")){
    return true;
  }else{
    return false;
  }
}

```

# Answer
> 2 votes
I have cobbled together, from the library examples, a program to log temperature and humidity to an MQTT server. The SSID/password, MQTT server and port, and the MQTT publish path can all be set at run time. Once they are set, the device will remember and re-use the settings next time it boots.

I am using the Arduino IDE to program an ESP8266-01. It, in turn, talks to a DHT11 sensor for temperature and humidity data.

The program is found at https://github.com/PabluskiNC/TempHumidityLogger

```
    #include <FS.h>                   //this needs to be first, or it all crashes and burns...

    #include "DHT.h"
    #define DHTPIN 2
    #define DHTTYPE DHT11
    DHT dht(DHTPIN, DHTTYPE);

    #include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

    //needed for library
    #include <DNSServer.h>
    #include <ESP8266WebServer.h>
    #include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager

    #include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson

    #include <PubSubClient.h>
    WiFiClient espClient;
    PubSubClient client(espClient);
    long mqtt_lastMsg = 0;
    char mqtt_msg[50];
    int  mqtt_value = 0;

    //define your default values here, if there are different values in config.json, they are overwritten.
    char mqtt_server[40];
    char mqtt_port[6] = "1883";
    char mqtt_topic[34] = "OutTopic";

    //flag for saving data
    bool shouldSaveConfig = false;

    //callback notifying us of the need to save config
    void saveConfigCallback () {
      Serial.println("Should save config");
      shouldSaveConfig = true;
    }

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

      //clean FS, for testing
      //SPIFFS.format();

      //read configuration from FS json
      Serial.println("mounting FS...");

      if (SPIFFS.begin()) {
        Serial.println("mounted file system");
        if (SPIFFS.exists("/config.json")) {
          //file exists, reading and loading
          Serial.println("reading config file");
          File configFile = SPIFFS.open("/config.json", "r");
          if (configFile) {
            Serial.println("opened config file");
            size_t size = configFile.size();
            // Allocate a buffer to store contents of the file.
            std::unique_ptr<char[]> buf(new char[size]);

            configFile.readBytes(buf.get(), size);
            DynamicJsonBuffer jsonBuffer;
            JsonObject& json = jsonBuffer.parseObject(buf.get());
            json.printTo(Serial);
            if (json.success()) {
              Serial.println("\nparsed json");

              strcpy(mqtt_server, json["mqtt_server"]);
              strcpy(mqtt_port, json["mqtt_port"]);
              strcpy(mqtt_topic, json["mqtt_topic"]);

            } else {
              Serial.println("failed to load json config");
            }
          }
        }
      } else {
        Serial.println("failed to mount FS");
      }
      //end read

      // The extra parameters to be configured (can be either global or just in the setup)
      // After connecting, parameter.getValue() will get you the configured value
      // id/name placeholder/prompt default length
      WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
      WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5);
      WiFiManagerParameter custom_mqtt_topic("topic", "mqtt topic", mqtt_topic, 32);

      //WiFiManager
      //Local intialization. Once its business is done, there is no need to keep it around
      WiFiManager wifiManager;

      //set config save notify callback
      wifiManager.setSaveConfigCallback(saveConfigCallback);

      //set static ip
      //wifiManager.setSTAStaticIPConfig(IPAddress(10, 0, 1, 99), IPAddress(10, 0, 1, 1), IPAddress(255, 255, 255, 0));

      //add all your parameters here
      wifiManager.addParameter(&custom_mqtt_server);
      wifiManager.addParameter(&custom_mqtt_port);
      wifiManager.addParameter(&custom_mqtt_topic);

      //reset settings - for testing
      //wifiManager.resetSettings();

      //set minimu quality of signal so it ignores AP's under that quality
      //defaults to 8%
      //wifiManager.setMinimumSignalQuality();

      //sets timeout until configuration portal gets turned off
      //useful to make it all retry or go to sleep
      //in seconds
      //wifiManager.setTimeout(120);

      //fetches ssid and pass and tries to connect
      //if it does not connect it starts an access point with the specified name
      //here  "AutoConnectAP"
      //and goes into a blocking loop awaiting configuration
      if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
        Serial.println("failed to connect and hit timeout");
        delay(3000);
        //reset and try again, or maybe put it to deep sleep
        ESP.reset();
        delay(5000);
      }

      //if you get here you have connected to the WiFi
      Serial.println("connected...yeey :)");

      //read updated parameters
      strcpy(mqtt_server, custom_mqtt_server.getValue());
      strcpy(mqtt_port, custom_mqtt_port.getValue());
      strcpy(mqtt_topic, custom_mqtt_topic.getValue());

      //save the custom parameters to FS
      if (shouldSaveConfig) {
        Serial.println("saving config");
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.createObject();
        json["mqtt_server"] = mqtt_server;
        json["mqtt_port"] = mqtt_port;
        json["mqtt_topic"] = mqtt_topic;

        File configFile = SPIFFS.open("/config.json", "w");
        if (!configFile) {
          Serial.println("failed to open config file for writing");
        }

        json.printTo(Serial);
        json.printTo(configFile);
        configFile.close();
        //end save
      }

      client.setServer(mqtt_server, stringToNumber(mqtt_port));
      client.setCallback(callback);
      Serial.println("local ip");
      Serial.println(WiFi.localIP());
      dht.begin();
    }

    int stringToNumber(String thisString) {
      int i, value, length;
      length = thisString.length();
      char blah[(length + 1)];
      for (i = 0; i < length; i++) {
        blah[i] = thisString.charAt(i);
      }
      blah[i] = 0;
      value = atoi(blah);
      return value;
    }

    void callback(char* topic, byte* payload, unsigned int length) {
      Serial.print("Message arrived [");
      Serial.print(topic);
      Serial.print("] ");
      for (int i = 0; i < length; i++) {
        Serial.print((char)payload[i]);
      }
      Serial.println();

      // Switch on the LED if an 1 was received as first character
      if ((char)payload[0] == '1') {
        digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
        // but actually the LED is on; this is because
        // it is acive low on the ESP-01)
      } else {
        digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
      }

    }

    void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        Serial.print(mqtt_server);
        Serial.print(":");
        Serial.print(mqtt_port);
        Serial.print("...");
        // Attempt to connect
        if (client.connect("ESP8266Client")) {
          Serial.println("connected");
          // Once connected, publish an announcement...
          client.publish(mqtt_topic, "Reconnected");
          // ... and resubscribe
          //client.subscribe("inTopic");
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 5 seconds");
          // Wait 5 seconds before retrying
          delay(5000);
        }
      }
    }

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

      float h = dht.readHumidity();
      float t = dht.readTemperature();
      if (isnan(t) || isnan(h)) {
        Serial.println("Failed to read from DHT");
      } else {
        Serial.print("Temp:");
        Serial.print(t);
        Serial.print( "*C  Humidity:");
        Serial.print(h);
        Serial.println("%");
        if (!client.connected()) {
          reconnect();
        }
        client.loop();

        //long now = millis();
        //if (now - mqtt_lastMsg > 2000) {
        //  lastMsg = now;
        //  ++mqtt_value;
        char temp[7];
        dtostrf(t,4,2,temp); //convert float to char
        snprintf (mqtt_msg, 50, "%s C", temp);
        //  Serial.print("Publish message: ");
        //  Serial.println(msg);
        //  client.publish(mqtt_topic, msg);
        //}
        char pub_topic[34];
        strcpy(pub_topic,mqtt_topic);
        strcat(pub_topic,"/temperature");
        client.publish( pub_topic , mqtt_msg);
        Serial.print("Publish: ");
        Serial.print(pub_topic);
        Serial.print(" , ");
        Serial.println(mqtt_msg);

        dtostrf(h,4,2,temp); //convert float to char
        snprintf (mqtt_msg, 50, "%s %", temp);

        strcpy(pub_topic,mqtt_topic);
        strcat(pub_topic,"/humidity");
        client.publish(pub_topic,mqtt_msg);
        Serial.print("Publish: ");
        Serial.print(pub_topic);
        Serial.print(" , ");
        Serial.println(mqtt_msg);
      }
      delay(5000);
    }

```

# Answer
> 2 votes
The following code can do what you want (source), all that is needed is to combine it with the sensor code. The default behaviour is to create an access point when it can't connect to the eeprom stored WiFi station but you can modify it to trigger with a button/jumper or any other way you prefer.

```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>

ESP8266WebServer server(80);

const char* ssid = "test";
const char* passphrase = "test";
String st;
String content;
int statusCode;

void setup() {
  Serial.begin(115200);
  EEPROM.begin(512);
  delay(10);
  Serial.println();
  Serial.println();
  Serial.println("Startup");
  // read eeprom for ssid and pass
  Serial.println("Reading EEPROM ssid");
  String esid;
  for (int i = 0; i < 32; ++i)
    {
      esid += char(EEPROM.read(i));
    }
  Serial.print("SSID: ");
  Serial.println(esid);
  Serial.println("Reading EEPROM pass");
  String epass = "";
  for (int i = 32; i < 96; ++i)
    {
      epass += char(EEPROM.read(i));
    }
  Serial.print("PASS: ");
  Serial.println(epass);
  if ( esid.length() > 1 ) {
      WiFi.begin(esid.c_str(), epass.c_str());
      if (testWifi()) {
        launchWeb(0);
        return;
      }
  }
  setupAP();
}

bool testWifi(void) {
  int c = 0;
  Serial.println("Waiting for Wifi to connect");
  while ( c < 20 ) {
    if (WiFi.status() == WL_CONNECTED) { return true; }
    delay(500);
    Serial.print(WiFi.status());
    c++;
  }
  Serial.println("");
  Serial.println("Connect timed out, opening AP");
  return false;
}

void launchWeb(int webtype) {
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("Local IP: ");
  Serial.println(WiFi.localIP());
  Serial.print("SoftAP IP: ");
  Serial.println(WiFi.softAPIP());
  createWebServer(webtype);
  // Start the server
  server.begin();
  Serial.println("Server started");
}

void setupAP(void) {
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
     {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
     }
  }
  Serial.println("");
  st = "<ol>";
  for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      st += "<li>";
      st += WiFi.SSID(i);
      st += " (";
      st += WiFi.RSSI(i);
      st += ")";
      st += (WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*";
      st += "</li>";
    }
  st += "</ol>";
  delay(100);
  WiFi.softAP(ssid, passphrase, 6);
  Serial.println("softap");
  launchWeb(1);
  Serial.println("over");
}

void createWebServer(int webtype)
{
  if ( webtype == 1 ) {
    server.on("/", []() {
        IPAddress ip = WiFi.softAPIP();
        String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
        content = "<!DOCTYPE HTML>\r\n<html>Hello from ESP8266 at ";
        content += ipStr;
        content += "<p>";
        content += st;
        content += "</p><form method='get' action='setting'><label>SSID: </label><input name='ssid' length=32><input name='pass' length=64><input type='submit'></form>";
        content += "</html>";
        server.send(200, "text/html", content);
    });
    server.on("/setting", []() {
        String qsid = server.arg("ssid");
        String qpass = server.arg("pass");
        if (qsid.length() > 0 && qpass.length() > 0) {
          Serial.println("clearing eeprom");
          for (int i = 0; i < 96; ++i) { EEPROM.write(i, 0); }
          Serial.println(qsid);
          Serial.println("");
          Serial.println(qpass);
          Serial.println("");

          Serial.println("writing eeprom ssid:");
          for (int i = 0; i < qsid.length(); ++i)
            {
              EEPROM.write(i, qsid[i]);
              Serial.print("Wrote: ");
              Serial.println(qsid[i]);
            }
          Serial.println("writing eeprom pass:");
          for (int i = 0; i < qpass.length(); ++i)
            {
              EEPROM.write(32+i, qpass[i]);
              Serial.print("Wrote: ");
              Serial.println(qpass[i]);
            }
          EEPROM.commit();
          content = "{\"Success\":\"saved to eeprom... reset to boot into new wifi\"}";
          statusCode = 200;
        } else {
          content = "{\"Error\":\"404 not found\"}";
          statusCode = 404;
          Serial.println("Sending 404");
        }
        server.send(statusCode, "application/json", content);
    });
  } else if (webtype == 0) {
    server.on("/", []() {
      IPAddress ip = WiFi.localIP();
      String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
      server.send(200, "application/json", "{\"IP\":\"" + ipStr + "\"}");
    });
    server.on("/cleareeprom", []() {
      content = "<!DOCTYPE HTML>\r\n<html>";
      content += "<p>Clearing the EEPROM</p></html>";
      server.send(200, "text/html", content);
      Serial.println("clearing eeprom");
      for (int i = 0; i < 96; ++i) { EEPROM.write(i, 0); }
      EEPROM.commit();
      WiFi.disconnect();
    });
  }
}

void loop() {
  server.handleClient();
}

```

The configuration access point ssid and password are set in

```
const char* ssid = "test";
const char* passphrase = "test";

```

The default IP is 192.168.4.1. When you open it from a browser you see a screen which lists the available WiFi stations (ESP8266 scan result), the signal strength and an asterisk on locked stations. There are also two text boxes where you enter the ssid and password of the station you want to connect to and submit:

Note that there is a link to a similar library in the comments of the source link, that didn't work for me but you can try it.

---
Tags: wifi, esp8266
---


# Question
Title: Does a moisture sensor need warm-up time?
I am trying to use a moisture sensor to identify the moisture value of my plants. (As every one does.)

The sensor was connected to VCC all the time and my battery goes empty after a short time. So I decided to connect power only at the time I read from the sensor (on the arduino with `digitalWrite(moisture_vcc, HIGH)`.

To problem is that the values were too high.

So I'm wondering if these kind of sensors need a "warm-up time"? And If so, how long is it?

Any experience with it?

# Answer
> 1 votes
Photograph of the YL-69 Sensor :

**Most of this content was generated by : Conner Wolf**

Basically, that sensor works by measuring the resistance between the two "pins" of the PCB stake. It does this by applying a voltage across the pins, and measuring the current flow. So, the intention is that more water means less resistance, means less voltage, and a fall in the voltage sent to the ADC of the processor.

However, this is also going to lead to the metal from one of the pins being eaten away by galvanic action (electrolysis).

The other pin is likely to have accumulation of materials rather than being eaten away.

This electrolysis and coating of the pins results in a change in surface area of the pins and causes resistance measured to change (for the same given moisture content).

If you want to squeeze as much life out of the thing as possible, there are a few things you can do.

1. DO NOT leave the sensor powered. When you want to take a reading, power the sensor for maybe a few seconds, and take your readings. Then power it off again. Don't take readings too often.
2. Periodically reverse the pins of the electrical connection between the readout board and the "stake" board. Since only one terminal will be eaten away at a time, this should spread the decay out a bit.
3. Be aware that ANY mechanical disturbance of the "stake" board will probably cause a large shift in readout value. Your "jiggling the wires" causing a shift in values probably came from the mechanical force transmitted to the PCB through the wiring.

An improved version for this sort of thing use a AC bias on the sensor, which minimizes galvanic corrosion. AC bias reverses the voltage applied to the sensor, attempting to eliminate electrolysis on the sensor.

Higher Quality soil moisture sensors use capacitive sensor, and therefore make the sensor immune to the corrosion issue, but are much more complex and expensive.

---
Tags: sensors, power
---


title: I2C between Arduinos without Master

text:
# Question
Title: I2C between Arduinos without Master
I am working on a library for some Arduinos that should talk between each other. The aim is that I can load the same binaries onto each Arduino. The I2C ID will be set by DipSwitches. So far everything works pretty nice but once a while everything gets stuck.

I am not asking you to resolve and debug my code, but I am not sure if i have done something completely wrong:

To make all Arduinos interchangeable I have no Master (`Wire.begin()`) in my I2C Bus.

I read, that the Master would be responsible for the pulse on the Clock line. As I have no Master in my setup maybe that is the reason for the instability.

Can anyone confirm that connecting some I2C Arduinos without master is something that cannot be done? (or do I have to look for some other reason)

# Answer
You have to have a master for an I2C bus to work. Can't you allocate one of the dip switches to define the master?

Edit to be able to remove the downvote Nick his answer seems to imply that you do not need masters but that is wrong. What Nick is saying is that you can swap masters over time.
But each time there is communication there is a master.
So the statement "You have to have a master for an I2C bus to work" is 100% right. As I misunderstood this myself I downvoted this answer. I hope this edit will enable me to remove my downvote and add a upvote.
> 3 votes

# Answer
> Can anyone confirm that connecting some I2C Arduinos without master is something that cannot be done? (or do I have to look for some other reason)

There is no master except during transmissions. Thus it is possible to rotate the job of master if you want. You would need some way of deciding when it was a particular board's turn to be master.

I have code here on my RS485 page about how you can set up a rolling master using Serial communications. The same basic idea could be used to make a rolling I2C master.
> 2 votes

---
Tags: i2c, communication, wire-library
---


title: Printing arduino pin numbers to MySQL

text:
# Question
Title: Printing arduino pin numbers to MySQL
I mistakenly posted this on stack overflow first. The community was kind enough to point me to this forum. I apologize for the double-post.

I've been working on an Arduino Uno r3 + WiFi Shield project for a few months now building up the complexity as I go. I've hit a wall. I started this project with exactly zero experience writing code of any kind and exactly zero experience working with boards. If you have any doubts as to whether or not I'll understand your response, please dumb it down!

I've made a simple arduino + wifi shield setup that can report a button push to a MySql database. All of the .php stuff on the backend works and the database is managed with phpmyadmin. I'm trying to add a second button but can't seem to make it work and need some help.

I have settled on a four-field database table as the output:

* 1st column: the key. A sequential, unique identifier for each entry
* 2nd column: the pin number that the sensor is connected to
* 3rd column: the sensor value
* 4th column: the date and time

Notice that I'm not using a dedicated column for each sensor. By using the sensor pin input, I want to simply print the sensor pin number in a column. This (a) saves space in the table and (b) allows the Arduino to use as many sensors as it has pins.

The idea is that each button press (even if two are pressed simultaneously) will get it's own line, sensor pin source, value, and timestamp. No values will be sent unless a button is pressed.

I haven't the foggiest idea of how to implement this! Help!

---

**My question:**

How can I ask the sketch to retrieve the pin from which a signal originates and write it to the db as a number in the second column? The 13th line of code is what will write the pin number (I think). The "senseval=" needs to be a variable that reports the source pin.

I don't know how to set this up and google has led to nothing but dead ends. I'd like this thread to answer the questions I'm sure a few more people have/will have!

---

My sketch is included below and the insert\_php\_doc below that. I'm using the Silinas/Benoit "Arduino /Post" example from github:

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

char ssid[] = "linksys";
int status = WL_IDLE_STATUS;
WiFiClient client;
IPAddress server(xxx,xxx,xxx,xxx);

int inPin_0 = A0; // choose the input pin (sensor #1)
int inPin_1 = A1; // choose the input pin (sensor #2) //ADDED FOR SECOND BUTTON//
int sensorSense_0 = 0; //variable
int sensorSense_1 = 0; //variable //ADDED FOR SECOND BUTTON//
String SensorVal = "senseval=";// "yourdata="
String senseval;//yourdata //MUST KEEP sensval for PHP

void setup() {
  Serial.begin(9600);
  pinMode(inPin_0,INPUT);
  pinMode(inPin_1,INPUT);  //ADDED FOR SECOND BUTTON//
  connectWifi();
}

void loop() {
  sensorSense_0=analogRead(inPin_0);
  if (sensorSense_0 == LOW){
    postData();
    delay(5000);
  }
  sensorSense_1=analogRead(inPin_1); //ADDED FOR SECOND BUTTON//
  if (sensorSense_1 == LOW){ //ADDED FOR SECOND BUTTON//
    postData(); //ADDED FOR SECOND BUTTON//
    delay(5000); //ADDED FOR SECOND BUTTON//
  }

void connectWifi() {
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid);

    delay(7000);
  }
}
}
void postData() {
  senseval=SensorVal+String(inPin_0);
  senseval=SensorVal+String(inPin_1); //ADDED FOR SECOND BUTTON//

  if (client.connect(server, 80)) {
    Serial.println("connecting...");

    client.println("POST /insert_mysql_doc.php? HTTP/1.1");
    client.println("Host: www.<domain>.com");
    client.println("User-Agent: Arduino/1.0");
    client.println("Connection: close");
    client.println("Content-Type: application/x-www-form-urlencoded;");
    client.print("Content-Length: ");
    client.println(senseval.length());//yourdata
    client.println();
    client.println(senseval);//yourdata
    client.stop();
  }
  else {
    Serial.println("Connection failed");
    Serial.println("Disconnecting.");
    client.stop();
    connectWifi();
    printWifiStatus();
  }
}

```

---

The insert PHP from https://github.com/ericbenwa/POST-Arduino-Data-Wireless:

```
<?php

foreach ($_REQUEST as $key => $value)
{
    if ($key == "senseval") {
        $senseval = $value;
    }
}

// EDIT: Your mysql database account information
$username = "test_user";
$password = "test_password";
$database = "test_db_name_here";
$tablename = "test_table_name_here";
$localhost = "localhost";

// Check Connection to Database
if (mysql_connect($localhost, $username, $password))
  {
    @mysql_select_db($database) or die ("Unable to select database");

    // Next two lines will write into your table 'test_table_name_here' with 'yourdata' value from the arduino and will timestamp that data using 'now()'
    $query = "INSERT INTO $tablename VALUES ($senseval,now())";
    $result = mysql_query($query);
  } else {
    echo('Unable to connect to database.');
  }

?>

```

# Answer
```
int inPin_0 = A0; // choose the input pin (sensor #1)
int inPin_1 = A1; // choose the input pin (sensor #2) //ADDED FOR SECOND BUTTON/

...

  senseval=SensorVal+String(inPin_0);
  senseval=SensorVal+String(inPin_1); //ADDED FOR SECOND BUTTON//

```

The above is wrong because you are sending the **pin numbers** and not the values read from those pins. You previously read them here:

```
  sensorSense_0=analogRead(inPin_0);
  ...
  sensorSense_1=analogRead(inPin_1); //ADDED FOR SECOND BUTTON//

```

It is `sensorSense_0` and `sensorSense_1` that you should be sending.

Also, as Damiano Verzulli pointed out, your second assignment to `senseval` clobbers the first. You want something more like:

```
  senseval  = SensorVal + String(analogRead(inPin_0)) + ", ";
  senseval += SensorVal + String(analogRead(inPin_1));

```

Even that may not be perfect, I didn't read your PHP side.

---

Looking at the PHP side now:

```
$query = "INSERT INTO $tablename VALUES ($senseval,now())";

```

That isn't going to work too well for two values. I don't know your database schema, but that won't handle two values very well. A bit of tweaking and it might, or you could do two `INSERT` statements.
> 1 votes

# Answer
First of all, your statement: "*I've made a simple arduino + wifi shield setup that can report a button push to a MySql database.*" is incorrect (or, at best, misleading) as the code you're running in Arduino is **not** talking with MySQL at all, but simply calling a remote PHP script via an HTTP/POST request.

So now your problem can be split in two parts:

1. checking if your arduino (via its own wifi shield) is correctly talking with remote HTTP server (invoking proper PHP script with related parameters);
2. checking if your PHP script is correctly dealing with MySQL.

As for 1), my first suggestion is to check web-server log files. Unfortunately you didn't tell us which web server (Apache? IIS? Other) are you running, as well as which operating system are you relying on (Linux? Windows? Other?). With Apache running on linux, tipically log files are stored in `/var/log/apache` or `/var/log/httpd` folders. There are plenty of other troubleshooting approaches but... please, let's start checking log files, ensuring that PHP script is invoked;

As for 2), your PHP script is lacking basic error-handling: should the `insert` (launched by the `mysql_query` function call) fail, you'll never know. I **strongly** suggest you to add proper error-handling code. Based on official documentation it's as easy as checking the result value of the `mysql_query` call: "*...For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql\_query() returns TRUE on success or FALSE on error....*" so what you have to do to improve your code (...and being notified about errors raised by MySQL via PHP) is to use something like following code:

```
$result = mysql_query($query);
if (!$result) {
   die('Invalid query: ' . mysql_error());
}

```

Having said all the above, let me add a couple of other notes.

* in your OP, you wrote: "*I'm trying to add a second button but can't seem to make it work*". So it seems that previously you were testing with only one button and, in such a case, everything worked. Is it right? If yes, please, can you tell us what you changed to add proper handling of second button?
* in your code I see following lines:

.

```
[...]
senseval=SensorVal+String(inPin_0);
senseval=SensorVal+String(inPin_1);
[...]

```

Please note that they are probably wrong, as the second line will override the assignment of the first one. So, with such lines, you'll surely/always loose the value related to `inPin_0` (in other words: the first line, is useless).

* giving a look to the server-side PHP script, I noted that it has been built to handle only **one** parameter (`sensval` passed to PHP via GET/POST parameter; with PHP storing it in the `$sensval` variable). So... to change the behaviour so to handle two different values... it's not trivial (in other words: such a change require a minimun understanding of web-programming and... getting deep to analyze such requirement is out of scope --I think-- of this answer).
> 1 votes

---
Tags: arduino-uno, c++, wifi, pins
---


# Question
Title: Arduino Ping sensor with NewPing library
I was trying out the NewPing library (the main example sketch) and when I compile it and check the serial monitor, it seems like it works for about 10 seconds, then instead of giving distance values it just writes out random characters. The only thing I can think of is that my sensor is bad. Any suggestions before I get another Ping sensor? I'm unsure if the same thing will happen.

# Answer
> 2 votes
The main example sketch has this:

```
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.

```

Your serial monitor is set to 9600 baud (bottom RH corner). Change that to match the setting in the sketch.

---
Tags: sensors
---


# Question
Title: Serial.println for pointers to the byte datatype behaves unexpectedly
```
byte subkeys[16][48/8];

for (size_t address = 0; address < 16*6; address++)
    Serial.println( (byte) *(subkeys + address) );

```

Why won't the compiler handle this? It tells me

> cast from 'byte\* {aka unsigned char\*}' to 'byte {aka unsigned char}' loses precision \[-fpermissive\]

If I omit the `(byte)` part, it tells me

> call of overloaded 'println(byte \[6\])' is ambiguous

I have no idea what's happening.

# Answer
A `byte` is to small to store a pointer value. Instead to casting to byte, you should cast to `uintptr_t`, which is guaranteed to be large enough. On an AVR-based device like the Uno, this is the same as `uint16_t` or `unsigned int`, but `uintptr_t` is more general.

**Edit**: From your comment it would seem you want to print the contents of the array instead of the addresses of the rows. The obvious way is to loop with two indices:

```
for (size_t i = 0; i < 16; i++) for (size_t j = 0; j < 6; j++)
    Serial.println(subkeys[i][j]);

```

If you really want to use `subkeys` as a 1D array, then cast it to a `byte *`, which is the type a 1D array would naturally decay to:

```
for (size_t address = 0; address < 16*6; address++)
    Serial.println(((byte *) subkeys)[address]);

```
> 3 votes

---
Tags: arduino-uno
---


title: Arduino error when compiling

text:
# Question
Title: Arduino error when compiling
When this code is uploaded I get an "Error Compiling". Any help is very much appreciated.

```
#include <MeetAndroid.h>
#define supplyVolts 6
#define motorVolts 5
#define baudRate 57600
// If you are using a General Bluetooth adapter (available on buildcircuit.net), then, it works with 9600bps baud rate
MeetAndroid phone;
int left = 255; // midpoint
int right = 255;
int pwmLeftPin = 3;  1 int pwmRightPin = 11;
int directionLeftPin = 12;
int directionRightPin = 13;
void setup() {
  pinMode(pwmLeftPin, OUTPUT);
  pinMode(pwmRightPin, OUTPUT);
  pinMode(directionLeftPin, OUTPUT);
  pinMode(directionRightPin, OUTPUT);
  setMotors();
  // use the baud rate your bluetooth module is configured to
  Serial.begin(baudRate);
  phone.registerFunction(setLeft, 'l');
  phone.registerFunction(setRight, 'r');
}

void loop() {
  phone.receive();
}

void setLeft(byte ignore, byte count) {
  int value = phone.getInt();
  left = value;
  setMotors();
}

void setRight(byte ignore, byte count) {
  int value = phone.getInt();
  right = value;
  setMotors();
}

void setMotors() {
  int vLeft = abs(left - 255) * motorVolts / supplyVolts;
  int vRight = abs(right - 255) * motorVolts / supplyVolts;
  int dLeft = (left > 255);
  int dRight = (right > 255);
  if (vLeft < 50) {
    vLeft = 0;
  }
  if (vRight < 50) {
    vRight = 0;
  }
  analogWrite(pwmLeftPin, vLeft);
  analogWrite(pwmRightPin, vRight);
  digitalWrite(directionLeftPin, dLeft);
  digitalWrite(directionRightPin, dRight);
}

```

# Answer
> 4 votes
Take a close look at this line. The compiler will not like that as it does not have the right syntax.

```
int pwmLeftPin = 3;  1 int pwmRightPin = 11;

```

Change it to:

```
int pwmLeftPin = 3;
int pwmRightPin = 11;

```

This should at least remove the first issue with your code.

Cheers!

---
Tags: arduino-uno
---


# Question
Title: Problem receiving CAN messages using arduino, MCP2515 CAN module and multiprotocol radio shield
I am using an arduino UNO and a Cooking Hacks CAN BUS module through a Cooking Hacks Multiprotocol radio shield. I plan to read the CAN messages through the car's OBD-II port. I have connected the components according to the tutorial and though there is no LED to indicate that the shield and CAN bus module are ON, I verified that they are indeed ON by using a multimeter. Also, when the reset button is pressed on either the shield or the CAN module, the arduino resets so I guess they are powered up. Coming to my problem, I uploaded the code and connected the setup to the OBD-II port and turned the ignition ON. I expected to see the CAN messages on the arduino serial monitor but I didn't see anything. I also took up this issue with the cooking hacks support team who told me that the libraries were updated and that I should use the updated ones. So I downloaded the revised libraries to use with my code but I am unable to upload the code itself to the arduino because of an error during compilation.

C:\Users\user\Documents\Arduino\libraries\arduinoCANBUS\arduinoCAN.cpp:26:49: fatal error: ../arduino-api/arduinoMultiprotocol.h: No such file or directory

The major difference as far as I can tell between the old and the new libraries is the addition of two lines in the arduinocan.cpp file :

# include "../arduino-api/arduinoMultiprotocol.h"

# include "../arduino-api/arduinoUtils.h"

Both of these are header files in another library that was included as part of the whole library that you can download from their website.

I realise I might have confused whoever's reading but please have a look at the arduino code. Hopefully, that should clear things up. Any help would be highly appreciated. Thanks.

Code:

```
    #include <arduinoCAN.h>
    #include <arduinoClasses.h>
    #include <arduinoMultiprotocol.h>
    #include <arduinoUART.h>
    #include <arduinoUtils.h>
    #include <Wire.h>
    #include <SPI.h>

    // Create an instance of the object
    CAN myCAN = CAN();

    // Setting up our devices and I/Os
    void setup() {
    // Using the Socket 0 onto which Can bus module is plugged in
    Utils.setONSocket0();
    Utils.setMUXSocket0();
    // Initializes the UART
    Serial.begin(115200);
    delay(100);

    myCAN.begin(500); // Start talking to the BUS. Speed= 500 Kbps
    }

    void loop() {
    // 1. Receive data

    if (myCAN.messageAvailable()) {
    // Read the last message received.
    myCAN.getMessage(&myCAN.messageRx);
    // Print in the serial monitor the received message
    myCAN.printMessage(&myCAN.messageRx);
     }
    }

```

EDIT: PROBLEM SOLVED!

Putting the header file's full path in the sketch did not solve it. The compiler still displayed the same error. I then made a backup copy of all the files containing the #include "arduinoMultiprotocol.h" statement and edited them to contain the full path. Initially, the error didn't change and I moved onto the next suggestions, all of which did not change the error. However, I went back to the edited files and replaced the backslash() with the slash(/). This time, the compiler did not throw the same error, instead saying it cannot find arduinoUtils.h. So I proceeded to do the same thing with arduinoUtils.h, editing all the files containing it to mention the full path. And this time it worked and the sketch works as well. Thanks for your help!

# Answer
The compiler is saying it can't find the header files. The part of the path `../arduino-api/` is suspicious.

It may be because the header files are expected to be somewhere else, or their is a small error which has had a knock on effect.

1 - Find arduinoMultiprotocol.h
Put its full path into the include statement, e.g.

```
    #include "C:\Users\user\Documents\Arduino\libraries\arduinoCANBUS\wibble\arduinoMultiprotocol.h"

```

If that is still broken, but a new error is printed, copy the error. If the error doesn't change, then make a backup copy of every file you can find containing `#include <arduinoMultiprotocol.h>` and edit it to contain the full path. It looks like starting with arduinocan.cpp is a good place to start.

2 - If that doesn't fix the error, create an empty sketch, including all those headers, e.g.

```
    #include <arduinoCAN.h>
    #include <arduinoClasses.h>
    #include <arduinoMultiprotocol.h>
    #include <arduinoUART.h>
    #include <arduinoUtils.h>
    #include <Wire.h>
    #include <SPI.h>

    void setup() { }

    void loop() { }

```

Compile and copy the error message. Move the `#include <arduinoMultiprotocol.h>` a bit later in the sequence of #includes. If the error changes copy that for later, and record which sequence changed it.

3 - Change `#include <arduinoMultiprotocol.h>` in that empty sketch to the full path (as in step 1). If that doesn't fix it, copy that error message.

If you still need help, please update your question with the results of those tests.
> 0 votes

---
Tags: can-bus
---


title: text to 2D array on Arduino

text:
# Question
Title: text to 2D array on Arduino
I am trying to read a text file and send the info to 2D array, but after loading the array, it reads all zeroes. What can I do to stop the Arduino from doing this and get the array with my required data?

```
/* This program was created by ScottC on 8/5/2012 to receive serial signals from a computer to turn on/off 1-9 LEDs */

int** ptr;

void setup() {
  // initialize the digital pins as an output.
  pinMode(13, OUTPUT);
  // Turn the Serial Protocol ON
  Serial.begin(9600);
}

void loop() {
  byte byteRead;

  if (Serial.available()) {

    /* read the most recent byte */
    byteRead = Serial.read();
    //You have to subtract '0' from the read Byte to convert from text to a number.
    byteRead = byteRead - '0';
    ptr = new int* [byteRead];

    int i,j;
    for ( i = 0; i < byteRead; i++) {
      ptr[i] = new int[3];
      for ( j = 0; j < 3; j++) {
        if (Serial.available()) {

            /* read the most recent byte */
            byteRead = Serial.read();
            //You have to subtract '0' from the read Byte to convert from text to a number.
            byteRead = byteRead - '0';
            ptr[i][j] = byteRead;
            Serial.print(ptr[i][j]);
        }
      }
    }
  }
}

```

# Answer
> 1 votes
There are several issues with your code but instead of correcting I recommend that you start by checking that your assumptions about the format is correct. Send your data to this "reduced" variant of your sketch. Does it work? Did you receive what you expected?

```
void setup() {
  // initialize the digital pins as an output.
  pinMode(13, OUTPUT);
  // Turn the Serial Protocol ON
  Serial.begin(9600);
}

void loop() {
  byte byteRead;

  if (Serial.available()) {

    /* read the most recent byte */
    byteRead = Serial.read();
    //You have to subtract '0' from the read Byte to convert from text to a number.
    byteRead = byteRead - '0';
    Serial.print(F("byteRead = "));
    Serial.println(byteRead);

    int i,j;
    for ( i = 0; i < byteRead; i++) {
      for ( j = 0; j < 3; j++) {
        if (Serial.available()) {

            /* read the most recent byte */
            byteRead = Serial.read();
            //You have to subtract '0' from the read Byte to convert from text to a number.
            byteRead = byteRead - '0';
            Serial.print(i);
            Serial.print(':');
            Serial.print(j);
            Serial.print(F(":byteRead = "));
            Serial.println(byteRead);
        }
      }
    }
  }
}

```

Did you see the issue with:

```
    for ( i = 0; i < byteRead; i++) {
    ...
    }

```

Cheers!

---
Tags: arduino-uno
---


# Question
Title: Convert string plus hexadecimals to array of hex:
I have a string which I send to the arduino using serial monitor. Something like that:

```
my specific string 0x0F 0x2C 0x98 0xBC

```

How can I parse this string in the arduino to get an array of hex values:

```
0x0F 0x2C 0x98 0xBD

```

? There are two prerequisites:

1. All hexadecimal starts with `#`
2. The size of hexadecimal is 2. No `0x111` or '0xbbb'

# Answer
> How can I parse this string in the arduino to get an array of hex values:

There are a few standard library (stdlib) functions that can help you with that. Below is a snippet:

```
char buf[] = "0x0F 0x2C 0x98 0xBD";
uint8_t val[4];

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

  char* bp = buf;
  int i = 0;
  do {
    char* ep;
    val[i] = strtol(bp, &ep, 16);
    Serial.println(val[i], HEX);
    bp = ep;
    i += 1;
  } while (*bp != 0);
}

void loop()
{
}

```

Cheers!
> 1 votes

# Answer
You can try reading each character and convert it to hexadecimal representation. I suppose you wanna 1 byte each value in hexadecimal representation, so, let's start.

For example the string "0x25", ignore the 0x and read the '2' and save it into a char variable. Same for '5';

```
char highBits = '2' - '0'; // convert to decimal representation
char lowBits  = '5' - '0';

byte = (highBits << 4 | lowBits);

```

Now, save it inside you array. Make sure you check if the value is one of the possible letters in hexadecimal and convert it properly (A=10 and so on). Just include an if statement if it is a letter and convert it.
> 0 votes

---
Tags: c++, arduino-ide
---


# Question
Title: Why is my SRAM so quickly filled? There are not more than 60 bytes
I have just gone through all my code. At max I use 60 bytes. I have done everything in order to minimize its usage - I even store booleans as bits, not bytes! What could be happening here?

The only thing that comes to my mind are extremely large arrays, like this:

```
const uint8_t SBoxes[8][4][16] PROGMEM;

```

However, these are stored in the program memory as you can see. How can I check they are really there and my memory usage? My code is too large to post it here.

EDIT:

IDE tells me (even though I believe it's very inaccurate):

> Sketch uses 7,898 bytes (24%) of program storage space. Maximum is 32,256 bytes. Global variables use 1,023 bytes (49%) of dynamic memory, leaving 1,025 bytes for local variables. Maximum is 2,048 bytes.

All my literal strings use F() and there are not many of them.

EDIT2:

Code on pastebin. Just for a quick glance, it is really large.

EDIT3:

My `Serial` prints

```
ready
some numbers (that's ok I ask it to print out an array)
ENready
again numburs
Enready
...

```

I ask it to print `ready` at the very beginning of my program. I ask it to println `End of encr` near the end of my `setup` funciton, but as you see it never finishes the printing.

It always behaves like that when I run out of SRAM.

# Answer
When you are asking yourself what is eating so much RAM, the first step is to look at the symbol table in the ELF file. If you use a makefile, you probably know where to find the ELF file. If you are using the Arduino IDE, go to File / Preferences, check “Show verbose output during compilation”, compile and look at the output: you will see the temporary directory where the compiler puts your ELF file.

Now run the command `avr-nm -Crtd --size-sort your_elf_file` and look for symbols of type 'D' (data), 'V' (vtable) and 'B' (BSS), in either upper or lower case. On a Unix-style OS you would pipe through `grep -i ' [dbv] '`. Running this on your program gives:

```
00000068 B tx_buffer
00000068 B rx_buffer
00000034 B Serial
00000021 B lcd
00000016 V vtable for HardwareSerial
00000008 V vtable for LiquidCrystal
00000004 B timer0_overflow_count
00000004 B timer0_millis
00000002 D __malloc_margin
00000002 D __malloc_heap_start
00000002 D __malloc_heap_end
00000002 B __flp
00000002 B __brkval
00000001 b timer0_fract
00000001 D encr
00000001 B debug
00000001 B EEPROM

```

Obviously, this cannot account for the 1,023 bytes of static RAM your program is using. What this command misses is the literal arrays and strings. These can be seen with the command `avr-objdump -j .data -s your_elf_file`. The literal strings are quite obvious in the output, the literal arrays less so. Running this on your program gives a long listing starting with

```
Contents of section .data:
800100 00000005 2000010e 040d0102 0f0b0803  .... ...........
800110 0a060c05 09000700 0f07040e 020d010a  ................

```

Now, on the source code we see:

```
const uint8_t SBoxes[8][4][16] PROGMEM = {
{{14,  4,  13,  1,   2, 15,  11,  8,   3, 10,   6, 12,   5,  9,   0,  7},
 { 0, 15,   7,  4,  14,  2,  13,  1,  10,  6,  12, 11,   9,  5,   3,  8},
 { 4,  1,  14,  8,  13,  6,   2, 11,  15, 12,   9,  7,   3, 10,   5,  0},
 {15, 12,   8,  2,   4,  9,   1,  7,   5, 11,   3, 14,  10,  0,   6, 13} },
 ...

```

If you translate this to hexadecimal, you get `0e 04 0d 01 02 0f...`, which appears also by the end of the first line of previous listing. So there is your culprit: all the big PROGMEM arrays. The compiler does not honor the PROGMEM attribute on local variables.

My first thought was to make the arrays global, and this does solve the problem. However, as pointed out by Mikael Patel in a comment, the documentation on PROGMEM states that “variables must be either globally defined, OR defined with the static keyword, in order to work with PROGMEM.” Then, making the arrays `static const PROGMEM` is a cleaner solution.
> 5 votes

# Answer
To elaborate on Edgar Bonet's answer and my comment under it, you cannot usefully put PROGMEM variables as local variables because local (non-static) variables have to be allocated on the stack.

```
void lookUpInSBox(size_t which, byte *address, byte* binaryOutcome, size_t addressFrom){

   ...

    const uint8_t SBoxes[8][4][16] PROGMEM = {

                             /*S1*/

   { {14,  4,  13,  1,   2, 15,  11,  8,   3, 10,   6, 12,   5,  9,   0,  7},
     { 0, 15,   7,  4,  14,  2,  13,  1,  10,  6,  12, 11,   9,  5,   3,  8},
     { 4,  1,  14,  8,  13,  6,   2, 11,  15, 12,   9,  7,   3, 10,   5,  0},
     {15, 12,   8,  2,   4,  9,   1,  7,   5, 11,   3, 14,  10,  0,   6, 13}    },

```

You could make them global. But if you prefer not to do that, put `static` in front of them. Doing that on your code reduced it to 247 bytes.

```
Global variables use 247 bytes (12%) of dynamic memory, leaving 1,801 bytes for local variables. Maximum is 2,048 bytes.

```

---

You expect a bit more than the 60 you counted. The serial buffers take a bit (128 bytes).

See Putting constant data into program memory (PROGMEM) for more information. On a tiny sketch I found the following 346 bytes already in use:

* 34 bytes for the HardwareSerial instance (Serial)
* 64 bytes for the Serial transmit buffer
* 64 bytes for the Serial receive buffer
* 4 bytes for the Serial transmit buffer head and tail pointers
* 4 bytes for the Serial receive buffer head and tail pointers
* 9 bytes for keeping track of millis / micros
* 4 bytes for memory allocation (\__malloc\_heap\_start, \__malloc\_margin)
* 128 bytes for the heap safety margin
* 6 bytes for a few nested function calls (main -\> setup -\> getFreeMemory)
* 16 bytes for the compiler vtable for HardwareSerial
* 4 bytes for variables \__brkval and \__flp (used in memdebug)
* 2 bytes pushed onto the stack in main (to save registers)
* 2 bytes pushed onto the stack in setup (to save registers)
* 4 bytes pushed onto the stack in getFreeMemory (to save registers)
* 1 byte because the stack pointer starts at 0x8FF rather than 0x900

The sketch on my page used dynamic memory allocation so it used a bit more than yours does (for keeping track of it).

---

> Once it starts printing gibberish or looping (that means it prints something and starts again from the beginning of the program) I know I have run out of SRAM

I'm a bit puzzled by all the `new`/`delete` you are doing. Why do that? For example:

```
byte *E;
E = new byte[48/8];
for(size_t i = 0; i < 48; i++){
    insertBit( E, i, bitValue( R, E_BIT[i]-1 ) );
}

// XOR Kn and  E(Rn-1)
byte KxorE[48/8];
for (size_t i = 0; i < 48; i++){
    insertBit( KxorE, i, bitValue( K, i ) ^ bitValue( E, i ) );
}
delete[] E;

```

Massive amounts of dynamic memory allocation may fragment memory. Can't you rewrite to not do that? You can pass arrays by reference, it just seems weird (and slow) to do all that allocation.
> 4 votes

---
Tags: arduino-uno, sram
---


# Question
Title: ATmega32U4 (Leonardo/Pro Micro) bootloader, 8K rather than 4K?
Recently hit the dreaded 0x7000 / 28k~ AVRDUDE+LUFA limit. It states everywhere this is because the bootloader uses 4KB, thus reducing the 32KB to 28KB. Makes sense, except...

Blank sketches on the 32U4 take nearly 4KB from the get go, which I thought was attributed to the bootloader? So now I'm confused. If I'm losing 4KB off the top, and 4KB off the bottom - is the bootloader 8KB?

EDIT: In case the above is unclear, it appears my sketches only have ~24k of the 32k available to them. Is this expected behavior?

# Answer
> 2 votes
The bootloader needs a USB stack to work. It is possible to run the main sketch without a bootloader. So yes, I suppose you must have two of them. Looking at the assembler output for a blank sketch, it appears that you get the USB code in it by default. As I said, they have to assume you may not have the bootloader around, so they can't just execute the stack from the bootloader.

---
Tags: arduino-leonardo, bootloader, avrdude
---


title: Dagu Mini Driver Board Issues

text:
# Question
Title: Dagu Mini Driver Board Issues
I have the Dagu Mini Driver board which is based on the atmega8 and I uploaded the code here. It uploaded perfectly and I wired 4x AA pack to the battery terminals making sure to observe polarity.

I then attached two DC motors to the ML and MR pins just like it said in the picture. I turned the board on, making sure the switch was set to on also.

The red light lighted up and the blue light flickered for a second. The motors did not move. I tried different motors. To check if it was a corrupt bootloader I tried to upload the hello world blink sketch. That worked perfectly.

I got my multi-meter out and tested the wires I was using...all good! Tested the battery...6.31v! That's within specs. I have the jumpers correctly inserted on the D7 - 10 pins. Here's my setup:

What in the world could be wrong? The code is supposed to make it turn in a rough square. I checked it over and over and it looks right. Any ideas?

# Answer
Switching the selector did not help. I received a new one which worked perfectly following the steps from before. Apparently the issue was hardware related, possibly a cold solder joint preventing the motor driver section to work while still letting everything else continue normally.
> 0 votes

# Answer
This is a generic debugging advice, but maybe it can still be of help: have you tried driving the led from the loop, to check that it doesn't get stuck for some reason?

Other thing you could do is to get the datasheet of the motor driver, find out the inputs from the ATMega and see how they look like. At least that would allow you to bisect the problem answering the question: "Does the ATMega generate the expected signal?"
> 0 votes

---
Tags: motor, hardware, robotics
---


title: Pass Several Values to Library

text:
# Question
Title: Pass Several Values to Library
Unfortunately I have yet to learn C++ though I have experience with C# and other non-C languages. After trying for the past 5 hours to pick up what I can from Stack and other sites I haven't found a workable solution that actually works with Arduino IDE (hence why I'm posting here and not stackoverflow).

Im trying to create a simple library to handle some analog inputs. I need to be able to compare the value from a pin to a list of values and handle the result accordingly. I can easily send the number of the pin to the constructor and read it. My issue is actually defining that list from the `setup()` function.

The list can be variable in length so I can't hard code an array in the library class and then pass values one by one. I can pass the length in the constructor but then I'm not really sure how to use it to initialize the array length without having the values to assign.

In C# or other languages I'd either use a list or pass the array directly. Neither of these seem to be an option with C++ (or at least I couldn't pass the array correctly). How could I solve this problem? If it helps I'm using a teensy++ 2.0.

# Answer
> 2 votes
If the list is a static list you could conceivably pass a pointer to it in the constructor. Example:

```
class myClass {
  const int num_;
  const int * values_;

  public:

  // constructor
  myClass (const int num, const int * values) : num_ (num), values_ (values) { }

  // other stuff here

  // demo
  void printThem ();
};  // end of class myClass

void myClass::printThem ()
  {
  for (int i = 0; i < num_; i++)
    Serial.println (values_ [i]);
  } // end of myClass::printThem

const int NUMBER_OF_VALUES = 6;
const int myValues [NUMBER_OF_VALUES] = { 22, 33, 44, 55, 66, 77 };

// make an instance of the class with the wanted values
myClass foo (NUMBER_OF_VALUES, myValues);

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

  foo.printThem ();
  }  // end of setup

void loop ()
  {

  }  // end of loop

```

That is the simple method. The values in the list are passed to the constructor as a pointer, the class remembers the list and uses it when necessary.

# Answer
> 2 votes
Here are a few examples how to pass vectors and variable number of arguments to a function in C/C++:

```
void foo(int* vector, size_t nmemb);

```

The function *foo* takes a *vector* of integers and the number of members, *nmemb*.

```
const size_t VECTOR_MAX = 5;
int vector[VECTOR_MAX] = { 0, 1, 3, 5, 7 };

foo(vector, VECTOR_MAX);

```

The next variant is generalization. A vector of whatever, number of members, and size of each member;

```
void fie(void* vector, size_t nmemb, size_t size);

```

This allows the function to handle different types of element.

```
fie(vector, VECTOR_MAX, sizeof(int));

```

Examples of usage are the standard library functions qsort() and bsearch().

The next variant is variable arguments. C/C++ allows the syntax "..." for a list of arguments.

```
void fum(size_t nmemb, ...);

```

This allows the following call:

```
fum(5, 0, 1, 3, 5, 7);

```

The implementation of function must be able to "parse" the argument list.

```
#include <stdarg.h>

void fum(size_t nmemb, ...)
{
  va_list ap;
  va_start(ap, nmemb);
  int arg;
  for (size_t i = 0; i < nmemb; i++) {
    va_arg(int, arg);
    ...
  }
  va_end(ap);
}

```

There are four primary methods to determine the number of arguments and value types; 1) number of arguments as parameter and fixed data type, 2) special end parameter value, 3) indirect through format descriptor such as printf() format string, and 4) attribute-value pairs.

Below is an example of variable number of arguments as attribute-value pairs.

```
void set_attrs(size nr, ...);

set_attrs(5, X_POS, 10, Y_POS, 110, R_COLOR, 0, G_COLOR, 255, B_COLOR, 0);

```

A usage of this notation can be found in Motif.

# Answer
> 2 votes
Arrays in C/C++ are handled as a pointer. That means the value of the pointer is the location in memory of the first element in the array. The next element is at that starting address, plus the size of each element. So for an array of 1-byte characters, each item in the array is at the very next address. For 32-bit members, it's at +4, and so forth.

You're storing an array of values to compare with analogRead() - so uint16\_t (aka: short int) will be large enough for each element, without wasting too much memory. But we also need to store a count of them, I'll assume 32-bits is enough readings.

```
uint16_t *comparison_points;
uint32_t  comparison_point_count;

```

These can be declared statically like:

```
uint16_t  comparison_points[] = { 2, 4, 6, 8, 47 };
uint32_t  comparison_point_count = 5;

```

Giving you a comparison function like:

```
bool readingInSet(uint16_t reading, uint16_t *check_points, uint32_t check_points_length)
{
    bool found = false;
    for (uint32_t i=0; i<check_points_length; i++)
    {
        if (reading == check_points[i])
        {
            found = true;
            break;
        }
    }
    return found;
}

```

But you could also make the array into an object, embedding this functionality

```
class AnalogueVector
{
public:
    AnalogueVector(uint32_t size, uint16_t *points)
    {
        comparison_point_count = size;
        comparison_points = points;
    }

    bool readingIn(uint16_t reading)
    {
        bool found = false;
        for (uint32_t i=0; i<comparison_point_count; i++)
        {
            if (reading == comparison_points[i])
            {
                found = true;
                break;
            }
        }
        return found;
    }

private:
    uint16_t *comparison_points;
    uint32_t  comparison_point_count;
};

```

Giving a usage like:

```
uint16_t  comparison_points[] = { 2, 4, 6, 8, 47 };
uint32_t  comparison_point_count = 5;

AnalogueVector cmp_points(comparison_point_count, comparison_points);

if (cmp_points.readingIn(analogRead(A1)))
    Serial.println("Matched");
else
    Serial.println("no");

```

Obviously if you're reading these data points in from a file, or other external media, then you would need to allocate space for the items, and store them in the object.

As with most coding problems, there's multiple solutions. Here I've tried to keep it simple, and explore different ways of handling array data, without getting to far away from that fact that an array in C/C++ is just a big contiguous block of data in memory somewhere. The address of that data, (aka the *pointer*), is simply the address of that first element.

---
Tags: c++, library, teensy
---


title: How to read data from PC

text:
# Question
Title: How to read data from PC
I'm new to Arduino.

I'm passing some data from my Android phone to my Macbook via bluetooth (throught the app Sensoduino).

What I'd like to do now is to export that data to my Arduino Mini Pro.

Is there any way to achieve it?

(NOTE: I'm not able to connect my Android Phone directly to the Arduino via Sensoduino)

# Answer
A simple bluetooth module like a HC-05 wired to your Arduino will give you a serial stream that can be read and/or written.

With the RX/TX connected to say pins 10 & 11, a SoftwareSerial() object will provide access:

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

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

void loop()
{
    int value;

    if (mySerial.available(sizeof(int)))
    {
        value = mySerial.parseInt();
    }
}

```

If you connect the module to pins 0 & 1 - you can just use the Arduino standard Serial functions, but it will cause problems uploading to the board. In which case you would disconnect the bluetooth module for uploading.
> 1 votes

---
Tags: bluetooth, arduino-mini, osx
---


# Question
Title: Use pointer in calculation results in error
I'm building a project to measure/track flyball dog races. The dogs timings are measured by photoelectric sensors at the start/finish line of the racing lane. I have most of my code working (available on github) but I'm having some difficulties in handling very short crossings of dogs. Since I cannot realistically run a real race at home next to my development machine :-), I'm trying to build a simulator class which gives the triggers that would normally come from my photoelectric sensors.

I have a RaceHandler class which has the following in its header file:

```
class RaceHandlerClass
{
 public:
   long* lRaceStartTime = &_lRaceStartTime;

 private:
   long _lRaceStartTime;
}
extern RaceHandlerClass RaceHandler;

```

As you can see I made a public pointer lRaceStartTime which points to the private \_lRaceStartTime member variable. This might seem stupid/strange, but it really should a private member variable, I just want to 'temporarily' make it publicly available, so that I can use it in a temporary 'simulator' class to simulate a race towards my code.

Then I want to use this public pointer in the Simulator class like so:

```
long* lRaceStartTime = RaceHandler.lRaceStartTime;
long lRaceElapsedTime = micros() - lRaceStartTime;

```

However I get the following error when trying to compile this:

> error: invalid operands of types 'long unsigned int' and 'long int\*' to binary 'operator-'

I'm afraid my c++ knowledge ends here and I have no clue what I should do different to fix this... Any help would be greatly appreciated!

# Answer
> 2 votes
Try this:

```
long* lRaceStartTime = RaceHandler.lRaceStartTime;
long lRaceElapsedTime = micros() - *lRaceStartTime;

```

You assigned the pointer to lRaceStartTime on the first line, but on the second line you are subtracting the pointer from `micros()` which returns an `unsigned long`. You need to dereference the pointer before subtracting. Also you might consider making all your longs `unsigned` to match the return type of `micros()` http://arduino.cc/en/reference/micros

# Answer
> 0 votes
I realise your question was but a simple query on syntax. But I would like to point out that the whole idea of object orientation is encapsulating functions and data so that external calls do not have to know about the internal-workings of that class.

It's common with object oriented programming to use 'getters' and 'setters' to modify private member-variables of the class. You really should not be giving a pointer to a *private* member. If you need to read/write it, add a setter function.

```
class RaceHandler
{
public:
    void setStartTime()
    {
        race_start_time = micros();
    }

    void setStartTime(unsigned long start_time)
    {
        race_start_time = start_time;
    }

    unsigned long getStartTime()
    {
        return race_start_time;
    }

    unsigned long getElapsedRaceTime()
    {
        return micros() - race_start_time;
        // TODO: handle overflow of micros() after ~72 minutes
        // maybe use millis() instead
    }

private:
    unsigned long race_start_time;
}

```

Obviously this is laborious. Some languages have special support for getters and setters to provide the functionality with less syntax.

Time is always positive, use an unsigned long. As people have already said, millis() & micros() return an unsigned long too.

```
RaceHandler race1;

race1.setStartTime();

[...]

unsigned long elapsed_time = race1.getElapsedRaceTime();

```

---
Tags: c++, pointer
---


title: Mysterious behavior when using objects

text:
# Question
Title: Mysterious behavior when using objects
I am writing a project that involves using complementary filters to combine gyroscope and accelerator readings in 3 directions. The relevant code is below.

```
class CompFilter {
 public:
   long prevTime;
   float alpha;
   int angle;

   CompFilter(float Alph);
   int combine (float gyroRate, float accelAngle);
};

CompFilter::CompFilter(float Alph) {
 alpha = Alph;
 prevTime = 0;
 angle = 0;
}

int CompFilter::combine(float gyroRate, float accelAngle){
  Serial.println("Here THREE");

 long timeStep = millis() - prevTime;
 if (timeStep == 0) { timeStep = 1;}

 angle = alpha * (angle + gyroRate * timeStep);

 angle += (1.0 - alpha) * accelAngle;

 prevTime = millis();

 return angle;
}

//Global Objects
CompFilter *senPitch; CompFilter *senRoll;  //Declare Complementary Filters

//Adjustable Parameters
float alpha = .5;   //Constant affecting Gyro's vs. Accel's influence on sensor reading

void setup(void)
{
  //Open Data Channel
  Serial.begin(115200);
  Serial.println(F("IMU Complementary Filter Tester")); Serial.println("");

 //Initialise TMU sensors
 sensorInit(accel, mag, gyro);
 senPitch = new CompFilter(alpha); senPitch = new CompFilter(alpha);
  Serial.println("HERE ONE");
}

void loop(void)
{
 //Variables for reading sensors
 sensors_event_t accel_event, mag_event, gyro_event;
 sensors_vec_t   orientation;

 // Retrieve Sensor Readings
 accel.getEvent(&accel_event);
 gyro.getEvent(&gyro_event);
 mag.getEvent(&mag_event);

 Serial.println("HERE TWO");

 int anglePitch = senPitch->combine(gyro_event.gyro.y, orientation.pitch);
 int angleRoll = senRoll->combine(gyro_event.gyro.x, orientation.roll);

```

}

I had to keep track of a couple of pieces of information for each direction, so rather than trying to use parallel arrays, I created a CompFilter class. I think I am using the correct syntax in the class and constructing the object, but I am getting very unusual outputs from Serial.print().

```
RE ONE
RE TWO
Here THREE
Here THREE
entary Filter Tester

```

Depending on how I fiddle with the code, I can get setup() repeating over and over or loop() running once before silently failing.

I suspect that I have misdirected a pointer somewhere, but I am not sure. I would appreciate any help.

# Answer
> 3 votes
Dave X is absolutely right.

I never assigned the senRoll pointer to an object. Then when I tried to dereference it, it went to some random address. I guess there are very few memory protections, so rather than causing a seg fault it just caused erratic behavior.

Thanks for the help.

---
Tags: arduino-mega, c++, class, pointer
---


# Question
Title: Help Understanding FFT Analysis and analogRead()?
Here's the deal, I'm attempting to learn how to use an FFT (Fast Fourier Transformation) Library for sound analysis (link is here). My issue is that this comes with included C++ code to show users how to use the FFT library. There are three examples, but I'll show this one because it's closest to the application I have planned for it:

```
/*
fft_adc_serial.pde
guest openmusiclabs.com 7.7.14
example sketch for testing the fft library.
it takes in data on ADC0 (Analog0) and processes them
with the fft. the data is sent out over the serial
port at 115.2kb.
*/

#define LOG_OUT 1 // use the log output function
#define FFT_N 256 // set to 256 point fft

#include <FFT.h> // include the library

void setup() {
  Serial.begin(115200); // use the serial port
  TIMSK0 = 0; // turn off timer0 for lower jitter
  ADCSRA = 0xe5; // set the adc to free running mode
  ADMUX = 0x40; // use adc0
  DIDR0 = 0x01; // turn off the digital input for adc0
}

void loop() {
  while(1) { // reduces jitter
    cli();  // UDRE interrupt slows this way down on arduino1.0
    for (int i = 0 ; i < 512 ; i += 2) { // save 256 samples
      while(!(ADCSRA & 0x10)); // wait for adc to be ready
      ADCSRA = 0xf5; // restart adc
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int k = (j << 8) | m; // form into an int
      k -= 0x0200; // form into a signed int
      k <<= 6; // form into a 16b signed int
      fft_input[i] = k; // put real data into even bins
      fft_input[i+1] = 0; // set odd bins to 0
     }
    fft_window(); // window the data for better frequency response
    fft_reorder(); // reorder the data before doing the fft
    fft_run(); // process the data in the fft
    fft_mag_log(); // take the output of the fft
    sei();
    Serial.println("start");
    for (byte i = 0 ; i < FFT_N/2 ; i++) {
      Serial.println(fft_log_out[i]); // send out the data
    }
  }
}

```

Now, with that said, I have a very general grasp of the idea that those lines referencing some variable called ADMUX and ADCSRA have to do with the analogRead() method and that the ADCH and ADCL refer to another two components that are combined to provide the returned integer that analogRead() spits out. What I don't understand whatsoever are those seemingly random strings of characters that these are being set equal to. For example, what does 0x40 or 0x01 or 0xe5 even refer to in the setup() method (if nothing else maybe somebody could point me in the right direction for this, because that part I really am entirely clueless about). And furthermore, why manipulate these directly in the first place, because if you reference the source code for analogRead() they look awfully similar. Thanks for any help in advance!

# Answer
It would have been preferable if the author of that code had used proper bit masks. For example:

```
  ADCSRA = 0xe5; // set the adc to free running mode

```

Looking at the datasheet:

Now, **0xe5** is **11100101** in binary.

So that line could have been written:

```
  ADCSRA = bit (ADEN) | bit (ADSC) | bit (ADATE) | bit (ADPS2) | bit (ADPS0);

```

The last two (ADPS2 and ADPS0) give the prescaler (of 32):

The other bits are explained in the datasheet:

* **Bit 7 – ADEN: ADC Enable**

Writing this bit to one enables the ADC. By writing it to zero, the ADC is turned off. Turning the ADC off while a conversion is in progress, will terminate this conversion.
* **Bit 6 – ADSC: ADC Start Conversion**

In Single Conversion mode, write this bit to one to start each conversion. In Free Running mode, write this bit to one to start the first conversion. The first conversion after ADSC has been written after the ADC has been enabled, or if ADSC is written at the same time as the ADC is enabled, will take 25 ADC clock cycles instead of the normal 13. This first conversion performs initialization of the ADC. ADSC will read as one as long as a conversion is in progress. When the conversion is complete, it returns to zero. Writing zero to this bit has no effect.
* **Bit 5 – ADATE: ADC Auto Trigger Enable**

When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a conversion on a positive edge of the selected trigger signal. The trigger source is selected by setting the ADC Trigger Select bits, ADTS in ADCSRB.

---

You can work through the other registers in a similar way.
> 1 votes

# Answer
Nick Gammon already gave a very fine answer about the meaning of the mysterious numbers you were wondering about. Here I am trying to answer only your last question:

> why manipulate these directly in the first place, because if you reference the source code for analogRead() they look awfully similar.

One of the reasons is, as Dave X said in a comment, to get a higher sample rate. Assuming this is an Arduino Uno or similar (ATmega328P @ 16 MHz), the Arduino core normally configures the ADC prescaler to 128. This gives a conversion time of 104 µs (equal to 13 × prescaler ÷ F\_CPU), and a maximum sample rate of about 9.6 kHz. This is fine for telephone quality audio, but insufficient for hi-fi applications. This example code sets the prescaler to 32 for a conversion time of 26 µs and a maximum sample rate around 38 kHz. According to Atmel, the ADC should work fine with this kind of sample rate, except that you should not expect to get the full resolution.

The main reason, however, is not to get a *fast* sample rate, but rather to get a *consistent* sample rate. The problem with `analogRead()` is that it is a *blocking* function. If you look at its source code you will see a busy wait like this:

```
// ADSC is cleared when the conversion finishes
while (bit_is_set(ADCSRA, ADSC));

```

This means that the CPU is not doing anything useful while waiting for the ADC to finish the conversion. If you do `analogRead()` in a loop, the CPU will wait for the ADC, then the ADC will be idle while the CPU completes the loop and so on. The conversion period is then the time required by the ADC *plus* the time taken by the CPU to loop. And the CPU time is hard to predict because it can be influenced by interrupts and by conditional branches inside the loop.

This code, in contrast, configures the ADC to work in *free running mode*. In this mode, the ADC starts a new conversion as soon as the previous one is done. This way you get a steady sample rate while the ADC and the CPU work in parallel. In the loop you see these lines:

```
while(!(ADCSRA & 0x10)); // wait for adc to be ready
ADCSRA = 0xf5; // restart adc

```

The comments are a bit misleading. The first line (which I would rather write `loop_until_bit_is_set(ADCSRA, ADIF);`) waits for a flags that is set when the current conversion is done and the data register updated. The next line does not restart the ADC (it restarted itself, as it is in free running mode): it only clears the flag so that it can be meaningfully tested on the next iteration.

Now, I have a few comments on this code that are not directly related to your question, but may be useful if you are going to build your program on this basis.

First, it should be noticed that the whole ADC-reading loop is done with interrupts disabled. This is *not* normally needed, as the free running mode gives you a steady sampling even if the CPU timing is somewhat jittery. The only valid reason I see for disabling interrupts is if one of your ISRs takes so long to execute that you may miss one sample. This could very well be the case with such a high sampling frequency. But still, there is no point in keeping the interrupts disabled during the FFT processing. And there is no point in turning off Timer 0 if you are disabling interrupts anyway.

My second point is about the three lines starting with `byte m = ADCL;`. Those are meant to read the ADC data register in the proper order: low byte first. However, the C compiler is well aware of the proper way to do read a 16-bit I/O register (see “Accessing 16-bit Registers” in the datasheet chapter about Timer 1). Thus, these three lines can be simplified to just `int k = ADC;`.

My last point is that having the CPU left adjust the result (`k <<= 6`) takes some time, as it is implemented as a loop. There is no point in doing this when the ADC can do it for free: you just have to set the ADLAR bit when configuring ADMUX in `setup()`. Then the 5 lines starting with `byte m = ADCL;` would be reduced to

```
int k = ADC - 0x8000;  // ADC reading as a 16 bit signed int

```
> 1 votes

---
Tags: programming, c++, library, analogread, sound
---


# Question
Title: Are there sensors that can detect the color of an LED?
Are there sensors that can detect the color of an LED?

I am working on an Arduino project that needs to detect the color of an LED on an external device. I am trying to identify a light sensor that can be connected to the Arduino's input that can tell me the color of light the LED is currently emitting. The LED is capable of displaying red, green and yellow.

# Answer
> 2 votes
You mean like this one?

Adafruit RGB Color Sensor

They have similar products in different form factors.

# Answer
> 3 votes
You can use an LED as a light sensor - http://www.instructables.com/id/LEDs-as-light-sensors/

In theory, LEDs should be most sensitive to the frequency it emits - if this is true, the same type of red/green/yellow LED would be best.

I don't know how sensitive this will be.

If you control the "external device", then you could get much better accuracy by blinking the LED at very high rates (not visible to the human eye). Or, if you can get at the legs of the LED, you can tap into the signal directly (you should use an opto-isolator - even if powered at a few volts, the ground of your project may be different from the ground of the external device, causing 100s of volts to run through your Arduino - not good!).

# Answer
> 3 votes
There are a few different things you can do to detect a color.

The Arduino starter kit that I got when I first got into Arduino had some photoresistors plus some colored films. One of the projects in the project book had you put a different color film over each photoresistor, so that only that color of light would hit the sensor. You could do something like that if you only need to check for a small number of distinct colors.

There are also a wide array of color sensors and sensor modules available (just search your favorite online store for "color sensor" or "arduino color sensor"), which will allow for far more detailed and precise color readings, but at a higher price point.

---
Tags: sensors, led
---


# Question
Title: Arduino not detected On El Capitan Public Beta 6
Since I updated to El Capitan Public Beta, my Arduino Uno doesn't show up in the serial devices list.

The System Information utility shows an Arduino connected on the USB port (as 'Communication Device'), but a serial port does not get created at `/dev`.

The board works on Windows and the previous versions of El Capitan.

The problem persists on beta 6.

# Answer
As noted elsewhere, there have been plenty of problems with the CH340 driver and the OSX El Capitan betas, culminating into the driver flat out not working in the latest beta. This is either a bug with OSX or a bug in the driver. I would lean towards this being a bug in the driver, which hasn't been updated since late 2013.

There are other 3rd party drivers that might work on El Capitan. mac-usb-serial.com is the most reliable looking one that I could find, and it does appear to be actively developed. It does cost money, but it is signed (which the mfg. driver isn't) and it has a test utility you can use before purchasing.

The only other options after that are:

* Hope that WCH update their driver (don't hold your breath).
* Program using an external programmer
* Buy an Arduino not using the CH340
> 4 votes

# Answer
I have the OS X 10.11 installed and was unable to upload to my Arduino board. I always got stuck with the error code

```
avrdude stk500_getsync() not in sync resp=0x00

```

After installing the FTDI driver it didnt't work either. So I figured out Apple provides it's own FTDI driver kernel extension since OS X 10.9, named *AppleUSBFTDI.kext*. So the AppleUSBFTDI kernel extension interferes with the FTDI driver. An USB port shows up in the Arduino Application, but no communication involving avrdude is possible.

Solution (without modifying or disabling any system security options introduced in 10.11):

1. Open a terminal
2. Execute: *sudo kextunload /System/Library/Extensions/AppleUSBFTDI.kext/* -\> this will unload the Apple FTDI Kernel extension.
3. Reinstall the FTDI driver
4. Start the Arduino IDE, select a Com Port, the correct Arduino board
5. Compile and upload your sketch to the board.

Please note that *kextunload* will only temporarily unload the module. When your system gets rebooted, you have to do this step again. It's possible to remove the kernel extension, but out of security reasons I don't describe how to do it in this post. If you're familiar with the console, you know how to do this :)
> 1 votes

# Answer
Check this https://www.youtube.com/watch?v=0zuRukW7o0A

* Reboot and press CMD+R immediately after reboot to enter in Recovery Mode
* Open Terminal from Recovery mode
* Run the command csrutil enable --without kext
* Reboot
* Install driver
> 0 votes

# Answer
My version of OS X 10.11 did not have the driver installed for the FTDI cable that I had. I downloaded the drivers here (for free): PL2303 Mac OS X Driver Download
> 0 votes

---
Tags: arduino-uno, serial, ftdi, osx
---


# Question
Title: Understanding global variables on Arduino
I am rewriting a set of LED manipulation functions to be more object oriented, and I have found that, mysteriously, my global variable memory space has been over consumed, despite a reduction of the use of global variables.

I played around with a number of things, and found something curious.

Here is a fragment of a function that does not live in an object, and is called directly from `loop()`:

```
Animation *getNewAnim(int index)
{
    switch(index)
    {
        case 0:
            return new RedClouds();
        case 1:
            return new TwoLayerClouds();
        case 2:
            return new LavaLamp1();
        case 3:
            return new Bubbles1();

        ...  (20 or so more cases)
     }

```

This is a function that lets me switch between display modes based on the value of `index`. Only one of these objects is ever created at a given time; I delete the old one before calling this, so there will never be multiple instances in use simultaneously.

Now the curious thing is that if I remove a few of these return statements, collapsing the block into something like this:

```
Animation *getNewAnim(int index)
{
    switch(index)
    {
        case 0:
        case 1:
        case 2:
        case 3:
            return new Bubbles1();
}

```

The amount of global memory space used falls considerably.

My hypothesis is that the Arduino build environment is pre-allocating space for each of these objects in the global memory space before the program is even run, rather than doing so dynamically as needed.

Is my hypothesis correct? And if so, is there any way to tell the build environment not to do this, as I'd rather use the same memory for my new object that was used by the old one.

To clarify: When I build I see this sort of output:

```
Sketch uses 6,550 bytes (21.3%) of program storage space. Maximum is 30,720 bytes.
Global variables use 1,167 bytes (57.0%) of dynamic memory, leaving 881 bytes for local variables. Maximum is 2,048 bytes.

```

When I refer to "global memory" I am referring to the Global variables number on that output. I'll also note that when I compile with the second example, the program storage space reported also falls dramatically.

**NEW HYPOTHESIS**

Here is what I think may be going on. When I omit the classes from the switch statement, the compiler seems to optimize them out of the codebase, which is what I expect, and is consistent with seeing the program storage space shrink. Each class has a method that returns it's name. This method contains an embedded string, and I now believe that this string is stored in the global variable space. Therefore, if the class is included, more global variable space is consumed to hold the name, and if it is optimized out, less is consumed. This theory is consistent with all the facts I have, and makes more sense than my previous hypothesis.

# Answer
I suggest you take a look at https://stackoverflow.com/questions/16274451/operator-new-for-arduino the new operator is not coming from the c++ libraries, it is coming from the Arduino libraries. It's a wrapper for malloc Is using malloc() and free() a really bad idea on Arduino?
> 1 votes

---
Tags: c++, memory-usage, build
---


# Question
Title: Error: invalid types 'int[int]' for array subscript
I am trying to get an Arduino to work with some Adafruit Motor shields. Everything seemed to work fine, but when I tried to create a function, I get the error in the subject. As far as I can tell, everything was declared properly (the array is initialized and is indexed elsewhere with without issue). Only the function seems to cause an issue.

Would anyone have a guess at what's wrong?

```
    //////// Imports
    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_PWMServoDriver.h"

    ////////My globals. Times are in milliseconds
    unsigned long currentTime = 0;
    unsigned long elapsedTime = 0;
    unsigned long startTime = 0;
    byte currentMotor = 1;
    byte currentShield = 1;
    byte motorRunning = 0;

    //// Settings

    // How many seconds between motors
    unsigned long endTime = 4000;

    // How many shields and motors per shield
    const int nShields = 1;
    const int nMotorsPerShield = 3;

    /////////MicroManager globals
    unsigned int version_ = 2;
    const unsigned long timeOut_ = 1000;
    byte currentPattern_ = 0;
    unsigned long time;

    /////////Adafruit globals
    Adafruit_MotorShield afms[nShields];
    Adafruit_DCMotor *motor[nShields][nMotorsPerShield];

    ////////////Setup
    void setup() {
      Serial.begin(57600);

      unsigned char address = 96;

      for (int i = 0; i < nShields; i++) {
        afms[i] = Adafruit_MotorShield(address);
        address = ++address;
        afms[i].begin();
      }

      for (int i = 0; i < nShields; i++) {
        for (int j = 0; j < nMotorsPerShield; j++) {
          motor[i][j] = afms[i].getMotor(j + 1);
          motor[i][j]->setSpeed(255);
        }
      }

      pinMode(13, OUTPUT);
    }

    ////////////////////Main
    void loop() {
      currentTime = millis();
      elapsedTime = currentTime - startTime;

      if (elapsedTime > endTime) {
        startTime = currentTime;
        currentMotor = currentMotor + 1;
        if (currentMotor > nMotorsPerShield) {
          currentMotor = 1;
        }
      }

      if (Serial.available() > 0) {
        int inByte = Serial.read();

        switch (inByte) {
          case 1:
            if (waitForSerial(timeOut_)) {
              currentPattern_ = Serial.read();
              if (currentPattern_ == 0) {
                for (int i = 0; i < nShields; i++) {
                  for (int j = 0; j < nMotorsPerShield; j++) {
                    motor[1][j]->run(RELEASE);
                  }
                }
              }
              else {
                switchMotor();
              }
              Serial.write( byte(1));
              digitalWrite(13, HIGH);
            }
            break;

          case 30:
            Serial.println("MM-Ard");
            break;

          case 31:
            Serial.println(version_);
            break;
        }
      }

      digitalWrite(13, LOW);
    }

    ////////////////Function definitions

    bool waitForSerial(unsigned long timeOut)
    {
      unsigned long starTime = millis();
      while (Serial.available() == 0 && (millis() - starTime < timeOut) ) {}
      if (Serial.available() > 0)
        return true;
      return false;
    }

    void switchMotor()
    {
      int shield = currentShield - 1;
      int motor = currentMotor - 1;
      for (int i = 0; i < nShields; i++) {
        for (int j = 0; j < nMotorsPerShield; j++) {
          if (i == shield && j == motor)
            motor[i][j]->run(FORWARD);
          else
            motor[i][j]->run(RELEASE);
        }
      }
    }

```

# Answer
Take a close look at this line:

```
motor[1][j]->run(RELEASE);

```

Looks like it should be:

```
motor[i][j]->run(RELEASE);

```

Otherwise it is an illegal index (as there is only one shield).

The next error is in the function switchMotor(). Again, have a close look at the definition of "motor". There is a local variable with that name but you want to also access the global array with the same name.

```
void switchMotor()
{
  int shield = currentShield - 1;
  int motor = currentMotor - 1;
      ^
  for (int i = 0; i < nShields; i++) {
    for (int j = 0; j < nMotorsPerShield; j++) {
      if (i == shield && j == motor)
        motor[i][j]->run(FORWARD);
        ^
      else
        motor[i][j]->run(RELEASE);
    }
  }
}

```

My guess is that this is where the compiler give you the error message!

Cheers!
> 2 votes

# Answer
I get a warning flag in UECIDE for the line:

```
address = ++address;

```

> ‣ operation on 'address' may be undefined \[-Wsequence-point\]

Increment address, and then assign the new value from address into address. That seems a bit odd to me. I think you just meant to increment:

```
address++;

```

Or

```
address = address + 1;

```

Also it flags up the `1` instead of `i` that Mikael found:

> ‣ array subscript is above array bounds \[-Warray-bounds\]

And of course there is the (somewhat hard to spot - Kudos to Mikael for finding it - it took me a bit to see it myself) naming conflict:

> ‣ invalid types 'int\[int\]' for array subscript

It was only when I used the advanced editing facilities of UECIDE to highlight all occurrences of `motor` that I found there was extra ones that shouldn't have been there causing the problem.

So just changing the integer variable name from `motor` to something else fixes it:

```
void switchMotor()
{
  int shield = currentShield - 1;
  int thismotor = currentMotor - 1;       // RENAMED MOTOR
  for (int i = 0; i < nShields; i++) {
    for (int j = 0; j < nMotorsPerShield; j++) {
      if (i == shield && j == thismotor)  // RENAMED MOTOR
        motor[i][j]->run(FORWARD);
      else
        motor[i][j]->run(RELEASE);
    }
  }
}

```
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: I²C with ATTiny85 at 8MHz using TinyWireM library
Hello fellow Arduino enthusiasts, I am trying to make the ATTiny85 talk I²C with a MMA7660 breakout board I have (it's an accelerometer, this is a follow up question to my previous one).

I would state in advance that the I²C chip works perfectly with Arduino Nano, that I am using the Arduino IDE v1.5.6-r2, using the arduino-tiny core (from here) and that until now I had no special issues working at 8MHz.

The official documentation for the **TinyWireM** library (at the Arduino playground website) states that:

> By default the I2C master library (TinyWireM) is set to run at 1MHz. To run at 8MHz, #defines in USI\_TWI\_Master.h / .cpp must be changed.

I have made the following changes in **USI\_TWI\_Master.cpp**:

```
#define F_CPU 8000000UL // was 1000000UL

```

I have made the following changes in **USI\_TWI\_Master.h**:

```
#define SYS_CLK   8000.0 // was 1000.0
#define T2_TWI    1.3 // was 5
#define T4_TWI    0.6 // was 4

```

My guess is that the T2\_TWI & the T4\_TWI values are wrong. I also tried **T2\_TWI 40 and T4\_TWI 32** (as stated here), and **T2\_TWI 2 & T4\_TWI 1** (as stated here) but no luck. I also tried some other values in between that I thought might make sense but it won't work.

The code I am running is the I²C scanner from here (which as I mentioned works perfectly with the Nano and finds the device), the blow is a modified version for interfacing the TinyWireM library instead of the Wire library:

```
#include <TinyWireM.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(-1,4);

void setup()
{
  TinyWireM.begin();
  mySerial.begin(9600);
  mySerial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;
  mySerial.println("Scanning...");
  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    TinyWireM.beginTransmission(address);
    error = TinyWireM.endTransmission();

    if (error == 0)
    {
      mySerial.print("I2C device found at address 0x");
      if (address<16)
        mySerial.print("0");
      mySerial.print(address,HEX);
      mySerial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      mySerial.print("Unknow error at address 0x");
      if (address<16)
        mySerial.print("0");
      mySerial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    mySerial.println("No I2C devices found\n");
  else
    mySerial.println("done\n");

  delay(5000);           // wait 5 seconds for next scan
}

```

As a side note I would say that my logic analyzer was broken recently and I'm sure it would have helped here... Also I am aware of the sound-card hack to be used as logic analyzer, but would prefer to avoid adding more error-prone variables to the system, if possible, for now.

Here is a picture of probing with Saleae logic analyzer of the two channels. The result of the code above is "No I2C devices found":

(Full size picture)

Would appreciate the insights of anyone with experience using ATTiny85 at 8Mhz with I²C successfully.

# Answer
> 1 votes
You really just need to scope the signals, even if it's with a DSO Nano-type scope.

Without downloading the datasheets:

* I would guess your pull-up is probably too small, but possibly too large (scope it)
* Slew rate may be either insufficient or too steep (scope it)
* Be aware that the ATTiny runs at "8MHz", and not 8.00MHz. The timing error can be off enough to cause communication issues at high speeds while working well at lower speeds (scope it, and/or start at default and incrementally increase speed by 0.5MHz until it stops working)
* MMA may not support a typical protocol feature being used, i.e. 'repeated start', burst transfers, etc. (datasheet register/programming section)

Edit: Both the ATTiny and the MMA should have bypass capacitors near the power pins.

# Answer
> 0 votes
Just an idea. On adafruit.com there's a product called Trinket which is an ATtiny85 microcontroller board. It can communicate over I2C using their TinyWireM library. Maybe you should check it out for reference. I hope it helps :)

---
Tags: i2c, attiny
---