body:
I am new to Arduino, also, I am not fluent in english.

I wish to create a controller for several circuits. All of those circuits are "in parallel" with additional circuits.

My question is:

* Do a Relay Shield protects the Arduino board from the current and voltage from the power supply?

Suppose the following:

[![Eletric wiring][1]][1]

The retangular boxes are "parallel switches" connected to the devices.

    R = Power Supply Phase

    S = Another Power Supply Phase

    N = power Supply Neutral

    Arduino, C2 and C3 are 127 Volts, (S+N)

    C0 and C1 are 220 Volts (R+S)

* Are the Shields safe from oscilations from the eletrical supply?

* What / Where / How should I look on what to ground? Local regulations state that I cannot let R and/or S be grounded.

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

title: Arduino and 127/220 Volts: Relay and Isolation

Answers: 1

body:
> Do a Relay Shield protects the Arduino board from the current and voltage from the power supply?

A relay provides *galvanic isolation* in the circuit.  The mains power is electrically isolated from the rest of the circuit since the device that performs the actual switching (the contacts in the relay) have no physical connection to the rest of the circuit - they are merely acted upon by magnetism.

That doesn't mean that it's *safe*, however.  There are a number of things you still need to deal with:

* The Arduino cannot directly drive a relay - it can't provide enough current. You must use a drive circuit.
* Back-EMF from the relay coil as the magnetic field collapses can damage sensitive semiconductors - good snubber circuit design is important here.
* Mains electricity is dangerous and must be treated with respect.  Proper circuit design is paramount to ensure that the mains is kept away from the rest of the circuit. Proper connectors must be used and exposed high voltage points must be rendered inaccessible, either by the project housing or by the addition of plastic insulating shielding.
* Relays as they turn on and off cause sparks. Sparks cause EMI. EMI causes induced currents. Induced currents cause damage to electronics.  Minimizing the spark generation not only prolongs the life of your relay but the life of everything else around. Ensure your relays can switch fast enough for the currents you are dealing with, or consider using *solid state relays* (SSRs) that don't suffer from this issue.


body:
I'm connecting Arduino UNO to Xbee S2 Zigbee module directly, and X-CTU cannot find Xbee module via arduino. i'm not using shield, it finds with non-arduino board connecter, but not by arduino UNO board.

i checked all parameters like baud rate, etc.., wirings, and it seems no problem at all, but it keeps msg like 'reset your radio module' and even i swtiched pin 5 and GND, it doesn't works.

what i have to do?

title: Why I cannot connect directly Arduino UNO and Xbee S2?

Answers: 1

body:
If you want X-CTU to see the Xbee while it's connected to the Arduino, you have to connect the Arduino's reset pin to ground. This bypasses the Arduino's MCU and allows the Arduino to act as a USB to serial adapter.

Also don't forget to connect the Arduino's Tx to the Xbee's Tx when it's connected like this, and likewise with the 2 Rx's.


body:
I was conducting some research on wireless communication between a simple transmitter and receiver module using an Arduino. Now, I tested the channel accuracy and i received 14% error for a delay of one micro second. For a delay of 2 microseconds, my error was 0%, and for three microseconds, my error rate was 30%. I am not quite sure why the data would result in this. I think it possibly has something to do with the gain on the receiver and the delay time. Some sweet spot perhaps? Can anyone offer me some ideas/explanations? Also, sorry for any confusion in this question. I am happy to clarify.

Part 2:

Hey Everyone,

I also had a question regarding what purpose each of the following delay serves in wireless communication.

    // Write each of the 8 bits
    for (uint8_t i = 8; i > 0; --i)
    {
      if (b & 1) // choose bit
        *reg |= reg_mask; // send 1
      else
        *reg &= inv_mask; // send 0

      tunedDelay(delay);// line in question ---------------------
      b >>= 1;
    }

and the delay used in the regular blink program.

**The regular delay used in the blink programs was what set the 2 microsecond delays.**

Lastly, I am looking at the read and recv methods in the software serial library and i don't see any checks for start bits, so what's the point of writing one in the write method?

title: What is the relationship between the gain on the receiver and the delay time

Answers: 2

body:
>  I am looking at the read and recv methods in the software serial library and I don't see any checks for start bits, so what's the point of writing one in the write method?

The start bit is absolutely essential in serial comms. In the graphic below, the start bit is marked "B" - which distinguishes it from "idle" data which is "A". Once received, the receiver then waits 1.5 bit times and starts clocking in the remaining bits. (Starting at "C" in the diagram, and then moving on for a total of 8 bits).

[![One serial byte][1]][1]

Without a start bit, how would the receiver know when the byte started? Imagine you wanted to send 0xFF (all 1 bits). Without a start bit that would be indistinguishable from the idle state.

In the graphic, "D" is the stop bit. Why have a stop bit? We need one (which is a "1" bit), so that we can detect the transition from the stop bit in the previous byte (a "1") and the start bit in the next byte (a "0").

In the graphic, "E" is the start bit for the next byte.

---

> I don't see any checks for start bits ...

SoftwareSerial has a pin-change interrupt set up to detect that the receiving pin has changed state (to a zero usually). **That** is your start bit. You don't see it in the loop, because it has already arrived, otherwise you wouldn't be in the receive loop in the first place.

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

body:
> Now, I tested the channel accuracy and i received 14% error for a delay of one micro second. For a delay of 2 microseconds, my error was 0%, and for three microseconds, my error rate was 30%.

Microsecond resolution delays on an Arduino are tenuous at best.  They aren't that accurate.  Simply because you're hitting the limit of the speed of the CPU.

At 16MHz you have a clock period of 1/16000000 seconds.  That's 63ns.  That's the *granularity* of the delays you can achieve - and that can only be achieved by inserting a precise number of `NOP` assembly instructions.

So for the best 1µs delay possible you would need (0.000001 / 0.000000063) 15.87 `NOP` instructions.  Of course, you can't have that many, so you have to round it either up or down.  Normal integer truncation would result in 15.  So that would actually be a delay of 945ns, which is an error of 5.5%.

2µs would be (0.000002 / 0.000000063) 31.74 `NOP` instructions, which would round to 31, so 1.953µs, or an error of 2.35%.  As you can see increasing the length generally reduces the error.

*HOWEVER*

The delay function on the Arduino for microsecond accuracy (`delayMicroseconds()`) is maybe not as accurate as it could be.  Simply because it's impossible to just have an exact number of NOP instructions for a delay since you can't know how long the delay should be until the function is called with a parameter detailing how long the delay should be.  So it has to perform a number of calculations and *make a number of assumptions*.  It tries to come close, but it was written for one specific version of the compiler and compilers change. Things may have been changed in how the function gets called, and how long parts of it take (what registers are pushed and popped may change with different compiler versions, for instance).  So it's not a perfectly reliable delay.

For more detail you can look at the source code of it (it's in `wiring.c`) and you can see how for small delays it's very hard to get it right. For instance, this couple of lines highlights the problem nicely:

        // for a one-microsecond delay, simply return.  the overhead
        // of the function call yields a delay of approximately 1 1/8 us.
        if (--us == 0)
            return;

Note the use of the word *approximately* there...

Also you need to note that the delay functions are just that - a delay *at that specific moment in time from the start of the call to its finish*.  It doesn't take into account anything else that's going on in your code, so a delay of 1µs in a loop of code that does other things will end up in a loop that takes `X + 1µs` where `X` is the amount of time that the rest of the code takes to execute.

And that's where the `tunedDelay()` function comes in.  It has been specially written to be used in that specific circumstance to provide a delay that *takes into account the time the rest of the loop takes to run*.  That is, the loop's time plus the `tunedDelay` time equate to the final period you want for the whole loop.  For asynchronous serial communications the timing accuracy is important.  Since there is no separate (or even embedded) clock to get the timing from both ends have to agree what speed the communication happens at (the baud rate), and any deviation from that can cause communication errors.  So the timing has to be as close as possible. A normal `delayMicroseconds()` function call just wouldn't cut the mustard - they needed it more precise than that.  Manually tuned to have specific delay values that are as precise as possible, and that was done for specific baud rates on specific speed chips.  Each supported frequency has a table such as this:

    static const DELAY_TABLE PROGMEM table[] =
    {
      //  baud    rxcenter   rxintra    rxstop    tx
      { 115200,   1,         17,        17,       12,    },
      { 57600,    10,        37,        37,       33,    },
      { 38400,    25,        57,        57,       54,    },
      { 31250,    31,        70,        70,       68,    },
      { 28800,    34,        77,        77,       74,    },
      { 19200,    54,        117,       117,      114,   },
      { 14400,    74,        156,       156,      153,   },
      { 9600,     114,       236,       236,      233,   },
      { 4800,     233,       474,       474,      471,   },
      { 2400,     471,       950,       950,      947,   },
      { 1200,     947,       1902,      1902,     1899,  },
      { 600,      1902,      3804,      3804,     3800,  },
      { 300,      3804,      7617,      7617,     7614,  },
    };

That's the value to send to the `tunedDelay()` function in the four different situations where its used for each of the baud rates at that specific clock frequency (16MHz in that example).

`tunedDelay()` itself is written in assembly code and is a very tight loop for the number of iterations specified in the parameter.  The shortest possible piece of code with the minimum of overhead to get the maximum accuracy and finest granularity (least number of clock cycles for one iteration) out of it.


body:
So I'd like to connect two of these sensors to an Adafruit Flora (https://www.adafruit.com/products/2020). In the product page it says you can only connect one but in the forum an admin said that you could do it but it required a bit of hacking. I'm new to arduinos and circuits in general. Can someone tell me how I could do this, or at least point me in the right direction?

**Edit**

I decided to use this multiplexer to use LSM9DS0's with the Flora.
https://www.adafruit.com/products/2717

title: Connect 2 LSM9DS0 to Flora

Answers: 1

body:
[Adafruit's rectangular 9DOF](https://learn.adafruit.com/adafruit-lsm9ds0-accelerometer-gyro-magnetometer-9-dof-breakouts) device, unlike [their round 9DOF](https://www.adafruit.com/products/1059), brings several more signals out to pads.  When using I²C with the rectangular 9DOF board, as I understand it signal pin SA0_G can be set low or high to modify the device address:
> The SDO/SA0 pins (SDO_XM/SA0_XM or SDO_G/SA0_G) can be used to modify the least significant bit of the device address. If the SA0 pin is connected to the voltage supply, LSb is 1 (ex. address 0011101b) else if SA0 pad is connected to ground, the LSb value is 0 (ex. address 0011110b).

Controlling that signal should let you put multiple 9DOF's on one system.  (See my answer to  [question 13830](https://arduino.stackexchange.com/questions/13830/arduino-due-and-bno055-address-in-i2c-mode/13833#13833) for some additional comments on setting an I²C address.) Also see tables 15 and 16 on page 33 in the spec sheet (DM00087365.pdf) regarding addresses.

If you insist on using round 9DOFs for this application, you would need to find the trace from pin 22¤ of the LSM9DS0 to Vcc on *one* of your 9DOF boards; working under a microscope with miniature tools, cut the trace and rewire the pin end of the trace to Ground.  This will change that board from using addresses 0x1D and 0x6B to 0x1E and 0x6C, if I correctly understand the spec sheet.

It probably would be a good idea to get one of the rectangular 9DOF's so that you could experiment with changing its addresses, before modifying one of the round ones.

¤ Looking at the top of the chip, pin 24 is just clockwise from the depressed round dot marking pin 1; pin 22 is 1.75 mm from the corner.  See Figure 21, LGA 4x4x1 mm 24-lead outline, in the spec sheet.  That figure shows the underside of the chip.


body:
In my project I want to retrieve the Latitude and longitude and then transmit to a cell phone through GSM module. But the GSM as well as GPS modules uses the same pins i.e. Tx and Rx, so is it possible to use both modules at the same time?

Link to products

GSM - http://www.ebay.co.uk/itm/SIM800L-GPRS-GSM-Module-SIM-Board-Quadband-PCB-Antenna-for-MCU-Arduino-/191611848583?hash=item2c9cf4c787

GPS-- http://www.ebay.co.uk/itm/New-1PC-Ublox-NEO6MV2-GPS-Module-Aircraft-Flight-Controller-For-Arduino-/400830328802?hash=item5d53596fe2

Thank you.

title: Can I use GSM and GPS modules at the same time?

Answers: 2

body:
Yes.  Use SoftwareSerial for one of them.  That way you can use any pins you like for that module.

I'd recommend using the GPS module on the SoftwareSerial since it's (mainly) half duplex, and SoftwareSerial can't both transmit and receive at the same time like the hardware UART can.

Either that or switch to a different Arduino board that has more than one hardware UART.

body:
If you are using two software serial then you can always use the `listen()` function to listen to specific object.

Suppose you have two software serial objects named GSM and GPS.
Now if you are reading or writing data to GSM then start with this, `gsm.listen();`
Now you can read/write data to GSM.
Next if you plan to read or write data to GPS then do this, `gps.listen();`


body:
I have followed all the instructions provided on  [http://allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/][1]

I have got the correct setup, I have got the message "Server Ready" in the serial monitor, i have an app similar to this, means the only thing i have done different from the web page is removing two buttons from the app.

But then also whenever i use my app to send request parameters to arduino it says "connection to 192.168.x.x:xx refused" , when i put the same ip and port in chrome, it says Server not reachable, the website may be down, What to do ? , Please help...

  [1]: http://allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/

title: Esp8266 server unreachable. Port doesn't open

Answers: 2

body:
The ESP module is not that difficult to work with, if you send the correct parameters to it AND you have the correct power it should work as expected.

My main suspicions will be cabling (just triple check that connections are as expected) and power source (the ESP is VERY power hungry, if you are powering the ESP from the Arduino that is your problem, you need a very good and stable power for the ESP to work (it might show up on your network but will not have enough power to actually send anything and it will disconnect (that will still show up on your router, it depends on how fast it connects/disconnects but won't be able to send anything).

This link can provide some good information about this subject:

http://bbs.espressif.com/viewtopic.php?t=133

body: I had the same problem and it worked when I disconnected my phone from 3g/4G.


body:
I am working on a project which includes Arduino and a fingerprint scanner. It is completely based on embedded system. But then, I have downloaded a library for the fingerprint scanner. When I run the program I get an error which maps to the cpp file of the library file. See below to see the error and the library file.

**Error**

> FPS_GT511C3\FPS_GT511C3.c.cpp.o: In function
> Command_Packet::GetPacketBytes()':
> C:\Users\Dipti\Documents\Arduino\libraries\FPS_GT511C3/FPS_GT511C3.c.cpp:17:
> undefined reference tooperator new[](unsigned int)'
> FPS_GT511C3\FPS_GT511C3.c.cpp.o: In function
> FPS_GT511C3::GetResponse()':
> C:\Users\Dipti\Documents\Arduino\libraries\FPS_GT511C3/FPS_GT511C3.c.cpp:735:
> undefined reference tooperator new[](unsigned int)' collect2.exe:
> error: ld returned 1 exit status

Library File (CPP)

> byte* packetbytes= new byte[12];
>
> byte* resp = new byte[12];

title: Error in Arduino Library file

Answers: 1

body:
The core of the problem is that the code is being compiled as C and not C++.

The error says 'new[]' is undefined at the link stage.  This is because the linker is not pulling in the C++ standard libraries.  The built-in function new[] it doesn't exist in C.

The filename FPS_GT511C3.c.cpp is the elephant in the room.  You could consider renaming it (and others) to FPS_GT511C3.cpp.  Although the plain Arduino IDE does not really have a problem with building them.

Another option might be to modify the new[] (and delete[]) for C's malloc() and free().  However this is only appropriate for the allocation of simple types (byte, int, etc).  If the code also allocates objects, it's not possible to simply swap these functions out since C++ (default) initialisation is be going on.


body:
I'm a web developer and I started building a small environment logger that will post to my website`s API. I'm really new to this kind of coding so bare with me.

Since yesterday, the whole Arduino started to acting funny. After the first or second request to the server(with already tested code), I started sending corrupted JSON data.

    {
      ":12": "module3",
      "10-7 18:26": {
        "1": {
          "": 21.50,
          "26:12": 55.50,
          "measured_at": "2015-10-7 18:26:12"
        },
        "2": {
          "": 21.10,
          "26:12": 55.70,
          "measured_at": "2015-10-7 18:26:12"
        }
      }

Where it should be

    {
      "modulename": "module3",
      "environments": {
        "1": {
          "temperature": 21.40,
          "humidity": 55.60,
          "measured_at": "2015-10-7 18:25:52"
        },
        "2": {
          "temperature": 21.20,
          "humidity": 55.80,
          "measured_at": "2015-10-7 18:25:52"
        }
      }
    }

The second JSON is from the initial request to the server. The first one is the corrupted one. I tried stopping all kinds of parts from the code, without any luck, except when I enter the measured_at manually (without getting the data from the RTC.)

    #include <DHT.h>

    #include <elapsedMillis.h>

    #include <DS3231.h>
    #include <Wire.h>
    //Json Library
    #include <ArduinoJson.h>

    #include <Ethernet.h>
    #include <SPI.h>

    #include <LiquidCrystal.h>

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // RESERVED MAC ADDRESS
    EthernetClient client;

    const String module_name = "module3";

    DHT dht1;
    DHT dht2;

    DS3231 clock;
    RTCDateTime dt;

    // initialize the library with the numbers of the interface pins

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    elapsedMillis timer0;
    const long interval = 10000; // READING INTERVAL

    int connected_sensors = 0;
    float t1 = 0;  // TEMPERATURE VAR
    float h1 = 0; // HUMIDITY VAR
    float t2 = 0;
    float h2 = 0;

    int nc = 0; //Network connection simulation INI

    byte temp[8] = { //icon for thermometer

      B00100,
      B01010,
      B01010,
      B01110,
      B01110,
      B11111,
      B11111,
      B01110
    };

    byte humi[8] = { //icon for water droplet
      B00100,
      B00100,
      B01010,
      B01010,
      B10001,
      B10001,
      B10001,
      B01110,
    };

    byte sconnect[8] = { //icon for connection
      0b00000,
      0b11111,
      0b10001,
      0b10001,
      0b11111,
      0b00100,
      0b11111,
      0b00000
    };

    void setup() {
      Serial.begin(9600);
      clock.begin();
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      Serial.println("Terrarium Serial");
      // Print a message to the LCD.
      lcd.print("Weather v0.1");
      delay(1000);
      lcd.setCursor(0, 1);
      lcd.print("Sensor loading...");

      lcd.clear();
      lcd.print("Network check...");

      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP"); //There is a problem with DHCP
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("DHCP ERROR");
        lcd.setCursor(0, 1);
        lcd.print("Please Restart");
        for (;;)
          ;
      }
      nc = 1;

      delay(2000);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print(Ethernet.localIP());
      lcd.setCursor(0, 1);
      lcd.println("Ready!");

      Serial.println(F("Connected!"));
      Serial.println(Ethernet.localIP());

      delay(4000);
      lcd.clear();

      lcd.createChar(1, temp);
      lcd.createChar(2, humi);
      lcd.createChar(3, sconnect);

      dht1.setup(15);
      dht2.setup(16);

      h1 = dht1.getHumidity();
      t1 = dht1.getTemperature();

      h2 = dht2.getHumidity();
      t2 = dht2.getTemperature();

      delay(2000);

      //Display the statics on the display
      lcd.setCursor(2, 0);
      lcd.print(module_name);
      lcd.setCursor(9, 1);
      lcd.write(2);
      lcd.setCursor(15, 1);
      lcd.print("%");
      lcd.setCursor(2, 1);
      lcd.write(1);
      lcd.setCursor(8, 1);
      lcd.print((char)223);

      timer0 = 0; // clear the timer at the end of startup

    }
    void CheckSensors() {

      if (timer0 >= interval) { // READ ONLY ONCE PER INTERVAL
        timer0 -= interval;

        dt = clock.getDateTime(); //get current time

        h1 = dht1.getHumidity();
        t1 = dht1.getTemperature();

        h2 = dht2.getHumidity();
        t2 = dht2.getTemperature();

        DataSend(); //send data
      }
    }

    //Print the changeable values on the display
    void LcdPint() {
      lcd.setCursor(0, 0);
      if (nc == 1) {
        lcd.write(3);
      } else if (nc == 0) {
        lcd.print(" ");
      } else if (nc == 2) {
        lcd.print("E");
      }

      lcd.setCursor(10, 1);
      lcd.print(h1);

      lcd.setCursor(3, 1);
      lcd.print(t1);

    }

    //Construct the JSON response
    JsonObject& prepareResponse(JsonBuffer& jsonBuffer, String measured_at) {

      JsonObject& root = jsonBuffer.createObject();
      root["modulename"] = module_name;

      JsonObject& environmentsObject = root.createNestedObject("environments");

        JsonObject& environmentsOne = environmentsObject.createNestedObject("1");
        environmentsOne["temperature"] = t1;
        environmentsOne["humidity"] = h1;
        environmentsOne["measured_at"] =  measured_at;

        JsonObject& environmentsTwo = environmentsObject.createNestedObject("2");
        environmentsTwo["temperature"] = t2;
        environmentsTwo["humidity"] = h2;
        environmentsTwo["measured_at"] =  measured_at;

      return root;
    }

    void writeResponse(EthernetClient& client, JsonObject& json) {

      char buffer[256];
      json.printTo(buffer, sizeof(buffer));

      if (client.connect("api.terrariums.eu", 80)) { // REPLACE WITH YOUR SERVER ADDRESS
        client.println("POST /v1/sensors HTTP/1.1");
        client.println("Host: api.terrariums.eu"); // SERVER ADDRESS HERE TOO
        client.println("Content-Type: application/json");
        client.println("Authorization: Basic bW9kdWxlMzoxMzIxMzI=");
        client.println("Connection: close");
        client.print("Content-Length: ");
        client.println(strlen(buffer));
        client.println();
        client.println(buffer);

        nc = 1;
      } else {
        nc = 2;
        Serial.println("connection failed");
      }

      while (client.connected())
      {
        if ( client.available() )
        {
          char c = client.read();
          Serial.print(c);
        }
      }
      Serial.println();
      client.stop();
      //End  post request

    }
    void DataSend() {

     //This is the part that I think crashes my entire code. I tried using the helper with the RTC library that I use
     //but that made things worse.

        String measured_at = (String) dt.year + "-" + dt.month + "-" + dt.day  + " " + dt.hour   + ":" + dt.minute + ":" + dt.second;

        StaticJsonBuffer<200> jsonBuffer;
        JsonObject& json = prepareResponse(jsonBuffer, measured_at);
        json.prettyPrintTo(Serial);

        writeResponse(client, json);

    }

    void loop() {
      CheckSensors();
      LcdPint();
    }

title: Json gets corrupted after first HTTP request

Answers: 2

body:
In all probability you are either running out of memory, or the libraries you are using (and the fact that you are abusing String objects) is fragmenting your heap to such an extent that your whole 2KB of RAM is being used and you are ending up with a stack-and-heap collision.

You have to remember that the Arduino Uno only has 2KB of RAM.  It's not a computer, and has no OS, and as such you have to unlearn much of what you know about programming and do things slightly differently.

The first problem you have is with your String abuse.  This line:

    String measured_at = (String) dt.year + "-" + dt.month + "-" + dt.day  + " " + dt.hour   + ":" + dt.minute + ":" + dt.second;

will be doing horrible things to your heap.  The String class dynamically allocates memory on the heap to store the string content.  The operations you have there inadvertently create a rather alarming number of temporary Strings which are then thrown away at the end.  Every temporary String dynamically allocates RAM on the heap and can potentially lead to heap fragmentation.

For instance the numeric value `dt.second` is first converted to a String and memory allocated to store the content.  Every concatenation results in a new String with its dynamic allocation, etc.  Quite messy really.

Secondly, who knows what dynamic memory the `ArduinoJSON` library is using - quite a lot would be my guess - every tag, every value, etc, would need to be stored in memory somewhere, and unless they statically allocate a huge chunk of RAM (wasting most of your precious resource) they will be doing dynamic allocation - and that will make matters much worse.

So how would you get around it? It's actually quite simple - you need to think more about spoon-feeding a baby instead of preparing a 5 course banquet.

Instead of building up big objects with lots of data in them and sending them all out in one big chunk you need to just send little bits at a time.  There is absolutely no reason to use things like ArduinoJSON if all you are doing is sending data.

For instance to send the JSON data you could do something like this:

      if (client.connect("api.terrariums.eu", 80)) { // REPLACE WITH YOUR SERVER ADDRESS
        client.println("POST /v1/sensors HTTP/1.1");
        client.println("Host: api.terrariums.eu"); // SERVER ADDRESS HERE TOO
        client.println("Content-Type: application/json");
        client.println("Authorization: Basic bW9kdWxlMzoxMzIxMzI=");
        client.println("Connection: close");
        client.println();

        client.println("{");
        client.println("    \"modulename\": \"module3\",");
        client.println("    \"environments\": {");
        client.println("        \"1\": {");
        client.print("            \"temperature\":
        client.print(t1);
        client.println(",");
        client.print("            \"humidity\":
        client.print(h1);
        client.println(",");
        client.println("        },");

Etc.  You get the drift.

You notice I removed the `Content-length` header?  That's because you don't know how long the content will be now (one drawback), so to signal the end of the transmission you will have to close the connection (I don't recall if `client` has a way of only half closing - just the TX portion) to signal to the web server that you have finished.  However, if you know how long your numbers will be (say you format them to a specific number of characters) then your body size would always be the same and you can hard code a `Content-length` header.

Also - do you really need to send the time and date?  Surely the computer has a better idea of what the current time and date is than the Arduino - just use the computer's internal clock.

body:
You have used 461 out of 2048 of your RAM bytes for string literals alone. At the very least, use the `F()` macro where you can, eg.

    client.println(F("POST /v1/sensors HTTP/1.1"));
    client.println(F("Host: api.terrariums.eu")); // SERVER ADDRESS HERE TOO
    client.println(F("Content-Type: application/json"));
    client.println(F("Authorization: Basic bW9kdWxlMzoxMzIxMzI="));
    client.println(F("Connection: close"));
    client.print(F("Content-Length: "));

Ditto for `Serial.print` and `lcd.print` where you are printing strings.

After that, what Majenko suggested is a good idea. Using a custom library is well and good, but JSON is easy enough to output directly. Just make a small function to do it for you.

---

> Problem now is the Content-length... How do I calculate it ?

Do you absolutely need it? If you do, instead of building up the entire content first, I suggest two passes.

First pass outputs to a dummy class which simply calculates the length, second pass actually outputs. Something like this:

    // outputting class that just counts output
    class DummyOutput : public Print
    {
    private:
      unsigned long length_;

    public:
      void begin ()
        {
        length_ = 0;
        }
      virtual size_t write (byte c)
        {
        length_++;
        return 1;
        }
      unsigned long getLength () const { return length_; }

    };  // end of DummyOutput

    DummyOutput countOutput;  // instance of DummyOutput

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

      Print * outputter;  // where to write to

      for (int pass = 1; pass <= 2; pass++)
        {
        randomSeed (1);
        switch (pass)
         {
         case 1: outputter = &countOutput;
                 countOutput.begin ();
                 break;

         case 2: outputter = &Serial;
                 break;
         } // end of switch

        // generate some output
        for (int i = 0; i < 25; i++)
          {
          outputter->print (random (5000));
          outputter->print ('\n');
          }

        switch (pass)
         {
         case 1: Serial.print (F("Content-length: "));
                 Serial.println (countOutput.getLength ());
                 break;

         case 2: break;
         } // end of switch

        }  // end of for loop
      }  // end of setup

    void loop ()
      {
      }  // end of loop

Output:

    Starting
    Content-length: 121
    1807
    249
    73
    3658
    3930
    1272
    2544
    878
    2923
    2709
    4440
    3165
    4492
    3042
    2987
    2503
    2327
    1729
    3840
    2612
    4303
    3169
    2709
    2157
    4560

By generating the same output in two passes you can first just calculate the length (without outputting) and the second time you can output that length first, and then output the actual data.


body:
I found two cheap GSM module on ebay but didn't know that I can use them with Arduino or not.
Will you help me please?

Here are the link-

http://www.ebay.co.uk/itm/Smallest-SIM800L-GSM-Module-Micro-SIM-Board-Quad-band-Port-Onboard-Antenna-/111789339320?hash=item1a0729f2b8

http://www.ebay.co.uk/itm/SIM900A-Development-Board-Extension-Module-GSM-GPRS-Antenna-TTL-e/281517486292?_trksid=p2045573.c100033.m2042&_trkparms=aid=111001&algo=REC.SEED&ao=1&asc=20131017132637&meid=70128bc79b60410d862b64d36cc479b3&pid=100033&rk=1&rkt=4&sd=281517486292

title: Can I use these cheap GSM module with arduino?

Answers: 3

body:
Both seem to have the pin header for a serial port. So chances are that they can take standard AT commands.
I've seen many modems using additional AT commands for special functions, but they all supported also the basic AT commands.

body:
The SIM900A won't work in the UK, it's dual band.

The SIM800L is cheap as there is no power regulation on board. IIRC it requires 3.4V - 4.5V, min 2 amp supply. Check the data sheet to be sure.

body:
You can actually use the sim900a and 900a mini in the uk but you will have to download firmware and flashing tools that you will find with a web search, not for the beginner though, an 800l is your best bet with a SMA Female JACK Connector to U.FL/IPX Converter Pigtail Cable F1445K so you can attach an sma antenna

cheers
Stuart


body:
Is it possible to use digital pin 6 (PD6_PCINT22/AIN0) to read an analog voltage with analogRead()?

According to the ATMega datasheet, this should be possible.

If yes how is it done ? (pin configuration)

title: Reading analog signal from digital pin #6

Answers: 2

body: That is not possible. AIN0 is an input to the analog *comparator*, not the analog-to-digital converter. Only ADC0 through ADC8 (connected to the internal temperature sensor), the 1.1V reference, and ground can be connected to the ADC.

body:
Maybe. The Arduino board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega) and the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the Mini and Nano, 0 to 15 on the Mega).

As you can see in the image below the pin PD6 is not an analog input. To be an analog pin it should be write ADCx, like the PC0..5.

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

So, if you are not using and Arduino Uno you can't use PD6 as analog input but you can use PC0..5.

To read an analog value using [analogRead()][2] method you can do like this:

    int analogPin = 3;
    int val = 0;           // variable to store the value read

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

    void loop()
    {
      val = analogRead(analogPin);    // read the input pin

      Serial.println(val);             // debug value
    }

  [1]: https://i.stack.imgur.com/GNTeU.png
  [2]: https://www.arduino.cc/en/Reference/AnalogRead


body:
Using the Arduino tutorial "[Button][1]", I have noticed that if I totally disconnect Pin2 from the circuit, the LED comes on dimly.

I am trying to understand HOW this happens.  Is it simply due to being a floating ground?

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

  [1]: https://www.arduino.cc/en/Tutorial/Button
  [2]: https://i.stack.imgur.com/St0Tc.png

title: How is LED powered when PIN 2 is disconnected?

Answers: 1

body:
The `pinMode(buttonPin, INPUT);` line tells the board to set the `buttonPin` in high impedance mode.

When you disconnect the wire the state of that pin becomes unknown; usually it oscillates.
Since it is oscillating, the LED turns on and off randomly: you see it "dimly light".

The usual solution is to use a pull-up or pull-down. I suggest you to wire your buttons towards the ground, declare the pins as `pinMode(buttonPin, INPUT_PULLUP);` and invert the logic (i.e. `buttonState = !digitalRead(buttonPin);`). This way it will never oscillate again.


body:
I am working on building a wordclock using one of the several design ideas that you can find all over the Internet. Something like a mix of this one: http://www.instructables.com/id/Sleek-word-clock/ and this one: http://www.instructables.com/id/Personalised-Word-Clock/ A lot of the guides suggested building your own Arduino to save money, but I found these Arduino Nano clones for $7/apiece: http://www.amazon.com/gp/product/B00SGMEH7G.

I've done a few simple projects before, but nothing with the same kind of power demand. How can I figure out the power requirements? My plan is to use approximately 64 3mm LEDs via shift register, or possibly the equivalent segments of an LED strip.

The Nano clone does not have a barrel connector for external power adaptor. Should I directly solder on the power cables from an external adaptor? Use a screw terminal or similar? Is the USB adaptor a good enough source of power for 64 LEDs? Or do I have to do something else to supply external power to that many LEDs?

Thanks for any advice! I am experienced in programming but not in electrical engineering so many of the concepts are something I don't have a good handle on yet.

title: Using an Arduino Nano, how many LEDs can I safely power?

Answers: 1

body:
If you are running the LEDs from shift registers then the power rating of the Nano is irrelevant.

If you are wanting to use the Nano as the power source (not recommended) then you would need to know both your expected current and what the regulator on the Nano would be able to supply.  My immediate guess is "not enough".

64 LEDs at full brightness would be expected to use a maximum of say 20mA each, so 1.28A just for the LEDs.  That's a huge amount, and way more than any linear regulator can be expected to supply without melting everything around it.

So you can reduce your current requirements by not having the LEDs as bright.  Half the current does not equate to half the apparent brightness. In fact at half the current you probably won't notice much difference at all.  At a tenth of the current you will see them a bit dimmer, but not as much as you would expect.

So you can come up with a compromise between the brightness you desire and the current consumed by each LED.

Say you end up deciding on (as Gerben has suggested) a current of 5mA per LED.  When all LEDs are on that would be (5 × 64) 320mA.  That's reasonable for a linear regulator, but still will generate more heat than is really advisable.

So you should, for this project (assuming you aren't going to be using multiplexing, which is a whole other ballgame), investigate using a switching (aka "buck") regulator.  You can pick these up on eBay for just a couple of dollars and can quite happily supply amps as opposed to milliamps and will allow you to run far more LEDs without going into thermonuclear meltdown.

Another important consideration to think about is how much current an individual shift register can provide - both through its output pins and in total for the whole chip.  There are special constant current LED driving shift registers that remove the need for individual resistors on each LED and give much better control over the LEDs than traditional logic output shift registers.


body:
I was using displays with serial communication (SPI), but sending bytes to draw a tile-based picture was way too slow so I'd like find one with a parallel port, enough fast bandwidth to receive fast pictures at a speed at least 10FPS (but I'd like 50FPS or 60FPS) from Arduino Mega (ATMEGA2560) and which has a library compatible with the Arduino's C++ compiler.

I think I've seen somewhere how to connect a display onto the XMEM pins of the Mega and send bytes like this:

    *(0x12)=0x34 // Sends 0x1234

However, I couldn't find where to buy that specific one.

I was searching on eBay, but only found displays of unsupported drivers or drivers with broken links that I couldn't download, and displays that are ridiculously large like a shovel!

The resolution it needs to have is minimum 128x64, aspect ratio must be X:Y where X is greater than Y (unless it's possible to send bytes sideways while the screen is physically placed in a different orientation on the PCB).

It must be a touch display sensitive on anything (like Nintendo DSi when drawing Flipnotes).

It should be either:

 - Monochrome
 - Color display with MS Paint colors if it has equal to or less than 256 colors
 - Color display with 16-bit color input mode if it has a lot of colors

It should be no bigger than 2.5" because this is for a little handheld console.

If anyone knows where to buy it, please comment.
<br>Thank you for your time.

title: Looking for a game application oriented display for Arduino Mega

Answers: 2

body:
I'd suggest, if you haven't done it already, to take a look at what is supported by [uGFX][1].

If you find any HW meeting your needs, you can at least be sure that it is supported.

  [1]: http://ugfx.org/

body:
> I was using displays with serial communication (SPI)  ...

Personally I regards serial and SPI as different things:

* [Serial](http://www.gammon.com.au/forum/?id=10894)
* [SPI](http://www.gammon.com.au/spi)

SPI is somewhat faster than serial.

---

> ... sending bytes to draw a tile-based picture was way too slow ...

How slow was it? What was your target speed?

---

> The resolution it needs to have is minimum 128x64 ... It should be no bigger than 2.5"

Something like [2.2" 18-bit color TFT LCD display](http://www.adafruit.com/products/1480) ?

---

> fast bandwidth to receive fast pictures at a speed at least 10FPS ...

See [Toorum's Quest II - Retro video game and console](http://www.gammon.com.au/forum/?id=12623)

That guy made a sideways scrolling game outputting to video with a display resolution of 104x80 with 256 colors. He also had sound generation and managed input from a NES controller.

See [video of it in operation on YouTube](http://www.youtube.com/watch?v=sLvgW_zb6bQ).


body:
For my project I need a GPS module, it should be cheap and I should be able to use it with arduino, after some search I got a product on ebay, I'm a 16 year old school boy and I didn't know that it will work with Arduino or not. Help me.

Here is the link--
http://www.ebay.co.uk/itm/DIYMALL-VK16E-Module-Gmouse-GPS-Module-SIRF3-Chip-with-Ceramic-Antenna-TTL-Level-/181594912168?hash=item2a47e675a8

title: Can I use this cheap GPS module with arduino

Answers: 2

body:
Yes.  You can tell that from two entries in the specification:

> TTL Level 9600 Baud Rate

That tells you it uses standard TTL (5V) serial to communicate, so on an Uno that would be pins 0 and 1 and the Serial object, or any pins of your choice and the SoftwareSerial library.

> Output SiRF binary system OR **nmea0183 V3.0**(GGA, GSA, GSV, RMC, VTG)

It outputs NMEA encoded data (bold added by me) which is what most of the Arduino GPS libraries are written to use.

body:
After some research it seems you can use that gps module with an Arduino. Here's a link to the data sheet for it: http://www.hanssummers.com/images/stories/ultimategps/vk16e.pdf. Also it seems like you have to use the TinyGPSPlus library to get it to work. Here's a link to learn more about it: http://arduiniana.org/libraries/tinygpsplus/. You may have to use the protocols in this data sheet: https://www.sparkfun.com/datasheets/GPS/NMEA Reference Manual-Rev2.1-Dec07.pdf.

All of this information was taken from this thread: https://www.linkedin.com/grp/post/4573843-5806249757395406852.


body:
I want to connect an RFID reader to an Arduino board. The RFID reader has several wires attached, and the manual mentions them as follows:

* Red: VCC +12V
* Black: GND
* Green: D 0/RX/4R+
* White: D 1/TX/4R−
* Blue: LED/CS
* Yellow: Beep

There is also another black wire attached, but the manual does not mention it.
This is an image of it:

[![Image of RFID reader][1]][1]

I have the red wire connected to the 5V pin and the black wire to the GND pin on Arduino board. Then I have the white wire connected to the RX pin on the Arduino board.

I'm trying to Serial-read the RX port using this code:

<!-- language: c -->

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

    void loop() {
        if (Serial.available() > 0) {
            int b = Serial.read();
            Serial.print(b);
            Serial.print(" ");
        }
    }

When I try to read a keyfob, only this is printed – nineteen times `248`:

    248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248

To me it looks like there's something wrong with the connection somewhere.

How can I properly read this RFID reader? If above assumption is not correct, is there something I should know?

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

title: How to read an RFID reader?

Answers: 2

body:
From my personal experience, you should give some init time to the rfid reader to init.

Try to use a digital output to control the chip reset, and give it some milliseconds to init.

I had a similar behavior with a rfid reader and the reason was this I just told.

Good luck!

body: Have you tried other baud rates? Could you paste a link to the manual or upload the manual itself? From what i could find quickly, the module supports 3 modes: RS232, RS485 and Wiegand 26/34. So the manual should provide some means of selecting a particular mode (perhaps the CS pin?). I suspect you arent actually using the RS232 mode, which is why you are getting strange results. If you can't find a way to select a mode, you could try brute-forcing it and try the WG26 mode next. This code from seeedstudio seems to do the job http://www.seeedstudio.com/depot/datasheet/RFID_630_WG.pde or you could look at the Wiegand protocol on Wikipedia and write your own code, since its relatively straight forward. Also a google image search turned up this link to Aliexpress: http://www.aliexpress.com/item/Waterproof-Security-Door-Access-Control-Wiegand-26-125KHz-RFID-ID-Card-Reader-EM4100-102A/1362129655.html; this is your reader, right?


body:
I am trying to make a workaround for the delay function. I am trying to use the function in the Analog Write Mega example, by replacing delay with the function i made. However, whenever i use my function instead of delay i get incorrect led behaviour.

Here is the link to the example:

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

Here is my code:

    int currmillis = 0; //used in my function to find the current millis()
    int prevmillis = 0; //used to hold previous value of currmillis
    int boolval = 0;    //used to control whether to write the brightness value to the led or not
    int time = 0;     //used in the delay function, difference between currmillis and prevmillis

    int timeloop(int); //the function i wrote, it is at the bottom of the code

    void setup() {
      Serial.begin(9600);
      for ( int i = 2; i <= 13; i++)
      {
         pinMode(i,OUTPUT);
      }
    }//Setting the pins to output and allowing serial communication.

    void loop (){

      for ( int thisPin = 2; thisPin <= 13; thisPin++ ) //to move from one led to the next
      {

        for ( int brightness = 0 ; brightness <= 255; brightness++) //change the brightness of the led
        {

          boolval = timeloop(2); //the delay function returns the time passed, if the time is greater than or equal to 2, the analogWrite will write the brightness to the led

          if (boolval >= 2){
            analogWrite(thisPin, brightness);
          }// if 2 ms pass, the led brightness will increase from 0 to 255 and then decrease in the following loop from 255 to 0, Once it reaches 0, the main loop moves to the next led.

        }

     for ( int brightness = 255 ; brightness >= 0 ; brightness--)
        {
          boolval = timeloop(2);

          if (boolval >= 2){
            analogWrite(thisPin, brightness);
          }
        }
              timeloop(100); // a delay of 100 ms using the function
      }
    }

    int timeloop (int interval){ // the delay function

      do{
       prevmillis = currmillis; //hold previous value
       currmillis = millis(); //find current value
        time = (currmillis-prevmillis);
      }while(time < interval);

      return time;
    }

Thank you

title: Alternative to delay function

Answers: 3

body:
What's the point? Why rewrite `delay()`?

Anyway:

    int timeloop (int interval){ // the delay function

      do{
        prevmillis = currmillis; //hold previous value
        currmillis = millis(); //find current value
        time = (currmillis-prevmillis);
      }while(time < interval);

      return time;
    }

In every iteration of that loop you are updating `prevmillis`. So you will never reach the wanted delay interval.

Apart from the fact that you may as well use the inbuilt `delay` rather than writing your own, and getting it wrong.

---

> I am trying to make a workaround for the delay function

Why?

[The XY Problem](http://xyproblem.info/)

body:
    // You don't need to return anything since it's just a delay
    // also I changed the parameters to long ints because millis()
    // returns a long int
    void timeLoop (long int startMillis, long int interval){ // the delay function

     // this loops until 2 milliseconds has passed since the function began
     while(millis() - startMillis < interval){}
    }

    // Your call for a 2 millisecond delay would be
    timeLoop(millis(), 2);

Also the leds may be acting weird because this schematic is wrong. As you can see one of the led's anode isn't connected to ground. It's circled in red.
[![enter image description here][1]][1]

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

If you really want it to return something you could use this:

    long int timeLoop (long int startMillis, long int interval){ // the delay function

     while(millis() - startMillis < interval){}
     return millis() - startMillis;
    }

But it really isn't needed.

body:
Depending on what you want the alternative function to do, there are a megaton of timer libraries at the [Arduino playground][1]. One of them is likely to provide what you need.

  [1]: http://playground.arduino.cc/Main/LibraryList#Timing


body:
I am using following code for my arduino project in which i have to control a dc motor using arduino uno via text messages.
my question is that i have used multiple number of 'If' statements and only one else statement at the last, i compiled this code and gives no error, is it ok to use multiple If statements one after another without using else after each if?

    #include <LiquidCrystal595.h>
    #include <GSM.h>

    GSM gsmAccess;
    GSM_SMS sms;
    char sendernumber[20];
    int Enable_m=11;
    int Control_2=12;
    int Control_7=10;
    LiquidCrystal595 lcd(7,8,9);
    void setup()
    {
       Serial.begin(9600);
       pinMode(Enable_m,OUTPUT);
       pinMode(Control_2,OUTPUT);
       pinMode(Control_7,OUTPUT);

       digitalWrite(Enable_m,LOW);
       digitalWrite(Control_2,LOW);
       digitalWrite(Control_7,LOW);

       lcd.begin(16,2);
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Hello");
       lcd.setCursor(0,1);
       lcd.print("Everyone");
       delay(2000);

       while (!Serial)
          Serial.println("SMS Messages Receiver");
       boolean notConnected = true;
       while(notConnected)
       {
          if(gsmAccess.begin("0000")==GSM_READY)
             notConnected = false;
          else
          {
             Serial.println("Not connected");
             delay(1000);
          }
       }
       Serial.println("GSM initialized");
       Serial.println("Waiting for messages");
    }

    void loop() {
       // put your main code here, to run repeatedly:
       char c;
       int val=0;
       val=digitalRead(Enable_m);
       if (val==LOW){
          digitalWrite(Enable_m,HIGH);
       }
       if (sms.available())
       {
          Serial.println("Message received from:");
          sms.remoteNumber(sendernumber, 20);
          Serial.println(sendernumber);

          if(sms.peek()=='#')
          {
             Serial.println("Discarded SMS");
             sms.flush();
          }
          while(c=sms.read())
             if(c=='motoroff'){
                analogWrite(Enable_m, 0);
                digitalWrite(Control_2,LOW);
                digitalWrite(Control_7,LOW);

             }
          if(c=='motoronclockwise'){
             analogWrite(Enable_m, 255);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          if(c=='motoronanticlockwise'){
             analogWrite(Enable_m, 255);
             digitalWrite(Control_2,HIGH);
             digitalWrite(Control_7,LOW);
          }
          if(c=='speedhalf'){
             analogWrite(Enable_m, 128);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          if(c=='speedquarter'){
             analogWrite(Enable_m, 65);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          if(c=='speed75'){
             analogWrite(Enable_m, 192);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          else{
             digitalWrite(Enable_m,HIGH);
             Serial.print(c);
          }
          Serial.println("\nEND OF MESSAGE");
          sms.flush();
          Serial.println("MESSAGE DELETED");
       }

    }

title: Multiple If statements

Answers: 3

body:
Two things:

1. The `else` will only be subject to the last `if` being false, the rest of the `if` statements are completely separate and can affect the `else` in no way whatsoever.  To chain them you need `if (...) { blah blah } else if (...) { blah blah }` etc.
2. You cannot compare characters and strings like that (and in fact they're not even strings, they're lots of characters squeezed into a single character through the use of the wrong kind of quotes).

So basically no, your whole program there is completely wrong and won't do what you think it will and you need to completely re-thing how it works.

Some tips:

* Use `strcmp()` to compare strings.
* If reading strings from serial store them in character *arrays* not a single character.

You might find this useful:

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

body:
If you intend each `if` statement to be executed, regardless of the whether the prior one(s) did, then yes, they do not require `else` clauses.

If you mean to try each condition until you find one that is true, and execute that one and only that one, then the second and subsequent `if`s need to be `else if`s. The final one may be just an `else`, if you want a catch-all clause; or an `else if` if it is possible that none of the clauses might need to be run.

Update: To execute at most one clause, you need to use `if`, some `else if`s, and maybe a final `else`.

If you're trying to match strings, you can use an array of strings or use literal strings as you've tried to do. Strings have to be enclosed in double-quotes (`"`) however, not the single quotes you've used. And the variable `char c;` you tried to use to hold the SMS message is really only one character. You'll need to make it an array of characters such as `char c[140+1];`,  the size of the longest SMS message + one more for a  zero-character string-terminator. C doesn't directly compare strings as simple variables so `==` and `!=` won't work here. You'll need to compare them with strcmp().

body:
    #include <LiquidCrystal.h>
    #include <GSM.h>

    GSM gsmAccess;
    GSM_SMS sms;
    char sendernumber[20];
    int Enable_m=11;
    int Control_2=12;
    int Control_7=10;
    LiquidCrystal lcd(7,8,9,8,1,2,3,4,5,6);

    void setup()
    {
       Serial.begin(9600);
       pinMode(Enable_m,OUTPUT);
       pinMode(Control_2,OUTPUT);
       pinMode(Control_7,OUTPUT);

       digitalWrite(Enable_m,LOW);
       digitalWrite(Control_2,LOW);
       digitalWrite(Control_7,LOW);

       lcd.begin(16,2);
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Hello");
       lcd.setCursor(0,1);
       lcd.print("Everyone");
       delay(2000);

       while (!Serial)
          Serial.println("SMS Messages Receiver");
       boolean notConnected = true;
       while(notConnected)
       {
          if(gsmAccess.begin("0000")==GSM_READY)
             notConnected = false;
          else
          {
             Serial.println("Not connected");
             delay(1000);
          }
       }
       Serial.println("GSM initialized");
       Serial.println("Waiting for messages");
    }

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

       // I chose 160 since that is max size for sms
       char message [160];
       // this fills message with null characters
       memset( message, '\0', sizeof(char)*160 );

       int val=0;
       val=digitalRead(Enable_m);
       if (val==LOW){
          digitalWrite(Enable_m,HIGH);
       }
       if (sms.available())
       {
          Serial.println("Message received from:");
          sms.remoteNumber(sendernumber, 20);
          Serial.println(sendernumber);

          // you used single qoutes properly here
          // single qoutes denote a char which is a single character
          if(sms.peek()=='#')
          {
             Serial.println("Discarded SMS");
             sms.flush();
          }

          // this will add the characters to messages[]
          for(int i = 0; message[i] = sms.read(); i++){}

          // I changed this to double qoutes since you need double
          // qoutes to denote a string literal
          if(strcmp(message, "motoroff") == 0){
             analogWrite(Enable_m, 0);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,LOW);
          }
          else if(strcmp(message, "motoronclockwise") == 0){
             analogWrite(Enable_m, 255);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          else if(strcmp(message, "motoronanticlockwise") == 0){
             analogWrite(Enable_m, 255);
             digitalWrite(Control_2,HIGH);
             digitalWrite(Control_7,LOW);
          }
          else if(strcmp(message, "speedhalf") == 0){
             analogWrite(Enable_m, 128);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          else if(strcmp(message, "speedquarter") == 0){
             analogWrite(Enable_m, 65);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          else if(strcmp(message, "speed75") == 0){
             analogWrite(Enable_m, 192);
             digitalWrite(Control_2,LOW);
             digitalWrite(Control_7,HIGH);
          }
          // This else will only be executed if the previous if and else if statements are false
          else{
             digitalWrite(Enable_m,HIGH);
             Serial.print(message);
          }
          Serial.println("\nEND OF MESSAGE");
          sms.flush();
          Serial.println("MESSAGE DELETED");
       }

    }

So I've made some edits to your code. For example this code `'motoronanticlockwise'` isn't correct. Single quotes are used for `char` data types and double quotes are used for string literals. You should use double quotes since there are multiple characters `"motoronanticlockwise"`. Also as Majenko said you would have to use `strcmp()` in order to compare `c-strings`
c-strings are `char` arrays that have a null terminator `'\0'`. Also `strcmp()` returns `0` if the two strings are equal.

Your last `else` statement will only executed if the previous `if` statement is `false`. It seems like you only want it to execute if **all** of the previous `if` statement are false. To do this you make the first `if` statement and then make a chain of `if else` statements followed by a single `else` statement. You can have a single `if` statement with no `else` or `if else` statements however, if you want `else` or `if else` statements then you need to have an `if` statement. I've made the necessarily edits to your code already.

Lastly, this part of the program is the biggest problem `while(c=sms.read())` This is because `sms.read()` returns a `char` so you can only read the sms message one character at a time. To do this properly you should make a character array and store the values returned by `sms.read()` in it. This can be done like this

    char message [160]; // I chose 160 since that is max size for sms
    memset( message, '\0', sizeof(char)*160 ); // this fills message with null characters
    // this will add the characters to messages[]
    for(int i = 0; message[i] = sms.read(); i++){}

I am using a `for` loop to iterate through `message[]`.

Try the above and get back to me if there are any problems with it.


body:
I want to log GPS positions to an external EEPROM over I2C.

For example:
Latitude: 51.0000
Longitude: 4.0000

If I remove the decimal place then each of these addresses would consume up to two bytes each.

My question is: ***How can I log each new set of GPS data to a new memory address on the EEPROM each time?***

Bearing in mind that the Arduino might be switched off between entries.

title: How do you write to a free location on an external EEPROM?

Answers: 4

body:
You could assign the first byte(s) of the EEPROM as the address of the next free location in which to store GPS coordinates, and update it before the Arduino sleeps. At wake-up, retrieve the address.

You could keep the pointer in RAM, too; RAM keeps its contents across a sleep. But using EEPROM would even let you power off the Arduino, and still pick up where you left off after the power-up reset. (Of course, other parts of your program would have to be restart-tolerant as well; I'm just looking at the coordinate storage here).

As an aside, two bytes isn't sufficient to store a GPS coordinate to four decimals unless their range is limited such that you can scale them into [0 - 65535].

body:
The trick you are looking to implement here is the ability to look through the EEPROM and say "This is the last place I wrote to - I will write to the next place now."

There's two ways of doing it, the easy way and the right way.

The easy way is to maintain a single address in the EEPROM that says where you wrote to last.  If you are trying to implement some form of wear levelling to extend the life of your EEPROM then this would basically negate it, since that one cell in the EEPROM will wear out before the rest of it and become useless.  So it's really not a good idea although it may sound like it at first.

The *right* way to do it is to store *more* information in the EEPROM every time.  Not only do you need to store the data, but also some kind of identifying *sequence* number.

Say you have 4 bytes of data to write each time.  Add a fifth byte to it.  That fifth byte increases by one each time you write.  Before you write you scan through the EEPROM looking at every fifth byte looking for the "end" of the sequence.

For instance, you may end up with (`xx` is your data bytes) in hexadecimal:

    00: 00 xx xx xx xx
    05: 01 xx xx xx xx
    0A: 02 xx xx xx xx
    0F: 03 xx xx xx xx
    14: FF FF FF FF FF

You see that at address 0x14 the nice sequence of numbers breaks.  Therefore your next write must be at that point.  Now, if you then loop through the EEPROM many times after a while, you may end up with something that looks like this:

    00: FE xx xx xx xx
    05: FF xx xx xx xx
    0A: 00 xx xx xx xx
    0F: 01 xx xx xx xx
    14: 58 xx xx xx xx

You can see a clear sequence here of `0xFE 0xFF 0x01` where they increase by 1 each time (0xFF + 1 = 0x00) so you can see that you have looped through your sequence numbers. You don't care though because it's still just plus one.  Only when you get the jump from 0x01 to 0x58 does the sequence break, so you know where the last write would have been.

There are only a couple of small gotchas here:

1. You can only use 5*n cells in the EEPROM since the last 5-byte packet of data may not fit within the last bit of EEPROM (say it's a 1024 byte EEPROM you would have room for 204.8 packets - so 204 packets and 4 bytes left over).
2. You must ensure that you don't end up with exactly 256 packets fitting in the EEPROM before you loop the address - otherwise the sequence won't "break" so you will never know where the last write was after the first loop.

body:
You can divide EEPROM space into entries and provide each entry with a single "used" bit. You could use a separate byte to store it, or reuse a bit from a byte which is not completely used by your data.

Suppose you start with EEPROM willed with zeroes, and you decide that the first byte of each entry holds the "used" bit in the LSb. When you log coordinates the first time, you'll have:

     /---"used"
    01 51 00 00 04 00 00
    00 00 00 00 00 00 00
     \---"free"
    ...
    00 00 00 00 00 00 00

(of course, you don't have to store GPS coordinates as [BCD](https://en.wikipedia.org/wiki/Binary-coded_decimal), it's just an illustration).

Note that as you add entries, it's trivial to keep track of the last one: just check the entries in sequence until you find a "free" one and go back one step. Also note that the first entry is always "used".

This will go on until all your entries are "used":

    01 51 00 00 04 00 00
    01 52 00 00 05 00 00
    ...
    01 53 00 00 06 00 00

At this point (when you have to write new data but there are no "free" entries), you start writing from the first entry again, inverting the value of the "used" bit:

     /---"used"
    00 54 00 00 07 00 00
    01 02 00 00 05 00 00
     \---"free"
    ...
    01 53 00 00 06 00 00

(remember that the first entry is always "used"? Thanks to this, it's possible to simply swap the values representing "used" and "free" entries without actually erasing anything).

To sum up, the algorithm is:

- read the "used" bit from the first entry
- scan entries until the value of the "used" bit changes, or until you reach the end.
- to read the last logged data, use the last "used" entry
- to write new data, use the first "free" entry. If there are no "free" entries, start from the beginning, inverting the "used" bit.

body:
The question asks specifically about EEPROM (E2) and many of the answers point out or attempt to address E2's main limitation: limited # of write operations. Not mentioned is E2's slow speed. Its is best suited for storing infrequently modified data such as-built- or setup parameters such device calibration data and features of a device's external operating environment. Its only real advantage over other solutions is that it may already exist on your MCU - Atmega 328, for instance.

The new(er) kid on the block for non-volatile data storage is Ferroelectric RAM - FRAM. Write times are on the order of 30 times faster, at 150ns, and endurance is claimed to be 10^12 writes, or 10 million TIMES the endurance of E2. I've built a data logger that uses a ring-buffer in FRAM to store periodic data samples and write them on request.

The same techniques proposed in the answers for E2 will work equally well in FRAM with the additional advantage that you can ignore the complications meant to work around E2's limited write-endurance.

And by way of disclaimer: I don't sell this this stuff or have any other interest in it. But I do use it and it works like it says on the box.

[Adafruit makes these][1] on a breakout board in a couple of variations - size and serial-bus type - that are sold by them and other retailers. The link is for an 8K-byte, SPI-bus board.

  [1]: https://www.adafruit.com/product/1897


body:
I have an Arduino Mega AT2560 and need to have real DAC. I purchased the [Sparkfun 12 bit DAC][1], however I don't think it is working properly.

I am using the Arduino wire library to communicate with the DAC. When I write 0, I am expecting to see 0v from the DAC's OUT pin. However, I see some seemingly random constant voltage. In reverse, when I write 4095 to the DAC I see the same voltage as when I write 0. I expected to see 5v.

 1. Can someone verify that I hooked it up correctly?
 2. Can someone verify the code I am using?

[![12 Bit DAC with Arduino ATMega 2560][2]][2]

    #include <stdint.h>
    #include <stdio.h>
    #include <Wire.h>

    #define MCP4725_ADDR 0x60 // [0000 0110]
    /*
    * 12 Bit DAC MCP4725 gives a range of 4096 possible values.
    *
    */
    void setup() {
      Wire.begin();
      Serial.begin(9600);
    }

    void loop() {
      Wire.beginTransmission(MCP4725_ADDR);
      Wire.write(64);            // cmd to update the DAC [0100 0000]
      Wire.write(4095 >> 4);        // the 8 most significant bits...
      Wire.write((4095 & 15) << 4); // the 4 least significant bits...
      Wire.endTransmission();
    }

  [1]: https://www.sparkfun.com/products/12918
  [2]: https://i.stack.imgur.com/YXl7l.jpg

title: Arduino with 12 bit DAC (MCP4725) Not Working

Answers: 2

body:
Sorry I'm late -- I realize this question was asked 8 months ago, but it doesn't look like you fixed it, and I figure others can always benefit (or you might even, if you still want to try).

Your code looks correct (I compared it to the Sparkfun example, and also to the datasheet for the MPC4725).

However, it does look like you're using the wrong address for the part.
(The actual value for the address is not given in the Sparkfun example -- at least, I couldn't find it).

Your line:

    #define MCP4725_ADDR 0x60 // [0000 0110]

is wrong in two places:

1) 0x60 is 0110 0000, not 0000 0110

2) According to the datasheet (section 7.2), the address should begin with the device code 00, and then the address gets appended. So assuming an address of A2 = 0, A1 = 0, and A0 = 0 (default), the value for MCP4725_ADDR looks like it should be 0xC0 or 00 000x.  If you soldered the address line to Vcc instead of ground, the address should be 0xC2 or 00 001x.

The x in the address line represents the read/write bit.  If you're trying to command the DAC, it should not be asserted, so the addresses above are correct. If you're trying to read the current value, it should be asserted, which makes your address 0xC1 or 0xC3.

If you have the address wrong, even though the rest is correct, the part will ignore it, so that's probably the issue you're seeing.

Hope this helps someone!

body:
1. you want to make sure that there are pull-ups on the SCL/SDA lines;
2. you want to make sure that the address is correct. some routines use 7-bit notation for that, and others use 8-bit notation for that. end of the day, you want the transmission to be 0xc0 | (A2:A1:A0:R/W). so check the write.write() and see what it expects. I suspect that it expects 0xCx, rather than 0x6x.

having said that, here is your code running on an uno, with the dac configured as per sparkfun spec.

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

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

so I think it is fair to say that the code is ok but something happened on your end that prevented it from working.


body:
I'm gettng an error "error: expected primary-expression before ',' token" in the following line of code - I have initialized an array with 220 ints. What am I doing wrong here?

    const PROGMEM int P7Val[] = {1635,1635,1635,1635,1635,1630,1630,1630,1630,1630,1625,1625,1625,1625,1620,1620,1620,1620,1615,1615,1615,1610,1610,1610,1605,1605,1605,1600,1600,1600,1595,1595,1595,1590,1590,1590,1585,1585,1580,1580,1580,1575,1575,1570,1570,1570,1565,1565,1560,1560,1555,1555,1555,1550,1550,1545,1545,1540,1540,1535,1535,1535,1530,1530,1525,1525,1520,1520,1515,1515,1510,1510,1505,1505,1500,1500,1495,1495,1490,1490,1490,1485,1485,1480,1480,1475,1475,1470,1470,1465,1465,1460,1460,1455,1455,1450,1450,1445,1445,1440,1440,1435,1435,1430,1430,1425,1425,1420,1420,1415,1415,1410,1410,1405,1405,1400,1400,1395,1395,1390,1390,1385,1385,1380,1380,1380,1375,1375,1370,1370,1365,1365,1360,1360,1355,1355,1350,1350,1345,1345,1345,1340,1340,1335,1335,1330,1330,1325,1325,1320,1320,1320,1315,1315,1310,1310,1305,1305,1305,1300,1300,1295,1295,1290,1290,1290,1285,1285,1280,1280,1275,1275,1275,1270,1270,1265,1265,1265,1260,12601635,1635,1635,1635,1635,1630,1630,1630,1630,1630,1625,1625,1625,1625,1620,1620,1620,1620,1615,1615,1615,1610,1610,1610,1605,1605,1605,1600,1600,1600,1595,1595,1595,1590,1590,1590,1585,1585,1580,1580,1580,1575,1575,1570,1570,1570,1565,1565,1560,1560,1555,1555,1555,1550,1550,1545,1545,1540,1540,1535,1535,1535,1530,1530,1525,1525,1520,1520,1515,1515,1510,1510,1505,1505,1500,1500,1495,1495,1490,1490,1490,1485,1485,1480,1480,1475,1475,1470,1470,1465,1465,1460,1460,1455,1455,1450,1450,1445,1445,1440,1440,1435,1435,1430,1430,1425,1425,1420,1420,1415,1415,1410,1410,1405,1405,1400,1400,1395,1395,1390,1390,1385,1385,1380,1380,1380,1375,1375,1370,1370,1365,1365,1360,1360,1355,1355,1350,1350,1345,1345,1345,1340,1340,1335,1335,1330,1330,1325,1325,1320,1320,1320,1315,1315,1310,1310,1305,1305,1305,1300,1300,1295,1295,1290,1290,1290,1285,1285,1280,1280,1275,1275,1275,1270,1270,1265,1265,1265,1260,1260,1255,1255,1255,1250,1250,1245,1245,1245,1240,1240,1235,1235,1235,1230,1230,1225,1225,1225,1220,1220,1215,1215,1215,1210,1210,1210,1205,1205,1200,1200,1200,1195,1195,1195,1190,1190,1185,1185,1185,1180,1180,,1255,1255,1255,1250,1250,1245,1245,1245,1240,1240,1235,1235,1235,1230,1230,1225,1225,1225,1220,1220,1215,1215,1215,1210,1210,1210,1205,1205,1200,1200,1200,1195,1195,1195,1190,1190,1185,1185,1185,1180,1180};

Answers: 1

body:
Two things:

1. You have a comma missing: `1260,12601635,1635,`
2. You have an extra comma: `1180,1180,,1255,1255`

If you reformat your list into a nice regular table (say 10 entries per line) across multiple lines these things instantly become apparent.


body:
First question: Since we can control the volts that we can throw via PWM pins on Arduino, can we use it to power the 3.3 V ESP8266?

Second question: Can we also use these PWM pins as software serial pins i.e. they will be sending instructions at 3.3 V?

title: Can I run ESP8266 via Arduino using the PWM pins?

Answers: 1

body:
>First question, Since we can control the volts that we can throw via PWM pins on Arduino, can we use it to power the 3.3v ESP8266?

No. The ESP8266 draws *far* too much current (in excess of 200mA) to use anything other than a proper supply.

>Second question, Can we also use these PWM pins as Software serial pins i.e. they will be sending instructions at 3.3v?

We'll drop the "also", since we've decided that you're not doing that.

You can use SoftwareSerial on any GPIO pins you like, provided the RX pin supports pin change interrupts.


body:
I want to connect my Arduino UNO to a serial device that once powered displays signature numbers. I want to then display those numbers on an LCD display. I have my 16x2 LCD wired correctly and it works fine even when I use the SerialDisplay example code from the library.

My questions are:

1. Can I use a USB to TTL serial cable to connect the RX/TX pins of the serial device to the TX/RX pins of the arduino?
2. The two numbers are more than 16 characters. How can I cut the numbers down and then display the two numbers on two seperate lines of the LCD display?

Let me know if I should provide further details.

title: Arduino Interface with Serial device and LCD display

Answers: 1

body:
 1. If the device _is_ serial and you want to connect it to the Arduino _serial_ port, why would you use a usb-to-serial converter?
For a serial to serial connection, you have to connect TX, RX and GND.
This is the bare minimum for bidirectional communication, if your device is really read only, you can use just the TX and GND.

 2. it depends how you receive data from your "serial device" - btw, what is it? If the data comes as either ascii or individual characters, then it's easy: treat them as strings and display them separately. If the numbers arrive in binary format, you have to perform the conversion to string.

Questions like this should have attached at least a snippet, if not all, of code.


body:
I'm teaching this [sketch][1] in my class. I understand most of the sketch and can see the class that makes the bird move, but I still don't quite understand how the code makes the sprite "move." I can also see what generates the Pipes but I don't how the code creates them or randomizes them.

Here is the code for both:

Bird

    class Chym {

    private:
      int frameCount;
      int x;
      int y;
      int deltaIde;
      int delayFrame;

      int jumpCount;
      int maxJumpCount;
      int moveSpeed;

      bool _isDead;
    public:
      void respawn() {
        x = 24;
        y = 20;
        deltaIde = -1;
        moveSpeed = 1;
        jumpCount = 0;
        _isDead = false;
      }

      Chym() {
        frameCount = 0;
        delayFrame = 0;
        maxJumpCount = 20;
        respawn();
      }

      void render() {
        if (frameCount < ANIM_FRAME / 2) {
          display.drawBitmap(x, y, flappybird_frame_1, 16, 12, 1);
        }
        else {
          display.drawBitmap(x, y, flappybird_frame_2, 16, 12, 1);
        }
      }

      void update() {
        delayFrame++;
        if (delayFrame == DELAY_FRAME) {
          y += deltaIde * moveSpeed;
          delayFrame = 0;
        }

        if (y > 35) {
          _isDead = true;
        }

        frameCount++;
        if (frameCount >= ANIM_FRAME) frameCount = 0;
      }

      bool isDead() {
        return _isDead;
      }

      void die() {
        _isDead = true;
      }

      void cancelJump() {
        jumpCount = 0;
        flyDown();
      }

      void flyUp() {
        if (jumpCount < maxJumpCount) {
          deltaIde = -1;
          moveSpeed = 3;
          jumpCount++;
        }
        else {
          flyDown();
        }
      }

      void flyDown() {
        deltaIde = 1;
        moveSpeed = 1;
      }

      int getX() {
        return x;
      }

      int getY() {
        return y;
      }

    };
 Pipe

    class Bar {

    private:
      int x;
      int y;
      int delayFrame;
      int moveSpeed;
    public:
      Bar() {
        delayFrame = 0;
        x = 0; y = 24;
        moveSpeed = 2;
      }

      void setPos(int sx, int sy) {
        x = sx; y = sy;
      }

      void render() {
        display.drawBitmap(x, y - 30, bar_top, 8, 20, 1);
        display.drawBitmap(x, y + 10, bar_bottom, 8, 20, 1);
      }

      void update() {
        delayFrame++;
        if (delayFrame == DELAY_FRAME) {

          x -= moveSpeed;
          if (x < -10) x = 95;

          delayFrame = 0;
        }
      }

      int hitTest(int tx, int ty) {
        int hitX = ((tx >= x - 16) && (tx <= x))?1:0;
        int hitY = ((ty <= (y - 10)) || (ty + 12 >= y + 10))?1:0;
        if (hitX != 0) {
          return hitY;
        }
        return 0;
      }

    };

https://www.youtube.com/watch?v=04cY78Y2d3g

  [1]: https://www.dropbox.com/s/1hxxvueidqjoi09/flappyDuino.zip?dl=0

title: How does this code move the bird sprite in this sketch?

Answers: 1

body:
This part of your code is what changes the sprite's y-value.

    y += deltaIde * moveSpeed;

When you click the "jump" button or when the bird falls the y-value is changed to reflect either an upward movement or a downward movement. When your `render()` method is called the bird will either be drawn higher up on the y-axis (it's flying) or lower on the y-axis (it's falling).

As for the bars, if you watch closely in the video you can see that they aren't actually randomized.

**Compound Assignment Operators**

`+=` is the "plus assign" operator. It adds whatever is on the right side to the variable on the left side. Here is a table of other compound assignment operators: https://en.wikipedia.org/wiki/Operators_in_C_and_C++#Compound_assignment_operators

    int x = 5;
    x += 2; // equals 7; equivalent to x = x + 2;
    x = 5;
    x = x + 2; // also equals 7; equivalent to x += 2;


body:
I have an Arduino UNO. It has VoltageIN on a pin. Is there any difference between powering my UNO through VIN or powering it through the DC port?

The [docs only say this](https://www.arduino.cc/en/Main/ArduinoBoardUno),

> 5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

So it seems to imply VIN/USB/DC in all go through the voltage regulator? Is there any difference then?

Is there any advantage to running a variable power supply through an adapter like this:
[![DC-in][1]][1]

Or should I just go through VIN?

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

title: Arduno Uno voltage in via VIN pin or DC power?

Answers: 2

body:
DC Jack has a Reverse Protection Diode, that drops 0.7V at usable currents. The VIN does not. Both go through the on board LM7805 or similar linear regulator. The USB does not, but it does go through a P-Channel Mosfet used to switch between USB and DC/VIN power before connecting to the 5V rail. The 5V pin bypasses the regulator, Diode, and P-Channel Mosfet completely.

The advantage of the DC jack is that the Reverse Protection Diode is used, preventing reverse voltage problems if you wire it wrong.

body: If you have a "variable power supply" just set it to 5.00v and connect to the 5v pins.  Eg like the this http://blog.unixbigot.id.au/2015/10/make-5-volt-battery-supply-for-any.html?m=1


body:
I have successfully made a voltage measurement circuit on my Teensy 3.1 that reads a voltage coming out of digital pin 0 set high and coming back into an analog pin A0 to read voltage.

Basically:

<!-- language: c -->

    int timer = 100;
    int ColA = 0;
    int Output;

    // Setting digital pin functions

    void setup()
    {
      Serial.begin(38400);
      pinMode(0, OUTPUT);

    }

    // Program

    void loop()
    {
      digitalWrite(0, HIGH);
      delay(timer);
      Output = analogRead(A0);
      Serial.println(Output);
      delay(timer);
    }

It works fine with my circuit on a Teensy 3.1 running 3.3v however when i run this code on an Arduino Uno running 5v wired exactly the same way I just get this print out of numbers that cycles back and forth from ~128 down to 0 and back constantly.

Any insight on the differences here would be great. I need the 5v micro-controller to run a 4051 multiplexer!

title: Why does my analogRead work on Teensy but not Arduino Uno?

Answers: 1

body:
If you're still using D0 as your output on the Uno then yes you are doomed to failure.

D0 and D1 are the serial port. You are using that to communicate with the PC. You cannot use them for any other purpose at the same time.

Pick a different IO pin to be your voltage source.


body:
**I just bought the SmartEverything FOX Board which is Arduino compatible** http://www.smarteverything.it/wp-content/uploads/2015/10/SmartEverything-User-Guide-Ver-1.01.pdf and simply tried to get started with it.

**My OS is Ubuntu 14.04, my laptop DELL XPS 13 bought in 2014**

**I cannot upload sketches on it, when I try, it gets stuck on uploading**, whether it is a basic script (blinkRBG) or even the default one with empty setup and loop methods, my laptop processor keeps running at 100% and nothing happens.
**The board does not do anything, tx/rx leds do not flash.**
**I can access to it with a Windows 7 laptop  (UPDATE: and another UBUNTU laptop) from a frien**d, I could upload the basic blinkRGB sketch. If I try to upload from my Ubuntu laptop after, it does erase the contents and stop the blinking but nothing follows.

When I try to upload, I only get the compiling logs:
Quote

    Sketch uses 13,368 bytes (5%) of program storage space. Maximum is 262,144 bytes.

**I could still upload sketches to another board from my Ubuntu laptop: to an Arduino micro.**

**I am connecting directly from my board to my laptop through USB 3.0**, I don't have USB2.0 plugs on my laptop, and I currently don't have any programmer device.

I tried with different versions of arduino IDE (1.6.4 1.6.5 nightly), same issue every time.
The IDE sees that my board is connected on /dev/ttyACM0

I tried to run in command line but it gets stuck as well
Quote
/home/jcharlet/.arduino15/packages/arduino/tools/bossac/1.6-arduino/bossac --port=ttyACM0

**I've been googling the world but could not find anything, could anyone help me to troubleshoot it please?**

title: Stuck on upload

Answers: 1

body:
Moved to another board more suitable to our needs, but @sm4rteverything (Twitter) gave us the following solution (not tested):

> This is a known bug of the bootloader.
>
> to fix this U need to download the one i attach in this email with the
> ATMEL-ICE tool. http://www.atmel.com/tools/atatmel-ice.aspx
>
> Copy the attched file under: <your home
> Page>\Arduino15\packages\AMEL\hardware\samd\1.0.0\bootloaders\sme
> (Linux) C:\Users\<user log
> in>\AppData\Roaming\Arduino15\packages\AMEL\hardware\samd\1.0.0\bootloaders\sme
> (Windows)
>
> last follow these three simple step Connect the ATMEL-ICE on the SWD
> J1 connector (pin 1 on top-rigth , the pin on eon cabel is the red
> one)

[![Board picture][1]][1]

> select on Arduino IDE to connect to ASME via atmel-ice (board menu)
> tool->burn bootloader

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


body:
I'm trying to write a state machine for my robot.

While the robot is moving around I would like to read the values of the sensors, but after some time the reading stops working.

For the first half hour it's ok, then I don't know what changes.

It looks like it halts when jumping from one state to another, or when the sensor value has a big jump...

I tried to move the debugOutput function inside the main loop, but the behavior is the same..

In addition to the serial halting, also the state machine itself seems to stop working good, since even if the sensor value change, the state is not updated..

Could you please help me with this?
Thanks a lot!

Here is the code:

        // motor one
        int enA = 13;
        int in1 = 12;
        int in2 = 11;
        // motor two
        int enB = 9;
        int in3 = 10;
        int in4 = 8;

        int sens1 = 0; //ingresso sensore bobina 1
        int sens2 = 1; //ingresso sensore bobina 2

        float soglia_barriera_norm = 1.5;
        float soglia_barriera_scarico = 390;

        // define the states
        #define DRIVE_FORWARD     0
        #define TURN_LEFT         1
        #define RADDRIZZA         2
        #define SCARICO           3 //Scarico cerca il filo

        int state = 3; //to start from state 3

        void setup()
        {
          // set all the motor control pins to outputs
          pinMode(enA, OUTPUT);
          pinMode(enB, OUTPUT);
          pinMode(in1, OUTPUT);
          pinMode(in2, OUTPUT);
          pinMode(in3, OUTPUT);
          pinMode(in4, OUTPUT);
          pinMode(53, OUTPUT);
          Serial.begin(9600);

        }

        //------------------------ LETTURA SENSORI ---------------------------
        //average of n readings

        float sensorReadDX(int n_medie) {
          int i, temp = 0;
          for (i = 0; i < n_medie; i++) {
            int sensorValue1 = analogRead(sens1);
            temp += sensorValue1;
          }
          float volt = (temp / n_medie);
          return volt;
        }

        float sensorReadSX(int n_medie) {
          int i, temp = 0;
          for (i = 0; i < n_medie; i++) {
            int sensorValue2 = analogRead(sens2);
            temp += sensorValue2;
          }
          float volt2 = (temp / n_medie);
          return volt2;
        }

        float differenza(float volt1, float volt2) {
          float D = volt1 - volt2;
          return D;
        }
        //----------------------------------------------------------------------

        //----------- MOTOR MOVEMENTS ---------------------------------------------

        void moto_dx_forward(int vel) {
          digitalWrite(in1, LOW);
          digitalWrite(in2, HIGH);
          analogWrite(enA, vel);
        }

        void moto_dx_backward(int vel) {
          digitalWrite(in1, HIGH);
          digitalWrite(in2, LOW);
          analogWrite(enA, vel);
        }

        void moto_sx_forward(int vel) {
          digitalWrite(in3, LOW);
          digitalWrite(in4, HIGH);
          analogWrite(enB, vel);
        }

        void moto_sx_backward(int vel) {
          digitalWrite(in3, HIGH);
          digitalWrite(in4, LOW);
          analogWrite(enB, vel);
        }

        // to stop motors
        void moto_dx_stop() {
          digitalWrite(in1, LOW);
          digitalWrite(in2, LOW);
          analogWrite(enA, 0);
        }

        void moto_sx_stop() {
          digitalWrite(in3, LOW);
          digitalWrite(in4, LOW);
          analogWrite(enB, 0);
        }

        //---------------------------------------------------------

        void debugOutput() {
          Serial.print(millis());
          Serial.print("\t");
          Serial.print(sensorReadSX(50));
          Serial.print("\t");
          Serial.print(sensorReadDX(30));
          Serial.print("\t");
          Serial.println(state);
        }

        void stateMachine() {
          float sensSX = sensorReadSX(30);
          float sensDX = sensorReadDX(30);

          if (state == DRIVE_FORWARD) {
            debugOutput();

            if (sensSX <= soglia_barriera_norm || sensDX <= soglia_barriera_norm) {
              moto_dx_forward(255);
              moto_sx_forward(255);
            } else {
              state = RIMBALZA;
            }
          }

          else if (state == SCARICO) {
            debugOutput();
            if (sensorReadSX(50) < soglia_barriera_scarico){ //|| sensorReadDX(20) < soglia_barriera_scarico) {
              moto_dx_forward(255);
              moto_sx_forward(255);
            } else {
              moto_dx_stop(); //ferma i due motori e poi raddrizza
              moto_sx_stop();
              state = RADDRIZZA;
            }
          }

          else if (state == RADDRIZZA) {
            debugOutput();
             while ( sensorReadDX(30) <= 490){
              //ruota su se stesso
              moto_sx_stop();
              moto_dx_forward(255);
            }

            moto_dx_stop();
            moto_sx_stop();
          }

        }

        void loop() {
          stateMachine();

        }

title: Serial print and sensor readings halts

Answers: 0