text:
How to explain the need/advantage for volatile in terms of microcontroller instruction flow
I know there are already many questions why volatile is used when it comes to interrupts.
But explanations like this doesn't help to picture what really happens:

Specifically, it directs the compiler to load the variable from RAM
  and not from a storage register, which is a temporary memory location
  where program variables are stored and manipulated. Under certain
  conditions, the value for a variable stored in registers can be
  inaccurate.

Above is from the official Arduino website:
And below is the basic Atmega328 architecture:

Is it possible to explain the use/advantage of volatile by comparing it to the usual declaration way considering the above architecture?
I mean such way: If volatile int x is used, the CPU fetches this from this  by this way ect. And if instead int x is used the instruction flow works like this so forth and so on.
Unfortunately I have difficulty to understand from plain two sentence explanations.
As you see my question is about after the compilation what do we observe as a benefit inside the hardware during the instruction flow.

Let's say you are running the code x++; x++; the compiled code will have to load variable x from the predefined memory location; place the value in a register; call the increment instruction; and write the register back to the memory location; and then the same steps for the next x++. The compiler will be smart and notices you write the register to memory, and the read it back from memory directly after, and will just remove these two steps entirely, to increase performance. It is however assuming the memory location doesn't change in between statements.

Are general purpose registers used for fetching volatile variables from SRAM?

The ALU can only work on registers, so you have to load the variable from SRAM to do anything with it. Sometimes local variable aren't even placed in SRAM, but only a register is used for them (for example the i variable in a for( i... loop)

The compiler can't see whenever an interrupt is being called. So may basically make a constant out of a value that you wanted to change in the interrupt. You can draw your normale program loop, with an interrupt completely loose from that. Tell that the hardware calls this function, thus the compiler doesn't know if and when it's called. Show some example code and ask what a compiler could do with or without interrupts.

Short answer: no, volatile cannot be explained in terms of the
figure you show in your question.
Longer answer: there is no direct link between the meaning of volatile
and the architecture depicted in the figure. If you insist in linking
them together, it is possible to find a very weak and indirect link
as follows:

Volatile is all about preventing the compiler from doing some
optimizations when translating your program to assembly. Looking at the
generated assembly can help understanding the effect of volatile.
When learning the assembly language, the figure you show is helpful
in understanding the assembly instructions themselves.

As you see, the link is indirect, mostly because we are talking about
different abstraction levels. Also, the link is weak because the figure
describes specifically the AVR architecture, whereas volatile applies
to any architectures for which there is a C compiler.
To illustrate the first point above, here is an example program which
shows the effect of volatile:
volatile bool volatile_flag;
bool plain_flag;

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

void loop()
{
    Serial.print("Waiting for volatile flag... ");
    while (!volatile_flag) ; /* wait */
    Serial.println("done.");

    Serial.print("Waiting for plain flag... ");
    while (!plain_flag) ; /* wait */
    Serial.println("done.");
}

As such, the program is not very interesting, it will just hang on the
first loop. But you can imagine there being some ISR that can set the
flags when some external event happens. Then the wait loops would start
to make sense, as they wait for the external event.
Here is the disassembly of the loop() function:
    Serial.print("Waiting for volatile flag... ");
  ce:   60 e0           ldi r22, 0x00   ; 0
  d0:   71 e0           ldi r23, 0x01   ; 1
  d2:   82 e5           ldi r24, 0x52   ; 82
  d4:   91 e0           ldi r25, 0x01   ; 1
  d6:   0e 94 b3 02     call    0x566   ; 0x566 <Print::print(char const*)>
    while (!volatile_flag) ; /* wait */
  da:   80 91 51 01     lds r24, 0x0151
  de:   88 23           and r24, r24
  e0:   e1 f3           breq    .-8         ; 0xda <loop+0xc>
    Serial.println("done.");
  e2:   6e e1           ldi r22, 0x1E   ; 30
  e4:   71 e0           ldi r23, 0x01   ; 1
  e6:   82 e5           ldi r24, 0x52   ; 82
  e8:   91 e0           ldi r25, 0x01   ; 1
  ea:   0e 94 d0 02     call    0x5a0   ; 0x5a0 <Print::println(char const*)>
    Serial.print("Waiting for plain flag... ");
  ee:   64 e2           ldi r22, 0x24   ; 36
  f0:   71 e0           ldi r23, 0x01   ; 1
  f2:   82 e5           ldi r24, 0x52   ; 82
  f4:   91 e0           ldi r25, 0x01   ; 1
  f6:   0e 94 b3 02     call    0x566   ; 0x566 <Print::print(char const*)>
    while (!plain_flag) ; /* wait */
  fa:   80 91 50 01     lds r24, 0x0150
  fe:   81 11           cpse    r24, r1
 100:   01 c0           rjmp    .+2         ; 0x104 <loop+0x36>
 102:   ff cf           rjmp    .-2         ; 0x102 <loop+0x34>
    Serial.println("done.");
 104:   6e e1           ldi r22, 0x1E   ; 30
 106:   71 e0           ldi r23, 0x01   ; 1
 108:   82 e5           ldi r24, 0x52   ; 82
 10a:   91 e0           ldi r25, 0x01   ; 1
 10c:   0c 94 d0 02     jmp 0x5a0   ; 0x5a0 <Print::println(char const*)>

The important thing to notice is how the compiler implemented the
waiting loops. The first one is essentially
0:  lds r24, volatile_flag  ; load the flag from RAM
    tst r24                 ; test it
    breq 0b                 ; if zero, loop back

whereas the second loop is:
    lds r24, plain_flag     ; load the flag from RAM
    cpse r24, r1            ; if zero, skip the following jump
    rjmp 1f                 ; jump over the next loop
0:  rjmp 0b                 ; infinite loop
1:

You may appreciate the first loop has been translated to assembly in a
very literal way, whereas in the second loop the compiler optimized away
all but the first read of the variable. That could be translated back to
C as
if (!plain_flag) {
    for (;;) ;  // hang in an infinite loop
}

The compiler assumed the flag cannot be changed by some external event,
so there is no point in reading it repeatedly. The volatile keyword
prevents the compiler from making such assumption.
And how is all this related to your figure you may ask? Well, if you
happened to not understand the assembly code above, you could check the
AVR Instruction Set Manual to see what each instruction does,
and that's when the figure becomes helpful.

I believe the back translation to C you provided is going to be the clearest explanation of volatile you can provide: any further simplification is not going to have any value.

@RobertoLoGiacco: Agree, but reading the generated assembly is the only (contrived) way I found to link volatile with the figure, and the OP kind of insisted on finding such a link. I reworded the answer to make this clearer.

Let me explain it like this. Modern compilers optimize. They do this to make things run faster. People would complain if they didn't, or switch to another compile that does optimize.
Here's an analogy. Let's say you are wondering how many cats your brother has. You call him up on the phone, and he says "two".
A week later your friend asks how many cats your brother has. You say "I'll call him up and ask him.".
Your friend says "Didn't you do that last week? How many did he have then?"
You reply, "Yeah, that's right. He must still have two cats, right? I've just saved the expense of a phone call!"
Not making the phone call is an optimization - you save time and money by not doing it. However what if your brother now has another cat? Or he gave one away? The information about the number of cats is out of date.
If your brother is a cat dealer, or frequently changes his cat configuration you might say "the number of cats my brother has is volatile - I'll have to call him up again to make sure of the number."
So, if something happens behind your back (like in your brother's house - or in a computer program in an ISR) then you need to check again each time. However if you are sure that things haven't changed (eg. in your house you would know if you got a new cat) then you can optimize by not checking each time.
I agree with Gerben's comment on this page. This is nothing to do with the compiler architecture - any more than the number of cats you have depends on the way the house is built.

volatile varaibles are used in Shared variables, because the flow can change whit compiler otimizations.
It's important to when you use timer's interrupt in sample.

Im looking for a pictorial explanation using illustrated flow chart I provided. How the variable is stored and fetched and processed in both volatile and other cases.

volatile variables are the same as variables, the diference is in the code otimization. A volatile variable is ever consistent.

Im not asking what you write about.

Volatile is a compiler only thing. It not part of the micro controller, so it doesn't exist in the diagram.

The mocrocontroles use a non-volatile program memory.
The Atmel328 has a Harvard architecture, so have a memory block for instrutions and one block for data, both are non-volatile.
If what you will is persist data betwhen a shutdown, you need use the EEPROM memory.

@rodrigo: You are mixing two very different meanings of the word “volatile”.

That's what I mean, volatile can be interpreted in two ways.

physically: Computers. of or relating to storage that does not retain data when electrical power is turned off or fails.
Logicaly: Compiler otimization rules


text:
Setting the sampling rate for timer interrupt
I had performance problems with the data acquisition and after some reading on the web, someone told to define a timer with the frequency I need (50hz):
// TIMER 1 for interrupt frequency 50 Hz:
cli(); // Stop interrupts.

TCCR1A = 0; // Set entire TCCR1A register to 0.
TCCR1B = 0; // Same for TCCR1B.
TCNT1  = 0; // Initialize counter value to 0.

// Set compare match register for 50 Hz increments.
OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)
// Turn on CTC mode.
TCCR1B |= (1 << WGM12);
// Set CS12, CS11 and CS10 bits for 64 prescaler.
TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
// Enable timer compare interrupt.
TIMSK1 |= (1 << OCIE1A);

sei(); // Allow interrupts.

But with that, I was unable to achieve good performance; I was expecting 50 reading / seconds. Luckily, I've changed for 8 bits prescaler instead of 64 and I've start to get better performance:
// Set CS12, CS11 and CS10 bits for 8 prescaler.
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);

But, honestly, I'm a newbie and I don't understand why!

This is definitely no newbie-level stuff. If yo have enough patience, study http://www.gammon.com.au/timers and you will have all your answers.

@EdgarBonet thanks for the reference. I see Atmega2560 code. I start from Atmega328 samples to implement timer.

The Timer 1 of the ATmega2560 and the ATmega328P are essentially identical. You can study either and apply what you learn to the other.

// = 16000000 / (8 * 50) - 1 (must be <65536) that 8 in the formula refers to the prescaler. So this formula expect you to have a /8 prescaler. But four lines below you used a /64 prescaler. So your timer runs 6.25 Hz.
When you changed it to /8, you got the correct frequency.

source: Stack Exchange

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

sort: votes


text:
My servo is misbehaving
I have been trying to get my 9g tower pro servo to work and no matter what i do nothing happens. I connected the servo to the arduino with the red wire to 5v, brown to ground and orange to pin 6.
#include <Servo.h>
Servo myServo;

void setup(){
myServo.attach(6);
}

void loop() {
myServo.write(0);
delay(1000);
myServo.write(60);
}

I have been using this code to test it.
Another weird occurrence is when i disconnect the servo it sometimes start moving very slowly even though it has now power. I dont think the Uno is broken as other projects work fine on there, are my servos fried?

My guess is your drawing too much current from the Arduino 5v rail.
Try connecting the servo to it's own 5v source with of course a common ground with the Arduino.

I tried connecting it to a 9v and it did not work, would the results be any different with 5v?

You connected the servo to 9v ?

yes i connected it to a 9v and the ground to the arduino

Is your servo motor 9v tolerant ?

I will look into that and test it with some smaller batterys.

I think i have broken my servos as i did use 9vs for a long time and they are only meant for 3 - 7.2v (according to the amazon page).

I tested another servo i had - not one of the ones i have ever used before and it worked perfectly.

I found your problem. There is no delay at the end of the loop. So it runs myServo.write(0) then pauses for one second then runs myServo.write(60) immediately afterwards it starts the loop over and runs myServo.write(0) this happens before the servo has time to move.
To fix this add a delay at the end of the loop.
Try:
#include <Servo.h>
Servo myServo;

void setup(){
myServo.attach(6);
}

void loop() {
myServo.write(0);
delay(1000);
myServo.write(60);
delay(1000);
}

this doesn't change anything as i do not think it is to do with the code, even if i put myServo.write(50) in void setup the servo would do nothing.

Did you try the program? When you put myServo.write(50) in the void setup was there code in the loop? There is no delay in between the setup and loop. Try: void setup(){myServo.attach(6) myServo.write(50)} void loop(){}

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


text:
If-statement gets ignored?
I'm kind of stuck with strange behaviour of my code and I really hope, someone could help me..
Objective
I'm trying to build a (multiple) magnetic stirring device with which I can either control the speed via potentiometer or via serial commands from a python script from pc (usb).
When the speed is set via serial, it shouldn't be possible to interfere with the potentiometer unless a button is pressed to unlock it.
Code
// Constants

const int FanPin[7] = {2,3,5,6,7,8,9}; // PWM Pins 2,3,5,6,7,8,9 for fan
const int PotiPin[7] = {A0,A1,A2,A3,A4,A5,A6}; // Analoge Pins 0,1,2,3,4,5,6 for potentiometers
const int SwitchPin[7] = {30,31,32,33,34,35,36}; // Digital Pins 30, 31, 32, 33, 34, 35, 36 for switches

// Variables
boolean ManualLock = false; // will be true if locked by serial input
int Fan[7][2] = { // [x][] for number of fan, [][0] for fan speed, [][1] for ManualLock
  {0, ManualLock},
  {1, ManualLock},
  {2, ManualLock},
  {3, ManualLock},
  {4, ManualLock},
  {5, ManualLock},
  {6, ManualLock}
};
int temp = 0; // Variable for temporary data
int FanSpeed[7] = {0,0,0,0,0,0,0}; // Variable fan speed
int PotiVar[7] = {0,0,0,0,0,0,0} ; // Variable for saving poti-input
byte bfr[2] = {7,7}; // Buffer for serial data

void setup() {

TCCR2B = TCCR2B & 0b11111000 | 0x01; // Timer2 (Pin 9, 10) @ 31000Hz
TCCR3B = TCCR3B & 0b11111000 | 0x01; // Timer3 (Pin 2, 3 und 5) @ 31000Hz
TCCR4B = TCCR4B & 0b11111000 | 0x01; // Timer4 (Pin 6, 7 und 8) @ 31000Hz

Serial.begin(9600);
delay(100);

// Declaration of Pin Modes
for (int i = 0; i < 7; i++){
  pinMode(FanPin[i], OUTPUT);
  pinMode(PotiPin[i], INPUT);
  pinMode(SwitchPin[i], INPUT);
  }
}

void loop() {
for (int i = 0; i < 7; i++){
  // ManualLock not active -> manual mode
  if (!Fan[i][1]){
    //Serial.print(i);
    //Serial.println(" ManualLock not active");
    PotiVar[i] = analogRead(PotiPin[i]);
    Fan[i][0] = map(PotiVar[i], 51, 1023, 60, 255);
    //Serial.println(Fan[i][0]);
  }
  //ManualLock active -> unlock by pressing button
  if (Fan[i][1]){
    temp = digitalRead(SwitchPin[i]);
    if (temp == HIGH){
      Serial.print(i);
      Serial.println(" ManualLock will be deactivated");
      Fan[i][1] = false;
      Serial.print("Fan[i][1]: ");
      Serial.println(Fan[i][1]);
    }
  }

  // fan off @ low poti setting
  if (PotiVar[i] < 50){
    Fan[i][0] = 0;
  }
}

// look for serial data

if (Serial.available()){
  Serial.println("Something's there!");
  Serial.readBytes(bfr, 2);
  delay(1000);
  Serial.print("Serial data: ");
  Serial.println(bfr[0]);
//  Serial.flush();
}

//Serial.print("before loop bfr[0]: ");
//Serial.println(bfr[0]);

for (int i = 0; i < 7; i++){
  if (i == int(bfr[0])){
    Serial.print("i: ");
    Serial.println(i);
    Fan[i][0] = int(bfr[1]); //set fan speed variable
    Fan[i][1] = true; // activate ManualLock variable
    byte bfr[2] = {7,7}; // clear buffer
    Serial.print("bfr[0]: ");
    Serial.println(int(bfr[0]));
  }
}

for (int i = 0; i < 7; i++){
  analogWrite(FanPin[i], Fan[i][0]); // write fan speed
  }
}

Error(s)
When I send a command via my python script, the speed is set correctly and I get the following output:
Something's there!
Serial data: 0
i: 0
bfr[0]: 7
i: 0
bfr[0]: 7
...and again and again and again...

Which means, although i "reset" my buffer variable to something that should prevent entering the if-statement, it will somehow fulfill the "if (i == int(bfr[0]))" condition.. but why?
If any further information is needed, i'll happily provide that.

This (inside your for loop) does not do what I think you think it does:
byte bfr[2] = {7,7}; // clear buffer

You think it sets the contents of the bfr array you declared at the top to {7,7} but what it actually does is declare a new byte array in that scope, containing the values {7,7}. It's not used and is immediately thrown away again.
I would expect the compiler to warn about it -- does it?  (If so, take it as a lesson not to ignore compiler warnings!)
I think you want to replace it with
bfr[0] = 7;
bfr[1] = 7;

or something equivalent.

unfortunately, there was no warning.
but now it works! thank you so much!


text:
Comparing two char array
I modified a code which replies BAR when I send FOO. The problem is the if else statement always lands on else which prints Wrong command. I tried comparing it to string FOO(??) and also comparing it to char FOO with the same buffer size but no joy. This is the code:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "##########";
const char* password = "##########";

WiFiUDP Udp;
unsigned int localUdpPort = 9999;  // local port to listen on
char incomingPacket[255];  // buffer for incoming packets
char command_1[255] = "FOO"; //Tried same buffer size... no luck
char replay_1[] = "BAR";
char wrong[] = "Wrong command";

void setup()
{
  Serial.begin(74880);
  Serial.println();
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
  Udp.begin(localUdpPort);
}

void loop()
{
  int packetSize = Udp.parsePacket();
  if (packetSize)
  {
    int len = Udp.read(incomingPacket, 255);
    if (len > 0)
    {
      incomingPacket[len] = 0;
    }
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(incomingPacket); // Prints the same as from icoming packet which is FOO (Debbuging)
    if (incomingPacket == command_1) { //Tried comparing to same buffer size "FOO" and string "FOO"... no luck
      Udp.write(replay_1);
    }
    else {
      Udp.write(wrong);
    }
    Udp.endPacket();
  }
}

You are comparing a char* to a char*. Array's are contiguous memory locations and the variable name for an array in this case command_1 and incomingPacket point to the first element in the array. Since they are two different array's, the location of the first element in command_1 is different than the location of the first element in incomingPacket so command_1 will never equal incomingPacket.
In order to check if the incoming packet equals "Foo" try
if(strcmp(incomingPacket, "Foo") == 0)

This utilizes the strcmp() compares two null terminated character arrays and returns 0 if they are equal.
Just ensure that the incomingPacket is null terminated I have never worked with this library before.

> if (incomingPacket == command_1)

that statement is testing if pointer incomingPacket is pointing to the same address as pointer command_1.
to compare strings, you can either use a ready-canned function (if your compiler supports it), or to define your definition of "string equality" and execute it. most likely that requires comparing size first, and the individual characters in the string until a mismatch is found, or you have exhausted one of the strings.


text:
Subtraction with doubles returning zero erroneously
I have a function that takes as parameter some doubles and does a subtraction operation on it. However I'm getting a result of 0 when one of the parameter is 0 for some reason.
int calcPID(double current, double desired, double k){
  double diff;
  diff = desired - current;
  Serial.print("desired = ");
  Serial.print(desired);
  Serial.print(", current = ");
  Serial.print(current);
  Serial.print(", diff = ");
  Serial.println(diff);
  int r = (int)diff;
  return r;
}

Output
desired = 250.00, current = 1.69, diff = 248.31
desired = 250.00, current = 0.00, diff = 0.00

When the current is 0.00 the result (diff) is also 0.00, when it should be 250. Can someone tell me what's going on?

I can't reproduce that.
int calcPID(double current, double desired, double k) {
  double diff;
  diff = desired - current;
  Serial.print("desired = ");
  Serial.print(desired);
  Serial.print(", current = ");
  Serial.print(current);
  Serial.print(", diff = ");
  Serial.println(diff);
  int r = (int)diff;
  return r;
}

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  calcPID (1.69, 250, 42);
  calcPID (0, 250, 42);
}  // end of setup

void loop ()
{
}  // end of loop

That gives expected output of:
desired = 250.00, current = 1.69, diff = 248.31
desired = 250.00, current = 0.00, diff = 250.00

I strongly suspect you are passing NaN (not a number) or Inf (infinity) instead of zero. If you add another test line like this:
 calcPID (1.0 / 0, 250, 42);

Then you get the result:
desired = 250.00, current = inf, diff = inf

Now I know you reported getting zero, but earlier versions of the IDE printed 0 for NaN or Inf. I suggested a change to the way the libraries handle that which has been implemented in more recent versions.
Here, for example.

If this doesn't answer your question, please post a Minimal, Complete, and Verifiable example - like I did above.

I think NaN is probably it because when I compare current > 1 and current <= 1 both came out to false.

dang it i was such a poopoohead before now i get it thnx

You are not providing the input values in the correct type:
calcPID(0.00, 250, 0.0);

will return 0, while
calcPID(0.00, 250.0, 0.0);

will return 250
UPDATE
Here you can get a working test case: it's running on a different processor, so don't expect to behave exactly as the 8bit MCU at Arduino's core.

Is this based on a test, or a source-code reading, or what?  What's the name of the library .cpp and .h files you looked at?  How do you account for implicit type conversion not occurring?

@jwpat7 I didn't look at any library, I just looked at the above code and the only viable option I was able to find is if the OP is expecting type conversion to occur in C as if it was Java. When I posted my answer there was only the calcPID function reported, but now, looking at the updated example I'm more convinced about my answer, so much I updated it with a test.

@Roberto Lo Giacco The difference is, that on Arduino (IDE) are headers for *.ino done before standard C++ compilation
#include <stdio.h> // on *.ino it is done in IDE hidden way
int calcPID(double current, double desired, double k) ; // forward definition, for *.ino it is done in Arduino IDE hidden way
int main()
{
    calcPID (1.69, 250, 42);
    calcPID (0, 250, 42);
    calcPID (0.0, 250.0, 42);
    return 0;
}

int calcPID(double current, double desired, double k) {
  double diff;
  diff = desired - current;
  printf("desired = %5.2f, current = %5.2f, diff = %5.2f, true = %i\n", desired, current, diff, diff > 0);
  int r = (int)diff;
  printf("desired = %5.2f, current = %5.2f, diff = %i, true = %i\n", desired, current, r, r > 0);
  return r;
}

This compiles and executes on your machine well a gives correct result same as @Nick Gammon have.
Without the definition int calcPID(double current, double desired, double k) ; standard C assumes definition with ints and makes different conversions, which leads to your "incorrect" result. So the result depends on forward definition, which Arduino does behind scene. But for *.cpp and *.h it may be different, so it would be interesting, how bakalolo organized his code.


text:
I2C communication, wrong response
With reference from http://www.gammon.com.au/i2c I tried the example there. However I am getting the wrong response and readings. At startup the Master will request for slave address. I should get a reading of "8" but I don't get it. Subsequently, A0 on the slave is connected to a miniature solar panel, that I have tested and it is working, however I keep getting a value -1 from it. No doubt I did modify a little bit to suit my inputs not sure if what I did affected the program.
This is the master code:
    #include <Wire.h>

const int slaveAddressA = 8;

enum {
  cmd_slaveAddress = 1,
  cmd_read_A0 = 2,
  cmd_read_A1 = 3
};

void sendCommand_toSlaveA (const byte cmd, const int responseSize)
{
  Wire.beginTransmission(slaveAddressA);
  Wire.write(cmd);
  Wire.endTransmission();

  Wire.requestFrom(slaveAddressA, responseSize);
}

void setup() {

  Wire.begin();
  Serial.begin(9600);

  sendCommand_toSlaveA(cmd_slaveAddress, 1);

  if(Wire.available())
    {
     Serial.print ("Slave address is: ");
     Serial.println (Wire.read (), DEC);
    }
  else
    {
     Serial.println ("No response to slave address request");
    }

}

void startupTest() {
  Wire.beginTransmission(slaveAddressA);

}

void loop() {

  int val;

  sendCommand_toSlaveA(cmd_read_A0, 2);
  val = Wire.read();
  val <<= 8;
  val |= Wire.read();
  Serial.print("Value of A0: ");
  Serial.println(val, DEC);

  delay(500);

}

This is the slave code:
#include <Wire.h>

const byte my_address = 8;

enum{
  cmd_address = 1,
  cmd_read_A0 = 2,
  cmd_read_A1 = 3
};

char command;

void setup() {

  command = 0;

  pinMode (A0, INPUT);
  digitalWrite (A0, LOW);  // disable pull-up
  pinMode (A1, INPUT);
  digitalWrite (A1, LOW);  // disable pull-up

  Serial.begin(9600);

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

void loop(){
  //everything is done using interrupts
}

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

void sendSensor (const byte which)
{
  int val = analogRead (which);
  byte buf [2];

    buf [0] = val >> 8;
    buf [1] = val & 0xFF;
    Wire.write (buf, 2);
}

void requestEvent ()
{
  switch (command)
  {
    case cmd_address: Wire.write(0x55); break;   // send slave address
    case cmd_read_A0: sendSensor(A0);   break;   // send A0 value
    case cmd_read_A1: sendSensor(A1);   break;   // send A1 value

   }

}

Also I'm wondering if I have to add a "Wire.begin(8);" at the slave program setup. ---------------------------I would like to know what did I do wrongly?
UPDATE: The 2 boards are now communicating with one another. However, requested address gives a '85' instead of an '8'. As for input A0, for example it should show '700' with a little bit of variant, but now it shows a repeated pattern of e.g '0 0 0 400 500 800 1040 1040 1040 800 500 400 0 0 0'

A possible problem is that you are doing an analogRead inside an ISR. ISRs are supposed to be fast, and an analogRead will take over 100 µs. Try doing the analogRead inside loop, and just send the latest reading in the sendSensor function. My (main) computer is currently doing an operating system upgrade, so I can't test this right now.

I'm wondering if I have to add a "Wire.begin(8);" at the slave program setup. - you did that, since my_address is 8.

Regarding my first comment, it looks like my code that you referenced does that as well (grin).

@NickGammon for this case I would like to know for void sendSensor (const byte which) { int val = analogRead (which); in the slave code, where is the which parameter passed?

Here: sendSensor(A0);

As Jot mentioned below, you are in fact sending 85 for the slave address: Wire.write(0x55). You should send: Wire.write(my_address); In my example that was not the I2C address (we know that after all) but an identifier - it was just an example anyway.

Subsequently, A0 on the slave is connected to a miniature solar panel, that I have tested and it is working - really? Can you show a schematic? What voltages is the solar panel delivering?

@NickGammon The solar panel delivers ~3V. However after you request for the schematic again, for some reason the ground wasn't connected properly and after amending it now the display values are showing correctly already. Thank you for your help!

When you send 'buf', how do you know that buf[0] is transmitted first and buf[1] is transmitted second ? Not long ago a bug in Wire library was fixed and it is now allowed to use multiple Wire.send() in the requestEvent() function. I suggest to send two bytes in sendSensor() in the Slave without using the 'buf'.
When you request the Slave addres, you send 0x55. That is not the Slave address. Do you receive 0x55 ?
It is not needed to remove pullup resistors from the analog input pins. It is also not needed to set the pinMode for those pins. You can use analogRead() without something else.
Did you connect the GNDs ? And did you connect SDA to SDA and also SCL to SCL. Which Arduino boards do you use ? Do you know that you can start the Arduino IDE twice, each connected to a board and each with its own serial monitor. That way you can work on both sketches at the same time.
As soon as the Slave is running with Wire.begin(8), the Master can run a i2c_scanner and it should find I2C address 8. That is the first test to verify that the I2C bus is working.

I have checked that the master and slave are indeed connected and working. I missed out the GND connection. The slave address i received is 85 instead.

@bytk - Are you saying it is working now? That the whole problem was a missing ground wire?

@NickGammon It is communicating with each other now, but it doesn't communicate correctly. As mentioned now the requested address gives a '85' instead of a '8' as for input A0, for example it should show '700' with a little bit of variant, but now it shows a repeated pattern of e.g '0 0 0 400 500 800 1040 1040 1040 800 500 400 0 0 0'

The slave address is not returned, but the value 0x55. That is decimal 85.
Reading analogRead() while the input is open, can result into anything.


text:
Understanding Soil Moisture Sensor Values
I have soil Moisture sensor inserted into the pot soil, wet in state. (not too damp) and soil moisture sensor is connected to Arduino Mega 2560.
This is the soil moisture sensor I am using:

Soil Moisture Sensor VCC is fed by 4.95 coming from Mega's 5 volt power out and soil moisture signal is connected to A0.
below are the readings
+---------------------+-------------------+-----------------------+
| timeStamp           | pot1_soilMoisture | pot1_avg_soilMoisture |
+---------------------+-------------------+-----------------------+
| 2017-01-26 14:31:19 |               825 |                    80 |
| 2017-01-26 14:32:19 |               816 |                    80 |
| 2017-01-26 14:33:20 |               828 |                    83 |
| 2017-01-26 14:34:20 |               826 |                    82 |
| 2017-01-26 14:35:20 |               820 |                    79 |
| 2017-01-26 14:36:20 |               833 |                    83 |
| 2017-01-26 14:37:20 |               463 |                    46 |
| 2017-01-26 14:38:21 |               546 |                    32 |
| 2017-01-26 14:39:21 |               156 |                    26 |
| 2017-01-26 14:40:21 |               157 |                    22 |
| 2017-01-26 14:41:21 |               509 |                    23 |
| 2017-01-26 14:42:22 |               204 |                    25 |
| 2017-01-26 14:43:21 |               226 |                    26 |
| 2017-01-26 14:44:21 |               190 |                    30 |
| 2017-01-26 14:45:22 |              1023 |                    84 |
| 2017-01-26 14:46:22 |               604 |                    83 |
| 2017-01-26 14:47:22 |               773 |                    79 |
| 2017-01-26 14:48:22 |              1023 |                    80 |
| 2017-01-26 14:49:23 |               599 |                    77 |
| 2017-01-26 14:50:23 |               766 |                    82 |
| 2017-01-26 14:51:23 |               579 |                    81 |
| 2017-01-26 14:52:23 |               729 |                    74 |
| 2017-01-26 14:53:24 |              1023 |                    82 |
| 2017-01-26 14:54:24 |               795 |                    80 |
| 2017-01-26 14:55:24 |               651 |                    77 |
| 2017-01-26 14:56:24 |               765 |                    83 |
| 2017-01-26 14:57:25 |              1023 |                    81 |
| 2017-01-26 14:58:25 |                 0 |                    60 |
| 2017-01-26 14:59:25 |               921 |                    30 |
+---------------------+-------------------+-----------------------+
1439 rows in set (0.02 sec)

I got three kind of readings of the sensor:

pot1_soilMoisture reading from 825 to 833 is when the sensor was dipped in water.
pot1_soilMoisture reading from 463 to 190-1023 is when soil moisture sensor was in air.
pot1_soilMoisture reading from 604 to last 921 is when soil moisture sensor is in soil. The soil is moist/wet.

I don't understand how to be definitive state of soil with such values?

I had this same problem when I began experimenting with soil moisture readings. I noticed that the readings from the sensor can vary widely when not hooked up correctly, or when other nearby objects are somehow interfering.
For instance when I put a SparkFun breakout similar to yours in dry soil and continuously take readings every 50ms, the signal oscillates from 0 to 50, and simply touching the soil with my finger can affect the signal due to the electricity in my body. If you have a metal pot on a metal table, that could be affecting your readings. There's a lot to consider!
However, once I water the soil and let it soak in, the reading generally becomes much more stable. Below I included a real-time plot using a plant I watered about 24 hours ago. Here's how I set up my soil moisture sensor, including code. The readings are taken every 60s and the plotter repeats the old reading until a new one is taken. There's very little deviation when all connections are secure and the soil moisture is evenly distributed.

In general, the specs for the sensor will inform you on what kind of signal to expect. Based on your sample data I suspect yours is a 10-bit signal from 0-1023, so 800 range means the soil is quite moist. If you just watered the plant, then the water content around the sensor will change as it seeps through the soil, leading to fluctuations when measuring. Give the soil a few hours to absorb the moisture and try measuring again.

Oh well thanks, I will use this strategy and see how it goes however, I have hooked up a realtime clock module using which I give water to pot for 10 seconds(enough for small pot) twice a day . And I think there really isn't need to set up a powering solenoid to water pot based on soil moisture . Thanks for your answer

I agree, for potted plants this is over-doing it. Still useful to learn how the sensor works. I think if you have a large number of plants in a raised bed this is a more useful technique for regulating water automatically.

Cool, now I have setup as per your answer, but millis instead of delay and now I am turning on soil moisture sensor using digital pin 8 . But so far I still can't make out huge distinction between when it is dipped in water or out in air or in soil

Do you have a second sensor to test? Or any other component that could use the same pins on your Arduino, so that you can verify that something works as intended? It's difficult to troubleshoot without some sort of reliable baseline. I did a search for your sensor and the example output on the official tutorial page seems to wildly fluctuate just like your sample data. The page doesn't provide specs so we can't be sure how it should be powered. Perhaps you could try powering with 3.3V instead of 5.

for experimenting I connected it to Arduino Uno and got this result : http://pastebin.com/1jDV0kjv with delay of 600 milieseconds, I found lower the delay more incorrect values but it seems to oscillates which I feel needs calibration that I dont know how to do it !

The values in your pastebin are the min/max of the sensor, so it sounds like there is a hardware problem. Is it possible for you to remove the header pins and temporarily place wires directly in the terminals of the sensor? Are you sure you're providing 5V to VCC? GND is secure? You can use A0 to reliably collect data from a different sensor? Perhaps your sensor needs more delay between powering on and taking a reading. Mine was fine with 10ms delay, but components and materials vary by manufacturer and it might make a difference.


text:
how does a bluetooth on android works and what are the best alternative in saving data receive from bluetooth?
Can anyone confirm this for me although I have tested it myself but when I send a string of data from my android app and send it to arduino say for example data = bluetoothPort.read(); inside an if statement then when I try to use the data in another if statement for example Serial.print(data); inside another if statement it will only show a blank line which let me believe that none of the data are saved. also when a receiving a string of data for example a string of abcde and send it to arduino for example data = bluetoothport.read() and then Serial.print(data) the serial monitor shows abcde as expected but what really happens is data has the value of a then prints then replace by b then print then replace by c then print then replace by d then print then replace by e. Am I wrong or somehow right? are there any work around or parts I need that will make me store data as a whole so that I can use it for other thread or a better code to store string of data?
#include <IRremote.h>
#include <SoftwareSerial.h>

SoftwareSerial bluetoothPort(4,5);
const int RECV_PIN = 12;
const int SEND_PIN = 13;

IRsend irsend;
IRrecv irrecv(RECV_PIN);

decode_results results;
char data;

void setup()
{
   bluetoothPort.begin(9600);
   Serial.begin(9600);
   irrecv.enableIRIn();
}

void loop()
{
   if (bluetoothPort.available() > 0)
   {
       data = bluetoothPort.read(); //received bluetooth data from android
   }

   if(irrecv.decode(&results))
   {
       irreceived(); //received IR code from a remote then sends it to my android
       irsend.sendNEC(data, 32)
   }
 }

 void irreceived()
 {
     Serial.println(results.value, HEX);   //receive value of 489010
     bluetoothPort.println(results.value, HEX); //send value to android
     irrecv.resume();
 }

so the above is a simple sketch that receive data from a remote controller then send it to my android app then when I resend it back to my arduino I would like the data to be able to receive all the data instead of saving it per letter/number and also be able to store it for other statement to use.

Serial communications only consist of one character. That is what serial is - the sending of one character at a time.
How you then deal with those characters, combining them into strings, interpreting them as numbers, whatever, is completely up to you to program.
There is no such thing as a string in serial communications. There is only the character.
The Arduino API has a few (badly implemented IMHO) helper functions that can get a whole string (kinda), but it is much better (both from a learning perspective and an implementation perspective) to do it yourself.
I have a little tutorial here that may help you get to grips with it.

This works great for me at best even and I love it. I got one question though... I am developing a universal remote control Arduino paired with Android app and thanks to your help I was able to receive the code sent from a remote control and send to the android app and on a push of a button the Arduino received(thanks to your help) and sends using IR emitter... the usual way to send was irsend.sendNEC(0x40BFEA15, 32); but when I do this irsend.sendNEC(buffer, 32); the buffer has 0x40BFEA15 value it does not work? any idea or tips or work around on how to make it work?

You have a string, and you need a 32-bit unsigned integer. You need to parse the string and convert it to an integer. strtoul() may help you there.

Through trial and error I have manage to figure out that I need when I do this long number = 0x40BFEA15; then this irsend.sendNEC(number, 32) it works so the next question is... how do I convert the received Bluetooth data on a char bufferthat contains 0x40BFEA15 into a long that will retain the value ofbuffer`..? or is there other way to receive bluetooth data as a long instead of a char.? silly question but I know I am near to finish with this one.

I told you the function to use just now.

just did this long data = strtoul(buffer, NULL, 16); then Serial.print(val); and it gives me a combination of numbers so I did this Serial.print(val, HEX); and gives me 40BFEA15 and was expecting the result to be 0x40BFEA15, it omits the first two character :"0x" am I doing it wrong?

0x is an instruction to the compiler to say "The following numbers are hexadecimal". Internally everything is just binary. Even your 40BFEA15, which the Arduino Serial.print() function, when passed the HEX parameter, displays in a human readable format using hexadecimal notation.


text:
Is there a way to keep a program on the Arduino after uploading new sketches?
I am looking for a way to keep a program on my Arduino Nano 3.0, after uploading new sketches on it. I would like to have a program on it that will control th screen and buttons at it. The user will choose one of the programs displayed on the screen and execute/pause/stop them. These programs will be uploaded on the Arduino, while the previous programmes stay.
If you are familliar with the Lego Mindsdorm microcontroller, you probably know waht I am looking for.
Is there a way to do that.

You want something like a dual boot arduino

looks to me like you just need one massive program which you flash onto the arduino, and theres a simple display and buttons that when it starts up allows you to select which "program" to run. Each time you add new programs its still the same big single program, but with more functions and you'd have to add more options to the GUI list.

@Gerben, you continue to astound me.  I thought you were just joshin' until I read that Hackaday.  +1

I have something similar - a text-to-Morse routine - that I use sometimes.  While it might be fun to have it always-resident it was just as easy to make it a function and then append it to my sketches as-needed.  The heavy lifting is finished, and I don't need it for every program, but can bolt it on quite quickly.

I'm not familiar with Lego Mindstorm, but I think I understand what you want and I am certain there is a way to do it, but I don't think it will be easy or even practical and I can't tell you exactly how to do it.
I'm pretty certain there will be a way to load a 'module' into memory and then make the program call that address.  I haven't got a clue how you would do it though, sorry.  GCC doesn't have a concept of DLLs like window does, but it does have shared libraries.  Or you might look at just reading a block of memory in.
Other approaches might be to have all the 'programs' as functions within you main program and call them depending on the user's input.  You can only do this if the 'programs' are small enough.
If you can refactor your 'programs' to extract the common code into functions and then have a data file (which could be read at runtime) that called the functions for each of your programming.  Basically  invent your own higher level programming language.  This wouldn't work if your code was very different and you could factor it down to a small enough number of functions.
Would it be possible to just have a number of hex files (compiled programs?) all of which have the common screen/button handler in and then have the special code for the appropriate program.  These could all be stored on an SD card and then loaded into memory by a second Arduino (sounds plausible to me, I'm sure someone will tell me whats wrong with that idea.)
An alternative based on the inverse of the above solution would be to have one Arduino to control the screen/buttons and it programs a second Arduino with the specialist code that is connected to the rest of your kit.

You cannot load code into RAM and then call that address: the AVR's Harvard architecture makes it impossible to run code from RAM. You need to load the code into flash, which is quite involved, and normally considered a bootloader's job. You will essentially have to write a custom bootloader. BTW, gcc doesn't support shared (aka dynamically linked) libraries on the AVR platform, only statically linked libs.

A special bootloader and a jump-list to functions in a seperate part of the flash is possible. But it is very impractical. Adding a .h include file to the project with binary compiled code as PROGMEM data (and a jump-list to the functions) might be a challenging job for programmers. That is also very impractical.
Perhaps the best way is to combine a number of normal libraries into a single .zip file which can be installed in the Arduino IDE.

You want something like this using the serial monitor:
if((homeMenuActivated) == true)
{
  Serial.println ("Program Number 1");
}

I am kind of glad you asked this, as I am working on a similar program with arduinos that can do the same thing you want.

The Arduino paradigm uses two programs on the target.  The boot loader and the application.  The processor is agnostic WRT this differentiation and runs the entire code set as one large application.
To put a 2nd application on an embedded processor is feasible. However, you would have to be intimately knowledgeable about how Arduino SDK works as well as the boot loader as you would have to create new features to relocate code normally found at fixed locations.  A rather involved task.
Instead, consider simply adding your utility code to your application code in the Arduino SDK and replace the utility code already on the processor with the new image.

Is there a way to do that.

sure.
one way to do it is to use a pin to indicate which program you want to execute.
uint8_t execution_switch=0;  //execution switch. 0->run setup0()/loop0(), 1->run setup1()/loop1()

void setup(void) {
  pinMode(EXECUTION_SWITCH, INPUT_PULLUP); //execution switch as input + pullup
  execution_switch=(digitalRead(EXECUTION_SWITCH)==LOW)?0:1;
  if (execution_switch==0) setup0(); else setup1();
}

void loop(void) {
  if (execution_switch==0) loop0(); else loop1();
}

you can easily change it to accommodate multiple programs / multiple switch pins, or real time switch, ....


text:
How to skip the first line and output the second?
My question is related to my previous question.
These encoder programs outputs two line per pule/tick.
Here is the part of the code I want to use:
void loop()
{
    // Read the status of the inputs
    debouncerA.update();
    debouncerB.update();

    int8_t EncVariation = 0;

    if (debouncerA.rose())
    { // if input A changed from low to high, it was CW if B is high too
        EncVariation = (debouncerB.read()) ? 1 : -1;
    }
    else if (debouncerA.fell())
    { // if input A changed from high to low, it was CW if B is low too
        EncVariation = (debouncerB.read()) ? -1 : 1;
    }
    else if (debouncerB.rose())
    { // if input B changed from low to high, it was CCW if A is high too
        EncVariation = (debouncerA.read()) ? -1 : 1;
    }
    else if (debouncerB.fell())
    { // if input B changed from high to low, it was CCW if B is low too
        EncVariation = (debouncerA.read()) ? 1 : -1;
    }
//
  if (EncVariation != 0) {

        encoder0Pos = encoder0Pos + EncVariation;

        int degs = (encoder0Pos * 6) % 360 ;

        if(degs<0){ degs = 360 + degs; }

        Serial.println (degs);
   }
}

For three inputs/ticks this outputs like:
6
12
18
24
30
36
But I only need the second ones like:
12
24
36
How can I do that?
(I need it to send the relevant data do a PC.)
I spend so long time on it couldnt find any solution.

This line looks like its a mistake if(degrees<0){ deg = 360 + degs; } is it correct?  You do the calculation of degrees and then start using degs.

was a mistype now i corrected

IF and only IF you want exactly what you have asked for which is alternate lines not to be output then this is a very crude and quick solution.
Outside of loop() add this declaration:
bool skipNextLine = true;  // true skips the odd lines, false skips even lines

And change the end of your code like this:
  if (EncVariation != 0) {
    encoder0Pos = encoder0Pos + EncVariation;
    int degrees = (encoder0Pos * 6) % 360 ;
    if(degrees<0){ deg = 360 + degs; }
    if (!skipNextLine)
    {  // This will skip alternate lines
        Serial.println (deg);
        skipNextLine = true;
    }
    else
    {
        skipNextLine = false;
    }
  }

Just tried it didnt work. It doesnt output anything

Can it be there maybe another   Serial.println (deg); needed before the last if?

should skipNextLine be false at some place?

Blush Whoops.  Thanks Mark for editing it.

Use a static variable to count loop execution and only prohibit the very first of every 3 counts.

I tried to use a variable and odd number selection but couldnt achive.


text:
One of my my buttons is interfering with the other (i think)
So for school i have to make a code for my arduino, that let's me turn 4 led's on and off (as an input) with 2 buttons (one to select the led, one to toggle the led), run the inputs trough a logic circuit and based on the output toggle a fifth led on or off. The only thing i can't manage to get working is the button that turns the leds on and off. My main problem is that if i want to let the second button (setButton) do anything, i have to hold it down and press the other button which then kind off controls setButton & inputButton at the same time..
so my main question: How do i make my setButton work in this script..
(sorry for the Dutch comments inbetween)
int led1 = 5;                    // van links naar rechts: led 1
int led2 = 6;                     //led 2
int led3 = 9;                    //led 3
int led4 = 10;                     //led 4
int ledRuben = 3;                  //led 5 (geeft de output aan)
const int inputButton = 7;         //select a led/input mode on
const int setButton = 8;       //toggle a led
int buttonState1;                 //inputButton state
int buttonState2;                 //setButton state
int pushCount = 0;                //how many times the button is pushed (used to select the right led)
int lastButtonState1;           //last inputButton state
int lastButtonState2;           //last setButton state
int inputLeds[4] = { 0, 0, 0, 0 };  //used to save the signal needed for the logic gates
char currentLed[4] = { led1, led2, led3, led4 }; //used to select a led
int i16, i09, i61, i34;           //inputs
int t16, t09, t61, ruben;          //in between and end signals
int ledState = false;              //current led on or not

void setup() {
    Serial.begin(9600);     // hoe veel data er verstuurd wordt.

    pinMode(ruben, OUTPUT);
    pinMode(led4, OUTPUT);
    pinMode(led3, OUTPUT);
    pinMode(led2, OUTPUT);
    pinMode(led1, OUTPUT);
    pinMode(inputButton, INPUT);
    pinMode(setButton, INPUT);
}

void loop() {
    buttonState1 = digitalRead(inputButton);
    buttonState2 = digitalRead(setButton);

    if (buttonState1 != lastButtonState1) {

        if (buttonState1 == HIGH && pushCount == 0) {
            analogWrite(led1, 125);
            analogWrite(led2, 125);
            analogWrite(led3, 125);
            analogWrite(led4, 125);
            Serial.println(pushCount);
            pushCount = pushCount + 1;
            delay(200);

        }
        else if (lastButtonState1 == HIGH && pushCount >= 1 && pushCount <= 4) {

            if (buttonState2 == HIGH && lastButtonState2 == LOW && ledState == false) {
                analogWrite(currentLed[pushCount], 255);
                inputLeds[pushCount] = 1;
                Serial.println("test 2");
                ledState = true;
            }

            else if (buttonState2 == HIGH && lastButtonState2 == LOW && ledState == true) {
                analogWrite(currentLed[pushCount], 1);
                inputLeds[pushCount] = 0;
                ledState = false;
            }

            Serial.println("test");
            Serial.println(pushCount);
            pushCount = pushCount + 1;
            lastButtonState1 = buttonState1;

        }

        if (buttonState1 == HIGH && pushCount >= 5) {
            Serial.println(" currentLed > 4;");
            pushCount = 0;
            delay(200);
            return; 55
        }

        circuit();                                        //zorgt dat void circuit gerunt word.
        if (ruben == 1) {                                  //Als output ruben 1 is, wordt ledRuben aangezet.
            analogWrite(ledRuben, 255);
        }
        else {                                            //als output ruben 0 is zet ledRuben uit
            analogWrite(ledRuben, 1);
        }

    }

    lastButtonState1 = buttonState1;
}
void circuit() {                   //logic gates
    t16 = !i16;                     //Dit is de NOT gate, maakt van output 1 een 0, en andersom
    t09 = t16 && i09;               //Dit is de AND gate, als alle inputs 1 zijn, is de output 1
    t61 = i61 || i34;               //Dit is de OR gate, alleen als alle inputs 0 zijn, is de output 0
    ruben = !(t09 || t61);           //Dit is de NOR gate, alleen als alle inputs 0 zijn, is de output 1

    return ruben;
    5
}

You might want to look at putting you LED pin numbers into an array, or rather using the one you already have.  led1 is the same as currentLed[0]  Apart from the type of the array is not strictly correct.

Thanks for the tip, i gues you're right because now i'm just using more variables then needed. But do you have any idea how to fix the button issue?

lastButtonState2 never changes in your code.

@gerben i added lastButtonState2 = buttonState2; to both the if and else if that should toggle the button, it didn't change anything tho..

Can't you just move the button2 code out of the if button1 block, and directly into the loop function?

lastButtonState2 still never changes in your code!

@gerben thanks to you i've fixed it! i put
if (buttonState1 != lastButtonState1) {
around the button2 if/else, ending with
lastButtonState2 = buttonState2;
}

Do you use a pullup or pulldown resistor for your buttons? If not, then add one or use pinMode(..., INPUT_PULLUP). Second, you probably have to debounce your buttons (by software or hardware), Google is your friend to find out how.


text:
Define a string with single quotation marks?
This is kind of a short question. All I want to know is, if I can define a string using single quotation marks ('), instead of the regular ones("). I want to use it in a function like this:
print('Hello world');
I unfortunately do not have an Arduino nearby so I cannot test it myself.

single quotes identify a single character, while double quotes create a string literal

Could you please explain what you want to achieve rather than your likely misguided idea about how to achieve it (i.e. removing quotes)?

I am making an extensions for a program that requires Arduino code inside the program, but if I write the quotation marks, the debugger reports an error, because there are quotation marks inside quotation marks.

Then you need to update your extension to properly escape the arduino code so that reserved/special characters in the code are not interpreted by the non-arduino debugger. How to do that depends greatly on the program you are extending, which you have not named.

It's a bit unclear to me what you're trying to do, but perhaps just escaping the "s will achieve what you want.  In C, the way to escape something is with a , so for example char myString[] ="\"\""; would give you a string containing two "s.

You are still not being clear about what you are trying to achieve. What program? Language? Platform? You may want to check out these questions on stack overflow: “#include” a text file in a C program as a char[], and Embed data in a C++ program.

No, you can't.  'x' defines a single character or integer (note: 'ab' is a two-byte single value [integer] made up from the ASCII values of both characters).
To include " within a string you have two options:

Escape the " with \, as in: char foo[] = "He said \"Hello there\".";
Use "raw strings" if the compiler is configured to support it: char foo[] = R"(He said "Hello there".)";

Option 1 is the most portable since it doesn't require compiler support for modern C++ standards. However it's the hardest to read, especially when you get lots of escapes in the same string.
You can make it more readable by defining QUOTE:
#define QUOTE "\""

char foo[] = "He said " QUOTE "Hello there" QUOTE ".";

No, you cannot. This rules comes from the basic C++ syntax on which the Arduino platform is built.

Is there a way to define it without the qoutation marks?

Only very convoluted ways.

Actually, C++ raw string literals are easy to use (ref 1, 2); the only convoluted bit is adding a  -std=c++11 or -std=c++0x switch to IDE compiler options.


text:
MCP23017 and stepper motors
I am new to Arduino and programming and I am muddling along with some tutorials, I have a little project I am working on. It's basically an LCD screen with 5 buttons, a simple menu system that will control some stepper motors.
Now I have been able to both program and run the LCD from the Arduino and program and run the stepper motors. This was pretty straightforward due to the abundance of information. Now due to the small number of inputs on the Uno I knew I would need to expand on these so I bought some MCP23017 I/O expander chips.
Setting up the LCD on the MCP23017 was easy enough again due to the lots of tutorials and libraries, but I just cannot figure out how to work a stepper motor via the MCP23017. I am using 28BYJ-48 stepper motors and ULN2003 stepper driver boards. Yes I know cheap and nasty but they are fine for my task.
So I am basically looking for a little help on how to run stepper motors through the MCP23017 chips. I have the wiring and connections set up, just need some help on the programming.

I couldn't understand what the problem is, since you already managed to connect an LCD to it... Anyway...
To run a stepper motor you have to first define the control technique. AFAIK there are a few, but the ones I know are

full step
rotated full step
half step
microstep

Your motor is a unipolar motor. You have to connect the common wire to +5V, the other ones to one transistor of the ULN2003, and each transistor should be directly controlled by one pin. These are called phases (and let's call these PH1, PH2, PH3 and PH4).
Now for the explanation I'll use some tables. In these tables, each row is a step, each column a pin, and if there is a X the transistor should be on during that step.
Now, the full step technique is the simplest one. It consists of four phases:
Step PH1 PH2 PH3 PH4
  1   X
  2       X
  3           X
  4               X

As you can see, you just have to power each phase through each step. Cycling the steps as 1-2-3-4-1-2-3... will rotate in one sense, 4-3-2-1-4-3-2... in the other.
The rotated full step technique powers two phases at each step:
Step PH1 PH2 PH3 PH4
  1   X   X
  2       X   X
  3           X   X
  4   X           X

This usually gives a higher current consumption, but also higher torque.
The half step is a mix of the two:
Step PH1 PH2 PH3 PH4
  1   X
  2   X   X
  3       X
  4       X   X
  5           X
  6           X   X
  7               X
  8   X           X

As you can see, the number of steps per cycle is twice as much. This means that you can increase the accuracy (since a 32 steps/rev motor will now require 64 steps to perform a complete revolution).
The microstepping technique requires a different hardware, since it better controls the current in the phases to further divide each step in different steps.
Anyway, a basic implementation using the MCP23017 and the full step technique can be this one. I used Adafruit's library, but you can change using whatever library you chose or the direct calls you used for the LCD.
#include <Wire.h>
#include "Adafruit_MCP23017.h"
Adafruit_MCP23017 mcp1;

const byte PH1 = 0, PH2 = 1, PH2 = 3, PH3 = 4;

const byte phasesTable[][] = {
    { HIGH, LOW,  LOW,  LOW  },
    { LOW,  HIGH, LOW,  LOW  },
    { LOW,  LOW,  HIGH, LOW  },
    { LOW,  LOW,  LOW,  HIGH }
    };

int currentPosition, targetPosition;
unsigned long previousMillis;
const int StepDelayMs = 100; // delay between steps

void setup()
{
    mcp1.begin(0);
    mcp1.pinMode(PH1, OUTPUT);
    mcp1.pinMode(PH2, OUTPUT);
    mcp1.pinMode(PH3, OUTPUT);
    mcp1.pinMode(PH4, OUTPUT);
    currentPosition = -1; // force first update
    targetPosition = 0;
}

void loop()
{
    void updatePosition(); // function prototype
    updatePosition(); // execute the update

    // ----------------------
    // Functional part
    // ----------------------
    // Edit this code according to your application
    // changing the targetPosition variable (DON'T CHANGE
    // the currentPosition variable

    if (currentPosition == targetPosition)
    {
        if (targetPosition == 50)
            targetPosition = 0;
        else
            targetPosition = 50;
    }
}

void updatePosition()
{
    if ((millis() - previousMillis) > StepDelayMs)
    {
        previousMillis += StepDelayMs;

        if (targetPosition != currentPosition)
        {
            if (targetPosition < currentPosition)
                currentPosition--;
            else
                currentPosition++;

            byte phIdx = currentPosition % (sizeof(phasesTable) / sizeof(phasesTable[0]));

            mcp1.digitalWrite(PH1, phasesTable[phIdx][0]);
            mcp1.digitalWrite(PH2, phasesTable[phIdx][1]);
            mcp1.digitalWrite(PH3, phasesTable[phIdx][2]);
            mcp1.digitalWrite(PH4, phasesTable[phIdx][3]);
        }
    }
}

NOTE: I did not test this code, but I'm pretty confident it should work. Maybe there are some bugs left, however, but you should be able to correct them yourself.
The program behaves this way: every 100ms (you can go a bit faster, but sometimes you can lose steps, so you have to test it) it checks if the motor has reached the final position he needs to reach (targetPosition). If it has, the program does nothing. Otherwise it moves one step towards the target. All this is managed in the updatePosition function.
You have to call this in the loop (and make a NON BLOCKING loop, otherwise also the motor will block). In the loop, modify the target position that you need to reach (the part I called Functional part). In the example, the program moves the motor 50 steps back and forth (so 50 steps in one direction, then back to the origin, then to 50 and so on).
The control technique used is the full step. If you want to use another, change the phasesTable constant variable.
If you need more functionalities, there are a lot of libraries for the steppers. Just use the proper commands to edit the pins on the MCP rather than the ones on the board.


text:
Melzi 2.0 Board Firmware Upload problem
I'm trying to flash the repetier Firmware to my Prusa i3 3D Printer, which uses Melzi 2.0 board. I uploaded it successfully 2 days ago with same settings  but now is failing always.
@avrdude -p m1284p -b57600 -c arduino -P COM%x% -e -U flash:w:%filename%.hex
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.02s
avrdude: Device signature = 0x1e9705 (probably m1284p)
avrdude: erasing chip
avrdude: reading input file "newa.hex"
avrdude: input file newa.hex auto detected as Intel Hex
avrdude: writing flash (114266 bytes):
Writing |                                                    | 0% 0.00s
avrdude: stk500_paged_write(): (a) protocol error, expect=0x14, resp=0x64
avrdude: stk500_recv(): programmer is not responding

How do I solve this problem?

The Electronics Stackexchange question avrdude error - stk500_paged_write() protocol error has answers that suggest three different tactics for protocol errors:
• Upgrade the Arduino IDE from 1.00 to 1.05, or install "AVR-GCC Toolchain" via Homebrew;
• Disconnect everything from TX / RX (Arduino digital pins 0 and 1);
• Use shorter or different USB cables, hooked to a USB port on computer instead of on a hub
I've seen dozens of answers here on arduino.stackexchange with such suggestions, as well as webpages elsewhere with ideas like those in an answer to AVRDUDE Error (Arduino Leonardo).
You could go through this list of programmer-is-not-responding arduino.stackexchange questions, and report back on what works and what doesn't:
• "avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program,
• How do I resolve "avrdude: stk500_recv(): programmer is not responding"?,
• avrdude: stk500_recv(): programmer is not responding after serial,
• avrdude: stk500_recv(): programmer is not responding + avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x47,
• avrdude: stk500_rcv :programmer is not responding,
• Arduino Nano Update failure - avrdude: stk500_recv(): programmer is not responding,
• avrdude: stk500_getsync(): not in sync: resp=0x00,
• Arduino Uno cannot upload any sketch: avrdude: stk500_recv(): programmer is not responding,
• "avrdude: stk500_recv(): programmer is not responding" when uploading sketch,
• Arduino not working / not uploading [duplicate],
• Problems uploading sketch to Arduino Due,
• FTDI stdk 500k not responding,
• Arduino Prototype on Breadboard: "avrdude: stk500_recv(): programmer is not responding",
• Arduino Nano - programmer is not responding,
• How do I resolve "avrdude: stk500_recv(): programmer is not responding"?,
• Arduino not in sync unique error,
• Arduino nano stopped working,
• Not in sync: resp=0x00,
• How to troubleshoot the Arduino Mini and Arduino usb2serial?,
• Atmega328P-PU: Programmer is not responding,
Note, click the “see more linked questions…” link in the sidebar to get a nice webpage with the above list and the opening lines of each question.


text:
Which timer does Arduino Nano use for each PWM pin?
I'm unable to find which Timer controls each PWM pin (3, 5, 6, 9, 10 and 11) in an Arduino Nano Board (ATmega328).
Any guesses?
Thanks in advance,
Eduardo

This is a good pinmapping picture of the Nano : www.pighixxx.com/test/portfolio-items/nano/
A timer has sometimes two outputs, A and B. The pins with OC0A and OC0B are timer outputs of Timer0. OC1A and OC1B are Timer1, OC2 and OC2B are Timer2.
Everything is also in the datasheet of the ATmega328P, but that picture is a lot easier.


text:
Is there an advantage to set pinmodes via bitmask and register?
I'm working with the capacitive sensor library currently and the author does not use digitalWrite(), but instead sets the output of a pin via functions changing the bitmasks of certain registers:
https://github.com/PaulStoffregen/CapacitiveSensor/blob/master/CapacitiveSensor.h#L39
I looked into the OneWire library description those functions come from, but I still can't see any advantage over simply using the standard way Arduino proposes.

Up to 10X faster! In some applications this is important for timing, for instance, 1-Wire where the timing is faster what can be produced with digitalWrite().

Can you explain why it works faster? Or better said, why is the classical approach so much slower?

See the source of digitalWrite(): there is quite a lot going on here, compared to a single machine instruction with direct port access.

It is possible to achieve both high abstraction and performance without resorting to direct port manipulation. One example is Cosa which is 5-10X faster than Arduino core but at the same time high abstraction and rich functionality; See https://github.com/mikaelpatel/Cosa and for instance https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/GPIO.hh. There are also benchmarks https://github.com/mikaelpatel/Cosa/blob/master/examples/Benchmarks/CosaBenchmarkGPIO/CosaBenchmarkGPIO.ino.

The “classical” approach is direct port access. It has been the standard way of programming AVRs way before Arduino even existed.

I still can't see any advantage over simply using the standard way Arduino proposes.

The standard functions are slower.

There is a very good reason that the Arduino "standard" functions digitalRead, digitalWrite and pinMode are slower than direct port manipulation: They take a variable as the pin number and value to set it to.
This means that the functions in question then have to do a table lookup to translate the pin number to a port number and a bit position. The advantage is you can write code like this:
for (int i = 0; i < 20; i++)
  {
  pinMode (i, OUTPUT);
  digitalWrite (i, LOW);
  }

That's quite handy!
However if you have timing-critical code, and you happen to know the pin number in advance, and it won't change, then you can use a library digitalWriteFast which can optimize that for you. The library cleverly detects if a particular call is given a variable or constant. If a constant then it does the faster port manipulation method (this can now be done at compile-time to find the port and bit number).
There seem to be a few different versions of this library around. The one I linked above fails if you don't pass a constant, others fall back to just doing a digitalWrite (etc).
Inside the library there is code like this:
if (__builtin_constant_p(P) && __builtin_constant_p(V)) { \

In other words it uses a compiler directive to detect if the argument (P = pin, and V = value) are constants or not.

You can also, of course, do direct port manipulation but be warned that if you do then your code becomes pretty non-portable. Try going from an Atmega328 to an Atmega16U4 and the ports and bit positions will change.

Another library: https://code.google.com/archive/p/digitalwritefast/downloads

With direct access to the pin registers, there is no need to call a function (since the digitalWrite function itself calls some functions), which is slower than manipulating the bits directly. You are also able to set the bits of several ports at the same time.
The manipulation of port registers is described in the PortManipulation chapter. It states:

Generally speaking, doing this sort of thing is not a good idea

However it could/should be used for time-sensitive applications. This is an interesting read on this topic.

Is there an advantage to set pinmodes via bitmask and register?

I can name a few:
1) speed - I benchmarked the arduino pin ops vs. direct register ops here;
2) size - the code size is considerably bigger with the arduino library;
3) portability - the bitmark approach is supported by any C-compiler;
4) convention - i'm used to the bitmask approach and wrote all of my libraries around it;
...
as i'm sure others have their reasons to use the bitmasks.

The reason for using direct port operations in capacitive-sensor code is that such code works ok, and slower code won't.  Here's an extract from CapacitiveSensor.cpp in Stoffregen's CapacitiveSensor code:
int CapacitiveSensor::SenseOneCycle(void) {
    noInterrupts();
    DIRECT_WRITE_LOW(sReg, sBit);   // sendPin Register low
    DIRECT_MODE_INPUT(rReg, rBit);  // receivePin to input (pullups are off)
    DIRECT_MODE_OUTPUT(rReg, rBit); // receivePin to OUTPUT
    DIRECT_WRITE_LOW(rReg, rBit);   // pin is now LOW AND OUTPUT
    delayMicroseconds(10);
    DIRECT_MODE_INPUT(rReg, rBit);  // receivePin to input (pullups are off)
    DIRECT_WRITE_HIGH(sReg, sBit);  // sendPin High
    interrupts();

    while ( !DIRECT_READ(rReg, rBit) && (total < CS_Timeout_Millis) ) {  // while receive pin is LOW AND total is positive value
        total++;
    }
//...
}

The general idea is that a source pin and receive pin are driven low, briefly, to discharge associated capacitance.  Immediately upon changing the receive pin to an input we want to change the source pin high, and begin counting the total number of cycles that elapse before the receive pin charges to above about 2.5 V.
Code using digitalWrite(), digitalRead(), and pinMode() calls at four to five microseconds each would take so long to switch from output to input, or to read the source pin and receive pin, that the charging event would be over before the count loop began.


text:
Absolute encoder vs Accelerometer for calculating angles
I've been toying with this idea for a while and after some thorough research I'm more than happy that the project is realistic. However I'm in need of some direction in terms of the sensors I should be using.
There will be 3 arms all connected together (Like a poor mans Microscribe). I want to read the angle between each arm and use that info to calculate the final X and Y coordinates of the final end point on the arm.
I've looked closely into forward kinematics in robot arms and understand the principles are very much the same.
I've narrowed it down to Absolute encoders or accelerometers. Unfortunately I just can't find enough documentation about how to use the encoder with Arduino. There's plenty on using an accelerometer but I can't imagine the accuracy would be as good as the encoder.
I'm hoping to get the X and Y coordinate accuracy within +/- 0.5mm. Is this accuracy feasible?
The diagram attached shows the basic principle and formula I will use.

------EDIT-----
Thanks for the info everyone! Seems like this is going to be a little trickier than I originally thought. I've found a project achieving something very similar, however there's no mention of it's accuracy. http://fablab.ruc.dk/diy-digitizer/
Any ideas as to what sort of accuracy he could be achieving? I understand the length of the arms are considerably shorter than mine which must help a huge deal.

If your angle range is suitably limited using simple potentiometers is probably the easiest option.

Just a comment: why do you need a sensor? Can't you use stepper motors (which will provide better torque, AFAIK) and so avoid the need for knowing the position (you just need to zero the arm every time you boot it)

@frarugi87 stepper motors rarely have more than 200 steps per resolution. Microstepping can increase this by a factor of 16 at the cost of lower torque. That gives 0.11 degrees per step, his target accuracy would require him to gear the motor down by at least a factor of 6 to give the required accuracy. Also he would need a motor with an encoder attached in order to detect slips, if you care about absolute accuracy you can't assume a stepper did exactly what you requested.

I'm hoping to get the X and Y coordinate accuracy within +/- 0.5mm. Is this accuracy feasible?

I'm only going to consider the A1 in your diagram since the accuracy of that will have the greatest impact in the final position. For the other angles any errors will have a smaller impact on the final position accuracy.
Take the most simple case, the arm is in a straight line almost completely in the X direction.
You want a Y reading of +/- 0.5 mm with an arm length of 1400 mm. That will require an angular accuracy of +/- 0.02 degrees.
Assuming you have a maximum travel of 90 degrees and you scale things such that your full ADC range is used linearly over that range then you require log(90/0.02)/log(2) = 12.1 bits resolution on your readings. So after allowing for the noise in all sensor outputs you're looking at a minimum of a 14 bit data required to give that level of resolution.
It's been suggested you use a pot connected to the internal 10 bit ADC.
Assuming you used your full ADC range over 90 degrees and the 10 bit ADC reading had no noise on it you would be looking at around 2 mm accuracy. In the real world I'd be impressed if such a system could reach 5 mm accuracy.
Assuming you are working vertically accelerators could work, they typically have at least 16 bit resolution on the output but are noisy, you'd need to average for a long time in a very stable environment to get the levels of accuracy needed. Probably a non-starter.
A very quick google didn't find any easily available encoders with the required accuracy. I'm sure they exist but they are probably going to be expensive. You could possibly use gearing to improve the sensitivity of a more standard part but that's adding mechanical complexity.
In other words the accuracy you're aiming for isn't easy to achieve. You may want to look at relaxing your requirements a little.

Hi Andrew, thanks for taking a look. how did you go about calculating the angular accuracy? I think I could compromise on accuracy if it'd help reduce the cost of the project and make it more realistic!

The angle of a 0.5 mm error on a 1400 mm arm is asin(0.5/1400)

An accelerometer is not a suitable sensor for this, unless you are working in a vertical orientation (drawing on a wall), in which case you can use the pull of gravity.
It would, though, be overly complex for what is actually a very simple requirement.
Absolute encoders in the traditional (digital) sense are also not good since they don't give great resolution without an overly complex (large number of bits) interface.
The simplest option is to use simple potentiometers. They give around 270° of rotation, which should be more than enough for most uses, and are incredibly simple to interface. They give the resolution of the ADC (10 bit) and are very very simple to read (just use analogRead()).
They are also very cheap.

Is this accuracy feasible?

possible with high accuracy encoders but unlikely with accelerometers - they also drift too much.
Also, cos(x+y) can be decomposed into cos/sin(x) and (y), making a recursive calculation possible. that can be handy if you are using a lut to calculate sin/cos.


text:
Does anyone know how to connect 2 digipots to Arduino? (MCP4141)
I'm struggling with getting the code right. I'm trying to connect 2 digipots (MCP 4141) to Arduino to work separately over SPI. Has anyone got any experience with that?

Do you have one working?

What have you tried? What are you trying to achieve? Can you provide links to the supplier of the digipots? Do they have any example code? Did it work for you?

Try to read the datasheet and get a basic understanding of how the device works. in this case, it consists of 16 bits transfer (2 bytes).
Try to write a set of routines that communicates with the chip over the spi.
After that, it is all about using the _CS pin to select a particular chip.
edit: if this helps you, here is my code driving two mcp41010 - slight different from your digit pot but very similar.
//write to the device wiper0
void mcp41xxx_write0(uint8_t dat) {
    spi_write(MCP41XXX_P0 | MCP41XXX_CMD_WRITE);    //send the command byte
    spi_write(dat);                                 //send the data byte
}

//write to the device wiper1
void mcp41xxx_write1(uint8_t dat) {
    spi_write(MCP41XXX_P1 | MCP41XXX_CMD_WRITE);    //send the command byte
    spi_write(dat);                                 //send the data byte
}

the actual writes to the devices will differ -> mine is specific to the mcp41010 devices. It supports two wipers, P0 and P1. No increment or decrement on my digit pots.
the way to drive two digit pots are below:
//first pot
spi_select(MCP41XXX_CS1);           //deselect cs1 -> idles high
mcp41xxx_write0(i + i);             //send the data
spi_deselect(MCP41XXX_CS1);         //select hte device

//second pot
spi_select(MCP41XXX_CS2);           //deselect cs1 -> idles high
mcp41xxx_write0(i++);               //send the data
spi_deselect(MCP41XXX_CS2);         //select the device

as i'm using a single pot device, writing to the 2nd pot means writing to its wiper0.

I looked at your digit pot and the only thing you need to change are the wiper-specific routine(s), as your transmission is slightly different in the msb.
the spi_write() routine can be replaced / mapped to the shiftOut() routine under arduino.
here is the above code, without any change, running on an arduino:

I also took a brief look at your device's datasheet (mcp4141) and I think this is all you need to change:
//send data on wiper0 of mcp4141
void mcp41xx_write0(uint16_t dat) {
    dat = dat & 0x03ff;                             //10-bit data
    spi_write(MCP41XX_CMD_WRITE | MCP41XX_WIPER0 | (dat >>  8));    //write the msb
    spi_write(dat);                                 //write the lsb
}


text:
Using strings inside mBlock extensions code
The following question is about a 3rd party Arduino programming enviroment mBlock and creating extensions for it. I hope that there are some of you out there, who are fammiliar with it.
I was recently making an extensions for mBlock that can be used to write code for Arduino, when I came over this obstacle. I tried to write a function inside the "work":"" statement.
It looked like this:
"work":"Serial.print("Hello world");"
The extensions could not be imported, due to the quotation marks around the Hello world string. I tried removing the quotation marks, the extension was sucessfully added, but the program did not work, beacause quotation marks are needed inside C++ code to define a string.
Is there a way to add them in the extensions, without screwing up the code?

If that is a JSON format you could try using single quotes instead of double quotes:
"work":'Serial.print("Hello world");'

Alternatively you could escape the internal quotes:
"work":"Serial.print(\"Hello world\");"

None of the mentioned solutions seem to work. The extensions still do not get uploaded. The extension I am writing has a .s2e extension, if that helps (I am not really familliar with these kinds of files).

Looking at existing libraries the escaping should work. This is from serial.s2e: "work":"Serial.print({0});Serial.print(\"=\");Serial.println({1});\n"

For some reason it worked this time. I do not not why, but let's just go with it. Thanks.


text:
Using StringStream in Arduino sketch
I learned about StringStream today at work.
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>

using namespace std;

char* getSql() {
    float outdoorTempInC = 15;
    int outoorHumidity = 23;
    float indorTempinC = 20;
    int humidity = 22;
    int val = 400; // soil sensor reading
    int avgVal = 38; // avaerage of 10 values of soils sensor
    char statusMsg[50] = {"Hello World"} ;
    std::stringstream sqlQuery;
    sqlQuery  << "INSERT INTO arduinoSensorData.sensorLog (out_temperature,  "
        << "out_humidity,  drwngRoom_temperature, drwngRoom_humidity, "
        << "pot1_soilMoisture, pot1_avg_SoilMoisture, wateringPot1) VALUES ('"
        << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
        << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
        << statusMsg << "');";

    char *mychar = new char[sqlQuery.str().length() + 1];
    strcpy(mychar, sqlQuery.str().c_str());
    return mychar;
}

string getSqlStream() {
    float outdoorTempInC = 15;
    int outoorHumidity = 23;
    float indorTempinC = 20;
    int humidity = 22;
    int val = 400; // soil sensor reading
    int avgVal = 38; // avaerage of 10 values of soils sensor
    char statusMsg[50] = {"Hello World"} ;
    std::stringstream sqlQuery;
    sqlQuery  << "INSERT INTO arduinoSensorData.sensorLog (out_temperature,  "
        << "out_humidity,  drwngRoom_temperature, drwngRoom_humidity, "
        << "pot1_soilMoisture, pot1_avg_SoilMoisture, wateringPot1) VALUES ('"
        << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
        << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
        << statusMsg << "');";
    return sqlQuery.str();
}

int main() {
    string sql = getSqlStream();
    cout << getSql() << "\n";
    cout << sql.c_str() << "\n";
    return  0;
}

I was very happy until I discovered I cannot use StringStream in Arduino, so I dug in the internet and came across with this.
So if I try to use the above linked gist StringSteam like I have used in my example code, I am getting this error:
error: no match for 'operator<<' (operand types are 'StringStream' and 'const char [60]')
     sqlQuery  << "INSERT INTO arduinoSensorData.sensorLog (out_temperature,  "
               ^
webServer_Displaying_everything_v01:24: error: 'outdoorTempInC' was not declared in this scope
         << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
            ^
webServer_Displaying_everything_v01:24: error: 'outoorHumidity' was not declared in this scope
         << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
                                        ^
webServer_Displaying_everything_v01:24: error: 'indorTempinC' was not declared in this scope
         << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
                                                                    ^
webServer_Displaying_everything_v01:25: error: 'humidity' was not declared in this scope
         << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
                      ^
webServer_Displaying_everything_v01:25: error: 'val' was not declared in this scope
         << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
                                            ^
webServer_Displaying_everything_v01:25: error: 'avgVal' was not declared in this scope
         << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
                                                             ^
webServer_Displaying_everything_v01:28: error: 'class StringStream' has no member named 'str'
     char *mychar = new char[sqlQuery.str().length() + 1];
                                      ^
webServer_Displaying_everything_v01:29: error: 'class StringStream' has no member named 'str'
     strcpy(mychar, sqlQuery.str().c_str());

Or I am doing it completely the wrong way? It feels I still cannot use it the way I have done in the example. Please help.

This class is not a “stream” in the C++ sense, it's a Stream in the Arduino sense, i.e. it provides an interface similar to Serial. You can for instance print() and println() to it.

@EdgarBonet so in that case how can I use sqlQuery  method of storing to a variable in arduino without having to use print(), println or sprintf ?

The whole purpose if this StringStream is to let you print() and println() into it.

The reference to StringStream is to "#include " which is very much a stream in the C++ sense, not in the Arduino sense. The OP is looking to use std C++ in Arduino. The answer is to use the GNU tool chains used by (and installed with) the Arduino IDE, but without the ino preprocessor. There is no class StringStream.  The class is ostringstream, and its purpose is to provide appendage methods via the << operator. Println is never used. The \n, \r\n, or preferably std::endl is used to terminate a line and sprintf may or may not be used underneath the ostringstream methods.

Direct Answer
Program in C++ and cross compile to the Arduino Yún.  The Arduino Sketch language is a thin layer over C++, but the std:: namespace is not light weight to the degree it would need to be to fit the things you are appreciating from the standard C++ library into the memory footprint of a small embedded CPU board.  See Arduino Yun C++ environment? Bridge + Cross-Compiler.
Serious Programming on Arduino
If you wish to open the door to C++ elegance on smaller embedded CPU boards like the simpler Arduinos, you will need to move beyond the Arduino sketch language.  You may find it both fun and useful to learn how to cross compile and link using the GNU tool set that targets the Atmel CPU you have on your board.
This more professional approach is not for the faint at heart, but it is done all the time.   We do it here in TranSeed Labs every day.
To get started, you don't need to download or install anything other than the Arduino software.  The tool set that targets Atmel's AVR architecture (used by several Arduino boards) is in a sub-directory under the Arduino IDE's home directory.  The tool set that targets Atmel's SAM Architecture for the Arduino Due is placed in a sub-directory of your home directory when you set up the IDE to upload sketches to the Due.
Returning to the Question in This C++ Context
Once you learn how to compile and link using g++ from the GNU tool chain1 and use the upload tools2 your program via the USB port, you can create a template class to get the elegance available in C++ like the operator overloading that you like.
The issue with trying to employ the C++ library with embedded targets is that the allocation system and other dependencies will probably exhaust much if not all of your program memory.  The ostringstream class from the C++ library, with all its dependencies included, is not extremely lean.
An approach that consumes very little memory and does not require the CPU cycles of dynamic allocation is to create a C++ template that wraps a static array.  Its buffer size can be one of the template parameters.
Then you can overload the << operator of the class using these examples as a guide.  You get your elegance and drastically reduce your computing resource requirements.

[1] Both cross compiling and cross linking are done with g++ (gcc for the Aruino and Atmel C files in the library).  For Arduino boards using the AVR based Atmel CPUs, use the AVR GNU Tool Chain.  For the Due, which uses the SAM based Atmel CPUs, use the SAM5X GNU Tool Chain.
[2] The program bossac is used to upload to the Due.  The program avrdude is used to upload to the Mega 2560.

well, I do not have Arduino Yun, but I was rather going to buy Arduino Yun Shield, I'd assume it should not make difference , correct me if I am wrong please !

Yun board != Yun shield

Thanks Douglas, best answer I have accepted however just little bit more trouble I would appreciate if in your answer you can link up the text "cross compile" , "link using the GNU tool" and "set that targets the Atmel CPU" example on web. It will seed the process of learning. However I would refrain from directly jumping to higher step.

This answer is almost exactly the road we take here at the lab, and it works very well. Most of the serious embedded programmers use microemacs to develop. We tried using the std:: namespace in sketches for containers and strings, but the advantage to moving to g++ and a makefile became obvious in the first week of writing actual programs. The way outlined here has worked for three years now and triples our development speed.

It has nothing to do with cross compiling or linkage using the GNU tool. IO streams do present on Arduino but attempt to include it result in too big binary. It simply does not fit on chip's memory.
There are a couple of solutions to this problem. One is to use a library called ard-streams. Another one is to use a lightweight, simplified version of stringstream just enough to compile your code.
#include <string>

namespace ard
{
    struct ostringstream
    {
        ostringstream() = default;
        ostringstream(std::string arg) : s(std::move(arg)) {}

        const std::string& str() const {
            return s;
        }

        // Arithmetic types: int, float, ...
        template <class T>
        auto operator<<(T arg) -> decltype(std::to_string(arg), *this) {
            s.append(std::to_string(arg));
            return *this;
        }

        // String types: std::string, const char*
        template <class T>
        auto operator<<(const T& arg) -> decltype(std::string().append(arg), *this) {
            s.append(arg);
            return *this;
        }

        // Single char: 'a', '\n', ...
        ostringstream& operator<<(char arg) {
            s.append(1, arg);
            return *this;
        }

    private:
        std::string s;
    };
}

Now just replace std::stringstream with ard::ostringstream and it will work as expected.

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


text:
Lighting LED with Arduino Uno from PC keyboard
I tried to turn on a LED with my PC keyboard and an Arduino Uno with the letter A.
I get the message

exit status 1
  'keypressed' was not declared in this scope

My code:
int led1 = 10;

void setup()
{

pinMode(led1, OUTPUT);
}
void loop()
{

 if(keypressed == 'a'){
               digitalWrite(led1, HIGH);
               delay(500);
}
}

What is the problem?

Uhh please don't tell me you just made up the term "keypressed" because I'm pretty sure that's NOT how programming works. By the way, getting a keyboard input to control a USB device is no where near simple. Along with the Arduino code for the Arduino, you need another program that will detect keyboard strokes, then interface serial with the Arduino.

Is not there something that can help me
Like plugin

I think keypressed() should be serial.Read() and then send the letter a from the serial monitor or maybe build a python script to find, connect to the arduino serial port then you are able to send this character. keypressed() is not a valid arduino function!

It tells you EXACTLY what your problem is: "'keypressed' was not declared in this scope". It means you never defined "keypressed". How is the Arduino supposed to know what you wanted it to mean? Arduinos can't read minds.

Firstly, you can't just make up the term "keypressed" because the programming language is unable to understand it (unless you assign it as a variable but it's purpose then would just be to store and retrieve values). Secondly the arduino itself is unable to detect keystrokes from the computer by itself. It needs a program on the computer to be able to detect keystrokes from the keyboard then send it to the arduino.
So how would one do this?
Assuming you use Windows, learn Python (A not-so-hard programming language on the computer), then look up the msvcrt library and from there learn how to get key strokes (this only works if you are currently selecting the running program). Then in arduino and python, learn how to use serial. For Python, you need to download this library and learn how to use it. For Arduino it's already in there you just have to learn how to use it. Then you can do the rest and make it turn on your LED.
I hope this helps.

Here you declared keypressed as a variable, so you need to assign an input to it using
'keypressed = serial.read()'
without quotes before if statement in void loop. Note make make use of serial monitor for input and also assign
'serial.begin(9600)'
without quotes in void setup function before pinmode statement.

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


text:
Upload custom trinket firmware
I'd like to disable the trinket 10-second bootloader when powered up, so it will just begin running the program. I would still like to be able to press the reset button to re-program it.
I found an edited version of the bootloader here. Currently, I am using an Arduino Uno and the 'repair the bootloader' sketch to load the hex to the trinket. The default hex is hard coded in the images.cpp file and the same hex is included in the Adafruit bootloader GitHub as trinketgemma_v1.hex.
How can I compile the forked copy to get the final compiled hex that can be burnt into the trinket?
Update:
I get this error when I upload to the board, how did you flash yours?
Setting fuses  Set Low Fuse to: F1 -> A000  Set High Fuse to: D5 -> A800  Set Ext Fuse to: 6 -> A400
Verifying fuses...
    Low Fuse: 0xF1 is 0xF1
    High Fuse: 0xD5 is 0xD5
    Ext Fuse: 0x6 is 0x6

Setting fuses

Verifying flash...
verification error at address 0x14C0 Should be 0x33 not 0x5F
Failed to verify chip

The fuses are set correctly, but it cannot verify the flash. The supplied Adafruit hex looks like about 93 lines of:
":2000000093CA15C0EBCA13C012C011C010C00FC00EC00DC00CC00BC00AC009C008C0112422\n"

Where the updated, compiled hex is about 181 lines of:
":100000005FCA5FCA5FCA5FCA5FCA5FCA5FCA5FCAA8\n"

Does the length of each line matter? The output of a successful flash looks like:
Verifying fuses...
    Low Fuse: 0xF1 is 0xF1
    High Fuse: 0xD5 is 0xD5
    Ext Fuse: 0x6 is 0x6

Setting fuses

Verifying flash...
    Flash verified correctly!
Verifying fuses...

Fuses verified correctly!
*OK!*

Looks like you can just replace the hex in the images.cpp, with the hex in flash_me_xv.hex. Though you have to encapsulate every line between a " and \n". Also make sure to change the fuses in image.cpp (correct value can be found here) (PS nice to see someone using my code)

@Gerben I tried just replacing the hex, however, it says there is an error verifying the flash. I updated the post with more info.

I used the makefile to upload the boot loader.