text:
SPI: problems communicating with sensor using Arduino
I have a sensor which I am trying to communicate with over SPI using an Arduino UNO. It is my first time using SPI and I'm experiencing some problems which I'm hoping are just due to some misunderstanding on my part. I have written a simple code to perform one basic operation: Turn on the sensor's fan. The Arduino is being powered through the 2.1 mm barrel jack by a 1.5 A DC adapter. The 5V, GND, MOSI, MISO, SS and SCK pins on the Arduino are connected to the corresponding pins on the sensor. The sensor receives power from the Arduino, drawing up to 250 mA (with the fan on).
The manufacturer provides a list of commands corresponding to each function of the sensor. To turn on the fan, the command list gives the following information:
Command_byte: 0x03
Bytes: 0x03, 0x00
Bytes_in: 0xF3, 0x03
Time_between_current_and_next_byte: 1.7ms, NA
Note: 1ms would be adequate delay between command byte and following byte

Based on my understanding of this, to turn on the fan, I need to send a command byte (0x03), then wait 1.7 ms and send another byte (0x00). My code for doing this is as follows:
#include <SPI.h>
const int chipSelectPin = 10;

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

  SPI.begin();
  pinMode(chipSelectPin, OUTPUT);
  SPI.setClockDivider(SPI_CLOCK_DIV32); //set clock to 500kHz
  SPI.setDataMode(SPI_MODE1);
  SPI.setBitOrder(MSBFIRST);
  delay(10000); // Let the sensor settle for 10 seconds

  digitalWrite(chipSelectPin, LOW);
  indata = SPI.transfer(0x03); //command byte for fan on
  Serial.println(indata);// value returned should be 0xF3
  delay(2);
  indata = SPI.transfer(0x00); //Turn on fan
  digitalWrite(chipSelectPin, HIGH);
  Serial.println(indata);// value returned should be 0x03
}

void loop() {}

When I send the command byte, the returned value (which gets printed to the terminal) is 243 which corresponds to the expected hex value of 0xF3. However, the second command does not turn on the fan and the second returned value is 231 which does not correspond to the expected hex value of 0x03.
I don't think it's a hardware issue because at least one of the returned values is correct and because the sensor does work when used with a different platform. I also experimented with different delays between bytes.

Could you post a link to the data sheet and programming instructions for the sensor?  Tha might help in finding an answer.

I actually just realised that although the sensor needs 5V power, it uses 3.3V logic whereas the Arduino uses 5V logic. I also have an Intel Galileo which can be configured to use 3.3V logic so I think I'll try that.

May or may not be related but the current draw is out of spec for the chip. From the Atmega 328p datasheet:  DC Current per I/O Pin...40.0 mA and  DC Current VCC and GND Pins...200.0mA

Thanks for the comments. After I swithched from UNO to Galileo (with the logic level set to 3.3V) it worked fine!

@JRobert - the current specification you site is for the ATmega I/O pins, but the device should be drawing power from the Arduino's regulator, not the ATmega.

Change your chipSelectPin. Pin 10 is exclusively used by SPI library. See Arduino Uno description.
Similar issue has been discussed here.

Thanks for the comment. After I swithched from UNO to Galileo (with the logic level set to 3.3V) it worked fine! I kept the chip select pin as 10 and it wasn't a problem.

Great, I am happy you have solved the issue.

You are substantially mis-stating the issue.  First, the posted code is already using pin 10 as the slave select, which is the "default" implied by the hardware.  The issues is rather than if pin 10 is being used for a different purpose and as a result is configured as an input then the ATmega SPI engine may operate in slave rather than master mode.  It is entirely appropriate to use pin 10 as the slave select.  It is also entirely possible to use a different pin, provided that pin 10 is still configured as an output.


text:
Help needed understanding Due performance
I'm going to be writing some performance critical code and have started trying to get an understanding of timers and how much "work" the Due CPU can do per second.  To help get started with this, I wrote a bare sketch that simply increments a counter whilst a timer which ticks every second dumps the value of the counter to the serial log and then resets the counter.  Here's the code I'm using:
#include <Arduino.h>

void EnableTimer7TickEverySecond();

volatile uint32_t gCounter = 0;

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

    EnableTimer7TickEverySecond();

//  while ( true )
//  {
//      ++gCounter;
//  }
}

void loop()
{
    ++gCounter;
}

void EnableTimer7TickEverySecond()
{
    pmc_set_writeprotect(false);
    pmc_enable_periph_clk(ID_TC7);
    TC_Configure(TC2, 1, TC_CMR_WAVE |
        TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1);
    TC_SetRC(TC2, 1, 656000 * 64);
    TC_Start(TC2, 1);
    TC2->TC_CHANNEL[1].TC_IER = TC_IER_CPCS;
    TC2->TC_CHANNEL[1].TC_IDR = ~TC_IER_CPCS;
    NVIC_EnableIRQ(TC7_IRQn);
}

void TC7_Handler()
{
    TC_GetStatus( TC2, 1 );

    Serial.println( (uint32_t)gCounter );

    gCounter = 0;
}

When I run this, I get values averaging 446,000 in the serial log for the increments per second.  That is way lower than I was expecting.  On an ARM chip running at 84MHz, I'd expect at least 14 million increments as few ARM instructions take more than 2 clock cycles and an increment should involve a read from memory, addition and a write back to memory (approx 6 clock cycles by my reckoning).
The timer is configured correctly, the TX led flashes regularly at 1 second intervals as the Serial.println is called.  I've checked for overflow on the counter (oddly, I found that the number of increments when working with a uint64_t was slightly higher).  I've also tried not calling Serial.begin() until I'm about to write the value to the log (and then only writing the value once) and whilst there is a slight increase in "performance", it doesn't account for the whole difference between expectation and reality.
My best guess would be that loop() is called on some sort of timer or has a built in default delay, so it occurred to me that if I comment out the counter increment in loop() and instead comment in the infinite while loop in setup(), I should be able to counteract any delay caused by how frequently the Arduino IDE calls loop().  I have seen other examples that never bother with loop() and just stick all their code in setup().
I do see a performance increase with this setup, but only to around 9 million, not the 14+ million I would expect. Oddly though, sometimes, randomly, the value is 2 or 3 times the "usual" value.  Not between 2 and 3 times, but exactly 2 or 3 times.  This happens regardless of whether I am incrementing the counter inside the loop() function or my own loop inside setup().  It is not a case of the timer "skipping", the output is written every second like clockwork.
So, my questions are:

What does the Arduino library do to make loop() so inefficient?
Is there any harm in keeping all your code inside an infinite loop in
setup() and never returning out of it?
Why would I sometimes see the number of increments being 2 or 3 times
higher than usual?  Could the counter be getting cached (despite
being marked as volatile) and not reset properly?  If so, how can I
prevent this?

What does the Arduino library do to make loop() so inefficient?

Alot.  For a start it's a function, so it has to push registers onto the stack before it runs, and pop them off afterwards.  Secondly there is the "serial event" system outside the loop.  In main.cpp in the core you can see how loop is called:
setup();

for (;;)
{
    loop();
    if (serialEventRun) serialEventRun();
}

Is there any harm in keeping all your code inside an infinite loop in setup() and never returning out of it?

If you don't use serial events, no harm whatsoever.

Why would I sometimes see the number of increments being 2 or 3 times higher than usual? Could the counter be getting cached (despite being marked as volatile) and not reset properly? If so, how can I prevent this?

My guess is the operations you are using are not atomic.  This is, the interrupt is able to be fired right in the middle of doing the series of instructions that perform the increment. The temporary registers end up not being the same as they were at the start of the operation, and consequently the value is corrupted.  You should wrap the increment in a critical section (i.e., disable interrupts before it, and enable them afterwards).
To better analyse the speed of execution you can look at the generated assembly code of your program.  If we look at the disassembled main() function for the bit where it loops you can get this:
80596:  f7ff fe05   bl  801a4 <loop>
8059a:  4b04        ldr r3, [pc, #16]   ; (805ac <main+0x30>)
8059c:  2b00        cmp r3, #0
8059e:  d0fa        beq.n   80596 <main+0x1a>
805a0:  f7ff feec   bl  8037c <_Z14serialEventRunv>
805a4:  e7f7        b.n 80596 <main+0x1a>
805a6:  bf00        nop

loop() consists of this:
801a4:  4b02        ldr r3, [pc, #8]    ; (801b0 <loop+0xc>)
801a6:  681a        ldr r2, [r3, #0]
801a8:  3201        adds    r2, #1
801aa:  601a        str r2, [r3, #0]
801ac:  4770        bx  lr
801ae:  bf00        nop

If we feed that into main() where it calls loop() the finished code looks like:
80596:  f7ff fe05   bl  801a4 <loop>
801a4:  4b02        ldr r3, [pc, #8]    ; (801b0 <loop+0xc>)
801a6:  681a        ldr r2, [r3, #0]
801a8:  3201        adds    r2, #1
801aa:  601a        str r2, [r3, #0]
801ac:  4770        bx  lr
801ae:  bf00        nop
8059a:  4b04        ldr r3, [pc, #16]   ; (805ac <main+0x30>)
8059c:  2b00        cmp r3, #0
8059e:  d0fa        beq.n   80596 <main+0x1a>
805a0:  f7ff feec   bl  8037c <_Z14serialEventRunv>
805a4:  e7f7        b.n 80596 <main+0x1a>
805a6:  bf00        nop

So that is what gets executed for every single iteration of loop().  If we (incorrectly) assume that each instruction takes 1 clock tick, that's 13 ticks.  84,000,000 / 13 = ~6.4 million loops per second.
Now - if we map the instructions against actually how many clock cycles they take, we can get a clearer picture:
bl                  1+P  (P = 1 to 3)
ldr (pc relative)   2
ldr (word)          2
adds                1
str (word)          2
bx                  1+P  (P = 1 to 3)
nop                 1
ldr (pc relative)   2
cmp                 1
beq.n               1 or 1+P (P = 1 to 3)
bl                  1+P (Only if serial event runs)
b.n                 1 or 1+P (P = 1 to 3)
nop                 1

So taking a worst case scenario where P = 3 (pipeline re-fill clock counts, that is), and no serial event running, we can calculate a total number of clock cycles of 4+2+2+1+2+4+1+2+1+4+0+4+1 = 28.
84,000,000 / 28 = 3,000,000 loops per second.
But hang on - that's still much more than you're seeing.  That's because you're still only looking at the small picture.  You're looking at just your sketch and forgetting what else there is going on.
Every millisecond the SysTick_Handler() gets called which does various tasks, including calling the TimeTick_Increment() routine to deal with millis().  That's 1,000 times per second, and that eats into your processing time somewhat.
Another important point is it can't be incrementing while you're running your interrupt.  The more you do in your interrupt (and using serial is a very heavy-weight thing to do in an interrupt) the less of your 1-second slice you get for doing your incrementing.
As an experiment, why not try disabling all the interrupts except just the one you are using for your timer and see how it changes the value.

Thanks for the extremely detailed answer. Where do you get the disassembly from? I find it interesting that it appears to be 16bit THUMB instructions rather than the 32bit ARM instructions.  I was planning to optimise a certain section of my code using ARM assembler.

Yes, it's thumb.  The compiler is called with the -mthumb option.  To get a disassembly you need to use arm-none-eabi-objdump -h -S <elf file>

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
CC3000 Blocking All Wireless Communication
I'm trying to send an email using an Arduino Uno and a Sparkfun CC3000. When I plugged in the arduino to the computer with the code I wrote for it, all wireless communication in the room I was in went down. This includes both computers that were there, my cell phone, even my Pebble Watch got disconnected. Any idea on why this happened and how to fix it? I replicated this numerous times to make sure it wasn't a fluke.
Here is my code
PingTest.ino
CC3000 Ping Test
Shawn Hymel @ SparkFun Electronics
February 1, 2014
https://github.com/sparkfun/SFE_CC3000_Library

Connects to the access point given by the SSID and password and
waits for a DHCP-assigned IP address. Pings the give website or
IP address and waits for a response.

The security mode is defined by one of the following:
WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA, WLAN_SEC_WPA2

Hardware Connections:

 Uno Pin    CC3000 Board    Function

 +5V        VCC or +5V      5V
 GND        GND             GND
 2          INT             Interrupt
 7          EN              WiFi Enable
 10         CS              SPI Chip Select
 11         MOSI            SPI MOSI
 12         MISO            SPI MISO
 13         SCK             SPI Clock

Resources:
Include SPI.h and SFE_CC3000.h

Development environment specifics:
Written in Arduino 1.0.5
Tested with Arduino UNO R3

This code is beerware; if you see me (or any other SparkFun
employee) at the local, and you've found our code helpful, please
buy us a round!

Distributed as-is; no warranty is given.
****************************************************************/

#include <SPI.h>
#include <SFE_CC3000.h>
#include <SFE_CC3000_Client.h>
#include <Client.h>
#include <Temboo.h>
#include "TembooAccount.h" // Contains Temboo account information

// Pins
#define CC3000_INT      3   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       9   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno

// Connection info data lengths
#define IP_ADDR_LEN     4   // Length of IP address in bytes

// Constants
char ap_ssid[] = "comcast";                  // SSID of network
char ap_password[] = "gooddays";          // Password of network
unsigned int ap_security = WLAN_SEC_WPA2; // Security of network
unsigned int timeout = 30000;             // Milliseconds
char remote_host[] = "www.sparkfun.com";  // Host to ping
unsigned int num_pings = 3;    // Number of times to ping

// Global Variables
SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);
SFE_CC3000_Client client = SFE_CC3000_Client(wifi);

int numRuns = 1;   // Execution count, so this doesn't run forever
int maxRuns = 10;

void setup() {

  ConnectionInfo connection_info;
  IPAddress ip_addr;
  IPAddress remote_ip;
  PingReport ping_report = {0};
  int i;

  // Initialize Serial port
  Serial.begin(115200);
  Serial.println();
  Serial.println("---------------------------");
  Serial.println("SparkFun CC3000 - Ping Test");
  Serial.println("---------------------------");

  // Initialize CC3000 (configure SPI communications)
  if ( wifi.init() ) {
    Serial.println("CC3000 initialization complete");
  } else {
    Serial.println("Something went wrong during CC3000 init!");
  }

  // Connect and wait for DHCP-assigned IP address
  Serial.print("Connecting to: ");
  Serial.println(ap_ssid);
  if(!wifi.connect(ap_ssid, ap_security, ap_password, timeout)) {
    Serial.println("Error: Could not connect to AP");
  }

  // Gather connection details and print IP address
  if ( !wifi.getConnectionInfo(connection_info) ) {
    Serial.println("Error: Could not obtain connection details");
  } else {
    Serial.println("Connected!");
    Serial.print("IP Address: ");
    for (i = 0; i < IP_ADDR_LEN; i++) {
      Serial.print(connection_info.ip_address[i]);
      if ( i < IP_ADDR_LEN - 1 ) {
        Serial.print(".");
      }
    }
    Serial.println();
  }

  // Perform a DNS lookup to get the IP address of a host
  Serial.print("Looking up IP address of: ");
  Serial.println(remote_host);
  if ( !wifi.dnsLookup(remote_host, &remote_ip) ) {
    Serial.println("Error: Could not lookup host by name");
  } else {
    Serial.print("IP address found: ");
    for (i = 0; i < IP_ADDR_LEN; i++) {
      Serial.print(remote_ip[i], DEC);
      if ( i < IP_ADDR_LEN - 1 ) {
        Serial.print(".");
      }
    }
    Serial.println();
  }

  // Ping IP address of remote host
  Serial.print("Pinging ");
  for (i = 0; i < IP_ADDR_LEN; i++) {
    Serial.print(remote_ip[i], DEC);
    if ( i < IP_ADDR_LEN - 1 ) {
      Serial.print(".");
    }
  }
  Serial.print(" ");
  Serial.print(num_pings, DEC);
  Serial.println(" times...");
  if ( !wifi.ping(remote_ip, ping_report, 3, 56, 1000) ) {
    Serial.println("Error: no ping response");
  } else {
    Serial.println("Pong!");
    Serial.println();
    Serial.print("Packets sent: ");
    Serial.println(ping_report.packets_sent);
    Serial.print("Packets received: ");
    Serial.println(ping_report.packets_received);
    Serial.print("Min round time (ms): ");
    Serial.println(ping_report.min_round_time);
    Serial.print("Max round time (ms): ");
    Serial.println(ping_report.max_round_time);
    Serial.print("Avg round time (ms): ");
    Serial.println(ping_report.avg_round_time);
    Serial.println();
  }

  // Disconnect
  if ( wifi.disconnect() ) {
    Serial.println("Disconnected");
  } else {
    Serial.println("Error: Could not disconnect from network");
  }

  // Done!
  Serial.println("Finished ping test");

}
    TembooChoreo SendEmailChoreo(client);
void loop() {
  if (numRuns <= maxRuns) {
    Serial.println("Running SendEmail - Run #" + String(numRuns++));

    //TembooChoreo SendEmailChoreo(client);

    // Invoke the Temboo client
    SendEmailChoreo.begin();

    // Set Temboo account credentials
    SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT);
    SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
    SendEmailChoreo.setAppKey(TEMBOO_APP_KEY);

    // Set profile to use for execution
    SendEmailChoreo.setProfile("Testofsoftware");

    // Identify the Choreo to run
    SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail");

    // Run the Choreo; when results are available, print them to serial
    SendEmailChoreo.run();

    while(SendEmailChoreo.available()) {
      char c = SendEmailChoreo.read();
      Serial.print(c);
    }
    SendEmailChoreo.close();
  }

  Serial.println("\nWaiting...\n");
  delay(30000); // wait 30 seconds between SendEmail calls
}

It could be that your code is making it respond to all ARP WHOHAS requests with a big "ME!!!!" regardless.  Impossible to say without seeing your code though.

@Majenko, ok, I'll post my code

Could you include in your answer the output you get in the serial monitor?

It would definitely be useful to see the  serial printouts. I'm a little curious at how this works, I've used the Adafruit_CC3000 which works in a very similar way, although I've never tried to send emails from it before. Is it just me or are you connecting and disconnecting from the wifi in your setup(), and then trying to send an email from the loop()? Does this work? I would have thought not...

I'll try to get a readout later but basically, sometimes the cc3000 will run a ping test, sometimes it won't connect. It can't do anything with consistency.

Does getConnectionInfo always work? Same to the dnsLookup? (output results!) This:  IPAddress ip_addr; also looks like a pointless variable as you get connection_info.ip_address later on. I notice the code is the standard example & this is exactly the same, apart from the email/loop part. Have you tried running it just with the setup code? (i.e. just have a delay in the loop)

Because of the limited information given any answers given will be by nature limited. However, I can suggest several troubleshooting tips.

Tips

Verify that username and password used are exactly right(punctuation, spaces, etc.). Where you putcomcast you should put the name of the network not the name of the provider. I am not sure if you have done this or not.
Make sure network is in fact WPA2.
In order to debug the issue make sure if you are getting nothing through serial to set it to the baud rate of 115200.
If you are using the breakout board make sure you correctly wired it and check any solder points:

Make sure you have the correct libraries installed.  Also, try sample code from the examples. Libraries can be found here.

Many of these seem obvious but can through someone off. So try these and let me know the results. A lot of information about setup can be found here.
EDIT Try removing the
if ( wifi.disconnect() ) {
    Serial.println("Disconnected");
  } else {
    Serial.println("Error: Could not disconnect from network");
  }

block. It appears that you are disconnecting before going into the main loop. This would obviously make it impossible to send an email. The reason pining would work sometimes would be that wifi.disconnect() is called sometimes but not all the time. To narrow the issue try an example code from the library.

all of that was checked and double checked. It's all correct

See EDIT above. I really need more info about you setup to properly answer your question.

not a direct answer but the sparkfun hookup guide connects pin 8 (SDCS) to the chip select for the SD card. If this line is floating, I'm not sure of the impact.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Calculate how much battery power left
I run my 12V car battery trough a trimpot into my pro micro, micro controller.
I am using (voltPinValue1 * 0.01465) to get the Volt out of analog in. I have trimmed the pots and getting the right V.
But now I want to calculate for how long I can run for, example the stereo and some LED:s, but don't know how.. Does anybody know how I can do this??
Sorry for my English
Thanks! //Rasmus

This would be easier if there was no engine involved. Throwing the engine in makes this very, very difficult to solve.

Is is a camper van that has an extra battery. So the sweet part is that the remains of the battery  can be calculated when the motor is not running. And its also then its the most important to know for how long I can run my stereo =)

Take a look at http://electronics.stackexchange.com/questions/110104/calculating-battery-percentage-using-an-arduino. You can measure battery percentage

Thx @PhillyNJ!!

You really need to know the current being drawn rather than the instantaneous voltage. A voltage drop profile of a battery changes depending on the current draw, and just using the voltage is very very hard indeed.
You could measure the voltage over time, and try and calculate the slope of the voltage and attempt to predict when it would reach a specific pre-determined cut-off point, but since that change in voltage will be non-linear it's not really something that can easily be calculated.
But, if you can measure the current instead, and you know the Ah of the battery, then you can get a better estimate of how long the battery will run until it's considered flat.

I think can get the current out of it using another calculation! But the thing is that its a camper van that has an extra battery. So the sweet part is that the remains it will be calculated when the motor is not running.


text:
Stack isn't popping off correct data?
So, I was working on a project where I needed to get a random object from a stack, so to make sure my design was correct, I made a dummy program that does nothing but fill a stack with data, then print it out.

why in the world is nothing coming out of the stack but -1s??
Here's the stack.h file.
http://pastebin.com/vjhNLpNu

Please do not put links to your code or worse, take screenshots of your code; the former makes your question NOT self-contained, the latter makes it extremely difficult to people who would be willing to help to actually try to, as they would have to retype everything from the screenshot!

That's very true, I really should have just put it in tags. Very lazy of me, I apologize and will try to remember that for next time.

You're not telling it how big your stack should be, and it defaults to 0 entries, which means nothing gets stored.
class Stack
{
private:
    int *p;
    int top,length;

public:
    Stack(int = 0);  <<== CONSTRUCTOR - DEFAULT SIZE IS 0
    ~Stack();

    void push(int);
    int pop();
    void display();
};

When you make your Stack object you must give it a size for the number of entries in the stack:
Stack stack(4);

You never allocate space for the stack.
The way it's written, you need to pass the stack size into the constructor, and then it's fixed for the lifetime of the object; i.e. it won't grow automatically when you call push(). You're not passing anything into the Stack constructor, so the parameter is defaulting to 0, meaning it has zero size.
The solution is to declare the stack something like this:
Stack stack(10);

(10 is just an arbitrary size -- use whatever you expect to need.)
Incidentally, there isn't an effective safeguard in your code to handle an empty stack. The result is that you're technically getting undefined behaviour at the moment when you call push() (it's writing to arbitrary memory locations).


text:
How to power on Arduino a few seconds later after GSM module initialization?
I've connected a SIM900A GSM module to Arduino and the circuit works standalone on a 12V power supply. The problem is when I provide the 12V power supply, both GSM module and Arduino starts but the Arduino don't initializes the program for GSM module and hence the send or receive message functions don't work. Also when I first power on the GSM module and let it initialize first and then power on the Arduino, everything works fine. How to deal with this problem?

It sounds like your problem is that the GSM module needs time to initialize before it is ready to be talked to by the Arduino.
A crude way of providing this would be to use the delay() function in the Setup() of your sketch.  The argument to that is an unsigned long number of milliseconds (thousandths of a second) so it can produce delays far longer than you need.
But a more sophisticated solution would be to repeatedly try to talk to the module and check for an expected response.  Apparently, with at least some of these, if you disable baud rate detection they will announce themselves with a prompt when they are ready - you could wait for that.  But I think repeatedly trying until you get a response is going to be the most robust.

Yes! Got that after posting this status. The delay I had mentioned earlier was less than the delay required to initialise the GSM.
How to disable baud rate and how will they themselves prompt when they will be ready? I've different modules too connected with the same circuit. I cannot disable it.

Let the 12 V charge a large capacitor over a resistor. The time to charge to 63% is RxC. Place a 5 V zener diode parallel to the capacitor, so that doesn't damage the microcontroller. Then either connect to the microcontroller's reset, or, and this is "nicer", use a MAX809 reset controller. The latter will keep the output low until a precise threshold is reached, there's for instance a 4.00 V version. Use that output to keep the microcontroller reset for some time.
Not sure how much delay you want, but a 10 uF capacitor and a 100k resistor will give you (from the top of my head) about half a second before the voltage on the capacitor reaches 4 V.

Why not just do the delay in software??

@Chris: Oh dear... Er, because that was too obvious? Well, in my defense, OP looked like a Real Problem at first sight. :-)


text:
Can I use Serial.println() in a class?
I'm trying to convert a class header file from another c++ project to arduino, which in my mind involves replacing cout with Serial.println.
When I try to recomplile with all of these changes, I get this error from the compiler:
error: 'Serial' was not declared in this scope
     Serial.print(p[i]);

Can someone explain this to me?

You have to #include <Arduino.h>, or compile with the -include Arduino.h flag. The Arduino IDE normally does that for you, but you have to do it yourself if you are working outside the IDE.
There are a couple of Arduino Makefiles floating around the Web which, just like the IDE, take care of this for you.

I'm actually using the Arduino IDE. :\

Are you compiling a .ino or a .cpp? If it's a .cpp, the IDE is probably not adding the #include. If it's a .ino, it may just have messed your code. In the IDE options, you can ask to see all the compile-time messages. This will show the g++ command-line and tell you if it's compiling your original source or a modified version. You will also see the paths of the temporary cpp files it's creating, check their contents, and see if it has broken something.


text:
Is supplying 5V from both external 5V and USB harmful?
I have an arduino nano which is powered through unregulated 5V (pin 27). For debugging purpose, I'd like to connect the USB port to my computer in order to use the Serial.Print function. The external 5V will stay connected. Will this cause damage ?
edit : I forgot to mention that the external power supplied to pin 27 is regulated with a switching DC-DC converter (measured 5.1V). Sorry it was not clear in my question.
Here is my circuit :

The switching regulator is not exactly the one in the schema.
Is using the circuit with the battery power supply + usb connection to my computer will damage something ?

No, it probably won't damage anything, as the PC's USB port is protected from overvoltage by the D1 schottky device on your arduino board.
Update, my previous answer contained the following paragraph, which is not related to your problem

But you should take care of some things.

Make sure, the voltage applied to your +5V-Net is regulated properly elsewhere. I.e. choose a laboratory PSU or another good
  source.
Avoid having both your PC and your 5V-supply connected to line voltage. Ground levels may differ due to Y-capacitors present in the
  switching PSUs. Those provide a AC voltage of half your line voltage
  to DC ground (only with 0.3 to 0.7 mA, but enough to cause
  disturbances on your signals at 55 volts in the US or 115 V in the EU)
If you have to use two switching PSU for both PC and arduino, provide an equipotential bonding between your PC's mass (e.g.
  VGA-port-screw) to your arduino's PSU's ground directly, to prevent
  leakage currents from the Y-capacitors wandering around in your
  circuitry.

Update according to your enhanced question
You are using a battery powered DC-DC supply for your Arduino. So, my previous notes do not apply to your problem.

5.1 V seem exact enough to drive your arduino safely. No need for additional stabilisation measures
D1 (see genuine arduino schematic) separates USB-Power from +5V and prevents current flowing in reverse direction over your USB connection.
Arduino circuitry and USB port have common GND so there are always well defined voltage levels.

In my opinion, there's nothing with your setup, which may harm your circuitry or your PC.
Depending on the maximum power of your DC-DC converter you may consider adding a fuse to protect converter and components in case of short circuit.

Since the external 5V supply is not regulated, it may cause some problems. It is possible that a small voltage difference will appear if and when the external voltage fluctuates from the 5V level. What you should do is short-circuit the 5V of the USB to pin 27.
And in general, add a 5V regulator circuit to feed the Arduino nano, like this one:

I don't think, shorting VUSB to +5V is a good idea. By this, you bypass D1. Hence, if +5V is slightly higher than VUSB, you may overload the regulators of your PC's USB port. The other thing is: @Masure did not write, the voltage supplied was unregulated. Hence, applying a linear regulator to an already regulated 5V will let the voltage drop below 4V, which is pretty useless, because all power will be drawn from USB then via D1.

@Masure wrote "...which is powered through unregulated 5V (pin 27)". That's why I suggested that

Yes, but Masure probably wanted to express, that by supplying the voltage via this pin, the builtin 7805 is bypassed. Otherwise Masure just had to connect the unregulated voltage to Vin. No need to apply another regulator.

Sorry guys, I edited my question because it was not clear. I'm powering the nano through pin 27 (which I call "unregulated 5v") with a regulated 5v source.


text:
I2C with an arduino, a PI and an IO expander
im working on a project which requires alo i/o pins. For that reason i bought a pcf8574P 8bit I/O expander which uses the I2C protocol. The problem is how to combine the Rasp PI and the arduino.
For example:
I want the Rasp to send data to the Arduino. Currently i'm using serial but i wanted to switch over to I2C because it better, simpler, and faster however how can i use 2 I2C when the Atmega 328P supports only 1 I2C bus?
The plan goes like this:
The PI is master of the arduino and it sends the data. Arduino is the slave
Arduino is master of the IO expander and the expander is slave
Possible solutions:

Use the Serial protocol to send the data and use the I2C for the expander
Make the arduino master of the PI and the expander which i'm not sure if its possible

http://playground.arduino.cc/Main/SoftwareI2CLibrary

You can have multiple masters on one I2C bus (http://electronics.stackexchange.com/questions/115577/how-does-multimaster-i2c-work-and-its-significance)


text:
How does coordinator XBee receive data from router?
I have two XBees S2, one is configured as an API coordinator connected to Arduino and the other as an AT router.
The coordinator sends a frame to the router to switch on a LED. I want to switch off that LED with a button and the router send a message to the coordinator to tell him that it switch off the LED.
How can I do this?
I have one Arduino with the coordinator. I'm asking what I have to put in the script to make the coordinator receive the data.
Here is my code, how the coordinator sends the data to the router:
String inputString;
int led = 13;
void setup() {
pinMode(led, OUTPUT);
Seria.begin(9600);
}
void loop() {
while (Serial.available() ) {
// get the new byte:
delay(3);
char inChar = Serial.read();
// add it to the inputString:
inputString += inChar;
}
if (inputString.length() >0) {
Serial.println(inputString);
if (inputString == "on"){
digitalWrite(led,HIGH);
setRemoteState(5);

}
inputString="";
}
}

void setRemoteState(char value){
Serial.write(0x7E); // start byte
Serial.write((byte)0x0);
Serial.write(0x10);
Serial.write(0x17);
Serial.write((byte)0x0);
// id of recipient or use 0xFFFF for broadcast
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write(0xFF);
Serial.write(0xFF);
// 16 bit of reciepent
Serial.write(0xFF);
Serial.write(0xFE);

Serial.write(0x02);

  Serial.write('D');
  Serial.write('2');

 Serial.write(value);

long sum = 0x17 + 0xFF + 0xFF + 0xFF + 0xFE + 0x02 + 'D' + '2' + value;
Serial.write(0xFF - ( sum & 0xFF) );
Serial.print(sum,HEX);
}

When you have one working as AT mode, it puts out whatever comes in, it is also called transparent mode.
You should first define which mode you want to use them and start coding.
If you choose AT, load the firmware for both and use Arduino to check the commands and execute tasks (supposing it is connected to the router).
If the task was done correctly, you send an okay message, otherwise, send error. This is a simple task in AT mode, just use Serial:
if (led == 1)
   Serial.println("ok");
else
   Serial.println("error");

If you choose API mode, it is a little bit different, where you have to mount the packet for sending data and put a message inside it. There are some libs out there you can achieve this.
On the other side, the coordinator will receive the message and interpret it.
If it is in AT mode, just read the serial. In API, you have to decode the packet and check the payload field where the data is located.

To change the state of digital pin 2,D2 set the "value" to 0x05 to switch it HIGH and set the "value" to 0x04 to switch the pin LOW

This is not a very good answer, it is not clear what you are talking about.  You need to consider what you are trying to explain and then read it back from the perspective of someone who does not have the knowledge you have.  I'd suggest reading some other peoples answers and get tips on how to explain what you mean before you answer anymore questions.  I have no doubt you understand what you are talking about, its just that it doesn't come across very well.


text:
Simulate a FTDI using an Arduino UNO
I'm looking to directly program an ESP8266 WiFi Module with out using a FTDI (USB-Serial interface) as suggested in this excelent tutorial. The real purpose is to have access to the GPIO ports of the module.
I heard (from this page) that one can use an Arduino UNO as an intermediate interface for burning the bootloader onto an AVR (e.g. ATmega168 or ATmega328). That is, using the ArduinoISP code example in the IDE.
Is it possible to use an Arduino UNO as temporal bridge to program the ESP8266? Can anyone please suggest some tutorial? Thanks

I can't comment on the other answers, but I wonder if the 16U2 output are safe for the ESP, i.e. 3.3V levels?

The simplest way is to unplug the ATMega328P from the board (or otherwise disable it) and just use the ATMega16U2 by connecting the ESP8266 to pins 0 and 1 of the Uno.  No programming required at all then - the ESP8266 just takes the place of the ATMega328P.
If you really want to "pass it through" the ATMega328P then you will need to make a transparent pipe for the serial data.  That would involve nominating two more pins on the Uno to be a new serial connection, and using SoftwareSerial to interface with those pins.  Then you have a simple loop which reads from one port and writes to the other, and the same in reverse of course.  Make sure you have the baud rates right.  I don't know how well SoftwareSerial would perform at the (commonly) 115200 baud the ESP8266 works at.
EDIT: (Interfacing to a 3.3-V system)
Since the ESP8266 works at 3.3V, while the ATMEGA16U2 is powered at 5V, you might need to adapt the level of the ATMEGA16U2's TXD line (which is connected to the "RX" input line of the ATMEGA328P/Arduino Uno Board), to 3.3V.
To do this, connect a  1.5 kOhm resistor between the RX pin and ground. In fact, the connection between ATMEGA16U2 and ATMEGA328P is done using an 1kOhm series resistor. This, together with the 1.5k Ohm resistor, will create a resistor divider, which converts the 5V output to 3V.
See schematics below.


text:
Can't burn arduino bootloader to atmega8a with usbasp
I want to burn the arduino bootloader with arduino IDE, but I cant get it done. And here  is my circuit:
I have marked the way I connect the ISP port and the chip.

I choose Arduino NG/older as the board and Atmega8 as the processor, but when I start to burn the bootloader to the chip the LED on the usbasp just blink once and an error was given:
Arduino:1.6.5 Hourly Build 2015/05/15 06:16 (Windows 7), 板："Arduino NG or older, ATmega8"

avrdude: warning: cannot set sck period. please check for usbasp firmware update.

avrdude: error: programm enable: target doesn't answer. 1

烧录引导程序出错。

avrdude: initialization failed, rc=-1

         Double check connections and try again, or use -F to override

         this check.

What should go wrong? I have check the connection many times and replace a chip as well, and I even add a 12M crystal(with 22pF caps) but things still keep the same.
EDIT
I do the flowing things as advise:

short the jp3 jumper of the usbasp to make a slow commiuncation. And remove the crystal.
I just found the way I connect the isp port might be wrong. so I changed it as flowing

And my actually circuit is like this:

But got no luck, things still the same :-(

Did you set the SLOW SCK jumper on the USBasp Programmer? Completely new ATMegas use the internal RC-Oscillator at a frequency of 8MHz, but the divide clock by 8 fuse is set too. That means that (before burning the fuses) the AVR is running at a clock frequency of 1MHz and the standard SCK clockrate of the USBasp is too high for this clock frequency. Therefore, you need to set the SLOW SCK jumper to get a lower SCK clockrate.

Thanks for advice, is the the one marked as jp3 on the usbasp board? I just shorted it and tried again, things still got no luck, I have detailed in my edit, please check

@armnotstrong The connection in your edit seams correct to me, but as I read you have removed the external crystal. Once the burning process sets the fuses (at the beginning) you need to have an external clock source (so a crystal). As far as I know there should be no problem when using a 12MHz crystal instead of an 16MHz one.

@armnotstrong One additional note: According to the original schematic of the USBasp (http://www.fischl.de/usbasp/) JP1 is the SLOW SCK jumper, not JP3. JP3 is the VCC jumper for target supply, which you will need too, when using the above circuit.

Thanks Simon, so what should do is a) add the crystal back. b) short the JP1 instead of JP3, right? Weird thing is JP1 seemed to be a double switch on my board, according to the mark on the side, it's a switch of the voltage(3.3v/5v)

@armnotstrong Well, it seems that you do not have the original USBasp board (see link above). If so, we would need the exact schematic of your USBasp board. Otherwise if you have the original board then you will have to do the following things: a) short JP1 (slow sck) and JP3 (supply the target ATMega with 5V)  b) add the crystal  c) burn the bootloader

What you could do to determine whether the target is supplied by setting JP3 or not is measuring the voltage between the VCC pin on the target-side of the cable and GND.

And one additional hint: Before you try to burn the bootloader you could open a command prompt on your computer and type
avrdude -c usbasp -p atmega8. Basically this is the command for doing something with the chip, but since no action is specified the programmer simply checks if the target is ready

Hi, Simon I find the user guide of the usbasp device I am using here

It seems that this USBasp board has a slightly different layout than the one I am using. For justification: JP1 (on your board) must be set to 5V to supply the target with VCC. JP3 must be set to enable a slower SCK clock rate for new AVR chips. Further, the circuit in your question shows that you've 4 GND pins. According to the manual there are only 2 GND pins, so you've shortened the RX and TX pins (although they may not be used at all). Probably its best to start from scratch, rewiring everything again and then check if the target is ready by typing the command mentioned above.

As an additional note: You will probably know that StackExchange uses votes to mark good or helpful answers. A little bit of reputation would be nice for me, so if you think my answer helped you, please vote it up or mark it as the correct answer (which cannot really be done at the moment since your problem isn't solved yet).

Thanks for the effort, I will try that, thanks a lot, really appreciate.

@armnotstrong You're welcome

You forgot the Pull Up resistor for Reset.
Using 12Mhz crystal is not a good idea because the Atmega8 config probably uses 8Mhz or 16Mhz, and the fuses which are burned during the bootloader process (yes, they burn fuses first, and THEN load the bootloader) will not expect there to be a 12Mhz crystal, so any further communication can fail because of this too.

USBasp actively drives the reset line, and ISP doesn't require the bootloader to run.

Thanks for advice, I just make a resistor value of 10k on the #1 pin as a pull up from VCC, tried again, got no luck :-(


text:
arduino weather shield and wind speed
I have Arduino Mega and Weather Shield. I want to calculate wind speed.
float get_wind_speed()
{

float deltaTime = millis() - lastWindCheck; //750ms

deltaTime /= 1000.0;

  float windSpeed = (float)windClicks / deltaTime; //3 / 0.750s = 4

  windClicks = 0; //Sıfırla ve yeni oluşan rüzgarı izle
  lastWindCheck = millis();

  windSpeed *= 1.492; //4 * 1.492 = 5.968MPH

 Serial.println();
 Serial.print("Windspeed :");
 Serial.println(windSpeed);

 return(windSpeed);
}

But when I run my code I see two windspeed value. First one is windspeed=0.0 or any value. Second one is windspeed=nan.
How can I make it better?

When debugging a problem like this one, print out values of the variables that the calculation depends on.
In this case, you may find that both windClicks and deltaTime are 0 or 0.0.  The IEEE 754 floating-point-operations specification dictates a result of NaN (not-a-number) for various zero over zero calculations.  It dictates a result of +Inf or -Inf for calculations like 7/0.0 or -13/0.0.  [See, for example, the stackoverflow question, Why does division by zero with floating point (or double precision) numbers not throw an exception.]
If arithmetic generates a NaN or +Inf result, subsequent arithmetic using that result will also produce NaN or +Inf results.
To deal with the problem, you could use deltaTime > 0 as a required pre-condition for calculation of windSpeed.  That is, have an if-statement protecting the calculation block.


text:
How do I even out Infared distance sensor readings?
I am using a standard infared distance sensor on a small robot and i am trying to even out the readings on it so it is more accurate. The readings are very sporadic and often take huge jumps in the distance. Is there a method of programming or circuit design that might make this easier to use? I'm trying to keep my robot from running into things.

Can you please include which sensor(s) you are including and your current circuit/code? Thanks!

Thanks for the quick reply. The sensor is the Infrared Proximity Sensor - Sharp GP2Y0A21YK I believe.

Wikipedia has a page on moving averages: http://en.wikipedia.org/wiki/Moving_average
I'd suggest at first try an exponential moving average:

average = a * sample + (1 - a) * average

Experiment with different values of a (with 0 < a <= 1).
The smaller a is, the smoother the curve, but also the longer (more iterations) it takes for an actual change in the input to be reflected in average.

IR sensors are very erratic in my experience. The best way is to take an average of multiple sensor readings. The number of readings required can be found by experimentation.
Example Sketch (Source)
The example below should be similar, and a good start for your model of IR sensor.
/*
 Sharp GP2Y0A21YK0F infrared proximity sensor (#28995)
 Collects an average of five readings from the sensor and displays the
 resulting value about every half second.

 See the SharpGP2Y0A21_Simple demonstration for additional usage notes,
 including connection diagram.

 This example code is for the Arduino Uno and direct compatible boards, using the
 Arduino 1.0 or later IDE software. It has not been tested, nor designed for, other
 Arduino boards, including the Arduino Due.

*/

const int irSense = A0;          // Connect sensor to analog pin A0
int distance = 0;

void setup() {
  Serial.begin(9600);            // Use Serial Monitor window
}

void loop() {
  Serial.println(irRead(), DEC); // Call irRead function to read sensor
                                 // Print value in Serial Monitor
  delay(250);                    // Wait another 1/4 second for the next read
                                 // (Note: Because of delays built into the
                                 //   irRead function the display of values will
                                 //   be slower than in the SharpGP2Y0A21_Simple
                                 //   sketch
}

// Take multiple readings, and average them out to reduce false readings
int irRead() {
  int averaging = 0;             //  Holds value to average readings

  // Get a sampling of 5 readings from sensor
  for (int i=0; i<5; i++) {
    distance = analogRead(irSense);
    averaging = averaging + distance;
    delay(55);      // Wait 55 ms between each read
                    // According to datasheet time between each read
                    //  is -38ms +/- 10ms. Waiting 55 ms assures each
                    //  read is from a different sample
  }
  distance = averaging / 5;      // Average out readings
  return(distance);              // Return value
}

Averaging is a very good technique for improving noisy data, provided
you have a “nice” noise. “Nice” meaning that you never get “atypical”
data points, i.e. the error of any given data point is of the order of
the “typical” error amplitude. If you have for instance
additive white Gaussian
noise, then
it can be shown that averaging is in some way the “best” way to clean
your data.
However, if you have big sporadic errors, then averaging is not a good
solution. This is because you will have to average a lot of samples
in order to smoothen out a single big error... and the more samples you
average, the more chances you have to get another huge error that will
ruin your average. Of course, averaging will somewhat improve things,
and it is better than no smoothing at all, but there are better options.
The solutions to this problem lye in the realm of robust
statistics. It may look
like hairy math, but there is actually a very simple smoothing filter
that is far more robust than the average: it's called the
median. The idea is quite simple:
you sort your list of samples from smallest to largest, then you pick
the one sample that ends right in the middle of the sorted list. Unlike
the average, this filter is completely insensitive to samples carrying
huge errors, as long as the majority of samples are reasonable.
Here is an implementation of a simple moving-median filter based on the
standard libc’s qsort(). It assumes samples have int type, but you
can change it to whatever numeric type you want. You can also change the
filter length: longer lengths provide more robustness against series of
consecutive bad samples, at the cost of more filter delay, more memory,
and more processing time.
/*
 * Comparison function for qsort(): return an integer "less than, equal
 * to, or greater than zero if the first argument is considered to be
 * respectively less than, equal to, or greater than the second."
 */
int compare(const void *pa, const void *pb) {
    int a = *(int *)pa;
    int b = *(int *)pb;
    return a<b ? -1 : a>b ? +1 : 0;
}

#define FILTER_LENGTH 11  // length of the median filter, should be odd

/*
 * Input: raw sample.
 * Ouput: filtered sample.
 */
int median_filter(int data) {
    static int input_buffer[FILTER_LENGTH];
    static int input_index;
    int sorted_buffer[FILTER_LENGTH];

    // Store the current data point.
    input_buffer[input_index] = data;
    if (++input_index >= FILTER_LENGTH) input_index = 0;

    // Sort a copy of the input buffer.
    for (int i = 0; i < FILTER_LENGTH; i++)
        sorted_buffer[i] = input_buffer[i];
    qsort(sorted_buffer, FILTER_LENGTH, sizeof *sorted_buffer, compare);

    // Return median.
    return sorted_buffer[FILTER_LENGTH/2];
}

As I did not explicitly initialize the filter memory, this will output
zeros the few first times it is called. I encourage you to try this
filter and compare against an exponential moving average, and only then
decide which works best for you.

The Sharp GP... infra red proximity sensors can produce noisy output sometimes.  This is partly caused by the fact that they work by repeating a brief, powerful IR pulse.
So - the very first tweak I would suggest when using any of these sensors is to try a cheap 10 micro Farad electrolytic capacitor on the 5V power connections, reasonably close to the sensor itself.  This is mentioned on some of their datasheets, but gets forgotten...

My solution keeps reading for cycles (10 times) and calculate average it.
Be careful voltage output of many surface NOT same.


text:
Can the Arduino Eclipse plugin v2.2 be used with Arduino 1.5.8?
It keeps giving me this warning:

You are using a version of the Arduino IDE that is newer than available at the release of this plugin.`

Does this means I need to use a night build?

V2.2 is pretty old by now.
As far as I recall it should work fine.
V2.2 of the Arduino eclipse plugin should work fine with the Arduino IDE version 1.5.8.
What that phrase wants to say is: the plugin V2.2 was released before Arduino IDE 1.5.8 was released; as such the code can not make a statement on the compatibility.
But again V2.2 is old. We hope to release V3.0 end of February 2016

Doesn't the warning just mean that Eclipse might be old, not the Arduino IDE? Getting a nightly build of the IDE would make things worse, wouldn't it?

Hi Nick.
IMHO The writer is referring to using the nightly of the arduino eclipse plugin (which is currently at V3) and not the "hourly" of the arduino IDE.
Note that the stable release of the arduino plugin is 2.4.

To clarify your answer it should work fine - do you mean the nightly build, or that V2.2 should work fine?

V2.2 of the arduino eclipse plugin should work fine with the arduino IDE version 1.5.8. As the statement says: the plugin V2.2 was released before arduino IDE 1.5.8 was released as such I could not make a statement on the compatibilty. But again V2.2 is old. We hope to release V3.0 this week

@jantje Could you please include more details to your answer, it's fairly short right now.


text:
Is it safe to feed 5v dc 1amp to an Arduino uno R3 board?
Is it safe to feed 5v dc 1amp to an Arduino uno board?

Yes, it is safe.

That's a common newbie question: "What will happen when I use a 1 A power supply for a device which only needs 0.1 A?"
The device will only draw the current it needs. It's the same as on your electricity grid. The nuclear power plant can supply a gigawatt, yet the bulb will only draw the 60 W it needs.
But do you want to apply that 5 V to the power connector? Then the 5 V is too low, you'll need at least something like 6.5 V, otherwise the onboard voltage regulator won't have enough headroom to output 5 V. If you're using the USB connector for a regulated(!) 5 V, then the onboard regulator will be bypassed. Never place an unregulated 5 V on the USB connector, though.

Yes as long as the polarity is correct, the board will only take the current it requires

The 1 Ampère you're mentioning is likely the maximum rating of the power supply, i.e. it cannot sustain higher currents for a long time. However, if you connect your Arduino board (or any other device) to your power supply, the actually flowing current will depend on the voltage U and the resistance R of the device as I = U/R. You can think of this as the Arduino drawing as much power as it needs.
In other words: you must not exceed the maximum voltage, but you don't have to (and cannot in a simple way) adjust the current flowing into the Arduino.


text:
Can anyone explain how hex codes 0x1A is used for sending ctrl+z & 0x0D for Carriage Return & 0x0A for LineFeed?
Please explain in detail. How the Hexadecimal code has been assigned?
Edit: This is the code:
#include <Wire.h>
void setup()
{
   Wire.begin();
   Serial.begin(9600);
   delay(1000);
   Serial.println("AT+CMGF=1"); //set to SMS mode
   delay(1000);
   Serial.println("AT+CMGS=\"+918460588440\""); //set the phone number (wrapped in double quotes)
   delay(1000);
   Serial.println("hello world. this is arduino");
   delay(1000);
   Serial.write(0x1A); // sends ctrl+z end of message
   delay(1000);
   Serial.write(0x0D); // Carriage Return in Hex
   delay(1000);
   Serial.write(0x0A);
}
void loop() {}

Please don't ask the same question twice.

They are all to do with where in the alphabet they are.  There are 26 letters in the English alphabet, and Z is the 26th.  The 26 in hexadecimal is 0x1A.
A carriage return is a CTRL-M, and a line feed is a CTRL-J.  M is the 13th letter of the alphabet, and 13 in hexadecimal is 0x0D.  J is the 10th letter - 10 is 0x0A in hexadecimal.
Why are they CTRL-M and CTRL-J?  Well, that all stems from the old teletype interfaces used on the very early computers.  That's what they used, and that's what's stuck, and finally made it into the ASCII standard.

Why are these lines added at the end of arduino code?

Because they are.  Whatever "the code" is, it obviously requires them.  Without knowing what "the code" is I can't comment any further.

this is the code

        #include

    void setup()
    {
      Wire.begin();
    Serial.begin(9600);
    delay(1000);
    Serial.println("AT+CMGF=1"); //set to SMS mode
   delay(1000);
    Serial.println("AT+CMGS=\"+918460588440\""); //set the phone number (wrapped in double quotes)
    delay(1000);
    Serial.println("hello world. this is arduino");
    delay(1000);
    Serial.write(0x1A);  // sends ctrl+z end of message       delay(1000);
    Serial.write(0x0D);  // Carriage Return in Hex delay(1000);
    Serial.write(0x0A);
    }
    void loop()
    {}
No, that is a huge mess of text that I can't decypher.  My guess is that whatever you are talking to requires those characters as part of its protocol.

These hex values are the numbers in the ASCII table, https://en.wikipedia.org/wiki/ASCII.
Characters corresponding to values below 32 are control characters, reserved for special purposes. For the values you mention in the question:

0x0d = 1*16 + d*1 = 13 = CR (carriage return)
0x0a = 0*16 + a*1 = 10 = LF (line feed)
0x1a = 1*16 + a*1 = 26 = SUB

("control+Z" is not the ASCII control character, but how you would generate this control character (SUB) on a keyboard.)
A table with both hexadecimal and decimal numbers is also given in the Wikipedia article.

if the value is in 0d, then why add '0x' to it?

0x is a prefix that indicates that the literal is a hexadecimal value: https://en.wikipedia.org/wiki/Integer_literal

(I've formatted your code and edited it into your question).
This code is apparently driving a device - GPRS shield? - to send an SMS. No doubt the code was written to meet the requirements of the device. Note that the CR and LF literals could have been written as '\r' and '\n', respectively. The author chose to write them in hex, probably because there is no "\" code defined for Ctrl-Z, and so wrote all three in a consistent style.


text:
How to fade in and fade out led strip connected to arduino based on continous analog input from capacitative sensor?
So I've been trying to get a capacitive sensor made from aluminum foil to work. And I have had success the kind of proximity and readings I need to light up a single LED and produce basic tone. Using this very basic code :
{
  Serial.println(value1);//value that i get from analog sensor
  //this is just to get the values in order for the led and sound
  if (value1<=8) value1=-100;
  analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
  tone(tonepin,value1+100,100);
  delay(10);

All this works perfectly for me, the delay isn't perceivable, the response is for all practical purposes simultaneous to input. Except it's not beautiful, because the LED keeps flickering when values reduce or increase because the jumps are sudden I suppose.
SO I thought I'll try to fade in and fade out to different values from present values.  Used the fading examples. Here:
Serial.println(value1);
  if (value1<=8) value1=-100;

  if (value1+100<=value2+100) {
    for(int fadeValue = value2+100 ; fadeValue <= value1+100; fadeValue +=5) {

    analogWrite(ledPin, fadeValue);

    delay(10);
    }
  }

  else
  {

    for(int fadeValue = value2+100 ; fadeValue >= value1+100; fadeValue -=5)
    {
        analogWrite(ledPin, fadeValue);

    delay(10);
    }
  }
  //analogWrite(ledPin,value1+100);
  tone(tonepin,value1+100,100);
  delay(10);
  value2=value1;

But this takes away the responsiveness, the whole thing is so slow to react, the sound and the light are obviously not in sync as I read my code. But also the light is not really fading, still blinking, but there seems to be some effect but I am not sure.
Any help with what I could do and what I am doing wrong would be nice.

You need to do away with all those delay() calls.  delay() is eeeeeeeeeeeevil.

That helped with making it responsive again, at least closer to how it was. Great. Now the only problem remains to have perceivable fade in fade out. Especially when the analog value drops to zero, the LED just goes back to off state. The fade in fade out doesn't seem to be working. Any ideas?

You need to replace the delay() calls with another method of slowing things down that doesn't block the whole system.  I.e., take a look at the BlinkWithoutDelay example program in the IDE and learn from it.

Smooth the change in output value by taking, e.g 10% of the new value, and 90% of the old value. You can try experimenting with different ratios and longer/shorter delays.
int lastValue = 0;

{
  Serial.println(value1);//value that i get from analog sensor
  //this is just to get the values in order for the led and sound
  if (value1<=8) value1=-100;
  value1 = (1*value + 9*lastValue)/10;// smooth the change in value by taking 10% of the current value, and 90% of the previous value
  analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
  tone(tonepin,value1+100,100);
  lastValue = value1;
  delay(10);

so I changed that part of the code to this
`int value1=0;
Serial.println(value);
if (value<=8) value=-100;
value1 = (1value + 9lastValue)/10;// smooth the change in value by taking 10% of the current value, and 90% of the previous value
analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
tone(tonepin,value+100,100);
lastValue = value1;
delay(10);`
Where value is the actual input from the sensor. and it sort of works as I changed one to the new value ( LED) And used directly for the sound.
The LED doesnt seem to switch off ever, some residue feel

Try value1 = 0.1*value + 0.9*lastValue; instead

Nope, similar results. Do you think using some kind of counter would help slowly fade it out when the sensor is not being played with?

Some more playing around. If I remove the statement that makes the counter -100 and put a zero instead and change the +100 values everywhere I use value1/value then the LED dies out when not interacting, but the upper limit also drops.
`int value1=0;
Serial.println(value);
if (value<=8) value=0;
value1 = (1value + 9lastValue)/10;
analogWrite(ledPin,value1);
tone(tonepin,value,100);
lastValue = value1;
delay(10);`
Tried the same code by substituting +100 by *10 and removing -100, but then the smoothing obviously also starts scrambling to some degree.
Delay is the key?

I think a nice way to redefine this challenge at this time would be to say that we need to figure out a way to keep the smoothed response while widening the range of output which has the minimum at 0 and maximum at a nice high range. While all this happens the minimum value should be achieved if low input values occur over a time ( seeing them as feedback and not really input)

Another try with a counter produces the best result as of now, but something instinctively feels off, maybe I will share a small video later.
int value1=0;      Serial.println(value);   if (value<=8) value=-100;   if (value<=0) counter=counter+1;   value1 = (1*value + 9*lastValue)/10;   if (counter>=50) { value1=-99; counter=0;}   analogWrite(ledPin,value1+100);   tone(tonepin,value+100,100);    lastValue = value1;   delay(10);

You need to re-think the entire way of dealing with the fading.
Instead of saying "The value has changed, fade the LED to that brightness", you need to say "The value has changed. I want the LED to be this brightness." followed by "Is the LED the brightness I want? No? Then move it a bit towards the brightness I want".
Something like, in pseudo-code:
TargetBrightness = SensorValue
if LEDBrightness < TargetBrightness
    increment LEDBrightness
    set LED to LEDBrightness
if LEDBrightness > TargetBrightness
    decrement LEDBrightness
    set LED to LEDBrightness

If that all happens too fast then you need to only run the brightness tests at certain periods.  Something like:
TargetBrightness = SensorValue
Has 10ms passed since last check? Yes?
    Remember the time this check happened.
    if LEDBrightness < TargetBrightness
        increment LEDBrightness
        set LED to LEDBrightness
    if LEDBrightness > TargetBrightness
        decrement LEDBrightness
        set LED to LEDBrightness


text:
arduino weather shield with gps
I have Arduino Mega and Weather shield and GPS Receiver - GP-635T (50 Channel).
here is my code for GPS
#include <SoftwareSerial.h>
#include <TinyGPS++.h>

TinyGPSPlus gps;

static const int RXPin = 5, TXPin = 4;
SoftwareSerial ss(RXPin, TXPin);

const byte GPS_PWRCTL = 6;

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

  pinMode(GPS_PWRCTL, OUTPUT);
  digitalWrite(GPS_PWRCTL, HIGH);
}

void loop()
{
  smartdelay(800);
}

And print weather with this code
void printWeather()
{
  Serial.print("lat=");
  Serial.print(gps.location.lat(), 6);
  Serial.print("lat=");
  Serial.print(gps.location.lng(), 6);
  Serial.print("altitude=");
  Serial.print(gps.altitude.meters());
  Serial.print("sats=");
  Serial.print(gps.satellites.value());

  char sz[32];
  Serial.print("date=");
  sprintf(sz, "%02d/%02d/%02d", gps.date.month(), gps.date.day(),gps.date.year());
  Serial.print(sz);

  Serial.print("time=");
  sprintf(sz, "%02d:%02d:%02d", gps.time.hour(), gps.time.minute(), gps.time.second());
  Serial.print(sz);
}

But I see only zero for location and date and time. What should I do?

Until you have the correct baud rate and good satellite reception, many fields will be zero or empty.  I wrote a diagnostic program for NeoGPS that will try different baud rates and confirm that the GPS device is functioning.  The example program is in this directory:
examples/NMEAdiagnostic

Installation instructions are here.
If you're inside, you may not be able to receive anything.  Move next to a window or go outside.

You need to feed the output from the GPS module to the TinyGPSPlus routines, otherwise they won't do anything (other than return 0). Try adding:
while (Serial.available() > 0) {
  gps.encode(Serial.read());
}

to your loop. TinyGPSPlus comes with examples that you should have a look at. It also provides many debug statistics, e.g. the number of characters processed (gps.charsProcessed()) and the if these made sense (gps.passedChecksum()).

When I try examples in TinyGPSPlus i see     È†ÔÂ`1h±PÁ   like this symbol.

That looks like you have a mismatch in the rate settings. 9600 baud is usually the default for GPS devices. Make sure the setting on your computer is correct, too (i.e. also 9600 baud, following your code snippet).

BTW, smartDelay feeds the TinyGPS routines.  There are many issues with these libraries that I have documented and fixed in NeoGPS.  Be sure to check out the Troubleshooting section.


text:
Arduino analog joystick
I'm planning to make a handbrake for my racing simulator (Assetto Corsa) and I wanted to know how can I transform arduino into a joystick so the game can read the analog input?
Thanks in advance, and sorry for my bad english.

You would need some sort of Human Interface working on your computer. A Leonardo should work but you would have to reprogram the HID interface so that it gets recognised by the PC as a Joystick. See this page for some info on how to use the potentiometer joystick.

I made this video and github just for this about a year ago.

And here is the code:
/*
2-axis joystick connected to an Arduino Micro
to output 4 pins, up, down, left & right

If you are using pull down resistors, change all the HIGHs to LOWs and LOWs to HIGH.
This skectch is using pull up resistors.

*/

int UD = 0;
int LR = 0;
/* Arduino Micro output pins*/
int DWN = 13;
int UP = 12;
int LEFT = 11;
int RT = 10;
/* Arduino Micro Input Pins */
int IUP=A0;
int ILR=A1;

int MID = 10; // 10 mid point delta arduino, use 4 for attiny
int LRMID = 0;
int UPMID = 0;
void setup(){

  pinMode(DWN, OUTPUT);
  pinMode(UP, OUTPUT);
  pinMode(LEFT, OUTPUT);
  pinMode(RT, OUTPUT);

  digitalWrite(DWN, HIGH);
  digitalWrite(UP, HIGH);
  digitalWrite(LEFT, HIGH);
  digitalWrite(RT, HIGH);

  //calabrate center
  LRMID = analogRead(ILR);
  UPMID = analogRead(IUP);
}

void loop(){

  UD = analogRead(IUP);
  LR = analogRead(ILR);
  // UP-DOWN
  if(UD < UPMID - MID){
   digitalWrite(DWN, LOW);
  }else{
   digitalWrite(DWN, HIGH);
  }

  if(UD > UPMID + MID){
   digitalWrite(UP, LOW);
  }else{
   digitalWrite(UP, HIGH);
  }
  // LEFT-RIGHT
  if(LR < LRMID - MID){
   digitalWrite(LEFT, LOW);
  }else{
   digitalWrite(LEFT, HIGH);
  }

  if(LR > LRMID + MID){
   digitalWrite(RT, LOW);
  }else{
   digitalWrite(RT, HIGH);
  }

  delay(400);

}

This is not what I meant. I want to connect the arduino to my computer and use it to control the handbrake in my game. I want to make my computer recognize the arduino as a controller. But thanks for replying =D

You can use my example as a starting point. However  I would assume you will need to create a customer driver for "Assetto Corsa".

Everything was just handed to you except for the PC side. Now you need to ask yourself: What does the game need for input: text? a logic signal? How can it receive input - through a serial port? The kbd only? Bluetooth? How can I provide that from what the Arduino and @PhillyNJ's code and diagram already make available - text messages to the serial port? Logic signals to RTS and DTR of 2 serial ports? Patch into the keyboard cable? (If your difficulty is on the PC side, this is probably not the right place to get help).

Never tried it with the Arduino, but it's quite easy to do with Teensy (which is mostly compatible with Arduino).
Teensyduino actually includes several examples.


text:
Capacitive sensor touch detection on wearable
I have a wearable wristband project where I'd like to detect a touch to the outside of the wristband, like a button. However, all my attempts to get this to work with capacitive sensing fail.
The problems accumulate from these aspects:

Without grounding, the behaviour seems totally arbitrary at times
I need high response times (12 fps so < 100ms), so some resistor values keep hitting the timeout limit
Testing is really hard, as behaviour changes after unplugging the USB connection to the computer. I have a bluetooth connection in the Arduino and debug via bluetooth connection to get a "actual scenario" type of reading
I've also tried things like setting very short timeouts as well as low sample sizes as well as experimented with different resistors

However, I am not trying to really get any sort of gradual "capacitive sensing" here at all, I merely would need to detect a threshold for "is touching". In fact, the area that the user is touching could even be made out of metal (which it was in my tests so far) and touched directly (so nothing in between finger and metal).
This seems like such an obvious thing to try to achieve, I believe there must be some way to get this done. Any ideas?

Could you put some metal on the inner side of the wristband? This would allow you to use the user's body as a ground.

@EdgarBonet It should be possible. You reckon this would help? How would this work without resulting in a "full" contact being detected all the time?

This still would need testing. But for sure having a closed circuit is
needed. C.f. my answer below.

Expanding on my previous comment:
You can think of capacitive sensing as a form of impedance measurement,
even though it's more a threshold detection than an actual measurement.
In order to perform an impedance measurement, you have to build a
circuit like this:
┌─────────┐           ┌───────────┐
│         ├───────────┤           │
│  meter  │           │ impedance │
│         ├───────────┤           │
└─────────┘           └───────────┘

The important thing in this figure is that you need two electrical
contacts in order to close the circuit. The lower contact is often
provided by a common ground, but since your wristband is not properly
grounded, you will have to provide it by some other means.
My suggestion is to have two electrodes on the wristband: a lower
electrode in permanent contact with the user, and an upper electrode
that will be the touch button. If both electrodes are exposed metal,
then you have a full DC path all around, and this is not “capacitive”
sensing any more. Depending on how your sensing is done, this may not be
a problem, and it may be detected just like an infinite capacity.
If you want to avoid a full DC path, you can have one of the electrodes
covered by a thin layer of dielectric. Or even both, but then you have
two capacitors in series and need twice the sensitivity.


text:
How to remember variable values after rebooting an Arduino Uno R3 board?
Is there any way to store the values of necessary variables somewhere (may be in a file that gets updated by the program at various events), which can be read back when program starts after rebooting the Arduino board?
I am trying to control my AC appliances using IR remote control. Where I want Arduino to remember what was on and what was off in my room after a power failure.
Using EEPROM looks like a fairly good solution, though it has a limitation of 100,000 writes which is making me try to find another way out.
Using an external EEPROM which doesn't have that limitation or is fairly big, is a really good idea I got from fuenfundachtzig, thanks for this great idea. But I don't know how to implement this in my project. Any resource to gather knowledge on using external EEPROM, will be much appreciated.

If you are only concerned about reboot, and not power cycling, then you can use RAM - you just have to keep any init code from wiping it.   Of course if you need to survive power cycling too, then you need the EEPROM.

Actually I am really concerned about the power cycling. I am trying to control my AC appliances using IR remote control. Where I want Arduino to remember what was on and what was off in my room after a power failure.

The internal RAM of the Arduino will be reset when you repower the chip, so if you want to keep your data, you need to store it in EEPROM.
If you are worried about the limited write/erase cycles, you should estimate how often the data would be updated (i.e. written to EEPROM) and how long you plan the lifetime of the device you build. If 100,000 cycles then still is an issue, you have several options:

Keep the variables in RAM and only write them to EEPROM say every 5 minutes (100,000 cycles then makes about one year of continuous usage until the EEPROM might fail).
Use an external EEPROM (in a socket) that could be easily replaced if needed.
If replacing it is not an option, consider using an FRAM instead (advantage vs EEPROM: much more erase/write cycles but also very expensive, so not an option for large amounts of data but certainly for a few variables).

Note, however, that your description sounds like a typical use-case for user settings that you don't want to get lost on reboot. For those the internal EEPROM is the right place: only store them when they're changed and you're golden -- the user won't change them a 100,000 times easily...

I usually use for this type of things an external EEPROM; something like an AT24C02 works fine for most projects (it's 256 bytes).
I just prefer external memory as it lasts more R/W cycles and because you can change it if it doesn't work anymore.

The ram is not cleared. The global variables are set to zero according to the 'c' standard. The unused ram keeps its value during a reset.

Yes, you are right. I was thinking of a power failure which leads to a loss of the data in RAM (and which makes a reinitialization necessary).

what about to use sdcard reader. is not so much expensive and sdcard will live lot of time.

adafruit seems to have FRAM for $5.  Am i missing something?

Approx. 5.5 years?

I'm really late to this party ... the 100,000 (typical) writes before fail metric on the EEPROM - isn't that count on a per bit basis? Meaning, each bit in the EEPROM can be written as a '1' about 100,000 times before a failure is expected V writing ANYTHING ANYWHERE to the EEPROM? If the former, then a cumbersome write-count tracking system could be used by adding a write-count to each block of data, along with pointers to the current block. I did say "cumbersome", but it could work, like a disk directory. Cumbersome.

EEPROM space, as already mentioned, will work if non-volatile is required. However, you have not qualified if it needs to be non-volatile or not. If not then you can use an __attribute__ to define the variable space not to be initialized. As the SRAM on the ATmega's are not cleared by reset or power cycle. The Compiler defaults to initializing them. Where this can be turned off per variable as in the below example:
//non-initialized value
union configUnion{
  uint8_t    byte[6]; // match the below struct...
  struct {
    uint16_t value1;
    uint16_t value2;
    uint16_t chksum;
  } val ;
} config  __attribute__ ((section (".noinit")));

void setup() {
  uint16_t sum;
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // prints title with ending line break
  Serial.print("Out of Reset -");
  sum = getchksum();
  printValues();

  if (sum != config.val.chksum) {
    config.val.chksum = sum;
    Serial.print("chksum is incorrect setting config.val.chksum = 0x"); Serial.println(config.val.chksum, HEX);
  }

  config.val.value1++;
  config.val.value2++;
  Serial.print("setup new values - ");
  printValues();
  config.val.chksum = getchksum();
  Serial.print("updating chksum config.val.chksum = 0x"); Serial.println(config.val.chksum, HEX);
}

int counter = 0;

void loop() {
  if (counter < 200) {
    Serial.print("after a while - ");
    printValues();
    Serial.println();
    while (true) {
      continue;
    }
  }
  counter++;
}

void printValues() {
  Serial.print(" value1 = 0x"); Serial.print(config.val.value1, HEX);
  Serial.print(", value2 = 0x"); Serial.print(config.val.value2, HEX);
  Serial.print(", sum = 0x"); Serial.print(getchksum(), HEX);
  Serial.print(", chksum = 0x"); Serial.println(config.val.chksum, HEX);
}

uint16_t getchksum() {
  int sum = 0;
  for (int position = 0; position < (sizeof(config) - sizeof(config.val.chksum)); position++) {
    sum = sum + config.byte[position];
  }
  return sum;
}

Output of above code is below. Note that the first output was the result of powering the UNO up with the Reset button depressed and then released after the Monitor window was started. Otherwise the "incorrect setting" print would have been missed, before the monitor window can be started.
Out of Reset - value1 = 0xBFED, value2 = 0xD2F9, sum = 0x377, chksum = 0xF457
chksum is incorrect setting config.val.chksum = 0x377
setup new values -  value1 = 0xBFEE, value2 = 0xD2FA, sum = 0x379, chksum = 0x377
updating chksum config.val.chksum = 0x379
after a while -  value1 = 0xBFEE, value2 = 0xD2FA, sum = 0x379, chksum = 0x379

Out of Reset - value1 = 0xBFEE, value2 = 0xD2FA, sum = 0x379, chksum = 0x379
setup new values -  value1 = 0xBFEF, value2 = 0xD2FB, sum = 0x37B, chksum = 0x379
updating chksum config.val.chksum = 0x37B
after a while -  value1 = 0xBFEF, value2 = 0xD2FB, sum = 0x37B, chksum = 0x37B

Out of Reset - value1 = 0xBFEF, value2 = 0xD2FB, sum = 0x37B, chksum = 0x37B
setup new values -  value1 = 0xBFF0, value2 = 0xD2FC, sum = 0x37D, chksum = 0x37B
updating chksum config.val.chksum = 0x37D
after a while -  value1 = 0xBFF0, value2 = 0xD2FC, sum = 0x37D, chksum = 0x37D

With this your variables will persist resets. As long as the power is not lost. Noting the above where you will get random data, to start.
Using either EEPROM or .noinit I would recommend that you checksum your persistent variable space during setup and if incorrect you can initialize or issue a warning.

If you really need to update your NVRAM frequently, look into FRAM (Ferroelectric Random Access Memory) which claims a write life of 10^13 cycles (that's ~ 318,000 years if you write once/sec!). They're 8KB, and faster than Flash or EEPROM at 20MHz (SPI).
Adafruit (in the US) sells them on a breakout board for about US$6 in onesies. Or you can buy the bare chips from the usual suppliers for around US$1.30, but not DIP, only SOP8 packages.

Store them in the on-chip EEPROM.

http://www.arduino.cc/en/Reference/EEPROM
http://www.arduino.cc/en/Tutorial/EEPROMWrite
http://www.arduino.cc/en/Tutorial/EEPROMRead

The EEPROM memory has a specified life of 100,000 write/erase cycles, so using EEPROM can be a limitation where program automatically writes values in it frequently, though, it reads them quite rare.

If you're open to a off-chip solution, it isn't too difficult to buy/build an SD card reader.

Please try to provide a more thorough answer: provide links to such SD card readers, post some sample code on how to read/write variables from it, and mention how it is better than EEPROM.

Good suggestion. SD is using a regular SPI interface. So all you need is some logic-level-conversion. Beside that you wire them directly to an Arduino. Just solder some wires to a micro-SD to SD adapter.

+jfpoilpret IMHO SD Card Readers are ubiquitous and shouldn't need examples or citation. The code is dependent on the brand of reader so no point in providing arbitrary code. I did mention how it is better than EEPROM, it isn't too difficult to buy or build.

I am very late to this party ... I just bought an UNO WiFi and I am looking at creating a simple protocol to persist data with a data store on another device connected to the WiFi. Probably will use HTTP with simple end points, treat the remote storage as a contiguous memory block:
GET IP:port/addr/len
PUT IP:port/addr data

I could also create named blocks (think files):
GET IP:port/name
PUT IP:port/name data

The actual remote storage could be anything, memory mapped disk file, SQLite3 database, etc.
There are many drawbacks, such as reliance on the external service, connectivity issues, error handling, etc. I could run out of code space just supporting the protocol.
EDIT: I got a little flack for my answer, including downvotes, however, read the OP - he stated "somewhere" for retrieving variable data; a LAN device certainly falls in the category of "somewhere", especially when the UNO has WiFi. My answer might not be suitable for the OP, however, after reading my answer, the OP might opt to get a WiFi enabled device. I do not believe in "keyhole" solutions, but rather to provide options that fit the general tone of the question even if it means getting out of its box.

so your answer is "add WiFi and store the values on a remote server"? isn't that a little complicated if the project doesn't use WiFi for anything else?

Does EEPROM not work for you?

@Juraj - Yes, that is my answer, and yes, it is complicated if your project does not use WiFi for anything else, but as I stated in my answer, WiFi is my best solution and I offered it as yet another possible answer for certain situations, see my response for Nick Gammon

@NickGammon - The EEPROM solution is not my best solution as I cannot predict how many updates to the persisted data, both in updates and new data, so I could eventually use all of the EEPROM data and/or perform too many writes to it, effectively destroying the UNO's capability for me.

All - the OP stated: "Is there any way to store the values of necessary variables somewhere" - emphasis on "somewhere" in my answer. "Somewhere" includes on a local network, which is what my answer provides.

Re-reading your answer, it seems to me like a new question. You might want to make it one. The question asked about remembering light switch statuses after a power failure. Given that the Uno has 1024 bytes of EEPROM, and only one bit is needed to remember a on/off status, you could store 8096 statuses. Or, do some load balancing, so that after 100,000 writes to EEPROM, you switch to a new bank of bytes. I'm assuming they don't have 8096 lights in their house.

Your suggestion of using a web server, for this purpose, would cause a long delay (maybe 5 minutes) while the router and web server rebooted and became ready to answer queries. If the power went off, would you really want to wait minutes before the lights came back on? If you are trying to solve a different problem than I want Arduino to remember what was on and what was off in my room after a power failure then I suggest you make your own, new, question.

@NickGammon I am using an Arduino with a very simplified implementation of HTTP, just so the client is familiar with the API. I've obtained a Rev 3 UNO with a off-brand SD/RTC board, using a simple HTTP service that I built for another project. The service is available in seconds. The router is a different issue, but I'm looking at simple devices, these will not be exposed to anything, so even a switch would be fine.

@NickGammon The whole thing with banks in EEPROM is a lot of monkeying around. I have 75+ devices, many of them are variable, so I would need 7 bits (0-99/128) for those. I also need a table to map devices to a slot in the memory bank. Many devices will be "hot" and be updated far more often, so I could lose a whole bank because of one or two devices. And then there is testing of the bank management - which is alleviated by just moving the bank with each write instead of counting, etc. However, I don't what to have to buy a new Arduino when one fails.

@NickGammon ... And ... My question extends beyond the scope of my question. I have similar projects (need for data) for my motor home. One application will have records that could be about 50 bytes each and an unknown number of records. Another application will have records with around 120 bytes each and there could be hundreds of those and any of those could be updated.

@NickGammon Not dwell on this, but in my house with the lights/devices, the router and server would be on a UPS (SPS) with about 12 hours of power, but the lights/devices are not.

You make some good points, but you are morphing the question from what the OP wanted "I want Arduino to remember what was on and what was off in my room after a power failure" to your requirements which seem somewhat different. If you want to make a new question with these somewhat more complex requirements then we could validly discuss it further.

@NickGammon My "morph" was explaining my project and how the OP might use my method for persisting data. Everyone else should have just left it at that - I was NEVER asking for help.

This was puzzling me too. I just wanted to use the onboard button to trigger a "count up an integer" regardless any setup routines. For me, mpflaga's answer gave me the right direction. But the given example was far too complicated for my needs. So here's the bare minimum example for an integer value that survives a reset, counting up. (But NOT a power loss, as it's in RAM!) Enjoy!
uint8_t c __attribute__ ((section (".noinit")));

void setup() {
  Serial.begin(9600);
  Serial.print("Just startet. c = ");
  Serial.print(c);
  if(c>7){c=0;}else{c++;}
  Serial.println(" - Waiting for RESET.");
}

void loop() {
  // Do more stuff.
}

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Arduino Tre, will it ever come out?
Does anyone have any information other than "coming soon" about the Tre?
Could the Tre be stuck in development hell?
Perhaps the new partnership with Adafruit could expidite things, seeing as Ardiuno (.cc) was touting the Tre to be the first Arduino made in the USA?

I'm just giddily awaiting its arrival, so I'm just wondering!

Just buy a BeagleBone Black and plug an Uno into it - you'll get pretty much the same thing without having to wait.

The latest news from Arduino that I can find is in their blog archive that the second round of beta testing is out.
The mentioned this:

When is the Arduino TRE going to be finally on the market? The board is ready, but we don’t have a final release date yet because we are still figuring out some manufacturing matters. We’ll keep you posted!

I'd imagine that the Arduino LLC vs Arduino SLR legal issue is also delaying the production.
Other than that, speculation is all that we know.
P.S: it's still spring until Sunday, June 21! :-)


text:
How to get weight data from glass electronic bathroom scale sensors?
I am doing a small project with a bathroom scale but I run into some problems. I am using an Arduino Uno V3, HX711 module amp and a scale.
Scale:

HX711 amplifier:

I disassembled the scale to get to sensor wires and I am a bit confused. These sensors have three wires each. So they are half bridge sensors. The scale is using 4 sensors so when the scale is measuring it is measuring with a full bridge. And these 3 wires are RED, BLACK, BLUE. I don't know what is black (GND or Positive) and blue (same guess). Four red wires are given names E+, E-, S+ and S-. I will provide a picture of the disassembled scale.

Two blue wires are soldered together on each side. I guess red wires are signal (S+, S-, E+ and E-) but what are Blue and Black? Then I soldered the wires to these wires to get sensor readings but I don't know what is what.

The sensor is looking like this:

I tried:

Two different libraries for this project both named HX711 (for this module)
Changing A+ for A- on module

// Hx711.DOUT - pin #A1
// Hx711.SCK - pin #A0

#include "hx711.h"

Hx711 scale(A1, A0);

void setup() {

  Serial.begin(9600);

}

void loop() {

  Serial.print(scale.getGram(), 1);
  Serial.println(" g");

  delay(200);
}

with no success. I get 0.0g on the serial monitor when calm, and the same when load is on.
My questions are:
How to know which wire is GND, +5V and which is signal? How to connect 4 of these sensors to read data? How to use HX711 libraries available and HX711 module? And, most important, how to read data from this scale on serial?

The sensorsare quite posibly configured as in Fig1 in the data sheett If so there should be +5 and 0V across two points and weight signal between two others. Use a DMM to Check for 5V (probably 5V =  E+). So find two leads with Vdd (5V or similar) . Other two probably at Vdd/2 abov ground. Connect meter on LOW V range between other two and see if reading varies with weight change. | Report back. ||  As jwpat7 says  - you may need to repower sensors off HX711 supply to get correct readings. | HX711 looks nice.

What Fig1? I know where is GND and VDD on HX711 module, and where goes the signal wires(A-,A+,B-,B+). That is clear. I dont know which colors of wires from sensors is GND VDD and Signal.
I will do this. I will put back the power on the scale (3v from battery) and I will try to measure wires to determine what is what (i will put some load on the scale). I have a multimer so i will try to determine which wires are signal, and which wires are GND and VDD. I will report back. Tnx Russell.

Sorry - Fig 1 here in HX711 data sheet

Please, I did exactly as it is explained. I am having a strange reading but when I pressed the sensor, the value is decreasing instead of increasing! Can you help please??

Your four half bridge load cell sensors can connect into a full wheatstone bridge as in https://electronics.stackexchange.com/a/199470/30711
If your sensors are like this 50kg load cell from SparkFun's https://www.sparkfun.com/products/10245  or Ebay's http://www.ebay.com/itm/4pcs-Body-Load-Scale-Weighing-Sensor-Resistance-Strain-Half-bridge-Sensors-50kg-/251873576571 they might have a compression and tension gage both on the top surface. The Ebay site has a diagram like:

... which indicates a positive strain gauge on the red-white, and a negative strain on the red-black. (note that the coloring order in this diagram does not match the coloring order in this picture.  I have a similar gauge with blue-red-black colors, and the positive strain gauge is the right pair, negative on the left.) The gauged surface on the center bar between the face-to-face coupled 'E's in the sensor should act like a parallel bar and has portions under compression and under tension, rather than purely under tension.  In cross-section, the gauged bar in the center is sort of the cross-piece in a Z-shaped spring. In this case, the strains oppose each other, and, if manufactured well, the reduction of resistance in the negative strain portion will offset the increase in resistance in the positive strain portion and the total white-black resistance should be constant.  One still needs to set up the bridge so that the voltage dividers move in opposite directions with added load, and 4 devices wired in a white-to-white and black-to-black loop should work as above.
If you wire four of these up carefully by flipping them around so the stress sensitive portions unbalance the bridge constructively, you can use all four sensors without any extra resistors.
Basically, two diagonally-opposite sides of a wheatstone bridge are each formed by the compression elements of two gauges wired in series, while the remaining two sides of the bridge are each formed from two tension elements from two cells.  With load on all the sensors, the compression resistances are reduced, while the tension resistances are increased and it pulls the bridge out of balance.
To get this, wire all four sensors in a big ring with maximum resistance, matching colors and initially ignoring the red center tap wires.  (This is the function of the soldered-together blues and blacks are in your scale.)  Choose two opposite (red) center taps as E+ and E-, and the remaining two (red) center taps as S+,S-.  Put the excitation voltage on the E+/E- from the diagram above and read a force-sensitive voltage difference across S+/S-, and this is what you feed into your HX711 as A+ and A-  (Ignore B+/B- as a second, unused channel.)
Here's a schematic with gauges 1-4 as G1 G2, G3, G4 per the above specs, applying an excitation on the G1 and G3 reds, and reading the signals off the G2 and G4 reds.  The G4 gauge is loaded a bit with some positive strain increasing the G4+ resistance, and some negative strain reducing the G4- resistance.  Ideally, loading G4 with 25kg would produce 0.5mV/V times its 2.5V excitation voltage, producing 1.250mV across Sig+/Sig-, and stretching R8 to be 1001 ohms and compressing R7 to 999 ohms as shown.   (The schematic/simulator thing on electronics.stackexchange.com is pretty cool.)

simulate this circuit – Schematic created using CircuitLab
Instead of the "White" wires in the diagram and like on my gauges, consider it the "blue" wires from your scale's sensors.
With only two of these half-bridge sensors, one should not match the end colors and hook white-to-black (blue-to-black) and black-to white, (black-to-blue) imposing an excitation voltage from between these two junctions, and read the differences across the reds, as increased load pulls one side high and the other side low.  This will look like the plain 4-resistor wheatstone bridges in the common datasheets, rather than the 4-half-bridge/eight-resistor scheme above.

The HX711 provides power to a bridge and amplifies the bridge's differential voltage.  The scale's original circuit board (which drives an LCD readout) also  provides power to a bridge.  You are unlikely to get any useful readings while both circuits are applying power to the bridge.

(You could cut the existing wires and attach connectors to allow changing back and forth between the original board and your Arduino circuit.)

Some scales like the one shown use a 9 V battery to run the electronics.  That voltage, if used, is likely to be incompatible with connecting an Arduino (typically powered by 3.3 V or 5 V) or an HX711 (powered with VDD in the range 2.7 V to 5.5 V) at the same time as the original board.

The scale have 3V litium battery that is powering the system. I cut that wires, look at the picture above. So i am not using any power except from arduino.

Text mainly from my comments with some additions - with image added.
The sensors are quite possibly configured as in Fig1 in the data sheet.
 If so there should be +5 and 0V across two points, and weight signal between two others.
Use a DMM to Check for Vdd (probably 5V if pV battery, ~= 3V with Lithium battery). Find two leads to bridge with ~= Vdd on. Other two probably at Vdd/2 above ground. It is likely there are 4 wire effectively so each of the red wires on one side may be conncted tpo one on the other side - an Ohm-meter will tell you. Connect meter on LOW V range between other two and see if reading varies with weight change. Report back.
As jwpat7 says - you may need to repower sensors off HX711 supply to get correct readings.
HX711 looks nice. Under $1/module in modest volume on Alibaba and under $US/0.50 / IC in hundreds.
What Fig1? I know where is GND and VDD on HX711 module, and where goes the signal wires(A-,A+,B-,B+). That is clear. I dont know which colors of wires from sensors is GND VDD and Signal. I will do this. I will put back the power on the scale (3v from battery) and I will try to measure wires to determine what is what (i will put some load on the scale). I have a multimer so i will try to determine which wires are signal, and which wires are GND and VDD. I will report back. Tnx Russell. –
See fig  of HX711 Data sheet for larger view of this image.

The sensor you have in your scale are a simple voltage dividers. Each consist of one resistor and one extensiometer, both connected in series. One wire (E+) is VDD another (E-) is GND and the third is divider output(S). You can not directly use it with HX711 which needs a bridge sensors not just dividers. You can try to set a 1/2vdd on S- and connect the signal from the sensor to S+. In case you get a negative weight, simply swap these connections. Your assumption that your scale uses full bridge, because it has four sensors, is completly wrong. You can read the signals  from the scale sensors using analog inputs in you arduino (without HX711) but you should amplify it before to get reasonable resolution. Good luck!
Greg