text:
Any way to pass EthernetClient to function outside of loop automatically?
I have an Arduino webserver that displays many buttons over a webpage (73 at the moment) that toggle different switches. I shortened up the button-drawing code with this function:
void displayButton(String toggleName, byte toggle, byte link1, EthernetClient & client, boolean last) {
  if (toggle == 0) client.print("<a href=\"/?");
  else client.print("");
  client.print(toggleName);
  client.print("");
  if (last) client.print("

");
}

And this is a shortened version of my loop function:
void loop() {
  EthernetClient client = server.available();
  if (client) {
    boolean done = false;
    while (client.connected() && !done)
    {
      while (client.available () > 0 && !done)
        done = processIncomingByte (client.read ());
    }  // end of while client connected
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println();
      client.print("");
      displayButton("F8", f8Toggle, 57, client, 0);
      displayButton("F9", f9Toggle, 58, client, 0);
      displayButton("F10", f10Toggle, 59, client, 1);
      client.println("");
      delay(5); client.stop();
  } // end of "if client"
} // end of loop

I'm wondering if there's any way to have the displayButton function use the EthernetClient instance without it having to be passed every time. I'm interested in this in order to clean up my code a little (since I would be able to remove 73 instances of the word "client"), and also as a learning experience.

If client is global then it already knows about it.

When I tried to remove the passed client, I was getting "'client' was not declared in this scope" for the displayButton function. Would it affect the webserver at all if I defined "EthernetClient client;" before the Setup and Loop functions? I just tested this out, and it seems to work, but I feel hesitant about it because I've never seen that in any other webserver code.

As long as you remove the EthernetClient from before the client in loop().

As Majenko has noted in the comments, the solution was to declare "EthernetClient client;" as a global variable, outside of the loop. Normally I would've tried something like this on my own, but was hesitant to do so because I had never seen anything like that in other code.

Using global variables is usually considered a sign of poor design (it can leaves you open to some kinds of errors that local variable are less subject to), is why you don't see it very often. The client variable in your program is one of the exceptions, where globalizing it probably reduces, rather than increases, the potential for errors.


text:
Create a device to detect object state
Here is what I want to do or get it done (since I am not a embedded guy)...

create a prototype with Arduino to detect open window/door of my room using camera(image processing/object state detection)?
that prototype will take pictures of room door/window at certain interval and than using some algorithm to decide whether they are open or not and will sound an alarm if it is open.
prototype should work in dark as well
No false alarms
Form factor should be small (the final product should not be bigger than smoke detectors that we have it in our room)

My questions are..

Is it possible? :)
What all things I need to create a prototype?
Which camera should I use? Camera should be really small.
Are algorithms available to detect it?

Not possible, the Arduino is far from powerful enough. What you need is a computer, not a microcontroller.  Think Raspberry Pi or BeagleBone Black.

Also, one has to ask the question: Why?! What's wrong with technology that's been around for a good century or more: the reed switch and magnet?

@Majenko tecnically both Galileo and Edison+Arduino shield qualify as Arduino, so you cannot just equate Arduino and microcontroller.

@IgorStoppa Technically some F1 vehicles qualify as Ford. I wouldn't want to drive one round town though. Also, good luck getting hold of one.

@Majenko certainly the availability of non-microcontroller Arduinos is several orders of magnitude higher than F1-Fords. But I'd rather go for the F1-Fiat, anyways :-P

@IgorStoppa I have been wanting an Edison to play with for ages. You just can't get them. It's like they don't exist. F1 cars are 10-a-penny by comparison....

@IgorStoppa Anyway, the Edison is Intel not Arduino - they just label it as Arduino under license. The only thing Arduino has to do with it is to build a selection of carrier boards for it.

@Majenko: strange, I have a few Edison and Galileo I use for work and they have been sourced from sparkfun or similar, afaik. Not from internal sources. Also on both Galieleo and and Edison you can run projects built with variants of the Arduino ide. I prefer plain Debian on them, but it is possible to use them as Arduino, afaik.

@IgorStoppa You probably got them from the first run - they sold out in the first 1273ms I think and they haven't been available since.  Anyway, I much prefer the 4D Armadillo, since I build the OS for it for them :P

This isn't really on-topic for the question anymore? Arduino is a brand, microcontroller is an 'architecture'. Arduino sells microcontroller development boards. But, they also sell Yún and Due which aren't (purely) microcontrollers. And yes, I would consider an atmega based board ineffective (somewhat incapable) for image processing. For Galileo and Edison+Arduino shield == Arduino they may be pin-compatible but their architecture isn't the same by a long shot? (Not mentioning that you're comparing a board with a brand) :)

Your answers :-)

yes, it's possible and should not be too complex
for a simple prototype, you do not need an embedded device, just a PC with a webcam
a webcam with few megapixels should be enough
try OpenCV

After your prototype is ready, you can use a small PC-like platform.
Examples: Minnowboard, Edison, BeagleBone, RaspBerry PI 2, Arduino Yun, Galileo 2
A word of warning: depending on the expectations you have, you will have to pick more powerful models. Computer Vision is computationally intensive.
The examples I gave are roughly sorted by performance and, unsurprisingly, cost. OpenCV is available for many architectures, but afaik, it is particularly optimized for x86, since it's mostly sponsored by Intel.
Disclosure: I work for Intel, so I am more informed on Intel products, but by no means I'm trying to do advertisement, this answer is simply given to the best of my knowledge.

I wonder if you haven't overspecified the device? Is there a reason that it must be photo-interpretive? Because if you only need to know whether a door or window is open, a couple of switches and some simple wired logic, or the very most basic of micro-controllers, if you choose to go that way, will be more than adequate, less expensive, more reliable in the long term (Ok, I know you won't be in a dorm room for long), less prone to false or missed alarms, totally unaffected by the ambient lighting or the lack of it, unobtrusive (no cameras - plural - in the middle of the room).
But I get that it might not be as much fun to make, if that is one of your top criteria!

I doubt you could make such a thing, especially with no embedded experience.

You want to use a camera, but it should "work in the dark" - problem there. You would need to somehow "light" the room with (say) infra-red, but then technically it wouldn't be dark any more.
It should be really small, but has to have the power of image capture and image processing. Maybe a dedicated board designed by people with a lot of experience, and using surface-mounted devices, could do that. I strongly doubt you could do it on an Arduino of any type.
No false alarms? Without knowing your windows that might be hard to say, but considering windows are usually made of glass, detecting the difference between a closed window, and a wide-open one, might be marginal as you would still see the scene outside through the glass.
As the sun rises and falls the image captured would change considerably, quite probably leading to false alarms. Imagine a sudden thunderstorm, where the next image is much darker than the previous one. The image comparison would register a "difference".
Imagine a picture taken during a storm with lightning flashes corrupting the image.
What is someone enters the room and walks in front of the window? That would register as a difference, but doesn't mean the window is open.

What seems much more practical to me would be variants of existing technologies, eg.

Magnets and reed switches
Shine a laser on the window and detect if it moves (the angle would probably change).
Use distance-detection, such as pinging devices. An open window would change the distance (a bit).
Use passive infra-red to detect the movement when the window opens.
Vibration detection mounted on the window glass, or possibly the window frame.
Temperature measurement to detect a difference in temperature as the window opens.

The camera sounds to me the least practical.

Here is what I want to do or get it done (since I am not a embedded
  guy)...

Welcome to the world of embedded... things. I highly appreciate your interest in the embedded world, after all it's more interesting as just PC things :)

create a prototype with Arduino to detect open window/door of my room

You've come to the right place, Arduino (embedded stuff) is very good at input/output. And that seems like a fun project!

using camera(image processing/object state detection)?

Wait, where did this come from? Humans are good at observing, their main sense would be vision (I guess?) to do so. Microcontrollers are somewhat better at logic signals. They are good at taking sensor signals and turning them into whatever you like.
There is a possibility you'd just like to do something with image processing/detection. If so, please mention that :)

that prototype will take pictures of room door/window at certain interval and than using some algorithm to decide whether they are open
  or not and will sound an alarm if it is open.

Arduino can read out a simple "Door sensor" and check if the door is, or is not closed. This will both shrink your project and make it easier.
Arduino can sound an alarm. You can even add a keypad (for a disable code).

prototype should work in dark as well

The drawback of human vision. Is that it does not work so well in the dark. Sensor's based on the touch of the door or a magnetic contact on the door are not affected by darkness.

No false alarms

If your sensor won't fail, the alarm won't go off by accident :)

Form factor should be small (the final product should not be bigger than smoke detectors that we have it in our room)

Use an arduino nano or micro.

My questions are..
  - Is it possible? :)

Yup! You can check for existing projects on the web. You can put in your own implementation though.

What all things I need to create a prototype?

Whatever you need is what you will need.
An sensor as input, an arduino to process it and an "alarm".
There are a trillion configurations for this, you can choose to just go by one or check what fits your needs best.

Which camera should I use? Camera should be really small.

Unless you really want to get going with camera detection/object tracking, you shouldn't use one. (Especially with arduino it can be quite frustrating.) You should use a PC or raspberry Pi or Android phone.
Or use arduino with said sensor.

Are algorithms available to detect it?

Yes. For this, it's again application specific. You should check out some resources, check what others use and determine what would work best for you. Try it out and if it won't work you can ask it :) (probably on normal stack-overflow since it's not really arduino related, maybe robotics stackexchange).

source: Stack Exchange

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

sort: votes


text:
PC <-> Xbee <-> Another Xbee Communication
I have this application where I want to send commands from the PC to an Arduino, remotely, and receive an answer back.
The hardware configuration I'm using to achieve that is the following:
PC <--> Arduino with an Xbee <--> Another Arduino with another Xbee

It's just half-duplex communication. Everything seems easy, but there is a problem.
Each Arduino has an Xbee Shield with an Xbee module connected to it.
Reading the documentation of the ArduinoXbeeShield, an excerpt caught my eye:
"With the jumpers in the Xbee position (i.e. on the two pins towards theinterior of the board), the DOUT pin of the Xbee module is connected to the RX pin of the microcontroller; and DIN is connected to TX. Note that the RX and TX pins of the microcontroller are still connected to the TX and RX pins (respectively) of the FTDI chip - data sent from the microcontroller will be transmitted to the computer via USB as well as being sent wirelessly by the Xbee module. The microcontroller, however, will only be able to receive data from the Xbee module, not over USB from the computer.
With the jumpers in the USB position (i.e. on the two pins nearest the edge of the board), the DOUT pin the Xbee module is connected to the RX pin of the FTDI chip, and DIN on the Xbee module is connected to the TX pin of the FTDI chip. This means that the Xbee module can communicate directly with the computer - however, this only works if the microcontroller has been removed from the Arduino board. If the microcontroller is left in the Arduino board, it will be able to talk to the computer normally via USB, but neither the computer nor the microcontroller will be able to talk to the Xbee module."
That means I will not be able to build what I want with this configuration?
I already tried, but didn't work.

Basically with your shield you have two options:

Communicate between the MCU and the XBee at the cost of not being able to communicate between the PC and the MCU.
Communicate between the PC and the XBee at the cost of having to remove the MCU from the board completely.

Neither of which are particularly ideal.  The first option is completely out since that rules out all PC communication.  The second option turns the Arduino into just a USB->TTL Serial adapter - and a rather expensive one at that (you can get them on eBay for like $2).
What you want is to re-wire the system using jumper wires (messy, I know) so that the TX and RX pins of the XBee connect to other pins on your Uno then use SoftwareSerial to communicate with the XBee.  That will leave the Arduino's TX and RX pins free for communicating with the PC.
Alternatively invest in a different Arduino that has more hardware UART interfaces, like a Mega2560.

With Mega I solve the problem completely?

@stdio.h With a Mega you can manually wire the XBee to a different pair of UART pins instead of 0 and 1.  That way you can communicate between the MCU and PC and the MCU and XBee.

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


text:
How can i change "+" sign into spaces?
I'm working with esp8266.i am able to send text from webserver to arduino which is displayed on my 16*2 lcd display.but the problem is that when i send text including space i.e:john smith, the text show on my serial monitor and also in lcd  like that (john+smith)..the spaces i gave is converted into "+" sign..Can anyone suggest me how to overcome from that problem??
my code is given below:
  #include <SoftwareSerial.h>
  #include <LiquidCrystal.h>

 SoftwareSerial espSerial(2,3);

  LiquidCrystal lcd(12,11, 7, 6, 5, 4);

const bool printReply = true;
const char line[] = "-----\n\r";
int loopCount=0;

char html[50];
char command[20];
char reply[500];

char ipAddress [20];
char name[30];
int lenHtml = 0;
char temp[5];

void setup()
{
      Serial.begin(9600);
        lcd.begin(16,2);

      Serial.println("Start\r\n\r\n");

      lcd.print("WELCOME ");

      espSerial.begin(9600);

      Serial.println("reset the module");
      espSerial.print("AT+RST\r\n");

      getReply( 2000 );

      Serial.println("Change to station mode");
      lcd.clear();
      lcd.print("station mode");
      espSerial.print("AT+CWMODE=1\r\n");
      getReply( 1500 );

      Serial.println("Connect to a network ");
      lcd.clear();
     lcd.print("connecting...");

      espSerial.print("AT+CWJAP=\"ESP_E61A83\"\r\n");
      getReply( 6000 );

      Serial.println("Get the ip address assigned by the router");
      espSerial.print("AT+CIFSR\r\n");
      getReply( 1000 );

      int len = strlen( reply );
      bool done=false;
      bool error = false;
      int pos = 0;
      while (!done)
      {
           if ( reply[pos] == 10) { done = true;}
           pos++;
           if (pos > len) { done = true;  error = true;}
      }

      if (!error)
      {
            int buffpos = 0;
            done = false;
            while (!done)
            {
               if ( reply[pos] == 13 ) { done = true; }
               else { ipAddress[buffpos] = reply[pos];    buffpos++; pos++;   }
            }
            ipAddress[buffpos] = 0;
      }
      else { strcpy(ipAddress,"ERROR"); }

      Serial.println("Set for multiple connections");
      espSerial.print("AT+CIPMUX=1\r\n");
      getReply( 1500 );

      Serial.println("Start the server");
        lcd.clear();
      lcd.print("Server starts");
      espSerial.print("AT+CIPSERVER=1,80\r\n");
      getReply( 1500 );

      Serial.println("");

   lcd.clear();
      Serial.println("Waiting for page request");
      Serial.print("Connect to "); Serial.println(ipAddress);
      Serial.println("");
lcd.print("feed me more");
delay(1500);
        lcd.clear();

}

void loop()
{
      if(espSerial.available())

          bool foundIPD = false;
          for (int i=0; i<strlen(reply); i++)
          {
               if (  (reply[i]=='I') && (reply[i+1]=='P') && (reply[i+2]=='D')   ) { foundIPD = true;    }
          }

          if ( foundIPD  )
          {

              loopCount++;

              int nameStartPos = 0;
              for (int i=0; i<strlen(reply); i++)
              {
                   if (!haveName)
                   {
                         if (  (reply[i]=='n') && (reply[i+1]=='a') && (reply[i+2]=='m') && (reply[i+3]=='e')  && (reply[i+4]=='=') )
                         {
                             haveName = true;
                             nameStartPos = i+5;
                         }
                   }
              }

              if (haveName)
              {
                    int tempPos = 0;
                    bool finishedCopying = false;
                    for (int i=nameStartPos; i<strlen(reply); i++)
                    {
                         if ( (reply[i]==' ') && !finishedCopying )  { finishedCopying = true;   }
                         if ( !finishedCopying )                     { name[tempPos] = reply[i];   tempPos++; }
                    }
                    name[tempPos] = 0;
              }

              if (haveName) { lcd.clear(); lcd.print("TEACHERS INFO..");Serial.print( "name = ");lcd.setCursor(0,1);Serial.println(name);lcd.print(name);Serial.println("");lcd.print(""); }

              else          { Serial.println( "no name entered");   Serial.println("");lcd.print(""); }

              strcpy(html,"");
              strcpy(command,"AT+CIPSEND=0,25\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              strcpy(html,"
TEACHERS INFORMATION WEBSERVER
");
              strcpy(command,"AT+CIPSEND=0,40\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              strcpy(html,"
CREATED by jack
");
              strcpy(command,"AT+CIPSEND=0,31\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              strcpy(html,"
 Teachers Request number ");
              itoa( loopCount, temp, 10);
              strcat(html,temp);
              strcat(html,"
");

              // need the length of html
              int lenHtml = strlen( html );

              strcpy(command,"AT+CIPSEND=0,");
              itoa( lenHtml, temp, 10);
              strcat(command, temp);
              strcat(command, "\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

             if (haveName)
             {

                  strcpy(html,"
TEACHER name is "); strcat(html, name ); strcat(html,"
");

                  lenHtml = strlen( html );
                  strcpy(command,"AT+CIPSEND=0,"); itoa( lenHtml, temp, 10); strcat(command, temp); strcat(command, "\r\n");
                  espSerial.print(command);
                  getReply( 2000 );
                  espSerial.print(html);
                  getReply( 2000 );
             }

              strcpy(html,"<form action=\""); strcat(html, ipAddress); strcat(html, "\" method=\"GET\">"); strcat(command, "\r\n");

              lenHtml = strlen( html );
              itoa( lenHtml, temp, 10);
              strcpy(command,"AT+CIPSEND=0,");
              itoa( lenHtml, temp, 10);
              strcat(command, temp);
              strcat(command, "\r\n");

              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              strcpy(html,"Name:
<input type=\"text\" name=\"name\">");
              strcpy(command,"AT+CIPSEND=0,40\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              strcpy(html,"<input type=\"submit\" value=\"Submit\"></form>");
              strcpy(command,"AT+CIPSEND=0,43\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              strcpy(html,"");
              strcpy(command,"AT+CIPSEND=0,14\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              espSerial.print( "AT+CIPCLOSE=0\r\n" );
              getReply( 1500 );

              Serial.println("last getReply 1 ");
              getReply( 2500 );

              Serial.println("last getReply 2 ");
              getReply( 2500 );

          }
      }

      delay (100);

}

void getReply(int wait)
{
    int tempPos = 0;
    long int time = millis();
    while( (time + wait) > millis())
    {
        while(espSerial.available())
        {
            char c = espSerial.read();
            if (tempPos < 500) { reply[tempPos] = c; tempPos++;   }
        }
        reply[tempPos] = 0;
    }

    if (printReply) { Serial.println( reply );  Serial.println(line);     }
}

It is hard to understand what your code does. You said that arduino recives text from the server, but I see in the code is that the arduino is the http server, serving an html page with a form in it.
That is also the reason you recieve spaces replaced with "+", the http request is url encoded.
The problem with a search and replace solution of a "+" sign is that url encoding is more than a "+" sign. A space can also be encoded into %20 and there are several other characters that are being encoded as well.
What you will have to do is to implement a decoding function. It is not that hard but if you are lazy, there are plenty of C implementations available on the net. Here is a quick google search hit: https://gist.github.com/jmsaavedra/7964251

If you have your text in a character array, which it seems you have, then it is simple enough to iterate through that array changing whatever characters you want.
For instance, if the text is in reply then:
for (char *p = reply; *p; p++) {
    if (*p == '+') *p = ' ';
}

That is, starting at the beginning of reply, by creating a pointer p and pointing it at the start of reply, check to see if there is anything except the NULL character, run the code inside the brackets, and move to the next character (p++).
The code inside the brackets looks to see if the current character is a + and if so then set the current character to be a space.
Another way is to use an integer counter:
for (int i = 0; reply[i] != 0; i++) {
    if (reply[i] == '+') reply[i] = ' ';
}

i have already used ur second way (integer counter)..but it's only show the first word of the text...i.e:whether i write (my text) ,it shows only (my)..

Two things:
+If you are using strings, try using the String built in object, it is very handy and useful
+when using String, you can use replace function


text:
Why does Arduino Due Native Port change serial ports after every reset? (Linux)
Previously I had my Due connected via Programming Port for weeks, and it never changed serial ports after pressing the reset button. Recently I switched to having it connected via the Native Port instead, and was surprised to see that it changes port numbers every time I press the reset button.
For example if it was on ttyATM1 beforehand, after pressing reset it'll be on ttyATM2 instead. It changes numbers like this after every reset. Is this normal behavior?
I have a python script sending serial data to the Due, and I have to change the port number in the python code every time the Due changes ports.

It happens because of Linux, not because of the Arduino.
Since you unplug/reset the DUE while the port is still open, when it's back online, the old file name is still in use, so a new one is created.
Just close the port before resetting the DUE and you will see that after the reset it will have the same one.
You can easily reproduce the same issue with a serial to usb adapter (/dev/ttyUSBS0,1,2,etc) and screen or minicom.
To make your program more robust, you should listen for kernel events and open the port accordingly.

Thanks! I'm glad you mentioned that it's possible to make a check for those events. I found this nice page with lots of info on how to do it: http://stackoverflow.com/questions/2530096/how-to-find-all-serial-devices-ttys-ttyusb-on-linux-without-opening-them. And then the command:  "# ls /dev/serial/by-id" neatly lists the Due as: "usb-Arduino_LLC_Arduino_Due-if00". Maybe it won't be as difficult as I had thought.

There is a problem with that: if you have 2 devices with the same id, your program might get confused, if it has to tell them apart.  In such case, if you do not change the way they are plugged, but simply restart them, like with the Arduino reset, you can inspect the usb device tree.

Thanks. I also frequently plug/unplug the units. If I'm expecting to only have one Due in the foreseeable future, would it be suitable to just detect the text for "Due"?

Or for whatever is the id shown by your device. Yes, it's ok as long as you are aware of the potential issue and document it in the code, so that later on you or someone else doesn't have to remember it.


text:
Will there be any pin interference in this Project?
I am working on a project with Arduino Uno Clone. After having a look on my arrangement, please tell me whether I will have to face any difficulty or consider any thing.
I have a relay on pin 2 (drive An Induction cooktop from AC Mains),
6 mini 9g servo from pin 3-8 (want to drive non-pwm pins with any Software library),
a 8 ohm speaker on pin 9,
a microSd card module from pin 10-13 (play .wav files through speaker),
5 pushbuttons from pin A0-A4,
a toy dc motor on A5 (Drive through a transistor). So my questions are:

Will I have to face any pin arrangement problem in my project? If yes, please give me a solution
I have six servos and a dc motor in which only one will be moving at a time, is there really a need of external power source for motors
I have to drive this arrangement through AC Mains, but i dont want to buy An adapter. I have a mobile charger which have written "INPUT 100-250V AC, OUTPUT 4-12V, 800mA" , can I drive my arduino with this?
Can I boost the volume of my speaker by using a transistor or capacitor (I have no idea about amplifier IC) ?
I have to include these librairies, SD library, tmrpcm, SPI, servo, and any one extra to drive servos on non-pwm pins. What would be the total size because my arduino has only 30kb approx?  Thanks To Give Me Time. Please help me.

possibly you will face problems with current drain and timing. There is no ready made solution. You have to get a bit farther by yourself and come back with detailed descriptions of your problems.
check on other threads (google) the issues with driving directly a coil. There are plenty of explanations why you need to be careful about it.
you should at least try to do the math yourself, then ask for verification. Try to calculate the power requirements of each component (average, maximum, peak) and add them up for every scenario. The you can report your finding and ask for confirmation/advice.
Sure you can, there are plenty of solutions available, but you have to define your requirements and constraints. Then it's easy to pick one solution (or at least google for it).
Just try to include them in the project and compile them. It's fast and you will get the answer immediately. There are ways to optimize things, but first you should assess if it's needed.

All in all, to get more help, you should show more in detail what you have already done, what are your concerns and why.

Thanks for Your Time. Basically, after seeing your answer I think that there is a very less chance of any type of pin interference. Sorry, because I am just a student without any special technical background. I am googling these topics. If i get any problem, i will Clear it with you


text:
Timer (or other) interrupt happens while servicing an interrupt - how to accurately handle the second one?
This seems like a simple question but I'm not finding an answer so far: at a high level, say I have a timer interrupt and some input interrupt. The input arrives, the ISR is entered, interrupts are (automatically by default?) disabled, I service the input (quickly!), but while that's going on a timer used for some other purpose fires. I don't want to miss that timer but because interrupts are disabled my input processing won't get interrupted for it.
I exit the input ISR and interrupts are (automatically?) re-enabled. Assuming the timer is uncomplicated (it wouldn't overflow twice during my input ISR) how do I accurately handle the fact that it overflowed during my input ISR and I "missed" it?
Would this differ if instead of the timer I simply had a second input2 that similarly might fire during my input1 processing (but would present a useful input long enough to process after input1, presuming I knew it triggered)?
I'm not looking to nest interrupts here, just to understand what happens when an interrupt happens during another ISR which has temporarily disabled them - do they pend and fire after the blocking ISR returns, or are they just lost?

Q1:

... exit the input ISR and interrupts are (automatically?) re-enabled

Yes, the RETI (return from interrupt) instruction enables interrupts.  See third paragraph of section 7.7 in Atmel's document #8271 (a 650-page spec sheet for the Atmega 48, 88, 168, 328 series), which says:

When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction – RETI – is executed.

Q2:

Assuming the timer is uncomplicated (it wouldn't overflow twice during my input ISR) how do I accurately handle the fact that it overflowed during my input ISR and I "missed" it?

If the timer is running a clock, set the timer control bits to automatically reload the count register upon each overflow (or underflow).  That will leave a full count period for processing each timer interrupt.
That is, you can pre-load a next-timer-count (I think it can be different from the current count if necessary), so the timer can start its next interval automatically.  If the timer is used for some purpose more complicated than that, you may need a nested interrupt.
Q3:

Would this differ if instead of the timer I simply had a second input2 that similarly might fire during my input1 processing (but would present a useful input long enough to process after input1, presuming I knew it triggered)?

If indeed input2 sticks around long enough to process after input1 processing is done, no problem.  Its interrupt will occur after the first interrupted code sequence executes one more instruction after the RETI occurs.  (See paragraph 6 of section 7.7 in doc8271.)
If input2 is brief, several different things can happen.   (a) If it is shorter than a clock cycle, in general it won't trigger an interrupt.  (b) If it is a level-interrupt-triggering event on INT0 or INT1 that ends while another interrupt is being processed, it won't trigger an interrupt.  (See discussion on page 72, section 13.2.3, of doc8271 of INTF0 and INTF1 being clear for level interrupts.) (c) If it is an interrupt-flag-setting event that sets a flag and ends while another interrupt is being processed, it will trigger an interrupt after the global interrupt flag is set, unless current processing clears its flag.
I think the above accurately states what happens on Atmega devices, but I suggest you also see doc8271 – and run tests – to see for yourself.  Here is part of what paragraphs 4 and 5 of section 7.7 in doc8271 say regarding (b) and (c):

There are basically two types of interrupts. The first type is triggered by an event that sets the Interrupt Flag.  ... Interrupt Flags can also be cleared by
  writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the
  corresponding interrupt enable bit is cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the Global Interrupt Enable bit is set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the interrupt is enabled, the
  interrupt will not be triggered.

So, based on some slow timer I need to do some background task, but one in a while I'll get an input during which the timer interrupt would've fired, but because I was processing that input (though quickly) I missed the timer's interrupt. Will the timer overflow interrupt stay flagged so that I can process it after I return from my ISR? (Similarly once triggered will the interrupt for input2 be ready for processing after input1 is done, even if data is a bit stale?)
I (think) I see the point about reloading the timer, but that seems like it'd skew timings unnecessarily.

Actually, that might fall under the "input flag setting event" thing above.


text:
How can I have two Arduino Uno's communicate wirelessly?
I'm an art student, using arduino in an Electronic Arts Class.  I have already created a skateboard speedometer, using a Hall Effect Sensor and a magnet embedded in one of my skateboards wheels.  I've attached a speaker to the arduino that plays a tone, with the pitch depending on the RPM's of the wheel.  (the faster the board is going, the higher pitch the tone being played is).  Currently the speaker is attached to the skateboard and wired directly to the arduino.  My goal is to have a speaker with an arduino wirelessly connected to the arduino on the skateboard.  The arduino on the skateboard record's the RPM's and then wirelessly send that information to the second arduino to play the tone through the speaker.  Is this possible? what hardware would yo recommend? I've been looking at the Bluetooth HC-05 but I'm not sure this will work.  Thanks for any help!

The nRF24L01+ modules are a popular choice for this type of thing, and will be much more direct to work with than anything Bluetooth.  You could also consider using a short range analog radio to send audio generated at the source with a stock headphone/speaker audio receiver, but may have trouble finding a quiet channel in an urban area.

@ChrisStratton So two of the nRF24L01+ modules connected to both arduino's should do the trick?

Probably, at least if misoperation/non-operation has no serious consequences.  For a point of comparison, a significant minority of the little quadcopter toys fly around via signals sent through compatible transceivers.

If you do buy the modules, make sure you download the library either through the IDE or from github.com/TMRh20/RF24. That way you'll have a library that has active development and is almost bug free.

ESP8266 is also a good choice. these little guys are really useful and give you a Wi-Fi connection between your Arduino boards.
Also, the cost of one ESP8266 is about $3.. super cheap!


text:
Need help converting a processing sketch for a robot arm with servo shield
I'm currently building a robotic arm. I'm using an Adafruit servo shield, 7 servos, Arduino uno, and a 5V 10A power supply.

I found a program that controls the arm with mouse movement using a processing sketch, Fixbot.
However I'm using the Adafruit servo shield, and I've got no clue how to convert the program. I've found the center points for the servos, so I've managed to make the robot stand upright using my own code.
If someone could give me some pointers as to how to convert from the on-board PWM outputs to the servo shield outputs for the linked program, and how to set servo max/min, I would highly appreciate it.

This site uses a question/answer format. A "question" along the lines of "please give me some pointers as to how to do X" is rather broad.

What aspect needs converting? More importantly, what does it need converting to? The Arduiino code for the Fixbot is wonderfully straightforward; it reads a run of integers (by parsing a string, blah blah) and then writes those integers to the servos. Where is the problem occurring?

I use a generic servo shield, and the servo PWM outputs (3 pin inline connector) on the shield are labeled accordingly (0 - 15). Your Adafruit servo shield should be the same, see below.

The link that you provide also has the Arduino version, see below. You should use that, instead of the Processing version.
The Arduino library Servo.h, handles all of the "Servo PWM to Arduino pin conversions" that you ask for. So, looking at the Fixbot code, it would seem that all you would need to do is change the five pins (servo PWM outputs) to which the servos are attached in setup(), according to which servo PWM outputs you attach each servo to.
#include <Servo.h>

String command;

Servo seg0;
Servo seg1;
Servo seg2;
Servo seg3;
Servo seg4;

void setup() {
  Serial.begin(115200);
  seg0.attach(8);            /* <--- Change Me !!! */
  seg1.attach(9);            /* <--- Change Me !!! */
  seg2.attach(10);           /* <--- Change Me !!! */
  seg3.attach(11);           /* <--- Change Me !!! */
  seg4.attach(12);           /* <--- Change Me !!! */
}

void loop() {
  if(Serial.available() > 0) {
    char inChar = Serial.read();
    command += inChar;
    if(inChar == '\n') {
      // clear command
      performCmd(command);
      command = "";
    }
    Serial.flush();
  }
}

void performCmd(String cmd) {
  int comma1 = cmd.indexOf(',');
  int comma2 = cmd.indexOf(',', comma1+1);
  int comma3 = cmd.indexOf(',', comma2+1);
  int comma4 = cmd.indexOf(',', comma3+1);

  int cmd0 = stringToInt(cmd.substring(0, comma1));
  int cmd1 = stringToInt(cmd.substring(comma1+1, comma2));
  int cmd2 = stringToInt(cmd.substring(comma2+1, comma3));
  int cmd3 = stringToInt(cmd.substring(comma3+1, comma4));
  int cmd4 = stringToInt(cmd.substring(comma4+1, cmd.length()));

  seg0.write(cmd0);
  seg1.write(cmd1);
  seg2.write(cmd2);
  seg3.write(cmd3);
  seg4.write(cmd4);

}

int stringToInt(String str) {
  String tmp = String(str);
  return str.toInt();
}

Regarding your question about the maximum and minimums, again, these will be handled by the Servo.h library.

TL;DR
Change the five servo attach lines in the setup() routine, to reflect which servo ports your servos are connected to.

Power Requirements
As an aside, remember that you will need to supply external power (+5V) to the Adafruit Servo board, via the blue screw terminal block, in order to have sufficient power (current) to actuate the servos. In the photo above the screw terminal block is not shown, but would be mounted half way up on the left hand side of the PCB (where it says 5-6V Servo). It can be seen in this photo, at the top:

If you do not supply external power, then the Arduino board, by itself will not be able to supply enough power. Even though the code may be running, the lack of power may make it appear that there is no output, as the servos remain immobile, due to the lack of current.


text:
Arduino Orion Upload - Which Board When Compiling
I'm trying to compile and upload the example code for the arduino robotics starter kit (https://github.com/Makeblock-official/Makeblock-Library and https://raw.githubusercontent.com/Makeblock-official/Assembly-Instructions/master/Starter_Robot_Kit_IR_Instruction.pdf).
In the IDE to compile the code, you need to select the appropiate 'board' for the sketch, and the Arduino Orion isn't listed.  Should I just compile under the Arduino Uno, which I believe the Orion is based on?

Yes, the "Orion" is just an Uno in a different shape with different connectors.  Just treat it like an ordinary Uno.
Similarly the "Baseboard" is just a Leonardo in a different shape with different connectors.


text:
Prevent reiteration of loop instruction in Arduino/Execute instruction via off switch
I'd like to make an Arduino play a (2sec).wav file once when it is powered on (via push button) and another when it is switched off i.e. when the push button is pushed there is a 2sec delay and the .wav file plays, then the arduino turns off.  What would the best way be to implement this?  So far I've come up with:
void loop()
{
//play .wav file

while(1){}
}

or:
void setup(){
//play .wav file
}

void loop(){
//empty
}

An Arduino doesn't understand the concept of "powering off".  It is either on (running) or off (not able to do anything).
Your first task must be to design a system whereby the Arduino can control its own power so the Arduino can then go "I have been asked by this external stimulus to switch off. Therefore I will play this sound and then perform whatever actions are required to remove power from myself."
Only when you have worked out how you can get the Arduino to control its own power and still have the ability to manually turn the power on can you begin to think about adding things that happen "when it powers off".

Thanks for your clear explanation Majenko.  I'm a novice and am merely looking to play a sound effect when the Arduino switches on and off.  Designing a "self-controlled power system" for the Arduino sounds a little daunting at this point in time : ]

Nevertheless, it is required.  The Arduino can't play the sound once it is turned off, and it doesn't know you're about to turn it off, so you need some way of telling the Arduino that it should turn itself off once it has finished playing the sound.

Thanks again Majenko.  Is this the type of direction I might take if undertaking it: http://forum.arduino.cc/index.php?topic=118504.0

Yep, that kind of thing would be good.

Ok great, thank you.  I'll look into it and see exactly what's involved.

Neither way addresses your second requirement. I would do something like:
void setup()
    {
    pinMode (OFF_BUTTON, INPUT_PULLUP);

    //play .wav file
    }

void loop()
  {

  if (digitalRead (OFF_BUTTON) == LOW)  // depending on how it is wired
    {
    delay (2000);   // 2 second delay
    // play .wav file
    // power self off somehow
    }

}

Thanks a lot Nick. So placing the .wav instruction within setup() should do the trick for making it play once only, when the Arduino is switched on?  Am I understanding your code correctly if I say that you've set the push button as a digital input pullup, which if read in as being low/off will cause a 2 sec delay followed by the .wav file playing and (in theory) then the Arduino will power itself off?  I'm trying to understand why you used INPUT_PULLUP as opposed to INPUT http://electronics.stackexchange.com/questions/67007/whats-the-difference-between-input-and-input-pullup

It makes the switch read reliably. See Switches


text:
Hardware serial not working, SoftwareSerial is
On my Uno-equivalent Arduino, a SoftwareSerial connection (on RX, TX = 8, 9) is working*, while a hardware serial connection to the same device, set up in the same way (but on pins RX, TX = 0, 1) is not working. Why is the hardware serial setup not working?
*By working I mean receiving a byte from the external device
Edit: as a simple example:
void setup() {
  Serial.begin(38000);
  pinMode(7, OUTPUT);
}

void draw() {
  if (Serial.available() > 0) {
    Serial.read();
    tone(7, 440, 1000);
  }
}

The above, using Serial, doesn't work, whereas
#include <SoftwareSerial.h>

SoftwareSerial serial(8, 9);

void setup() {
  serial.begin(38000);
  pinMode(7, OUTPUT);
}

void draw() {
  if (serial.available() > 0) {
    serial.read();
    tone(7, 440, 1000);
  }
}

does work.

I don't know if this helps, but connecting RX/TX through an LED to ground gave me the following, using Serial on (0, 1) and SoftwareSerial on (8, 9):
Serial
RX: bright
TX: bright
SoftwareSerial
RX: dim (but still lit)
TX: bright
Is the fact that RX is dim using SoftwareSerial significant?

Please post your code. Please define "not working". What device have you connected?

@NickGammon This is interfacing with a CASIO fx-9750GII. I can receive the request byte from the calculator using SoftwareSerial but not with Serial. If the Arduino receives any data it makes a sound.

What if you try SoftwareSerial serial(0,1);?

38000 bps is not a standard rate and hardware at one end or the other might not support it, while software might not care.  You still haven't said what "doesn't work" means, but if it means garbled characters, use a standard rate, eg 38400 bps.

@jwpat7 'Doesn't work' means no byte is received. The external device supports 38000 bps only, and the Arduino can use it on the hardware serial port (as tested connected to a computer with a Processing sketch). The fact that it is simultaneously connected to a computer through the USB port doesn't seem to be an issue, because it exhibits the same behaviour powered by a phone charger (unless the charger also interferes with something?).

@frarugi87 I don't think SoftwareSerial serial(0, 1); worked either.

What do you mean by "think"? Did you test it?

@frarugi87 Tested again now; no success.

Just a stupid question, but did you try to swap RX and TX? Anyway if SoftwareSerial on pins 0,1 doesn't work it's an hardware problem...

@frarugi87 Yes, I tried swapping – about ten times. Maybe my ESP8266 will work with Serial; I'll give it a try. Do you know if it supports SoftwareSerial?

I think so.. Or at least it can; if the libraries rely on interrupts you'll have to re-write them..

Serial works on the ESP8266; SoftwareSerial fails to compile (I think it is available as an external library though). I was testing this for an ESP8266 project so it will work. I'd say it is a harware issue on the uC.

There may be several reasons

Be sure uC pin connect pin header
In setup part, you write Serial.begin(xxxx);
After serial begin, don't change this pins IO features(Input, output)

Please check that after if not solve, please share code

Can you explain what you mean in 1?

Also explain what you mean by (3).

I think that means don't use pinMode on pins 0 or 1.

I think a translation might be: 1. Make sure you connect to the right pins. 2. Be sure to use Serial.begin(baud). 3. Never use pinMode() on pins 0 and 1 when you are using Serial.

In that case: check, check and check... I think.

I would check if the arduino you are using supports your selected baudrate.
38000 is not a standard rate and it could be, that the hardware is not able to work at it with the needed precision.
The software serial (and most USB serial dongles) could use any baudrate, but not the limited hardware within most arduinos.

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


text:
Sending serial data to Arduino from Matlab(not using support package)
I am learning Arduino and trying to understand how integers and strings are sent across the serial port.
I tried a small program in arduino which reads a number as a string and tries to blink led 13 according to that number. Below is the arduino side of code.
const int ledpin = 13;
int value = 0;
int blinkrate;
void setup()
{
   Serial.begin(9600);
   pinMode(ledpin,OUTPUT);

}

void loop()
{
    if (Serial.available())
      {
         char ch = Serial.read();
         if (isDigit(ch))
            {
               value = (value*10) + (ch - '0');
            }
         else if (ch == 10)
            {
               blinkrate = value;
               Serial.println(blinkrate);
               value = 0;
            }
      }
    blinkled(blinkrate);
}

void blinkled(int blinkrate)
 {
   digitalWrite(ledpin,HIGH);
   delay(blinkrate);
   digitalWrite(ledpin,LOW);
   delay(blinkrate);
 }

When i try to send a string from MATLAB, the RX led blinks once indicating something is coming, but the LED on pin 13 is not behaving accordingly(it should blink according to the number i send). Here is the matlab side of code.
pre_open = instrfindall;
delete(pre_open);
serial_port = serial('COM3');
set(serial_port,'Terminator','CR');
set(serial_port,'BaudRate',9600);
set(serial_port,'DataBits',8);
set(serial_port,'StopBits',1);
set(serial_port,'Parity','none');
fopen(serial_port);
num = 200;
fwrite(serial_port,int2str(num));
data = fscanf(serial_port,'%d');
pause(2);
fclose(serial_port);

When i try to read the return string from arduino, MATLAB shows me a timeout error.
I would be grateful if anybody points me to the right solution.
Thank you.

Got it, instead of depending on the Serial object, i sent the line feed to arduino. All this time it has been waiting for the Line feed that never arrived.
delete(instrfindall)
s = serial('COM3', 'BaudRate', 9600); %38400
fopen(s);
pause(0.1);
text = input('enter','s');
fprintf(s,'%s\n',text,'sync');
pause(0.1);
d = fscanf(s,'%s');
pause(0.1);
delete(instrfindall)

You're setting the terminator to be 'CR'.  CR, or Carriage Return, is character 13.  In your Arduino program you are looking for character 10.  That is 'LF' or Line Feed.
Either are commonly used to denote a line ending, but both ends must agree on which it is.
For instance, Unix files use a single LF for a line ending.  Windows files use the combination of both a CR and an LF.  Many networking protocols use a single CR for the line ending.  It really doesn't matter what is used as long as it is consistent.

Thanks for the answer,I also had the same doubt, i tried putting linefeed(LF) in the code, but its not working


text:
Why serial communication does not work on atmega168/328p?
I expect from the following program serial.c to light the led on if I send key 1 from terminal, and light the led off when I send key 0 from terminal:
#define F_CPU 16000000UL
#define BAUD 9600
#include <avr/io.h>
char data;
void main(void) {
  #include <util/setbaud.h>
  UBRR0H = UBRRH_VALUE;
  UBRR0L = UBRRL_VALUE;
  UCSR0B |= (1<<RXEN0);
  UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
  DDRB |= (1<<PB1);
  while(1) {
    while(!(UCSR0A&(1<<RXC0)));
    data = UDR0;
    if (data=='0') PORTB &= ~(1<<PB1);
    if (data=='1') PORTB |= (1<<PB1);
  }
}

I use the following commands to compile and burn all the programs:
avr-gcc -Os -mmcu=atmega328p -c -o serial.o serial.c
avr-ld -o serial.elf serial.o
avr-objcopy -O ihex serial.elf serial.hex
avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

The output of avrdude is the following:
$ avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "serial.hex"
avrdude: input file serial.hex auto detected as Intel Hex
avrdude: writing flash (12 bytes):

Writing | ################################################## | 100% 0.03s

avrdude: 12 bytes of flash written
avrdude: verifying flash memory against serial.hex:
avrdude: load data flash data from input file serial.hex:
avrdude: input file serial.hex auto detected as Intel Hex
avrdude: input file serial.hex contains 12 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 12 bytes of flash verified

avrdude: safemode: Fuses OK (E:07, H:DE, L:FF)

avrdude done.  Thank you.

For serial connection I tried PL2302 and FT232RL usb-com adapters - the effect is always the same.
Terminal settings on the computer are correct (9600,8N1).
avr-gcc version 4.8.1
avrdude version 6.1
Why the very first program in this question does not work as needed and what should be changed in it to achieve the desired behavior?

How is the LED wired to the ATMega?

@Majenko: one led is built-in from the arduino duemilanove board (PB5), another is an ordinary led directly connected to GND and PB1.

So no resistor on the PB1 LED then?

@Majenko: no resistor. I'll try with 270 ohm between GND and led (right?) and report in a minute....

Yes, you do that.  270Ω should be OK.

Also, do you have an Arduino bootloader installed on this chip?

@Majenko: No, as in fuse settings I have BOOTRST enabled.

@Majenko: With the resistor the strange blinking disappeared.

Ok, so forst problem solved: the one LED was most likely causing the Brownout detector to kick in and reset the chip.  Now we can tackle the problem with your code.  I suggest you update your question now the blinking is no longer an issue so the answers can focus on the software problem.

@Majenko: I'll update the question in a moment... It is not clear about Brownout detector - I have it totally disabled in fuses. And where could this problem with voltage appear from anyway? 5V is provided by the PC.

But an LED has a fixed forward voltage of say 2V.  With no resistance the current drawn by the LED is theoretically infinite. That can cause all sorts of issues, including power supply droop and general crashes and resets even with brownout disabled. With it enabled it just reboots cleanly. With it disabled it just crashes messily.  The good news is I can replicate the symptoms of your first bit of code on my Uno quite happily, so I can diagnose the problem now.

The problem you have is that your baud rate is not being set right.
You only have part of the settings you need.  There is a third macro in the setbaud.h file that you need to take account of:  USE_U2X.
That defines whether or not you need to set or clear the U2X0 bit of UCSRA0.  If that is set wrong then your baud rate will be either twice or half what you want it to be - in this case it's coming out as twice.
Modify your code to assign the baud rate like this:
#include <util/setbaud.h>
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
#if USE_U2X
UCSR0A |= (1<<U2X0);
#else
UCSR0A &= ~(1<<U2X0);
#endif
UCSR0B |= (1<<RXEN0);
UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);

Then you should be able to receive characters.
In the actual header file in question there is a large number of comments and instructions, including this:

Assuming that the requested BAUD is valid for the given F_CPU then
     the macro UBRR_VALUE is set to the required prescaler value.  Two
     additional macros are provided for the low and high bytes of the
     prescaler, respectively: UBRRL_VALUE is set to the lower byte of
     the UBRR_VALUE and UBRRH_VALUE is set to the upper byte.  An
     additional macro USE_2X will be defined.  Its value is set to 1 if
     the desired BAUD rate within the given tolerance could only be
     achieved by setting the U2X bit in the UART configuration.  It will
     be defined to 0 if U2X is not needed.

My resulting UART configuration, which may be being affected by the bootloader, is:
UBRR0H: 0x00
UBRR0L: 0x67
UCSR0A: 0x20
UCSR0B: 0x10
UCSR0C: 0x06

That equates to data register empty, RX enabled, 8-bit.
To my mind that is equal to the values being manually set in the code, so shouldn't be a problem.

No, it changes anything - still the program does not work as needed. With F_CPU = 16MHz and BAUD = 9600 it leaves U2X0 setting in the default value (I already checked this before).

Then there must be something else unrelated that is stopping it from working. This code works, I tested it on an Uno.

What could this be? I've been fighting with this all the week...

By the way, did you say you didn't have a bootloader installed, because you had BOOTRST enabled? With BOOTRST turned on (hf=0xDE) you boot into the bootloader. With it turned off (hf=0xDF) you boot into your code.

With it "enabled" (=0) you boot the bootloader. With it "disabled" (=1) you boot your code. Make sure you have it set right if you don't have a bootloader installed.

Oh, and on my Uno, which is like your setup 16MHz, I had to add the U2X code to make it work - the bit defaulted to the wrong state for 9600 baud.

Of course, BOOTRST must be disabled. Their enabled/disabled = 0/1 terminology is totally confusing... I'll change the fuse and report in a minute...

It's not their "convention" - it's normal. It's all to do with the fact that an un-programmed flash cell is 0xFF not 0x00, so they map the default values to be 1 and the non-default to be 0. That way it can operate direct from the factory without needing to have any fuse bits manually changed.

Maybe the fact that I am using a bootloader is leaving some value in a different state that you would need to change.  I will just print out my register values... one sec...

I'm very curious what is the problem ... Still nothing makes sense to me ...

@IgorLiferenko You need to disable the watchdog timer, and the only way I have found to do that reliably is using the functions in avr/wdt.h - the watchdog is a right pain and can be hard to get rid of when you don't want it - the bootloader disables it for you normally which is why I wasn't seeing a problem before.

I cannot disable it by any means - in fuses it is disabled and wdt_disable(); does not help. I would like to use the bootloader so that it will do necessary resets. Will anything change in my compile-burn workflow described above if I will use bootloader? (for example, burn my programs via ICSP, not via bootloader). The answer should be edited with this info, as it relates to the core problem.

Once the WDT has fired it's almost impossible to turn it off short of removing the power.  Once it is turned off though it won't fire again so won't get stuck in that condition.  The only difference for using the bootloader with ICSP is to make sure you don't wipe the bootloader when you program the chip, which means making sure you use the -D flag to disable chip erase.

I found the solution - see http://arduino.stackexchange.com/questions/17585/what-makes-the-watchdog-timer-start-on-atmega168-328p/17614#17614


text:
Controlling Servo Motors with push button. Problem though
I have this setup where I have and Arduino Uno, a mini servo motor, and a pushbutton. I use a single pushbutton to control the servo motor to go to one position, then push it again to go back. It first goes to 0 degrees, then if you push it it goes to 180 degrees then vice versa. The problem is that in its initial state (which is 0 degrees), the servo motor makes noise. Like it's running or something then it gets hot.
I've seen other servo motors that never do this. Here is my code by the way:
#include <Servo.h>

const int buttonPin = 8;
const int servoPin = 9;
int buttonState = 0;
int directionState = 0;
Servo servoOne;
int pos = 0;

void setup() {
  servoOne.attach(9);
  servoOne.write(directionState);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (directionState == 0) {
    if (buttonState == HIGH) {
      directionState = 1;
      for (pos = 0; pos < 180; pos = pos + 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  } else if (directionState == 1) {
    if (buttonState == HIGH) {
      directionState = 0;
      for (pos = 180; pos > 1; pos = pos - 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  }
}

I really need all the help I can get.

Can you try setting the initial state to a middle value like 20 or 30? I have these really cheap servos I bought on ebay (no datasheet or anything). Empirically, I've found that my range is less than advertised. I see something similar to what you described when I try writing a degree beyond what my servo is capable of.

You might need to add more time to the delay. Also, check how your powering the servo. If you're powering from the Arduino, it might be drawing to much current and causing issues. If it's a bigger servo, try to hook it up to an external power source and just connect the PWM line and it's ground.

also be sure to join the ground of the arduino with the ground of your external power supply (+5vdc)

Looks like your delay is too short. If the delay gets over before the servo can reach the set postion, it will skip that command and execute the next one.
Also I agree with @julio about how are you powering your servo. By "mini" servo I assume that you are using a micro servo. I have a Tower Pro 9G micro servo (which I use as steering servo btw, small but pretty decent), and it works fine if I power it with the Arduino UNO, but torque is a bit less. Anyways, check your servo's datasheet, your servo might need more power. Just hook it up to a power supply and make sure the grounds are common. The jitter might just be the result of inappropriate power.

The most basic issue with servo motors is wrong cabling and then insufficient motor driver in terms of amperage. And then, PWM duty cycle must be set correctly. If you don't treat those things properly, you may hear noises such as humming, vibration instead of turning the motor.

The code was absolutely ok but position 180 was a problem sometimes. Those servos simply can't reach position 180 because the end is on 178 or nearby. But the servo was trying to go on that position. The solution is simple: try a different position (179 or less).

I think you need to do some debouncing  on the button.
You can modify the code to suit your project:
/*
 Debounce

 Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
 press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
 a minimum delay between toggles to debounce the circuit (i.e. to ignore
 noise).

 The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached from pin 2 to +5V
 * 10K resistor attached from pin 2 to ground

 * Note: On most Arduino boards, there is already an LED on the board
 connected to pin 13, so you don't need any extra components for this example.

 created 21 November 2006
 by David A. Mellis
 modified 30 Aug 2011
 by Limor Fried
 modified 28 Dec 2012
 by Mike Walters

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Debounce
 */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

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

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH),  and you've waited
  // long enough since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButtonState = reading;
}

Your assessment is incorrect. The nearly second (180 * 5ms) of delay already present in the code already accomplises substantial debouncing.

The delay(5) is after servo.write() the debouncing is for the buttons!! I'm not sure what you are referring to. As an electronics and communication engineer, I believe I have a good idea of what I'm talking about!

You are fundamentally and grossly mistaken.  Because this is a serial execution language, once the button is detected high the entire blocking delay, 180 times 5 ms, must elapse before the state of the button will again be evaluated, which is an order of magnitude beyond typical debounce time. When it is seen as low, no action is taken so no debounce is required. Facts are facts, regardless of who you claim to be.

So you're saying the program is checking for the button state while it's executing the for loop?

No, rather obviously, once it decides to execute the for loop, it will ignore the button until the for loop is complete.  Ignoring an input after acting on it, until such time as any contact bounces must have died away, is the simplest and most basic form of debouncing.

And what happens when the button is set to low after the program has checked for the state?

Nothing happens when the button is set low.  But the key is that after the button is set high, the state of the button isn't even considered again for almost a second.  If you hold the button down, you can get it to slowly toggle modes, but that may not be undesired, and regardless it has nothing to do with the problem reported in the question.

NO, the button was left to high when the program checked for the state and was immediately set to low. Because there is no debouncing process in place the processor will miss the state change, as it's running on high frequencies. THIS means the program will run an extra loop and will cause problems in more important applications.

You are rather confused.   The program does not need to detect state changes, it is so slow that it can merely detect states.  If the user releases the button in less than 179*5 = 895 ms, the function will run only once.  If they hold the button down for longer than that, the motor will change position every 895 ms.  There is nothing in the question to indicate that such a result is undesired.  In fact, the question is quite clearly about a different problem entirely!!.

authors: 北京做假证_北京办文凭毕业证 - spam


text:
Computer to multiple arduino bluetooth modules
Im going to take part in a competition called IEEE Very Small Soccer and I need to set up a communication between my computer, that will run visual and strategy algorithms, and send some commands to 3 Arduinos, which will be the players. Most people use the Xbee module to send data to the Arduinos, so I was wondering why not use the Bluetooth module instead, once it is so much cheaper and the difference in power consumption isn't so big, the only drawback would be the working range, which is 10m, if Im correct... However, if the distance is really 10m, not 5m It will be ok, because the computer is always close to the robots.
Summing up, my questions are:

Can I use a computer to send data to 3 Arduinos at the same time?
What is the real working range of the Bluetooth module?
Any suggestions or tips? =D

?

yes, you can, this is what happens normally in a crowded area where multiple people use their phones with bluetooth headsets, for example.
if you believe the claims typical 10m max 100m but in practice there are a number of factors:

Quality of the HW design of the antennas
Signal to noise ratio due to other radios operating in the same area
Obstacles in the path
Responsiveness and throughput required by your application
etc.

you could consider other options, like this module, which is basically the same, from the perspective of transferring data. Also wifi could work, if you are allowed to setup your own access point.


text:
Connect HX711 to a three wire load cell
I have the following load cells:

I'm using the following HX711 amplifier
Every guide i can find on the internet describes how to connect a load cell with four wires to the amplifier. How can i connect a load cell with three wires to the amplifier?
Thanks in advance.

How many three-wire load cells do you have?

how can I get data from the 4 loadcell circuit??

A datasheet for the HX711 is https://cdn.sparkfun.com/datasheets/Sensors/ForceFlex/hx711_english.pdf  (On your board, it looks like E+ is AVDD and E- is AGND.)
Each of your two load cells could be a half-bridge of a wheatstone bridge, with excitation on the white and black, and sensing on the red like:
I have a similar loadcell with the colors as Blue-Red-Black, (instead of White-Red-Black as above, or the Red-White-Black in your image) with my red sensing wire in the middle.  The positive strain resistance (increasing resistance with increasing load) is between the Blue and Red, while the negative strain (decreasing resistance with decreasing load) is between the Red and the Black. The ~1000 ohm resistance in each leg changes by tenths of an ohm with hand pressure on the button, when the outer portion is supported, but the inner portion is not supported.  Your cells do not have the bridge-button part that create a balanced twist along the center portion, so it might be hard to reliably apply a load your cell.
To make positive deflections of the cells combine to unbalance the Wheatstone bridge, wire one cell's white and black opposite to the other cell, and attach them to E+ and E-, with the reds connected to A+ and A- like this:
   HX711.E+ : Cell1.White + Cell2.Black
   HX711.E- : Cell1.Black + Cell2.White
   HX711.A+ : Cell1.Red
   Hx711.A- : Cell2.Red

The labelling on the schematic isn't quite right-- the "Reference 1K" are actually the negative-strain portions of the cells, and might be better labelled as "-Active 1k Ohm".
If it moves in the wrong direction/wrong sign with increasing force, switch the reds or multiply by -1.
If you have only one three-wire cell, use a couple 1K resistors, or a 2K potentiometer to balance the existing cell as the other half of the Wheatstone bridge.  One issue with using discrete (10%, 5%, 1%?) resistors is that the precision and tolerances when configured as a voltage divider may produce a significantly different result as compared with the balance in a lead cell and its full-scale signal (+/-0.1%) in a loadcell.  A the center tap of a potentiometer can provide for tuning to match the load cell voltage.  For the HX711's 32x, 64x, or 128x gain, you need to keep the voltage differences between the sense terminals  between +/-80mV, +/-40mV, or +/-20mV to stay within the limits of the HX711.
Per @wirewrap's comment, the colors on the wire could be different than the picture I posted.  You can make certain by measuring the resistances between the wires and exciting on the pair with the greatest resistance, and sensing on the middle terminal.

In the picture of the OP's loadcell it looks like the common of the resistors is the white lead, not the red.

You are right.  One could measure the resistances and determine the center terminal to be certain.

When you have four half bridges I think that you will need to read them separately as pairs and then sum the result in software.  I would be interested in hearing how multiple hx711 modules should be best handled by a Nano.
Update.  I have discovered that sparkfun produce a load cell combinator board that assists wiring four half bridge load cells to appear as a full bridge.  I have still not understood how that works yet.

It seems like that module is used to connect the 4 wire load cell, but on the internet I found other schematics that might help you out how to wire it up.
This is one way (http://i46.tinypic.com/30j0d2t.jpg):

Otherwise try this way:

I am not an expert on load cells but it seems like you just need to give it a try and see if it works.

How can i connect a load cell with three wires to the amplifier?

it is one-side of the bridge.
the other side can be another load cell or a resistor bridge.


text:
Burning arduino generate hex file to blank atmel chip
Is it possible to burn the hex file to a blank chip, generated by Arduino to burn using USBASP to that particular chip without using Arduino board ? Will the program work ?

My main goal is to use Atmega328P for low power. Should I select Arduino pro mini in the arduino IDE ?
Ater successful testing I will just burn the hex file to another 50 chips. thats why I dont want to use arduino board.

Can you please reword your question to be a little more clear?

I wan to burn the hex file which is generated by arduino ide. But dont want to use arduino board. Instead I want to burn by USBASP like regular avr program hex file burning.

Note that the Arduino IDE supports several programmers directly, including the USBasp.

Yes. The binary generated by the Arduino IDE in no way requires the presence of the Arduino bootloader in order to operate. Note that certain characteristics such as the MCU and clock rate are set at build time and cannot be changed in the final binary.

Do I have to do anything with fuse settings while burning ?

The clock settings should match those expected by the code. The other fuses are up to whatever is required for the application.

Yes that's no problem as long as you check your fuse bytes. And the connections to the 6pin ISP header.
Make sure you study the avrdude command line and the manual for the particular Atmel chip.
I'm assuming the programmer you are using must use avrdude to be able to work.
I often use a nice GUI called "avrdudess" which is freeware. Great for avr beginners, and takes some of the effort out of writing directly into the command prompt.

I will check avrdudess

What will be the fuse settings if I use Arduino UNO as platform in IDE ?


text:
How to measure relay current draw from Arduino
How does one measure the amount of current a relay is drawing from an Arduino?
Do I connect a multimeter in series with the digital pin to which the relay 'IN1' is connected (in this case pin 7), the 5V pin or GND pin?
Provisional testing gives me the following results (when the relay is ON):

Pin 7: 3.93 mA
5V pin: 70.2 mA
GND pin: 66.8 mA

Also, assuming I pull more than 40 mA through digital pin 7 for a number of seconds, is the pin likely to fail immediately? Or slowly degrade over time?

What relay has an "IN1" pin? All mine have two coil pins and three or six switched pins.

My guess is you are using a relay (breakout) board, not a bare relay. 70mA sounds about right for a 5v relay. Which is indeed more that a digital pin can handle.

Have you noticed how the 5V current is, give or take a little inaccuracy on the part of your ammeter, the sum of the other two currents?
Without knowing what relay you are talking about, my guess is it is one of the SainSmart 5V relay modules with opto-coupler. Those, by default, use a common 5V input and split it between the opto-coupler (and then into your digital pin to be sunk through ground) and the relay to ground.  Therefore the 70mA is split between 66mA through the relay and 4mA through the digital IO pin.
So the correct place to measure the total current in this instance is the 5V pin since that is the common point for the circuit.
In answer to your second question, read the datasheet.  It quite clearly states:

Although each I/O port can sink more than the test conditions (20 mA at VCC = 5V, 10 mA at V CC = 3V) under steady state conditions (non-transient), the following must be observed:
ATmega48PA/88PA/168PA/328P:

The sum of all I OL , for ports C0 - C5, ADC7, ADC6 should not exceed 100 mA.
The sum of all I OL , for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100 mA.
The sum of all I OL , for ports D0 - D4, RESET should not exceed 100 mA.

If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.

And also a similar note for sourcing current.
So although they can sink or source more than 20mA, and theoretically up to 40mA, anything more than 20mA is not guaranteed and should be avoided.
Basically overcurrents cause increased heat dissipation in the MOSFETs which causes the internals to break down.  Hence the note about under steady state conditions.
So sourcing or sinking more than 20mA for longer than a few ms is asking for trouble. More than 40mA is just being irresponsible.
Furthermore, the MOSFETs in the IO pins act like resistors when turned on.  As you should know, according to Ohm's Law, the voltage across a resistor is proportional to the current through the resistor.  Increase the current and you increase the voltage across the resistor.  Since that resistance is in series with your circuit that voltage gets subtracted from your available voltage on the IO pin - so drawing too much current will cause the voltage to drop (or rise for sinking) below (above) the specifications for the logic voltage for that IO pin.  So not only do you risk damage to the IO pin and other parts of the chip through overheating, but you also then operate outside the specifications for the logic levels which can cause things that you are communicating with to not work right.

You are correct, the relay is a module board identical to that of the SainSmart 5V. Thanks for the detailed reply.


text:
Why were Atmel MCUs used for Arduino?
Atmel microcontrollers are not cheap compared to STM and Microchip. Why did Arduino select Atmel MCUs such as atmega328 and atmega2560 on their board out of so many alternatives?

Simply because the Wiring system that Arduino stole was written for the Atmel chips.
Arduino didn't "invent" the Arduino system - they just took an existing system called Wiring and adapted it slightly and branded it Arduino.

I wonder why did Arduino succeed when Wiring failed given that Wiring had first-mover advantage.

It's called Marketing. If you have it then you win.

Actually, "stolen" is quite a bold word. If Wiring didn't want any forks, they should use licence that prevents them, not GPL created exactly to allow them. At least that's for software, can't find licences for actual wiring, but arduino uses open licence for them as well.

@Mołot Maybe "Appropriated" then?  Blatantly used and pretty much claimed as their own with little or no reference to the original Wiring project.  Actually, "stolen" fits that quite well...

@Majenko AFAIK they posted all references actually required by original licence. Of course, GPL is easygoing about that. But that's what Wiring decided to use. Are you using any sources just the way licence allows you to? Does it make you a thief?.. Would you find it fair to call you thief if you follow licences of code you use?.. OK, they wasn't as nice as they might be, but they fulfilled their duties. It's not like Wiring ever forbade what they did.

This was the first time I've heard of Wiring. It's interesting how little recognition they've received. Also it's not easy to google their name, since the name is so generic.

The site is wiring.org.co and yes, it's hard to search for something that is named after such a generic word. @Mołot The license allows them to use the code without asking etc, which is fine. But they completely stole the whole market segment from Wiring, and that isn't covered by the GPL license.

I don't really get the impression the Arduino crew misrepresented themselves as far as their use of Wiring. And a probably more significant part of what Arduino is about is making the hardware easy to use (IMHO).


text:
Arduino UNO, using 5V and 3.3V
I am newbie in Arduino (using UNO) and as I have 2 components that I wish to connected that one needs 5V and the other need the 3.3V, is it safe to connected them together next to each other?

In general, yes: you would just connect the 5v component to the Arduino's 5v output pin, and the 3.3v component to the Arduino's 3.3v output pin. They should share the same ground connection. Just make sure not to give the 3.3v component 5v power.

You may put a potentiometer to change and organize the voltage, if you need.

If a component needs 5V it must be connected to 5V. If it needs 3.3V it must be connected to 3.3V.  Connecting a 3.3V component to a 5V supply is a sure fire way of destroying it.
Furthermore, since the Arduino's main chip is a 5V device, if you want to connect it to a 3.3V device you must use some form of level translation so that the 5V signals from the Arduino don't damage the 3.3V device. Also it may (though not always) be necessary to convert the signals from the 3.3V device to a level that the Arduino can understand (5V).

"sure fire way" - pun intended?


text:
Can't get Ubuntu to see FTDI cable for breadboarding Arduino project
I am in the process of breadboarding an Arduino for a project and am using my FTDI Serial cable Adafruit FTDI Cable (tested working on Windows 7). I have also tested the breadboarded Arduino successfully on Win7.
When I plug the FTDI Serial cable into my Linux (Ubuntu 14.04 with Mint Desktop) laptop and the other end to my project (exactly as I did for Windows and it works for Win7), the Tools, Port is grayed out when in Linux.
I have tried running Arduino as root, with no success.
The output of : dmesg | tail is
sudo dmesg | tail
[  729.069015] usb 4-1.2: New USB device strings: Mfr=1, Product=2,     SerialNumber=3
[  729.069019] usb 4-1.2: Product: TTL232R-3V3
[  729.069022] usb 4-1.2: Manufacturer: FTDI
[  729.069024] usb 4-1.2: SerialNumber: FTF50VXW
[  729.487689] usb 4-1.2: USB disconnect, device number 4
[  729.615330] usbcore: registered new interface driver usbserial
[  729.615384] usbcore: registered new interface driver usbserial_generic
[  729.615432] usbserial: USB Serial support registered for generic
[  729.621997] usbcore: registered new interface driver ftdi_sio
[  729.622057] usbserial: USB Serial support registered for FTDI USB Serial Device

When I type "lsusb" into the terminal, there is no difference between when the FTDI is plugged in and not plugged in.
I have tried switching ports with no success.
Any suggestions?

Is there a /dev/ttyUSB0 file entry with the cable plugged in?

If it is not in the lsusb output, there should not be a device node - if there is, it is not connected to anything.  By appearances, the USB connection has failed after briefly being recognized - try a different port, try it with the logic end of the cable not connected to anything, try it with a hub or without one if you were using one.

Check if the driver is loaded, in Terminal type:
lsmod | grep  ftdi_sio

If you get no answer then it's not loaded, load it using:
sudo modprobe ftdi_sio

I hope this helps.

lsmod | grep ftdi-sio
shows that the driver is already loaded.

lsmod | grep ftdi-sio
shows that the driver is already loaded.
The device is appearing in the /dev/ folder
Now when I try to upload code I get a avrdude out of sync error. I have confirmed I have the correct device (UNO) selected. As the Arduino is breadboarded, I press the reset button just as compilation completes (I use this same timing successfully when downloading from my Win7 machine).


text:
creating array using string name
I appreciate if someone can help me.
I have a function that counts the time and I would like to store values according to the day.
For example: day_7.11.2015 = [gain = 100.23, cost = 78.0 ...]
              day_8.11.2015 = ...
I do not know how can I create an array with these values taking as input the day, month and year. Does anyone have any idea?
String test = "day_" + String(day) + "." + String(month) + "." + String(year);
float String(test)[] = {11.2, 10, 20, 31.2};
 Serial.println(test);
Thanks a lot!

What is your end goal?  Is this an Arduino-related question?  Please edit question and state the general idea before obscure details.

What you're talking about is often called a Hash or a Map or sometimes both together as a HashMap.
Unfortunately it's a facility that isn't supported in the Arduino C++ language
There are map objects available in normal C++, but they are incredibly expensive to use with regards to memory and they just aren't practical for use on a small microcontroller with memory measured in the kilobytes.
The closest you can probably get is to "invert" the storage, so you have a list of values that happen to be in date order (because that's when you added them) but the "key", a simple sequential number, doesn't define the date.  Instead you store the date inside the array along with the data - assuming you really need to know the date.
A good concept to get to grips with for this is the struct.  This is a custom data type which you define and can store a number of other different data types within itself.  You can then make an array or linked list out of those new data types.
For instance, you may have:
typedef struct {
    int year;
    byte month;
    byte day;
    float gain;
    float cost;
} Data;

You can then create variables of type "Data" and assign values to the items within it:
Data myEntry;
myEntry.year = 2015;
myEntry.month = 11;
myEntry.day = 7;
myEntry.gain = 100.23;
myEntry.cost = 78.0;

Or assign them directly at creation time:
Data myEntry = {2015, 11, 7, 100.23, 78.0};

If you wanted to store 100 days' worth of data you could use an array:
Data myArray[100];

Then you access each slice:
myArray[0].year = 2015;
... etc ...

I mentioned above "assuming you really need to know the date".  Most of the time with this kind of method you really don't need to store the date.  If you have one entry per day and you know when you started gathering data then you know that each entry is one day more than the one before it - so you know that the tenth entry is ten days later than when you started gathering data.  Alternatively, if you have a 100 entry circular array (that is, when you reach the end of the array you start filling from the bottom again, so you keep the last 100 days' worth of data) and you know what the date is today you can count backwards from today to work out what date each entry is.

Hi Majenko,
I tried to solve the problem with structs, but I'm not sure how it works. I could not even run the examples I found on the internet.
Your example worked here. But I can not access the values that I want. How should I do if I want to access the value of the variable cost that I created? Is printing another value when I try   :|


text:
Uploading sketch to ESP8266
I'm managing to upload a sketch to the ESP8266 01. I have been researching on internet but I'm not able to get it.
I have installed the libraries for Arduino IDE and my circuit is the ESP powered by 9V converted to 3.3V using a LD 3.3 converter. I tested the voltages and works fine. Also the led in ESP is on (red).
To connect to the computer I'm using a TTL USB cable without vcc connected only for tx and rx.
The commands for the ESP works fine (AT commands), but when I try to upload a sketch it shown the following error:

espcomm_open failed

I also have connected to GP0 (ESP) a button to ground. The circuit is:
9V battery --> 3.3V converter --> ESP---> TTL
Anyone knows about that error and why could be? Because the AT commands works fine. Maybe I need to provide more information but not sure.
My goal is to do this tutorial:
https://learn.adafruit.com/downloads/pdf/esp8266-temperature-slash-humidity-webserver.pdf
Another problem that I have following that tutorial is that in Arduino IDE, I cannot setup esptool as programmer, because isn't there. I loaded the same library for esp

If when I tried to do the commands and now doesn't work, means that I have to reflash the AT firmware again?

Are you using the original AT firmware?

Are you releasing GP0 from ground once the ESP has turned on?

Following on from user1637451 the following sequence has always worked for me:

Before download, pull both GPIO0 and RST to ground.
Release the pull down on RST, but keep GPIO0 low.
When the IDE has finished downloading, release GPIO0 from low.

I usually have pull-up resistors (10K) on both RST and GPIO0.
As to the IDE problem. I used the tutorial from Sparkfun entitled "ESP8266 Thing Hookup Guide" and then the section "Installing the ESP8266 Arduino Addon". Because I used a different ESP8266 board to them I set the IDE to use the "generic ESP8266 board". This worked for me.


text:
Getting a binary string and convert it to decimal
I have a 4 dipswitch to get a 1 or a 0, try to get that into a string and from that get a decimal, therefor if I get for example a 0011 a 3.
so, I know that from the variations of 0000 to 1111 is a decimal from 0 to 15, I already have my string but how do I convert the "binary string" to decimal?
to get the string I'm using this (the I is at 5because there is where is the dipswitch):
      for(int i = 5; i <= 9; i++){
           Serial.println(digitalRead(i));
           Dstate = Dstate + digitalRead(i);
      }

What has a String got to do with anything?

What you want are the bit-shifting operators << and >>, and the OR operator |:
for(int i = 0; i < 4; i++) {
    Serial.println(digitalRead(5 + i));
    Dstate = Dstate | (digitalRead(5 + i) << i);
}

You'll notice I changed the loop so it runs from 0 to 3 instead of 5 to 9 - it makes other parts easier if you start counting from 0.
Then the line:
Dstate = Dstate | (digitalRead(5 + i) << i);

is where all the magic happens.  Let's break it down:
digitalRead(5 + i)

That of course gives you a 0 or 1 for pins 5, 6, 7 and 8 in turn.
<< i

That shifts the value returned by digitalRead() left i bits.  For instance, if digitalRead() returns 1 and i is 0 then 1 is left shifted 0 times so remains as 0b0001.  If i is 1 then it left shifts one bit, so the value becomes 0b0010.  If i is 2 then it shifts two bits, so you get 0b0100.
Finally the result is combined with the current value of Dstate with OR, so the four values basically get laid over the top of each other.
So say you have the four switches in the positions ON-OFF-ON-OFF and Dstate starts off as 0, then the sequence would be:
i = 0, digitalRead = 1, shifted = 0b0001, OR = 0b0001
i = 1, digitalRead = 0, shifted = 0b0000, OR = 0b0001
i = 2, digitalRead = 1, shifted = 0b0100, OR = 0b0101
i = 3, digitalRead = 0, shifted = 0b0000, OR = 0b0101

awesome response, but then how do I change the value 0b0101 to decimal and get a number from 1 to 15?  because if I try 0b0101 in a binary to decimal calculator from google, it obviously won't work

It already is a number from 0 to 15.

yeah you are right! I messed up when I copied and pasted your code and then started playing with the dipswitches to notice the change.


text:
Arduino Leonardo bugs and lack of removable microcontroller
Following one of the article from 2013 :

Before you start hammering that “add to shopping cart” button, note
  that the general impression around the web seems to be that the
  Leonardo still has a few bugs that need ironing out, and isn’t quite
  as beginner friendly as the Uno. For builders already familiar with
  Arduino, this is the better deal.

The question is if Leonardo is still buggy and may cause any confusion to newbie Arduino programmers. Furthermore, Leonardo doesn't have removable chip, so how can one transfer the project into a separate processor and use Arduino to the other project?

The question is if Leonardo is still buggy

Probably.

and may cause any confusion to newbie Arduino programmers.

Definitely.  The whole way the Leonardo works is very different to the likes of the Uno. Transitioning from one to the other, if you don't know what the differences really mean, can be confusing.

Furthermore, Leonardo doesn't have removable chip, so how can one transfer the project into a separate processor and use Arduino to the other project?

You build your circuit on a PCB and you provide an ICSP header.  ICSP stands for In Circuit Serial Programming.  You then use a hardware programmer to install either the Leonardo bootloader, which can then be used to install sketches through USB, or install a sketch direct without the bootloader.
Or, if you're making thousands of them you send your code to Atmel and they burn it to the chip in the factory for you - at a price of course.


text:
Turning on led every half hour
How can I make my program so that every half hour LED lights on and work for 5 minutes and than go off and the process should repeat
I made code but it does not works. Can someone help me?
void setup() {
  pinMode(8,OUTPUT);

}
void loop() {
  digitalWrite(8,HIGH);
  delay(300000);
  digitalWrite(8,LOW);
  delay(1800000);

}

Whats the problem? what's happening? btw. this does shift 5min every 30min... you can try this: http://playground.arduino.cc/Code/SimpleTimer

When i run my code nothing happens.

First start with a smaller delay (a second or so) until you know it is working.

Test the LED: Connect it between +5v and ground with its current-limiting resistor. Make sure the cathode is connected to ground and not the other way round. Inside the plastic bubble are two tiny bits of metal. The larger one is the cathode. Does it light? If not, the LED is faulty or the resistor is too high.
Reconnect the LED to pin 8, which is physical pin #14. (In case you got confused and used physical pin 8, no harm was done - physical pin 8 is another ground!) Reduce the delay times to 1 second on, 1 second off. Again be sure to connect its cathode side to ground. Does it blink? If not, perhaps Arduino's pin 8 driver is faulty.
Try the same thing on a different pin (adjusting your code, of course). If it still doesn't blink, there is probably an issue with either the MCU chip or the power you're supplying to it. Assuming you used the board's +5v and ground in test (1.), then the power is OK and the chip is likely the cause.

I see that the code is OK,
are you sure that the led pis is 8 ?
what is your input voltage ? (is it between 7 to 12 ?)
did you tried lower time values ? (like 1:2 minuts ?)
if you answer to all of these questions is "yes" then probably the arduino board is broken.

You need to make sure that the LED is connected with the right polarity, you need to connect the negative to Ground and the positive to the digital pin 8.
Try the led by connecting 3.3v and GND so you are sure that the led is not broken.


text:
what is the difference between providing 7 volts or 12 volts to arduino uno?
according to this the recommended input voltage is between 7 and 12 volts.
The question is what is the difference between providing 7 volts(minimum recommended volts) and 12 volts(maximum recommended volts) ?.

The amount of heat dissipated by the voltage regulator.  The higher the voltage you supply the hotter the regulator will get.

I agree with Majenko. A higher voltage will make the voltage regulator run hotter, particularly if you are drawing a lot of current (eg. to power LEDs or similar). However since you probably won't find a 7V wall-wart, they give you a range of voltages that are acceptable.