text:
Difficulties with raw string literals
I have an application where I would like to include an external multiline script as a const in my sketch. As far as I understand from C++11, this should work:
raw_string_literal_test.ino
const char *script =
#include "script.txt"
;

void setup() {
  // put your setup code here, to run once:

}

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

}

script.txt
R"(Line 1
Line 2
Line 3
Line 4
Line 5
Line 6)"

script.txt is placed in the same folder as raw_string_literal_test.ino
However, upon clicking Verify (selected board is Arduino/Genuino Uno, Arduino version is 1.6.12 on Mac OS 10.11.6) I get the following error:
/Users/owner/Desktop/raw_string/raw_string.ino:2:22: fatal error: script.txt: No such file or directory
 #include "script.txt"
                      ^
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno.

What am I doing incorrectly?

Try renaming the script to "script.h".

Perfect - thanks Mikael - I am guessing the build recipe doesn't like the .txt extension!

I guess that you could have a "script.h" that includes a "script.txt" once the Arduino preprocessor is convinced that the sketch is using the local directory the path is included in the build/compile.

That's a good point - but practically I can deal with a little renaming. The main aim is to avoid escape hell (and the readability issues that it brings) in putting a small test script into flash (on an ARM device).

Unlike other more "normal" build systems, the Arduino IDE doesn't compile the files in the project directory.
Instead it loads all the files with certain extensions into the IDE, each in its own tab. When you press the compile button it then writes the contents of each of those tabs to files in a temporary build folder and then compiles there.
Because of that only files with certain extensions ever get placed in the build folder. Those include:

.pde and .ino for sketch files
.c and .cpp for C and C++ source
.h for headers
.S for assembly source.

There may be a few others as well but those are the main ones. Things like text files aren't considered source files and thus aren't ever seen by the IDE.


text:
Will unnecessary Serial.print() statements slow down my program?
I have lots of Serial.print() and Serial.println() statements throughout my (rather large) program for debugging when things fail. I've commented out the Serial.begin() statement so I don't slow down execution by running a serial port. However, I'd like to leave the Serial.print() calls so I only have to uncomment Serial.begin() later on.
If there is no Serial port active on the device, are the Serial.print() lines still executed at runtime, or does the compiler ignore them? Is there any performance advantage to explicitly commenting out those lines?

You may write your program in machine code instead then you'd know exactly what the microcontroller is doing.

What has that got to do with Serial prints?

No, there is no USART wasn't enabled so skip all prints. Everything must be done anyways (calls, conversions to strings, writes to UDR - USART Data Register). It is just not sent outside by USART and it doesn't have to wait for UDRE (USART Data Register Empty flag) so it might be slightly faster.
You can use similar technique as Loggers - log level variable and ifs (this can be changed runtime).
Or you can use macros:
// comment out this line, if you want to show logs:
#define NDEBUG

#ifdef NDEBUG
  #define LOG(...)
  #define LOGLN(...)
#else
  #define LOG(...) Serial.print(__VA_ARGS__)
  #define LOGLN(...) Serial.println(__VA_ARGS__)
#endif

And later:
LOG(F("Something: 0x"));
LOGLN(variable, HEX);

And how it looks after macro substitution? For code:
if (...) LOG(F("something")); else LOG(F("something else"));

With NDEBUG defined it's expanded to:
if (...) ; else ;

And without NDEBUG defined it's expanded to:
if (...) Serial.print(F("something")); else Serial.print(F("something else"));

A quick test shows that not doing a Serial.begin makes things run 10 times as fast. For example:
void setup ()
  {
  Serial.begin (115200);
  pinMode (13, OUTPUT);
  }  // end of setup

void loop ()
  {
  digitalWrite (13, HIGH);
  for (byte i = 0; i < 100; i++)
    Serial.println ("But does it get goat's blood out?");
  digitalWrite (13, LOW);
  delay (500);
  }  // end of loop

That took 292 ms to do 100 x of those prints on my Uno. If I comment out the Serial.begin call it takes 29 ms. So, faster but not incredibly fast.
On my page about debugging I have suggested code to turn on or off debugging prints. The basic idea is to have a Trace define that lets you output stuff if debugging is on, like this:
#define DEBUG false

// conditional debugging
#if DEBUG

  #define beginDebug()  do { Serial.begin (115200); } while (0)
  #define Trace(x)      Serial.print   (x)
  #define Trace2(x,y)   Serial.print   (x,y)
  #define Traceln(x)    Serial.println (x)
  #define Traceln2(x,y) Serial.println (x,y)
  #define TraceFunc()   do { Serial.print (F("In function: ")); Serial.println (__PRETTY_FUNCTION__); } while (0)

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

void setup ()
  {
  beginDebug ();
  pinMode (13, OUTPUT);
  }  // end of setup

void loop ()
  {
  digitalWrite (13, HIGH);
  for (byte i = 0; i < 100; i++)
    Traceln ("But does it get goat's blood out?");
  digitalWrite (13, LOW);
  delay (500);
  }  // end of loop

Now in this case, with DEBUG defined as false, the time taken with pin 13 high is now only 5 µs - a substantial speed-up.
If you define DEBUG to be true, then it is much slower - 290 ms as in the first test.

The suggestion made by KIIV will fail if you have if statements:
#ifdef NDEBUG
  #define LOG(...)
  #define LOGLN(...)
#else
  #define LOG(...) Serial.print(__VA_ARGS__);
  #define LOGLN(...) Serial.println(__VA_ARGS__);
#endif

For example:
if (something)
   LOG ("something is true");

digitalWrite (8, HIGH);

Imagine that debugging is off. Now the empty define makes the code look like:
if (something)
  digitalWrite (8, HIGH);

So you have a side-effect that the code behaves differently if debugging is off.

Semicolon is not part of the macro, so it will be expanded into: if (something) ;

See What does the c precompiler do with macros defined as (void)0 - there are subtle issues with using an empty define compared to void(0).
For example:
  Serial.println ("hi there"), LOGLN ("debugging");

That fails to compile (with the empty define) if debugging is off. The void(0) version does compile. Admittedly it's an edge case, but nevertheless ...

Semicolon is not part of the macro, so it will be expanded into:  if (something) ;

A way around the if(...) [macro] problem is, when debugging is turned off, to define your macros to equate to {}, such as #define LOG(...) {}, then the if(...) turns into if(...) {}

@Majenko But if you have: #define MACRO() {} and you'll use it as: if (...) MACRO(...); else ...  (notice that semicolon) it will turn into if (...) {}; else .... That's why the pattern do { ... } while(0)  is used sometimes instead of simple block { ... }

Semicolon is not part of the macro - you edited your post after I made mine. In your original post (as you can see from what I copied/pasted) you had semicolons.

The compiler cannot know what the situation with the device is at runtime. The function itself must determine that, so the call will take place, with arguments and everything. A well-written function would test early on whether there was anything to do, and if not then return early - but that still wastes time.
The norm in programming is to have two versions of the code: one labelled "DEBUG", which has lots of print()s, and one labelled "RELEASE", which uses language contructs to ignore them. This is achieved a number of different ways - but Arduino doesn't really support this out of the box.
@KIIV's answer, using #define, is one way to do this. The problem with it comes when you have multiple modules, or are using libraries that themselves do their own print()s. If you only have your main sketch, then it would work fairly well.

source: Stack Exchange

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

sort: votes


text:
Function to send SMS in PDU format
I'm trying to send SMS using Arduino Uno v3 and Sony Ericsson K700i. I have a function that converts a text and a number to pdu format but I'm unable to deliver the message. I don't get any error after posting the serial data to phone. Could someone please quide me?
Here is the function that I use
void send_sms(String message, String phone_nr )
{
 byte original_byte;
byte newbyte;
int pdu_length;
int counter;
String newphone_nr;
int numlength;

 delay(1000);
  Serial.begin(9600);
  delay(1000);
  numlength=phone_nr.length()-1;
  if (numlength% 2 != 0 ) {
    phone_nr += "F";
  }
  for(int x = 0; x < numlength; x = x+2){
    newphone_nr.concat(phone_nr.charAt(x+2));
    newphone_nr.concat(phone_nr.charAt(x+1));
  }

  //start sending SMS
  Serial.println("AT");  //optional: say hello to the modem
  delay(3000);
  Serial.println("AT+CMGF=0"); //set pdu mode
  delay(3000);
  int textlength= message.length()*7/8;   // text message length: number of characters*7/8
  if (message.length()*7%8 != 0) {
    textlength++;
  }
  if (numlength%2 != 0) {   //if the length of phone number was uneven, it now increases by 1 because of the added "F"
    pdu_length = (8 + (numlength+1)/2 + textlength);
  }
  else { //8 bytes of parameters + (length of phonenumber)/2 + number of bytes in the text
    pdu_length = (8 + numlength/2 + textlength);
  }

  Serial.print("AT+CMGW="); //message will be stored in the mobile phone - AT+CMGS will send it off.
  //delay(3000);
  Serial.println(pdu_length);
  //delay(100);
  Serial.print("001100");  //these are some parameters which we don't need to bother about
  //delay(100);
  if (numlength<16){       //now we have to send the byte containing the length of the phone number in HEX format
    Serial.print(0);
  //delay(100);
  }        //the byte in HEX format needs to be 2 characters long; if needed we add a 0 in front, e.g. "C" will become "0C"
  Serial.print(numlength,HEX); //length telnr - this time any additional F is not to be considered
 // delay(100);
  Serial.print("91");     //international format of phone number //81 for national format
  //delay(100);
  Serial.print(newphone_nr); //now we send the rearranged phone number
  //delay(100);
  Serial.print("0000AA"); //some more parameters
  //delay(100);
  if (message.length()<16){
    Serial.print(0);
    //delay(100);
  }       //a byte in HEX format indicating the length of the text. Again the byte needs to be made of 2 characters
  Serial.print(message.length(),HEX);
  //delay(100);

  counter=0;
  newbyte=0;
  for (int j=0; j<message.length(); j++) {
    original_byte = message.charAt(j); //one by one we take each byte out of the original text

    for (int i=0; i<7; i++) {
      newbyte=newbyte|bitRead(original_byte, i)<<counter;  //take the bits 0 to 6 of the old byte, shift as required for the new byte and add to the new byte
      counter++;
      if (counter==8) {
        counter=0;          //if a new byte is complete, set the counter to 0
        if (newbyte<16){
          Serial.print(0);
         // delay(100);
        } //each byte in HEX format should consist of 2 characters, if necessary add 0 in front
        Serial.print (newbyte, HEX); //when the new byte is finished, send it to the mobile phone
        //delay(100);
        newbyte=0; // the next new byte will start again from 0
      }
    }
  }
  if (message.length()*7%8!=0) {    //if there were remaining bits (not enough to form a new byte), these are sent out as the last byte
    if (newbyte<16){
      Serial.print(0);
      //delay(100);
    } //each byte in HEX format should consist of 2 characters, if necessary add 0 in front
    Serial.println (newbyte, HEX);
    //delay(100);
  }
  delay (3000);
  Serial.write(26); //this is a command telling the mobile phone that the end of the transmission has been reached

}

Q1: Is there any way I can add service message center as a parameter?
Q2: How can I make this functionshow the phone response to the commands I give?
Thanks a lot!

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


text:
How to disable Due USB power?
I need my Arduino Due to work only from external power supply, not from USB power. Is there any way to modify the circuit to allow this? I still need to keep USB communication, but it should happen only when external power is on. Thanks

Disabling USB power is slightly tricky, as the incoming USB power is not only used for potentially powering the system, but it is also used by the various USB interfaces to indicate the presence of a connection.
The best way, looking at the schematics of the Due, would be to remove one or both MOSFETs that switch the USB power - that's T1 for the native port and T2 for the ATMega interface.  That will isolate the USB power from the 5V system while keeping it connected to the VBUS pins of the relevant microcontrollers.

Thanks, I removed the MOSFET and now it works exactly as I want!

There is four ways I know of you can do to achieve exactly this :

You can remove the usb polyfuse from your board, which will make the usb behave exactly as you need it to. Between the 2 two usb connections in this picture  is a smd component marked 501V. This is your polyfuse. Disabling this cuts the +5v line to the board from the usb but leaves the data lines open.
If you dont want to physically modify your board, then there is 2 other solutions you could use instead. You can buy a data-only usb cable, but they will probably be expensive and difficult to find.
Modify your usb cable. It has 4 pins used by the board, +5v, GND, and the 2 data comms pins. All you have to do here is cut out or block the +5v. The GND pin is still needed as the data pins still draw power off the board.
The arduino boards auto select a power source(the usb usually) if you have both usb and external power connected at the same time. A way to force the board into switching to the external power source instead, while supplying power to the data lines on the usb is to make sure the dc supply is greater than 6.6v.

Edit: That last one is for the 5v arduino boards, I just remebered the due works on 3.3v instead so this probably won't work on your board

Thanks  a lot for your detailed comment, I already got this working by removing the MOSFET. I'll keep these methods in mind though.

@ruffles Removing the polyfyses or otherwise killing the incoming USB power is a bad idea since that would isolate the incoming USB power from the VBUS pins of the ATMega and/or the SAM3X, which it needs to know if there is a USB connection for it to work with.


text:
5V+ Voltage to the arduino analog
If I connect a 12V / 12V+ battery to the arduino (uno) analog, will it be damaged ? What if I connect 230-240V to it ? Don't worry I haven't tried it yet. :D
Thanks in advance.

Yes, it will be damaged.  Especially if you connect mains direct to it.
The Arduino is designed to take up to 5V on any of its IO pins.  Any more than that is asking for trouble.  A slight amount above (as in say 5.5V) is usually tolerated OK, but anything more than that WILL cause irreparable damage.
And with mains, maybe even death.
For low DC voltages, like +12V, you can use a voltage divider to reduce the voltage to a 0-5V range.
For mains you will need to first reduce it down massively to a safe level (for example through a transformer) then re-scale and adjust it from there.  Note that mains is AC not DC so it has a negative value of voltage as well, so you will either need to rectify and smooth it to create a DC voltage or, if you are interested in the waveform itself, reduce the voltage even more and add a DC offset into it to move the mid-point of the AC waveform up to around 2.5V.

The inputs have clamping diodes, so you can put more that 5.5v on them, but you have to limit the current of the diodes will burn up. Adding a high value resistor between the higher voltage and input will do this. However, every voltage higher than 5v will give the same analog value as 5v does.

@Gerben More than 5.5V violates the absolute maximum ratings. Lack of Death is not guaranteed. . > 5V when operating violates the operating conditions - walking funny until powered off and on again may happen.

For the 12 V battery, let's assume it might get up to 15 to 20 V when charging, so we need a voltage divider to divide that down.

The zener diode is there to clamp the input to no more than 5.1 V in case of spikes or other damaging things on the input.
The voltage divider will divide down to 25% of the input, ie.
output = R2 / (R1 + R2) = 10 / (30 + 10) = 0.25

So now if you measure 5 V on the analog input you know you have 20 V on the battery. Thus you can scale your calculations appropriately.
(A more common value would be a 33 k resistor, in which case redo the calculation and scale accordingly).

For 240 V I strongly advise against trying something like that with bigger resistors. For one thing, 240 V RMS will have 240 * sqrt (2) = 340 V peak to peak. And that is both negative and positive.
A suitable approach would be to run through a small transformer, which will reduce the voltage and also isolate you from (almost) certain death.
In addition to that you would need to rectify the resulting voltage (say, 12 V) so that you don't put negative voltages into your input pin. And on top of that filter it so smooth out the peaks and troughs.


text:
UNO Timer 1 CTC mode not resetting TCNT1
I'm trying to set up timer 1 to run an isr in CTC mode. no matter what i set OCR1A to it always executes at the same frequency and if i print out TCNT1 I get values higher than OCR1A.
here is my Code
    void timer1_init()
    {
    // set up timer with prescaler = 8 and CTC mode
    TCCR1B |= (1 << WGM12)|(0 << CS12)|(1 << CS11)|(0 << CS10);

    // initialize counter
    TCNT1 = 0;

    // initialize compare value
    OCR1A = 100;

    // enable compare interrupt
    TIMSK1 |= (1 << OCIE1A);

      // enable global interrupts
        sei();
    }

ISR(TIMER1_COMPA_vect){
    SET(MOTOR_PORT,LEFT_MOTOR_STEP); //set the pin high
    delayMicroseconds(3); //keep high for a bit
    CLR(MOTOR_PORT,LEFT_MOTOR_STEP); //set it low
}

I'm using this to drive a stepper motor so using PWM mode wont work.

It sounds as though timer 1 has not in fact been set to wavegen mode 4. You can ensure that it is by also clearing the other bits of WGM1:
TCCR1A &= ~(_BV(WGM10) | _BV(WGM11));
TCCR1B &= ~_BV(WGM13);

I normally assign to TCCR1A and TCCR1B rather than "or". That way I know it is set to a fixed value.


text:
Arduino yun strange uploading error
I'm new to arduino and I'm trying to upload a fairly large (I think) program to a arduino yun which includes a 3 dimensional array. I'm using the bridge features of the yun.
when I upload the first time after unplugging and plugging back in again it runs fine. When I try and upload a second time I get the following error regardless of which code I'm trying to upload (blink example for example)
 avrdude: verification error, first mismatch at byte 0x0000
 0xff != 0x0c avrdude: verification error; content mismatch

In the serial monitor I get the following output:
Unable to connect: retrying (1)...
Unable to connect: retrying (2)...
Unable to connect: retrying (3)...
Unable to connect: retrying (4)...
Unable to connect: is the sketch using the bridge?

I'm currently developing as much as I can in another sketch but it's a pain.
I can provide the code if needed.
Thanks for any help


text:
RDM630 RFID Reader on Beaglebone Black?
I have an RFID reader RDM-630 with these specifications: http://www.seeedstudio.com/depot/datasheet/RDM630-Spec..pdf
Could I connect this to a Beaglebone Black?

Yes.  But why ask us?

BBB I believe is off topic for the site: http://arduino.stackexchange.com/help/on-topic

Found what I was looking for and the answer is yes.


text:
Buttons for LED strip only work when held down
I am trying to make a 24 button board that assigns different methods to each button. When a button is pressed, it should interrupt the method of the previous button and begin the new method. Currently, the button has to be held down in order to work. I'm not sure why since the methods should continue without being held down. All 24 methods are similar to the one posted below.
loop(){
  if (digitalRead(inPin(5)) == HIGH){
    fifthButtonTheatreChaseRedSlow(strip.Color(127,   0,   0), 100); // Red
  }

void fifthButtonTheatreChaseRedSlow(uint32_t c, uint8_t wait) {
  for (int j=0; j<100; j++) {  //do 100 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (int i=0; i < strip.numPixels(); i=i+3)
      {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();
      delay(wait);

      // give up if switches pressed
      if (digitalRead (inPin(1)) == HIGH ||
             digitalRead (inPin(2)) == HIGH ||
             digitalRead (inPin(3)) == HIGH ||
             digitalRead (inPin(4)) == HIGH ||
             digitalRead (inPin(6)) == HIGH ||
             digitalRead (inPin(7)) == HIGH ||
             digitalRead (inPin(8)) == HIGH ||
             digitalRead (inPin(9)) == HIGH ||
             digitalRead (inPin(10)) == HIGH ||
             digitalRead (inPin(11)) == HIGH ||
             digitalRead (inPin(12)) == HIGH ||
             digitalRead (inPin(13)) == HIGH ||
             digitalRead (inPin(14)) == HIGH ||
             digitalRead (inPin(15)) == HIGH ||
             digitalRead (inPin(16)) == HIGH ||
             digitalRead (inPin(17)) == HIGH ||
             digitalRead (inPin(18)) == HIGH ||
             digitalRead (inPin(19)) == HIGH ||
             digitalRead (inPin(20)) == HIGH ||
             digitalRead (inPin(21)) == HIGH ||
             digitalRead (inPin(22)) == HIGH ||
             digitalRead (inPin(23)) == HIGH ||
             digitalRead (inPin(24)) == HIGH)
               return;

      for (int i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

Not sure if it's a hardware issue or a software issue.

Related to Multiple buttons activating different methods for an LED strip
 // give up if switches pressed
  if (digitalRead (inPin(1)) == HIGH ||
         digitalRead (inPin(2)) == HIGH ||
         digitalRead (inPin(3)) == HIGH ||
         digitalRead (inPin(4)) == HIGH ||
         digitalRead (inPin(6)) == HIGH ||
         digitalRead (inPin(7)) == HIGH ||
         digitalRead (inPin(8)) == HIGH ||
         digitalRead (inPin(9)) == HIGH ||
         digitalRead (inPin(10)) == HIGH ||
         digitalRead (inPin(11)) == HIGH ||
         digitalRead (inPin(12)) == HIGH ||
         digitalRead (inPin(13)) == HIGH ||
         digitalRead (inPin(14)) == HIGH ||
         digitalRead (inPin(15)) == HIGH ||
         digitalRead (inPin(16)) == HIGH ||
         digitalRead (inPin(17)) == HIGH ||
         digitalRead (inPin(18)) == HIGH ||
         digitalRead (inPin(19)) == HIGH ||
         digitalRead (inPin(20)) == HIGH ||
         digitalRead (inPin(21)) == HIGH ||
         digitalRead (inPin(22)) == HIGH ||
         digitalRead (inPin(23)) == HIGH ||
         digitalRead (inPin(24)) == HIGH)
           return;

Time to learn about loops, buddy. How about:
for (int i = 1; i <= 24; i++)
  if (digitalRead (inPin (i)) == HIGH)
    return;

My guess about this particular problem is that you are not debouncing. You enter the function, one of the bounces is detected, and you leave the function. I mentioned debouncing in your other, closely-related, thread.

Let me show you what a switch bounce looks like. Using a normal switch from my parts drawer, this is what you see when you press it:

See that? It looks to the (fast) Arduino that you pressed the switch 20 or 30 times. That is the physical metal bouncing back and forwards. So if you test for one press, and then stop when you get another, your chances of it working are rather slim. That's why a simple delay of (say) 10 ms after detecting a change in state of the switch can help debounce it.
See: Switches tutorial

Could also be a chance for the OP to learn about switch cases.

One thing you're missing there, mate - he's entering the function on button 5, but he's not checking button 5 as a reason for terminating the function - so it can't be debouncing that's causing it - button 5 only enters, it never causes it to leave.  So a loop would break that functionality and then bouncing would then become a problem. As it is, the problem is caused by the if (digitalRead(inPin(5)) == HIGH) { ... } in the main loop (which equates to "while input 5 is high ... ").

Thank you for your responses. It turns out the bread board was not working. Changed it out and everything is fine now. I replaced the if statements with a switch. However, your suggestion for the alteration for the for loop isn't working. I need to skip a single value in the loop. My understanding of for loops, however, would make each of the ((inPin(i) == HIGH)) statements an AND statement, not an OR statement. I need it to be an OR statement to work. Do you have a suggestion for how to get around this?

@JetPropelledInsectivore Personally I would have a single function which reads all the buttons and sets each bit in a 32-bit unsigned integer as a bit-field representing which buttons are pressed. You can then mask out the button you want to ignore and see if the result is anything other than 0.

@Majenko - but he's not checking button 5 as a reason for terminating the function - Not really. He is saying he needs to hold the button down for it to be noticed. The function is already written to only do 100 iterations. So you could count that as a debounce. My proposed code exits on any button press, so it can go back and test for other buttons immediately.

My understanding of for loops, however, would make each of the ((inPin(i) == HIGH)) statements an AND statement, not an OR statement. I need it to be an OR statement to work. - what do you mean by "not working"?

It's a software issue.  You are basically saying "If this button is currently pressed down then run this sequence once", rather than "If this button has transitioned from OFF to ON then set my current sequence to X"
You need to learn about the Finite State Machine and about switching from one state to another (or one selected sequence to another) when a button changes state not when it is in a state.
So basically the whole logic of your program is flawed and needs re-working.


text:
Toggle Button For LED Strip not executing properly
I have been using a library to control a LED Strip with buttons. My current code does not execute properly. It skips the if statement and just runs the code in a loop with no regard to the button and I'm uncertain why. I'm using an Arduino Uno with an LPD8806.
#include "LPD8806.h"
#include "SPI.h" // Comment out this line if using Trinket or Gemma
#ifdef __AVR_ATtiny85__
#include <avr/power.h>
#endif

int nLEDs = 160;

// Chose 2 pins for output; can be any valid output pins:
int dataPin  = 2;
int clockPin = 3;

// First parameter is the number of LEDs in the strand.  The LED strips
// are 32 LEDs per meter but you can extend or cut the strip.  Next two
// parameters are SPI data and clock pins:
LPD8806 strip = LPD8806(nLEDs, dataPin, clockPin);

int inPin = 4;
boolean lastState = LOW;//storage for last button state

void setup(){
   pinMode(inPin, INPUT);//this time we will set the pin as INPUT
   Serial.begin(9600);//initialize Serial connection
   #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
   clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
   #endif

   strip.begin();
   // Update the strip, to start they are all 'off'
   strip.show();

 }

void loop(){

   if (digitalRead(inPin) == HIGH && lastState == LOW){//if button has just
   been pressed
   // Start up the LED strip
        theaterChase(strip.Color(127, 127, 127), 50); // White
        delay(100);
    } else if(digitalRead(inPin) == LOW && lastState == HIGH){
        digitalWrite(dataPin, LOW);
        digitalWrite(clockPin, LOW);
    }
    lastState = digitalRead(inPin);
    }

    //Theatre-style crawling lights.
    void theaterChase(uint32_t c, uint8_t wait) {
         for (int j=0; j<10; j++) {  //do 10 cycles of chasing
              for (int q=0; q < 3; q++) {
                   for (int i=0; i < strip.numPixels(); i=i+3) {
                      strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (int i=0; i < strip.numPixels(); i=i+3) {
      strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
  }

Do you have a pull-up or pull-down resistor on the input pin? See Switches tutorial.

Some of your comments overflow onto the next line of code...

I think it doesn't work because you define the theatherChase() function inside loop(), where it should be before or after.

If you have just connected a switch to the Arduino pin, like the image below, it will just return "random" undefined results:

There are various ways of avoiding this, including using a pull-down resistor to ensure that, if the switch is open, it will read LOW. For example:

There are other possible techniques as discussed on this page.
One is to change:
   pinMode(inPin, INPUT);//this time we will set the pin as INPUT

to:
   pinMode(inPin, INPUT_PULLUP);//this time we will set the pin as INPUT

Then wire the switch to ground, not +5 V. That way the pull-up resistor pulls the switch HIGH, and when you close the switch it is LOW.


text:
Where are the digital and analog pins for the adafruit atmega 32u4 breakout board?
Which pins are the analog and digital pins? I've been searching the internet for an hour and I could get an answer.

The information is right there on the product page for you. It took be a total of about 4 seconds to find it.
http://ladyada.net/products/atmega32u4breakout/


text:
Arduino DUE Interrupt 1MHz
My Due is interfaces with a DAC which I need to update with freq 1MHz. The nice solution seems to be a timer interrupt. I found a thread here called "Arduino Due - creating an 8Mhz clock signal". I tried the following code to see if I can get 4MHz on P41. No luck. Any help will be greatly appreciated. Thanks.
volatile boolean l = false;

void TC6_Handler()
{
    TC_GetStatus(TC2, 0);
    digitalWrite(41, l = !l);
}

void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) {
    pmc_set_writeprotect(false);
    pmc_enable_periph_clk((uint32_t)irq);

    TC_Configure(tc, channel,
    TC_CMR_WAVE |
    TC_CMR_WAVSEL_UP_RC |
    TC_CMR_TCCLKS_TIMER_CLOCK1|
    TC_CMR_ACPA_TOGGLE );  // RC compare TOGGLES TIOA);

    TC_SetRA(tc, channel, 1); //50% high, 50% low
    TC_SetRC(tc, channel, 1);

    PIO_Configure(PIOC,
    PIO_PERIPH_B,
    PIO_PC25B_TIOA6,
    PIO_DEFAULT);

TC_Start(tc, channel);

}

void setup(){
pinMode(41,OUTPUT);
startTimer(TC2, 0, TC6_IRQn);
}

void loop(){
}

Generally you should try to do something like this with DMA, creative use of some other on-chip peripheral, etc rather than the main processor core - at least if you want your MCU to be useful for much else.

I'm not 100% certain without my Due in front of me to test this, but as far as I can see, you are configuring your clock to run at 42MHz with "TC_CMR_TCCLKS_TIMER_CLOCK1" and are getting the timer to trigger when the count is "1" with "TC_SetRC(tc, channel, 1);", which would give you 42MHz, not 4MHz.
Since the clock timer still increments during the TC6_Handler() function, I'm guessing that the interrupt triggers a second time before it has exited the function the first time causing a hang.
Try changing your code to "TC_SetRC(tc, channel, 42000000 / 4000000);" to see if that works.  Your interrupt will still be triggered every 10 ticks of the timer which will only give you 20 ticks of the CPU clock to do your work and exit.  I suspect this may still be too little time to exit before the next interrupt is triggered.  If you still don't get the result you want, try reducing the frequency considerably to see if your timer is actually getting configured correctly.  I don't think you can get exactly 4MHz as the Due timer frequencies are not divisible by 4000000, unless my brain is a little fuzzy this morning and I'm missing something obvious...
If you do need to optimise the code inside your handler so it can run faster, let me know and I'll post some ideas when I can get near my Due and my source code for reference.
You could always check out this link that I used when I needed to understand how to set up a timer for my own projects:
http://2manyprojects.net/timer-interrupts
Should that link go dead before you have a chance to read up, this is the example source from that page I modified for my own purposes:
// These are the clock frequencies available to the timers /2,/8,/32,/128
// 84Mhz/2 = 42.000 MHz
// 84Mhz/8 = 10.500 MHz
// 84Mhz/32 = 2.625 MHz
// 84Mhz/128 = 656.250 KHz
//
// 42Mhz/44.1Khz = 952.38
// 10.5Mhz/44.1Khz = 238.09
// 2.625Hmz/44.1Khz = 59.5
// 656Khz/44.1Khz = 14.88 // 131200 / 656000 = .2 (.2 seconds)

// 84Mhz/44.1Khz = 1904 instructions per tick
const int led_pin = 13;
int state = false;
int interruptCtr = 1;
int S = 0;

void setup()
{
  pinMode(led_pin, OUTPUT);
  /* turn on the timer clock in the power management controller */
  pmc_set_writeprotect(false);       // disable write protection for pmc registers
  pmc_enable_periph_clk(ID_TC7);     // enable peripheral clock TC7

  /* we want wavesel 01 with RC */
  TC_Configure(/* clock */TC2,/* channel */1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4);
  TC_SetRC(TC2, 1, 131200);
  TC_Start(TC2, 1);

  // enable timer interrupts on the timer
  TC2->TC_CHANNEL[1].TC_IER=TC_IER_CPCS;   // IER = interrupt enable register
  TC2->TC_CHANNEL[1].TC_IDR=~TC_IER_CPCS;  // IDR = interrupt disable register

  /* Enable the interrupt in the nested vector interrupt controller */
  /* TC4_IRQn where 4 is the timer number * timer channels (3) + the channel number (=(1*3)+1) for timer1 channel1 */
  NVIC_EnableIRQ(TC7_IRQn);
}

void loop()
{
  // do nothing timer interrupts will handle the blinking;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// INTERRUPT HANDLERS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void TC7_Handler()
{
  // We need to get the status to clear it and allow the interrupt to fire again
  TC_GetStatus(TC2, 1);
  state = !state;
  digitalWrite(led_pin, state);

  if( interruptCtr++ >= 6 )
    {
     interruptCtr = 1;
     S = !S; // are we flashing S or O
     if( S ) // set time till next interrupt
        TC_SetRC(TC2, 1, 131200); // 131200 / 656000 = .2 seconds
     else
        TC_SetRC(TC2, 1, 656000); // 656000/ 656000 = 1 second
    }
}

I just noticed the title mentions 1MHz as does your question, before it mentions 4MHz. Using "TC_SetRC(tc, channel, 42);   // 42MHz / 1MHz" will give you the 1MHz timer you desire.  This will give you approx. 80 ticks of the CPU clock to complete your interrupt.  Still pretty low, but definitely doable to flip an IO line - you may need to avoid digitalWrite() though.

i didnt read your answer, just vote up to bump it above comment-answers of the OP

When I'm working with timers on my Due I always keep my code low level so my solution for your problem would be:
// These are the clock frequencies available to the timers /2,/8,/32,/128
// 84Mhz/2 = 42.000 MHz
// 84Mhz/8 = 10.500 MHz
// 84Mhz/32 = 2.625 MHz
// 84Mhz/128 = 656.250 KHz
//
// 42Mhz/44.1Khz = 952.38
// 10.5Mhz/44.1Khz = 238.09
// 2.625Hmz/44.1Khz = 59.5
// 656Khz/44.1Khz = 14.88 // 131200 / 656000 = .2 (.2 seconds)

#define SPEED(x) 42 * x

// 84Mhz/44.1Khz = 1904 instructions per tick
const int led_pin = 13;  //PB27
int interruptCtr = 1;
int S = 0;

void setup()
{

    pmc_set_writeprotect(false);       // disable write protection for pmc registers /**always the first thing to do*/

    // Enable pin 13 with direct port manipulation
    REG_PIOB_PER = 1<<27;
    REG_PIOB_OER = 1<<27;
    REG_PIOB_OWER = 1<<27;

    /* turn on the timer clock in the power management controller */
    pmc_enable_periph_clk(ID_TC0);     // enable peripheral clock TC0

    //Enable interrupt in NVIC before starting interrupt
    NVIC_EnableIRQ(TC0_IRQn);

    //Wavesel on rising edge with timer clock1 (42MHz)
    REG_TC0_CMR0 = TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1;

    //Enabel RC compare interrupt
    REG_TC0_IER0 = TC_IER_CPCS;

    //Set the timer register c
    REG_TC0_RC0 = SPEED(200000);  //SPEED() converts us to clock ticks

    //Start timer
    REG_TC0_CCR0 = TC_CCR_SWTRG | TC_CCR_CLKEN;
}

void loop()
{
  // do nothing timer interrupts will handle the blinking;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// INTERRUPT HANDLERS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void TC0_Handler()
{
  // We need to get the status to clear it and allow the interrupt to fire again
  REG_TC0_SR0;

  //get curretn pin state (REG_PIOB_ODSR & PIO_PB27) and invert it. AND this result with the pin bit to only set pin 27 to high/low
  REG_PIOB_ODSR = (~(REG_PIOB_ODSR & PIO_PB27)) & PIO_PB27;

  if( interruptCtr++ >= 6 )
  {
    interruptCtr = 1;
    S = !S; // are we flashing S or O
    if( S ) // set time till next interrupt
      REG_TC0_RC0 = SPEED(200000); //0.2 seconds
    else
      REG_TC0_RC0 = SPEED(1000000); //1 second
    }
}

With this code you should be able to increase the switching frequency to theoretically 42MHz. But due to the time the interrupt needs to run it will be reduced to something about 10MHz or less but even this is much higher than your 334KHz.

I need to update with freq 1MHz. ...No luck.

no kidding.
think about interrupt overhead. and how much it takes away the processing power if you interrupt at 1 million times a second.
think DMA if available on your chip. If not, think a faster chip or compromise on your 1Mhz expectation.

Indeed, unless the processor needs to do essentially nothing else, using DMA to feed the DAC is probably necessary.

This works
int unsigned A[2500];
int unsigned S;
void setup()
{
  Serial.begin(9600);
  //pinMode(30, OUTPUT);
  REG_PIOB_OWER = 0xFFFFFFFF;     // Enable PORT B
  REG_PIOB_OER =  0xFFFFFFFF;     // Set PORT B as output port
  REG_PIOD_OWER = 0xFFFFFFFF;     // Enable PORT D
  REG_PIOD_OER =  0xFFFFFFFF;     // Set PORT D as output port
  REG_PIOC_OWER = 0xFFFFFFFF;     // Enable PORT C
  REG_PIOC_OER =  0xFFFFFFFF;     // Set PORT C as output port
  /* turn on the timer clock in the power management controller */
  pmc_set_writeprotect(false);     // disable write protection for pmc registers
  pmc_enable_periph_clk(ID_TC7);   // enable peripheral clock TC7

  /* we want wavesel 01 with RC */
  TC_Configure(/* clock */TC2,/* channel */1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1);
  TC_SetRC(TC2, 1, 42);// 1 MHz
  TC_Start(TC2, 1);

  // enable timer interrupts on the timer
  TC2->TC_CHANNEL[1].TC_IER=TC_IER_CPCS;   // IER = interrupt enable register
  TC2->TC_CHANNEL[1].TC_IDR=~TC_IER_CPCS;  // IDR = interrupt disable register

  /* Enable the interrupt in the nested vector interrupt controller */
  /* TC4_IRQn where 4 is the timer number * timer channels (3) + the channel number (=(1*3)+1) for timer1 channel1 */
  //NVIC_EnableIRQ(TC7_IRQn);
}

void loop()
{
int unsigned MSBs = 0;
int unsigned LSBs = 0;
int unsigned C = 0;
int unsigned B = 0;
int unsigned i = 0;
//int unsigned long B1 = 0;
//int unsigned B2 = 0;
int unsigned MSBMask = B11111111;
MSBMask << 8;

 //Serial.println(base, DEC);
//delay(100);
 //Serial.println(ratio, DEC);
//delay(100);
for(i=0; i<2500; i++)
{
  //C = 20000/2*sin(2*PI*(90000/0.0025*i+10000)*i);
  C = 20000*sin(2*PI*i);
 // A[i] = sin(2*PI*(10+90/25*i)*1/1000);
   //A[1] = sin(2*PI*(10+90/25*i)*1/1000);

  MSBs = C >> 8;
  LSBs = C & MSBMask;
   //Serial.println(C, BIN);
  //Serial.println(MSBs, BIN);
 // Serial.println(LSBs, BIN);
MSBs = MSBs << 12;
LSBs = LSBs << 1;
B = MSBs+LSBs;
A[i] = B;
 //Serial.println(B, BIN);
 //Serial.println(A[i], BIN);
//delay(100);
}

NVIC_EnableIRQ(TC7_IRQn);
while(1){}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// INTERRUPT HANDLERS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void TC7_Handler()
{
 TC_GetStatus(TC2, 1);// We need to get the status to clear it and allow the interrupt to fire again
  //int i=0;
  REG_PIOD_CODR = 0x1 << 9;// clear pin 30 on due
 // REG_PIOD_CODR = 0x1 << 10;// clear pin 32 on due

REG_PIOC_ODSR = A[S];//set outout pins to array entry

REG_PIOD_SODR = 0x1 << 9;// set pin 30 on due, commanding DAC to take commended Analog output,
   S++;
   if(S>2500){S=0;}

}


text:
Arduino UNO/ZERO PRO, enough computing power for PID-controller?
I am currently working on a project, where I design a PID-Controller for a 2-axis stabilization with brushless-propeller-motors.
My question is: Does an Arduino UNO have enough computing power to perform this task in a useful manner? Arduino UNO Specs
And secondly: If the UNO was really too slow for this task, would the newly released Arduino ZERO PRO perform at an acceptable rate? Arduino ZERO PRO Specs
Thanks for your help and inputs in advance!

PID is a relatively simple algorithm. You probably only need something like 50 updates per second at the most (wild guess). So my guess, on the limited amount of info given, is that the uno will do fine.

@Jay J floating point math is not that much slower than fixed on the UNO. In my experience the time savings (if any) have not been worth the extra work to do fixed point safely.

Assuming you're not doing anything too fancy, yes, it should be fine.
There's even a library to do all the work for you: http://playground.arduino.cc/Code/PIDLibrary

Also look for the ospid project which is a full hardware/software arduino based pid


text:
LCD-Display showing wrong numbers
Hy guys,
I am having an issue with my new LCD16x2 display. I connected a potentiometer and read the values. The values are properly read and send to Serial. I also display the values on the display. I am having no issues when increasing the values, but when I go down again at a certain point the displays doesn't display the correct value anymore, but on the Serial I can still see the right readings.
I suppose this has something to do with the display still storing previous values for this digit in the buffer and when I go down the values are not properly reset. But I don't wan't to clear the whole buffer, since then the whole thing just blinks every iteration.
Here's my code
// ESC_Calibration.ino
#include <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>
#include <Servo.h>

#define WHITE 0x7

Servo firstESC;
Servo secondESC;
int throttlePin = 2;
int firstESCPin = 2;
int secondESCPin = 3;

Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

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

    lcd.begin(16, 2);
    lcd.setBacklight(WHITE);
    lcd.setCursor(0, 0);
    lcd.print("throttle:");

    firstESC.attach(firstESCPin);
    secondESC.attach(secondESCPin);
}

void loop() {
    int throttle = analogRead(throttlePin);
    throttle = map(throttle, 0, 1023, 0, 179);

    lcd.setCursor(0, 1);
        Serial.println(throttle);
        lcd.setCursor(0, 1);
    lcd.print(throttle);

    firstESC.write(throttle);
    secondESC.write(throttle);

    delay(500);
}

Does anyone have a suggestion how to improve this and fix it, so it'll display the right readings, but doesn't blink?
Thanks for your help in advance! :-)

As you have surmised, the problem is that the LCD retains what was there before and you need to clear it away.
That means, as the numbers increase you get, say,
4
10
48
89
194
309

etc.
When they go down though, because the LCD remembers what was there, only the characters you print will be replaced:
309 (309)
194 (194)
894 (89 - the 4 remains from before)
484 (48 - the 4 remains from before)
104 (10 - the 4 remains from before)
404 (4 - the 04 remains from before)

Also, as you have noticed, clearing the whole screen is not very nice since it makes it flash.
To combat that it is important that you only overwrite the characters that you need to overwrite and leave those that want to stay.  There's two common ways of doing this:

Append enough spaces after the number to force an overwrite:

lcd.print(throttle);
lcd.print("   "); // 3 spaces should be enough for 3 extra digits

Format the data with snprintf():

char temp[5]; // enough room for 4 numbers and one NULL character
snprintf(temp, 5, "%4d", throttle); // %4d = 4 digits, right aligned
lcd.print(temp);

The latter method, though it is more complex and uses more resources, can be preferred because it creates a much nicer output with the numbers properly right-aligned.  Also arbitrarily adding spaces after the number could overwrite things you want to keep.
You could also achieve a similar result doing it manually:
if (throttle < 10) lcd.print(" "); // 0-9 add one space
if (throttle < 100) lcd.print(" "); // 0-99 add one space
if (throttle < 1000) lcd.print(" "); // 0-999 add one space
lcd.print(throttle);

Just like with cats, there's many ways to skin this problem...

Alternatively call lcd.clear() to clear the entire screen and start adding text again.

@Gerben As has already been mentioned in both the question and my answer - that is very very bad since it makes the whole display flicker.


text:
Fastest wireless communication
Hy guys,
I am currently working on a quadcopter stabilization algorithm for an indoor quadcopter. I now need to setup a wireless communication between my onboard Arduino and my controlling Arduino (and/or RasperryPi (not shure yet)).
My question is: What would be the fastest wireless communication possibility?
I am not worrying about distance; they won't get far apart from eachother. I want to keep a lot of resources on the stabilization algorithm and to keep down resources used for the communication and thus get the fastest communication on very few resources.
What are your opinions and experiences, what is going to be fastest?

There is a difference between Wifi and Wireless. Wifi requires an already established network and uses the standard internet protocols. If this is what you mean, then the communication speed would only be influenced by the bandwidth of your network and the speed of the arduinos. I have not been able to find what the speeds of the modules are, but if they are 150 mB/s and your network is only 100, then you'll only get a speed of 100mB/s (which is a pretty decent speed).
If you want wireless (they create their own network using the unlicensed 2.4ghz spectrum, then buy these: nRF24L01+ 2.4GHz. They seem pretty reliable at short distances, and have a low power and high power variant. These have a speed of (at tops) 2 mB/s, but you won't have to worry about having a Wifi connection.
I personally do not know much about Bluetooth modules, so I cannot comment there.
Hope this helped.

Be careful of the distinction between throughput vs latency.  WIFI may have great throughput, but what the poster's application requires is to move a small amount of data with low latency, and simpler schemes often do better at that.  nRF24L01+ and compatible are already in widespread use as one of the three main chipsets for manual control of flying toys, so do seem worth investigating.

Good point Chris, typically a packet has to move from the quadcopter to a router and then to your PC/phone. Which might take longer as a direct link. But you should specify requirements, otherwise it will be a witchhunt on the fastest method. Also,  it's realtime and shouldn't have random  delay spikes.


text:
Replacing Atmega8a pu 1440 arduino Ic with 1337
I have one Arduino uno, and one atmega8a 1337 ic. Can i replace the Arduino uno ic with 1337 to program the 1337 one?

That second number is the date code. 40th week of 2014 vs. 37th week of 2013. They're the same chip (although they may be different revisions).

@IgnacioVazquez-Abrams Thanks man. I had no idea.

If you have a bootloader installed on the 8A then yes, you can.  The two chips are pin and electrically compatible.

How do I check for it? Sorry but I am new to this.

Did you buy it with a bootloader installed, or did you install a bootloader? If the answer to both those is no then you will need to install a bootloader. You can use your existing Arduino Uno to do it - google for tutorials, there's plenty.


text:
My arduino won't show up in Device Manager in any way, neither in unknown devices nor in COM port.
I have a brand new arduino(original), and it is not showing up in Device manager or anywhere else. Even the computer doesn't Prompt anything. I am using Windows 7 32 bit.

Have you tried a different cable? Different computer?

Is there anything connected to it? (Like sensors and what not) that could be wired up wrong. Is the power light on?

It worked with a different cable.

As the OP reported: It worked with a different cable.
I converted his comment to an answer so the system would regard this issue as solved. Please accept this answer.

Some cheap USB cables only carry power, and not data. I have such a cable that came with a USB desk light. To save money they only run two wires and not four, since the desk light is not a data device.
Be cautious about grabbing any old cable from your desk for testing. Make sure it is designed for data use. If in doubt, try a known good cable.


text:
Leonardo broken?
My leonardo was working fine until today, when I plug it to my computer all led (RX/TX/L/ON) stays on (Green for on, amber for others) and my computer no longer see a com port.
(by the way, do you know what the L led mean ?)
If I add external power, TX goes off then after few seconds RX goes off too then back on.
With external power, the atmega goes very hot (I can't touch it).
RESET button do nothing.
Is my Leonardo dead ? Any idea what could have cause that ? The fact that the atmega is so hot when the board is powered up with 12V let me think that the voltage regulators is no longer working. Good guess ?

By your description, I'd say:

Quite Probably.

You should check what the 5V and 3.3V voltages are using a DMM.

Confirmed, i have 12V on 5V pin when I put external power. I guess it would be safer to have something which can limit the input current on the external power supply. Any idea how I could do that ?


text:
LiquidCrystal_i2c and Pin 2
I'm trying to read temperature and humidity from a DHT11 sensor and write values to a 20x4 LCD.
I hit a behaviour I don't understand. When I use the DHT tester program that come with the DHT library, everything works well. I get the DHT information on the Serial console. This DHT tester program use the pin 2 to read the data from the DHT.
I wrote the following code who works perfectly:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>  // F Malpartida's NewLiquidCrystal library
#include <DHT.h>

#define DHTTYPE DHT11
#define DHTPIN 13      // Digital

DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C    lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void setup() {
  Serial.begin(9600);
  while (!Serial) {
  }
  Serial.println("Serial OK!");

  dht.begin();
  lcd.begin(20,4);
  lcd.setBacklight(0);
  lcd.clear();
  lcd.print("Hello! ");

  Serial.println("Init finished!");
}

void loop() {
  delay(2000);

  float DHT_hum = dht.readHumidity();
  float DHT_temp_c = dht.readTemperature(false);
  float DHT_temp_f = dht.readTemperature(true);

  if (isnan(DHT_hum) || isnan(DHT_temp_c) || isnan(DHT_temp_f)) {
    Serial.println("Failed to read from DHT sensor!!");
    lcd.clear();
    lcd.print("fail! ");
    return;
  }

  float heat_index = dht.computeHeatIndex(DHT_temp_f, DHT_hum);

  Serial.print("Humidity: ");
  Serial.print(DHT_hum);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(DHT_temp_c);
  Serial.print(" *C ");
  Serial.print(DHT_temp_f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(heat_index);
  Serial.println(" *F");

  lcd.clear();
  lcd.print("Humi: ");
  lcd.print(DHT_hum);
  lcd.print("%");
  lcd.setCursor(0, 1);
  lcd.print("Temp: ");
  lcd.print(DHT_temp_c);
  lcd.print("C");
  lcd.setCursor(14, 0);
  lcd.print("HI: ");
  lcd.setCursor(14, 1);
  lcd.print(dht.convertFtoC(heat_index));
  lcd.print("C");

}

As you can see, I use pin 13 for the DHT11 (DHTPIN).
If I set to it to "2" then my program is no longer working (having the pin connected or not doesn't change the result).
The serial display
Serial OK!
Init finished!
Failed to read from DHT sensor!!

and that's all, it even doesn't loop to display "Failed to read from DHT sensor!!" again. LCD text doesn't change too. Like if the program is totally exiting after "Serial.println("Failed to read from DHT sensor!!");"
I'm lost... The LCD lib I use is the very common one from fm
https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home

I'm self answering..
On my Arduino Leonardo, the SDA and SCL pin used for the I2C connexion to the LCD panel, are the same pin than the Digital pin 2 and 3. So using SDA/SCL remove ability to use pin 2 & 3.

LiquidCrystal_I2C    lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

Are you not using pin 2 in the LiquidCrystal_I2C constructor? So you can't also use it for the DHT sensor.

I withdraw that suggestion.

Can you please try saving some RAM?
Use the F macro with your prints, eg.
  Serial.print(F("Humidity: "));
  Serial.print(DHT_hum);
  Serial.print(F(" %\t"));
  Serial.print(F("Temperature: "));

Ditto with the lcd.print() calls.

From my understanding, the pin used in the constructor, are the pin used by the logic chip on the LCD panel, not on the arduino. I don't have anything from the LCD connected on pin 2 and LCD works. If I changed '2' to another (not used) pin, the LCD no longer work.

I don't see how that could be right. Why would the code care what pin is on the LCD logic chip? It needs to know what pin on the Arduino it uses for certain functions.

Because all LCD panel are not wired the same way. see https://arduino-info.wikispaces.com/LCD-Blue-I2C "Set the pins on the I2C chip used for LCD connections"

Hmm, that's odd. I see what you mean. Please see revised answer.


text:
How to int variables with similar names without tons of code?
I'm using int with 14 LEDs to specify pins, but I don't want to use int 14 times, like this:
int led1 = 2;
int led2 = 3;
int led3 = 4;
int led4 = 5;
int led5 = 6;
int led6 = 7;
int led7 = 8;
int led8 = 9;
int led9 = 10;
int led10 = 11;
int led11 = 12;
int led12 = 13;
int led13 = 45;
int led14 = 46;

is there any way to not do this?
Also, to define them as output, is there any way to avoid using pinMode(***, OUTPUT) 14 times as well?

The word you are looking for is array.
An array is like a list of values all of the same type.  For instance, your LED pins could be specified as:
int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

You can then access the LEDs by number.  Note that arrays start counting from zero not from one, so you would have:
leds[0]
leds[1]
leds[2]
... etc to ...
leds[12]
leds[13]

It's great for using them in an array:
for (int i = 0; i < 14; i++) {
    pinMode(leds[i], OUTPUT);
}

If the values are never going to change, as in this case since they are pin numbers, the array should be declared const so it doesn't take up any of your precious RAM:
const int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

Also you should get into the habit of tailoring the data types to the expected values.  If the values are never going to exceed 255 then you should use "byte" not "int", or better still the C standard "uint8_t".
const uint8_t leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

for (uint8_t i = 0; i < 14; i++) {
    pinMode(leds[i], OUTPUT);
}

An int takes two bytes, so using int when you can get away with uint8_t means you're wasting half the memory.


text:
Shortening large chunks of code
Some of the code that I have is unbearably long and drives me insane. I don't know if there were simpler ways to doing what I am doing.
long turn1;
long turn2;
long turn3;
long turn4;
long turn5;
long turn6;
long turn7;
long turn8;
long turn9;
long turn10;
long turn11;
long turn12;
long turn13;
long turn14;
long turn15;

#################
  turn1 = random(sizeof(turns) / sizeof(char*));
  turn2 = random(sizeof(turns) / sizeof(char*));
  turn3 = random(sizeof(turns) / sizeof(char*));
  turn4 = random(sizeof(turns) / sizeof(char*));
  turn5 = random(sizeof(turns) / sizeof(char*));
  turn6 = random(sizeof(turns) / sizeof(char*));
  turn7 = random(sizeof(turns) / sizeof(char*));
  turn8 = random(sizeof(turns) / sizeof(char*));
  turn9 = random(sizeof(turns) / sizeof(char*));
  turn10 = random(sizeof(turns) / sizeof(char*));
  turn11 = random(sizeof(turns) / sizeof(char*));
  turn12 = random(sizeof(turns) / sizeof(char*));
  turn13 = random(sizeof(turns) / sizeof(char*));
  turn14 = random(sizeof(turns) / sizeof(char*));
  turn15 = random(sizeof(turns) / sizeof(char*));

#

if (turn1 == turn2 or turn2 == turn3 or turn3 == turn4 or turn4 == turn5 or turn6 == turn7 or turn7 == turn8 or turn8 == turn9 or turn9 == turn10 or turn10 == turn11 or turn11 == turn12 or turn12 == turn13 or turn13 == turn14 or turn14 == turn15) {

#

lcd.print(turns[turn1]);
lcd.print(turns[turn2]);
lcd.print(turns[turn3]);
lcd.print(turns[turn4]);
lcd.print(turns[turn5]);
lcd.setCursor(0, 2);
lcd.print(turns[turn6]);
lcd.print(turns[turn7]);
lcd.print(turns[turn8]);
lcd.print(turns[turn9]);
lcd.print(turns[turn10]);
lcd.setCursor(0, 3);
lcd.print(turns[turn11]);
lcd.print(turns[turn12]);
lcd.print(turns[turn13]);
lcd.print(turns[turn14]);
lcd.print(turns[turn15]);

You mean like using an array and loops?

Yes you can, and the solution is very simple. It's in two parts, and they make up part of the absolute fundamental building blocks not just in C, but in almost any programming language.
You can read good information on arrays here, and 'for loops' here (it's about half way down the page). Without wishing to offend, it seems like you are missing some really basic concepts and I recommend starting at the beginning of the tutorial series that the two aforementioned links are part of.
I'll just cover the basics. If you don't understand anything, refer to the tutorials. If you still don't understand then please comment, but make sure you can convince us that you've really given it a good go. We're here to help as long as you're here to learn.
To declare an array of N variables, all of which are the same type, you use:
<type> <name_of_variable> [<number_of_elements>];

or:

long turns[15];

Now you have an array of 15 longs. Ta da!
You now have to set the values of each turn. As your values are all the same (if you ignore the fact that random() ultimately leaves you with different values) you can use a for loop:
for (int x=0; x<15; x++)
{
    turns[x] = random(sizeof(turns) / sizeof(char*));
}

I won't explain how a for loop works; I gave you a link to the tutorial to save me writing it all out myself.
That covers shrinking of part 1 and 2. Part 3 requires a little more thought. That said, as you didn't complete your if statement, I don't actually know what you plan to do if any two adjacent turn elements are the same. I shall assume that you would 're-randomise' one of the duplicates. For this you can again use a for loop, starting at the beginning and running to N-1 th element, where N is the total number of elements:
for (int x=0; x<14; x++)
{
    if (turns[x] == turns[x+1])
    {
        turns[x+1] = random(sizeof(turns) / sizeof(char*));
    }
}

You need make sure that turns[x+1] is not outside of the array, which is why the for loop runs for one iteration less than there are elements.
The fourth shrinkable part is just a matter of swtiching multiple print statements into single for loops:
for (int x=0; x<NUMBER_OF_PRINTS_IN_1st_BUNCH; x++)
    lcd.print(turns[x]);
lcd.setcursor(0,2);
for (int x=WHERE_YOU_LEFT_OFF; x<NUMBER_OF_PRINTS_IN_2nd_BUNCH; x++)
    lcd.print(turns[x]);
lcd.setcursor(0,3);
for (int x=WHERE_YOU_LEFT_OFF_AGAIN; x<NUMBER_OF_REMAINING_PRINTS; x++)
    lcd.print(turns[x]);

All done.

Is it my imagination or are you off-by-one, @chaaarlie2? Your array is of length 15, so is 0-14; in the first for loop code, you say int x=0; x<16; x++ - surely that will go around from 0 to 15, not 0 to 14? Same applies to the second for loop (reduced by 1 to skip the last value).

Alternative to the fourth part: do one loop to do all of them, then if (x==4) lcd.setcursor(0,2); if (x==9) lcd.setcursor(0,3);

@AMADANON it's obviously my imagination, not yours. I wrote the whole answer with reference to 16 values, then when I noticed the OP didn't have "long turn0;" at the start, went back and only remembered to change the first two references. Answer updated, thanks for spotting.

Thanks for the help. Also, for the third shrinkable, good assumption, that's actually what I am doing. On another note, is there a way to fix if two of them match? The turn values are stated as this: {"L2 ", "R2 ", "F2 ", "U2 ", "D2 ", "B2 " , "L' ", "R' ", "F' ", "U' ", "D' ", "B' ", "L ", "R ", "U ", "F ", "D ", "B "} , is there a way I could prevent something like L2 L or L2 L'?

Also, turns[] was already declared in char *turns[], so i end up getting conflicting declaration 'long int turns [15]' Heres the chunk: char *turns[] = {"L2 ", "R2 ", "F2 ", "U2 ", "D2 ", "B2 " , "L' ", "R' ", "F' ", "U' ", "D' ", "B' ", "L ", "R ", "U ", "F ", "D ", "B "}; long turns[15];

I assume char *turns[] = {"L2 ", "R2 " ... }; is your list of possible values, and long turns[15] holds an array of 15 random values from your that list? I'm afraid you've got yourself in a muddle again. You can't have two variables with the same name, even if they're different types; you're attempting to declare two things called turns. No! Perhaps have char *turnChoices[] instead - always consider naming your variables in a way that tells a stranger what the variable means. This is definitely a good idea if you're new to programming, because it's easy to forget what does what!

Next up I have to complain about how you're doing what it looks like you're trying to do: 1. Make a list of possible turn 'commands'; 2. Make a list of N random choices from that list of possible commands. Nothing wrong with that idea, it's perfectly sensible, but you're going about it the wrong way. Really wrong! I understand that you're new to C, we all were once, so I definitely don't want to put you off when I keep referring you to tutorials; read the section on enumeration - it's exaclty what you need.


text:
WizNet chip on Ethernet Shield oddly hot
I'm making a thermometer and, so I can graph the data, I have an Uno with the WizNet shield sending the data to a LAN ip. The chip itself is oddly hot, its temperature measures at around 110-120ºF (43.33-48.89ºC). I want the program to be running almost 24/7. Is it okay for the chip to be this hot?

According to the WizNet forums this is normal for these shields. Their justification being that it is a PHY and controller on a single chip. (Note this post only specifically mentions the W5100, which is among the more commonly used chips on these kinds of shields, however, I suspect that this is typical for most of the WizNet line, e.g. W5200 etc.)


text:
control Arduino board using Android sensors and wifi?
i am thinking about building a Quadcopter that can be controlled with a computer via Wifi . but the problem is that with a lack of components and limited resources , i have been thinking of using my available components ( Arduino uno + smart phone + quadcopter frame with 4 brush-less motors and 4 speed control )
so i am asking you guys if it is possible to read smartphone sensor values using Arduino usb and control the quadcopter using smartphone wifi ??

Is it possible?  Yes, it's certainly possible.  You can read the sensor values from within an Android program. It's possible to get Android to communicate with the Arduino through the USB.  The Arduino can be programmed to respond to what it gets through the serial.
Is it easy? Well, that depends on how good you are at Android programming.
One good place to start might be the ArduinoFirmata-Android project.  Don't worry about programming the Arduino, just install Firmata on it.  Then it's all down to how you program the Android device.  The Arduino just becomes a peripheral to your phone.

it looks a little bit complicated , in addition i dont have so much knowledge about android programming !!! is there any other more simpler method ?

Yes there is. It's called "buying the right components".

Thank you for your help @Majenko . I think i have to start learning android  programming .


text:
Parsing Int over Serial Slow
I am trying to communicate between my PC and Arduino Mega 2560 using this serial library. It works reliably, however I am having trouble passing messages at a high rate over serial. I set the baud to 460800 bps on both systems, and am using a serial handshake. The Arduino reads the values by parsing a string, however during my testing I cannot parse more than ~240 messages per second. Each message into the Arduino is either of the form "r/n" to reset some variables or "0,0,0\n" where in this case the zeroes are the ints I want to parse, these can change. My Arduino code in the loop is as follows:
if(Serial.available() > 0){
  resultString = Serial.readStringUntil('\n');
  if(resultString.equals("r")){
    countEnc0 = 0;
    countEnc1 = 0;
    countEnc2 = 0;
  }else{
    int counter = 0;
    int lastIndex = 0;
    for (int i = 0; i < resultString.length(); i++) {
      // Loop through each character and check if it's a comma
      if (resultString.substring(i, i+1) == ",") {
        // Grab the piece from the last index up to the current position and store it
        write[counter] = resultString.substring(lastIndex, i).toInt();
        // Update the last position and add 1, so it starts from the next character
        lastIndex = i + 1;
        // Increase the position in the array that we store into
        counter++;
      }
      // If we're at the end of the string (no more commas to stop us)
      if (i == resultString.length() - 1) {
        // Grab the last part of the string from the lastIndex to the end
        write[counter] = resultString.substring(lastIndex, i+1).toInt();
      }
    }
    analogWrite(8, write[0]);
    analogWrite(9, write[1]);
    analogWrite(10, write[2]);
  }
  Serial.println(String(countEnc0) + "," + String(countEnc1) + "," + String(countEnc2));
}

I know there are more efficient ways to parse this, however my attempts to use them yield similar results (Using parseInt(), char*, etc). Additionally, I am using 3 interrupts to read sensor values and store them in variables here, and writing the values I acquire to the PWM. As long as I can read and send up to 1000 messages per second that's all I need for now. Many thanks...been banging my head against the wall on this one.

Yup, parsing is slow. Use raw binary whenever possible.

If you are getting ~240 message/sec, comment out your for loop and see what the maximum throughput might be is the cost of processing your data were 0.  That would be an interesting number to hear from you and would then give us a base line on your expectations.

First off, I would recommend  strtok or even getline to parse comma delimited strings.
Secondly, I'm pretty sure no PWM is responsive enough for 1000 updates per second. But for other purposes this data rate might be needed.
To do this, build a custom cache that does the following:

Reads 1000 characters per go, if available, or less.
Parses on the go. From this set up callbacks to you PWM class, so that you can set PWM values while parsing.

Why this? I am not convinced that the sluggishness is due to the for parsing data. More likely, it's because you are processing every instruction as you get it.
1000 serial reads with 6 length for loops over strings (your case) will be significantly slower than 1 serial read and a 6k length for loop.

The String class is slow. I would get rid of that first. I am confused about whether you are sending or receiving, or both, as your code seems to parse and then send. See this test code here:
int countEnc0 = 123;
int countEnc1 = 456;
int countEnc2 = 789;

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

  unsigned long start = micros ();
  Serial.println(String(countEnc0) + "," + String(countEnc1) + "," + String(countEnc2));
  Serial.flush ();

  Serial.print ("Time taken = ");
  Serial.print (micros () - start);
  Serial.println (" uS");
  }  // end of setup

void loop () { }

That replicates the time taken for that one line which echoes the three figures. My results were:
Time taken = 1632 uS
OK, yours will be faster at the faster baud rate, but only 4 times as fast.
So, 240 times that and allowing for the faster baud rate gives:
1632 * 240 / 4 = 97920 µS

That's a fair bit of that second gone (a tenth), without even parsing anything.

If your bottleneck is really in the parsing (and you should confirm this before you spend any effort to optimize it), eliminate the parsing.
I usually recommend sending ASCII strings on serial channels to make debugging simpler, and I'd still suggest you get everything working this way first, even if you can't make the sample rate you need.
Once you're convinced your system works except for its speed, you can replace the ASCII communication with raw binary. A simple protocol would suffice: 3 or 6 bytes (do you need int16_ts?) of data and a 1 byte checksum downstream, and an ACK / NAK byte upstream to trigger a resend if needed, will probably be more than sufficient.
The receiver would only have to confirm the checksum and process the already ready-to-go binary sample values.


text:
What is GND on board?
I've looked in several places, and so far can not understand to want to be the GND who is on the board.
There is this documented anywhere?

It is the 0V reference for everything else, as well as the power supply return.
"Ground (electricity)" on Wikipedia


text:
How should I organize a 3-day Arduino beginners course?
I will be teaching Arduino during a fair in my university, and the school gave me 3 afternoons to teach Arduino to Engineering students. Now I am looking for ideas on how to organize this course, and any help would be very nice.

Alphabetically (case sensitive).

This question is being flagged as too broad, and I don't blame them. This isn't a site for suggesting a syllabus for a course. Good luck with the fair, I hope it goes well, but questions here need to be more focussed. See What types of questions should I avoid asking?. There doesn't seem to be a problem to be solved, as such.

Introduction, Blink, Serial, ADC, servos, more LEDs, I2C sensors / libraries, (WiFi with ESP?)...  You can pick some Starter Kit Manual for instpiration.

Good point @NickGammon. I would also question if the OP needs to ask this question are they qualified to teach the class. I am not trying to be mean, but I know the following to be true: to know how to do something is one thing, to teach it, is another. You need to know all about AVR and c/c++. You need to know the material inside and out.  However you may be prepared to do so. Either way, good luck.

well, I do know the stuff, as I am graduating from Control Engineering, and I am a teacher on other subjects already, so I was mainly wondering if there was any shortcut anyone more experienced could give me. I'll plan a little bit more and when my question becomes more specific I can edit it. Also, I couldn't find any tags for education, teaching, etc, so maybe that's an area not discussed much around here. Or I didn't look up in a proper fashion. Thanks, anyway!


text:
Did I fry my DUE by powering it from a external source and USB at the same time? If so, why?
I guess I just fried my second DUE in a week. The first I didn't really see what happened, but I couldn't upload any sketches, even if the computer could recognize it, and the SAM would get really hot.
Now, I had it powered by a 12V External supply, through a regulator bringing it down to 9V, and in the exact moment I plugged the USB, with power still on, I got a lot of smoke, smelling of fried electronics :p. Afterwards, I have the same symptoms as I had in the other boards: Green and orange LEDs on, chip very hot, computer recognizing it as a Arduino DUE but not being able to upload any sketches.
What just happened?

"I got a lot of smoke" -- Yes, it's dead.

Step 1: check the voltages on VIN, 5V and 3.3V pins.

Maybe ground loop - the voltage difference between USB ground and power source ground?

You're doing it wrong. You should have burnt an UNO before this DUE. Now, at least wait for the TRE to be release before smoking anything else. It's good to be in synchrony.

I did check the pins, and I've got 3.3 V on the 5V one, and 2.7V on the 3.3V. Can't remember the other one, but I guess all hope is gone anyway, after the amount of smoke...

If it was the same sketch involved in the destruction of both it may be a good idea to check to make sure the sketch that is involved as well to make sure there are no logical shorts to ground or other pins. Rugged-Circuits has a list of some common ways the Arduino can get shorted. It is showing the Uno but I am sure all similar rules apply with the exception of total power requirements and other differences between the boards.

As Majenko said you should check these voltages.
Arduino DUE uses the LM2734Y DC/DC converter and according to datasheet it works up to 20V so there is no need to use your 9V regulator.
Also on DUE there is comparator which should turns off a USB power supply when external power supply is used. Look for 2 transistors on board (FDN340P) called T1 and T2. There both are turning on/off power from USB source. Also check them. There can be also problem with all components around USB power. For more info check Arduino schematic.


text:
Can I use IO10 as digital IO while using SPI interface?
If my arduino is the master device in a SPI network, hence not using the slave select SS pin, can I use the same pin as IO10?
I am actually using an Intel Galileo, with the same pinout as an Arduino Uno Rev3.

Can I use IO10 as digital IO while using SPI interface?

On AVR it must be OUTPUT when using SPI in master mode and INPUT in slave mode.

If my arduino is the master device in a SPI network, hence not using the slave select SS pin, can I use the same pin as IO10?

The SS pin (D10) has to be OUTPUT when using SPI master mode. It can be used for chip select on the SPI bus (slave select) or some other output function.
So far the Arduino design with AVR (e.g. ATmega328). The Intel Galileo based Arduino has the following block diagram:

IO10-IO14 are multiplexed from SPI1 or GPIO. This implies that the SPI SS (IO10) signal is hardwired to the SPI controller when enabled. Last, according to the product info SPI is master only. More details schematics details here.
Cheers!

I am actually using an Intel Galileo - I think Mikael's answer specifically addresses the Atmega328P processor. The Galileo may have different requirements.

Added some more info on Intel Galileo. Nick is very right about the different requirements.


text:
How do I know which is ground and power in Piezo?
I have a piezoelectric sensor. Both pins are the same length. I have one like this: Piezo picture. On the Piezo it's written muRata and 01P. How do I know which do I send to the digital pins and which to the ground? I have an Arduino Uno.

On the one I have, the shorter pin is ground. I discovered that empirically - a scientific word for "I tried it the wrong way round the first time but the magic smoke stayed inside." Afterwards I inspected it more carefully, I found a '+' embossed in the top surface nearer one side. :-o

If you're using just one or sound quality doesn't matter: it doesn't matter.
Otherwise you need to figure it out with a scope like this:

Connect both poles of the connector of the PZT to an oscilloscope (time base approx. 50ms/div, y-axis 200mV/div).
Slightly tap the head of the PZT with your finger. As a result you should get a voltage pulse on the oscilloscope.
Positive Amplitude  -> + pole of the piezo is connected to the inner conductor of the oscilloscope BNC connector.
Negative Amplitude -> + pole of the piezo is connected to the outer conductor of the oscilloscope BNC connector.

Please edit your answer and copy in the (smallish) amount of information from the linked site. StackExchange frowns on link-only answers in case the link goes dead. If you copy the information into your answer it then stands on its own.

@NickGammon Done!


text:
FIFO overflow - reading IMU MPU6090 and GPS uBlox NEO-6M at once
I am trying to read data from uBlox NEO-6m (I need just speed, just part of the code):
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

static const int RXPin = 7, TXPin = 4;
static const uint32_t GPSBaud = 9600;

float gps_speed = 0;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup(){
ss.begin(GPSBaud);
}

void loop(){
if (ss.available())
    {
      gps.encode(ss.read());
      gps_speed = gps.speed.kmph();

    }
}

And in the same time I read data from MPU6090 using this code (gps code is integrated in it):
http://nevit.blogspot.de/2014/07/arduino-mpu-6050-pitch-roll-with-2.html
When I try to read data separately it works but together it stuck every second (probably reading of gps data) and MPU6050 serial monitor sending FIFO overflow error ..
I tried to lower MPU data rate to 20Hz from 100Hz but it didn't work. I use Arduino UNO.
I am not so much skilled.. Any idea? Is it even possible to do it like this?

It looks like the instant you have a single character received from the GPS, you will go off and wait until the full mesage is received from it in a blocking collection function where you may be unable to drain the MPU FIFO.  Instead, what you may want to do is collect characters one at a time from the GPS while continuing to monitor the MPU, and only deal with the GPS once you have a complete message from it.

When I try to read data separately it works, but together it stuck every second (probably reading of gps data) and MPU6050 serial monitor sending FIFO overflow error .

Yes, you have to be careful about the loop structure and "blocking" to "wait" for a new GPS speed report.  SoftwareSerial also blocks everything else during each received character time.
Just check for GPS characters and update the speed if a complete sentence was received, then do "other things" (e.g., use the IMU data).  Here is a NeoGPS version of your example:
#include "NMEAGPS.h"
#include <NeoSWSerial.h>

static const int RXPin = 7, TXPin = 4;
static const uint32_t GPSBaud = 9600;

float gps_speed = 0;

NMEAGPS gps;

// The serial connection to the GPS device
NeoSWSerial ss(RXPin, TXPin);

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

void loop(){

  // Read GPS characters and see if a new fix is available
  if (gps.available( ss )) {
    gps_fix fix = gps.read();

    //  A fix is available once per second, but the GPS may not know
    //  the speed value, perhaps because the satellite reception is
    //  poor or the unit is just starting.  Check the valid flag.

    if (fix.valid.speed) {

      // Update the gps_speed.  Other parts of your
      //   program can use it whenever they want.
      gps_speed = fix.speed_kph();
      Serial.println( gps_speed );
    }
  }

}

NeoGPS is smaller and faster than other libraries and can be configured to only parse the fields you really use.
Your original sketch uses 6884 bytes program space and 349 bytes of RAM.
The NeoGPS version can be as small as 4802 bytes program space and 150 bytes of RAM. Significant savings!
For the software serial library, I would suggest using AltSoftSerial on pins 8 & 9, if you can move the GPS.  It is much more efficient, and does not disable interrupts for long periods of time: SoftwareSerial will block for ~1ms, and eternity for a 16MHz Arduino.  This is probably interfering with the IMU interrupts.
If you can't move the GPS to pins 8 & 9, you might try another library I maintain, NeoSWSerial.  It is much more efficient than SoftwareSerial, and it works on any two pins.  NeoSWSerial will "play nicer" with the IMU interrupt code, but it can still be affected if the IMU interrupt code takes too long.  NeoSWSerial should not affect the IMU interrupt code.  I used it in the above sketch, along with a debug print.

Here is answer for you.
GPS keeps on sending data and fill the mcu input buffer . Use listen function and read one software serial at once ..
If you use listen then only one serial port will work at a time and you can swap accordingly .
I was having same problem and It solved my problem
Just open a dummy serial port and when ever you need gps then listen to GPS serial port and do listen to dummy after GPS reading .

Again, please do not add signatures to your post. I've edited these out. Thanks!


text:
HC-SR04 quits pinging when distance < 0 || distance < MAXDISTANCE
so here is the issue. I have a mega 1280, a handful of neopixels and a HC-SR04. I am using the New Ping library (tried both 1.5 and 1.6). I am trying to make a device that will tell my mom when she has pulled into the garage enough so she don't get hit by the garage door AND doesn't run into the wall. I wrote a bunch of code to handle the lights and what colors to do when and this part works perfectly. My issue is with the sensor. It works great except for 2 specific conditions.

if you are too close. I normally either cover one of the 2 sonic sensor part or just barley touch then with a piece of cardboard (or anything for that matter
If you go outside the scope of the max distance

when either of this are met, the ping sensor stops clicking and it just returns all 0's for the output. I am including the code less the part for the lights because even if i remove that part of the code, it still fails on those 2 conditions.
#include <Adafruit_NeoPixel.h>
#include <avr/power.h>
#include <NewPing.h>
#define TRIGGER_PIN  52
#define ECHO_PIN     53
#define MAX_DISTANCE 120
#define PIN 6
#define LEDNUM 8

int codeFact = (MAX_DISTANCE / (LEDNUM * 3));
Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDNUM, PIN, NEO_RGB +     NEO_KHZ800);
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  strip.begin();
    strip.show();
    for(uint16_t i=0; i<strip.numPixels(); i++)
    {
      strip.setPixelColor(i, strip.Color(0, 255, 0));
      strip.show();
      delay(50);
    }
    for(uint16_t i=0; i<strip.numPixels(); i++)
    {
      strip.setPixelColor(i, strip.Color(255, 255, 0));
      strip.show();
      delay(50);
    }
    for(uint16_t i=0; i<strip.numPixels(); i++)
    {
      strip.setPixelColor(i, strip.Color(255, 0, 0));
      strip.show();
      delay(50);
    }
    for(uint16_t i=0; i<strip.numPixels(); i++)
    {
      strip.setPixelColor(i, strip.Color(0, 0, 0));
      strip.show();
      delay(50);
    }

Serial.begin(115200);
}

void loop()
{
 delay(2000);
  int uS = sonar.ping();
  int dis = uS / US_ROUNDTRIP_CM;
  Serial.println(dis);
  /*
  Light code normally goes here
  */
}

What is the problem with exceeding the maximum distance (which you have as 120 cm)? The library is supposed to return NO_ECHO which is zero, which is what you say it is doing. As for the minimum distance, possibly the echo return is so short it can't be measured, thus it times out, returning NO_ECHO.

my issue is once it reaches these conditions, even if you bring some in the 1 - 120cm range, it does nothing at all...still returns 0's...you have to shut off the device and turn it back on to get it to work again.

Let's tackle this from a different direction. Once it fails, does pressing the Reset button on the Arduino help, or not help? (Without powering off the sensor)

yes...the reset does the trick (it resets everything and it starts working again

So just to clarify, once you get too close/far it just prints 0 every 2 seconds, regardless of where the sensor is? Or prints nothing at all?

I can't reproduce your problem. I commented out the Neopixel code and the sensor seems to work OK, recovering from being too close or too far. This was with the NewPing library v1.5. Can you try a cut-down version without any reference to the Neopixel library?

i haven't tried without the neopixel library, but that would defeat the purpose of the project...when i get too close or too far it just returns 0 for everything...I have tried both the 1.5 and 1.6 libraries for the ping

Yes, but the point is to isolate the problem. Either there is an issue with the Neopixel library and the NewPing library, working together, which can be resolved, or there is something else going on.

I'll try later on

The HC-SR04's range is 2cm to 300 cm, if you exceed this range or come below this range, which is exactly what you are doing, the utrasonic sensor will not receive any echo and hence there will be no data on the output.
If you bring it too close and since both the transmitter and receiver located close to each other, the receiver will not receive any ultrasonic.
Put a function that checks if the ultrasonic comes down to 2-3. If it becomes true beep a buzzer that tells you that you are too close. Don't let it reach 0.


text:
glediator + PL9823 (WS2812B) + teensy = fail?
here is what I got:

teensy++ 2.0 with code below
Glediator configured for Glediator_Protocol/Single_Pixels/HL_TL/RGB/B_1000000
led matrix with the PL9823 leds (80 of them)

I first off have to set the code to 160 on the teensy just to get it to                     at least make the leds change. even when i have it set to that OR the 80 leds, it does not show what is on screen (see video below). I have no clue what to try next.
Code
#include "FastLED.h"
#define NUM_LEDS 160
const int dataline = PIN_B4;
CRGB leds[NUM_LEDS];

void setup()
{
    digitalWrite(6,LOW);
    Serial.begin(1000000);
    LEDS.addLeds<WS2812B, dataline>(leds, NUM_LEDS);
    for (int p=0;p< NUM_LEDS;p++)
    {
        leds[p] = CRGB::Black;
        FastLED.show();
    }
}

int serialReadBlocking()
{
    while (!Serial.available())
    {
    }
    return Serial.read();
}

void loop()
{
    while (serialReadBlocking() != 1)
    {
    }
    for (long i=0; i < NUM_LEDS; i++)
    {
        leds[i].r = serialReadBlocking();
        leds[i].g = serialReadBlocking();
        leds[i].b = serialReadBlocking();
    }
    FastLED.show();
}

https://www.youtube.com/watch?v=H6OuMWKtbmo

G'day Guy, What you're building there looks nice. Do you have a circuit diagram you can share? Regarding the code, I've never played with FastLED.h but is the serialReadBlocking how it deals with the input data? Not that it's wrong, just not what I was expecting.
Two things to look at:

Your serial baud rate is a bit odd, 1 million neat. Is that intended? I wouldn't think so. Most common is 9600, I have run projects at 19,200 for giggles, but I doubt that you have it correct there.
I see your project you are using multi coloured LEDs with 3+1 pins which in actual fact means you have 240 LEDs (are the last 80 segments/colours all lighting?). If your PC sending the serial stream is expecting 80x single colour LEDs (80 individual LEDS) but you've got 80x tri-colour LEDs (80x3=240 LEDs) you probably aren't lighting them all up. (I only mention this point because I noticed your PC appeared to be sending only one colour, but that could have just been the moment I saw in the video).

edit: I meant to include this link for the teensy serial baud rate info: https://www.pjrc.com/teensy/td_uart.html

The teensy++2.0 uses a hardware USB built into its AT90USB1286 chip and  completely ignores any baud rate set in the Serial.begin(10000000) line, using instead a 12Mbit/sec rate i. See https://www.pjrc.com/teensy/td_serial.html

Cool, I didn't know that, thanks. I don't yet have any Teensy stuff. It is something I've wanted to play with :)


text:
no response in recieving with arduino uno by nfr905
from examples of  RadioHead library .
https://github.com/PaulStoffregen/RadioHead/tree/master/examples/nrf905

I tried the client and server examples ; the client was fine with no errorrs and the serial monitor showed the demanded data but I had a problem with the recieving side , the Rx led did not light on and nothing in the serial monitor had been showed .
what's the matter !?
and I did'nt change anything in both codes .


text:
Arduino Xbee AT command mode
I have 2 Xbee Series 2 modules.
One of it is connected to arduino via an adapter. And Ground 5V, as well as Rx>>Tx and Tx>>Rx.
The xbee is configured AT mode Coordinator.
I want to use the serial monitor in arduino to change the parameters of the xbee, such as DH or DL or PAN ID things like this.
Is there a way for the xbee to display its "OK" response after entering command mode on the serial monitor?

Because you have an Arduino Mega, you can set it up to use it like a USB-to-UART adapter by using the following code (source):
void setup() {
  // initialize both serial ports:
  Serial.begin(9600);
  Serial1.begin(9600);
}

void loop() {
  // read from port 1, send to port 0:
  if (Serial1.available()) {
    int inByte = Serial1.read();
    Serial.write(inByte);
  }

  // read from port 0, send to port 1:
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial1.write(inByte);
  }
}

Basically what this does is it takes the data it receives from the USB port via Serial and transmits it to Serial1 and then also reads from the UART port via Serial1 and transmits it back to the computer via Serial. With this code running you should be able to hook up the XBee to RX1 and TX1 and communicate to it using the Serial Monitor.

Wow, Thank you for your response. I tried it out, it worked, but somehow it only work if i connect xbee rx to arduino rx1 and xbee tx to arduino tx1. Is this supposed to be this way. all i change is changing int inByte to char inByte

And, i also tried using +++ to enter command mode. i can receive the first OK response, but the subsequent commands are not able to go through. thank you in advance

It should be rx to tx in both directions. Also the baudrate in my example (9600) should be changed to match whatever your xbee is configured for.

THANK YOU SO MUCH, it worked as you said.. My coordinator DL is wrongly typed.

Not if you have it connected to pins 0 and 1, no.  You should not use those pins for anything unless you absolutely have to, since they are what are used for communication with the PC.  You can't do both communication with the PC and with the XBee using the same pins.
You should ensure that the XBee is connected to one of the other serial ports on the Mega and then write a sketch that passes the data through from one port to the other as needed so you can view it on the serial monitor.


text:
xbee communication not established between arduino
I have 2 Xbee Series2 modules, one set to Coordinator AT (Connected to PC with XCTU via USB dongle) and other set to Router AT(Connected to Arduino is connected to PC USB... RX>TX  TX>RX and 5V GND)
http://continentalee.com.sg/xbee-adapter
My xbee adapter
I have the programme uploaded into Arduino, a very simple sketch to test xbee wireless communication.
Code is here
char msg = ' '; //contains the message from arduino sender
const int led = 13; //led at pin 13

void setup() {
Serial.begin(9600);//Remember that the baud must be the same on both arduinos
pinMode(led,OUTPUT);
}
void loop() {
while(Serial.available() > 0) {
           msg=(char) Serial.read();

           if(msg=='H') {
               digitalWrite(led,HIGH);
           }
           if(msg=='L') {
                digitalWrite(led,LOW);
           }
delay(1000);
}
}

The problem comes.
When I type "H" in the Serial Com, the led light up, and the letter "H" appears in the XCTU console.
however, when I type something into the XCTU console, nothing appears on my Serial monitor and no light is seen on arduino
Thank you for your help in advance.

Your example does not show your code that sends correctly but I will assume that it used 9600 speed and that the xbees are configured to 9600.
Not sure if this will help ...

Arduino is connected to PC USB... RX>TX TX>RX

1) In this case maybe you should ensure that xbee tx is connected to the correct rx pin on the Arduino? I know you have stated this above but with the basic xbee configuration, if data works one way then it should also work the opposite way.

however, when I type something into the XCTU console, nothing appears on my Serial monitor and no light is seen on arduino

2) Your example doesn't show any code to send data to XCTU and the pin13 LED will only light up when an 'H' is sent from XCTU
You could try this for better diagnostics
    void loop() {
while(Serial.available() > 0) {
           msg=(char) Serial.read();

      Serial.print("data arrived from xctu: ");
      Serial.print(msg);
      Serial.println();

           if(msg=='H') {
               digitalWrite(led,HIGH);
           }
           if(msg=='L') {
                digitalWrite(led,LOW);
           }
delay(1000);
}
}

Hi, thank you for your response. I checked the baud and the connection, everything is fine. Do you mind to enlighten me how to write code to send messages to XCTU using the arduino serial monitor

Hi, my code example shows how to do this. You should see a message in xctu showing the text "data arrived from xctu:". Have you configured xctu to 9600 baud and opened the port?


text:
Attiny88 programming with Arduino
I want to program Attiny88 with Arduino IDE 1.6.5. I chose Attiny88  because it's the cheapest Attiny (as low as $0.5) and at the same time has 28 pins. I found a library that support Attiny88 (https://github.com/TCWORLD/ATTinyCore) but it seams it does not support IDE 1.6.5 and generates errors when I burn bootloader or during ISP.
Is there any library to program Attiny88 with Arduino 1.6.5?

The older versions of Arduino are still available for download. Why not use an older version?

Finally I found ATTinyCore library. I have tested it with a blink sketch. Just download the zip file. Unzip and copy  Attinycore-master directory into "program files/Arduino/hardware/arduino/avr" directory. Restart the IDEA. Select ATTiny x8 Series from the boards menu, and select the specific chip (48 or 88), clock speed, and BOD level from the appropriate menus that will appear in the tools menu after selecting ATTiny x8 series as the board.
https://github.com/SpenceKonde/ATTinyCore

I went through the same problem finding the cores for the attiny 88 and found this
http://forum.arduino.cc/index.php?topic=320742.0
programming attiny88 & attiny828 with arduino
However, I have not yet found the core for the attiny88 at 12mhz (http://co.mouser.com/ProductDetail/Atmel/ATTINY88-AU/?qs=sGAEpiMZZMvqv2n3s2xjscfa4zIkTHJI8r77%252bczQD%252bE%3d)

Different speeds don't use different cores. Simply copy the existing entry in boards.txt and modify the clock rate there.

The above links don't lead to a working core. The bootloader does not work correctly.


text:
Remove Bootloader on Arduinos
I am trying to move from arduinos to AVR C. Would somebody know how to remove the arduino bootloader from the microcontroller? Is there a different process for the different atmega microcontrollers like the 32u4, 328, or 2560?
Thanks.

You don't "remove" the bootloader, you just ignore it.  When you program your new code with the hardware programmer of your choice it will just overwrite the bootloader code with your software's startup code.

If you actually need to.  Just because a program is written bare-metal without use of the Arduino runtime libraries down't mean an Arduino/optiboot/whatever bootloader may not still be a convenient way to get it onto the chip.  It's really only necessary to remove the booloader if you need to speedup the start of the application after reset, remove any chance of it not starting based on serial input that looks like programming commands, or reclaim that small amount of flash space.

I think you need to change the fuses, to set the correct Boot Start Address (or that flash memory isn't available for your program).

Isn't that naturally part of you writing your program? Setting the right fuses for your program?


text:
Is it possible to setup a CAN-BUS Arduino Shield to communicate with SocketCAN for UNIX?
I have an Arduino + SparkFun CAN shield, and I was hoping to set it up to work with candump on an Ubuntu system. Is this doable, or is candump made specifically for raspberry Pi's?

What's candump? How about providing some links, eg. to the shield and whatever candump is.

what do you mean "set it up to work with candump"? What are you trying to achieve? Are you trying to use an Arduino to expose a CAN bus to the linux candump?

Yes. Normally you would write a linux kernel driver to communicate with your device (arduino) following your own protocol, but SocketCAN provides by default a way to interface with Lawicel dongles, whose communication protocol is publicly available: CANUSB / CAN232 protocol.
Many people have built arduino sketches that implement this protocol so you can use your arduino with SocketCAN in Linux (candump, cansniff...) as if it were a Lawicel dongle.
You may find this useful:
https://github.com/autowp/arduino-canhacker
https://github.com/kahiroka/slcanuino

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