body:
I'm trying to use a MIFARE 1K RFID card with RC522 RFID reader/writer for my college project.
I'm trying to understand about memory organization of MIFARE 1K.A documentation() that supplied with a RFID Arduino library() says like this.
I will very appreciate if someone explain me this portion clearly.

> The MIFARE Classic 1K offers 1024 bytes of data storage, split into 16 sectors; each sector is protected by two different keys, called A and B. Each key can be
programmed to allow operations such as reading, writing, increasing valueblocks,
etc. MIFARE Classic 4K offers 4096 bytes split into forty sectors, of which 32 are same size as in the 1K with eight more that are quadruple size sectors. MIFARE Classic mini offers 320 bytes split into five sectors.
For each of these card types, **16 bytes per sector** are reserved for the keys and access conditions and can not normally be used for user data. Also, the very first 16 bytes contain the serial number of the card and certain other manufacturer data and are read only. That brings the net storage capacity of these cards down to 752 bytes for MIFARE Classic 1k, 3440 bytes for MIFARE Classic 4k, and 224 bytes for Mini. It uses an NXP proprietary security protocol (Crypto-1) for authentication and ciphering.

Accordind to above quote,

>For each of these card types, **16 bytes per sector** are reserved for the keys and access conditions and can not normally be used for user data.
> Blockquote

Explain how to divide 1024 bytes like this.It has 16 sectors.So,total memory should be 16*16=256 bytes.This is impossible. Please explain this.

title: Memory organisation of MIFARE 1K

Answers: 3

body:
You're reading (and doing your sums) backwards.

You have 1024 bytes of data space.

That data space is split into 16 sectors, so 1024 / 16 = 64 bytes per sector.

Each sector has 16 bytes reserved for keys etc, so each sector has 64 - 16 = 48 bytes of user data space.

48 bytes of user data space per sector multiplied by 16 sectors is 768 bytes.

Incidentally 1024 - 768 = 256, which is what you were calculating before.  What you calculated was the amount of the 1024 bytes that is reserved *in total* for the keys and access controls.

body:
Divide 1024 bytes into 16 sectors -

    1024 bytes / 16 sectors = 64 bytes per sector

The first 16 bytes of each sector are used for 'management' and thus reserved. This leaves -

    64 - 16 = 48 bytes (per sector) for general storage

body: There is also an excellent graphic of the various mifare card layouts, that someone has put together: https://upload.wikimedia.org/wikipedia/commons/thumb/3/39/MiFare_Byte_Layout.png/220px-MiFare_Byte_Layout.png


body:
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;
      }
    }

title: Esp8266 Arduino smart connect

Answers: 2

body:
The following code can do what you want ([source](https://gist.github.com/dogrocker/f998dde4dbac923c47c1)), 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 = "
";
      for (int i = 0; i < n; ++i)
        {
          // Print SSID and RSSI for each network found
          st += "
";
          st += WiFi.SSID(i);
          st += " (";
          st += WiFi.RSSI(i);
          st += ")";
          st += (WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*";
          st += "
";
        }
      st += "
";
      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\nHello from ESP8266 at ";
            content += ipStr;
            content += "
";
            content += st;
            content += "
<form method='get' action='setting'>SSID: <input name='ssid' length=32><input name='pass' length=64><input type='submit'></form>";
            content += "";
            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";
          content += "
Clearing the EEPROM
";
          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:

[![enter image description here][1]][1]

Note that there is a [link to a similar library](https://github.com/tzapu/WiFiManager) in the comments of the source link, that didn't work for me but you can try it.

  [1]: https://i.stack.imgur.com/imsTv.jpg

body:
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);
        }


body:
I'm new to Arduino and electronics. I want to make a project including SD data-logger, but I had a problem. I would appreciate if someone show me where I made a mistake.

Firstly, circuit  was set up as in picture:

[![Hardware setup][1]][1]

I am using 8 Gb micro SDHC card with SD adapter. I formatted in FAT32. I can play audio files which are in appropriate format and read and the print contents of text files.

But when I want to create a new file, strange file is obtained in SD card as in pic:

[![Directory listing][2]][2]

So I reformat SD card. the code that is used while creating file is as this;

    // open a new file and immediately close it:
    Serial.println("Creating example.txt...");
    myFile = SD.open("example.txt", FILE_WRITE);
    myFile.close();

Somewhere I read SDHC card with more than 2 Gb capacity  is not supported in Arduino and I bought 2 Gb SD micro with SD adaptor.

But in this case aurduino does not detect SD card. please someone help me.

  [1]: https://i.stack.imgur.com/Htgk6.jpg
  [2]: https://i.stack.imgur.com/CxVEy.jpg

title: arduino creates strange files in SD card

Answers: 2

body:
I've had similar issues with large (> 1Gb) SD cards, I've had various different problems with different cards, some things that helped me debugging the problem:

 - make sure your wires are the same length and try to use **short wires**
 - make sure your power supply is sufficient, sd card readers can draw up to `150mA`
 - format the card in either `FAT16` or `FAT32` and never use "quick erase", try to use official tools (like https://www.sdcard.org/downloads/formatter_4/index.html)
 - make sure if you're the correct `BAUD rate` (9600) to talk to your card
 - filename support is pretty old so keep them short and don't use spaces or special characters
 - make sure the SD card is not in "**write lock**" mode, there's a small switch on the side of some SD cards that can prohibit writing (but will allow reading)

body:
I have faced this problem. Try

 - If you are using multiple devices with SPI communication ignore the others by keeping their slave select HIGH
 - Never forget `file.close()`


body: Is it possible to create a set of ultrasonics frequencies using only the Arduino? What code to be used? And how am I going to do for it to work? For this project I need to focus in  the emitter side; all resources on Google are only on sensor and distance detector. I just want to use ultrasonic on other field just like for example on repelling rats. Thanks!

title: Sets of Ultrasonic frequencies using arduino uno

Answers: 2

body:
There are three parts to this project, one of which you asked:

1.  I need to generate a frequency greater than 40 khz using arduino uno?

This one is easy: Yes. You can use the tone() library call. You can specify a frequency up to 8mhz. You can call this in the `void setup{}` part of your code, and (if you don't want to do anything else), leave the `void loop() {}` empty. You might want to generate an audible tone for a short period first, to show that it is working.

2. You need something to actually make the sound.

Depending on the frequency, most speakers won't do the trick, or will do it at a very low volume. Speakers are made to work with audible frequencies. Even then, some speakers (larger ones) are better at low frequencies; others (smaller ones) are better at higher audible frequencies. I think piezoelectric buzzers would give you a better response at higher frequencies. In any case, whatever you buy find out the frequency response for the specific part, find the frequency you intend to use along the bottom, then see what the volume (db) is for that frequency - this will give you an indication of how loud it will be. Remember that you won't be able to hear it.

The circuit is pretty trivial. Google piezo arduino

3. Efficacy:

From https://en.wikipedia.org/wiki/Electronic_pest_control#Effects_on_rodents

> Rodents adjust to the ultrasound (or any new sound) and eventually ignore it. At best, ultrasonic waves have only a partial or temporary effect on rodents. Numerous studies have rejected ultrasonic sound as a practical means of rodent control.Tests of commercial ultrasonic devices have indicated that rodents may be repelled from the immediate area of the ultrasound device for a few minutes to a few days, but they will nearly always return and resume normal activities. Other tests have shown that the degree of repellance depends on the frequency, intensity, and pre-existing condition of the rodent infestation. The intensity of such sounds must be so great that damage to humans or domestic animals would also be likely; commercial ultrasonic pest control devices do not produce sounds of such intensity.

body: Another answer to generating ultrasonic frequencies is to ditch the Arduino altogether - use a 555 timer circuit (for lower range frequency, probably up to low mHz), or a resonator. A quick search found a 2.4 gHz resonator for less than an Arduino. 555 timers can be tuned, resonators cannot. I think you could build a 555 square-wave generator for about $1-$2.


body:
I enable messages about new SMS

    AT+CNMI=2,2,0,0,0

    OK
and when received sms, output like this.

    +CMT: "+79XXXXXXXXX","1","15/09/23,01:34:03+24"
    Test

But when I read message, output only before `<CR><LF>`
I don't see text of message.

    AT+CMGR=1

    +CMGR: "REC READ","+79XXXXXXXXX","1","15/09/23,00:34:17+24"

    AT+CMGL="ALL"

    +CMGL: 1,"REC READ","+79XXXXXXXXX","1","15/09/23,00:34:17+24"
    +CMGL: 2,"REC READ","+79XXXXXXXXX","1","15/09/23,01:34:03+24"

I use [following](https://gist.github.com/YokiToki/9d5e730c0c196ebaf3cf)  (via SoftwareSerial) code for test this.
`SMSGSM.GetSMS` and `SMSGSM.GetAuthorizedSMS` of [GSM GPRS GPS Shield Library](https://github.com/MarcoMartines/GSM-GPRS-GPS-Shield) receive only phone number without sms text.

I use this shield:
![_57](https://cloud.githubusercontent.com/assets/1845813/10030856/50090b88-6193-11e5-916b-5f58ac58e6d8.JPG)

    AT+GSV

    SIMCOM_Ltd
    SIMCOM_SIM900
    Revision:1137B05SIM900M64_ST_ENHAN

title: SIM900 Shield read only sms headers without text

Answers: 2

body:
Could you confirm that any of the commands sent over your `SoftwareSerial` are responding?

You probably need to add a `"\n"` (new line) at the end of your messages or just use `println()`.

Also, add your code to the question so we can be of better assistance.

body:
This is most likely a case of overrun SoftwareSerial buffer. You are reading too slowly from the modem, especially with the `Serial.print()`s in your code. You should look for SoftwareSerial.h in `C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial` if you're using Win 8 and above. Or just search your PC for it. Look for this line:

        #define _SS_MAX_RX_BUFF 64

Change 64 to 256 and save. If it solves your problem, try reducing 256 to 128 to see if it still works. The greater the size of the buffer, the lesser the amount of memory available to the rest of your program.

You could also try this, to interact with the module:

    #include <SoftwareSerial.h>

    SoftwareSerial SIM900(7,8);

    void setup() {
      Serial.begin(19200);
      SIM900.begin(19200);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      while (Serial.available() > 0){
        SIM900.write(Serial.read());
      }
      while (SIM900.available() > 0){
        Serial.write(SIM900.read());
      }
    }

It does the same thing as your code and doesn't require adjusting buffer size, though I still recommend you make the change if you will use other sketches.


body:
I have two Arduino Leonardos here. They do different things, but basically they both emulate a keyboard. Here is an example:

    const byte SWITCH = 12;

    void setup ()
      {
      Keyboard.begin();
      pinMode (SWITCH, INPUT_PULLUP);
      }  // end of setup

    void loop ()
      {
      if (digitalRead (SWITCH) == LOW)
        {
        Keyboard.println ("foo");
        delay (2000);
        }
      }

Now I program a second Leonardo with the same code but send "bar" rather than "foo".

Now if I plug these into my PC (running Ubuntu 14.04) using different USB ports, everything works. When the switch is closed I see "foo" and "bar" being typed into whatever application is open.

However ...

If I plug them both into a D-Link 4-port USB hub (model DUB-1340) only the first one works. The other is ignored.

Doing `lsusb` shows this (along with other irrelevant devices):

    $ lsusb
    Bus 003 Device 040: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)
    Bus 003 Device 039: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)

This happens in both cases (if they are both in the USB hub or not).

---

## My question

Is this proper behaviour that two Leonardos on a USB hub fail to both work? (Perhaps you aren't supposed to plug two identical USB devices in at once).

Or, is this a bug in either:

* The Leonardo USB interface?
* My USB hub?

---

## Update

Further testing revealed that the setup worked OK when plugged into my Mac running OS/X.

Then I went back to Ubuntu and it worked as well! However a mouse that I had plugged into the USB hub now stopped working!

Further investigation reveals that the fourth port on my USB hub is faulty in some way. If I swap the mouse and the Leonardo the Leonardo works but not the mouse.

Following Majenko's suggestion:

> You can try running usb-devices from the usbutils package (should be already installed since lsusb is in the same package) and look for the two Leonardo blocks.

First one:

    T:  Bus=03 Lev=02 Prnt=50 Port=00 Cnt=01 Dev#= 66 Spd=12  MxCh= 0
    D:  Ver= 2.00 Cls=02(commc) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
    P:  Vendor=2341 ProdID=8036 Rev=01.00
    S:  Manufacturer=Arduino LLC
    S:  Product=Arduino Leonardo
    C:  #Ifs= 3 Cfg#= 1 Atr=80 MxPwr=500mA
    I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(commc) Sub=02 Prot=00 Driver=cdc_acm
    I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=cdc_acm
    I:  If#= 2 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=00 Prot=00 Driver=usbhid

Second one:

    T:  Bus=03 Lev=02 Prnt=50 Port=03 Cnt=04 Dev#= 72 Spd=12  MxCh= 0
    D:  Ver= 2.00 Cls=02(commc) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
    P:  Vendor=2341 ProdID=8036 Rev=01.00
    S:  Manufacturer=Arduino LLC
    S:  Product=Arduino Leonardo
    C:  #Ifs= 0 Cfg#= 0 Atr= MxPwr=
    cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceNumber: No such file or directory
    cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bAlternateSetting: No such file or directory
    cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bNumEndpoints: No such file or directory
    cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceClass: No such file or directory
    cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceSubClass: No such file or directory
    cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceProtocol: No such file or directory
    /usr/bin/usb-devices: line 79: printf: (none): invalid number
    I:  If#= 0 Alt= 0 #EPs= 0 Cls=() Sub= Prot= Driver=

---

## Tentative conclusion

Perhaps I somehow damaged that USB port by drawing too much current during testing at some earlier point.

Although ... now the mouse is working in the port where it was not working before, and the Leonardo has stopped working in the 3rd port, when it was previously not working in the 4th port.

Those error messages above must be relevant, but I don't know enough about it to say in what way.

title: Two Leonardos on one USB hub - not working properly

Answers: 1

body:
There is no reason I can think of that would stop it working as it should.

`lsusb` is showing both the devices, so they are being detected by the kernel.

You can try running `usb-devices` from the *usbutils* package (should be already installed since `lsusb` is in the same package) and look for the two Leonardo blocks. You should get two blocks like this:

    T:  Bus=01 Lev=03 Prnt=07 Port=00 Cnt=01 Dev#= 11 Spd=12  MxCh= 0
    D:  Ver= 2.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
    P:  Vendor=2341 ProdID=0036 Rev=01.00
    S:  Manufacturer=Arduino LLC
    S:  Product=USB IO Board
    C:  #Ifs= 3 Cfg#= 1 Atr=80 MxPwr=500mA
    I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(commc) Sub=02 Prot=00 Driver=cdc_acm
    I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=cdc_acm
    I:  If#= 2 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=00 Prot=00 Driver=usbhid

The important bit is the `I:` lines - they show the individual USB interfaces and what kernel driver has been associated with them.   For the keyboard, of course, it's the last entry, which is assigned to the `usbhid` driver.

Another good diagnostic is `dmesg -w`

Run that with both Leonardos disconnected.  Plug one in and it should show it registering as a USB device.  A few moments later you should get a pair of lines like:

    [ 2106.937086] input: Arduino LLC USB IO Board     as /devices/pci0000:00/0000:00:1a.7/usb1/1-1/1-1.4/1-1.4.1/1-1.4.1:1.2/0003:2341:0036.0006/input/input21
    [ 2106.990523] hid-generic 0003:2341:0036.0006: input,hidraw4: USB HID v1.01 Mouse [Arduino LLC USB IO Board    ] on usb-0000:00:1a.7-1.4.1/input2

That is the board being associated with an input device (in this case input 2).

Repeat it with the second Leonardo and see if the same appears, but this time with a higher input number (it would be 3 on mine if I had a second Leonardo).

The fact that the two Leonardos work together normally means that they should be working fine in any arrangement, so if the OS is seeing it all fine but the data isn't getting through, then my money is on the hub.  It looks quite a new hub, so it may have a few bugs in it that are yet to be ironed out.

USB devices are identified to the drivers using the VID and PID, but to the kernel the USB device is just a chain of bus/port numbers.  For instance my Leonardo above is identified as:

    1-1.4.1

That's USB bus 1, downstream port 1 (root hub - normally only has 1 port), which connects to a hub (the one built into the computer to drive multiple ports) which then has downstream port 4 connecting to a hub (on my desk) which then has downstream port 1 connecting to the device.  Nothing else can be connected to that same combination of downstream ports - it's physically impossible, so it's uniquely identified.


body:
I followed instructions to get my TFT to work.

[![TFT photo][1]][1]

I want to use other pins on the Arduino Uno for other I/O, so how can I use 4-bit data transfer for the TFT touchscreen?

  [1]: https://i.stack.imgur.com/VtD3P.jpg

title: TFT touch, 4bit data transfer

Answers: 1

body: You read the datasheet for the chip that is on your TFT display (whatever that is) and find if it even supports a 4-bit mode.  It probably doesn't. I have a large number of TFT screens here and I don't recall any of them using parallel 4-bit.  It sounds like you actually want a TFT screen that works of SPI rather than a parallel interface.  Those *are* available, but by using SPI the screen updates are considerably slower.


body:
I'm looking for a way to wait for a response from an AT command to return OK or CONNECTED or whatever the command returns when it's true.

I can check if the serial is available, but that means I have to manually guess what time between commands to give them time to connect or start.

Function:

    void ModemCommand(String command) {
      //Send command to modem
      mySerial.println(command);
      Serial.println(command);
      delay(100);
      while (!mySerial.available()) {
        //Wait for Response from modem
        Serial.println(F("No response yet"));
        delay(1000);
      }
      while (mySerial.available()) {
        Serial.write(mySerial.read());
        //Print response from modem
      }
      Serial.println("");
      //Linefeed after reponse
      delay(10);
    }

Code example:

    ModemCommand(F("ATE0"));
    //Turn on echo
    ModemCommand(F("AT+CFUN=1"));
    //Turn modem functions on
    waitSec(8,F("turning on Modem functions"));
    ModemCommand(F("AT+CGREG?"));
    //GSM attached?
    ModemCommand(F("AT+CSQ"));
    //Signal Quality
    ModemCommand(F("AT+CSTT=\"internet\""));
    //Set APN
    ModemCommand(F("AT+CIICR"));
    //Connect to APN GPRS
    waitSec(8,F("connecting to APN GPRS"));
    ModemCommand(F("AT+CIFSR"));
    //Get IP

Does anybody know how to do this?

title: Waiting for an AT command to complete

Answers: 2

body:
You would need to create a buffer which will populate over each loop so you dont block the main loop while waiting the all string.

When you get the string or your buffer is full, just check whatever is the response, and based on that you can make your decision.

body:
The most you can do is define a certain amount of time between received characters, after which you can decide that there's nothing more to be read from the modem. Of course, the time taken for processing is longer for certain commands (and some provide no response at all, until you've completed entering their payload, like TCPSEND, in which case you should simply use `mySerial.write()` to send said payload, and not your function), but once a response is ready and its first character is available, a timeout of 1 second between characters should be sufficient, for any reasonable baud rate. Something like this:

    #define TIMEOUT 1000

    void modem_command(String command){
      mySerial.println(command);
      Serial.println(command);
      while (mySerial.available() == 0);  // wait for first char

      unsigned long lastRead = millis();   // last time a char was available
      while (millis() - lastRead < TIMEOUT){
        while (mySerial.available()){
          Serial.write(mySerial.read());
          lastRead = millis();   // update the lastRead timestamp
        }
      }
      // No need for extra line feed since most responses contain them anyways
    }

Of course, you can always alter `TIMEOUT` based on your findings.


body:
To reduce the components amount I don't want to put the  32.768 kHz oscillator on my own Due.
Can I leave the corresponding XTAL inputs unconnected?

What is the main target of the slow clock?
What I can not do with the high clock but can do with the slow one?
Will I face to any issues if I don't use the low freq. oscillator?

title: Arduino due slow clock

Answers: 2

body:
The slow clockr is primarily used for the real time clock (RTC) module inside the SAM3X chip.  It can also be routed to other places when you want a low speed clock source, but the only places it is actually *required* are the RTC and the watchdog.

The slow clock can be generated from an internal RC oscillator instead of requiring an external crystal, but the accuracy and stability of the RC oscillator is many orders of magnitude worse than a crystal.  Trying to use that for the RTC module will result in the clock drifting over time.  The watchdog won't really care if the clock isn't perfectly accurate.

body:
Atmel datasheet says:

**If the user does not need the crystal oscillator, the XIN32 and XOUT32 pins can be left unconnected**


body:
Arduino does not recommend to program the Due board via Native port  as it is not reliable:

*If the MCU crashed for some reason it is likely that the soft erase procedure won't work as this procedure happens entirely in software on the SAM3X*

Unfortunately Arduino doesn't say what is crash and how to solve this issue if your home made Due has only the Native port.

I have only several assumptions but not sure that they are correct.

The Arduino Due boot-loader starts only if the Flash is not programmed. If the code is programmed to the flash but is damaged the boot-loader will not
start. As the MCU is hanged it can not erase the flash.

What can be done in this situation?

Just push the erase button on the board. It will the erase the content of the memory and allow boot-loader to start.

Now the programming via the Native port should be possible.

Please correct me if I'm wrong.

title: Arduino Due native programming port

Answers: 0


body:
I need to control about 6 RGB Led Strips from an Arduino Board. The problem is that i need 3 PWM outputs for each led strip, but each will have probably the same colors. I was wondering if i could put two strips receiving a signal from the same PWM output, then i would have to use half the PWM outputs but send the same signal for each pair of strips.

The scheme i found is this one:

[![arduino schematic][1]][1]

And what i want is something like this:
[![enter image description here][2]][2]

Is this possible? What should i modify to make it work?

Thanks in advance.

  [1]: https://learn.adafruit.com/system/assets/assets/000/002/693/medium800/led_strips_ledstripbjt.gif?1396785837
  [2]: https://i.stack.imgur.com/yokZr.png

title: Light multiple RGB Led Strips from same 3 RGB PWM outputs

Answers: 1

body:
You have few options:

 1. do as you represented in the drawing: it should work, as I expect the transistors to not load too much the input.

 2. add a [logic buffer][1] inbetween the arduino and the driver stage

 3. use other pins from the arduino for driving the additional strips and bitbang the PWM, instead of using the HW blocks

Whether the solution you propose (1) will work or not depends entirely on the max current that each PWM pin can output vs the total load from the 3 transistors it will have to drive.

  [1]: http://www.digikey.com/product-search/en/integrated-circuits-ics/logic-buffers-drivers-receivers-transceivers/2556308


body:
I'm making a simple Infrared detector using a thermopile. I have a few extra capacitors than what that schematic says. I'm currently following another, but this is the gist.

Schematic and Breadboard- [![Breadboard and Schematic][1]][1]

**I can add breadboard picture if needed. I don't have 10 points in this Stack so I can't post more than 2.**

I'm using a 9V battery through a 24v - 5v regulator (had one around) to power my op amp and schematic. The signal from the OPAMP will be between 0-5V so voltage hasn't damaged the Arduino Uno. The final project will be something like: output > A then power green, A < output < B power yellow, B < output red.

The issue is that I'm getting an oscillating value from my Serial Monitor that goes from 0 to 1023 (or I have a conversion to change it back to output voltage. So 0V to 5V. See code).

It does this oscillation when I have the board connected to any of the AX pins (X=0-5) or nothing plugged in at all (I understand it will output weird numbers with the pin floating).

**I had a picture of the serial monitor but I don't have 10 points to add more than 2 pictures. Please see image below**

I know that the output from the OPAMP works because when I use a VoltMeter to read the output, it works fine. 0.3XXV when no flame, 5V when flame is directly on top of my theromopile. [![Serial Monitor and VM][2]][2]

Would anyone happen to have a suggestion to why the Arduino is acting this way? The volt meter reading is directly out of the Op amp pin 1. **no more than 2 links. AD822 op amp**

Here's my code before adding if statements for the LED's. It was incorrect.

    int TP=A2; // Assign Thermopile to pin A2
    int val; // Declare readValue Variable
    float Voltage; // Declare real world voltage variable - Float = in between variable
    int ledG = 11;
    int ledY = 12;
    int ledR = 13;

    void setup() {
     pinMode(TP,INPUT); // Declare Thermopile pin as input
     pinMode(ledG, OUTPUT);
     pinMode(ledR, OUTPUT);
     pinMode(ledY, OUTPUT);
     Serial.begin(9600); // Start your Serial Port
    }

    void loop() {
      val = analogRead(TP); // Read Thermopile pin and place value into readValue

      Voltage = (5./1023.)*val; // To do "floating point math" have a "." //after the number. If not, it will return real number (5/1023 = 0) according to Arduino

    Serial.println(Voltage); // Print readValue to Serial Monitor
      delay(100); // Delayed output to 1/4 a second
    }

  [1]: https://i.stack.imgur.com/cvHXe.jpg
  [2]: https://i.stack.imgur.com/rIZ78.jpg

title: Arduino Analog Input Oscillating

Answers: 1

body:
It seems you haven't connected the circuit ground to the Arduino ground.  This is essential to complete the circuit between your breadboard and the Arduino.  Without the ground connection the electrons that you send to the Arduino have no way of getting back again.

Here's a couple of diagrams that I drew for another question which deals with the Arduino driving a remote device, but the theory holds true no matter which way around it is.

[![enter image description here][1]][1]

In that diagram the red arrows (*not the aerial display team I hasten to add*) represent the connection between your breadboard circuit and the Arduino.  Without the ground connection there is no circuit, and a circuit is always needed for current to flow (and hence your signal).  With the ground connection the red arrows become a loop which allows the current to flow and transfer your signal.

  [1]: https://i.stack.imgur.com/gFtVI.png


body:
I would like to place analog sensor in a place, that is impractical to reach with a wire. But it looks like an overkill to use a separate small Arduino board to read and transmit sensor signal to main Arduino board at a close range (~1 m).

Is there a cheap practical way to setup such sensor signal broadcast over RF without using Arduino board? Something that could work for considerable duration with a small tablet like battery?

title: Is there a away to transmit sensor signal over RF without Arduino?

Answers: 2

body:
You don't have to use a $30 Arduino. You can make a "breadboard" one for a few dollars, like this:

[![Breadboard Arduino][1]][1]

$5 for the chip and a couple of dollars for a couple of capacitors and resistors.

---

Add to that a NRF24L01 transceiver like this:

[![NRF24L01][2]][2]

Available from eBay for around $1 each. You need two, as you need to transmit from one and receive from another.

So the whole thing could be done for under $10.

---

> Something that could work for considerable duration with a small tablet like battery?

See [Power saving techniques for microprocessors](http://www.gammon.com.au/power)

  [1]: https://i.stack.imgur.com/jBTgZ.jpg
  [2]: https://i.stack.imgur.com/WDHUg.jpg

body:
I would recommend investigating the ESP8266 modules.  Many people use them as a WiFi interface to an Arduino, but they are also capable of being used completely standalone.

You can pick up a cheap module and program it using a readily available USB to TTL UART adapter using the ESP8266 plugin to the Aduino IDE.

https://github.com/esp8266/Arduino

It's like having an Arduino and a WiFi interface all embedded in one chip, and the modules are tiny too - perfect for embedding in a project.

There are many different modules available, some with more pins than others for IO.  The best one is the NodeMCU since it has the programming interface built in (go for version 1.0 not version 0.9 since it has better IO options), but the higher end ESP8266 modules on carrier boards (ESP-12, etc) are as good, if a little harder to work with.


body:
I have found a few good tutorials on how to send and receive data via I2C in connected arduinos. My limitation is now how to transmit different types of data like for instance, long, float, etc. Right now the communication via I2C using the wire library only allows transmission of numbers between 0 and 255. How can one transmit different types of numbers?.

In my code a master receives three types of data from the slave, and it send data of a fourth variable to the slave.

here is the code for the master

    #include <Wire.h>

    const int SLAVE_ADDRESS = 8; //Slave arduino ID
    int table[]={0,0,0}; //the data will be transmited via table as to allow different data to be transfer.
    void setup ()
    {
    Wire.begin ();
    Serial.begin (9600);  // start serial for output
    }  // end of setup
    void loop()
    {
    Wire.requestFrom(SLAVE_ADDRESS, 3);// request 3 bytes from slave device #8

    for(int i=0;i<3;i++)//organizes the data from the slave in the table
    {
    int c = Wire.read(); // receive a byte as character
    table[i]=c;
    }
    //displays the data
     Serial.print('\n');
       Serial.print(table[0]);
        Serial.print('\t');
       Serial.print(table[1]);
        Serial.print('\t');
       Serial.print(table[2]);
       Serial.print('\n');

    delay (500);

    // transmit just this variable to the slave
    int Work=1;
    Wire.beginTransmission (8);
    Wire.write (Work);
    Wire.endTransmission ();
    }

here is the code for the slave

    #include <Wire.h>
    int table[]={0,0,0};
    int Work=0;

    void setup() {
    Wire.begin(8);                // join i2c bus with address #8
    Wire.onRequest(requestEvent); // register event
    Wire.onReceive(receiveEvent); // register event
    }

    void loop() {
    int x=120;
    int y=1200;// gets converted to an strange # because is larger than 255
    int z=3;
      table[0]=x;
      table[1]=y;
      table[2]=z;
    }

    void requestEvent()
    {
      uint8_t Buffer[3];
      Buffer[0]=table[0];
      Buffer[1]=table[1];
      Buffer[2]=table[2];
      Wire.write(Buffer,3);
    }

    void receiveEvent(int howMany)
    {Work = Wire.read();}

title: Sending and receiving different types of data via I2C in Arduino

Answers: 3

body:
I believe that for your scenario, i.e. sending different types of variables, the EasyTransfer library (by Bill Porter) would be an elegant solution. The library can be found here: [https://github.com/madsci1016/Arduino-EasyTransfer][1]. There are implementations for serial, I2C, and VirtualWire and the examples provided are pretty self-explanatory.

The handling is very easy. After including the library, you create an EasyTransfer object, define a data structure that basically represents a "container" of your data and this can consist of different variables.

    struct RECEIVE_DATA_STRUCTURE{
      //put your variable definitions here for the data you want to receive
      //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
      int blinks;
      int pause;
    };

Once the "container" is filled, i.e. the variables are set on the sender side, they are sent with a simple command

      ET.sendData(I2C_SLAVE_ADDRESS);

On the receiver side, you define an identiacl data structureand receive the data by

    ET.receiveData();

Hope this helps.
[1]: https://github.com/madsci1016/Arduino-EasyTransfer

body:
I2C is truly a powerful option of Arduino, for too many reasons; yet the amount of tutorials available are not that many and unfortunately are too complicated for the average person.

After working on this for 2 days, I think I have a way to transfer pretty much anything between master and slaves and viceversa. Note that I2C does not transfer floats or even integers larger than 255, there are several ways to go about this and here is a good tutorial
http://www.gammon.com.au/i2c
and even a library: http://forum.arduino.cc/index.php?topic=171682.0

The solution I found was simpler. Basically we convert any value, string, number, text, float, you name it, and turn into a variable char, which can be transferred via I2C. Once transferred, you can convert back to a number although in my case below, I just wanted to display the data from the slave.

Here is the code. I provide comments on different parts for clarity. I hope this helps. it worked for me.

    //master
    #include <Wire.h>

    char t[10]={};//empty array where to put the numbers comming from the slave
    volatile int Val; // varaible used by the master to sent data to the slave

    void setup() {
      Wire.begin();        // join i2c bus (address optional for master)
      Serial.begin(9600);  // start serial for output
    }

    void loop() {
      Wire.requestFrom(8, 3);    // request 3 bytes from slave device #8

    //gathers data comming from slave
    int i=0; //counter for each bite as it arrives
      while (Wire.available()) {
        t[i] = Wire.read(); // every character that arrives it put in order in the empty array "t"
        i=i+1;
      }

    Serial.println(t);   //shows the data in the array t
    delay(500); //give some time to relax

    // send data to slave. here I am just sending the number 2
      Val=2;
      Wire.beginTransmission (8);
      Wire.write (Val);
      Wire.endTransmission ();
    }

here the other part
    //slave

    #include <Wire.h>

    char t[10]; //empty array where to put the numbers going to the master
    volatile int Val; // variable used by the master to sent data to the slave

    void setup() {
      Wire.begin(8);                // Slave id #8
      Wire.onRequest(requestEvent); // fucntion to run when asking for data
      Wire.onReceive(receiveEvent); // what to do when receiving data
      Serial.begin(9600);  // serial for displaying data on your screen
    }

    void loop() {
      int aRead = analogRead(A0); //plug a potentiometer or a resistor to pin A0, so you can see data being transfer
      float x = aRead/1024.0*5.0; //generate a float number, with this method you can use any time of data pretty much

      dtostrf(x, 3, 2, t); //convers the float or integer to a string. (floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, empty array);
      Serial.println(Val);         // print the character
     delay(500);
    }

    // function: what to do when asked for data
    void requestEvent() {
    Wire.write(t);
    }

    // what to do when receiving data from master
    void receiveEvent(int howMany)
    {Val = Wire.read();}

body:
Use the 'I2C_Anything' library, available [here][1]. I use it in all my I2C projects.  It is extremely simple and works great. Here's the entire .h file

    // Written by Nick Gammon
    // May 2012

    #include <Arduino.h>
    #include <Wire.h>

    template <typename T> unsigned int I2C_writeAnything (const T& value)
      {
      Wire.write((byte *) &value, sizeof (value));
      return sizeof (value);
      }  // end of I2C_writeAnything

    template <typename T> unsigned int I2C_readAnything(T& value)
      {
        byte * p = (byte*) &value;
        unsigned int i;
        for (i = 0; i < sizeof value; i++)
              *p++ = Wire.read();
        return i;
      }  // end of I2C_readAnything

  [1]: https://github.com/nickgammon/I2C_Anything


body:
I have a piece of a broken camera flash (an old Yongnuo one) that has a single pin that tells the flash when to fire. The pin looks like this :[![bottom of flash module][1]][1]
(I guess the ring is the return/ground?)

The other side of the piece looks like this:
[![circuit side of flash module][2]][2]

If my guess isn't completely wrong, those four wires are the only thing that tell the rest of the flash unit what's going on, when. So if I plugged (two, three, all four?) of those pins into my arduino I could use it as an input, yes?

I.e. Arduino would detect when the camera has taken a picture via this unit, and do something else (in my case open the gate on a mos for a length of time). No actual camera flash involved (just the signal)

My question is: how do I determine which of these four wires carry the signal to the rest of the circuit, and can I plug this into my Arduino input pin? My multimeter is a cheap crappy one so I don't think it would react fast enough to measure a pulse like that...

  [1]: https://i.stack.imgur.com/pIQwm.jpg
  [2]: https://i.stack.imgur.com/GP7am.jpg

title: can this piece of a camera flash send an input signal to my arduino?

Answers: 0


body:
How do I make an electrical switch using Arduino, that when it receives signal (wirelessly or through a LAN port) to switch off it disconnects the switch and then again told to turn on turns the switch on?

The main problem I am facing is that I need to give a 5V output to turn off the transmission between two wires having voltage rating of 230V.

title: Using an Arduino as a electrical mains switch

Answers: 2

body: As pointed out in the comments, I would need to use something known as a relay with my Arduino.

body:
You need to use [Relays][1].  There all kind of relays.

Regular and Solid state ... for controlling a Regular Relay using Arduino you will need a transistor (so you will able to provide the right current to the relay to close a circle)

There are a lot of guides for Arduino and Relays (for [example][2])

  [1]: https://en.wikipedia.org/wiki/Relay
  [2]: http://www.instructables.com/id/Arduino-Controlled-Relay-Box/


body:
I am making a counting device, and I would like to be ensure that the count is not lost if the power is lost.
As I need to count to many millions I cannot use EEPROM writes as I will trash the nvm after ripping through the 100,000 max write cycles. I also need to ensure the count is accurate, so can't update 'every-so-often' either.

I want to write to EEPROM when the Arduino detects power down. I am reading on an Analogue input pin and am then planning on using a capacitor to hold the power on to complete the write. I have this set up but am having issues testing as I have found that when Ground is connected to GND pins and then when 5v is supplied to any I/O pin the device powers up. I have now tested a Nano and Uno and have found the same thing on both.

I have looked through the arduino site and tried looking for forums where this has been discussed, but to no avail.

Is this damaging to the Arduino if powered in this way? Does this pass the sanity check as a way of achieving my main objective of not loosing the count on power down?

thanks in advance :)

title: Write to EEPROM during power down

Answers: 4

body:
The arduino chips have clamping diodes on all the GPIO pins. So if the voltage on one of the pins is above Vcc (which is 0v is there is no power applied to the chip), the internal diode will 'redirect' this voltage to the Vcc line. This will damage the chip, is too much current is going through the clamping diodes.

Instead, connect the 5v signal via a large resistor (e.g. 100k) to the input pin.

Using a capacitor (plus diode to prevent backfeeding) will work. You just have to be careful if you have connected anything to an output pin that uses current. An led running at 20mA will drain a charged capacitor pretty quickly.

What I've done in the past is use the entire EEPROM space to store a single value. Just write every next value to a higher address. On powerup read the entire EEPROM till you find two adjacent address that don't contain successive numbers. Then you know where the last written value was, and you can read this last value, and continue writing the the address right after that one.

body:
I would suggest powering it from the 12V input and monitor the 12V with a power supply monitoring chip or circuit which will send an interrupt to your system when the voltage drops to whatever voltage you design it for. This can be accomplished with a few resistors and a comparator.

Your hold up time will be controlled by the amount of capacitance on the 12V side.  When the interrupt is tripped write the value to EEPROM and then shut down.

The analog input is a good sounding idea but there is a lot of latency between the time the voltage starts to fail and is detected.  The hardware interrupt will be much faster giving you more time to save your counter and the additional capacitance on the 12V side will give you a lot more time then back feeding through the GPIO pins..

body:
A typical method of increasing the number of writes to EEPROM is to use a vector of counters instead of a single value. The counter value is written to the EEPROM vector in a cyclic fashion.

On startup the vector is searched for current counter value, i.e. the highest counter in the vector. The write index is restored by locating the lowest counter value.

The number of writes is increased with the length of the vector.

Please read more about this method [here][1].

  [1]: http://www.atmel.com/images/doc2526.pdf

body:
A more sophisticated version of @MikaelPatel's techique is not to store the individual counts, but to store a derivative:

1. Reserve a block of storage with (say) 8 counters. Each counter has as many bits as necessary to store the largest value - but see below for what "largest" means.
2. Each time the count goes up, write into the next counter along (modulo the number of counters).
3. But don't write the value of the counter, write the value divided by the number of counters - `counter/8`.
4. Here's the trick: while that looks like you're losing precision, you're not - because the counter location is information too! In fact you're _gaining_ size.

It's best shown with an example. For ease, I'll assume an 8-bit counter, and only 8 counters:

    0000: 03 03 03 03 03 02 02 02

Assuming that everything started at `00`, that means that it took 8 counts for them all to get to `01`, a further 8 counts for them all to get to `02`, and only 5 counts to get the first 5 to `03`. That's a total of `8+8+5` or `21`.

At boot time, look for where the number sequence goes down. That's your current buffer position for future updates, plus the information for the current value:

    CurrentCount = [Smaller number] * [Number counters] + [Number of larger];

Once you've worked it out, keep the current value for incrementing, and the buffer pointer for where to store the next count.

### Advantages:

A. You write as often as you would storing a counter - but in different locations, spreading the load.
B. Each location (8, 16 or 32 bits) can store a certain maximum - but the total maximum is a factor of `Number of Counters` larger than that!

Odometer manufacturers use this exact technique to store the current mileage in digital dashboards - they have a legal requirement to maintain the correct number. They only use 16-bit counters (which would overflow after 65,535 miles), but then they use 16 counters, for a total mileage maximum of over a million. Each location only gets written every 16 miles, and they don't need to use 32-bit locations.


body:
[Arduino UNO][1] is 5V, 16 MHz.

USB 1.1 Low Speed spec operate:

 * at 5V level - so we avoid to maintain voltage level
 * at 1.5 Mb/s - so we have 16/1.5 ~= 10 instructions per elementary protocol signal

Is it possible to make Arduino as slave USB device from UART lines connected to USB D+/D- interface with careful timing and assembler programming?

I doesn't familiar with ATmega328P pin I/O capabilities, may be them can't operate at 1.5 MHz so project isn't possible?

**UPDATE** I found [V-USB][2] library that:

    implementation of a low-speed USB device for Atmel’s AVR® microcontrollers,
    making it possible to build USB hardware with almost any AVR® microcontroller,
    not requiring any additional chip.

Still dig into docs to realize possibilities.

  [1]: https://www.arduino.cc/en/Main/arduinoBoardUno
  [2]: https://www.obdev.at/products/vusb/index.html

title: USB 1.1 Low Speed project for Arduino UNO/ATmega328P to learn USB protocol

Answers: 1

body:
Not exactly the answer to your question, but have you tried the [typical][1] way to emulate slave devices with Arduino UNO?

It uses the 2nd ATMega present onboard (this applies only to UNO, afaik) and lets you use the main ATMega for other tasks, delegating the USB protocol to the smaller ATMega16.

Do you have any specific reason why you would use the serial lines?

  [1]: http://smartinteractionlab.com/lufa-example-turning-your-arduino-into-a-keyboard/


body:
My project is having Arduino with my WiFi shield connect to Twitter and look for any messages that other users have tweeted at me that contain a certain color, (I.E. @myTwitterHandle I want red) and then changes an RGB LED to become that color.

I have been searching online for different methods, and found a few different solutions which I could use as a starting point. However, these apparently call to an old Twitter API that is not supported anymore (support stopped mid 2013).

One solution I came across was to use node-red as well as MQTT.  I am not too familiar with these programs.

Does anyone know how to have Arduino parse a twitter account for mentions containing certain strings and have it print to LED? Any help with be appreciated

title: Linking Arduino With Twitter

Answers: 1

body:
The new Twitter 1.1 API requires OAuth authorization over SSL, for which Arduino is under-powered.

You will need to write a proxy application, which would parse the tweets and then send a RGB color value to your Arduino.

You should split your project into three parts.

1. Retrieving tweets with the [Twitter API](https://dev.twitter.com/overview/documentation).
You can get some library to do it for you.

2. Communicating with your Arduino.
Just try to send an arbitrary color to your Arduino over internet.

3. And finally joining first two pieces of code together.

And if you get stuck somewhere, you can always ask for help here on StackExchenge.


body:
I am new to Arduino and this forum, so please forgive me if I am asking something really trivial and stupid.

I have an Arduino board which collects sensor readings from an MPU6050 sensor (acceleration+gyroscope). The next step for me would be to process these data directly on the board. I want to somehow store N last sensor values and then query this set (collection, vector, array, whatever you call it) to fetch certain values. This set will be constantly updated with new values, whereas older values will be pushed out, so that only the most up-to-date values are stored in the set. For example, I want to know if the acceleration exceeded 10 m/s in the last minute.

In the literature this kind of set with most recent values is sometimes called *window* - this approach allows limiting an unbounded sequence of constantly generated tuples to a bounded bag and then apply traditional SQL-like query operators. For example, Oracle has come with [CQL][1] - an engine and a query language for handling streaming data.

Before I start implementing this, I am wondering if there is a similar (and, of course, much simpler) library for Arduino? If not, which data structure should I use to implement such functionality?

Also, my intention is to query not just individual values, but certain patterns and sequences - e.g., I want to know if the acceleration first decreased and then increased again (something similar to the WHERE condition of an SQL query). Does it look realistic to implement with Arduino?

  [1]: http://docs.oracle.com/cd/E16764_01/doc.1111/e12048/intro.htm "CQL"

title: Querying streaming sensor data on the Arduino board

Answers: 1

body:
It sounds like you are after my Average library:

* https://github.com/MajenkoLibraries/Average

It allows you to store a rolling set of data where you get to "push" values into it and the oldest one drops off the end. (It's implemented internally using a circular buffer).

You can then do various forms of analysis on the data - get the *mean* average, the *mode* average, calculate the standard deviation, find the maximum and minimum values of the set, and even access individual entries within the set.

It's a fully templated library, so you can use it with any numerical data type (float, double, int, long, etc).


body:
Someone posted a solution for a problem I had which used Serial.read() .Why doesn't readString() seem to work though? From the docs it seems it reads the data as a String object which would make things a bit cleaner.

But here's my Python code:

    import serial

    arduinoSerialData = serial.Serial('com7', 9600, timeout=0)

    while True:
     arduinoSerialData.write('ALIVE\r\n')

And Arduino code:

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

      pinMode(13, OUTPUT);

    }

    void loop() {
        if (Serial.readString() == "ALIVE") {
            digitalWrite(13, HIGH);
        } else {
            digitalWrite(13, LOW);
        }
    }

If this was right, the green LED on the Arduino would light up when the Python program would run, but it doesn't. What is Serial.readString() expecting that it doesn't get?
I even tried `if (Serial.readString().startsWith("ALIVE"))` instead, as well as `arduinoSerialData.flush()` before `arduinoSerialData.write()`

title: Serial.readString() - how does it work exactly?

Answers: 1

body:
`readString()` will read characters from the serial (or other Stream) device until a timeout occurs.  That timeout is, by default, 1 second.  It is only appropriate to use `readString()` if your data is arriving in chunks with a minimum time between each chunk.

It is more appropriate to use `readStringUntil()` which will read characters from the serial device until *either* it times out, *or* it receives a certain character.  It is most common to use either the line feed (`\n`) or carriage return (`\r`) characters as the end of string marker.  You must, of course, ensure that your sending program sends the string terminated in the right way.

However, that all said, you really should avoid using String objects when possible, since the constant creation and destruction of temporary objects all over the place can make a real mess of your heap.

It is far better to learn to use character arrays and fill them using `Serial.read()`.  A tutorial I wrote for that is here:

* http://hacking.majenko.co.uk/reading-serial-on-the-arduino


body: I'm both sending and receiving strings to Arduino from my Python program on the PC and the opposite. I don't check by code if one is finished before doing the other. Are they seprate buffers, or is it just pure luck my program has been running fine until now and each program has been reading the right string ?

title: Is the Serial buffer going from Arduino to PC and from PC to Arduino different?

Answers: 1

body:
There shall be separate buffers for Tx and Rx (in Arduino Serial library). The actual buffer size may vary, but shall be around 8-16 bytes and there is also hardware buffer in MCU. Please try to increase serial baudrate, if possible.

**UPD:** In HardwareSerial.h:

    #if (RAMEND < 1000)
    #define SERIAL_TX_BUFFER_SIZE 16
    #else
    #define SERIAL_TX_BUFFER_SIZE 64
    #endif

    ....

    unsigned char _rx_buffer[SERIAL_RX_BUFFER_SIZE];
    unsigned char _tx_buffer[SERIAL_TX_BUFFER_SIZE];

It seems for Atmega328 the buffers are 16 bytes each

**UPD:** As Nick pointed, for Atmega328:

    #define RAMEND       0x8FF     /* Last On-Chip SRAM Location */

So the buffers are 64 byte each.


body:
I have bricked a few AT328P by invalid fuse settings.

Has anybody used the above sketches and the associated circuitry to perform high voltage programming?

title: Is it difficult to do high voltage parallel programming using Nick Gammon library?

Answers: 1

body:
I have not tried with those instructions, as I have an AVRDragon, but it's a good exercise for precision, since you have to wire lots of pins.

20+ iirc

My guess is that if anything fails, it's likely to be because of a mistake in the wiring.

If you are planning to do it often, you might consider soldering the wires and the ZIF socket to a prototype board, to preserve your mental sanity.


body:
I'm new to the arduino and to EE in general. I've built the basic examples and a, now trying to get a deeper understanding of what the physics is doing. As such, I'd like some help in understanding the diagram here:

https://www.arduino.cc/en/Tutorial/Blink

**Question 1:**

Specifically,it seems that the flow is going from Pin 13 to Ground. Is the diagram using the conventional flow or the electron flow approach.

Specifically, is it the *electrons* flowing from Pin 13 to ground or does the diagram show protons flowing? It seems that its showing the electron flow as the diagram has the anode attached to the resistor so the electrons flow from the pin to the resistor to the positive end (anode) of the LED.

**Question 2:**
This is about bread boards, like one shown here:

https://www.google.com/search?q=arduino+breadboard&biw=1696&bih=988&tbm=isch&tbo=u&source=univ&sa=X&ved=0CFEQsARqFQoTCIjsw5WhkMgCFdWYiAodttcKIw#tbm=isch&q=breadboard&imgrc=KwnTrtjnYJdB1M:

1) Would I connect Pin 13 (or say the 5V pin) to the + (the red line). Then I would connect the blue line (the -) to the ground on the arduino? Do I need to connect the blue line?

2) Also, is it again the electron flow notation so that from Pin 13, the electrons flow to the + (red), then to one of the lettered columns and then to whatever component I have?

Thank you for your help! I realize these are basic questions but I want to go a little beyond building the examples and start trying things out myself. As such I want to make sure I'm getting the theory behind it right!

title: Arduino circuit diagram help

Answers: 3

body:
It doesn't matter whether you use conventional current or electron current to describe a circuit; in the end they give the same results.

Protons are not a charge carrier in 99.99999% of circuits; positive charge carriers are the quasiparticles known as **holes**, but they only flow in semiconductors.

The power rails on a breadboard should be used for power only, never signals. It is possible to use them for other things, and it is possible to not use them at all, but when they are used they should only be used for supply in order to cause the least confusion.

body:
Protons don't flow. They are part of the atom nucleus. If they flowed the copper wire would be flowing. Electrons are what flow, particularly if there are some free ones hanging around, like teenagers hanging around a mall.

You don't need to worry about that however. Most people think of current as flowing from positive to negative (ie. pin 13 to ground) even if in fact the electrons are flowing from ground to pin 13.

See [Conventional Versus Electron Flow](http://www.allaboutcircuits.com/textbook/direct-current/chpt-1/conventional-versus-electron-flow/). I quote:

>  When Benjamin Franklin made his conjecture regarding the direction of charge flow (from the smooth wax to the rough wool), he set a precedent for electrical notation that exists to this day, despite the fact that we know electrons are the constituent units of charge, and that they are displaced from the wool to the wax—not from the wax to the wool—when those two substances are rubbed together. This is why electrons are said to have a negative charge: because Franklin assumed electric charge moved in the opposite direction that it actually does, and so objects he called “negative” (representing a deficiency of charge) actually have a surplus of electrons.
>
> By the time the true direction of electron flow was discovered, the nomenclature of “positive” and “negative” had already been so well established in the scientific community that no effort was made to change it, although calling electrons “positive” would make more sense in referring to “excess” charge. You see, the terms “positive” and “negative” are human inventions, and as such have no absolute meaning beyond our own conventions of language and scientific description. Franklin could have just as easily referred to a surplus of charge as “black” and a deficiency as “white,” in which case scientists would speak of electrons having a “white” charge (assuming the same incorrect conjecture of charge position between wax and wool).

Quote courtesy of Design Science under [this license](https://www.gnu.org/licenses/dsl.html).

---

>  Would I connect Pin 13 (or say the 5V pin) to the + (the red line). Then I would connect the blue line (the -) to the ground on the arduino? Do I need to connect the blue line?

When using a breadboard I connect the 5V pin to the red line, the Gnd pin to the blue line, and other things (signals) to the internal (numbered) holes. The internal ones are connected cross-ways, so that is useful, for example, to put a series resistor for the LED there.

I trust you are using a resistor for the LED, if not you might damage both the LED and the Arduino. See [The care and feeding of LEDs](http://www.thebox.myzen.co.uk/Tutorial/LEDs.html).

body:
The thing to remember about electrons is they are a negative charge.  That means that the direction of current flow (positive charge) is opposite to the direction of flow of the actual electrons (negative charge). Picture it like those "compression jams" you get on the motorway (freeway) where cars that are travelling too close together have to slam their breaks on to avoid running into each other.  The one at the front slams its breaks on briefly then carries on. The one behind has to do the same, and so on and so forth.  You then get a wave effect travelling in the opposite direction to the direction of travel of cars as they slam their breaks on in turn.  The cars are moving forwards, but the compression jam is moving backwards.  Similar in a circuit - the electrons are moving forward, but the charge is moving backwards.

Another way to visualize it is as a bubble in a pipe of stationary water.  The bubble moves in one direction, but in order for it to do that the water has to flow past the bubble in the opposite direction.*

So the current flows out of pin 13 through the LED and to ground, but the electrons themselves are actually flowing from ground through the LED and in to pin 13 (where they eventually return back to ground through the power supply).

For how the IO pin works it's best to picture it as a pair of switches - one connected to Vcc and one connected to GND.  For instance, this is the LED wired up with the IO pin set to HIGH:

[![enter image description here][1]][1]

You can see that S1, being on, forms a circuit between the battery and the LED to allow the current to flow.

When the IO pin is set to LOW the circuit looks a bit like this:

[![enter image description here][2]][2]

You see that S1 is now turned off, and S2 is turned on.  the connection from that battery is now broken, and current can't flow.

But, you ask, what is the point of S2 here? It doesn't actually do anything.  No, not in that circuit it doesn't. But consider if you re-arrange the circuit to be like this:

[![enter image description here][3]][3]

Now it's S2 that is controlling the connection to the battery.  S1 is now the redundant switch.

This leads to some terminology.

When S1 is closed the IO pin is said to *source* current since it is pretty much connected directly to the positive power source.

When S2 is closed instead the IO pin is said to *sink* current since it is connected to ground, so current can "sink" down to ground through it.

As far as breadboards are concerned - they are just collections of metal strips that are used to join wires and component leads together in whatever way you need to.  There is no one part of it that is any different to any other, and there is nothing that says you must use this bit in a certain way, or that bit in another way.

Your typical breadboard has sprung metal clips that are arranged in this pattern:

[![enter image description here][4]][4]

You can use any collection of holes for any purpose you choose.

That said, normally the blue (or black) marked line of holes down each side is used for ground, and the red line of holes is used for power.  As both sides of the board are separate it is possible to use different voltages on each side, or the same voltage on both sides, etc.  That can be especially useful when you're working on a circuit that has, say, +3.3V and +5V in it.  Another common split usage is for a positive voltage on one side and a negative voltage on the other - common when working with op-amps.  Just remember which is which.

----
* This is a complete lie, but it's as close as you need to know at this point in your education. https://en.wikipedia.org/wiki/Lie-to-children

  [1]: https://i.stack.imgur.com/gWOUn.png
  [2]: https://i.stack.imgur.com/Atfxx.png
  [3]: https://i.stack.imgur.com/uaV1O.png
  [4]: https://i.stack.imgur.com/u220p.png


body:
I had a very common question. Why a additional MEGA used in most of the Arduino Boards. Arduino board Mega2560 also have a MEGA16U2 controller on board which i think is used for programming via USB. Is there any other specific usage of atmega16 on arduino board.

Thanks

title: atmega16 in Arduino Board

Answers: 1

body: It's an ATmegaU2, which has USB hardware and handles the USB communication. It passes the hex file on to the bootloader in the main microcontroller. That is its only job.


body:
My name is Gianni, I live in Olbia Sardinia Italy and I have some experience in electronics.

For several years I have been passionate about Arduino.

They are now engaged in a project to counter with hall sensors.

The slave sends data to the master via I2C, for my project. I'm using the [sketch of Gammon](http://www.gammon.com.au/i2c) which uses a structure enum to send a request to the slave.

I have the need to send a reset command from master to slave.

I edited the sketch and I can see the command on the slave but will not let me use it to reset the counter.

---

## Master code section

       void RstCounter()
      {

      Serial.println ("funzione azzera attivata");
       Serial.println (sensor);
      char key = keypad.getKey();
      if (key !='A')
      {

       char cmdrst = 'a';
       //set=key;

         if (sensor==11)
        {
        sendCommand (CMD_WRITE_D2, 1);

        Wire.beginTransmission(SLAVE_ADDRESS); // testiamo questa istruzione
        Wire.write(cmdrst);
        Wire.endTransmission();

        delay(100);
        Serial.println (cmdrst);
        }

       else
      {
      m=0;
      }

       azzera =true;
      }
       else if (key=='A')
        {
       Serial.println("");
       Serial.println("AZZERA close");
       azzera = false;
       }
         delay(100);
        }

---

## SLAVE code section

    #include <Wire.h>

    const byte MY_ADDRESS = 42; // address in valore esadecimale

    /************  VARIABILI SENSORI **********************/

    #define Sensor11 2
    int lastValueSensor11 =0;
    int ValueSensor11=0;
    int contatore11=0;
    int counter11;

    // various commands we might get
    /************  VARIABILI ENUMERATORE **********************/
    enum {
        CMD_ID = 1,
        CMD_READ_D2  = 2,
        CMD_READ_D3 = 3,
        CMD_READ_D4 = 4,
        CMD_WRITE_D2 = 5
        };

    char command;
    int sensor;
    char cmdrst;

    /************  SETUP **********************/
    void setup()
      {
      command = 0;

      pinMode (Sensor11, INPUT);
      digitalWrite (Sensor11, HIGH);  // enable pull-up

      Serial.begin(9600);
      Wire.begin (MY_ADDRESS);
      Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
      Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

      }  // end of setup

    /************  LOOP **********************/
    void loop()
      {
            /************************ CONTATORE SENSOR 1 ***********************/
       ValueSensor11  = digitalRead(Sensor11);

                if ( ValueSensor11 != lastValueSensor11)
                   { if ( ValueSensor11 == LOW)
                        {
                          contatore11 = contatore11 + 1;

                            }
                         }
       lastValueSensor11 = ValueSensor11;

    /************  I2C RECEIVE **********************/
    void receiveEvent (int howMany)
      {

      command = Wire.read ();  // remember command for when we get request
      //Serial.println(command);
      switch (command)
         {
         case CMD_WRITE_D2:
         Serial.println("comando 5 ricevuto");
         char cmdrst=Wire.read();
         delay(100);
         Serial.println (cmdrst);
         break;
        }
    } // end of receiveEvent

    void sendSensor1 (const byte which)
      {
      int val11 = contatore11;
      Serial.println(contatore11);
      byte buf11 [2];

        buf11 [0] = val11 >> 8;
        buf11 [1] = val11 & 0xFF;
        Wire.write (buf11, 2);
      }  // end of sendSensor

    void requestEvent ()
      {
      switch (command)
         {
         case CMD_ID:
         Wire.write (0x55);
         break;   // send our ID

         case CMD_READ_D2:
         sendSensor1 (2);
         break;  // send A0 value

         case CMD_READ_D3:
         sendSensor2 (3);
         break;    // send D8 value

         case CMD_READ_D4:
         sendSensor3 (4);
         break;

         }  // end of switch

      }  // end of requestEvent

title: I2C Master send reset command to the slave counter

Answers: 1

body:
    void receiveEvent (int howMany)
      {

      command = Wire.read ();  // remember command for when we get request
      //Serial.println(command);
      switch (command)
         {
         case CMD_WRITE_D2:
         Serial.println("comando 5 ricevuto");
         char cmdrst=Wire.read();
         delay(100);
         Serial.println (cmdrst);
         break;
        }
    } // end of receiveEvent

* Don't do serial prints inside an interrupt service routine (ISR). That is, not here.

* Don't do `delay` inside an ISR.

---

      if (key !='A')
      {

I would be checking for NO_KEY first, otherwise you will assume that no key press is not 'A' and be doing that transmission to the slave **a lot**.


body:
This is a broad question but I want advice on what type of hardware I should look for to make a device that could measure the velocity of an object attached via a string/wire to some sort of rotary wheel.

The purpose of this is to attach it to a barbell and measure mean-velocity for weightlifting atheletes.

I'm a software engineer by trade but know nothing about hardware. I will obviously need to start with simple projects to learn, but I would like to know which hardware I should lean towards buying, so I don't have to re-buy anything?

title: Hardware to measure velocity via string/wire attatchment? beginner

Answers: 2

body:
[This][1] is an example of the optical encoder.
You want to use interrupt detection, rather than polling.
Or maybe even an HW counter.
That's all you really need.

I am using 4 of them for a car.

I am in the process of refactoring the code, but you could already have a look at the driver & example I wrote for ChibiOS, [here][2].

  [1]: http://www.ebay.com/itm/photoelectric-speed-sensor-encoder-coded-disc-code-wheel-for-freescale-smart-/231699340055?hash=item35f25b5b17
  [2]: https://github.com/ChibiOS/ChibiOS/pull/10

body:
You can use a dog lead (or replace it with a fishing line). I made one my self. I used a rotary encoder and a dog lead, an Arduino board Paralax, and Excel.

It will use interrupts. Once the wire is triggered, the Arduino will send to Excel time and distance traveled. Once the weight goes down distance and time will be printed too, however distance will run in a minus direction. Later just press one button in Excel and each set of lifts will appear on the desktop. I can see my lift speed, power generated, distance travelled and so on.

[![Excel example][1]][1]

  [1]: https://i.stack.imgur.com/8lhAU.png


body:
I'm playing with a 7 segment display.

The following works on my breadboard:

    5V -> 330 Ohm Resistor (same row, row 9)
    330 Ohm Resistor -> Com Port (row 9 to row 15)
    h led (the dot/row 17) -> ground rail

I get the dot to light up.

However, the following does not light up:

    5V -> h led (the dot/row 17)
    Com Port -> 330 Ohm Resistor (Row 15 -> row 38).
    330 Ohm Resistor to negative rail (row 38 -> negative rail)

I realize that the row numbers are meaningless -- things just need to be on the same row. I've included them to make it easier to visualize.

So basically, if the circuit goes:

5V -> Resistor -> Com, then I can use the ground wire to light up any part I want.

If the circuit goes Com -> Resistor to Ground, I can't use the 5V to light up any part.

I'm not sure why given that all the stuff is in serial?

title: help with 7- segment display

Answers: 1

body: Because you have a common-anode display and you're trying to use it as a common-cathode display. LEDs, like all diodes, only conduct freely in one direction.


body:
I want to print Bitmap image from thermal printer, but image data is from Serial Input. But I am not getting valid print. What wrong i am doing ?

Here is code i wrote

    #include "Adafruit_Thermal.h"
    #include "SoftwareSerial.h"
    // PIN 6 -> Yellow
    // PIN 5 -> Green
    // GND -> Black

    #define TX_PIN 6
    #define RX_PIN 5

    SoftwareSerial mySerial(RX_PIN, TX_PIN);
    Adafruit_Thermal printer(&mySerial);

    int count =0;
    void setup() {
      pinMode(7, OUTPUT);
      digitalWrite(7, LOW);
      mySerial.begin(9600);  // Initialize SoftwareSerial
      printer.begin();        // Init printer (same regardless of serial type)

      Serial.begin(9600);
      Serial.print("1");

      //printer.printBitmap(384, 5, image);

      //printer.feed(2);

      printer.sleep();      // Tell printer to sleep

      delay(3000L);         // Sleep for 3 seconds
      printer.wake();       // MUST wake() before printing again, even if reset
      printer.setDefault(); // Restore printer to defaults
    }

    void loop() {
        if(Serial.available()>48){
          uint8_t image[50];
          Serial.readBytes(image,48);
          printer.printBitmap(384, 1, image);
        }

    }

title: Printing bitmap image from thermal printer using Serial input

Answers: 0


body:
If I wanted to throw together a simple burglar-alarm system that had wireless sensors talking to an Arduino (which would then send me an SMS message via cellular shield as a silent alarm telling me which alarm sensor had changed state_)... what technology would you recommend for the sensor-to-arduino signalling?

It needs to be something that draws little or no power until the alarm is triggered, resistant to radio interference, and as always cheap is a huge plus.... but I haven't gotten much beyond that.

(Of course if anyone's already implemented something like this and there are descriptions/sketches I can adopt and adapt, feel free to point me in the right direction.)

EDIT: To provide more info,this is a wood-framed house, 2 storey plus basement, brick chimney possibly in the way. No straight-line distances greater than 60 feet. Wifi, wireless phone, usual electronics and a wood shop I'm still putting together. Shouldn't be difficult, I just want a robust solution in case a friend asks me to replicate it... and for purely aesthetic reasons.

title: Just sanity-checking a concept... poor man's self-monitored alarm system

Answers: 1

body:
NRF24L01+ for communication. Extreme low power if not sending. Detects packet loss, and automatically resend the packet.

You would however need a small arduino board at the sensor, to read the sensor, and signal to NRF24L01 to send a message.

You'll have to put the arduino in to low power sleep mode to get some good battery life. Either have the sensor wake the arduino up with an interrupt, of poll the sensor like every half second, and immediately go back to sleep.


body:
I started a project with my Arduino Mega 2560 that gets some values from sensors. I'm using MySQL Connector, https://launchpad.net/mysql-arduino, and this library allows me to connect to a server using the IP address, and it worked on localhost.

This is the code:

    /* Setup for all libraries */
    #include <SPI.h>
    #include <Ethernet.h>
    #include <sha1.h>
    #include <mysql.h>
    #include <OneWire.h>

    /* Setup for Ethernet Library */
    byte mac_addr[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xB3, 0x05 }; // MAC address must be unique; this is the Ethernet shield address
    IPAddress server_addr( 177, 156, 122, 113 ); // Server addr

    /* Setup for all others variables */
    int DS18S20_Pin = 2; // Temperature sensor
    float temperature;
    float placasTensao;
    float placasCorrente;
    float geradorEolicoTensao;
    float geradorEolicoCorrente;
    float bateriaTensao;
    float bateriaTemp;
    float correnteSaidaControlador;
    float correnteSaidaConsumo;

    OneWire ds(DS18S20_Pin);  // On digital pin 2

    /* Setup for the Connector/Arduino */
    Connector my_conn; // The Connector/Arduino reference

    /* Setup for connection and all variables of the database */
    char user[] = "";
    char password[] = "";
    char INSERT_SQL[1000];
    char temperature_convt[10], placasTensao_convt[10], placasCorrente_convt[10], geradorEolicoTensao_convt[10],
         geradorEolicoCorrente_convt[10], bateriaTensao_convt[10], bateriaTemp_convt[10], correnteSaidaControlador_convt[10],
         correnteSaidaConsumo_convt[10];

    void setup(){
      Ethernet.begin(mac_addr);
      Serial.begin(9600);
      delay(1000);
    }

    void loop(){
      temperature = getTemp();
      convert(temperature, temperature_convt);
      snprintf(INSERT_SQL, "INSERT INTO data.data VALUES (%s, 1, 1, 1, 1, 1, 1, 1, NULL)", temperature_convt);
      sendData();
      delay(20000);
    }

    // Convert a float variable to string
    void convert(float data, char *value){
      dtostrf(data, 7, 3, value);
    }

    // Saves all data on database
    void sendData(){
      Serial.println("Connecting...");
      if (my_conn.mysql_connect(server_addr, 3306, user, password)){
        delay(500);
        Serial.println("Starting SQL!");
        Serial.println(INSERT_SQL);
        my_conn.cmd_query(INSERT_SQL);
        Serial.println("Query Success!");
        my_conn.disconnect();
        Serial.println("\n");
      } else {
        Serial.println("Connection failed!");
        Serial.println("Make sure all cables are properly connected!\nIf they are, restart the Arduino!\n");
      }
    }

    // Returns the temperature from one DS18S20 in degree Celsius
    float getTemp(){
      byte data[12];
      byte addr[8];
      if (!ds.search(addr)) {
          // No more sensors on chain, reset search
          ds.reset_search();
          return -1000;
      }

      if ( OneWire::crc8( addr, 7) != addr[7]) {
          Serial.println("CRC is not valid!");
          return -1000;
      }

      if ( addr[0] != 0x10 && addr[0] != 0x28) {
          Serial.print("Device is not recognized");
          return -1000;
      }
      ds.reset();
      ds.select(addr);
      ds.write(0x44,1);
      // Start conversion, with parasite power on at the end
      byte present = ds.reset();
      ds.select(addr);
      ds.write(0xBE); // Read Scratchpad
      for (int i = 0; i < 9; i++) { // We need 9 bytes
        data[i] = ds.read();
      }
      ds.reset_search();
      byte MSB = data[1];
      byte LSB = data[0];
      float tempRead = ((MSB << 8) | LSB); // Using two's complement
      float TemperatureSum = tempRead / 16;
      return TemperatureSum;
    }

Now, how can I connect to a server using the URL? Is there a library like MySQL Connector that allows me to use the URL instead of the IP address?

All I want is to do exactly the same thing that I'm doing with MySQL Connector, but using the URL of the server instead of the IP address.

title: How do I connect Arduino directly to MySQL server using the URL?

Answers: 2

body:
You are using DHCP, so this step might be optional.
Specify your network addresses (actually we want to specify DNS only but have to specify IP in 2nd argument, so likely have to specify gateway and subnet too):

    IPAddress dns_addr( 8, 8, 8, 8); // GOOGLE DNS server, could be any DNS
    IPAddress gateway_addr( , , , );   // put your gateway addr
    IPAddress ip_addr( , , , );   // put your IP addr
    IPAddress subnet( , , , );   // put your subnet mask

    void setup(){
                      Ethernet.begin(mac_addr, ip_addr, dns_addr, gateway_addr, subnet);...

Now you could modify **Connector::mysql_connect** method (or create new method) as follows (only function declaration is changed, body is not):

    boolean Connector::mysql_connect(/*IPAddress server*/const char *server, int port, char *user, char *password)
    {
      int connected = 0;
      int i = -1;

      // Retry up to MAX_CONNECT_ATTEMPTS times 1 second apart.
      do {
        delay(1000);
        connected = client.connect(server, port);
        i++;
      } while (i < MAX_CONNECT_ATTEMPTS && !connected);

      if (connected) {
        read_packet();
        parse_handshake_packet();
        send_authentication_packet(user, password);
        read_packet();
        if (check_ok_packet() != 0) {
          parse_error_packet();
          return false;
        }
        print_message(CONNECTED);
        Serial.println(server_version);
        free(server_version); // don't need it anymore
        return true;
      }
      return false;
    }

Modify the header file also:

    boolean mysql_connect(/*IPAddress server*/const char *server, int port,
                                     char *user, char *password)
Now you can supply URL:

    if (my_conn.mysql_connect("http:\\www.mysqlserver.com", 3306, user, password))...

body:
The easiest, just git 'er done, way would be to do an nslookup on the domain, get the IP address and just hard code that into your source. It's not the most robust solution, as it's possible for the IP address to change over time. However, it's highly likely the IP address won't change frequently.

    > nslookup google.ca
    Server:  64.59.144.93
    Address: 64.59.144.93#53

    Non-authoritative answer:
    Name: google.ca
    Address: 216.58.193.67

If you need it to be more robust, you would need the Arduino to perform the dns lookup to resolve the IP address. This looks like it would do the job:

https://github.com/esp8266/Arduino/blob/master/libraries/Ethernet/src/Dns.h