text:
How to properly construct objects on ATmega2056?
I was wondering the correct method to construct objects for use in the setup and loop scopes. I tried working constructing in the global scope, but I get garbage values printed to serial (probably from misusing pointers)? If I use the new keyword, then it works, but I heard that that is not best practice.
I is there a better way I should do this?
// navigator.cpp

#include "navigator.h"

Navigator::begin(Waypoint* w, int count) {
  waypoints = w;
  pointCount = count;
  next = 0;                               // start with first waypoint
  course = 90;                          // Notice that initial course is due East

  Serial.println('here');
}

-
// navigator.h

#define _navigator_h

#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

struct Waypoint {
  double lat, lon;
};

class Navigator {
public:
  begin(Waypoint* w, int);
};

#endif

-
// TransAt.ino

#include "navigator.h"

Waypoint w = { 43.36, -75.1 };  // These objects must be accessible in both setup() and loop(), but we can't use the new keyword
Navigator nav();                    // That means we have to do a lot of the heavy lifting here

uint32_t timer = millis();

void setup() {
  nav.begin(&w, 1);
}

void loop()
{

}

No Serial.begin(baudrate);? Also Navigator nav(); is kind of function prototype. You can use Navigator nav;

What might be easy in such cases, is first to make it in e.g. VisualStudio (without using Arduino), and later when everything works on a PC (where you can debug everything easily) run it on an Arduino. Only calls like Serial, you have to comment out or stub.

Debugging questions need to include the actual output produced.  Is it repeatable or random?  also, you should reduce your code to a minimum example which demonstrates the problem, and correct your title for the fact that there is no such thing as an ATmega2056.  Are you targeting the bare chip, or an Arduino Mega2560/clone?

I tried working constructing in the global scope, but I get garbage values printed to serial ...

Constructors in global scope are called before init and setup and thus are probably executing too soon for you. This would account for the garbage printed to serial, because your constructor is printing before the Serial.begin() call.
You can put constructors in global scope, however they should do fairly trivial things (eg. setting a counter to zero, or a pointer to NULL). Do not rely upon the system being initialized, thus do not call functions like millis, nor should you be using dynamic memory allocation at this point.
Most classes defer their "real" initialization to a begin function (eg. Serial.begin) because it is safe to do that, usually in the setup function.


text:
4:1: error: expected initializer before 'void'

int button

void setup()
{
 pinMode(13, OUTPUT);
 pinMode(12, OUTPUT);
 button 4;
 pinMode(4=INPUT);
}

void loop()
{
  if(digitalRead(4)== LOW);
  {
  digitalWrite (13, HIGH);
  delay (250);
  digitalWrite (13, LOW);
  digitalWrite (12, HIGH);
  delay (250);
  digitalWrite (12, LOW);
  }
 }

I need help, im new on this and i want to try something like Press button to start LOOP but it didtn work. it still telling me :4:1: error: expected initializer before 'void' and 4:1: error: expected initializer before 'void' but i still cant find a mistake on code.

You are missing a semicolon after the button declaration

Please don't post photos of the code editor, that's not useful. Paste your code in with at least four spaces ahead of each line to retain the formatting.

There's significant syntax errors in your code. I think I've caught them all.
   //int button;

   void setup() {
     pinMode(13, OUTPUT);
     pinMode(12, OUTPUT);
     // button 4;
     pinMode(4, INPUT);
   }

   void loop() {
     if (digitalRead(4) == LOW) {
       digitalWrite (13, HIGH);
       delay (250);
       digitalWrite (13, LOW);
       digitalWrite (12, HIGH);
       delay (250);
       digitalWrite (12, LOW);
     }
   }

NICE!! Thank you, I can finally start simulation. But do you know why the leds are always on? The leds doesnt react to button.

@Deepee: The button-input needs a pullup resistor to keep it HIGH when the button is not pressed. The easiest way to add one is to make pinMode(4, INPUT); read pinMode(4, INPUT_PULLUP); instead. This uses an internal pullup provided by the MCU and saves you having to install one on your board.

@JRobert Thanks :) . U solved my problem.

Also good to note about the commented out and unused button 4; : if you want to assign 4 to the variable button, you use the = operator, so button = 4;

source: Stack Exchange

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

sort: votes


text:
Can't upload new sketch
Recently I have unsoldered most connector pins there are on the arduino uno board.
However, when I now attempt to upload a new sketch (works when I upload it to another model) it gives me the following error:
> avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xfa

I would like you take a look at my arduino board to see whether I have unsoldered important pins which might have to be connected.
Also when I try to upload a new sketch the 'L'-LED doesn't flash but the RX one.
(BTW: Yes I've set the settings to the correct board, port etc...)

Thanks for any solution attempts!

Clean the board up using solder wick -- if there are shorts like those mentioned in Jot's answer, it may clear them up.  Also, if you need an Arduino to solder into a circuit, just start with one that doesn't come with pins soldered on already -- eg, a Nano or Micro.  You can buy half a dozen of each for the cost of the time to take the pins off an Uno.

If I may suggest, there are "minimal" boards around you can buy for a couple of dollars that just have the basic processor on them. This could be a better solution than heating up your Uno (probably quite a lot) to get rid of the existing pins.

Removing there pin headers should not cause any sketch upload issue. I have done it many times.
You did try uploading BEFORE unsoldering the headers right ?
However looking at the desoldering job you did, my guess is that you applied too much heat or cut a trace on the PCB while doing it.
Can you upload a high resolution of the back side of the board?
What I would try is to take a known good 328p chip and replace the one on this board with it and try uploading again.

Checking the schematic, the TX/RX leds are driven directly by the atmega16u and are not connected to the TX/RX lines of the 328p.  That would seem to indicate the 16u has a problem so it's a good place to double check. The lines that run to the TX/RX of the 328p run from pins 8 - 9 of the 16u. I assume that this ran previous to the fatal 'surgery'? I don't suppose you loaded something simple, like the led flash program before surgery?  Just curious, are you hard wiring it to something?

Pin 0(RX) and 1(TX) and the RESET pins are important to upload a sketch. Can you check those carefully with a magnifier ? Perhaps there is some solder that shortcuts to something else, or perhaps you damaged a copper trace.

Try to unplug the IC and the plug it again.
I think that you have removed the IC off of the board. If it doesn't work then buy a new ATmega328P IC and replace it with the old one and then try again.

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


text:
can someone please fix this code
there is something wrong with this code logic and i can't put my hand on it so if any one can fix i would really appreciate it
Basically the code is used to receive couple of char from Bluetooth or serial monitor combine them together in an array then print this array then search for ":" in this array and atoi them into two different integer
IE (50:90) will be (50) and (90) in two different integer that are then used to control the direction and the speed of a motor
//motor a
int enA = 9;
int in1 = 8;
int in2 = 7;

//motor b
int in3 = 5;
int in4 = 4;
int enB = 3;
char data[32]; // Allocate some space for the string
char inChar; // Where to store the character read
byte index = 0; // Index into array; where to store the character

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(enA , OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
  pinMode(enB, OUTPUT);
  Serial.println("\n String conversion testing");
}

void loop() {

if(index < 31) // One less than the size of the array
      {for( int i = 0; i < sizeof(data);  ++i )
          data[i] = (char)0;

          inChar = Serial.read(); // Read a character

          data[index] = inChar; // Store it
          index++; // Increment where to write next
          for( int i = 0; i < sizeof(data);  ++i )
          Serial.println (data);

      }
    char* command = strchr (data, ":");
    if (command !=0)
    {
      *command = 0;
      int direc = atoi (data);
      ++command;
      int speeds = atoi (command);
      Serial.println(speeds);
      Serial.println(direc);
     int s;
     s = map(speeds, 0, 100, 0, 255);
    if (direc >= 85 &&direc <=100 ){//odam
        digitalWrite(in1,HIGH);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,HIGH);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
    }

      else if (direc >=260 && direc <=280){  //reverse
        digitalWrite(in1,LOW);
        digitalWrite(in2,HIGH);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,HIGH);
        analogWrite(enB,s);
      }

     else if (direc >=350 && direc <=360 | direc <=10 && direc >=0){ // RIGHT
        digitalWrite(in1,HIGH);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,HIGH);
        analogWrite(enB,s);
     }

      else if (direc >=170 && direc <=190){ // LEFT
        digitalWrite(in1,LOW);
        digitalWrite(in2,HIGH);
        analogWrite(enA,s);
        digitalWrite(in3,HIGH);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
      }

      else if (direc >=120 && direc <=150){ //FORWARD LEFT
        digitalWrite(in1,LOW);
        digitalWrite(in2,HIGH);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
      }

      else if (direc >=30 && direc <=60){ // FORWARD RIGHT
        digitalWrite(in1,LOW);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,HIGH);
        analogWrite(enB,s);
      }

     else if (direc >=210 && direc <=259){ // BACKWARD LEFT
        digitalWrite(in1,HIGH);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
     }

     else if (direc >=300 && direc <=340){ // BACKWARD RIGHT
        digitalWrite(in1,LOW);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,HIGH);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
     }

      else{ //If bluetooth module receives any value not listed above, both motors turn off
        digitalWrite(in1,LOW);
        digitalWrite(in2,LOW);
        analogWrite(enA,0);
        digitalWrite(in3,LOW);
        digitalWrite(in4,LOW);
        analogWrite(enB,0);
      }
    }
  }

@user35247 - Please don't literally "fix" the code by editing the question. Post an answer instead.

      inChar = Serial.read(); // Read a character

      data[index] = inChar; // Store it

The above is almost certainly not going to work as expected. You need to check if there is serial data available before reading it. (ie. call Serial.available()).
I have a page about reading from serial that might help you with that.
For example, your loop might look like this:
void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

Notice that the Serial.read is only done if Serial.available is true?

what about this part of the code though
inline char* command = strchr (data, ":");       if (command !=0)     {       *command = 0;       int direc = atoi (data);       ++command;       int speeds = atoi (command);       Serial.println(speeds);       Serial.println(direc);

What about it? You need to fix what I mentioned first, and probably add a debugging display to show what sort of string is being passed to that piece of code.

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


text:
Why Ethernet webclient fails to initiate?
I use the Ethernet shield with an Uno and create a web client. If I put a delay like one second for initialization it works fine. However if I wait for it in a while loop (like waiting for the serial, and as mentioned in Arduino docs) it never gets out of the loop that means the client instance is null.
I found this method on Arduino website in an example code:
while(!client) { ; } // waiting to get ready

Here's the code; if I uncomment it will stay there. Also the same with providing the MAC argument only.
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE };
char server[] = "www.google.com";    // name address for Google (using DNS)

IPAddress ip(192, 168, 1, 213);

EthernetClient client;

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

  Ethernet.begin(mac, ip);
  delay(1000);
  //while(!client){ ; }
  Serial.println(Ethernet.localIP());
}

Show the rest of your particular code.

@josecanuc #include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE };
char server[] = "www.google.com";    // name address for Google (using DNS)
IPAddress ip(192, 168, 1, 213);
EthernetClient client;
void setup() {
Serial.begin(9600);
while (!Serial) { ; }
Ethernet.begin(mac, ip);
delay(1000);
//while(!client){ ; }
Serial.println(Ethernet.localIP());
}

Code in comments is unreadable. Edit it into the post.

What is the commented line supposed to achieve...?

@majenko I want to check that if the hardware is functional and ready and my client object has created successfully so I can start communication. Instead of putting a blind delay(n) and hope for the best.

Then you want to do such things as check that you have a valid IP address from your DHCP server. Your "client" object will only be in any way valid once you have tried making a connection to a remote server.

@majenko then I think the only way left to let a client or server knowing it's possible for them to start is polling the Ethernet.begin() for some time / tries . Then rising an error and halt. Or is there a better way?  A server.begin() is a null type and server.available() is a client object type. None of them return an error.

You try opening a connection. If it works you can open a connection. If it doesn't then you can't.

Your while(!client){ ; } line can never do anything useful.
It is used to wait for a client socket to connect to a remote port. You aren't connecting to a remote port (that client object is doing nothing), so how it can never succeed.
It's like saying "Do nothing, and tell me when you're done".
I don't know what you hope to achieve with that line of code...

So what does it serve here

is the linked example wrong?

Most likely. I can't see what they think they are doing there. That test can never pass unless a connection has been attempted, and no connection has been attempted.

What you write is not a function but a variable. And the variable will not change its value (unless you have some interrupt and it is a global variable).
so you need to change 'client' to some function you want to call, probably 'client.xxx()' where xxx is the name of the function you want to call (possibly with parameters).

Actually it's an instance of an object with an int operator. It returns whether the socket is connected or not. That may be interrupt driven, or it may be done through yield(), which may explain it working with delay(), since delay() calls yeild().

I guess you're right but the code is available at link


text:
Trouble programming custom ATMEGA2560 board
I need some help. I copied the heart of MEGA2560 design into a new project. I have the new PCBs with blank MCUs and now I need to get things programmed. (I have an existing project that runs on a MEGA2560)
I was able to get the MEGA16U2 programmed using the procedure here: https://www.arduino.cc/en/Hacking/DFUProgramming8U2, (I loaded "Arduino-usbserial-atmega16u2-Mega2560-Rev3.hex") and it shows up in the Arduino IDE.
I got the ATMEGA2560 bootloader loaded using the Arduino-as-ISP instructions here: https://www.arduino.cc/en/Tutorial/ArduinoISP
But, now when I try to program my board with the with Arduino IDE (through the USB connection of the MEGA16U2), I just get:
avrdude: stk500v2_ReceiveMessage(): timeout

The full output of the IDE is:
Sketch uses 30056 bytes (11%) of program storage space. Maximum is 253952 bytes.
Global variables use 1280 bytes (15%) of dynamic memory, leaving 6912 bytes for local variables. Maximum is 8192 bytes.
/home/xxxxx/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/bin/avrdude -C/home/xxxxx/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf -v -patmega2560 -cwiring -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/arduino_build_464802/yyyyy.ino.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/xxxxx/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf"
         User configuration file is "/home/xxxxx/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

avrdude done.  Thank you.

An error occurred while uploading the sketch

I can see the RX led of the MEGA16U2 flashing, and the data at the RX pin of the ATMEGA2560 IC, indicating that data is getting to the MCU from the IDE, but there is no corresponding  TX activity.
The IDE and USB cable can program an Elegoo MEGA2560 clone with no problem.
Is this a baud rate problem? A protocol problem? What should be my next debugging step?
Thanks!

EDIT: Per Nick Gammon's comment, I have run his chip detector script. Here is the output:

Atmega chip detector.
Written by Nick Gammon.
Version 1.20
Compiled on Sep  5 2020 at 07:17:55 with Arduino IDE 10812.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x98 0x01
Processor = ATmega2560
Flash memory size = 262144 bytes.
LFuse = 0xFF
HFuse = 0xD8
EFuse = 0xFD
Lock byte = 0xCF
Clock calibration = 0x88
Bootloader in use: Yes
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 8192 bytes starting at 3E000

Bootloader:

3E000: 0x0D 0x94 0x89 0xF1 0x0D 0x94 0xB2 0xF1 0x0D 0x94 0xB2 0xF1 0x0D 0x94 0xB2 0xF1

<....snipped for length....>

3FFF0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

MD5 sum of bootloader = 0xD9 0xE6 0x6B 0x4E 0xD1 0xA6 0x11 0x2C 0x61 0x8F 0x9B 0xD5 0x5D 0x24 0xE2 0x13
Bootloader MD5 sum not known.

First 256 bytes of program memory:

00: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
10: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
20: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
30: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
40: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
50: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
60: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
70: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
80: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
90: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
A0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
B0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
C0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
D0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
E0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
F0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

Programming mode off.

I assume you have a few Arduinos lying around. Can you please run my chip detector sketch and report the results? (Amend the question).

Do you have the right fuse settings on the 2560 for your clock?

Have you built a 16Mhz external clock (e.g. a crystal oscillator)? When I tried something similar with a ATMega-328P (home design based upon an UNO) , I noticed that when I first uploaded my program it ran super slow (because the default fuses are to run on the internal RC oscillator / 8 = 1 MHz). Reloading the bootloader onto my design resulted in it running at normal speed - because it seems that this activity reset the fuses to use an external clock. Check out this post for reading and writing the fuses https://www.instructables.com/id/How-to-change-fuse-bits-of-AVR-Atmega328p-8bit-mic/

does the auto-reset circuit work? try a manual reset while avrdude attempts the upload

@NickGammon, I ran your program. See updated question. Thanks!

From the output, the LFuse = 0xff means that the MCU is expecting an 8-16MHz external crystal oscillator (the low 4 bits of the LFuse). Refer to sections 30.2 and chapter 10 of the Mega2560 data sheet (you can easily find this online). Do you have an external clock (crystal + supporting capacitors - section 10.4 of the data sheet) included in your hardware design?

@GMc Yes, there is a 16 MHz crystal on the board that appears to be oscillating correctly.

How is this going? Have you resolved it yet? If not, Have you tried uploading a simple program (e.g blink) via ICSP and see if that runs on your h/w?

@GMc Yes, I've been pushing ahead. I got the FW loaded into the 2560 using the "Upload Using Programmer" option in the Arduino IDE. So with that I have been able to verify much of the board...
Interestingly, I did notice today when trying to dump some debug text out of the serial port into the IDE, I was just getting garbage. It was not a baud rate issue, as that was the first thing I checked. I suspect that its related to the downloading issue.
Next I'll run a simple sketch to print "Hello world" and see if I can capture the TX data on my scope.
I'm open to any other debug ideas!

That is great news, I can't offer any further suggestions, but when you work it out, it would be really great if you could answer your own question and ideally post a circuit diagram (before and after if that is relevant). Hopefully you can work it out soon, but this sounds like significant progress. One thought though, how are you clocking the MEGA16U2 and what are the fuse settings for it?

As per the comments your output shows that the chip is working "normally" in that it reacts to the chip detector sketch. Thus the bulk of the design/implementation is OK.
Referring to Engbedded Atmel AVR® Fuse Calculator your fuse settings means the processor is expecting an external crystal oscillator. The bootloader expects (I think) a 16 MHz crystal (with appropriate capacitors). If you have not provided this then the bootloader will be running at the wrong baud rate (so to speak) — or not at all — and not react to attempts to download it by serial programming.
If you have a different frequency crystal then you may be able to work around this by adjusting the baud rate in the boards.txt file by an appropriate scaling factor.
The chip detector sketch worked because that uses ICSP programming, which provides its own clock.

Thus the bulk of the design/implementation is OK.
Great news!

I do indeed have a 16 MHz crystal on the board, and it looks like this oscillating correctly. I'll look into the baud rate issue.
Thanks again for your help, Nick!

Nick, apologies for the messages.
I have played around with various baud rates (via the boards.txt file), and nothing is working.
In the output of your program, also says
'''
Bootloader MD5 sum not known.
'''
Is that anything to be concerned with? I used the procedure outlined here: https://www.arduino.cc/en/Tutorial/ArduinoISP

That sketch, written quite a while ago, stored some MD5 sums of known bootloaders (at the time). There may well have been updates released since then. So that is no particular concern.

I suggest you get yourself a cheap logic analyser (say, around $100). Then you can see what is going on when the sketch starts to upload.

I use the Saleae ones - however the price seems more than I remember it. :(

There seem to be some on eBay which are very cheap - however I can't vouch for them. I think $100 to $200 (USD) would be a reasonable price to pay.

Nick, I greatly appreciate your help. Can I compensate your time for you to help me track down this issue? I feel like its something simple, but it's taking too much of my time. Please send me a message at infosavoyengineeringcom. Thanks!

I am not doing private consulting at present (paid or unpaid). My support for the Arduino community is through Stack Exchange, plus the (read only) articles on my web site. To problem-solve this issue you might be better off with the Arduino Forum - perhaps the Microcontrollers section. That might be more suitable for the "have you tried this? have you tried that?" style of working on your issue.

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


text:
I get an error saying, "exit status 1 expected initializer before 'void'."
I will be wiring a switch to the Arduino that controls the voltage. When the I turn the switch it can adjust the voltage from 0 to 5. The overall task is to print the output voltage. The print is to be a multiplication table of the voltage.
I created this code:
void setup()

void loop(){

  int (n,i,j,result);

  printf("enter N Value");

  scanf ("%d", &n);

  for (i=1; i<=n; i++);

  {
    for (j=1; j<=n;j++);

    {
      result= (i*j);

      printf("%d", result);

    }
    printf("\n");

  }
  return 0;

}

But i get the error exit status 1
expected initializer before 'void' when I try to verify it. what does it mean. How do you fix it?

Your setup() function has no body.

@Majenko what do you recommend for the set up? I though it could run off the loop

If you don't need any setup code then give it an empty body.

@Majenko im not sure if anything needs to go in the setup. this is my second day of trying this, that's why im asking for assistance.  What do you recommend for ?

I think you should start by learning basic c syntax.

@Majenko well I am trying to learn at the moment. But that doesn't help me get this working.

Functions must have a body. So instead of:
void setup()

You need:
void setup()
  {
  // do nothing
  }

You have other issues, for example this is not C++:
  int (n,i,j,result);

That should be:
  int n,i,j,result;

Also you are returning 0, when void functions don't return a value.
Also, here:
  printf("enter N Value");

  scanf ("%d", &n);

Where is this value coming from? There isn't a keyboard on the Arduino.
See: scanf

The C library function int scanf(const char *format, ...) reads formatted input from stdin.

The Arduino is a microprocessor. It doesn't have stdin.

Nick, Im under the impression that most of my issues remain in the fact that i have nothing in the setup body. that's why im getting errors like n, i, and j was not declared in this scope. How do you recommend I address this?

No, they are two different issues. I showed in my first paragraph how to fix setup.

with the corrections you gave me the code was verified. Im going to have to work on it doing what i need.   Also you asked we i got these, I pulled them from other forums and tried to piece together something. I know its not proper but its the second day for me learning this.

OK, you are progressing. :) You might want to read up on Serial because that lets you work with the Serial Monitor (something you can activate in the IDE), and (using the USB interface) you could indeed show text, and receive text. However printf and scanf are not the exact functions you need for that.

Great, thank you so much. I will look into them now.


text:
Level tracking using optical or capacitance sensors
I am looking to devise a level tracking system using arduino and some sensors. My particular situation is I have solute that is coming out of solution and I want to track the formation rate of the solid phase as the salts settle at the bottom and build a bed of particulates.
I am looking for precision at about 0.5mm and over a range of like 6 inches. My initial idea was to get a sensor bar that could detect when and where light is hitting the sensor and post processes that signal. I have to design this device to sit outside the cylindrical vessel. The solvent is transparent so any form of light would work. I am stuck on finding the parts that could pull this off and I was hoping the more experienced community could point in the right direction.
* UPDATE *
a little cartoon for a clearer picture of the idea
I am leaning towards capacitance since using light seems like a rabbit hole. I was playing with some foil and it may work but I need a much more sensitive tool on the order of pico-Farads to work.

What is the distance between the sensors? If it's a short distance, you could possibly get away with using two clear tubes and putting sensors in one tube and then lights in another tube.

@AnnonomusPenguin The diameter of the tube that contains the liquid I want to measures is on the order of 3cm. My best thought thus far was to go for an approach parallel plate capacitors, but I am not sure that would work to well.  I need really high resolution since the materials would have low k values.

Ultrasonic sensor?

@RSM how would that work? I am thinking I need to account for possibly 6 inches in elevation change.

@TheCodeNovice the time from the transmit to the time of receive would change as the level increases. If the liquid level increase with proportionally to the increase of the solid the level sensor could work. Also there capacitive sensors for level sensing, partially described here http://en.m.wikipedia.org/wiki/Level_sensor

@RSM Thanks for the link! The problem is for my experiment I cannot have anything inside the tube I must measure the level externally. Also I am looking to get the level as a function of time so I need a continuous means of measurement.

@TheCodeNovice so in terms of in the tube and the ultrasonic sensor, if that works, can sit above the vessel.

@RSM top or bottom is not workable because of flow inlets and outlets. I am trying to get the height without intruding. This is tube is hooked up to a machine. I can only attack it from the sides. Thanks for all the great suggestions though!

@TheCodeNovice - possibly if you isolate the capacitive sensor on the outside of the tube from the interference of air, it should increase the accuracy to a point.

What solution is it?

@RSM how could i isolate from air interference?

@TheCodeNovice - I don't know off hand what would be best but I am sure a Google search should give something. It should basically keep the surrounding air at a constant so that it doesn't change with changing air flow(blocking movement from changing the level) if possible you could put a plastic tube around the other tube and seal the ends. That's if you can get something around withe the other stuff.

A quick search for “capacitive water sensor” gives this.

Light might be the way to go, since the preciptate might not have significantly different capacitive or acoustic properties   How about a laser-sensor pair shining through to a sensor on a movable servo or stepper-driven stage, and you move the stage upwards/tube downwards whenever the laser diffuses into the precipitate, keeping track of the motion of the stage?

What about measuring this with two resistive probes - the electricity will go through down one probe to the top of the water, across the water, and up the other probe. You can measure how much of the probe it went down, by measuring the resistance. You would need the probes to be a specific, very consistent distance apart, and be made of resistance wire.
Another option is to use a float of some kind, and measure it this way. This is a lot easier if all you need to know is full/not full.


text:
w5100 and nrf24l01 - SoftSPI - Radio not starting
I had posted some questions about this project earlier this week. Arduino uno + w5100 ethernet shield + nrf24l01 transeiver.
The w5100 is running a webserver to accept GET requests and parse out the variables - Works all the time
The nrf24l01 is acting as a transmitter and sending data out to other nodes - Only works with no Ethernet code.
What doesn't work is both at the same time. With everything hooked up it parses get fine, gets the variable but I can't transmit it since the radio never seems to fire up. Remove all the ethernet code and leave just the radio code it sends fine.
Code here. http://pastebin.com/SMWC9x4F it errors at 146. Which I assume is the radio never starting since the:
radio.printDetails();

does nothing.
I'm using manicbug's library.
I use the EXACT same send bits in that file to test wireless communication, it works. I only need it to transmit wirelessly when it get data from the network.
Pinouts:
CSN -> 10
CE   ->  9
MISO -> 12
MOSI -> 11
SCK   -> 13
VCC   ->  Separate 3.3 source, not the arduino
GND  -> GND
My guess is this is because both are using SPI.
Tried the softspi method http://pastebin.com/4mv612B7 .
Same thing. I can post GET to it, parse out variables but nothing on the radio side. And I still get no output from radio.printDetails() so it just must not be starting. Commence hair pulling..
EDIT: Bloody hell, printDetails() relies on printf...... that would have been handy to figure out an hour or two ago.  I can get details now. still having communication issues.  Will post more debugging information in a bit.

The issue here is that the Ethernet chip locks the SPI bus thus making it impossible for NRF24L01+ to communicate with the arduino properly. Please use softSPI to fix this.

Issue one:  .printDetails(); uses printh.  If you don't have that included you won't get the information.
Issue two:  The ide gets confused when you have two libraries with the same file.  I compiled my receiver with the softspi file. Once I put the right library in it works.


text:
Receive data from ESP32 with HTTPClient
I need to receive data from sensors on the websites located on my PC (hosted with XAMPP).
When I was first using AsyncWebServer library and hosting them on ESP32 everything was working with a combination of those two:
response = String(digitalRead(button1)) + "," +String(digitalRead(button2)) + "," +
                String(digitalRead(button3)) + "," +String(digitalRead(button4)) + "," +
                String(angleX) + "," + String(angleY) + "," +
                String(sensor1value);

server.on("/state", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send(200, "text/plain", response);
  });

and:
setInterval(function ( ) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            var Answer = this.responseText;
            console.log(Answer);
            let values = Answer.split(',');
            document.getElementById("led1").style.backgroundColor = (values[0] == 0) ? 'green' : 'red';
          }
        };

        xhttp.open("GET", "/state", true);
        xhttp.send();
      }, 100 ) ;

JS script was linked on dashboard.html page and changed the appearance of elements on it according to the values.
Now I need the same result with HTTPClient
String serverName = "http://192.168.0.20/glove/state.html";

/*response = String(digitalRead(button1)) + "," + String(digitalRead(button2));*/

response = "?button1=" + String(digitalRead(button1)) +  "&button2=" + String(digitalRead(button2));

/*response = "button1=" + String(digitalRead(button1)) +  "&button2=" + String(digitalRead(button2)); */

    WiFiClient client;
    HTTPClient http;

    //String serverPath = serverName + response;
    String serverPath = serverName;
    //Serial.println(serverPath);
    http.begin(client,serverPath);

    http.addHeader("Content-Type","application/x-www-form-urlencoded");
    //http.addHeader("Content-Type","text-plain");
    //http.POST(response);
    int httpCode = http.GET();
    //Serial.println(response);

    //int httpCode = http.sendRequest("POST",response);
    Serial.println(httpCode);

But I can't get it to work (was trying different combinations with GET and POST methods).

Why do you use /glove/state.html in the new client instead of just/state?

Please, show your attempt at using POST, as this is the relevant HTTP method. Are you sure you have WiFi connectivity? Are you able to send the data to your XAMPP server manually with either curl or HTTPie? Can you capture the HTTP dialog with a network sniffer? Could you show us the on-the-wire requests, both a successful (with curl or HTTPie) and an unsuccessful one (with your HTTPClient code)? Comparing them should tell you what is going wrong.

I've written a set o ESP32 libraries. One of them is for a web server. Check it out here: https://github.com/aeonSolutions/aeonlabs-ESP32-C-Base-Firmware-Libraries#readme . ilnd "routes.cpp". Hope it helps

@PeterPaulKiefer because with old library there was no additional file called "state" (or state.html or whatever) - it was declared in that server.on. When i tried using only "/state" with new library i was getting error that  there is no file/page with that name (so i created state.html)

@EdgarBonet i think i had connection with my xampp server, because when i was serial printing response status code i was getting 200 (or some error ones depending on my changes in code)


text:
Arduino Uno R3, WS2812B, 1 strip of 60 leds, segmented in to 4
Arduino Uno R3, WS2812B, 1 strip of 60 leds, segmented in to 4.
Problem: Only want a single segment/fx_mode to run at any one time.

#include <WS2812FX.h>

#define LED_COUNT 60

#define LED_PIN 13

WS2812FX ws2812fx = WS2812FX(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

void setup() {

ws2812fx.init();

ws2812fx.setBrightness(85);

// divide the strip of 60 LEDs in to 4 segments

ws2812fx.setSegment(0,  0, 14, FX_MODE_COMET, BLUE,  3000, false);

ws2812fx.setSegment(1, 15, 29, FX_MODE_SCAN, RED, 3000, true);

ws2812fx.setSegment(2, 30, 44, FX_MODE_SCAN, BLUE,  3000, false);

ws2812fx.setSegment(3, 45, 60, FX_MODE_SCAN, RED, 3000, true);

ws2812fx.start();
}

void loop() {

ws2812fx.service();
}

and doesn't it? ... what is your question?

aren't they individually addressable LEDs?

look at example code in the arduino IDE

your post doesn't say much of anything about what you are trying to do  ... the example code is right there in the Arduino IDE on your computer

Please let me explain this more.  I have 1 strip of 60 leds, segmented in to 4 parts with 4 different FX_MODES and colours. I only want 1 segment or FX_MODE to be ON at any one time...  Segment(0, to be ON and the rest are OFF.  Next Segment(1, is ON and the rest are OFF. Next Segment(2, is ON and the rest are OFF. Next Segment(3, ON and all the rest are OFF.

You can help by putting the additional information in the question by editing it. As it is now, your question only consists of unformatted code with no descrtiption of what's wrong with it or what you're trying to accomplish. It's unlikely to be answered like this.

You have to look at the ws2812fx library to see what the code is doing. I think it is described pretty well here, including how the setSegment function works. You can leave out the ws2812fx.setSegment(1, ...) to (3, ...) to stop using that segment. You can change the amount of LEDs in a segment with the second and third parameters, i.e. ws2812fx.setSegment(0, 0, 4, ...) will only light the first 5 LEDs (0..4). Just experiment a bit with the parameters.

I'm just an unpaid volunteer trying to help you in my free time, which I will stop doing after your comment. I can't read your mind. You need to put all of this information in the question. What about "pause/delay/time/count"? It's not in your question. How was I supposed to know that you already changed the amount of LEDs in each segment? You did not mention it anywhere.

I've tried to read everything I could on here and in library examples, on youtube and google.  Finally post a question here at 3am as I thought the problem would be obvious to a pro.  It's now 5am and way past bed time lol good night

Your question reads like: "Problem: I want to bake a cake. Here is the recipe". You don't say what actually happens when you follow the recipe. Even a pro can't answer that.

The used library doesn't give you the direct possibility to automate the segment changes. So you need to write that code yourself.
Currently you are setting up all segment in setup() and starting them together via start(). Instead you should add the corresponding segment only, when it should be on, and removing all segments, that should not run. In the following I don't remove and add a segment, but I'm replacing the previous segment (described below)
I propose a code like the following, to light up each element after the other for a specific time each (not tested):
#include <WS2812FX.h>

#define LED_COUNT 60

#define LED_PIN 13

#define SEGMENT_INTERVAL    3000
unsigned long segment_timestamp;
uint8_t current_segment = 0;
#define SEGMENT_N   4

WS2812FX ws2812fx = WS2812FX(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

void setup() {
    ws2812fx.init();
    ws2812fx.setBrightness(85);
    ws2812fx.start();
}

void loop() {
    if(millis()-segment_timestamp > SEGMENT_INTERVAL){
        segment_timestamp += SEGMENT_INTERVAL;
        switch(current_segment){
            case 0:
                ws2812fx.setSegment(0,  0, 14, FX_MODE_COMET, BLUE,  3000, false);
                break;
            case 1:
                ws2812fx.setSegment(0, 15, 29, FX_MODE_SCAN, RED, 3000, true);
                break;
            case 2:
                ws2812fx.setSegment(0, 30, 44, FX_MODE_SCAN, BLUE,  3000, false);
                break;
            case 3:
                ws2812fx.setSegment(0, 45, 60, FX_MODE_SCAN, RED, 3000, true);
                break;
        }
        current_segment = (current_segment + 1) % SEGMENT_N;
    }
    ws2812fx.service();
}

What happens here? First we use the millis() function in the pattern of the BlinkWithoutDelay example to time the change of segments to every 3s (3000ms) without blocking the execution of the other code (here the service routine of the LED animation). I will not go into detail here, since this principle is described at numerous places through the web and this site. Just search for something like "Arduino millis" or "Arduino Blink without delay". Now is only important, that the code inside the if statement will be executed every 3s (can be changed with SEGMENT_INTERVAL).
In the if statement we use a switch statement to set the corresponding segment, that should be activated at that time. Here we always set the segment 0, since only one segment is active at any time. Instead of removing the previous segment and adding the new one, we just change the previous segment to the data of the new segment.
With the line
current_segment = (current_segment + 1) % SEGMENT_N;

we increment to the next segment, while wrapping around from segment 3 to segment 1 via the modulo operator %. This is needed to loop through the segments.
The call to ws2812fx.service() is still needed, since it handles the actual animation of the current segment.

Note, that the above code can still be improved. You could save all the segment data in an array of structs and replace the switch statement with one line, using the current_segment'th element of the array. I will leave that improvement to you.


text:
Plotting a real time graph of sensor data from Arduino on Processing, MatLab or Python
I have an accelerometer connected to my Arduino Due to spit out data on my serial monitor as described in my earlier post. I'm trying to find a sketch I could use to plot a continuous real-time graph on either Processing, MatLab or using Python MatPlot.
The accelerometer data is stored in arrays of xArray[k] for the x-coordinate values, yArray[k] for the y-coordinate values and zArray[k] for the z-coordinate values. How can I plot a real-time graph of these values? Thanks in advance.

 import serial #import Serial Library
 import numpy  # Import numpy
 import matplotlib.pyplot as plt #import matplotlib library
 from drawnow import *

 accelX = []
 accelY = []
 accelZ = []

arduinoData = serial.Serial('COM4', 115200)
plt.ion()    #Tell matplotlib you want interactive mode to plot live data
cnt = 0
def makeFig():         #Create a function that makes our desired plot
#plt.ylim(0,1000)                #Set the limit on the y axis
plt.title('Sensor data')         #Set the title
plt.grid(True)                   #Set The grid
plt.ylabel('Axis Acceleration')  #Label the y axis
plt.plot(accelX,'ro-', label='Raw X Acceleration') #Set the line plot
plt.ylim(0, 1000)
plt.legend(loc = 'upper left')
plt2 = plt.twinx()  #Create a new object of plt2
plt2.plot(accelY, 'b^-', label='Raw Y Acceleration')
#plt2.ylim(0,1000)
plt2.legend(loc='center right')
plt2.ticklabel_format(useOffset=False) #Compel matplotlib not to autoscale
#plt3 = plt.twinx()
plt.plot(accelZ, 'go-', label='Raw Z Acceleration')
plt.legend(loc='upper right')
plt.ylim(0,1000)

 while True: #While loop that loops forever
   while(arduinoData.inWaiting() == 0):   #Wait here until there is data
    pass #do nothing
arduinoString = arduinoData.readline() #read the line of text from serial
dataArray = arduinoString.strip().strip('\n')  #Split into an array
# Ensure that you are not working on empty line
if arduinoString:
    dataArray = arduinoString.split(",")
# Ensure that index is not out of range
if len(dataArray) > 1:
    xAxis = int(dataArray[0]) #Convert first element to int insert in xAxis
    yAxis = int(dataArray[1]) #Convert second element to int insert in yAxis
    zAxis = int(dataArray[2]) #Convert third element to int insert in zAxis
    print xAxis, ",", yAxis, ",", zAxis
    accelX.append(xAxis)   #Build our x axis array by appending to accelX
    accelY.append(yAxis)   #Build our y axis array by appending to accelY
    accelZ.append(zAxis)   #Build our z axis array by appending to accelZ
    drawnow(makeFig)       #Call drawnow to update our live graph
    plt.pause(.0000001)
    cnt=cnt+1
    if(cnt>50):
        accelX.pop(0)
        accelY.pop(0)
        accelZ.pop(0)

Hi all, so after tweaking that sketch, it did generate the graph for the buffered data but it's still rather slow but it works..If anyone has an idea that could make it plot the graph faster please do help out. Thanks

I hope this is helpful to you.
First, you need to read about serial communication between matlab and arduino. You need to establish communication between those two first.
Then take note of the format of the data coming out of your Accelerometer. In my case, I'm working with IMU and my data format is as an example: #YPR = 2.34, 13.23, -2.20
Then, from Matlab, you need to write a script to be able to read this string and identify any floating-point value.
This is what I did in Matlab. YPR = Yaw, Pitch, Roll
data = fscanf(s);              %Read Data from Serial
[Y(count),P(count),R(count)] = strread(data, '#YPR = %f,%f,%f');

Then you have to set up the plot and force matlab to update the plot in real time.
%set() is used to set graphic object properties
       set(plotGraph1,'XData',time,'YData',Y,'color','r');
       set(plotGraph2,'XData',time,'YData',P,'color','g');
       set(plotGraph3,'XData',time,'YData',R,'color','b');
       drawnow;           %force matlab to updata plot instantaneously

The link below is a good place for you to get going. But you need to make some modifications to it though.
https://billwaa.wordpress.com/2013/07/10/matlab-real-time-serial-data-logger/

Thanks @goddar..will have a look and tell you how it turned out. Cheers

So @goddar ..I tried out the matlab code but I couldn't get it working properly, I mucked around with that of python , could only get it reading out values rather slowly and with the unbuffered data sketch in my first post http://arduino.stackexchange.com/questions/17206/pushing-accelerometer-data-in-packets-from-an-arduino-due-to-the-pc-and-unto-pro?lq=1 but when I tried it with the buffered data  sketch it froze.....the data couldn't even read out but there were no errors on the stacktrace. Below is the python sketch

Sorry for the late reply. I did some work on this mainly on Matlab and Im not that familiar with python. In the matlab you have to make sure that you set matching COM port and baud rate. You can use Test and Measurement Tool toolbox to check whether connection is made between your device and the computer. Once connected, you should first try to read the data continuously without plotting it yet. Once you can get there, just follow the link that I provide above. You need to do some modifications to it.

In Matlab, set InputBufferSize to 50000 and set ReadAsyncMode to 'continuous'.

MATLAB has a free add-on for connecting to Arduino hardware.


text:
Arduino and HC-05 hardware serial issues
I have a software sending bitmap data to an Arduino Pro 5V 16MHz 328P that drives an LED display (sketch). This works using the USB-Serial adapter for the Arduino Pro with baud rates up to 500000 Baud. Now I wanted to switch to Bluetooth...
I tried connecting a 5V HC-05 module (set to 230400 Baud 8N1) to the hardware RX/TX pins on the Arduino Pro (Pins 0/1) and connect the PC to the Bluetooth serial port wirelessly (e.g. /dev/rfcomm0 on Linux). My problem is that I can receive data on the PC side using a terminal (the 'Ada' string is received), but nothing is displayed on the LED display. I have tried connecting an oscilloscope to the RX/TX pins on the Arduino and Data is arriving from the HC-05 module TX pin to the Arduino RX pin.
When the USB-Serial adapter is connected to the same pins (0/1 instead of the regular pin header) it still works as before, so there should be no connection issues.
What I tried was adding a 5kOhm resistor from the Arduino RX line to ground. (I found this hint somewhere here), but no dice...
I'm not sure what's wrong, because communication IS working over the USB-Serial adapter. Any ideas on what to try?!

Start by using reasonable baud rates!   Whatever you think you are accomplishing by trying to make one piece of the system so fast, is almost certainly not going to result in meaningful improvement overall, yet vastly increases the change that the system won't work at all.

There's a few things I can think of that may be causing your issue. First, though, a few questions: (1) Which version of the Arduino Pro are you using (168, 328P, voltage, frequency, etc)? (2) Are you saying that you can connect the PC to the Bluetooth serial port via a USB cable or via a wireless Bluetooth link (a little confused by the wording)? (3) What model of the HC-05 are you using (I know you said 5V, but I've come across many variations of this device - a link of where you bought it would be great). Hope I can help once you have a chance to answer these questions!

@ChrisStratton: The HC-05 advertises Baud rate up to ~1MBaud, so imo 230400 is reasonable. Also it works with the USB-Serial adapter connected to the same pins.

@Mlagma: The model is an Arduino Pro 5V 328P 16MHz. I "connect"/pair the PC to the HC-05 wirelessly and then plug the module into the RX/TX pins (Pins 0/1) on the Arduino. The HC-05 Module is a regular board with a 5V level-shifter-breakout (very common). Sorry, but I don't have a link anymore. What I tried was adding a 5kOhm resistor from the Arduino RX line to ground. (I found this hint somewhere here), but no dice...

I have in fact used another HC-05 (no level shifters, 3.3V) sucessfully with an Arduino Due, plugging it into hardware Serial1 (Pins 18/19) and using the Dues' native USB port as a serial port to transfer text PC->HC-05->Arduino->PC back and forth. Even at 230400 Baud.

I have now tried connecting an oscilloscope to the RX/TX pins on the Arduino and Data is arriving from the HC-05 module TX pin to the Arduino RX pin. I guess the sketch is not working properly with the HC-05 connected, but I'm not sure why... What could I be missing?

No, 230400 is not reasonable unless you have verified for a fact that both your devices can generate the necessary timings signals accurately, which a little math would suggest an Arduino cannot.

@Chris: I did not say you don't have a point. I know you're referring to this problem. The error at 230400 should be ~8%, which is way off. I'll try with a lower bit rate.

115200 should be more than enough.

For everyone? You are probably joking and mean "640k". And no, it is not. I have too many LEDs for the Baud rate...

Have you actually calculated how many bits you actually need?

I have ~600 LEDs * 3 color * 8 bit resolution = ~14400 Bit / frame. This amounts to max. 8 frames/s for 115200 Baud, which is not enough. With 230400 It'd be ~16 frames/s, which is usable for me. I am testing simple compression algorithms too, so I can reduce the amount of data a bit, but ~10-20% size reduction will be the maximum.

A simple 10k/20k voltage divider is enough to bring the 5V arduino logic-level voltage down to ~3.3 for the HC-05.  It worked for me anyway.
The default baud rate for HC-05 is 9600 baud.  So unless you've changed this with AT- commands you will run into issues.  Although I read that some boards default to 38400 - best check your documentation.  All the cheap HC-05 boards I've tested default to 9600.

Communication works up to 115200 Baud, but not more. The goal was to get higher Baud rates...

@Bim - My HC-05 doco says my HC-05 hardware is only good for up to 115200.  Hopefully yours is a better brand.

Can you provide a link? A quick look in [http://www.instructables.com/files/orig/FOR/4FP2/HKZAVRT6/FOR4FP2HKZAVRT6.pdf](here, page 8) says it should allow up to ~1.5MBit, which makes sense, because Bluetooth 2.0 does. I also tried with two different modules.

I've run into similar issues with the Arduino and serial communications - it's quite a pain.
There really shouldn't be an issue with your sketch if PC->USB->FTDI->Arduino is working since the same protocols are used (UART is UART, after all).
In regard to the BAUD rate, sure, 230400 should work just fine. For purpose of testing, though, I would slow it down to a measly 9600 or something like that just to rule out any possible issues. (Plus, if I remember right, 9600 or ~11000 is the rate at which it operates when being programmed via AT commands).
Now these are my thoughts on what the problem may be:
You said several times that you have a 5V HC-05 with level shifters. The HC-05 chip itself operates on 3.3V, so typically there is a voltage regulator on the breakout board dropping the voltage down to 3.3V for the Vcc pins and whatever else is pulled high on the chip.
However, I have never seen an HC-05 on Amazon, Sparkfun, or Ebay that actually has a true logic-level shifter on the board itself. Instead (and this is true from my experience with Ebay sellers who claim logic-level shifting built in), there is a voltage divider on the HC-05 RX pin that allows you to send a 5V signal without external resistors. But this isn't bidirectional, so your TX pin still has a logic high level of 3.3V. In short, I think your HC-05 chip really doesn’t have a logic-level shifter.
You may be thinking I’m totally wrong about this, and I very well could be since I don’t have your module in front of me, but just hear me out by reading my reasoning below.
(1) You said you can receive data on your PC. This means the HC-05 is receiving data from a 5V signal and successfully converting it to 3.3V. Great. That works!
(2) You said you were able to get an HC-05 (presumably the same model) to work with an Arduino Due in both directions. The Arduino Due operates on 3.3V, so its logic high threshold is around 2.1v.
(3) On the 5V Arduino Pro, the minimum logic high threshold is (0.6)*Vcc -> 3V. So if the HC-05 is transmitting a signal with a logic high of 3.3V, the Arduino is barely registering it. Factoring in resistance and noise, your signal is probably less than 3.3V. (In fact, my HC-05’s usually push out a signal of ~3V).
Reading that you can see a signal on the HC-05 TX line, but the Arduino is not registering it, I’d bet your signal is below the threshold.
So, I’d fire up your oscilloscope again and check the peak voltage to see what it is.
Additional (Response to "what can I do?)"
You have a few options. The best option would be to use a bidirectional 3.3V-5V level shifter, but not many people have those laying around. If you happen to have some common components, you could try building a makeshift level shifter like in the images below:

The first "level-shifter" is a a voltage comparator using an opamp. If you go this route, ground V-, tie V+ to 5V, and calculate a voltage divider for around 1.5V. (Note: use the non-inverting setup). A cheap TL272 from Radioshack should work.
The second level shifter uses two NPNs and is self-explanatory.
Note, though, that I haven't tried any of these setups nor know their frequency responses. However, the TL272 should handle signals into the MHzs, and BJTs handle high frequencies rather well. My gut tells me it should work, but just in case, I would use a low BAUD rate.

DAMN! You seem to be right! The HC-05 puts out ~3V on its TX line. The RX line shows a maximum of 3.8V. What can I do?

@Bim I added some suggestions

Thanks a lot! I don't have a TL272 (or other OpAmps) at hand and don't really want to build a level shifter for 3 channels (RX/TX/EN) right now, so I ordered a bi-directional 4-Channel level shifter board. I still have a 3.3V linear regulator lying around. I seem to have broken the EN/KEY pin of the HC-05, but have a working one for 3.3V. It should take a couple of days for the stuff to arrive and for me to try things out, but then I'll get back with the results...

The parts have arrived and I tried connecting the HC-05 to the Arduino Pro through the level-converter. The voltage levels are now around 4.5V. It all works well through bluetooth at 115200 Baud, but not at 230400 Baud.I also tried using a Arduino Due instead and connecting the HC-05 directly (TX0/RX0). As before, I can receive data on the PC side (The "Ada" status message), but no data arrives on the Arduino side... I'm at loss what to try to get higher throughput through the HC-05...

@Bim Just to be sure, it is working now in both directions at 115200 Baud? The problem is that 230400 isn't working?

Yes.It is working at 115200 Baud in both directions. I captured the waveforms of a bit for 115200 and 230400. The signal generated by the Arduino looks good, but that of the HC-05 is pretty crappy: 115200
230400

A problem in the code could be that FastLED takes a lot of time in "show()" and due to that the serial port is overrun and data dropped... But at some point the code should recover. I uncommented the "while (Serial.available() > 0) { Serial.read(); }" loop (Line #83 in the sketch) to make sure incomplete data is consumed and the code will "sync" again, but that didn't help. It seems the other baud rates above 115200 the HC-05 supports are all not compatible with the (16MHz) Arduino... :(

@Bim One thing that might be worth checking is the signal after the level converter. The part you bought said its used for I2C, and 115200 BAUD is around the standard I2C frequency. When you double it, the signal might be attenuated you're nearing the crossover point of the frequency response.

See my previous reply that has screenshots of the signals linked. I grabbed the signals on the Arduino RX/TX pins so they are "behind" the level converter in relation to the HC-05. The TX signal from the HC-05 (RX on the Arduino) looks a bit distorted to me... They time the signal is HIGH might not be long enough for the Arduino.

@Bim I didn't notice the links before. They definitely look distorted, and it also looks like they only go up to 4V (which is fine, I was just expecting a little less than 5V). In any case, it could be, like you said, there isn't enough time for the Arduino to register the logic high signal being that it takes a while to pass the threshold. You could try a pull up resistor, but the trade off is a longer fall time. Also, the level converter could be messing with the high frequencies, which can cause what you're seeing. If you really want, you could generate a sine wave and watch the response.

I found this which suggest what you said (level-shifter distorts signal). I'll attach a probe and check the input/output signals of the level converter. I tried a pull-up resistor on the arduino side, but that didn't help. Will try one on the HC-05 side too...

I captures the signals on the HC-05 TX line at 230400 Baud before and after the level converter now. Images here. The upper image is without a pull-up. The lower image is with a ~1.5kOhm pull-up from 5V to the RX pin of the Arduino (behind the level-converter). It looks like the signal should be fine with the pull-up... It could still be that the bit rates of the HC-05 and Arduino are not matching as Chris Stratton mentioned. In that case I guess I'm lost?

Well this is really irritating. The signals look fine, so I doubt there are any problems left there. Another thing I can think of is in regard to the BAUD rate. The 16MHz crystal doesn't play too well with standard baud rates (even 115200 is a little off). However, multiples of 250k may work for you. The Arduino can deal with these speeds (others have done this). The HC-05 can also handle this, but it requires flashing it with different firmware.

I can run the Arduino at 250k and 500k Baud and it still works via standard serial, thus switching the HC-05 to those Baud rates might be a solution. Could you point me to a firmware/page that does this? I have already searched but not really found anything useful...

@Bim I'll throw some stuff together tomorrow. I didn't get a chance to do so today.

No sweat. I've got it hooked up via USB-Serial atm. I took a look at the CSR toolchain. Are you using the BlueCore SDK for this? If yes, in case you have sources I can compile, I could give it a shot too... That said, flashing the firmware seems to be the hard step. What would you recommend? I found this, which suggest using an Arduino as an SPI programmer. Sadly I have no access to a proper LPT port or FTDI232L atm.

The HC-05 requires a 5V power supply and 3.3V logic.
Using SoftwareSerial might be easier for you as you can use pins 8 and 9 rather than 0 and 1, because there can be issues with the USB.
Are you transmitting the data you think you are, might Big/Little Endian be an issue?
I can get two HC-05 devices to communicate when they are connected to the PC via serial port adapters.  However when I replace the receiver with a HC-05 connected to an UNO I get intermittent garbage received.  So I suspect there may be some sort of problem with PC->Arduino.

My HC-05 has level shifters, so it it suitable for 5V. Software serial is no option, because it is just too slow and blocks the Arduino. There should no issue with USB, because the Arduino Pro does not have USB. I don't think the Bluetotth module can change the endianess of the data. I'm interested what that "some sort of problem" is...

I have used HC-05 modules earlier, with baud rate 9600. But the Chinese modules I recently purchased from eBay appear to be pre-wired for 38400. The module refused to transmit anything, and was receiving garbage on the Rx side. So I changed the line
softSerial.begin (9800);

to
softSerial.begin (38400);

This solved my problem.


text:
How to read data from PC
I'm new to Arduino.
I'm passing some data from my Android phone to my Macbook via bluetooth (throught the app Sensoduino).
What I'd like to do now is to export that data to my Arduino Mini Pro.
Is there any way to achieve it?
(NOTE: I'm not able to connect my Android Phone directly to the Arduino via Sensoduino)

Could you please add more detail about what bluetooth hardware for example you are using. Also, could you elaborate a bit what "export that data to my Pro Mini" means?

A simple bluetooth module like a HC-05 wired to your Arduino will give you a  serial stream that can be read and/or written.
With the RX/TX connected to say pins 10 & 11, a SoftwareSerial() object will provide access:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

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

void loop()
{
    int value;

    if (mySerial.available(sizeof(int)))
    {
        value = mySerial.parseInt();
    }
}

If you connect the module to pins 0 & 1 - you can just use the Arduino standard Serial functions, but it will cause problems uploading to the board.  In which case you would disconnect the bluetooth module for uploading.


text:
Using 3.3V XBee with Arduino Pro Mini 5V Version
The Xbee requires a 3.3V power input and the Arduino Pro Mini (5V version) only provides a regulated 5V.
Question: What will be the simplest way to provide a 3.3V rail to the XBee from the Arduino Pro Mini?
If we use a voltage divider consisting of 2 resistors, the ratio should be 66/100, but how do we choose the resistor values?
If we choose a 3.3V voltage regulator, will the STMicroelectronics L78L33ACZ be suitable?

Between the voltage divider and voltage regulator, which is the preferred method? Is there a better alternative?

There is a second part to this - does the XBee talk to the Arduino? Connecting a 5v device to a 3.3v device requires a level shifter to protect and interface between the different voltage devices. While both power and IO can be interfaced using simple voltage divider resistors - personally I recommend regulating the 3.3v supply and using a simple MOSFET level shifter for IO. If you update the question for this, I can post a relevant circuit to accomplish both.

@RonJ. Yes XBee is communicating with Arduino. How can you use the MOSFET level shifter for IO? Will be great if I can have a look at your circuit :)

Is there any particular reason that you need a 5V Pro Mini? If not, then it would be much more appropriate to use a 3.3V Pro Mini in its place.

This is part of a Fritzing circuit I used to control the x'mas tree lights (the relays and sensors have been snipped out) with an XBee. This circuit uses a 3.3v LDO you may have to change the capacitor values depending on your regulator specs. I chose to use a separate 5V regulator (not shown) but it will work off the Pro Mini's +5V power rail.
There are two FETs that do the actual level shifting, the bonus transistor allows you to reset the Arduino and thus gives you the ability to program it over the air via the XBee (beyond the scope of the question, but if you want to go wireless, go wireless all the way - do the Google for wireless programming over XBee if needed). Note the 0.1uF across the XBee power pins, I recommend this capacitor be placed as close to the XBee as possible to minimize noise (I solder it across the back of the XBee interface board).

In what ways can noise across the XBee's power inputs affect it?

@Nyxynyx I don't remember exactly where it was specified, may have been in the XBee datasheet. The XBee is after all a 2.4GHz transceiver, and electrical noise [could] [may] disrupt communications. A 3 cent disc capacitor certainly doesn't hurt things.

The simplest way, as you ask, is probably a resitor-based voltage divider; its main drawback is the waste of energy in the resistors.

To calculate the "best" resistor values, you'll need to know the amount of current needed by the XBee module.
So you have:

Vin = 5V
Vout = 3.3V
Iout = to be determined (check XBee spec sheet for that)

Then you have to resolve the following equations to calculate the resistor values you shall use:
R1 = R2 x (Vin - Vout) / Vout
Iout = (Vin - Vout) / R1 - Vout / R2

These equations simply come from applying Ohm's law and Kirchhoff's circuit laws.
This site calculates the ideal resistor values for you.
For Iout = 100mA, it gives the following values:

R1 = 17 Ohm
R2 = 33 Ohm

Another simple way is to use a 3.3V zener diode if you have one on hand. You can google for good circuit examples.

You can use a voltage regulator to get the supply voltage down to 3.3v.
For the Serial Lines, the best way forward is to use a good level convertor like https://www.sparkfun.com/products/11978 from sparkfun.
If you don't want to buy it, you can also make it using a couple of Mosfet's and resistors. Here's the schematic from Sparkfun.

Please do not link to external content.  When the URL become invalid, this answer becomes useless.


text:
Delay function not working as intended
int j;
void setup()
{
   for(j=2 ; j<=9 ; j++)
      pinMode( j , OUTPUT );
   digitalWrite( 2, HIGH );
}
void one()
{
   digitalWrite( 3, HIGH );
   digitalWrite( 4, HIGH );
}
void all_off()
{
   for(j=3 ; j<9 ; j++)
      digitalWrite( j,LOW);
}
void loop()
{
   one();
   delay(1000);
   all_off();
   delay(3000);
}

Trying to do a blinking "1" (stopped at 1 before continuing other numbers because of this problem ) with a single-digit 7 segment display. Where pin 2 is comnected to the com pins of the display.
Expected: display 1 for a second , then turn off for 3 seconds.
Reality: display1 for 3 seconds then turn off for a second.
Tried putting the delay functions in the one and all_off functions but no use.
Tried changing the delay(1000) to delay(7000) , the off time increased.
Tried changing the delay(3000) to delay(1000) , the turn on time changed to 1 second.
The code should work in order, should it not?  What is happening? How to fix it?

And the wiring/circuit?

Without circuit information and part numbers, one can't say for sure what the problem is.  However, the symptoms suggest that your LEDs turn on when you pull some pin low, rather than when it goes high.  This can happen if, for example, the LED anodes are wired (through a resistor) to V+ and the cathodes are connected to a drive pin.  If, however, the cathodes are connected to  ground through a transistor, positive-logic should apply, rather than negative logic.


text:
I can't make more than one arduino gas sensor work at the same time
I'm doing a school project in which I need to track different kinds of gases, the problem is I can't read more than one sensor at the same time, I'm using four sensors (mq5, mq7, mq8 and mq135) and the code I'm using was one that I merged using four different codes that I found on github (https://github.com/mdsiraj1992/Gassensors). When I'm only one sensor it works normally, but when I use the code I merged the values are totally off. So basically I'm doing something wrong, but I don't know what. Please help me, I have to deliver the code this week.
#include <Adafruit_Sensor.h>

#include <Adafruit_Sensor.h>

#include <DHT.h>
#include <DHT_U.h>

#include <DHT.h>
#include <DHT_U.h>

/***Hardware Related Macros***/

#define         MQ5PIN                       (2)
#define         RL_VALUE_MQ5                 (1)
#define         RO_CLEAN_AIR_FACTOR_MQ5      (6.455)

#define         MQ7PIN                       (3)
#define         RL_VALUE_MQ7                 (1)
#define         RO_CLEAN_AIR_FACTOR_MQ7      (26.09)

#define         MQ8PIN                       (1)
#define         RL_VALUE_MQ8                 (1)
#define         RO_CLEAN_AIR_FACTOR_MQ8      (1)

#define         MQ135PIN                     (5)
#define         RL_VALUE_MQ135               (1)
#define         RO_CLEAN_AIR_FACTOR_MQ135    (3.59)

/***Software Related Macros***/

#define         CALIBARAION_SAMPLE_TIMES     (50)
#define         CALIBRATION_SAMPLE_INTERVAL  (500)
#define         READ_SAMPLE_INTERVAL         (50)
#define         READ_SAMPLE_TIMES            (5)

/***Application Related Macros***/

#define         GAS_LPG                      (1)
#define         accuracy                     (0)
#define         GAS_CARBON_MONOXIDE          (3)
#define         GAS_HYDROGEN                 (0)
#define         GAS_METHANE                  (2)
#define         GAS_CARBON_DIOXIDE           (9)
#define         GAS_AMMONIUM                 (10)

/***Globals***/
float           Ro = 10;

void setup() {
  Serial.begin(9600);
  Serial.print("Calibrating...\n");

  Ro = MQCalibration(MQ5PIN);
  Serial.print("Calibration is done...\n");
  Serial.print("Ro5=");
  Serial.print(Ro);
  Serial.print("kohm");
  Serial.print("\n");

  Ro = MQCalibration(MQ7PIN);
  Serial.print("Calibration is done...\n");
  Serial.print("Ro7=");
  Serial.print(Ro);
  Serial.print("kohm");
  Serial.print("\n");

  Ro = MQCalibration(MQ8PIN);
  Serial.print("Calibration is done...\n");
  Serial.print("Ro8=");
  Serial.print(Ro);
  Serial.print("kohm");
  Serial.print("\n");

  Ro = MQCalibration(MQ135PIN);
  Serial.print("Calibration is done...\n");
  Serial.print("Ro135=");
  Serial.print(Ro);
  Serial.print("kohm");
  Serial.print("\n");
}

void loop() {

  Serial.print("METHANE:");
  Serial.print(MQGetGasPercentage(MQRead(MQ8PIN) / Ro, GAS_METHANE) );
  Serial.print( "ppm" );
  Serial.print("    ");
  Serial.print("HYDROGEN:");
  Serial.print(MQGetGasPercentage(MQRead(MQ8PIN) / Ro, GAS_HYDROGEN) );
  Serial.print( "ppm" );
  Serial.print("    ");
  Serial.print("GLP:");
  Serial.print(MQGetGasPercentage(MQRead(MQ5PIN) / Ro, GAS_LPG) );
  Serial.print( "ppm" );
  Serial.print("    ");
  Serial.print("CARBON_MONOXIDE:");
  Serial.print(MQGetGasPercentage(MQRead(MQ7PIN) / Ro, GAS_CARBON_MONOXIDE)
              );

  Serial.print( "ppm" );
  Serial.print("    ");
  Serial.print("CARBON_DIOXIDE:");
  Serial.print(MQGetGasPercentage(MQRead(MQ135PIN) / Ro, GAS_CARBON_DIOXIDE)
              );
  Serial.print( "ppm" );
  Serial.print("    ");
  Serial.print("AMMONIUM:");
  Serial.print(MQGetGasPercentage(MQRead(MQ135PIN) / Ro, GAS_AMMONIUM) );
  Serial.print( "ppm" );
  Serial.print("\n");
  delay(200);
}

/***MQResistanceCalculation*****************************************
  Input:   raw_adc - raw value read from adc, which represents the
  voltage
  Output:  the calculated sensor resistance
  Remarks: The sensor and the load resistor forms a voltage divider.
  Given the voltage
  across the load resistor and its resistance, the resistance of the
  sensor
  could be derived.

*******************************************************************/
float MQResistanceCalculation(int raw_adc)
{
  return ( ((float)RL_VALUE_MQ5 * (1023 - raw_adc) / raw_adc));
  return ( ((float)RL_VALUE_MQ7 * (1023 - raw_adc) / raw_adc));
  return ( ((float)RL_VALUE_MQ8 * (1023 - raw_adc) / raw_adc));
  return ( ((float)RL_VALUE_MQ135 * (1023 - raw_adc) / raw_adc));
}

/*** MQCalibration*******************************************************
  Input:   mq_pin - analog channel
  Output:  Ro of the sensor
  Remarks: This function assumes that the sensor is in clean air. It use
  MQResistanceCalculation to calculates the sensor resistance in clean
  air
  and then divides it with RO_CLEAN_AIR_FACTOR. RO_CLEAN_AIR_FACTOR is
  about
  10, which differs slightly between different sensors.
****************************************************************/
float MQCalibration(int mq_pin)
{
  int i;
  float RS_AIR_val = 0, r0;

  for (i = 0; i < CALIBARAION_SAMPLE_TIMES; i++) {
    RS_AIR_val += MQResistanceCalculation(analogRead(mq_pin));
    delay(CALIBRATION_SAMPLE_INTERVAL);
  }
  RS_AIR_val = RS_AIR_val / CALIBARAION_SAMPLE_TIMES;
  r0 = RS_AIR_val / RO_CLEAN_AIR_FACTOR_MQ5;

  return r0;

  for (i = 0; i < CALIBARAION_SAMPLE_TIMES; i++) {
    RS_AIR_val += MQResistanceCalculation(analogRead(mq_pin));
    delay(CALIBRATION_SAMPLE_INTERVAL);
  }
  RS_AIR_val = RS_AIR_val / CALIBARAION_SAMPLE_TIMES;
  r0 = RS_AIR_val / RO_CLEAN_AIR_FACTOR_MQ7;

  return r0;

  for (i = 0; i < CALIBARAION_SAMPLE_TIMES; i++) {
    RS_AIR_val += MQResistanceCalculation(analogRead(mq_pin));
    delay(CALIBRATION_SAMPLE_INTERVAL);
  }
  RS_AIR_val = RS_AIR_val / CALIBARAION_SAMPLE_TIMES;
  r0 = RS_AIR_val / RO_CLEAN_AIR_FACTOR_MQ8;

  return r0;

  for (i = 0; i < CALIBARAION_SAMPLE_TIMES; i++) {
    RS_AIR_val += MQResistanceCalculation(analogRead(mq_pin));
    delay(CALIBRATION_SAMPLE_INTERVAL);
  }
  RS_AIR_val = RS_AIR_val / CALIBARAION_SAMPLE_TIMES;
  r0 = RS_AIR_val / RO_CLEAN_AIR_FACTOR_MQ135;

  return r0;
}
/*****************  MQRead *********************************
  Input:   mq_pin - analog channel
  Output:  Rs of the sensor
  Remarks: This function use MQResistanceCalculation to caculate the
  sensor resistenc (Rs).
  The Rs changes as the sensor is in the different consentration of the
  target
  gas. The sample times and the time interval between samples could be
  configured
  by changing the definition of the macros.
********************************************************/
float MQRead(int mq_pin)
{
  int i;
  float rs = 0;

  for (i = 0; i < READ_SAMPLE_TIMES; i++) {
    rs += MQResistanceCalculation(analogRead(mq_pin));
    delay(READ_SAMPLE_INTERVAL);
  }

  rs = rs / READ_SAMPLE_TIMES;

  return rs;
}

/***********************  MQGetGasPercentage ****************************
  Input:   rs_ro_ratio - Rs divided by Ro
  gas_id      - target gas type
  Output:  ppm of the target gas
  Remarks: This function uses different equations representing curves of
  each gas to
  calculate the ppm (parts per million) of the target gas.
******************************************************************/
int MQGetGasPercentage(float rs_ro_ratio, int gas_id)
{
  if ( accuracy == 0 ) {

  }
  if ( gas_id == GAS_LPG ) {
    return (pow(10, ((-2.513 * (log10(rs_ro_ratio))) + 1.878)));
  }
  else if ( gas_id == GAS_CARBON_MONOXIDE ) {
    return (pow(10, ((-1.525 * (log10(rs_ro_ratio))) + 1.994)));
  }
  else if ( gas_id == GAS_HYDROGEN ) {
    return (pow(10, ((-2.568 * (log10(rs_ro_ratio))) + 0.360)));
  }
  else if ( gas_id == GAS_METHANE ) {
    return (pow(10, ((-16.16 * (log10(rs_ro_ratio))) + 1.093)));
  }
  else if ( gas_id == GAS_CARBON_DIOXIDE ) {
    return (pow(10, ((-2.890 * (log10(rs_ro_ratio))) + 2.055)));
  }
  else if ( gas_id == GAS_AMMONIUM ) {
    return (pow(10, ((-2.469 * (log10(rs_ro_ratio))) + 2.005)));

  }
  else if ( accuracy == 1 ) {
  }
  else if ( gas_id == GAS_LPG ) {
    return (pow(10, ((-2.513 * (log10(rs_ro_ratio))) + 1.878)));
  }
  else if ( gas_id == GAS_CARBON_MONOXIDE ) {
    return (pow(10, ((-1.525 * (log10(rs_ro_ratio))) + 1.994)));
  }
  else if ( gas_id == GAS_HYDROGEN ) {
    return (pow(10, ((-2.568 * (log10(rs_ro_ratio))) + 0.360)));
  }
  else if ( gas_id == GAS_METHANE ) {
    return (pow(10, (-281.3 * pow((log10(rs_ro_ratio)), 3) - 12.26 *
                     pow((log10(rs_ro_ratio)), 2) - 7.925 * (log10(rs_ro_ratio)) + 1.668)));
  }
  else if ( gas_id == GAS_CARBON_DIOXIDE ) {
    return (pow(10, ((-2.890 * (log10(rs_ro_ratio))) + 2.055)));
  }
  else if ( gas_id == GAS_AMMONIUM ) {
    return (pow(10, ((-2.469 * (log10(rs_ro_ratio))) + 2.005)));
  }
}

Using your merged code, but commenting out the calls to all but one sensor (at a time), will each of them run correctly?

First of all you only need to include once. Including anything more than once is pointless and could be bad, if the header doesn't have include guards (yours do, but still it just makes the code harder to read).
Let's take a look at the MQResistanceCalculation function, well... It's simply broken.
float MQResistanceCalculation(int raw_adc)
{
  return ( ((float)RL_VALUE_MQ5 * (1023 - raw_adc) / raw_adc));
  return ( ((float)RL_VALUE_MQ7 * (1023 - raw_adc) / raw_adc));
  return ( ((float)RL_VALUE_MQ8 * (1023 - raw_adc) / raw_adc));
  return ( ((float)RL_VALUE_MQ135 * (1023 - raw_adc) / raw_adc));
}

I'm not sure what you expect to happen, but as soon as you reach a return statement that block of code stops and the result is returned, so basically that function executes the first return and then stops. You probably want to pass a sensor type and then use a switch to make it return for either the MQ5, MQ7, MQ8 or MQ135, because right now it only returns the MQ5 value.
Then let's take a look at the MQCalibration function. So same thing as above applies, as long as you reach a return the function stops. Your MQCalibration function currently only does:
float MQCalibration(int mq_pin)
{
  int i;
  float RS_AIR_val = 0, r0;

  for (i = 0; i < CALIBARAION_SAMPLE_TIMES; i++) {
    RS_AIR_val += MQResistanceCalculation(analogRead(mq_pin));
    delay(CALIBRATION_SAMPLE_INTERVAL);
  }
  RS_AIR_val = RS_AIR_val / CALIBARAION_SAMPLE_TIMES;
  r0 = RS_AIR_val / RO_CLEAN_AIR_FACTOR_MQ5;

  return r0;
}

And then the MQGetGasPercentage function can be re-written with switch statements to be way easier to read and understand. Oh and also that accuracy == 0 check is also pointless it has nothing in it.
From reading this I see you've just copied code you don't understand and hoped it'll work, but as expected it didn't. And well copying code without atleast having an idea about what it does is stupid. So just read it, understand it and write it again, but by yourself. Your code has many pointless variable declarations and it just isn't well "written"(or copy-pasted should I say).
Also I've never worked with that sensor myself, so I was looking at the code aspect mostly, just so you know.

I understand now and I will try to make a new code by myself, I had to copy paste it because of my lack of knowledge in Arduino and I didn't have much time to research, thanks for the help, I'll make sure to do it right next time.


text:
Changing how a longpress is executed
I have an RGB LED common Anode attached to my Uno and this code detects a long press to turn the LED on and off.  Short presses cycle through colors, then off.
The problem is that a longpress is 2+sec, but it doesn't register until I release the button.  How would I set this up to execute the code at 2sec regardless of whether the button is released?
It's probably not worth my time if it requres too much modification.  I have a working item, it's just not... ideal.
Xhunsigned long keyPrevMillis = 0;
const unsigned long keySampleIntervalMs = 25;

int redPin = 11;
int greenPin = 10;
int bluePin = 9;
int LEDcolor=0; // 0=White, 1=Red, 2=Green, 3-Blue, 4=Yellow, 5=Purple, 6=Pink, 7=Orange, 8=Off
int LEDstatus =0; //0=Off, 1=On
int changed =0; //has the LEDstatus just changed?
byte longKeyPressCountMax = 80;    // 80 * 25 = 2000 ms
byte longKeyPressCount = 0;

byte prevKeyState = HIGH;         // button is active low
const byte keyPin = 2;            // button is connected to pin 2 and GND

// called when button is kept pressed for less than 2 seconds
void shortKeyPress()
{
   Serial.println("short");
   if (LEDstatus==1)
   {
      LEDcolor = LEDcolor +1;
      if (LEDcolor==0) {analogWrite(redPin, 0);analogWrite(greenPin, 0);analogWrite(bluePin, 0);Serial.println("White");}
      if (LEDcolor==1) {analogWrite(redPin, 0);analogWrite(greenPin, 255);analogWrite(bluePin, 255);Serial.println("Red");}
      if (LEDcolor==2) {analogWrite(redPin, 255);analogWrite(greenPin, 0);analogWrite(bluePin, 255);Serial.println("Green");}
      if (LEDcolor==3) {analogWrite(redPin, 255);analogWrite(greenPin, 255);analogWrite(bluePin, 0);Serial.println("Blue");}
      if (LEDcolor==4) {analogWrite(redPin, 0);analogWrite(greenPin, 0);analogWrite(bluePin, 255);Serial.println("Yellow");}
      if (LEDcolor==5) {analogWrite(redPin, 175);analogWrite(greenPin, 255);analogWrite(bluePin, 175);Serial.println("Purple");}
      if (LEDcolor==6) {analogWrite(redPin, 0);analogWrite(greenPin, 255);analogWrite(bluePin, 155);Serial.println("Pink");}
      if (LEDcolor==7) {analogWrite(redPin, 5);analogWrite(greenPin, 215);analogWrite(bluePin, 255);Serial.println("Orange");}
      if (LEDcolor==8) {analogWrite(redPin, 255);analogWrite(greenPin, 255);analogWrite(bluePin, 255);Serial.println("Off");LEDstatus=0;}
   }
}

// called when button is kept pressed for more than 2 seconds
void longKeyPress()
{
   Serial.println("long");
   if (LEDstatus==0 && changed==0)
   {
      analogWrite(redPin, 0);
      analogWrite(greenPin, 0);
      analogWrite(bluePin, 0);
      LEDcolor=0;
      changed=1;
      LEDstatus=1;Serial.println("On");
   }
   if (LEDstatus==1 && changed==0)
   {
      analogWrite(redPin, 255);
      analogWrite(greenPin, 255);
      analogWrite(bluePin, 255);
      LEDcolor=0;
      changed=1;
      LEDstatus=0;Serial.println("Off");
   }
   changed=0;
}

// called when key goes from not pressed to pressed
void keyPress() {
   Serial.println("key press");
   longKeyPressCount = 0;
}

// called when key goes from pressed to not pressed
void keyRelease() {
   Serial.println("key release");

   if (longKeyPressCount >= longKeyPressCountMax) {
      longKeyPress();
   }
   else {
      shortKeyPress();
   }
}

void setup()
{
   Serial.begin(9600);
   pinMode(keyPin, INPUT);
   digitalWrite(keyPin, HIGH);
   pinMode(redPin, OUTPUT);
   pinMode(greenPin, OUTPUT);
   pinMode(bluePin, OUTPUT);
   analogWrite(redPin, 255);
   analogWrite(greenPin, 255);
   analogWrite(bluePin, 255);
}

void loop() {
// key management section
   if (millis() - keyPrevMillis >= keySampleIntervalMs) {
      keyPrevMillis = millis();

      byte currKeyState = digitalRead(keyPin);

      if ((prevKeyState == HIGH) && (currKeyState == LOW)) {
         keyPress();
      }
      else if ((prevKeyState == LOW) && (currKeyState == HIGH)) {
         keyRelease();
      }
      else if (currKeyState == LOW) {
         longKeyPressCount++;
      }

      prevKeyState = currKeyState;
   }
}

The button watcher will have to become aware of time, or be able to be alerted that the short-press time has been exceeded. How much trouble and whether it's worth it is up to your own cost (labor) vs. benefit preference, but it's probably a worthwhile learning exercise.

I've rewritten the code entirely. Not that yours was terrible, it was just easier for me to start from scratch. You are left with a very empty loop(), which I always prefer.
The code contains three 'colours' and an OFF state. You can add as many other colours as you wish: add an enumeration to _LED_STATE and then add a corresponding case(<NEW_COLOUR>) statement in LEDcontrol(). I haven't included any analogWrite() functions - or in fact any declarations for the LED pins at all - because I'm a little too lazy but it should be obvious where to put them within the case statement.
Note that in the final case() statement, the LED state is changed from green to off. This means that a short press will turn the LED off after it has cycled through all the other colours, but will stay off until a long press. If you only want long pressed to switch off/on, change line 103 to eLED_STATE = _LED_STATE_RED;, or whichever the first colour is.
#define btn 3   // button pin

#define SHORT_PRESS 100     // useful for debouncing, can be changed
#define LONG_PRESS  2000    // defines how long a 'long press' is
#define CYCLE       false
#define SHOW        true

//--// You can add new colours in this enum block
enum _LED_STATE
{
    _LED_STATE_OFF,
    _LED_STATE_RED,
    _LED_STATE_BLUE,
    _LED_STATE_GREEN
};

_LED_STATE eLED_STATE = _LED_STATE_OFF;

void setup()
{
    pinMode(btn, OUTPUT);
    LEDcontrol(SHOW);
}

void loop()
{

    if (digitalRead(btn))
        btnPressed();
}

void btnPressed()
{
    unsigned long tStart = millis();

    //--// Loop continuously while button is pressed
    while (digitalRead(btn))
    {
        //--// If LONG_PRESS is exceeded...
        if (millis() > tStart + LONG_PRESS)
        {
            //--// If LED is off, turn it on
            if (eLED_STATE == _LED_STATE_OFF)
                eLED_STATE = _LED_STATE_RED;        // Choose 'starting' colour
            //--// If LED is on, turn if off
            else
                eLED_STATE = _LED_STATE_OFF;
            //--// Update LED to display new eLED_STATE
            LEDcontrol(SHOW);
            //--// Now loop here until button is released
            while (digitalRead(btn));
        }
    }

    //--// If button is released in between the two press times
    if ((millis() > tStart + SHORT_PRESS) && (millis() < tStart + LONG_PRESS))
    {
        //--// Ignore if LED is off         ////// REMOVE ////////////////////
        if (eLED_STATE == _LED_STATE_OFF)   ////////// IF ////////////////////
            return;                         ///////////// NECESSARY //////////

        //--// Change the LED colour
        LEDcontrol(CYCLE);
        //--// Update LED to display new eLED_STATE
        LEDcontrol(SHOW);
    }

    //--// This helps to debounce; experiment with it
    delay(10);
}

void LEDcontrol(bool SHOW_OR_CYCLE)
{
    switch (eLED_STATE)
    {
        case(_LED_STATE_RED) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it red
                return;
            }
            eLED_STATE = _LED_STATE_GREEN;
            return;
        }
        case(_LED_STATE_GREEN) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it green
                return;
            }
            eLED_STATE = _LED_STATE_BLUE;
            return;
        }
        case(_LED_STATE_BLUE) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it blue
                return;
            }
            //--// What happens after last colour? Next colour or OFF?
            eLED_STATE = _LED_STATE_OFF;
            return;
        }
        case(_LED_STATE_OFF) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it black
                return;
            }
            eLED_STATE = _LED_STATE_RED;
            return;
        }
    }
}


text:
How can i do something like multi threathing in arduino?
I am checking for ways to implement multi threathing in Arduino, I have also tried using the library TimerOne but it doesn't seem to work, what I'm trying to make is an Arduino application then, every time a certain amount of time passes, it pops an item from the stack, and between these times, the application allows me to add items to the stack, both processes working in parallel of course.
The items popped and pushed are numbers.
I have already tried some other questions, but their solutions don't work, especially one that seems very useful, but for some reason doesn't work, I'm speaking about the one of the TimerOne library.
Any suggestion to fix the problem some other way would be cool.
Here is the code:
#include <TimerOne.h>
#include <QueueList.h>
#include <StackList.h>

const uint16_t  NOTE_B0     =   31;
const uint16_t  NOTE_C1     =   33;
const uint16_t  NOTE_CS1    =   35;
const uint16_t  NOTE_D1     =   37;
const uint16_t  NOTE_DS1    =   39;
const uint16_t  NOTE_E1     =   41;
const uint16_t  NOTE_F1     =   44;
const uint16_t  NOTE_FS1    =   46;
const uint16_t  NOTE_G1     =   49;
. . . ETC . . .
const uint16_t  NOTE_DS8    = 4978;

uint16_t Notas[] =
{
      NOTE_B0
    , NOTE_C1
    . . . ETC . . .
    , NOTE_C8
    , NOTE_CS8
    , NOTE_D8
    , NOTE_DS8
};

QueueList<int> KeyNotesNode = QueueList<int>();
StackList<int> StackNote = StackList<int>();

char receivedChar1 = '<';
char receivedChar2 = '<';

char receivedChar[] = {receivedChar1, receivedChar2};

int TempInt = 0;
bool newData = false;

bool itPopUp = false;

int modality = 0;

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

  if(modality == 0){
    Serial.println("Ingrese el tipo de funcionalidad deseada");
    Serial.println("1.- Constructor de canciones en tonos");
    Serial.println("2.- Juego de imposicion musical");
  }

  Timer1.initialize(150000);
  Timer1.attachInterrupt( setForPop );
}

void loop() {
  //Checa y controla la recepcion de los char a traves de la consola de arduino

  if (Serial.available())
  {
    receiveChar();
    showReceivedChar();
  }

//   . . .  Here is some code to process the reception of data from serialData  . . .

// From somewhere here start the loop

// . . . LOOPED . . .

    //Here is used the data
    if(modality == 1){
       //This option doesn't matter
    }
    else if(modality == 2){
      StackNote.push( (((int)(receivedChar[0]-'0'))*10)+((int)receivedChar[1]-'0') );
      Serial.println("Agregado receivedChar exitosamente a la Pila");
      Serial.print("Tamano Total Lista: ");
      Serial.println(StackNote.count());
      Serial.print("Dato:");
      Serial.println( (((int)(receivedChar[0]-'0'))*10)+((int)receivedChar[1]-'0') );
      Serial.print("Dato(get):");
      receivedChar[0] = '<';
      receivedChar[1] = '<';
    }
}

    //Run and show the data on the stack
     if(modality == 1)
     {
           //This option doesn't matter
      }
      else if(modality == 2)
      {

        if(itPopUp){   //With this variable i want to control when it is show, this code is inside loop()
          Serial.print("Reproducido con exito la nota: "); //se escribe 'éxito' pero la consola no acepta tildes, que se arrepienta :P
          TempInt = StackNote.pop();
          Serial.println(TempInt);
          tone(9,Notas[((int)TempInt)],500);
          delay(500);
        }
      }

  } //Here the loop() end

//This function i want to run it asyncronously
 void setForPop(){
    if(itPopUp){
      itPopUp = !itPopUp;
    }
    else{
      itPopUp = !itPopUp;
    }
 }

The standard answer, which works for most simple programs, is to get rid of delay(), as explained in the Blink Without Delay tutorial.

your 'setForPop' does exactly the same thing. Whatever the value of itPopUp, the result will be always the same. Also what is receiveChar() and showReceivedChar() function? Can you paste the full code?

You will not have full parallel execution in an Arduino (only one CPU).

You might do multi-threading by implementing a small OS (e.g. FreeRTOS)
Or write your own task scheduler.
Or even just do state machine looping forever checking if push or pop has to be executed.
Last and preferred solution: I would consider running the normal Push task always and execute the Pop task (function in fact) using interrupts.

I haven't used the TimerOne library, but I have had good success with the SimpleTimer library.   http://playground.arduino.cc/Code/SimpleTimer
It's served me well in handling building small iot apps.  As the arduino has to both maintain connection info as well as doing it's processing data, this library seems to handle keeping both happy pretty well.
Here's an example in use: https://github.com/adbacker/bcc2016/blob/master/bcc2016.blynk.kitchensink/bcc2016.blynk.kitchensink.ino
The money bit is at the end => the setup and loop functions. (note: yes, I know. the comment says every second, but it's actually every 2 seconds...)
void setup()
{
  Serial.begin(115200); // See the connection status in Serial Monitor
  pinMode(WATER_SENSOR_PIN, INPUT); //water sensor pin, init as input
  Blynk.begin(auth, WIFI_SSID, WIFI_PW);
  while (Blynk.connect() == false) {
    Serial.println("trying to connect ....");
  }

dht.begin();

// Setup a function to be called every second
timer.setInterval(2000L, sendTemp);
timer.setInterval(2000L, updateLcd);
timer.setInterval(2000L, checkForWater);
}

void loop()
{
  Blynk.run(); // Initiates Blynk
  timer.run(); // Initiates SimpleTimer
}