text:
Make Sure \n is the last character in serial string
I have an Arduino that I've put between a computer and an RS485 device. The job of the Arduino now is just to transmit data but will eventually do data logging and have a small user interface as time goes by.
So far, this serial read code has worked for me to communicate to the Arduino from the computer:
 void serialEvent()
 {
  while(Serial.available())
  {
    // get new byte
    char inChar = (char)Serial.read();
    if (inChar == '\n')
    {
      stringComplete = true;
    }
    else
    {
      inputstring += inChar;
    }
  }
 }

The downside here is that I cannot send the '\n' char to my RS485 unit. Is there a way I can refine the code so I can send an arbitrary string of chars while still having a termination [thing] to turn on the stringComplete flag?
EDIT To clarify this the process by how my message string is being created:
Input: U16 Address, U16 Data, U8 Function Code
U16 Address -> U8 Address Split High, U8 Address Split Low
U16 Data -> U8 Data Split High, U8 Data Split Low

U8 Array of [U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]

U8 Array -> Message String

Output: Write Message String

Is it just strings of ASCII characters (codes 32 to 127 + \n) that you want to send?

No, I'm sending n number of u8 ints (words?) that are represented as \code characters put together to form a string.

But the actual string content that is sent over the wire only consists of printable characters? You're sending such things as \024\075\216\030\777\000\123 etc?

Or are you sending the actual 8 bit values that you have put into the string using '\whatever`?

Right now, I'm sending and receiving the actual 8bit values the entire process is as follows:
Computer
Input: U16 Address, U16 Data, U8 Function Code
U16 Address -> U8 Address Split High, U8 Address Split Low
U16 Data -> U8 Data Split High, U8 Data Split Low
U8 Array of [U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
U8 Array -> Message String
Output: Message String

Since you are using all 8 bits of the serial data for your data there is nothing "in band" that you can use for a delimiter.
Instead you will have to think outside the box somewhat and create some form of "out of band" data that can signal the end of a packte.
One option (probably the simplest) would be to include the concept of time into your protocol.  If you go more than X milliseconds (X is to be determined by you) without receiving a byte then you are at the end of your packet. This has the disadvantage that it slows down your maximum packet rate, since each packet has to have a suitable delay between them.
Another option may be to use a serial break character between packets. This is a special event where the UART output is held low for at least 10 symbol lengths, which results in an framing error (the STOP bit is wrong) and a flag being set. It would mean though that you have to implement all the UART code yourself since the Arduino's UART code doesn't support breaks.
A third option, which also would require you to write your own UART code, or alter the Arduino UART code, would be to operate the UART in 9-bit mode. You then have 0-511 instead of 0-255, so you can send your 8-bit data as per normal (with the 9th bit set to 0) and any control and protocol characters with the 9th bit set, so between 256 and 511.
Finally, you could halve your overall transmission speed by sending the data as ASCII-encoded HEX digits. That would be two characters (0-9,A-F) for each byte sent, leaving all the other characters (including \n) available for you to use as you wish.

Normally strings end with a '/0' item ... than /n is part of the string and can be handled as normally.
So you have to change the check to
if (inchar == '\0')

Also consider not adding a character every time to the string, since it will cause the string to be replaced/copied every time, which is not good for both performance and memory gaps resulting.
Instead make a predefined buffer if possible (if you know the maximum string length, don't forget to add +1 for the ending '0' character). In that case you can add the '\0' yourself or even better:
char inputString[101];
uint8_t inputStringLength = 0;

while(Serial.available())
{
    // get new byte
    char inChar = (char) Serial.read();
    inputString[inputStringLength++] = inChar;

    stringComplete = (inChar == '\0')
}

Serial.avilable() returns the number of bytes available in the buffer. One solution could be to try reading that many bytes at a time. This assumes that the buffer contains only entire strings.
Note: If your RS485 device sends multiple, non-delimited strings between buffer reads then this may not work as desired.
void serialEvent()
{
  int bytes = Serial.available();

  if ( bytes == 0 ) // empty buffer, bail
    return;

  for (; bytes > 0; bytes-- )
  {
    // get new byte
    char inChar = (char)Serial.read();
    inputstring += inChar;
  }
  stringComplete = true;
}


text:
Simple Ground circuit layout
I am making a circuit without using a PCB or perfboard and i am unsure if i am running the ground wire correctly.

I usually prototype on a breadboard with the ground all joining on the far right, is this the same concept? I wanted to know if this is the accepted  convention for running the ground back to the board.

For a basic circuit like this you don't need to worry terribly about the grounding details. It's when you have higher speed and more complex signaling that it really matters.

@IgnacioVazquez-Abrams My final circuit is utilizing 20 pins running 2 LEDs each in parallel on a blinking program. Does that fall into the "complicated" category or is that still on the simpler side? No motors, rotors, ICs, isensors, Etc

The only problem I see is running two leds at (looking at the resistor value) 20mA each on only one pin. 40mA is the absolute maximum rating of a pin. 20mA is generally advised. There is also a maximum current per section of pins (see datasheet). So depending on the pattern of lights, you might run into a limit there.

Consider using a LED driver chip instead, running the LEDs in series with a higher voltage.

Further to the above point. 20pins at 40mA (ie: all lights on) is 800mA which is more than the micro can safely source.

Just because i don't understand completely, if i use an LED driver with the arduino would that solve the mA limitations and if so how?

@Mazaryk I outlined that limit yesterday at the OP's other question. I wonder if we should try to keep the whole issue in one question or rehash it over in (now) three...

Hey @Ghanima, yea this circuit keeps bringing conversations back to the inevitable question of power. All i wanted to know was if the ground wire is run correctly which they answered here. I figured if i simplified the question, i could get it answered, but i suppose I really need to rethink this circuit if it keeps raising red flags.

Yes, based on basic electrical theory, you have the ground connected correctly.

source: Stack Exchange

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

sort: votes


text:
Error on sending AT+CWJAP_DEF commands to ESP8266
I am trying to send AT commands to ESP8266 to get connected with internet with the Wifi.
When I am sending AT and AT+RST command on serial monitor then I am getting OK and ready response which seems perfect.
Then I am sending AT+CWLAP to get list of available wifi networks which is also executing correctly.
AT+CWLAP

+CWLAP:(3,"Moto",-42,"a4:70:d6:7a:fa:6c",1,25,0)
+CWLAP:(4,"PRANJAL",-95,"1c:a5:32:3d:f5:c4",1,-16,0)
+CWLAP:(2,"VIHAN",-94,"c8:3a:35:2f:1d:81",1,-21,0)
+CWLAP:(3,"Tenda",-93,"c8:3a:35:20:a9:b1",9,-4,0)

OK

Then I sent AT+CWMODE? which is also perfect.
AT+CWMODE?

+CWMODE:1

OK

Now I am trying to connect ESP8266 with above listed Wifi with this command, it is sending an ERROR on serial monitor.

AT+CWJAP_DEF="Moto","reset1234"

Error
⸮=IRe"Moto","reset1234"

ERROR

Can anyone suggest me what could be the reason of this issue ?at

Don't cross post.

Alright! I just tried to connect with different wifi and it got connected with it. It was some kinda issue with mobile hotspot.

The source of such problems are mostly as under

Bad / loose wiring (power and communication)
software serial is not much reliable
Arduino serial monitor is not a user friendly way of testing out ESP modue

To solve wiring related problems for good check out this design.
To solve communication monitoring problems check out this solution
Use USB to TTL interface to connect ESP module directly to your PC without using an Arduino (find details here)

Based on the gibberish echo, the possible causes are:

Insufficient power. You need a source that can supply up to 300mA which is about the max consumption for the module. A good-sized capacitor across the ESP power rails (10uF maybe) wouldn't hurt.
Baud rate is too high. If you're using an Arduino as 'middle-man' and talking to the ESP8266 through a SoftwareSerial port, you're likely to face this sort of issue if the baud rate is as high as 115200; SoftwareSerial is unreliable at such rates.

I connected VCC and CH_PD to 3.3 V, should I connect GPIO0 and GPIO1 also to 3.3 V ? and ESP8266 baud rate is 9600

I connected GPIO0 and GPIO1 to 3.3V and your solution is not working :(

@Williams What solution? I didn't mention GPIO pins. I asked you to provide a better power source to it or reduce the baud rate. Which did you do?

My baud rate is already 9600 and VCC and CH_PD to 3.3 V. How I can provide better power? can you please suggest

@Williams How are you powering it at the moment?

I connected VCC and CH_PD of ESP8266 to 3.3 V of Arduino, GND to GND

@Williams Do you have an LM1117T regulator? Or any other 3.3V regulator?

Let us continue this discussion in chat.

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


text:
How to logically tell than an UNO is being, or about to be programmed
I have an MIDI application that uses the RX and TX serial interface.  When I program the UNO there is a collision between the on board programmer and the MIDI application RX serial port.  The MIDI shield provides a jumper to disconnect to prevent the collision during programming.
I would like to add a FET switch to open and close if I am programming, but it's not clear to me that there is a signal I can tap into on the UNO that indicates programming is about to start or that it has just finished.
I was thinking about using a pull up on a digital pin on the UNO that drives low when the program starts up. That might be the way to go, but I assumed that this must be a common issue with a common solution that I am just not finding on stack exchange.
Is there a standard logical way to tell that UNO is about to be programmed via the onboard USB port?

Your proposed solution is the normal method. A GPIO pin which is an "Activate Device" signal. It's pulled in one direction, the "inactive" direction, and you actively drive it in the other "active" direction in your program.


text:
OSX upload error: avrdude: ser_open(): can't open device "/dev/cu.mydev" : Resource Busy
I'm trying to upload the blink script to my unnamed Arduino-like board. However, the USB port appears to be busy.
This is all the output I get:
Archiving built core (caching) in: /var/folders/43/7_h5zwcs1csdr2dc635m1yq40000gp/T/arduino_cache_942504/core/core_arduino_avr_uno_51f02b7210b938436b779d1c032618e1.a
De schets gebruikt 928 bytes (2%)  programma-opslagruimte. Maximum is 32256 bytes.
Globale variabelen gebruiken 9 bytes (0%) van het dynamisch geheugen. Resteren 2039 bytes voor lokale variabelen. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "/dev/cu.mydev": Resource busy

I've tried all solutions I could find on internet, but they haven't solved my issue. The main difference with my error and online solutions/errors is that I only have this error. Other people experienced extra errors which enabled the debugging of the problem.
Can anyone help me please?

Not nearly enough information to answer this question.  Why are you using that particula device, for instance?

I think my available serial ports were insufficient or something. I installed the ch34* driver which allowed an additional device showing up. Here's the download: http://www.wch.cn/download/CH341SER_MAC_ZIP.html
Then I selected this port and I finally could upload.

If this is the answer, you should not have tagged your question "arduino-uno" as that board does not use a CH34x.  The erroneous tag and board description have been removed from your question, so that people with actual Arduino UNO boards do not mistakenly install inappropriate drivers as a result of reading your question/answer.

strangely it did solve my issue

If you have some random clone that uses a ch34x rather than the Arduino Uno you originally claimed, potentially it could.   But if your board has an ATmega8u2/ATmega16u2 on it, then you are mistaken in thinking this had anything to do with it.

I have a genuine Arduino Uno. Perhaps I changed something else in the process, but I can't recall. After installation of this driver, I had access to an additional port which worked.

Then this answer is wrong, misleading, and should be deleted so that it does not cause others to install inappropriate software, especially software that runs with kernel privileges.

I checked the readme file. I got the port by this installer. So this in fact solved my issue. You're right about the Arduino. I checked it on the site of the reseller and they in fact sell clones. So mine is not genuine. Thanks for the help. Would you recommend another solution than installing this ch34 driver, or is this the only way?

The solution might be bad in theory but it's good in practice. Worked for me, with a couple of different genuine boards and random ebay clones. But if you have a better suggestion @ChrisStratton, do please post it for us.

@stib -This answer is WRONG AND MISLEADING.  A CH340 drivers is of ABSOLUTELY NO HELP WITH GENUINUE BOARDS.  It can only help with cheap boards that use a CH340/CH341 chip.


text:
Arduino nano Serial port not recognized
First sorry for my bad english, not my native lenguage.
Today I started working on my Arduino nano (first time used). When plugged for the first time the "L" led started blinking, after that I tried to write a simple program but I noticed that the "Port" option on the Arduino IDE was Gray. So I couldn't choose the port. After that I searched A LOT but nothing seems to work.
While trying to test if the problem was the Arduino and not the PC, I make a simple circuit with 1 LED, 1 resistor of 1Kohm, and a breadboard. I connected the 5V pin to the LED and GNG to the other point, And when I did this the "L" LED stopped blinking forever. I am 100%  sure that I did not make a short circuit. ¿Maybe the breadboard is in a bad state?
Additional info:
-Windows 10.
-The port doesn't appear at Device manager (tried every port of my notebook).
-The "POW" led is ON when I plug the USB.
- The Arduino is a clone (chip CH340G).
So now I don't know if the problem is the port or if the Arduino Nano is dead because of a possible short circuit between 5V and GND pins.
thanks in advance!

Did you install the CH340G drivers?

I can't because the COM doesn't appear on Device Manager.

Not even in Unknown Devices ?

No. It doesn't appear at all.

Sounds like you most likely killed it. Maybe show how you wired the LED up with a photograph of it on your breadboard.

I can't show a picture, but I'm 100% that the connection was OK because that was my first fear so I watched closely and the 5V pin wasn't in the same line that the GND pin.

Maybe then it's just the curse of the cheap Chinese clone.

I assume you have tried another USB port and another cable, and tried something else in the USB port you had the Arduino in?

Yes, I tried all that.

And the results were that the board didn't wake up no matter which cable and port you tried, and the something else worked fine in the port you had been using?

Yes, I have an Arduino Uno and that works fine. When I plug the Nano The "POW" LED turns ON but nothing more.

Sounds like it may be fried. Possible that the CH340G has died.

Yes I think the same. Thanks for all your help !

I think your Arduino got short or the transmitter-receiver in it is damaged so the device manager cannot recognize the COM port.It once happened with my Arduino Uno. Try changing the USB cable.If it does not help your Arduino is damaged.


text:
POWER_MODE_IDLE wake on any input change?
I want to be able to put an Arduino to "sleep" but I want it to immediately resume if any panel tactile buttons are pressed.
The purpose is to try to minimize any digital noise in an nearby high gain analog circuit.
My guess at this point is that I want to put the Arduino into POWER_MODE_IDLE but it is less clear to me the best way to wake up.
How can I instantly wake up from POWER_MODE_ILDE if any input changes? I don't want to have to hold down a button or even use a specific input. Is there a "catch-all" interrupt that will react immedately to a change on any or on a large set of inputs?

Look for "pin change interrupts" (PCINT).

As I mention on my page about interrupts you can use pin-change interrupts on the Atmega328P to wake from the deepest sleep mode (SLEEP_MODE_PWR_DOWN).
Example code:
#include <avr/sleep.h>

const byte LEDLOOP = 8;
const byte LEDWAKE = 9;

ISR (PCINT1_vect)
 {
 // handle pin change interrupt for A0 to A5 here

 // toggle LED
 digitalWrite (LEDWAKE, !digitalRead (LEDWAKE));
 }  // end of PCINT1_vect

void setup ()
  {
  pinMode (LEDWAKE, OUTPUT);
  pinMode (LEDLOOP, OUTPUT);
  digitalWrite (A0, HIGH);  // enable pull-up

  // pin change interrupt
  PCMSK1 |= bit (PCINT8);  // want pin A0
  PCIFR  |= bit (PCIF1);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE1);   // enable pin change interrupts for A0 to A5

  }  // end of setup

void loop ()
{

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_mode ();

  // flash to indicate we got out of sleep
  digitalWrite (LEDLOOP, HIGH);
  delay (100);
  digitalWrite (LEDLOOP, LOW);
  delay (100);

  } // end of loop

This has the advantage of consuming very little power while asleep, and also waking on any pin (of an Atmega328P).
Running on 5V at 25°C you should only consume around 150 nA of current while asleep (on a "bare bones" board without USB chip, voltage regulator or power LEDs).
Other sleep modes may use more power but wake more quickly.

The Arduino can only be woken from sleep by a change on pins 2 and/or 3.

On the hardware front, the Arduino is equipped with two interrupt
  ports: digital pin 2 and 3. So the Arduino can sense those pins for an
  event to wake up and resume execution of code.

http://playground.arduino.cc/Learning/ArduinoSleepCode
However, the datasheet indicates that any pin can be used:
http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf Section 17. EXINT - External Interrupts

The External Interrupts are triggered by the INT pins or any of the PCINT pins.
  [...]
  The Pin Change Interrupt Request 2 (PCI2) will trigger if any enabled
  PCINT[23:16] pin toggles. The Pin Change Interrupt Request 1 (PCI1)
  will trigger if any enabled PCINT[14:8] pin toggles. The Pin Change
  Interrupt Request 0 (PCI0) will trigger if any enabled PCINT[7:0] pin
  toggles. The PCMSK2, PCMSK1 and
  PCMSK0 Registers control which pins contribute to the pin change
  interrupts.

Pin change interrupts can be used as well. Even for deeper sleep modes with disabled IO clock or with stopped oscillator.


text:
Using ALL the analog pins on Mega for Servo
I wish to use ALL the Analog pins on a Mega2560 R3 to control Servo's, all is well up to and including A9, but from there on nothing. {sound familiar} this is apparently not a new problem. I have tried Servo.h and MegaServo.h but still no luck, does anyone have info on a library that will do this or a method to get around it........all the pins on the end buss are used for other purposes and are not available. I can post the code, but first just asking the general questions. Thanks Doug

OK..Solved...tried a library I had previously discarded for another project but it works with this situation..SoftwareServo ....(had also tried versions of Servo and MegaServo with no luck) I have attached a proven sketch that shows the method using arrays (as i have 16 servos to control) hope this is of use to others.
    /*This sketch will enable you to use ALL of the Analog pins on a Mega2560 to control a Servo
 * it uses the Arrays and the Softwareservo.h as the other Servo libraries do not support
 * Mega Analog above A9
 * this is the only method i have found that works
 * hope this is of use to others.
 */
#include <SoftwareServo.h>

SoftwareServo servos[16];  // create servo object to control a servo

int pos=0;
int servoPins[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,A13,A14,A15};                    //servo pin numbers
int servoPosMin[] = {80,80,80,80,80,80,80,80,80,89,80,81,80,70,80,45};                        //servo lower setting to suit individual servo
int servoPosMax[] = {100,100,100,100,100,100,100,100,100,100,100,100,100,110,100,160};        //servo upper setting to suit individual servo
boolean refresh = false;  // toggle refresh on/off
int m = 0;
int p = 0;
void setup()
{
  Serial.begin(115200);
  for (m=0;m < 16;m++) {
      // attaches the servo on pin to the servo object
    servos[m].attach(servoPins[m]);
      // init angle of servo inbetween two limitations
    servos[m].write(((servoPosMax[m]+servoPosMin[m])/2));
    Serial.println(m);
    delay(10);
      SoftwareServo::refresh();
  }
}
void loop()
{
  for (p=0;p < 16;p++) {

    for (pos = servoPosMin[p]; pos <= servoPosMax[p]; pos += 1) { // goes from 0 degrees to 180 degrees
      servos[p].write(pos);                                       // tell servo to go to position in variable 'pos'
      delay(15);                                                  // waits 15ms for the servo to reach the position
      Refresh();
  }
    for (pos = servoPosMax[p]; pos >= servoPosMin[p]; pos -= 1) { // goes from 180 degrees to 0 degrees
      servos[p].write(pos);                                       // tell servo to go to position in variable 'pos'
      delay(15);                                                  // waits 15ms for the servo to reach the position
      Refresh();
    }
  }
}
void Refresh() {
  refresh = refresh ? false : true;                             // set refresh one time / 2
  if (refresh) SoftwareServo::refresh();
  Serial.print("Servo Number = ");
  Serial.println(p);
  Serial.print("  Angle =  ");
  Serial.println(pos);
}

There seems to be something quirky about this, the line "servos[m].write(((servoPosMax[m]+servoPosMin[m])/2));" in Setup() accepts the value but doesn't execute until it runs the void.loop() at the first servo.write command. How can I preset the servo position in void.setup() with this action the way it is??

There is a relatively easy fix, you need to change one symbol in the library code, in Servo.h:
Change
typedef struct  {
   uint8_t nbr        :6 ;
   uint8_t isActive   :1 ;
 } ServoPin_t   ;

To
typedef struct  {
   uint8_t nbr        :7 ;
   uint8_t isActive   :1 ;
 } ServoPin_t   ;

Pull request here: https://github.com/arduino-libraries/Servo/pull/11

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


text:
Programming Arduino Micro via RX/TX
I can't access my Arduino Micro's USB programming port when it's in my project. I want to reroute the RX and TX pins outside to a serial-to-usb adapter.
I have this on hand from a while ago. I found the RX and TX pins in the serial connector and I connected them to the RX and TX pins of the Arduino as well as GND but when I try and program the device nothing happens. I usually get an open port error or something like that but the programming LED on the adapter doesn't light up. Conversely if I try using the Basic Stamp software I at least get a programming LED to light up on the adapter.
Do I need an FTDI breakout instead? Or am I wiring something wrong?

Well, RS-232 signals are not compatible with 5V ttl logic of Arduino.

how is the device i mentioned any different than say and ftdi breakout except for a different connector?

Clearly, you need another decoder on the micro side to convert the RS-232 to normal ttl signal.

Is there any provision for RESET or you manually do it while uploading?

Yes I wired in the reset. The device actually resets and I see the programing led flash briefly but nothing happens. Its strange, because I can program the basic stamp just by connecting the rx and TX. I feel like your statements must hold water in that the arduino can't interface somehow.

Have a look at this link

first of all, the ATmega32u4 bootloader only listens on its native USB

RS-232 logic uses a negative voltage typically from -3 to -25V to represent a logical high and a positive +3 to +25V to represent a low. On the flip side TTL used on the AtMega uses +5V or +3.3V as a high (or VCC) and 0V as a low. Read more
Other than that the signals are the same logically so all that is needed is to invert the RS232 from -/+ ~12V to 0-5V using a simple converter.
Possibly the easiest approach is to use another Arduino Uno as a programmer, which needs 3 pins, TX, RX, and RESET. This tutorial seems to have some success. Check out "programming an Arduino with another".

I would say that an: ftdi->USB board, Bluetooth board or ICSP programmer is much easier than using yet another Arduino. (The Bluetooth one is tricky, but worth it if you don't like cables).

yes you can, use a FTDI 232 USB TO SERIAL  then set the Arduino IDE to the board you will be programing, and the serial port the FTDI RS232 Programmer is on.
connect the two rx to tx, and tx to rx, also the vcc of programmer to Arduino 5v pin.
then press and hold the reset button, and upload "regular".
The trick is to let go of RESET just after it finishes compiling, and it will get programed.
i think between 1-2 seconds after it finishes compiling and the compiling line just turned all green.
This is also how wireless programmer work using a Bluetooth module. I tried using the DTR pin to reset, but that did not work for me.

it is a Micro so ATmega32u4 with native USB. the bootloader doesn't listen on Serial1

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


text:
Make lights come on and off depending on which button is pressed
Imagine a strip of LEDs with O being HIGH and X being LOW.
X O X O X
Now if I pressed the button below the second O and wanted it to switch the last two LEDs (4th one to LOW and 5th to HIGH or any opposite value of what it was), but if I pressed the first X wanted it to switch that one HIGH, the second one LOW, and the third HIGH.
I want to continue this type of pattern where each button press will result in two or three of the LEDs changing their effective state.
How might I achieve this? I have researched using the modulo function and can only get it to work every other click of a button. I have also tried using a pullup function and couldn't get it to work at all.
Can someone please just point me in the right direction?

Show your work please :)

I am working on it still.  So far I can get one to change and when I work on a second button it changes the first back to the original state.

I want to continue this type of pattern where each button press will result in two or three of the LEDs changing their effective state.

I'll assume there are nLED LEDs and buttons, and that the buttons are momentary buttons and need debouncing.  I presume you have one button beneath each LED, numbered say 0 to nLED-1, and that the two or three LEDs that will change when button k is pressed have numbers  k, k+1, and possibly k+2.
To simplify the coding, create an array (or a bit map), say Lsts, with nLED entries, to represent the current state of LEDs, and a similar array, say Bsts for button statuses, and an array of bytes bounce to track debouncing status.
On each pass through loop(), use a for loop to read each eligible switch.  A switch with a nonzero bounce entry is debouncing and doesn't get read.  If a switch is read and it changes, update the LED statuses in  Lsts and at ports.  For example:
enum { nLED=5, debouncePasses=50 };
byte Lsts[nLED]={0}, Bsts[nLED]={1,1,1,1,1}, bounce[nLED]={0};
const byte Lpins[nLED] = { 3,4,5,6,7 };
const byte Bpins[nLED] = { 8,9,10,11,12 };
//... etc

void setup() {
  for (byte i=0; i<nLED; ++i) {
    pinMode(Lpins[i], OUTPUT);
    // Buttons will have negative logic, hi for open, lo for pressed
    pinMode(Bpins[i], INPUT_PULLUP);
  }
  // ... any other initialization ...
}
void loop() {
  for (byte i=0; i<nLED; ++i) {
    // See if button is eligible for reading, and if it changed
    if (bounce[i]) {
      --bounce[i]; // Decrease bounce pass counter
    } else {
      if (digitalRead(Bpins[i]) != Bsts[i]){
        // Yes,  it's eligible and it changed
        bounce[i] = debouncePasses; // Set button's debounce counter
        if (Bsts[i]) { // Test if switch was pressed vs released
          // Toggle the button's light and the next one or two lights
          for (int j=i; j<nLED && j<i+3; ++j) {
            Lsts[j] = !Lsts[j];
            digitalWrite(Lpins[j], Lsts[j]);
          }
        }
        Bsts[i] = !Bsts[i]; // Toggle button state
      }
    }
  }
  // ... any other stuff
  delayMicroseconds(500); // Delay for bounce-pass timing
  // alternately, instead of delayMicroseconds, sleep until timer tick
}

Edit 1:  If there are more LEDs than buttons, then use separate constants for the counts, adjust the initializations, etc.  For example:
enum { nButton=5, nLED=6, debouncePasses=50 };
byte Lsts[nLED] ={1,0,1,0,1,0};
byte Bsts[nButton]={1,1,1,1,1}, bounce[nLED]={0};

//... etc

void setup() {
  for (byte i=0; i<nLED; ++i) {
    pinMode(Lpins[i], OUTPUT);
    digitalWrite(Lpins[i], Lsts[i]);
  }
  // Buttons will have negative logic, hi for open, lo for pressed
  for (byte i=0; i<nButton; ++i) {
    pinMode(Bpins[i], INPUT_PULLUP);
  }
  // ... any other initialization ...
}

In loop(), change the initial for from for (byte i=0; i<nLED; ++i) to for (byte i=0; i<nButton; ++i).  This will work ok if there is an extra LEDs after the LEDs that line up with buttons.

Edit 2:

Why when using an array doesn't the arduino recognize the HIGH or LOW state of an led? I tried adding this simple code:
if (42 && 44 && 46 && 48 && 50 == HIGH){
digitalWrite (ledWin, LOW); } else {digitalWrite (ledWin, HIGH);}

Evidently you want to test if all the LEDs are on, and apparently the numbers 42, 44, ... 50 are supposed to somehow represent LED states.
However, numbers like 42, 44, ... are constant values and cannot properly represent the value of something that varies.  The condition in that if statement will always evaluate to the same value, false, as follows.
According to the C/C++ standard, a condition like 42 && 44 && 46 && 48 && 50 == HIGH consisting of a series of terms separated by && operators will be evaluated left to right until either one is false (making the whole expression false) or all are true (making it true).  (For example, see the Remarks section of Logical AND Operator: &&.)
In this case, 42 is non-zero, hence true.  Next, 44 is true, 46 is true, and 48 is true.  But 50 == HIGH is false – the value of HIGH is 1, and 50 is not equal to 1.  Therefore the whole expression is false.
A better approach to finding out if all the LEDs are on or off is to test the values of Lsts[] entries.  For example, you could add them up, and then see if the sum is equal to 0 (all off) or equal to nLED (all on):
byte nOn = 0;
for (byte i=0; i<nLED; ++i) nOn += Lsts[i];
digitalWrite (ledWin, nOn < nLED);

That will set the ledWin pin if not all of the LEDs are on, else will clear it.

Can an array be declared as something else later in a sketch?  ie; When Lsts[nLED]= {1,1,1,1,1}, can that be used to set one additional pin to a high state rather than declaring new variable for the same purpose?

@upstartlilevil, yes, you could treat an extra LED and LED initialization as shown in edit 1 of answer.  However,  re “Can an array be declared as something else later in a sketch?”, it can be used as something else (which can make code difficult to understand and maintain) but cannot be re-declared as something else in the same scope as the original declaration.  Note, if the additional pin gets treated about the same as other LED pins, it makes sense to handle it via the loops and code for other LED pins; but if it's treated differently, just set up a simple var for it.

@jwpat7 I understand how to do that and had actually already made it 5 buttons and 6 leds, I want a "prize" so my kids can see that when they get it correct something happens, a green led comes on and a relay for a magnet release a matchbox car down a track or something like that.  Adding an led in this way just makes it an additional led.  My question is then; Why when using an array doesn't the arduino recognize the HIGH or LOW state of an led?  I tried adding this simple code:  if (42 && 44 &&  46 && 48 && 50 == HIGH){
digitalWrite (ledWin, LOW);
}else{digitalWrite (ledWin, HIGH);}

@upstartlilevil, see edit 2

Can someone please just point me in the right direction?

what is "right" is highly subjective. I would consider a good solution to be one where the functionalities desired is broken down into natural modules that are then integrated to perform the desired functions. By that (highly subjective) standard, the solution posted earlier would be a poor one -> due to its tightly coupled / inter-mingled approach.
if I were to take a shot at this, I would consider the implementation below:
  key_state = read_keys(); //read keys / buttons, with or without debouncing
  led_process(key_state);  //process the key_state, and light up / off leds based on key_state

Essentially, you scan the keys / buttons, and based on that, turn on / off the leds.
All you need to do after that is to implement the individual functions based on your particular hardware design, or even software approaches: for example, read_keys() can be implemented in the isr, as can led_process().
A solution like this is highly portable: it works on pretty much anything that supports a C compiler, and is implementation-independent: the logic holds true, and all you do is to change the two functions to perform different kinds of lighting.
To me, modulizing your code is a huge advantage for a high-level language like C, and vital in taking on a real life project of moderate complexity.


text:
Connecting a 5v dc fan to ultrasonic sensor
I am currently doing a simple uni project where i want the distance read by an ultrasonic sensor to control the speed of a dc 5v fan. I have attached a schematic of how i think i can link the ultrasonic sensor and fan components in order to achieve my main goal. Please tell me if this circuit is right or wrong and give some helpful feedback, thank you!

It's wrong.
A fan is a motor. A motor is a power hungry inductive device.
Just like any other motor or similar device (such as a relay or solenoid) you cannot drive it directly from the Arduino. Instead you need (at the very least) a transistor to switch a higher current and a diode to absorb back EMF.

Thank you for telling me it was wrong. Would like to know where i could possibly plop this transistor and diode.

The same way as you would for any other inductive device such as a relay (like I am sure I mentioned). There's a billion and one tutorials telling you how (and that's not an overstatement).


text:
Trying to send .wav files between NodeMCU
Im trying yo send wav files between two nodeMCU. My setup is like this
uSD Card Module -> Arduino Mega -> Node MCU
So this is my setup, where I have 4 devices like this. One will serve as the central network(where I called it "server") where it will create an access point for the 3 other devices("modules") to connect to. The server will send data by using UDP so it can broadcast to the three modules simultaneously.
I'm able to send .txt files which is stored on the uSD module. Pass the .txt file contents to the nodeMCU through serial port, then recieve it on the other NodeMCU which will then send the data to the Arduino Mega also through serial port and will store it on its uSD Shield.
When I would try .wav files. It is able to send the whole .wav file to the NodeMCU from Arduino Mega (since .wav files are too big, I divide the .wav files into sets since the serial port can't handle too large data being sent/recieved. But when it would send the data from the nodeMCU to the other nodeMCU there are parts which are not being sent. When I try to observe what are not being sent, its part of the WAV Header Format, so it needs to be sent. Ill be posting the codes Im using to send and recieve and also a screenshot/example of the wav file as it is being sent.
Server's Arduino Mega Sending data to NodeMCU Serially:
void sendFiletoSerial(char fileSend[12]){
  Serial.println();
  Serial1.println();
  if (!myFile.open(fileSend, O_READ)) {
    sdf.errorHalt("opening test.txt for read failed");
  }
  Serial.print(fileSend);
  Serial.print(" Size:");
  Serial.println(myFile.fileSize());

  Serial1.print(fileSend);
  Serial1.print(" Size:");
  Serial1.println(myFile.fileSize());
  delay(1500);
  fileofSize = myFile.fileSize();
  myFile.close();
  // read from the file until there's nothing else in it:
  char data;
  long int index=0;
    for(int i =0; i<(fileofSize/tempSize);i++){
    if (!myFile.open(fileSend, O_READ)) {
    sdf.errorHalt("opening test.txt for read failed");
  }
    //Serial.println(i);
    myFile.seekSet(index);
  for(int j =0; j<tempSize;j++){
  int temp = myFile.read();
 intTempFile[j]=temp;
  index++;

  }
  for(int k =0;k<tempSize;k++){
  Serial1.write(intTempFile[k]);
  }
    myFile.close();
    delay(1500);
  }
  Serial.println("LAST SET OF DATA");
    if (!myFile.open(fileSend, O_READ)) {
    sdf.errorHalt("opening test.txt for read failed");
  }
    myFile.seekSet(index);
    int lastSetSize=fileofSize-((fileofSize/tempSize)*tempSize);
    Serial.println(fileofSize-((fileofSize/tempSize)*tempSize));
  for(int j =0; j<lastSetSize;j++){
 int temp = myFile.read();

 intTempFile[j]=temp;
  index++;

  }
  Serial.println();
  Serial.println("tempFile");
  for(int k =0;k<lastSetSize;k++){
  Serial1.write(intTempFile[k]);
  }
    myFile.close();

}

Server's code for Sending from NodeMCU to other Node MCU:
    if (Serial.available()) {
          byte readStr[100];
        Serial.readBytes(readStr,100);
       // Serial.write(readStr[i]);
        }

         port.beginPacket("192.168.4.255",2390);
         for(int i =0; i <100; i++){
        port.write(readStr[i]);
         }
         port.endPacket();
      }

Module's Code for NodeMCU to recieve data from other NodeMCU:
void dumpMode(){
  while(1){
    int packetSize = port.parsePacket();
      if (packetSize) {
        port.read(packetBuffer, fileSentSize);
        Serial.write(packetBuffer);

  }
  if(Serial.available()){
    String reply = Serial.readString();
    if(reply == "STOP"){
      break;
    }

    }
  }
}

Server's NodeMCU Sent Data:
RIFFäN  WAVEfmt      À]  À]    dataÀN  €€€€€€€€€€€€€€€€€€€€€€€€

Module's NodeMCU Recieved Data:
RIFFäN€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€

Is there something im doing wrong thats why NodeMCU is not either sending or recieving every content of the wav file?
Thank you for those who will help out. :)

You could just program the NodeMCUs and skip the Megas; they have sufficient pins to drive an SD card. There's so much wrong with your code: opening and closing the same file so many times and then having to seek for every chunk because of the previous nastiness, writing and reading bytes singly instead of just passing in a buffer, among others. I also hope you know that you didn't send only the WAV data to the transmitting NodeMCU; there's a bunch of stuff (CRLF, file size, etc) before that.
Your particular problem's most likely the fact that your Mega "server" is just sending chunks continuously to the NodeMCU, never minding if the latter is reading them quickly enough that its serial buffer doesn't overflow, especially considering you're sending data over the network between chunks. You should also note that UDP isn't exactly the most reliable protocol; it's connection-less and so packets will be lost. It's generally used if packet loss isn't a big deal (in your case, it is) or if upper layers implement error control.
What you need to implement is a way for each party to confirm that they've received the next chunk before the their sender transmits the next. The Mega needs to wait for a 'go-ahead' from the NodeMCU before sending the next chunk; for instance, the NodeMCU can reply each chunk with the number of bytes it actually read, so you can know if you should reduce your chunk size to not overwhelm the NodeMCU buffer.
The packets sent over the network also need to be tagged with a sequence number (because of aforementioned error control). The NodeMCU at the receiver needs to acknowledge the packet it received each packet, perhaps by sending that packet's number to the transmitting NodeMCU. This will help ensure all packets are received and in order. Or you could just use TCP which already implements these and more.

Actually I also have an RFID Scanner connected to the Mega and also playing some WAV Files with the arduino, thats why I still need to use an Mega + NodeMCU.
The "CRLF, file size, etc" you've mentioned is the 44byte Wav Header Right? I am also trying to send that but since its that part thats not being sent, it cant create the wav file completely.
I chose UDP over TCP since I need to broadcast the data between the 3 modules. Based from my researches UDP can implement broadcast while TCP can' but if im wrong please do tell me.

@boomacoh The stuff I mentioned is not part of the official header unless you mean its your own customized header to help parse the data. TCP isn't built for broadcast yes, but if you use UDP, you'll have to find a way to handle lost packets.


text:
Arduino Nano and ESP8266
I am trying to use Arduino Nano with ESP8266 (01). I tried to follow a lot of online tutorial with no result.
In particular this one http://www.martyncurrey.com/arduino-to-esp8266-serial-commincation/.
I think connections between Arduino Nano and ESP8266 are fine, when I upload the code on Arduino the red led on the ESP8266 turns on, I set the Arduino Monitor to 9600 BAUD and try to send command like "AT" but I got not reply from ESP8266. I also tried to switch to 115200 BAUD with no result too.
I don't if is something wrong or ESP8266 is damaged. Is there any tutorial that you may suggest?
Thank you.

The Serial Monitor's baud rate must match what you have in
Serial.begin(9600);

The EDP8266's baud rate is specified in the line
ESPserial.begin(9600);

and that is the one you need to change to try different baud rates with the ESP8266. The newer AIThinker firmwares default to 115200 baud, not 9600 baud.
Be warned, though, that SoftwareSerial isn't that great at 115200 baud - you tend to get some data corruption. It is best to change the baud rate to 9600 baud with
AT+CIOBAUD=9600

I'd also recommend investing in one of the ESP-01 programming boards from eBay. Make sure you get one of the ones with a switch on it that switches between programming and UART mode. Something like this one. It makes working with the ESP-01 much simpler - you can directly use your PC to set it up right for your system, and even upgrade the firmware (or program it directly with a sketch from the Arduino IDE if you install the right core) with minimum hassle.

many ESP's default to 74880 baud

Thank you a lot, I solved setting  ESPserial.begin(115200);


text:
Make RFID Tag as a variable
I want to make RFID Tag as a variable, and push it to the web server. But I struggle to do the Serial.read function.
Any solutions?
Here is my code

#include <ESP8266WiFi.h>
#include <SPI.h>
#include <MFRC522.h>

/* wiring the MFRC522 to ESP8266 (ESP-12)
SDA(SS) - D4 (GPIO2)
SCK - D5 (GPIO14) (hw spi)
MOSI - D7 (GPIO13) (hw spi)
MISO - D6 (GPIO12) (hw spi)
IRQ -
GND - G
RST - D3 (GPIO0) (FLASH)
3.3V - 3V
*/

#define RST_PIN D3 // RST-PIN für RC522 - RFID - SPI - Modul GPIO5
#define SS_PIN D4 // SDA-PIN für RC522 - RFID - SPI - Modul GPIO4

const char *ssid = "Keluarga"; // change according to your Network -
cannot be longer than 32 characters!
const char *pass = "batikpekalongan11"; // change according to your
Network

String a;

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
WiFiServer server(80);

void setup() {
Serial.begin(115200); // Initialize serial communications
delay(10);
Serial.print(F("Booting...."));

SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522

WiFi.begin(ssid, pass);

int retries = 0;
while ((WiFi.status() != WL_CONNECTED) && (retries < 10)) {
retries++;
delay(500);
Serial.print(".");
 }
if (WiFi.status() == WL_CONNECTED) {
Serial.println(F("WiFi connected"));
}

Serial.println(F("Ready!"));
Serial.println(F("Scan for Card and print UID:"));
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

// Start the server
server.begin();
Serial.println("Server started");
  }

void loop() {
 // Check if a client has connected
 WiFiClient client = server.available();
 if (!client) {
 return;
 }

 // Look for new cards
   if ( ! mfrc522.PICC_IsNewCardPresent()) {
delay(50);
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
delay(50);
return;
}
// Show some details of the PICC (that is: the tag/card)
  Serial.print(F("Card UID:"));
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  a = Serial.readString();
  Serial.println("kakak");
  Serial.println(a);

// Wait until the client sends some data
Serial.println("new client");
 while(!client.available()){
 delay(1);
 }

// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();

// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); //  do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");

client.print("Card UID:");
client.print(a);
client.println("</html>");
//delay(1);
//Serial.println("Client disonnected");
//Serial.println("");
}

I've add my code to the the questions. Thank you~

What you already have on the Serial.read ? I cannot see a line. And what you try to read?

What makes you think Serial.read() has anything at all to do with the card data?

I'm sorry if my code didn't look so good. I'm still a beginner in this. I'm trying to read the RFID tag. I thought with Serial.read(), I could read the serial data on serial monitor, from the tagged RFID Card and transform it into a variable. My purpose is to send the RFID tag data to the web server. ~Thankyou (sorry for my bad english)

Reading from the serial port does not read back what you wrote to it. It looks like the data you want is in mfrc522.uid.uidByte, so try to get that into a. You'll need to format it - you might find clues in your dump_byte_array function.


text:
NRF24L01 only receiving zeros
I'm attempting to transmit very simple data across some NRF24l01 modules for testing purposes, and I've been following a YouTube guide.
Here is my code:
Trasmitter:
#include "RF24.h"
#include <SPI.h>

RF24 Radio (7, 8);
byte address[][6] = {"0"};
struct package{
   int on = 1;
};

typedef struct package Package;
Package data;

void setup() {
  Serial.begin(9600);
  delay(1000);
  Radio.begin();
  Radio.setChannel(118);
  Radio.setPALevel(RF24_PA_LOW);
  Radio.setDataRate(RF24_250KBPS);
  Radio.openWritingPipe(address[0]);
  delay(1000);
}

void loop() {
  Radio.write(&data, sizeof(data));

  Serial.println("Data sent:");
  Serial.println(data.on);
  delay(1000);
  }
}

Receiver:
 #include "RF24.h"
 #include <SPI.h>

 RF24 Radio (7, 8);
 byte address[][6] = {"0"};
 struct package{
    int on = 1;
 };

 typedef struct package Package;
 Package data;

 void setup() {
   Serial.begin(9600);
   pinMode(2, OUTPUT);
   delay(1000);
   Radio.begin();
   Radio.setChannel(118);
   Radio.setPALevel(RF24_PA_LOW);
   Radio.setDataRate(RF24_250KBPS);
   Radio.openReadingPipe(1, address[0]);
   Radio.startListening();
   delay(1000);
 }

 void loop() {
   while(Radio.available()){
     Radio.read(&data, sizeof(data));
     if(data.on == 1){
       digitalWrite(2, HIGH);
     }
     else if(data.on == 0){
       digitalWrite(2, HIGH);
     }
     else{
       digitalWrite(2, LOW);
     }
     Serial.println(data.on);
   }
   while(!Radio.available()){
     Serial.println("Error");
   }
   delay(1000);
 }

When I run the code on each respective unit, I receive only zeros on the receiver. Since I don't see where data.on could get set to zero in my code, I'm assuming there is a communication issue somehow between the two modules, even though Radio.available() is functioning properly.
Am I missing something obvious?

I would try it without the structs.

Are they both Unos? Could be a packing issue if one is a 32-bit MCU. You realize pin 2 is set whether data.on is 1 or 0?

@TisteAndii, Im transmitting with an orginal Uno and receiving with a knock-off Mega2560. Is that a cause for concern? Also, pin 2 is just an led that I was using for debugging. I am reading the serial port for the actual value.

Well, they're both 8-bit CPUs. So packing shouldn't be an issue. Still print the values of 'sizeof(data)' for each MCU to confirm they're the same. Also I'd advise that you add more characters to your address...remember reading the module has problems with 2 bytes or less.

@TisteAndii, sizeof(data) is the same on both ends, and changing the address to a larger number doesn't resolve the issue either. Another interesting note, Radia.available is returning true even when the sending module is not powered on...
Sorry for the delayed response, busy life

What new address did you use? Use 3 bytes at least.

@TisteAndii, I used 888. I would assume that would be 3 bytes, but I don't actually know how you determine byte length of a number.

@Wilson The amt of memory the number occupies depends on its type. It should take up at least 2 bytes assuming you assigned it to an integer type variable. Update your post to show how you used the new address. Or merely use "uint64_t address = 0xdeadbeef" so you get a 4-byte address.

@TisteAndii, I figured it out! thank you so much for your help, the issue turned out to be that the SPI pins on the MEGA are assigned differently than the UNO, and the code was actually working the whole time. I cant thank you enough for helping me, even if it turned out to be in vain.

@Wilson please add an answer stating how you fixed this and accept it: this way this is not anymore reported as an "unanswered question"

The OP wrote:
The issue turned out to be that the SPI pins on the MEGA are assigned differently than the UNO, and the code was actually working the whole time. I cant thank you enough for helping me, even if it turned out to be in vain.


text:
Major difference between DTR signal and RTS signal?
I actually had a doubt about what is the difference between the RTS signal and DTR signal ?
I already know this that the DTR signal is used to auto reset when we use Arduino and similar MCUs. Can anyone say what is the major difference between these signals and what is their active state ?

Electrically they are both the same. The difference is what they are used for.
DTR means Data Terminal Ready and indicates that the connected device is ready to receive data.

Data Terminal Ready (DTR) is a control signal in RS-232 serial communications, transmitted from data terminal equipment (DTE), such as a computer, to data communications equipment (DCE), for example a modem, to indicate that the terminal is ready for communications and the modem may initiate a communications channel.

RTS means Request To Send and indicates to the connected device that it wants to send data.

The DTE asserts RTS to indicate a desire to transmit to the DCE, and in response the DCE asserts CTS to grant permission, once synchronization with the DCE at the far end is achieved.

Basically DTR is used to indicate the presence of some equipment, and RTS is one half of hardware flow control (along with CTS) to start and stop communication.
On USB communication (e.g., using FT232 USB to UART adaptor, etc) the meaning is less clear. DTR is asserted when the port is opened (usually) and RTS is most likely not asserted at all. It's at the whim of the operating system and/or the driver whether DTR is automatically asserted or not, and whether RTS is even implemented.

I'd only add that the FTDI cables (at least the ones I have, from two different vendors) bring out CTS and RTS and assert RTS when the port is opened.

@Majenko Some devices such as an ESP device really needs DTR and RTS signal so how do they communicate through UART ICs. Do they both work the same ?

Very few devices these days use RTS and CTS for anything. Many mcus don't even have them. They were used more when devices couldn't keep up with the speed of serial communication. Now everything is so fast and serial is so slow CTS and RTS are almost redundant.

DTS and RTS are used on esp8266 boards with USB (Wemos, NodeMcu) to reset the board and to set io 0 low for bootloader mode. You can see it in source code of esptool.py. Sometimes you want a reset without going to bootloader mode.
RTS = either CH_PD/EN or nRESET (both active low = chip in reset
DTR = GPIO0 (active low = boot to flasher)

As a counter point, industrial systems utilize the UART protocol at much higher rates - 10 Mbits for example.   RTS/CTS can prove very useful when a large data set is being received at a higher rate.  We have clients using LVDS and RS-485 IO types for the higher speeds. DTR/DSR is occasionally used to see if the other equipment is on-line but this signal pair is in the rare to use category.


text:
l293d is not able to drive two 300 rpm motors simultaneously
I am using l293d in a line follower but recently I am facing a problem. my l293d motor driver is not able to power 2 300 rpm motors simultaneously while with one of the motors at a time it works perfectly fine. Earlier it used to drive both the motors at optimal desired speed but recently its posing the above mentioned problems. I have tried replacing the Motor driver and Arduino itself but nothing worked and I am still facing the problem.

What is your power source, is it able to supply the current for 2 motors? The L293d with proper heatsinking should supply .6A per channel which seems like it should be sufficient for a robot under minimal load. I would check the batteries!

yeah the power source is just  fine .. I use a 12V-1A power adapter from the beginning . Earlier it worked just fine but recently this whole arrangement just got messed up with the motor driver failing to drive the 2 motors.

Do you have an earlier revision of the code? Could it be something software related?

I sense the code is all fine because the motor driver isn't able to drive the two motors simultaneously even when I directly connect them to the l293d outputs without taking any inputs from the Arduino .

Please post your code. I have seen this problem before, the OP claimed that it was a power/board problem and it turned out to be a bug in the code.

@SomitSinha Please also post your wiring/circuit diagram. You can either use the inbuilt circuit tool or you can draw it using Fritzing.

Check if both channels are working in either direction individually.
Check the current draw under the load per motor using an Digital Multimeter as an Ammeter function.

The L293 is designed to provide bidirectional drive currents of up to 1A at voltages from 4.5V to 36V.
600mA per channel for L293D

As long as your motors at drawing more than 600mA per motor, it should work fine.

Check your power supply with a multimeter. Look out for voltage drops under load, or similar problems.
Also, make some tests with another power supply in order to find out if the one you're currently using is faulty or not. You say you've tried replacing the motor driver and the arduino, but not the power supply.


text:
RFID+Fingerprint sensor code
I'm trying to create a security door system that uses an RFID and fingerprint sensor (Adafruit) to allow/deny access to a door. I have the fingerprint sensor and RFID hooked up to an LED, but the code isn't working very well. I want the LED to light only and only when both fingerprints and RFID are verified. Here is my preliminary code.
//HEADERFILES
#include <SPI.h> //rfid
#include <MFRC522.h>//rfid
#include <Adafruit_Fingerprint.h> //FINGERPRINT
#include <SoftwareSerial.h> //FINGERPRINT
#include<stdint.h> //FINGERPRINT

//rfid settings
#define RST_PIN         9          // rfid pin 9 RST_pin
#define SS_PIN          10         // rfid pin 10 SS_pin
MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
String read_rfid;
String ok_rfid_1 = "cbb427b2"; //white card
String ok_rfid_2 = "0ebb14f39"; //blue key chain

//fingerprint settings
int getFingerprintIDez();
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino  (YELLOW wire)
SoftwareSerial mySerial(2, 3);
//activates serial communication on pin 2 & 3
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

//output garage door pin
int door = 7; //motor to door

void dump_byte_array(byte * buffer , byte bufferSize) { //why so important
  read_rfid = "";
  for (byte i = 0; i < bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
}

void setup() {
  //RFID setup
  Serial.begin(9600);
  // Initialize serial communications with the PC
  while (!Serial);
  // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  finger.begin(57600);
  SPI.begin(); // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 RFID
  pinMode (door, OUTPUT);
  //FINGERPRINT setup
  {
    while (!Serial);  // For Yun/Leo/Micro/Zero/...
    if (finger.verifyPassword()) {
      Serial.println("Found fingerprint sensor!");
    } else {
      Serial.println("Did not find fingerprint sensor :(");
      while (1);
    }
    Serial.println("Waiting for valid finger...");
  }

}

// OK success!

p = finger.image2Tz();
switch (p) {
case FINGERPRINT_OK:
  Serial.println("Image converted");
  break;
case FINGERPRINT_IMAGEMESS:
  Serial.println("Image too messy");
  return p;
case FINGERPRINT_PACKETRECIEVEERR:
  Serial.println("Communication error");
  return p;
case FINGERPRINT_FEATUREFAIL:
  Serial.println("Could not find fingerprint features");
  return p;
case FINGERPRINT_INVALIDIMAGE:
  Serial.println("Could not find fingerprint features");
  return p;
default:
  Serial.println("Unknown error");
  return p;
}
}

//DOOR/OUTPUT PIN PROPERTIES CHANGE TO REFLECT HOW FAST AND HOW LONG MOTOR     PULLS DOOR USING DIGITALWRITE; BREAK..   //USING LED FOR NOW

void open_door() {
  digitalWrite (door, HIGH);
  delay (2000);
  digitalWrite (door, LOW);
}

void loop() {
  // RFID LOOP SETTINGS                                                   `
  if ( ! mfrc522.PICC_IsNewCardPresent()) {     // Look for new cards
    return;
  }
  if ( ! mfrc522.PICC_ReadCardSerial()) {       // Select one of the c ards
    return;
  }
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println(read_rfid);
  // FINGERPRINT LOOP SETTINGS

  getFingerprintID();  // start fingerprint sensor
  delay(100);

  uint8_t getFingerprintID() {
    uint8_t p = finger.getImage();
    switch (p) {
      case FINGERPRINT_OK:
        Serial.println("Image taken");
        break;
      case FINGERPRINT_NOFINGER:
        Serial.println("No finger detected");
        return p;
      case FINGERPRINT_PACKETRECIEVEERR:
        Serial.println("Communication error");
        return p;
      case FINGERPRINT_IMAGEFAIL:
        Serial.println("Imaging error");
        return p;
      default:
        Serial.println("Unknown error");
        return p;
    }

    p = finger.fingerFastSearch();
    if (p == FINGERPRINT_OK && read_rfid == ok_rfid_1) {
      Serial.println(ok_rfid_1);
      open_door();
    }

  }

And this is the error I am getting
Arduino: 1.8.1 (Windows 10), Board: "Arduino/Genuino Uno"

fingerprint:127: error: expected unqualified-id before '{' token

 {

 ^

exit status 1
expected unqualified-id before '{' token

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I am new to this so please bear with me and explain in childish manner if possible.

Welcome to Arduino SE.  Please take the tour at https://arduino.stackexchange.com/Tour.    And btw, when you put in code, just make sure you have one blank line at the top then enter the code with 4 spaces at the beginning of each line.  It is much more readable that way.

Looks like your switch statement is outside a function declaration.

Can't say I have read what you posted here or what you're trying to do, however nonetheless I have fixed the errors in your post. This will compile no problem. Good luck with your project.
#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
int getFingerprintIDez();
SoftwareSerial mySerial(2, 3);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

//HEADERFILES
#include <SPI.h> //rfid
#include <MFRC522.h>//rfid
#include<stdint.h> //FINGERPRINT

//RFID settings
#define RST_PIN         9          // RFID pin 9 RST_pin
#define SS_PIN          10         // RFID pin 10 SS_pin
MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
String read_rfid;
String ok_rfid_1 = "cbb427b2"; //white card
String ok_rfid_2 = "0ebb14f39"; //blue key chain

int door = 7; //motor to door

void dump_byte_array(byte * buffer , byte bufferSize) {
  //why so important
  read_rfid = "";
  for (byte i = 0; i < bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
}

void setup() {
  //RFID setup
  finger.begin(57600);
  Serial.begin(9600);
  // Initialize serial communications with the PC
  while (!Serial);
  // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin(); // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 RFID
  pinMode (door, OUTPUT);
  //FINGERPRINT setup
  {
    while (!Serial);  // For Yun/Leo/Micro/Zero/...
    if (finger.verifyPassword()) {
      Serial.println("Found fingerprint sensor!");
    } else {
      Serial.println("Did not find fingerprint sensor :(");
      while (1);
    }
    Serial.println("Waiting for valid finger...");
  }
}

// OK success!

void open_door() {
  digitalWrite (door, HIGH);
  delay (2000);
  digitalWrite (door, LOW);
}

void loop() {
  // RFID LOOP SETTINGS
  if (! mfrc522.PICC_IsNewCardPresent()) {
    // Look for new cards
    return;
  }
  if (!mfrc522.PICC_ReadCardSerial()) {
    // Select one of the cards
    return;
  }
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println(read_rfid);
  // FINGERPRINT LOOP SETTINGS
  getFingerprintID();  // start fingerprint sensor
  delay(100);
}

uint8_t getFingerprintID() {
  uint8_t p = finger.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println("No finger detected");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK success!
  p = finger.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    Serial.println("Found a print match!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {
    Serial.println("Did not find a match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }
  // found a match!
  Serial.print("Found ID #"); Serial.print(finger.fingerID);
  Serial.print(" with confidence of "); Serial.println(finger.confidence);
}

default:
  Serial.println("Unknown error");
  return p;
}
} <-- Why?

Proper indentation shows that you have an extraneous closing curly brace.


text:
Arduino MPU6050 not working due to LED PWM
I'm having some problem with the MPU6050 example sketch. I added a few bits of code of my own, so that my LEDs change color based on the yaw-pitch-roll. However when I try to run it, the values of the yaw-pitch-roll get all distorted, like this:
ypr -38.68  -30.05  41.34
ypr -55.42  -35.25  -31.68
ypr -101.02 23.53   -65.01
ypr 101.29  -19.63  12.81
ypr -51.97  -37.49  44.85
ypr 37.89   38.20   -37.95
ypr 72.15   -13.70  22.68
ypr 0.00    0.00    90.00
ypr -45.73  74.52   -11.89
ypr 134.36  31.89   -31.08
ypr -13.86  -21.51  3.54

And when I disable analogWrite on the LED lights the yaw-pitch-roll gives normal output again.
Below is the code for changing the LED colors.
void setColor (float red, float blue){
  int redColor = (int)255 - red;
  int blueColor = (int)255 - blue;
  analogWrite(redPin, redColor);
  analogWrite(bluePin, blueColor);
}

Does anyone know what is going wrong here?
EDIT:
The wiring:

The code:
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)
//#define OUTPUT_READABLE_QUATERNION

// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)
//#define OUTPUT_READABLE_EULER

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_YAWPITCHROLL

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
//#define OUTPUT_READABLE_WORLDACCEL

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
//#define OUTPUT_TEAPOT

#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

int redPin = 11;
int bluePin = 9;

int startR = 100;
int startB = 10;

int eindR = 255;
int eindB = 255;

int gyroMin = 0;
int gyroMax = 80;
int gyroRange = 0;
float rangeR = 0;
float rangeB = 0;

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    gyroRange = (gyroMax - 10) - (gyroMin + 10);
    rangeR = (float)(eindR - startR)/gyroRange;
    rangeB = (float)(eindB - startB)/gyroRange;

    Serial.begin(115200);
    while (!Serial);

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    /*while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again*/

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
    pinMode(redPin, OUTPUT);
    pinMode(bluePin, OUTPUT);
    //digitalWrite(redPin, LOW);
    //digitalWrite(bluePin, LOW);
    setColor(100.0,100.0);
}

void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));
        } else if (mpuIntStatus & 0x02) {
          // otherwise, check for DMP data ready interrupt (this should happen frequently)
         // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
            int degree = ypr[1] * 180/M_PI;
            if (degree <= (gyroMin + 10)){
              setColor(startR, startB);
            }
            if ((degree > (gyroMin + 10)) && (degree < (gyroMax - 10))){
              float calcR = (startR + ((degree-10) * rangeR));
              float calcB = (startB + ((degree-10) * rangeB));
              setColor(calcR,calcB);
            }
            if (degree >= (gyroMax - 10)){
              setColor(eindR, eindB);
            }
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
}
void setColor (float red, float blue){
  int redColor = (int)255 - red;
  int blueColor = (int)255 - blue;
  analogWrite(redPin, redColor);
  analogWrite(bluePin, blueColor);
}

EDIT 2:
After a lot of testing with and without resistors and new cables (I thought there might be some sort of cable damage), it still isn't working fully. The weird thing is that when every component is hooked up via a breadboard it works (without resistors). But as soon as I try to solder everything it works randomly.
Is there a chance that the type of cable (copper vs aluminium) has any effect on this? The breadboard cables are aluminium and the soldered cables are copper.

Not without seeing both the entirety of your code and the wiring of your circuit.

@Majenko thanks for the quick reply, i uploaded a screenshot of the wiring and added the full code

Just a question. Why you pass float variable as colour? Try int. analogWrite change the value to 8bit.

Jimi just quick test. Take off LEDs and try the code if there is any difference. Also try to pass integer instead of float

Yeah did that, then the output is stable.

You have no resistors on your LEDs. The PWM signals are causing huge amounts of noise in the MCU corrupting all your data and communications.
Add resistors (say 330Ω) to each LED cathode pin (so 9 resistors).

but the led are in series, do I still need 9 resistors or just 3?

No, they aren't in series. They are in parallel. Every single LED needs a resistor, and there's 3 resistors per device, and 3 devices, so 9 resistors.

Aah right, my bad. I will try to add the resistor and will let you know if it works. thanks for all the help so far! :D

I added the resistors, but it still isn't working + now the leds are very dim (which is not what I want), what now?

The MPU board you have pictured looks like it should be powered by 5V not 3.3V.

According to the datasheet it supports 2.375V-3.46V range. So not 5v

That's the datasheet for just one of the chips on that board. The board (at least the one pictured) appears to have a 3.3V regulator (the 5-pin SOT-23 chip) that powers the MPU6050.

So if I move the MPU to the 5v will the led still get power? (also sorry for all the questions, this is all still very new to me)

Yes, you can plug in as many things as you like into a single 5V pin. Just like you wired multiple LEDs in parallel to the same IO pin.

I updated the post, after a lot of tests I'm still having issues


text:
Testing ID and Serial Communication (Update)
Here is my challenge: I have to create a sketch where I would have a prompt asking the user to enter an ID. If it is successful, it would turn on the green LED and response with "Hello, your name is so-so."  If it failed, it would turn on the red LED and response with "Invalid username! Try again."
The code is here:
//Establish myID as CHAR data type
 char myID = 'tg123';
 //Establish testID to receive data to be tested against myID
 char testID;

 //Establish green and red LEDs to PWM pins
 const int gLED = 10;
 const int rLED = 5;

 void setup()
 {
  //Establishing baud rate at 9600
  Serial.begin(9600);
  pinMode(gLED, OUTPUT);
  pinMode(rLED, OUTPUT);
 }

 void loop()
 {
  //Act when there are data in the buffer
  while (Serial.available())
  {
    testID = Serial.read();
    //If data = myID, turn on green LED and acknowledge
    if (testID == myID)
    {
      digitalWrite(gLED, HIGH);
      digitalWrite(rLED, LOW);
      Serial.println("Hello! Your name is Trevor.");
      delay(5000);
    }
    else
    {
      digitalWrite(rLED, HIGH);
      digitalWrite(gLED, LOW);
      Serial.println("Invalid ID! Try again.");
      delay(2000);
    }
  }
 }

Two problems I have had with this:

The damn thing would print the line "Please enter your ID:" infinitely if it was inside the loop, so I got fed up and moved it to the set up, and
no matter what I enter in the serial monitor, it does not do anything.

Update: After reading Arduino's website, I found I can predefine the char data type by adding char myID = 'tg123';.  It is getting closer to achieving what I want, but it's exhibiting some strange behavior.  When I type in exactly tg123 in the serial monitor, it would report the error message as defined in the sketch before passing.

Your sketch assumes that the ID is a single character. If that is the case then comparing with 'tgreen123' will not work very well.

I have updated the original post.

Your question has been answered (twice). Please, accept one of them to close this question.

You are assigning a string to a single character here.

char myID = 'tg123';

Instead you should make it a String variable. And compare it after all the characters are recieved.

String myID = "tg123";

And Here is the modified code you should test with. In this case I have assumed you simply write the ID (string) in serial terminal and hit enter.
N.B. If you want to enter each character one by one, then it will not be able to catch the whole string. For this case you have to add some time-out to wait for next character to arrive.
String recvData = "";
void loop()
{
  while (!Serial.available());
  while (Serial.available())
  {
    char ch = Serial.read();
    recvData += ch;
  }
  if (myID == recvData)
  {
    digitalWrite(gLED, HIGH);
    digitalWrite(rLED, LOW);
    Serial.println("Hello! Your name is Trevor.");
    delay(5000);
  }
  else
  {
    digitalWrite(rLED, HIGH);
    digitalWrite(gLED, LOW);
    Serial.println("Invalid ID! Try again.");
    delay(2000);
  }
  recvData = "";
 }

When you use the Arduino IDE to compile your code for an Uno, it will tell you

Sketch uses 2106 bytes (6%) of program storage space. Maximum is 32256 bytes.
  Global variables use 237 bytes (11%) of dynamic memory, leaving 1811 bytes for local variables. Maximum is 2048 bytes.

as if there had been a clean and correct compilation.  However, if you compile it via make and a makefile (see, eg, sudar's Arduino Makefile) you will see a warning like the following:

stringInit1.ino:2:14: warning: character constant too long for its type [enabled by default]
    char myID = 'tg123';

where stringInit1 stands for whatever you call your sketch.
The char data type stands for a single character.  To represent a text string, use either an array of characters (for example, char *myID = "tg123" or char myID[] = "tg123") or a String type (which, in general, is problematic on small-RAM embedded processors).
Then, to make the comparison, keep track of how many characters have been input so far, and as you input each character, compare it to the current character of myID, clearing a match-flag if characters don't match.  Eg, if (testChar != myID[currentCount]) matchFlag = false;.  Note, initialize currentCount to zero and matchFlag to true in setup() and before each retry.

I agree.  Serial.read() will only bring in a single character.  You do have the option of using Serial.readstring, but then you can't compare it to chars.  I like @James' idea of just checking with each character whether or not you have the whole ID.  Then you wouldn't even need to press enter when you have it right.  But you could type the entire constitution of the US, newlines and all, and the program would do nothing.  I also agree that you may have an uploading error because you say it prompts you for your ID but I don't see that in the code.  Might be an older version that is running.


text:
Accelerometer MPU-6050 marks timeout in Unity
I've been having this problem, that I am trying to use an accelerometer MPU-6050 to get the rotation and pass that information to Unity.
I also have some buttons in the same Arduino. I'm using an Arduino Uno. With those buttons, everything works well, but the moment I put something related to the accelerometer in the Arduino code, Unity marks a time out. When I run it on Arduino it sends me all the info I'm asking, so I don't really know what's the problem. I really appreciate if someone could help me.
Here is code on Arduino:
#include<Wire.h>
#define A_R 16384.0
#define G_R 131.0
 #define RAD_A_DEG = 57.295779
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int AcX,AcY,AcZ,GyX,GyY;

float Acc[2];
float Gy[2];
float Angle[2];
int button = 0;
int button2 = 0;
int button3 = 0;

float arriba=0, abajo=0,mouse=0;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  pinMode(7, INPUT); // declare pushbutton as input
pinMode(6, INPUT);
pinMode(5,INPUT);
  Serial.begin(9600);
}

void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  //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();

  Acc[1] = atan(-1*(AcX/A_R)/sqrt(pow((AcY/A_R),2) + pow((AcZ/A_R),2)))*RAD_TO_DEG;
   Acc[0] = atan((AcY/A_R)/sqrt(pow((AcX/A_R),2) + pow((AcZ/A_R),2)))*RAD_TO_DEG;

  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)

  Angle[0] = 0.98 *(Angle[0]+Gy[0]*0.010) + 0.02*Acc[0];
   Angle[1] = 0.98 *(Angle[1]+Gy[1]*0.010) + 0.02*Acc[1];

        button = digitalRead(7);
  button2 = digitalRead(6);
  button3 = digitalRead (5);

   //Mostrar los valores por consola
   if(button == HIGH){
 arriba=1;
  }else if(button==LOW){
  arriba=0;
  }

  if(button2 == HIGH){
    abajo=1;
  }else if(button2==LOW){
    abajo=0;
  }

  if(button3 == HIGH){  //boton 3
    mouse=1;
  }else if(button3==LOW){
    mouse=0;
  }
  Serial.print(arriba);
  Serial.print(",");
  Serial.print(abajo);
  Serial.print(",");
  Serial.print(mouse);
   Serial.print(",");

   Serial.print(Angle[0]);
   Serial.print(",");
   Serial.println(Angle[1]);

  delay(200);
}

I know this isn't an Unity forum, but here is the code in Unity. The only thing it does, is read it and put the results in an array.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;
using System.Globalization;
using System;

using UnityEngine;

public class ConectarArduino: MonoBehaviour
{
    string Recibidos;
    public string Linea, Linea1,Linea2;
    public int Arrib, Abajo,Boton;
    SerialPort stream;
    // Use this for initialization

    void Start()
    {
        stream = new SerialPort("COM3", 9600);
        //  stream.
        stream.Open();
        stream.ReadTimeout = 300;

    }

    // Update is called once per frame
    void Update()
    {
        try
        {
            Recibidos = stream.ReadLine();
            Debug.Log(Recibidos);
        }
        catch (System.Exception e)
        {
            Debug.Log(e.Message);
            throw;
        }

        string[] Values = Recibidos.Split(',').Select(str => str.Trim()).ToArray();
        Linea = Values[0];
        Linea1 = Values[1];
        Linea2 = Values[2];

There's too many things call Unity these days. Which Unity are you talking about?

Can you add the timeout error to your question? What is/are the line(s) that when you add, causes the timeout? Could you be a bit more explicit about what works, and what doesn't (a sort of "before and after")..?

Running MPU-6050 at 57600bps seemed to be the good rate for me:
  pinMode(5,INPUT);
  Serial.begin(57600);
}

It worked for me and I found these guys for whom it was the good rate :
From MPU-6050-simple-library, specifically MPU6050_test.ino:

void setup() {
  Serial.begin(57600);
  MPU6050mgr.begin(); // Initializes IMU module
}

From Another Arduino as external i2c device for MPU6050:

void setup() {
  Wire.begin(0x1E);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(57600);           // start serial for output
}

From Library for Arduino and MPU-6050 communication:

void setup() {
  Serial.begin(57600);
  MPU6050mgr.begin(); // Initializes IMU module
}

You may also find this link useful: MPU-6050 Redux: DMP Data Fusion vs. Complementary Filter.

You may be correct but can you provide evidence that 57600 bps is its preferred rate?

That may not be a proof from the datasheets, but in my project in worked, and there is a lot of people for whom it worked too :
https://github.com/dadez87/MPU-6050-simple-library
http://www.geekmomprojects.com/mpu-6050-redux-dmp-data-fusion-vs-complementary-filter/
https://www.i2cdevlib.com/forums/topic/538-another-arduino-as-external-i2c-device-for-mpu6050/
https://www.monocilindro.com/2017/02/25/library-arduino-mpu-6050-communication/

Excellent, could you edit your answer, and include that information then? Important information should not be in comments, as they are rather ephemeral and, as such, may be deleted at any time. Thanks

sorry for this, it s okay now

You omitted two links, and you should have included the relevant code from the links, because if the links die (which is often the case), then your answer becomes (effectively) useless. I have edited your answer for you. Please take the time to see how I have done the edits. Oh, and welcome to SE Arduino... :-)

thank you for your edit, i understand the links problem !


text:
Attiny85 not recognized at windows startup
I'm using an Attiny85 to interact with a computer using an USB connection, and everything works fine except when I restart my computer and the Attiny85 is connected. When Windows end to boot up the Attiny85 isnt't recognized, and on Device Manager it's listed like this:

If I unplug the Attiny85 and then plug it back in, everything works just fine.
Is there any to make it detectable at boot time without having to always unplug/plug it?
EDIT:
More details:
I'm using this board

and libusb-win32 as the USB driver

The ATTiny doesn't really do USB. Making it interface with a USB port using something like V-USB is a hack at best. You shouldn't expect it to work properly in all respects.

You could use an oscilloscope and/or a USB protocol analyzer to find out what exactly V-USB does wrong, but in any case such a hacky software emulation cannot be fixed. Better use a microcontroller that actually supports USB (e.g., a Teensy).

Added more details (board and USB driver) to help in problem analyis

I don't have enough reputations to make a comment so I will drop my 2 cents here.
There should be more elegant way to do this but as a fast solution I would recommend two things:

If it is possible, add a push button to your board to reset the MCU manually when the PC is booted up.
You can make a software reset after powering up the board by a certain time (e.g. 10 sec) by using watchdog timer.

I can't use the button idea because the board will be inside a case, and it wouldn't be practical.
The idea about the watchdog timer won't work because the board is always connected, so when the PC is off I would be executing the reset procedure at every 10 seconds, and I don't know if it would "like it".

@GonçaloCardoso Regarding watchdog timer, you can use watchdog timer just one time. You can handle this in your code.

But at what time would that be?

@GonçaloCardoso The time completely depends on your application. To perform a software reset one time look at this link.

The problem is that I need to make the restart when Windows boots up, and I haven't managed to find a way for the board to detect it.

@GonçaloCardoso When PC is off there should be no supply at USB port. After powering up the PC your board is going to be supplied and here where you start the timer to get the MCU reset. The time should not be too long because if you plug in your board while the PC is running the board is going to start working after the time you had already set. As I told you in my answer, it is not a perfect solution and I don't know if you can manage to place a push button on your board case. Otherwise you have to dig into the V-USB code and hope that you find a way to get the job done.

@GonçaloCardoso By the way I have an idea that should work for you. Try to disable the power saving options for USB devices and then reboot and see whether it works or not. Look at this link.


text:
How many WS2811 LED strips can I control with Arduino?
Is there any limitation to connecting more strips?
I plan to create for my temple Ganpati Street Lighting LED Decoration - Full HD Ahmednagar Mh India
Watch this video and give me some ideas and suggestions.

In principle you can connect one strip per digital pin, but that looks like a huge amount of data to stream out of an Arduino. Even a Mega would likely be short of flash and RAM.

you could use a bunch of $2 pro-minis, software serial controlled by a mega.

There are three factors to consider when driving strings of these LEDs from an Arduino:

How much memory the Arduino has - each LED takes at least 3 bytes of RAM (possibly more depending on the library implementation). (An Uno could probably just manage 500 at most)
How long it takes to send the data over the wire - the more LEDs you have in a chain the longer each update takes and the slower your animations run.
How you power such a huge number of LEDs efficiently. You won't just plug them into the 5V pin of the Arduino that's for sure.

Note that the arrangement you link to most likely isn't a single small microcontroller controlling the whole lot. Instead it is much more likely each individual strip has a single controller and those controllers are all networked together (probably through RS-485 or CAN) to a master controller (probably a PC) to send instructions to them all.

Majenko is totally right (as always).
But as an alternative solution, you could opt for SPI-based LEDstrips. They're not bound to specific timings and thus:

You can "generate"/stream colors. You can let your Arduino calculate the next color and send it directly. In this way, you'll only need RAM for one pixel at the time. For the length, you're now only limited to the time it takes to update a strip.
Sending of data in SPI is done in hardware and can thus be done by hardware, while your software focusses on the next job/pixel. (So you also don't need to calculate the whole strip at once, before sending)
Often, you can send "pixels" much faster, by simply increasing your SPI clock. I'm not sure what the limit will be here, check the ledstrip datasheets.

Also, if you're going to push the limit of Arduino, why not use better hardware? The Teensy 3.2 is often used for ledstrip projects, since it has 64K ram and 256K flash and can run at 96Mhz  (not sure about the SPI speed). Have a look at fastled and octows as well.
You should split up this project, to make it scalable. Try to make one "row" of it and start adding more rows (with individual controllers and power).
I agree with Majenko on using RS485 or CAN to connect/command/sync these different rows.

I think the SPI trick only works when you combined it with DMA.

@Gerben, you've got SPI-controlled LEDstrips, they can handle "waiting" between LED's, since you can effectively "halt" them by not toggling the clock line. Also, I believe hardware SPI has a "SPI Serial Transfer Complete" interrupt and an 8-bit shift register, so after starting the transfer, you do have some "free time" before it had been completely written, but I'm not sure if it's significant. (But if you start the next transfer a little later, it won't matter for spi-strips, since their timing isn't arbitrary but based on the spi-clock you generatie yourself)

But this question was specifically about ws2812s which don't have an SPI like interface.

You've got a point there! But I wanted to give an alternative option, choosing the right hardware/interfacing can overcome having to solve everything in software/making it more efficient. If spi-ledstrips are too expensive (or simply want to use WS2812’s, Majenko's answer is better but the options are more limited.

I have worked with setups similar to this. Arduino is limited as mentioned by Majenko.
If you like the Arduino platform I recommend you look into the Teensy based controllers.  They are 32 bit based and have more memory and are optimized to handle LED projects like this. Best of all, it uses the Arduino IDE with numerous libraries.  The Teensy would need to be paired with a Network adapter, so you could use sACN E1.31 and use software like Jinx to create the effects you're wanting to do.