text:
Send serial commands through IDE while RX pin is in use
This is really a two part question. I have an ESP8266 hooked up to USB. I have connected my LED strip (WS2812B LEDs) to the RX port, so I can control them individually and so on. I realised WiFi is a bit slow and will eventually crash the ESP8266 if I send enough requests, which is why I want to give serial a go.

If I open up the serial monitor, how do I send something to it, such as a color or 100 colors in one command? I'd assume Serial.read() inside a Serial.write() would display whatever I type in, but it doesn't do that. I can Serial.write() inside a loop, and it will display that.
Is something like this even possible? I'm looking for a way to send a lot of information (could be 100 colors (1 per LED)) as fast as possible. Speed is the key here.

Software serial is an option as well, as long as it's faster than WiFi.

what are the LEDs saying that you need to listen to them? ;) do you need RX?

Are you suing the NodeMCU eLua-based firmware or the ESP8266 Arduino Core?

@EdgarBonet Arduino :)

Regarding “I have connected my LED strip (WS2812B LEDs) to the RX port”:  If you connect an LED strip to the RX pin, there's a good chance you won't be able to read serial data reliably on that pin, and may have trouble loading new sketches.  It makes sense to connect the LEDs to some pin other than RX.
Regarding “If I open up the serial monitor, how do I send something to it”:  Ordinarily, one uses the serial monitor to receive data from an attached MCU or to send data to the MCU. (An MCU is a microcontroller – eg an Arduino or ESP8266.)  In the sketch on the MCU, use Serial.write() to send binary data to the monitor, and Serial.print() to send text and formatted numbers to the monitor.
If you want to send serial data rapidly from your host computer to the MCU, write a C or Python (etc) program that opens a serial port, marshals the data, and sends it.  In the  sketch on the MCU, use Serial.available to test if characters are available to read, and Serial.read to read a character.  For faster transmission, you can send binary data instead of ASCII, but would need to read up on that before attempting it.
For fast data transmission, aim for either high data rates or strong data compression.  For example, you might make up a protocol that only sends colors for pixels that are going to change; or might have high-level commands that tell the MCU how to generate a set of data, via color end points, step rates, and numbers of steps.
In general, wifi data rates are somewhat higher than serial data rates.  If that is not what you are experiencing, perhaps review the article Found a way to upload data VERY fast by wifi from github.com/esp8266.

Edit 1:
Regarding “Nothing is displayed in the serial monitor” [from code like if (Serial.available()) { Serial.write(Serial.read()); }]:  I'm assuming that the sketch in use has a setup() routine containing a Serial.begin(somedatarate) statement, with the same data rate selected in the serial monitor as in the Serial.begin() statement.   I'm also assuming the sketch has a loop() routine containing the if (Serial.available()) { Serial.write(Serial.read()); } code.
I'm also assuming the sketch was properly downloaded, and then the serial monitor was opened, using the USB-serial port the ESP8266 is attached to, and then you typed some text into the text entry box of the serial monitor and pressed or clicked Enter to send the text to the ESP8266, with a proper setting for the end-of-line character.
If all those assumptions are correct, but nothing shows up in reply to the text you send, then it seems likely some hardware or software issue is occurring.  For example, when the Serial data structure is set up (when the sketch begins running) it might be selecting an incorrect Rx pin.  Or something may be loading down the Rx pin.  To find out if either of those is the case, use an oscilloscope (if you have one) to look at what's arriving at different ESP8266 pins when you send text from the  serial monitor.  If no scope, connect a 5K-10KΩ resistor to an LED and use that as a logic probe.  One end of the resistor connects to a probe; the other end goes to the LED anode; and the LED cathode is grounded.  Test if that's working by touching the probe to +3.3V.  When the probe appears to be working ok, use it to check for brief flashes of data at different Rx pins on the ESP8266 when you send data from the serial monitor.  If no data gets to the ESP8266, it can't echo it.  (Note, I'm not sure how your NodeMCU ESP8266 handles serial-via-USB data; my notion that serial data should be visible on some Rx pin might be wrong.)
If it appears data is getting to some pin but isn't showing up as available, you might try opening software serial on that pin.  Some examples appear in code in a serial monitor note at github.com/esp8266.  I don't know enough about NodeMCU / ESP8266 to say what to do if probing and software serial don't help.

Thanks a lot for the reply! I am using NeoPixelBus which automatically sends the data to the LED strip through the RX pin (because I use NeoEsp8266Dma800KbpsMethod and couldn't get any other to work). In my void loop(void){} function, I can write if (Serial.available()) { Serial.write(Serial.read()); } right? If I then input something into the Arduino IDE serial monitor (like 0xff0000) it should write that in the monitor right after, right? Because that doesn't seem to work.

“Doesn't seem to work”  is what symptoms?  No LEDs lighting up?  No serial monitor output at all?  Wrong monitor output? If the latter also try Serial.print(Serial.read());.  Note, I'm assuming RX is pin D3.  You might put LED strips on several pins at once, eg D2 as well as D3, while trying to find a Neo Esp method that works.  Perhaps detach LED strips while trying out Serial comms

"Doesn't seem to work" meaning nothing it displayed in the serial monitor. The LED strip is hooked up to GPIO03/RXD0. Check out this image (bottom right)

I added some paragraphs in Edit 1 that might help, but I don't really know what the problem is due to.

Thanks a lot for the reply! As far as I remember, I had to remove all the serial commands from my Arduino code before I could get the LED strip to work (in the first place). It's really bugging me why it won't work properly. Do you happen to have any kind of guide I can follow (that you know works), which allows me to enter something like 0xff0000 into the serial monitor console and read it straight back in the console? Not even a guide, just some code that works on the ESP8266.

I have some ESP8266's which I haven't hooked up yet; can't vouch for any code.  It sounds like your setup has a LED vs. serial-data conflict.  If you have a USB serial adapter, or another Arduino, you could wire up to use an alternate serial port on the ESP8266.    Or perhaps follow up on the Found a way to upload data VERY fast by wifi article mentioned before.


text:
Sparkfun OpenLog both lights flashing
I'm building a simple RS232 data logger with the Sparkfun OpenLog and a SEEED RS232-TTL adaptor. I'm powering it with a 9 volt battery and a 7805 voltage regulator.
It's dead simple. I built it on a breadboard first and determined that TX-TX and RX-RX connections are called for. I logged several files on the breadboard then soldered it all up. Now it's not working, sigh.
When I power it up  both lights will flash rapidly for about a second and then it settles down to a steady on-off with both lights.
If I delete the config file a new one is created, which shows that it recognizes the card at least.
I've triple checked my wiring and confirmed I have no shorts, and that the voltage is good.
I'm attaching a photo as built. Hopefully it's obvious what's what. The purple trace is ground.

It can be so many things. Be careful when one wire is on the top of another wire, when you solder them the plastic could melt and they could connect. A 7805 without capacitors is an oscillator. You need 100nF at the input and output at least. The Sparkfun OpenLog is a ATmega328P running at 3.3V at 16MHz. That is not okay. It will work in most cases, but it is not okay according to the datasheet. And last but not least: something could be broken.

Sorry Jot, I don't understand, what part is "not ok"? I've added caps to the 7805 and quaduple checked there are no shorts. Still no improvement.

The problem with the circuit was a bad rs232-ttl converter. Not sure how that messed up the openlog, but replacing it fixed the problem.
In the photo above, D1 on the converter is an led which should be normally on.

If the OpenLog's RX pin is held low for too long at startup, it'll reset to 9600 baud to attempt to recover. A bad rs232-ttl converter could cause this, if the RX pin was being held low. If you need the OpenLog to ignore this, see the ignoreRX parameter in config.txt and the hookup guide.

source: Stack Exchange

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

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

sort: votes


text:
How can I split a string into three parts after space and turn the values to doubles?
I am currently gathering info from a BLE device. I made a thread earlier where I successfully split a string consisting of 5 letters to their unique chars.
However from this BLE device i will also send some different information from time to time where I send 3 different values with a space after each one. So for example looking like this:
-0.1 0.51 0.07
So what I want to do now is to store this three numbers in different doubles and what I have done so far is this:
First i store the recieved message:
String recievedMessage;

recievedMessage += (char)BTLEserial.read();

Now I have to determine if the value sent is the 5 letters or if it is the numbers with a space between each value.
if (recievedMessage.length() > 5) //so if the recievedmessage is more than 5 words then it is the 3 values that is being sent.
{
char * charTheMessage = recievedMessage.c_str();
char *str;
str = strtok(charTheMessage, " ");

double one = str[0];
double two = str[1];
double three = str[2];

Serial.println (one);
Serial.println (two);
Serial.println (three);

}

if (recievedMessage.length() == 5)
{
 //http://arduino.stackexchange.com/questions/36227/how-can-i-split-a-string-into-multiple-parts/36237?noredirect=1#comment72313_36237
//Here I split the letters into 5 different values if the value sent is 5.
}

But this values do not come out right when I print them in the serial monitor. I have also read that strtok is not reliable when data is sent fast so is strtok the right way to go you think?

You're almost there. Strtok returns the first token in the string only. You then have to convert that to a double yourself. You then call strtok again with NULL as the source string to get the next token. And so on.
I have written a good strtok example on here already. Look around, you may find it.

I am out and about and using my phone right now so can't do a complex answer.

Here is one example: http://arduino.stackexchange.com/questions/31126/strtok-problem-while-parsing-string

Trying it right now! :) Will strncmp also work with spaces?

strncmp sees space as just another character

ok, let me try to see if i can work it out!

Ok. I get some more accurate results now (progress!) but in the while loop I only reach the "FIRST" if statement. Check post for updated code:

Nvm I fixed it! I just used the if-statement and removed the else if functions and inside the if statement i just added a simple int that increases in order to separate the three results

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


text:
Complex Arduino programs
Im working on a RGB LED matrix project (10 x 10 Neopixels) and I'm using classes to handle the different hardware components. Whats the best way to deal with multiple files in the project eg, I have a class which holds the various display functions such as writing text and drawing circles, but every time I change something it takes ages to compile (Greater than 30 seconds) is there a way to have multiple files without using classes?
Any help would be greatly appreciated.
Cheers

In my experience simply having multiple files should not inflate your compile time by that much. What Arduino are you using? i would try troubleshooting (i.e. what happens when there is 1 file with all your functionality? what happens when there are multiple files with less functionality?)

I'm using sublime with STINO as an instead of the IDE to program a nano v3

You can have multiple files without implementing any classes. just make sure to include the arduino.h header in them if you want to use any arduino API (like "digitalWrite", pinMode, etc..)

Look at the compilation messages. Does it recompile everything when you change a single file? If so, you should probably file an issue.

What version of the IDE and what host (Windows, Linux, etc)? If you are running on Windows you need to shut off the virus scan of generated files.

I'm using windows 10 with the latest version of Arduino. I have added the temp folders in the exception list for avast but its still really slow, I think it could be something to do with the STINO build process

I like to separate logical chunks of a complex program into libraries. The IDE I use (UECIDE) then caches those libraries and it compiles very fast.

I noticed that it is very hard to use classes with the default IDE.
Each file will be in a different tab, but normally each class has a header (.h) and implementation (.c) file, so 2 extra tabs per class.
If you have just 3-4 classes you can use the default IDE.
However, if you want to use more, you have to use e.g. Eclipse or Visual Studio, whatever IDE you like best.
Search for Eclipse/Arduino, I think there are multiple options.
Myself I use visualmicro ... it is free except you cannot use the debugger option.
I used several classes in my sketch and don't think the compile time was 30 seconds; it might be depending also on the amount of include files.
Also a complex program is not necessarily a program with many classes. I would say, that if you put too much functionality in one class (or one single sketch), you get a complex program.

I'm currently using STINO but ill have a look in to other IDE's. Cheers

Yes you can have multiple files without classes.
Functions don't have to go in classes, see loop and setup for an example. All you have to do is declare the function in a header file and then implement it in a body.
so:
// File Bob.h
#ifndef __BOB_H__
#define __BOB_H__

int SomeFunction(const char val);

#endif // __BOB_H__

// File Bob.cpp
#include Bob.h
int SomeFunction(const char val)
{
   return (int)val;
}

// File SketchName.ino
#include "Bob.h"

setup()
{
  ......... Stuff

Now in theory the compiler will only rebuild Bob.cpp when you change code in it.  In practice you will change code in it and the compiler won't rebuild it and you'll tare your hair out until you remember that if all else fails, rebuild all!
In SketchName.ino some people will say you should always put your includes first, some will say last and some will say it makes no difference.  In my experience its easier to fix duplicate definitions by changing your code so I always put 'my' includes last, because that way the compiler will report the errors against my code.
BTW 30 seconds is not a long build time.  I've worked on projects taking 12+ hours, and missing a semi colon on those projects does not make you popular :)

Ahh, this sounds about right. I am using STINO with the full compile option switched on because I'm changing the cpp files quite often. I'll have a go at your suggestion when i get home tonight, cheers.

Sounds recognizable, build times of multiple hours. However, I hope you could check semicolons without having too do a full build. In my work full builds are scheduled at night, so waiting times can be some hours + 8+ hours depending when initiating a full build.

Whats your methodology when working on huge programs, do you have some software for debugging or do you rely on the compiler throwing highlighting the errors?

It depends what the platform is.  For Arduino I extract all the non-platform specific code out and get it compiling in Visual Studio (Community) and then write a set of tests to make sure every function and class does what I expect.  I've also written some mock modules that offer some Arduino functionality (pinMode, digitalWrite, etc) so I can tests lower level code on the PC.  Then switch to the Arduino as late as possible.  The only way (AFAIK) to debug on an Arduino is Serial.Print or similar.


text:
Random data sending integers between two Arduinos
I'm trying to do something seemingly simple, but I'm running into difficulties. I want to send about 5 separate integers between two Arduinos over software serial. I have written the following, but I rarely get the two numbers on the receiving end - they're usually garbled or in the wrong order. I'm sure that I'm missing something obvious, but I can't work it out no matter how hard I try. Any help would be greatly appreciated.
Sender:
#include <SoftwareSerial.h>

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

int val, val2;

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

void loop()
{
  val = 123;
  val2 = 456;
  if(mySerial.read()=='#')
  {
    mySerial.write(highByte(val));
    mySerial.write(lowByte(val));
    delay(3);
  }
  if(mySerial.read() == '~')
  {
    mySerial.write(highByte(val2));
    mySerial.write(lowByte(val2));
    delay(3);
  }
}

Receiver:
#include <SoftwareSerial.h>

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

byte val;
byte low, high;

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

void loop()
{
  mySerial.write('#');
  byte h = mySerial.read();
  byte l = mySerial.read();
  int y = word(h, l);
  delay(2);
  mySerial.write('~');
  byte h2 = mySerial.read();
  byte l2 = mySerial.read();
  int z = word(h2, l2);

  Serial.println(y);
  Serial.println(z);
  Serial.println();
}

Have you tried doing a loopback test on both ends. That is, disconnect the serial link between the Arduinos and test them one at a time: Connect the Tx to Rx, send some characters and make sure you receive the characters you sent.

On your system have you connected the Tx line of one to the Rx line of the other. Ie crossed over the cables?

I have had a brief look at your code and you need to add a delay to the Receiver software immediately after you send the '#' and the '~' characters. The delay is needed so the microcontroller has enough time to send the character out of the serial port, have it processed by the other side and then the new data sent back.

Thanks sa_leinad. Those extra delays seem to have done the trick and everything is working as it should so far.

You need to add a delay to the Receiver software immediately after you send the # and the ~ characters.
void loop()
{
  mySerial.write('#');
  delay(8);    // <<<<<<<< Line added
  byte h = mySerial.read();
  byte l = mySerial.read();
  int y = word(h, l);
  delay(2);
  mySerial.write('~');
  delay(8);    // <<<<<<<< Line added
  byte h2 = mySerial.read();
  byte l2 = mySerial.read();
  int z = word(h2, l2);

  Serial.println(y);
  Serial.println(z);
  Serial.println();
}

The delay is needed so the microcontroller has enough time to send the character out of the serial port, have it processed by the other side and then the new data sent back.
Using 9600 baud, the time for each bit is around 104 microseconds. So a byte of data sent will take about 1.04 milliseconds. One byte sent + processing time + 2 bytes back is about 4 milliseconds. Adding a bit of margin, 8 ms delay would be a good value to use.
Using if (mySerial.Available() > 0) will not work on its own unfortunately, as Matt's answer suggests. What would happen is that you send the first # and then immediately it would check for any data recieved. From the calculation above we know it would take about 4 ms to get data back. So it just skips the if statement and goes onto the 2ms delay and then sending the ~. It then checks if serial is available. By this time the first response 'may' be back, so if it is, it then saves the data into h1 and l1. It then finishes the serial prints and loops back to the beginning. In this time the second response has come back, so after it sends # for the second time, the response to the ~ gets saved into h and l. This will continue forever.

Thanks. I was trying it with smaller delays (about 3ms), which didn't work. I just changed it to 8ms as suggested and it worked perfectly. I've managed to bring that down to 5ms, which seems to be the minimum before it fails.

You are being too impatient.
The receiver needs to wait until there is some data available.  if (mySerial.Available() > 0).  So before every read add that line and it should work.

Thanks @Matt. That seems to have cut down on the random numbers somewhat, but I still don't get a reliable stream of data. Often the two values are swapped, for example. Any other ideas?

I can't see a reason why the bytes would be swapped.  Try slowing it down make the delay between characters 500ms and see if that helps.  An alternative would be to send a byte array.


text:
Converting a char* with numbers to a double is giving me 0.0 in return
I recently made a thread where I read BLE data that has three different numbers/values. The data changes but it typically looks something like this:
0,5 -0,1 0
I successfully store the three numbers in a unique char* but when I try to convert the char* to a double I get the value 0.0 in return.
This is my code:
        while (tok)
        {
            if (currentRow == 0)
            {
              currentRow = currentRow +1;
              double a = atof(tok);
              Serial.println (a);
            }

            else if (currentRow == 1)
            {
              currentRow = currentRow+1;
              double b = strtod(tok, NULL);
              Serial.println (b);
            }

            else {
              currentRow = 0;
              double c = atof (tok);
              Serial.println (c);
            }

            tok = strtok(NULL, " ");
        }

Comments are not for extended discussion; this conversation has been moved to chat. Comments are for clarifying the question - not answering it.

The value that was being sent used a comma "," instead of a dot "." that was needed in order to convert the number.


text:
Arduino does not make any sound when connected to laptop?
When I connect my Arduino through USB to my laptop, it does not make any sound like something is connected but green light is on. And port option in the Arduino IDE remains grayed out. I might have burned my Arduino, maybe? Please help.

Can you try 1) a different cable, 2) connecting to a different computer, or 3) a different Arduino? Has anything happened to the Arduino to make you suspect any damage? It does sound like a problem with the communication processor on the Arduino board, but best to be sure.

An Arduino never makes a sound when connected.  Any such sound would be a function of the host operating system, which you have neglected to even mention in your question.

Is this a real Arduino, or a cheap Chinese CH340G based BoS?

The Arduino will not make a sound, but probably you refer to the sound Windows makes when a USB device is connected?
Try (except for the tips already given by JRobert)

different USB port
reinstall Arduino IDE
disable/enable or reinstall driver in Control panel/hardware/system/USB devices

There are a number of possible scenarios as to what is wrong:

The USB cable is a power only cable and has no data lines. However, this is unlikely because, whilst power-only USB cables are common with mobile phones (i.e. USB to Micro USB), a full on USB-A to USB-B cable, which is what the Uno uses, normally do not come in a power-only configuration.
The port is damaged on the laptop. This is unlikely, but it worth checking by connecting a keyboard or mouse to the same port, to see if data is transferred
You have no driver installed. This is the most likely scenario. Normally the Arduino will trigger a driver to be automatically installed. However, in the case of the cheap Chinese clones, which use the CH340G chip, then the CH340 driver will need to be installed, if you are using Windows. Check the Device Manager in Windows to see if you Uno is recognised when connected, or whether is is shown as an "Unknown Device". A quick google should provide you with the correct driver for the CH340G. Please note that, if you are using Linux, then no driver is required, see Majenko's answer to Safe place to download CH340G drivers from.


text:
Serial data is not sent on interrupt
I have a short program which should receive data, use this data to turn on/off an LED, and send data when a button is pressed. It is deployed on a Digispark board. The button is connected to INT0 port (PB2). The interrupt works, but data is not send. Receiving data works fine.
What am I missing here?
#include <SoftSerial.h>

#define RxD 1
#define TxD 0
#define out 3
#define btn 2
#define testled 4

SoftSerial blueToothSerial(RxD, TxD); //RX, TX
volatile int buttonState = 0;

void setup() {
  pinMode(out, OUTPUT);
  pinMode(btn, INPUT);
  pinMode(testled, OUTPUT);
  setupBlueToothConnection();
  digitalWrite(out, HIGH);
  digitalWrite(testled, HIGH);
  attachInterrupt(0, intrpt, CHANGE);
}

void loop() {
  char newVal;
  if(blueToothSerial.available()){
    newVal = blueToothSerial.read();
    if (newVal == '1') {
      digitalWrite(out, HIGH);
    } else {
      digitalWrite(out, LOW);
    }
  }
}

void intrpt() {
  buttonState = digitalRead(btn);
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(testled, HIGH);
  } else {
    // turn LED off:
    digitalWrite(testled, LOW);
    blueToothSerial.println("0");
  }
}

void setupBlueToothConnection() {
  blueToothSerial.begin(9600);
  blueToothSerial.print("\r\n+STWMOD=0\r\n");
  blueToothSerial.print("\r\n+STNA=HC-05\r\n");
  blueToothSerial.print("\r\n+STOAUT=1\r\n");
  blueToothSerial.print("\r\n+STAUTO=0\r\n");
  delay(2000);
  blueToothSerial.print("bluetooth connected!\n");
  delay(2000);
  blueToothSerial.flush();
}

EDIT
Serial data is sent fine. The above code works. On Windows I can see the data are coming, but not on OS X.

it appears your interrupt would trigger itself, it that intended?

Which board are you using here?

@Majenko Digispark with attiny85 http://i.imgur.com/LT4szAd.png

@Dandavis it triggers itself because of lack of debouncing, but shouldn't it send data even if it's unintentionally triggered?

no, i mean you println() on the TX pin, which changes its hi/low state, triggering the interrupt. TX==0

@dandavis, ohh I see... I thought 0 represents INT0... Now I've tried with attachInterrupt(digitalPinToInterrupt(btn), intrpt, CHANGE) but it cannot compile because digitalPinToInterrupt is not declared in the scope.

hmmm. https://forum.arduino.cc/index.php?topic=370167.0 ?

@dandavis seems 0 is INT0, which is on PB2 - https://digistump.com/board/index.php/topic,1060.msg12633.html#msg12633

Why would you use software serial on the hardware serial pins?  If you're going to use those pins, then just use Serial.  It works a lot better than any flavor of soft serial.

If you are handling interrupts then you need to keep the code as quick and simple as possible.  I suspect that in this case calling blueToothSerial.println is what's causing the problem. It may well be calling an operation that an ISR can't call and so it fails and your code doesn't write the data you expect it to.
All I ever do in ISRs is set flags and then get the 'normal' code to handle changes to the flags. Personally I wouldn't do the digitalWrites within the ISR. Have two volatile variables, one for the pin state and one when sending a message is required and handle those in your loop().


text:
Best Bluetooth module for the Lilypad?
So I'm trying to work on a project and need to include bluetooth. The latest problem I have is I'm using a Lilypad Arduino and need to keep the project in the same round area. I was looking at this: https://www.sparkfun.com/products/12580 however I'm not sure how I would make it smaller? Does it have to clip on or can I simply solder it in a way that it's resting directly above/below the Lilypad?

you need to electorally connect the pins, how that's arranged is up to you.

@dandavis Thanks so basically if I simply just solder it with wires or something and hold it in a casing it'll be fine?

yes, provided static/water/smooth protection...

@dandavis Well it's not gonna be exposed to any water or such. Just a very basic case to attach to a person. Thank you though :)


text:
What does this notation stands for? Wire.read() <<8 | Wire.read()
I'm using the Arduino's site test code for getting raw values from a MPU-6050 accelerometer + gyro. In the loop, there are this lines for getting the next data from its registers:
Wire.requestFrom(MPU_addr, 14, true);  // request a total of 14 registers

AcX = Wire.read()<<8 | Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read()<<8 | Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read()<<8 | Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp = Wire.read()<<8 | Wire.read();  // 0x41 (TEMP_OUT_H)   & 0x42 (TEMP_OUT_L)

GyX = Wire.read()<<8 | Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY = Wire.read()<<8 | Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ = Wire.read()<<8 | Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

Hex numbers indicates, of course, the address of each register. However, I can't get how, if the first instruction only requests from the MPU_addr (constant), it changes to the consecutive registers. Is it that <<8| makes something like a sum or a logic OR to switch the register to read?
Regards!

Left shift 8 bits, then bitwise OR. Turns two 8-bit values into one 16-bit value.

Just trying to find the duplicate I know is there (cus I answered it). Closest I can find right now is: http://arduino.stackexchange.com/questions/19243/and-syntax-in-arduino/19244

One important thing to note though is that the use of Wire.read() inside the shifting and ORing like that is not good. There is no guarantee that the Wire.read() functions will be called in the right order. You should read into variables first then work with those variables. http://en.cppreference.com/w/cpp/language/eval_order

I see, it's a point I'll have to considerate with my own design. Though, actually, I prefer to work with variables instead of functions. Thanks for the advice!

@Majenko, are you sure ? I tried to read that page about the the order of evaluation, but it is very hard to understand for me. Since it is the same function called twice and it is I/O function, the compiler should understand that there is a order. The origin of the code is here: http://playground.arduino.cc/Main/MPU-6050#short

In practice it is usually ok, but there is no guarantees. And what works in one version of the compiler may stop in another. Also Arduino playground isn't the most reliable of sources for good quality code.

Just adding a couple of points to Michel Keijzers's answer.
The expression Wire.read() << 8 takes the value returned by
Wire.read(), which is an int, and shifts it 8 bits to the left,
which is equivalent to multiplying by 256. If you are using a 32-bit
microcontroller (e.g. an Arduino Due), this is safe. However, most
Arduinos are based on an 8-bit AVR chip. On them, an int is 16-bits
and can only hold values up to 32767. If the initial value is larger
than 127, then the bit shift causes a signed integer overflow, which in
C and C++ is undefined behavior (read: “illegal operation”). It is
likely that everything runs fine and you get the expected result, but
it is unwise to ever rely on undefined behavior in C or C++.
The proper way to do the shift is to cast the initial value to an
unsigned data type, which is always safe v.s. overflows, and then do the
shift, like in
((uint16_t) Wire.read()) << 8

You may omit the outer parentheses if you know your operator priorities.
The second point is about the already mentioned fact that the order of
the reads is not specified. The simplest fix is to do one read per
statement, as in:
AcX = (uint16_t) Wire.read() << 8;  // first read MSB
AcX |= Wire.read();                 // then LSB

It is worth noting that the first statement has an implicit cast from
uint16_t (the result of the shift) to int16_t (the type of AcX).
This can also overflow if the shifted value is larger than 32767.
However, an overflow happening during a conversion in not undefined,
but rather implementation defined behavior. This means that the
authors of the compiler must decide and document what happens. Arduino
code is usually compiled by gcc, and the gcc docs document this
behavior as

• The result of, or the signal raised by, converting an integer to a
  signed integer type when the value cannot be represented in an object
  of that type (C90 6.2.1.2, C99 and C11 6.3.1.3).
For conversion to a type of width N, the value is reduced modulo 2^N
  to be within range of the type; no signal is raised.

This is exactly what we want here, and since it is the most efficient
choice on a two’s complement architecture, it seems unlikely that
another compiler would make a different choice.

Such a great explanation!

1 << 3 means the value 1 shifted 3 times to the left. So 1 in binary is 0000001, shifted left 3 places is 00001000. And 0001101 << 3 will be 1101000.
The | command is a logic or (where bits will be 1 if one of the bits is 1, e.g. 001100 | 001001 = 001101.
Probably every Wire.read() gives the next byte.
For the first line: Acx = Wire.read() << 8 | wire.read() means one (mostly the first byte) is read, it is shifted to the left one byte and the other (mostly next byte) read is placed in the right. So it results in the first two read bytes to be positioned in AcX. It is semantically the same as Wire.read() * 256 + Wire.read(), but normally a bit shift is easier for a computer, same as | and the + operator.

I got it, it seems as you said that it composes a word with those two bytes,  because item's datasheet indicates that in each pair, one register has the high bits and the other one the low bits. Thank you.

You are welcome, and yes, the high 8 bits go into the first part of the pair, and the next (low) 8 bits go in the second part.

“For the first line: Acx = Wire.read() << 8 | wire.read() means the first byte is read, it is shifted to the left one byte and the next byte read is placed in the right” is incorrect.  It should instead say, “For the first line: Acx = wire.read() << 8 | wire.read() means that two bytes are read, one of them is used as MSB, and the other as LSB”.  That is, according to the C standard N1570 §6.5.2, without parenthesization it is undefined which wire.read() is first and which is second.  Of course it often is the case they are used in the order you mentioned, but it's undefined here.

@jwpat7 yes you are right ... I will update the answer


text:
Run motor for a set amount of depending of Pressure Sensor
I'm a noob when it comes to time-based coding.
I have a pressure sensor which shows me readings for when someone is sitting on a chair.
I want to turn a motor for 2 seconds when the pressure sensor says occupied
I want to turn the motor the other way for 2 seconds when the pressure sensor says empty.
Also after the motor has turned for 2 seconds, I don't want it to turn the motor at all until the reading of the pressure has changed to the other reading.
Here is my code.
#include <AFMotor.h>
AF_DCMotor motor(1,MOTOR12_64KHZ);
AF_DCMotor motor2(2,MOTOR12_64KHZ);
int fsrPin = 0;     //FSR and 10K resistor are connected to pin 0
int fsrReading;     //the analog reading from the resistor divider

bool WheelLock = true;  //controls whether the wheelchair is locked or not
long startTime = millis();
long stopTime = startTime;

void setup(void){
  Serial.begin(9600);
  motor.setSpeed(255);
  startTime = 0;
  stopTime = 5000;
}

void loop(){
  while(startTime < stopTime){
    if(onChair() == false){
      motor.run(BACKWARD);
      startTime = millis();
    }
    else{
      motor.run(FORWARD);
      startTime = millis();
    }
  }
  motor.run(RELEASE);
  Serial.println("RELEASED");
  startTime = 0;
  Serial.println(startTime);
}

bool onChair(){
  fsrReading = analogRead(fsrPin);

  if(fsrReading > 800){
    Serial.println("Wheelchair is occupied");
    WheelLock = false;
  }

  else{
    Serial.println("Wheelchair is empty");
    WheelLock = true;
  }
  delay(200);
  return WheelLock;
}

I think you want something like this:
int motorRunSecs = 2
bool chairLastState = false;
bool chairCurrState = false;
int motorDirection = FORWARD;

void loop() {
    chairCurrState = onChair();

    // if the chair occupied state has changed, then do something
    if (chairCurrState != chairOccupied) {

        // set the motor Direction based on the state of the chair
        motorDirection = ((chairCurrState) ? FORWARDS : BACKWARDS);

        // run motor for X secs
        motor.run(motorDirection);
        delay(motorRunSecs * 1000);
        motor.run(RELEASE);

        // now update the last chair state
        chairLastState = chairCurrState;
    }
}

You really want to look at the finite state machine to model your problem.
With this, you are looking at states and the transition between states.
In your problem, for example, you want to turn on a motor for a certain length of time
after the chair state changes from empty to occupied. However, in your code you are not retaining
the previous state (empty or occupied) so you cannot act when there is a state change fom empty to occupied.
Here is some rough C++ code to show you how this could work in paractice.
// states:
// ChairOccupancyState: occupied; empty
// MotorState: on; off

// pseudo code

loop() {
   if ( ChairOccupancyState == empty && onChair == true ) {
      // we have a transition from empty to occupied
      // switch motor on direction 1
      motorState = on ;
      // record time
      motor_on_at_ms  = millis() ;
      ChairOccupancyState = occupied ;
   }

   if ( ChairOccupancyState == occupiedy && onChair == false ) {
      // we have a transition from occupied to empty
      // switch motor on direction 2
      motorState = on ;
      // record time
      motor_on_at_ms  = millis()
      ChairOccupancyState = empty ;
   }

   If (motorState == on && millis() - motor_on_at_ms > 2000 ) {
      motorState == off ;
      // switch motor off
   }

}

Fairly easy.
You have to determine if the pressure has changed from its previous reading.
If it has, you can start to turn the motor for two seconds.
Once the time is up, turn the motor off.
Once you put your code in that framework, it would be much easier to code top down.


text:
Turn on one by one the LEDs of a Neopixel rgb LEDs strip for each detection at the same distance from an Ultrasonic Distance Sensor (HC-SR04)
For this project I seek to create a counter of water glasses we drank throughout the day.
I use for this an Arduino UNO card, a Piezo buzzer and a Neopixel rgb LEDs strip (5 LEDs for this test).
Aside from the last 2 LEDs that only light up to indicate to the user that his presence is considered by the product, I would like that when the HC-SR04 first detects our glass of water between 0 and 5cm (cheers!), the first LED lights up and stays on. When the first LED is on and the HC-SR04 detects a second time our water glass is between 0 and 5cm, then the second LED lights up and stays on as well. And so on.
For each glass detected between 0 and 5cm, a slight sound sounds through the piezo buzzer.
By using the Adafruit Neopixel library (download here), I manage to make everything work as I see fit. However, I still have trouble programming if the LED n is on then the n+1 LED lights up at the next detection between 0 and 5cm, without all the LEDs lighting at the same time in a single detection.
I recently tried to use a boolean to identify when the LED n is true (ON/HIGH), but unsuccessfully. I leave you my code as is by thanking you for any help you can bring me.
See my layout and my code below:

#include <Adafruit_NeoPixel.h>

const int trigPin = 9;
const int echoPin = 10;
const int buzzer = 11;

#define dinPin 4
#define numLEDs 5

Adafruit_NeoPixel strip = Adafruit_NeoPixel(numLEDs, dinPin, NEO_GRB + NEO_KHZ800);

long duration;
int distance;

int blue;
int green;
int off;

boolean lightLED = false;

void setup() {
  strip.begin();
  strip.setBrightness(80);
  strip.show();

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(buzzer, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

  distance = duration * 0.034 / 2;

  uint32_t blue = strip.Color(0, 100, 255);
  uint32_t green = strip.Color(0, 255, 20);
  uint32_t off = strip.Color(0, 0, 0);

  ///////////////////////////////////////////////////////////
  // LED 1 + Buzzer
  ///////////////////////////////////////////////////////////

  if (distance <= 5) {

    if (! lightLED) {
      strip.setPixelColor(0, blue);
      strip.show();
      delay(0);
    }

    else {
      lightLED = false;
    }

    digitalWrite(buzzer, HIGH);
    tone(buzzer, 400, 100);
    delay(75);
    tone(buzzer, 600, 100);
    delay(75);
    tone(buzzer, 800, 100);
    delay(75);
    noTone(buzzer);

  }

  else {
    digitalWrite(buzzer, LOW);
  }

  ///////////////////////////////////////////////////////////
  // LED 2
  ///////////////////////////////////////////////////////////

  if (lightLED && distance <= 5) {

    lightLED = true;

    if (! lightLED) {
      strip.setPixelColor(1, blue);
      strip.show();
      delay(0);
    }
  }

  ///////////////////////////////////////////////////////////
  // DETECT USER PRESENCE
  ///////////////////////////////////////////////////////////

  if (distance >= 6 && distance <= 20) {
    strip.setPixelColor(3, green);
    strip.setPixelColor(4, green);
    strip.show();
    delay(0);
  }

  else {
    strip.setPixelColor(3, off);
    strip.setPixelColor(4, off);
    strip.show();
    delay(0);
  }

  // Voir la distance dans le moniteur
  Serial.print("Distance: ");
  Serial.println(distance);
}

Sorry for the code that is a bit rough, I am a beginner but I hope not to have lost you in my explanations (I lose myself in my code…).
Thanks,
Thibaut

You need to debounce the detection.

Thanks for answering @IgnacioVazquez-Abrams, can you be more explicit with a piece of code or something? As I said, I'm a beginner and I have trouble seeing what you mean.

Search for "debouncing" on Google.  There are many ways to do it in hardware or software.  I doubt you will find someone who has debounced a HC-SR04 in software for an Arduino, you will have to piece together bits from various sources.  Debouncing switches is probably the most common.  You might be a beginner, but if you have written that much you'll be able to write a debouncing function and it will be more 'fun' than copy and paste, because you will understand it.  If you get stuck though, come back with what you have.

Yes you're totally right @Matt :)
I'll see this as soon as possible and will come back here if I struggle to do what I want.
Similarly, I will not fail to share the result if it's successful. Thanks guys.

@Thib Can you share your solution here as an answer (which is encouraged in cases like this)?  I had a similar idea for combining range-detection with the WS2812 so I'm interested in how your project came out.


text:
Issue with IF statement
The program plays a random mp3 file from an Adafruit mp3 breakout board. The trigger to play the song is a sharp IR sensor. Basically to play a file you pass your hand over the sensor and it plays the full track. If you want to stop the file playing pass your hand over again and it switches it to an off mode.
I wrote a while statement using millis() to keep track of time. I would like for the songs to keep playing for a defined time or if you pass your hand over it, it stops playing the music.
Right now it's only playing a single file. It appears that the if statement I have in the while loop is being ignored. The program goes straight to break when the file is played.
//----------------------------------------------------------
// MUSIC PLAYER
// vonderasche
// 3/26/2017
//----------------------------------------------------------

// include SPI, MP3 and SD libraries
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>
#include <SharpIR.h>

// constants
#define ir A4
#define model 1080
#define TRIGGER_PIN  5
#define ECHO_PIN     6
#define MAX_DISTANCE 200

// These are common pins between breakout and shield
#define DREQ 3
// VS1053 Data request, ideally an Interrupt pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define CARDCS 4 // Card chip select pin
// These are the pins used for the breakout example
#define BREAKOUT_DCS 8
// VS1053 Data/command select pin (output)
// used to be pin 8
#define BREAKOUT_RESET  9 // VS1053 reset pin (output)
#define BREAKOUT_CS     10 // VS1053 chip select pin (output)

Adafruit_VS1053_FilePlayer musicPlayer =
// create breakout-example object!
Adafruit_VS1053_FilePlayer(BREAKOUT_RESET, BREAKOUT_CS, BREAKOUT_DCS,     DREQ, CARDCS);

SharpIR SharpIR(ir, model);

int state = 1;
const unsigned long onTimer = 1200000;

/// File listing helper
void printDirectory(File dir, int numTabs) {
  while (true) {
    File entry = dir.openNextFile();
    if (!entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i<numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

// random seed function
int rNumbers(int rNum) {
  randomSeed(analogRead(3));
  rNum = random(1, 10);
  return rNum;
}

// play a certain file
void playFile(int rNum) {
  switch (rNum) {
    case 1:
      Serial.println(F("Playing track 001"));
      musicPlayer.startPlayingFile("track001.mp3");
      break;
    case 2:
      Serial.println(F("Playing track 002"));
      musicPlayer.startPlayingFile("track002.mp3");
      break;
    case 3:
      Serial.println(F("Playing track 003"));
      musicPlayer.startPlayingFile("track003.mp3");
      break;
    case 4:
      Serial.println(F("Playing track 004"));
      musicPlayer.startPlayingFile("track004.mp3");
      break;
    case 5:
      Serial.println(F("Playing track 005"));
      musicPlayer.startPlayingFile("track005.mp3");
      break;
    case 6:
      Serial.println(F("Playing track 006"));
      musicPlayer.startPlayingFile("track006.mp3");
      break;
    case 7:
      Serial.println(F("Playing track 007"));
      musicPlayer.startPlayingFile("track007.mp3");
      break;
    case 8:
      Serial.println(F("Playing track 008"));
      musicPlayer.startPlayingFile("track008.mp3");
      break;
    case 9:
      Serial.println(F("Playing track 009"));
      musicPlayer.startPlayingFile("track009.mp3");
      break;
    case 10:
      Serial.println(F("Playing track 010"));
      musicPlayer.startPlayingFile("track010.mp3");
      break;
    }
  }

void setup() {
  Serial.begin(9600);
  Serial.println("Adafruit VS1053 Simple Test");
  if (!musicPlayer.begin()) {
    // initialise the music player
    Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
    while (1);
  }
  Serial.println(F("VS1053 found"));
  if (!SD.begin(CARDCS)) {
    Serial.println(F("SD failed, or not present"));
    while (1); // don't do anything more
  }
  // list files
  printDirectory(SD.open("/"), 0);
  // Set volume for left, right channels. lower numbers == louder volume!
  musicPlayer.setVolume(30, 30);
  // Timer interrupts are not suggested, better to use DREQ interrupt!
  //musicPlayer.useInterrupt(VS1053_FILEPLAYER_TIMER0_INT);
  // timer int
  // If DREQ is on an interrupt pin (on uno, #2 or #3) we can do background
  // audio playing
  musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT); // DREQ int
}

void loop() {
  // calls random number function
  int randomNumber;
  // takes distance measurment
  float distance = (SharpIR.distance() / (2.4));
  static enum { ON, OFF } state;
  // if distance range is between certain values switch the state
  if (distance > 1 && distance < 12) {
    switch (state) {
      case ON:
        {
        unsigned long previousMillis = millis();
        unsigned long currentMillis = millis();
        while ((currentMillis - previousMillis) < onTimer) {
          Serial.println("inside while loop");
          randomNumber = rNumbers(randomNumber);
          // calls random number function
          playFile(randomNumber); // plays music file
          float distance2 = (SharpIR.distance() / (2.4));
          delay(1000);
          //breaks timer if hand swipe
          if (distance2 > 2 && distance2 < 8) {
            Serial.println("Break");
            break;
          }
          currentMillis = millis();
        }
        state = OFF;
      }
      break;
    case OFF:
      {
      Serial.println("Triggered Off");
      musicPlayer.stopPlaying();
      state = ON;
      }
      break;
    }
  };
}

There's probably a good chance that when you trigger the ON state by placing your hand close to the sensor, the while loops runs and hits the if statement before you have moved your hand out of the trigger distance.
I see the delay of 1 second before the if, however, you take the reading of the IR sensor before the delay.
Try the delay before reading the sensor:
        ...
        playFile(randomNumber);  // plays music file

        delay(1000); // let the user move their hand
        float distance2 = (SharpIR.distance() / (2.4));

        //breaks timer if hand swipe
        if (distance2 > 2 && distance2 < 8)
        {
        ...

If you wanted to remove the delay function (highly recommended) after playing the file, set the state to something like PLAYING.
Then in the PLAYING state switch case you first wait for an IR reading that there is no hand present (allowing the user to finish moving their hand away), set a flag that you are ready to detect the hand. Then if that flag is true and the IR sensor reads a hand, then you can move to the OFF state.
You can add a second condition to the PLAYING state to test for elapsed time as well.

that seems to work. Ill look into trying to implement a flag setup later.

The intent of some of your code isn't clear, and the description “The program goes straight to break when the file is played” looks wrong – it appears that at least one delay(1000) will occur between start and break, so perhaps you mean that about a second after playing starts, it breaks.
If so, here is a possible explanation of that behavior:

At the beginning of loop(), you say distance = (SharpIR.distance() / (2.4));
Suppose that results in a value between 2 and 8.  Then the if condition (distance > 1 && distance < 12) will be true, so the body of the if will execute.
state initially is ON (state is static, and per §6.7.9.10 of the N1570 C++ spec, apparently gets initialized to 0, which corresponds to ON) and will be ON after each execution of the OFF case in loop().
When state is ON, we proceed into the ON case of the switch, set some variables to current time, then use a few microseconds to serial-print and call rNumbers() and playFile().  Then distance2 = (SharpIR.distance() / (2.4)); sets distance2 to about the same value read a few microseconds earlier into distance; as we supposed earlier, a number between 2 and 8.
With delay(1000), the program sits for a second doing nothing and paying attention to nothing.
The (distance2 > 2 && distance2 < 8) condition for the next if is  true, so program prints "Break", breaks out of the while, turns off state, breaks out of the switch, exits loop(), enters loop(), etc.

However, now that a second has gone by, the Sharp sensor shouldn't be reading a gesture.  If it is, that will allow the OFF case to execute and call musicPlayer.stopPlaying().

Note, issue the randomSeed(analogRead(3)) call only once, and do so within setup().  Calling it within each rNumbers() call is going to give you non-random numbers.


text:
High-range obstacle detection system
I am making a high-range and fast obstacle detection system.
The HC-04 is too slow for that, other sensors don't have the range, and Lidar is too costly.
Any idea how to make a long range (more than 10 m) high-speed obstacle detection system?

https://www.adafruit.com/products/3316 isn't the range, but is probably a lot faster. I don't think there is a solution that fits all your requirements.

Thanx for the reply but the rank is too short .

Is the sensor to be put on a mobile device or could you use a light sensor and shine a laser into it from the other end and detect when the laser beam is broken?

You can Use PIR Sensor which is Cost Effective and covers upto 10 Meters

Thanx for reply, but they doesn’t really detect the presence of an object, but rather the motion
Offers no distance sensing capabilities
Does not detect stationary objects

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


text:
How to reset the arduino uno after 5 seconds?
I am using this code.. But everytime after one rfid tag is read by the reader, I have to manually press the reset button on the arduino before scanning the next tag. I want to do this operation after every 10 or 20 seconds from one tag scanning without manually pressing the reset button. What changes I have to make to this code??
/*
* source: http://www.electroschematics.com/11301/arduino-rfid-reader-rc522-access-control-system/
* Read a card using a mfrc522 reader on your SPI interface
* Pin layout should be as follows (on Arduino Uno):
* MOSI: Pin 11 / ICSP-4
* MISO: Pin 12 / ICSP-1
* SCK: Pin 13 / ISCP-3
* SS: Pin 10
* RST: Pin 9
*/

#include <SPI.h>
#include <RFID.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address----------------------------------------------

#define SS_PIN 10
#define RST_PIN 9

RFID rfid(SS_PIN,RST_PIN);

int startAlarm = false;
int resetAlarm = 2;
int relay = 6;
int alarm = 8;

int serNum[5];

int cards[][5] = {
  {00,162,227,135,198} // card 1

};

bool access = false;

void setup()
{
  // Setup size of LCD 20 characters and 2 lines
  lcd.begin(20,2);    //------------------------------------------------------
  // Back light on
  lcd.backlight();  //---------------------------------------------------------

  lcd.setCursor(0,0);         //----------------------------------------------
  lcd.print("SCAN your ID");   //------------------------------------------------

    Serial.begin(9600);
    SPI.begin();
    rfid.init();
    pinMode(resetAlarm, INPUT);
    pinMode(relay, OUTPUT);
    pinMode(alarm, OUTPUT);
    digitalWrite(relay, HIGH); // or LOW if you have a regular relay------------------------------(ALREADY CHANGED)
    attachInterrupt(0, reset_alarm, LOW);
}

void loop()
{

    if(rfid.isCard()){

        if(rfid.readCardSerial()){
            Serial.print(rfid.serNum[0]);
            Serial.print(",");
            Serial.print(rfid.serNum[1]);
            Serial.print(",");
            Serial.print(rfid.serNum[2]);
            Serial.print(",");
            Serial.print(rfid.serNum[3]);
            Serial.print(",");
            Serial.print(rfid.serNum[4]);
            Serial.println("");

            for(int x = 0; x < sizeof(cards); x++){
              for(int i = 0; i < sizeof(rfid.serNum); i++ ){
                  if(rfid.serNum[i] != cards[x][i]) {
                      access = false;
                      break;
                  } else {
                      access = true;
                  }
              }
              if(access) break;
            }

        }

       if(access){
          Serial.println("Welcome!");
          startAlarm = false;
          digitalWrite(relay, LOW); // HIGH with regular relay (I have already changed the code)  //------------------------------
          lcd.setCursor(0,0);   //----------------------------------------------------------------------------------------------
          lcd.print("Access Granted");  //-------------------------------------------------------------------------------------------
          delay(3000);
          lcd.clear();
          lcd.setCursor(0,0);         //----------------------------------------------
          lcd.print("SCAN your ID");   //------------------------------------------------
             //---------------------------------------------------------------
       } else {
           Serial.println("Not allowed!");
           startAlarm = true;
           digitalWrite(relay, HIGH);  // LOW with regular relay (I have already changed the code)----------------------------------
           lcd.setCursor(0,0);         //------------------------------------------------------------------------------------
           lcd.print("Invalid Access ");        //------------------------------------------------------------------------------------
           delay(3000);
           lcd.clear();                            //--------------------------------------------
           lcd.setCursor(0,0);         //----------------------------------------------
           lcd.print("SCAN your ID");   //------------------------------------------------

       }
    }

    if(startAlarm) {
       digitalWrite(alarm, HIGH);
    } else {
      digitalWrite(alarm, LOW);
    }

    rfid.halt();

}

void reset_alarm(){
    startAlarm = false;
}

Sound like you are having a software problem. I'd suggest trying to fix that, instead of this hackish workaround. My first instinct is that, because you call rfid.halt();, the RFID reader will no longer read any further cards, which would explain why you need to reset the Arduino.

XY problem.

I would think the rfid library would be able to read multiple cards in a row... however I'm not familiar with it.
Here is an answer from a similar question about how to initiate a hardware reset with software using the watchdog timer - https://arduino.stackexchange.com/a/1478/31106 :

The SoftReset library makes it easy. Although it is not difficult to
  implement directly. Shown below..
#include <avr/wdt.h>
...
setup() {

  ...
  MCUSR = 0;  // clear out any flags of prior resets.
  ...

then when desired...
...
wdt_enable(WDTO_15MS); // turn on the WatchDog and don't stroke it.
for(;;) {
  // do nothing and wait for the eventual...
}
...

This would certainly force a system restart which is what the OP said he wanted. It is, however, a drastic solution for what is almost certainly a simple coding problem which may be better handled by a timeout or some similar mechanism in the application program.

100% agree. Finding a solution that didn't require a reset would be ideal.

This may not be your only issue, but I think you are using sizeof() wrongly.  This 'function' returns the number of bytes occupied by a variable or type OR the number of bytes occupied by an array.
So
1 == sizeof(char)
6 == sizeof ("Hello")  // Because of the trailing null
2 == sizeof(int)
int cards[][5] = {
                  {00,162,227,135,198} // card 1
                 };
10 == sizeof (cards)

So you line that says for(int x = 0; x < sizeof(cards); x++){ is happening 10 times, not once.
Personally I would never use sizeof to measure the size of an array, but if you have to then you need to do this:
size = sizeof (cards) / sizeof (int)

You mean 10 == sizeof(cards).

Yes I do, I wasn't sure when I wrote it, but just tested and corrected it.

As you may know, sizeof is an operator rather than a function.  So one can say, equivalently,  sizeof (cards) / sizeof (cards[0]) or   sizeof cards/ sizeof  cards[0].  Note, per §6.5.3.4.2 of ISO/IEC 9899:201x N1570 C++ std, "The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type."  That is, sizeof (int) is ok,  but malformed sizeof int is not ok


text:
Arduino Uno as USB to Serial converter (bypass 328p)
I'm trying out computer to computer serial communication using 2 Arduino Unos (both connected to different computers).
Right now, I use the Software Serial library, which redirects data from the SoftwareSerial ports to the hardware Serial (over USB to the PC).
Is there any way to bypass the 328p chip, and only use the 16U2, which works as a USB to Serial converter?
Will the circuit in the diagram work? By connecting the GND to RST on both the Unos, the 328p gets disabled, which in theory should all me to directly tap into the serial line of the 16U2.

Have you tried it?

Just tried it, it works fine. Tried 1 mega-baud, but there were a few errors

That's to be expected.

I'd probably add some resistors in between, in case the ground potential of both PC is a bit off. Not sure if this adequate, or if this is even a problem to begin with.

i don't think you want a resistor on the ground, if that's what you're getting at...

You may want a smallish (220ohm should be fine) resistor on each TX line in case the other device is accidentally configured as an output, but this is less of an issue on "known good" devices such as two Arduino Unos.

If your Arduino board has the Atmega328p in DIP format (not SMD), the best way is to extract it and you will have a pretty USB-UART so your schematic must work.

As per your diagram, ground the reset pin on both Arduinos and connect TX to RX on the one to RX to TX on the other. Alternatively, if your Unos have a socketed 328P, you can remove it.
(This answer summarized from the comments above in order to take it off the "unanswered" list.)

The circuit you have drawn will work for PC to PC coms. Essentially your connection diagram looks like this:
PC1 -(USB)- Arduino1 -(TTL serial)- Arduino2 -(USB)- PC2
To answer your second question, you can bypass the 328p chip by removing them both as they are not needed. The 16U2 converts the USB to TTL serial which it provides to the Arduino on pins 0 and 1. Since the ATmega328p microcontrollers aren't being used (ie in reset state) then you may as well remove them and use them on another project.


text:
Sending a string to arduino and is not reacting to it
I am trying to move servos with a VR headset, I am using the Unreak 4 Arduino Plugin, but that is not the problem. I send the rotation Y and Z from the headset, convert them to int and then send them together as an int separated by commas. Here's what it does: It gets the rotation Z, it converts it to int, then it converts it to String, I add a comma at the end of the String, then I add the rotation Y after the comma, and it returns me: "rotationZ","rotationY" (the values between " are the numbers sent by Unreal to arduino), these results may come in negative or positive value.
Then inside arduino I have this code:
#include <Servo.h>
#include <SoftwareSerial.h>

Servo servo1;
Servo servo2;  // Crea un Objeto servo

int angle = 10;
int posicion = 10;    // Variable de la posicion del servo

String user_input1;

int r;
int g;

void setup()
{
  Serial.begin(9600);
  servo1.attach(2);  // Selecionamos el pin 2 como el pin de control para el servo
  servo2.attach(3);  // Selecionamos el pin 2 como el pin de control para el servo

  servo1.write(0);
  servo2.write(0);

  Serial.setTimeout(5);
}

void loop()
{
  if (Serial.available() > 0)
    {
  String firstValue  = Serial.readStringUntil(',');
 // String first = Serial.readString(); //next character is comma, so skip it using this
  String secondValue = Serial.readStringUntil(',');
//  String second =  Serial.readString();

   r = firstValue.toInt();
   g = secondValue.toInt();
    }
  if (r < 0)
  {
    r = r * -1;
  }

  if (g < 0)
  {
    g = g * -1;
  }

  Serial.println(r);
  Serial.println(g);

  servo1.write(r);
  servo2.write(g);

}

As you can see, it gets the numbers between the commas and then it converts them to int, and then it applies to the servos which are in pins number 2 and 3 (yes, everything is plugged in correctly), which it should then move them acordingly the position of the VR headset, I've also tried to make them always receive positive results but still doesn't work. I have searched over the internet on how to separate a string divided by commas and I still don't know if it's correctly done.
EDIT: I also tried to input the numbers in the console manually, and it gets them right and moves the servos but it still doesn't work with the VR. I also added Serial.setTimeout(5) to try if it works that way.
Thanks in advance for reading this bunch'o text about my problem.

I also tried to input the numbers in the console manually, and it gets them right and moves the servos but it still doesn't work with the VR.

This implies that the problem is in the code sending the data.  Get a terminal emulator program and hook that up to the code generating the data from the VR headset (you will need 'local echo' turned on).  I suspect you will see the headset is not writing the data in the format you expect.  Also it will let you capture a real sample of data that you can feed into you program to generate a repeatable test.
If this isn't the fault, then please can you post the a few lines of data so we can see whats wrong.

I have to apologize but, what do you mean by "terminal emulator program"? I am kinda new to this kind of programming with arduino.

I should apologise 20+ years of embedded development and I forget things like speaking English :)  What you need is a program that you run on your "PC" and it lets you talk to the serial port.  The serial monitor is a sort of basic terminal emulator, but I don't think it would work in this case.  So for Windows try "Terraterm" [https://ttssh2.osdn.jp/index.html.en] or "Putty" [http://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html].  (Linux and Mac will need advice from someone else, sorry)


text:
Pre-heat time required for MQ-5 gas sensor
The datasheet of MQ5 sensor says, it requires a pre-heat of 24 hours. Does this mean that it needs to be powered on for 24 hours consecutively before usage? Some other websites (e.g. http://www.circuitstoday.com/interfacing-mq5-lpg-sensor-to-arduino) say that 15 minutes pre-heat would suffice. Could someone clarify this issue? Thanks.

I used one after a few minutes or heating.

salut , NB que le MQ 5 ne peux tenir que +/- 1 semaine et après il va plus marcher ... car l capteur de gaz est un petit truc qui brûle à l’intérieur et qui va s’arrêter de brûler après cette semaine et donc le capteur ne marchera plus !! Google Translate: > hello, NB that the MQ 5 can only take +/- 1 week and after it will not

work ... because the gas sensor is a little thing that burns inside
and will stop burning after this week and so the sensor will not work
anymore

Does this mean that it needs to be powered on for 24 hours
  consecutively before usage?

No, it just means that typical performance data in the datasheet has been measured after 24h. So, if you want to be within specification you must observe that 24h preheating time.
Does it mean you can't use the sensor before those 24h? Absolutely not. Given the small size of the sensor, thermal equilibrium will be almost surely reached within 30 min. And it would probably take just a few minutes to be within +/- X % of the specification (you can only know by actually measuring how much time does the output need to stabilise, which you should do).
At the end, the time to wait for thermal stabilisation of the sensor (preheating time) will depend on your application.
Only if you want a very accurate measure of gas concentration, you will need to wait those 24h (and also have a good calibration of your sensor, as well as means to compensate other environmental factors like temperature, humidity, etc.). But if you wanted to do this kind of measurement you probably won't be using a MQ-5 sensor anyway.
EDIT:
Take a look at this excellent technical note from Figaro Sensors to better understand the preheating time. It ISN'T a burn-in time per se, but a stabilisation time whose duration depends on several factors.

Please be clear when you mean the one time only pre-heat and when you mean turning the sensor on to take a measurement.
It is a electrochemical sensor and it needs time to burn-in. During those 24 hours, the impedance of the sensor changes a lot. After those 24 hours it can be used in a normal way and it will return consistant values.
The pre-heat should be done just once. I mean: just once in the lifespan of the sensor. After buying it, you should run the pre-heat.
When the manufacturer writes in the datasheet that the pre-heat time is 24 hours, then you should do 24 hours.
I suggest to connect the sensor in a normal way, with 'A' en 'B' pins connected and with the load resistor, and keep it on for 24 hours. Maybe it is already stable after a few hours, but keep it on for 24 hours to be sure.
To take a measurement, the sensor needs time to warm up. About 5 minutes might be okay. I think that 2 minutes is definitely too short.
When the sensor is always at room temperature, and the time to warm up is always the same, then the measurement is relative accurate and can be compared with other measurements. That means that when the sensor is mostly turned off to save power, only a few minutes to warm up can be used. However, I would start with at least 5 minutes.
[EDIT] The datasheets and other information from the manufacturers use the term "pre-heat" in different ways. The Technical Note in the link by @EnricBlanco uses the term "preheating" only for the "one-time-only" heating after storage to make the sensor more stable, as far as I can tell. Although it is not "one-time-only", it should be applied after storage or changing conditions as well. @EnricBlanco, try a very cheap MQ gas sensor (which is probably not preheated in the factory) and see how the impedance changes a lot during the first hours of preheating, and becomes stable after a few hours.


text:
Too slow start up with Atmega2560 on custom PCB
I have some several custom PCB's based on Atmega 2560.
I am using AVRISP MarkII for flashing. No bootloader.
Flashing is flawless, it just works. I have one assembled PCB works as it should be, no issues.
But, the other one has a quite time lag in its functions.
It has also been flashed OK but, it is not running quite OK.
Here are my observations;
By asserting Reset, I expect four leds on the pcb running (on and then off) by 100ms intervals one after each others. This is happening in the very beginning in Setup() section of the program.
Note that: Leds are connected to MCU via mosfets. If MCU output is LOW, they are ON and vice versa.
So, with this problematic PCB, all leds come ON all together after 10 seconds after pressing reset button and they stay almost 60 seconds before they start the sequence (on and then off) as coded.
And then that sequence is also slowly occurring. It is not 100ms as I coded but almost 4 seconds or so.
I am suspecting from the external clock (16Mhz) circuitry but I can't proof it accurately as I don't have oscilloscope at hand.
You may see the simple code I use to test that behavior;
void TestLeds() {
    unsigned long interval = 100;

    digitalWrite(LED1_PIN, LOW);
    delay(interval);
    digitalWrite(LED1_PIN, HIGH);
    delay(interval);

    digitalWrite(LED2_PIN, LOW);
    delay(interval);
    digitalWrite(LED2_PIN, HIGH);
    delay(interval);

    digitalWrite(LED3_PIN, LOW);
    delay(interval);
    digitalWrite(LED3_PIN, HIGH);
    delay(interval);

    digitalWrite(LED4_PIN, LOW);
    delay(interval);
    digitalWrite(LED4_PIN, HIGH);
}

How/where should I check the bottle-neck on that?
Thank you.
EDIT:
To be more specific, I add this output regarding programming;
here

Measure voltage and current.

Did you change the fuses? By default most AVR run at 1MHz from the factory. So that would mean your code runs 16 times as slow.

@Gerben  You mean a sixteenth of the speed, not sixteen times as slow. Sixteen times as slow as what?

I am just using same setup (fuses) as I used for the other PCB. But, how about this: if the external oscillator (16Mhz) doesn't work for some reason although the flashing has just worked fine, could there be something happened about the fuses e.g. automatically adjusted itself or so and started to work at 1Mhz instead?

@Mikael Patel: Can you be more specific about measuring voltage and current? What to measure and compare to what and to find out what eventually? Thanks.

Fuses don't reset themselves. There also no failover in case the crystal isn't working. You could try reading the fuses to verify that they are set correctly.

@majenko that's the way we say it in my language. Appearantly it doesn't translate into English. Thanks for the heads up.

@Gerben It's also how a lot of native English speakers say it, despite it being completely incorrect

@Gerben: I can't get it. If I use same fuses for the other identical PCB design and it works just fine, why I would check the fuses again if they don't reset themselves? I am obviously missing a point here. Can you be more specific if you still insist for checking fuses? (which I will check anyway) Thank you.

Maybe something went wrong when you set the fuses, and so that they have their original value.

I am closing the case. It is not 100% satisfaction though. Because, using Visual Studio with Visual Micro didn't help me on that issue in a natural way but something else.
For the future reference for somebody might get benefit out of this, I like to explain here what I did to get over this issue briefly. As @Gerben (big credits go to him) has pointed the right direction, I did check fuses by installing Atmel Studio 7 and use its programmer.
Yes, the fuses were completely wrong. I have therefore read the fuses from my healthy PCB and noted aside and then applied these very same fuse settings to the slow working PCB. I have just programmed the fuses, Firmware was the one I programmed earlier in the uC. So, voilà, the slowness has gone.
I think I am going to use Atmel Studio 7 now on next to Visual Studio as it has everything built-in including Arduino support.
Thanks everybody involved.

Just burn the bootloader via  arduino ide before you burn your firmware. During bootloader burning, ide also configures the fuse bits you needed.

That's what I do. Then Upload Using Programmer to load without having the bootloader called.

I must agree with you guys. I do it at home with my hobby projects. The way I choose as stated in my solution has been already liked by the field engineers of ours. I can't ask them to use Arduino IDE to deploy new firmware versions. They used to use Atmel Studio flasher. Thanks anyway.


text:
PWM generation using Arduino uno
How to obtain four PWM outputs at 100 kHz using an arduino uno board? The requirement is that all four PWM outputs should have controllable duty ratios individually.

There's a ton of examples in the web. Google doesn't bite, use it.

This is a arduino user level question, nothing about electrical engineering.

In a comment to Dmitry Grigoryev’s answer you wrote:
void setup()
{
    TCCR2A = 0x23;
    TCCR2B = 0x09;
    OCR2A = 159;
    pinMode(3, OUTPUT);
}

void loop()
{
    OCR2B = 80;
}

It seems you already have the solution to your problem: that's exactly
the way to do it!
Well, there is a catch: since you are using OCR2A to define the period
of your timer, this means you are left with a single PWM channel, where
the duty cycle is controlled by OCR2B. Given that the Arduino Uno has
only three timers, it would seem you can only have up to three PWM
channels at 100 kHz.
But there is a solution. Timer 1 has a feature the other timers
don't have: you can define its period using using the input capture
register ICR1 instead of OCR1A. This leaves you both output compare
registers available for PWM. For this you have to set the timer into
waveform generation mode 14, i.e. fast PWM with TOP = ICR1.
Now you can have your four channels, with Timer 0 driving
pin 5, Timer 2 driving pin 3, and Timer 1 driving
pins 9 and 10.
Some caveats:

As already pointed out by Dmitry Grigoryev, your PWM resolution is
slightly reduced.
By reconfiguring Timer 0, you loose the Arduino Timekeeping function
millis(), micros() and, delay(). You could write your own ISR to
count the overflows of some other timer, but it would be called every
10 µs: even if it is very short it would eat a non-trivial
fraction of your CPU power.

Great answer. Thanks for the help. I'm trying to implement as you mentioned. I'll get back to you with some results.

You can't squeeze 100kHz out of an Arduino without a major software rewrite (at which point you will be using an AtMega chip rather than Arduino). analogWrite defaults to ~500Hz and can be boosted to 62.5kHz on some Arduino models, and only for 2 pins. Other PWM pins are capped at 31.4kHz.
You can achieve 100kHz PWM by toggling pins manually and busy-waiting, but you won't be able to do anything else during this. Or you can make use of interrupts, which is a big leap from Arduino ecosystem as I already said.

setup()
{TCCR2A = 0x23;
TCCR2B = 0x09;
OCR2A = 159;
pinMode(3, OUTPUT);
}  loop()
{
OCR2B = 80;

I used the following code to generate 100 khz pwm signal-
setup()
{
TCCR2A = 0x23;
TCCR2B = 0x09;
OCR2A = 159;
pinMode(3, OUTPUT);
}
loop()
{
OCR2B = 80;
I have to drive 4 MOSFET's simultaneously for my project to achieve multiple O/P dc-dc converter. Probably an arduino Mega would work?

@ParikshitDeshmukh You're sacrificing resolution for speed here. You get your 100 kHz, but only 160 distinct PWM duty cycles instead of 256.


text:
LED fade with LDR sensor depending on the light
I need help on a project. I just started to experiment with arduino 2 weeks ago and I am building a lamp that react to movement and interactions.
So the idea is; when there is nobody in the room, the light stay white.
And when there is someone, it turns orange and I want it to « breathe » (fade function).
I am using a LDR sensor to make it happen and so far my code looks like:
int LDRvalue = 1;
int RedLED = 9;
int GreenLED=10;
int BlueLED=11;
int pinLDR = A0;

void setup()
{
pinMode(RedLED, OUTPUT);
pinMode(GreenLED, OUTPUT);
pinMode(BlueLED, OUTPUT);
Serial.begin(9600);

}
void loop()
{
LDRvalue = analogRead(pinLDR);
Serial.print("valeur ldr: ");
Serial.println(LDRvalue);

int colour = map(LDRvalue, 0, 1023, 0, 255);
Serial.print("valeur mappe: ");
Serial.println(colour);

if(LDRvalue >= 1023)
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 255);
analogWrite(BlueLED, 255);
delay(1000);
}

else if((LDRvalue >= 800) & (LDRvalue < 1023))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 255);
analogWrite(BlueLED, 255);
delay(1000);

}

else if((LDRvalue >= 600) & (LDRvalue < 800))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 105);
analogWrite(BlueLED, 0);
delay(1000);

}
else if((LDRvalue >= 300) & (LDRvalue < 600))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 35);
analogWrite(BlueLED, 0);
delay(1000);
}

else if((LDRvalue >= 150) & (LDRvalue < 300))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 15);
analogWrite(BlueLED, 0);
delay(1000);

}

else if((LDRvalue >= 0) & (LDRvalue < 150))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 0);
analogWrite(BlueLED, 0);
delay(1000);
}

delay(1);

}
void color(int red, int green, int blue)

{
analogWrite(RedLED, red);
analogWrite(GreenLED, green);
analogWrite(BlueLED, blue);
}

The code is working for the light changes depending on the human presence.
But I don’t know how to make it fade and breathe when it turns orange.
Could you help me to make it happen ?

For one, you need to change the & in your if statements with &&. & is a bitwise AND, && is a logical AND. Which one of the if statements is orange? It seems like you have 3 different kinds of orange.

Thanks for the answer, I have 3 orange because the more there is a light change the more it turns orange to red. I forgot to talk about it. But for each of these orange, I need it to breathe, maybe more each time.

While some parts of your code don't make much sense to me, the breathing led code is easily searchable on the internet, with one of the first results being:
#include <math.h>
#define ledPin 11
int i=0;
int breathe_delay = 15;   // delay between loops
unsigned long breathe_time = millis();
void setup() { }
void loop() {
  nonBlockingBreath();  // call the nonblocking function
  // yourOtherCodeHere();
}

void nonBlockingBreath() {
  if( (breathe_time + breathe_delay) < millis() ){
    breathe_time = millis();
    float val = (exp(sin(i/2000.0*PI*10)) - 0.36787944)*108.0;
    // this is the math function recreating the effect
    analogWrite(ledPin, val);  // PWM
    i=i+1;
  }
}

As you can see the code above works for monochromatic LEDs only, so my advise is to combine the code above with a conversion from HSL to RGB, like RGBConverter library, specifically the hsvToRgb function.
This way your version of the nonBlockingBreath function will become:
byte[3] rgb;
void nonBlockingBreath() {
  if( (breathe_time + breathe_delay) < millis() ){
    breathe_time = millis();
    float value= (exp(sin(i/2000.0*PI*10)) - 0.36787944)*108.0;
    hsvToRgb(hue, saturation, value, rgb);
    analogWrite(RedLED, rgb[0]);  // PWM
    analogWrite(GreenLED, rgb[1]);  // PWM
    analogWrite(BlueLED, rgb[2]);  // PWM
    i=i+1;
  }
}

Obviously you will have to set the hue and saturation variables accordingly to the tonality of orange you wish to breath.


text:
Arduino IDE - Maximum serial COM ports
What is the maximum number of serial ports (com) can Arduino IDE detect ?
I need to connect 6 Arduino UNO Wi-fi at a time to make a small network and I use a 7 port USB hub for the same. The device manager shows 6 com ports detected but Arduino shows only 4 serial ports detected. Is there a limitation on the serial ports interfaced with the Arduino IDE ?

You could run 6 copies of the IDE to allow a Serial Monitor per board.

I've never had any success connecting the IDE to multiple boards, it seems to use a global for the Serial Port and so all instances program the same board.  It might have changed with the latest IDE, I haven't tried for a few months.

Thanks for your comments. I found the solution.
Inside the My computer -> Properties -> Device manager under ports I found that multiple Arduino's where assigned same COM values.
Therefore, just go to properties of the COM and change them to COM values that are not used.

Thanks for your comments. I found the solution. Inside the My computer -> Properties -> Device manager under ports I found that multiple Arduino's where assigned same COM values. Therefore, just go to properties of the COM and change them to COM values that are not used

Cool! Indeed, a valid solution was to try another OS ;)

According to the last version of code for Arduino IDE, there are no limits of discovered Serial or Network devices since they are stored in a list (not limited as an array).
To discard problems, try with another operating system.

Thanks a lot for your reply. From my findings, if I'm not wrong the maximum detectable serial port for Windows 7 is 255.


text:
Creating a library of C++ classes for Arduino; How to #include "Arduino.h", "WProgram.h"?
I've written 6 C++ classes on the CLion IDE to be used on Arduino. One of these classes uses a C++ library called "Adafruit_PWMServoDriver.cpp" provided by Adafruit to use the PWM driver they sell. I'm trying to test my code in a main.cpp, but upon building my code, I noticed that "Adafruit_PWMServoDriver.cpp" has the following code:
#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

Naturally, I copied Arduino.h from the Arduino installation folder to my C++ project header directory. But for reasons I don't know, ARDUINO is apparently not greater than or equal to 100, so it attempts to include "WProgram.h." Because I cannot find this header file, I changed my code to only attempt to include Arduino.h.
#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "Arduino.h"
#endif

However, Arduino.h itself includes several header files, and I am not sure where I can find all the find them, or if it is even necessary to try to do so. I need to get my test code running, so I don't want to directly test it in the Arduino IDE yet. What can I do to overcome #include Arduino.h and #include WProgram.h?

I guess that you are not using the Arduino build. Could you describe your IDE and compiler setup. Looks like you need to configure CLion with a path to the Arduino core files.

I am using CLion. Environment: MinGW-w64 (w64 5.0), CMake: 3.6.3, C++ compiler: C:\msys64\mingw64\bin\g++.exe. I've actually managed to find all the header files from the avr library and placed them in my project directory. However, now I am running into compatibility issues in the avr library files. As of now, the compiler can find all 3 avr header files that I've placed in my \include directory, which is correctly imported in my CMake. However, in my io.h file, there is a long list of #if defined (AVR<various_names>_).

I assume this is to identify the type of device I am using, and it only expects different types of Arduino. However, I am currently working in CLion; therefore, it reaches the end of this list and the following code executes: #else
if !defined(COMPILING_AVR_LIBC)
warning "device type not defined"
endif
#endif
How can I make my coding environment compatible with the Arduino setup? Or can I avoid all this and somehow create C++ classes independently?

You need to set the correct MCU define. Please see the Arduino-Makefile for an example. Or run the Arduino IDE and look at the compiler parameters.

The libraries from Adafruit and elsewhere assume you are using the Arduino IDE. If you choose not to use that you will have difficulties compiling your own code. The header files you ask about are in the IDE download. You can always grab a copy of that and put the appropriate .h files into your "include" search path.

However, in my io.h file, there is a long list of #if defined (AVR_various_names).

Well, do a test compile using the Arduino IDE, using "verbose compiling" and see what defines are generated for your particular board (which you haven't mentioned). There won't be that many of them. Then you can put that on the build commands for your IDE.

Or can I avoid all this and somehow create C++ classes independently?

You can create C++ classes inside the Arduino IDE. I don't see how this relates to your other issues.

The Arduino IDE basically generates build commands for avr-g++ - it isn't some horrible beast you should avoid using.

The #if defined (AVR_<various_names>) you see here have nothing to do
with Arduino: this is the avr-libc trying to import the IO register
definitions for the AVR chip you are using. Whenever you compile an AVR
program, you pass the option -mmcu=<mcu-name> to avr-gcc, and it
automatically defines the proper macro. For example, the Arduino Uno is
built around an ATmega328P. Programs for the Uno must then be compiled
with -mmcu=atmega328p, which makes the compiler define
__AVR_ATmega328P__, which directs the avr-libc to
#include <avr/iom328p.h>, which contains all the IO register
definitions for that chip.
As for the ARDUINO macro, this one is defined by the Arduino IDE to be
the version of you Arduino installation, without the dots. For example,
if you downloaded the core files from Arduino 1.8.2, then you should
compile with -DARDUINO=182.
Also, you should avoid copying all the library headers to your project,
and instead use the proper -I options. And don't forget to tell the
compiler your clock frequency with -DF_CPU=..., as it is needed by
some avr-libc and Arduino stuff.
In the end, you will see you need quite a lot of compiler options to
properly compile Arduino code. The easiest way to do it is definitely to
use the Arduino IDE, as it handles all this for you. If you don't like
the IDE (understandable...), you could try Arduino
Builder, which should be
entirely compatible. If you want to compile from just a Makefile, I
recommend you take a look at Sudar Muthu’s Arduino
Makefile.


text:
Run 5V/2.3W water pump on Arduino Pro Mini 5V
I want to build up my automatic water pump with an arduino pro mini 5v and a 5v usb water pump (2.3 W). As I understand, I cannot power the pump directly through the vcc pins of the board, right?
Would it be possible to place a female USB Port in my system to power the board and the pump through a relay on the board? What would be an appropriate circuit diagram?

if the micro has a VIN pin, you can simply connect that to the pump, and switch the ground "on/off" using an n-chan mosfet like the IRLZ44N: gate to GPIO, drain to pump, source to GND. FETs switch faster and with less power than a relay, so you can even use PWM to slow down the pump!

As I understand, I cannot power the pump directly through the vcc pins
  of the board, right?

This is from the Arduino Pro Mini schematic:

Note that the maximum current output is 150 mA. On the other hand, your pump needs 2.3 W / 5 V = 460 mA > 150 mA. So your understanding is right: you can't power the pump directly through the Vcc pins of the board.

Would it be possible to place a female USB Port in my system to power
  the board and the pump through a relais on the board? What would be a
  appropriate circuit diagram.

There are lots of extremely cheap, commercially available, opto-isolated 5V relays modules in aliexpress and the like.
I'd recommend one like this because it allows you to have separate supplies for the relay coil and for the input diode in the opto. That will help you to avoid problems related to having "different" 5V levels due to dropout in the Pro Mini regulator.
Module picture:

Module schematic:

Module connectivity:

VCC --> VCC from the Pro Mini.
JD-VCC --> V+ from the power supply (same as RAW input to the Pro Mini).
COMMON --> V+ from the power supply.
NO (normally open) --> connect it to the 5V rail of the USB pump.
NC (normally closed) --> leave it unconnected.
Be sure to connect all grounds together.
I'd also recommend adding an additional decoupling capacitor close to the RAW pin of the Pro Mini, to protect the regulator from voltage spikes caused by switching-off inductive loads like the relay coil and the pump motor.

NOTE: take into account that the relay module can draw up to an additional 80-100 mA of current. Take that into account in your power/current budget.

Hi Florian you can take power from USB fro both Arduino and the water pump.This is the schematic you have asked for your project. An arduino Pin can give maximum 20mA current that's why we need a limit resister to limit the current below 20mA and also this current should be such a way that it can drive the switching transistor. So the challenging thing is choosing the correct resister
I have taken the value 1K
So the current at Arduino Digital pin is Current I = 5V/1k = 5mA which is below of 20mA and sufficient to drive the Transistor. you can use BC548 transistor also.

simulate this circuit – Schematic created using CircuitLab


text:
I fried the AMS1117 voltage regulator on my Arduino Clone, is this the cause?
I had the 12V DC power jack plugged-in all the time, and "to make things more exciting" I also plugged-in the "data" USB whenever I had a new sketch to upload. Is this combination a big no-no, or is my step-up converter to blame?
I am completely new to this stuff but now when thinking of it those 12V from the power jack + 5V from the "data" USB probably violate this clause:
If using more than 12V, the voltage regulator may overheat and damage the board.

Original Arduino boards work fine with both USB and the barrel jack plugged in. However, I think you are having a clone, as the original doesn't use the AMS1117. Depending on what you have connected, the voltage regulator can get quite hot.

@Gerben indeed it is a clone... and given I have ordered an original since this sounds like a promising news to me, thank you very much sir :)

Did you have anything else connected to the 12V DC supply at the same time?

@EnricBlanco nothing else

The "problem" with the AMS1117 voltage regulator is the amount of current they can safely provide drops as the input voltage rises. I'm a Arduino noob, so I looked at the data sheet for the AMS1117 series of voltage regulators. There is a formula: PD=(VIN-VOUT)(IOUT) and Note 2: which says the maximum power dissipation for the SOT-223 package is 1.2 W.
The best case scenario is to use an input voltage of 6.5 volts. (6.5-5)(0.8)=1.2W. This gives you 0.8 amps maximum output. If you use a 12 volt power supply: (12-5)(0.1714)=1.2W. This only gives you 0.1714 amps maximum output.
I'm not sure what kind of power jack you are using, so I'll give you an example of one that I used in a project. It says input 120VAC, output 12VDC, 200ma. The problem is, it actually puts out 20VDC open circuit with no load.
The data sheet gives a maximum input voltage of 15 volts but that would only provide a maximum of 120 mA output.

What if I have a 3.7V battery to supply power for a 3.3V ESP8266 (WiFi module)? Would a AMS1117 between the battery and the module be good at making sure the voltage is at ~3.3V?

The datasheet for the 3.3V AMS1117 gives a maximum dropout voltage of 1.3V, so 4.6V would be the lowest voltage you should apply to it. Another option is to use the battery with a Buck-Boost DC DC 0.9-6V to 3.3V Step-UP Step-Down Converter Board such as this one: www.aliexpress.com/item/Auto-Buck-Boost-DC-DC-0-9-6V-to-3-3V-Step-UP-Step-Down-Converter/32756017955.html.

Probably not. There is nothing fundamentally wrong with what you're doing - it's within the design parameters. In particular:

12V is within the 7-12V recommended range specified for that input. Yes, it means the regulator will get hotter, but the AMS1117 is supposed to be current limited and thermally limited so should just start shutting down if it supplies too much current or gets too hot. As this answer suggests, it would be wise to limit it to 1.2W, which is 171mA. That's plenty for the Arduino itself, so you'd only be running into trouble if you have other peripherals to power.
The Arduino Uno has circuitry specifically designed to disconnect the USB's 5V rail if the external power supply is present. This is really only to protect the USB supply from being damaged by the external power supply - the Arduino doesn't care as long as it is getting 5V from somewhere. The USB data function is independent of whether the 5V comes from the USB's 5V rail or the 5V generated from the external supply you provide. The AMS1117 itself, according to its (various) datasheet, has no design susceptibility to an alternate 5V supply being on the output.

Finally, there's an alternate reason for the failure. We've also been using an Arduino Uno clone with the AMS1117, and have also been supplying 5V external (directly to the 5V rail in our case) as well as connecting to USB for programming. We've also had an AMS1117 fail, despite operating everything within normal limits. Our symptoms are that the OUT pin is shorted to the GND pin. Removing the regulator restores full functionality.
Based on various reports around the Internet of suspect behaviour and doubtful provenance of these chips on the clone boards, I would suggest that a faulty IC might be the root cause.


text:
Problem on Arduino Interrupt and RTC
I am doing an experiment. In this experiment I want to start the RTC by presing the external Push Button which is connected with Aquino's pin 2 and take varites of action according to Time. For interrupt I have made a ISR and in this interrupt I wrote my main logic. But this things is not working.
The schematics is
and The code is
`include <Wire.h>
#include "RTClib.h"
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 9);

RTC_DS1307 rtc;
int k = 0;
int led =13;
int pin =2;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {
 lcd.begin(16, 2);
 rtc.begin();
 Serial.begin(11520);
 pinMode(led,OUTPUT);
 pinMode(pin,INPUT);
 attachInterrupt(0, Time  , LOW);
  // Print a message to the LCD.
  if (! rtc.begin()) {
    lcd.print("hello, world!");
    while (1);
}

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
  }
}
void loop()
{}

void Time()
   {
    {DateTime now = rtc.now();
    lcd.setCursor(0, 0);
    lcd.print(now.year(), DEC);
    lcd.print("/");
    lcd.print(now.month(), DEC);
    lcd.print("/");
    lcd.print(now.day(), DEC);
    lcd.print(" ");
    lcd.print(daysOfTheWeek[now.dayOfTheWeek()]);
    int c = now.second();
    lcd.setCursor(0, 1);
    lcd.print(c);
    if(c==58)
      {
        k=k+1;
        lcd.setCursor(5, 1);
        lcd.print(k);
        if(k==4)
          {
            digitalWrite(led,HIGH);
            k=0;
          }
     }

    }}`

please help me.

Well, for example Arduino's delay needs interrupts to be working and as you may not know it's disabled inside of ISR handler.
Never ever use anything like while (1), delay(1000) and so on inside of ISR! And also do not reenable interrupts either! Set a simple volatile flag and use it inside of loop function instead.
Basically something like this:

constexpr int8_t button = 2;
volatile bool      flag = false;

void setFlag() {
  flag = true;
}

void setup() {
  pinMode(button, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button), &setFlag, FALLING);
}

void loop() {
  if (flag) {
    // it's running, you can do something here

    // and you can reset the flag here either
  }
  //delay(100); // if needed
}

sorry I am not getting your point. I have used while(1) and delay() for special reason forget about that. I have checked this code without while(1) delay() inside ISR still its not working.

@Prayuktibid: You wrote “I have checked this code without [...] still its not working.” There is no point in talking about code we cannot see. Please update the question with the relevant code and tell us exactly how it is not working.

@EdgarBonet  I have updated the code plaese check it

@KIIV Sir, Why you using address of setFlag() Function Instead of setFlag() function in this program please explain me.

@Prayuktibid Well, without ampersand it's converted to the function pointer implicitly, so it's not required. But it's more obvious for reviewers or coworkers. For the class methods (member functions) it's required.