text:
Advice for lower power clock type project
Arduino newbie here! I'm a programmer but my hardware knowledge is ... slim.
I'd like to build a clock type wake up timer for my daughter, using an Arduino type board. Probably overkill, but it's practice for me, not just the end result! The idea is that is sleeps all night, then around say 4, gradually fade on a red LED. At 6, which is when she's allowed to come in, the red LED switches to a green, or some colourful sequence that tells her it's time. At a later time, maybe 7/8, it goes back to sleep to conserve power.
I have an Arduino Uno, but looks like I'll also need an RTC, and I've read that the sleep power consumption is ~40mA, which on batteries is what? A day or two max?
So I'm thinking I can't do this with a Uno.
So, my question is, are there any very low power Arduino compatible boards with built in RTCs that I can use for this project that will get me up and running as quickly as if I was using the Uno?

Is plugging it into a wall not an option?

An Arduino Micro Pro could be used (after removing the power LED and voltage regulator). It is possible to reduce to less than 10 uA.

@ratchetfreak It's sadly a suboptimal option as the room has extremely limited power sockets, however thinking about it actually might be the perfect option to make a proof of concept at least.

A extension cord with multiple outlets should help with that.

Try one of supported RTC's boards. The most popular (and simple) are: DS1302, DS1307, PCF8563, and - very nice, precise DS3231 (my fav). Hook any of them up to your Arduino, add some (readily available) libraries, tweak a little and voila. Most (if not all) of mentioned RTC have 'alarm' function: you can set up your system to wake up your Arduino from sleep (sleep state to save battery) and gradually light up the LED.

i would use an esp8266 to "drive" the LEDs and send color commands over wifi from a computer that knows the time. i use such a setup for several LED matrix clocks, and it works well w/low effort (little c++ coding, no soldering, no RTC or external modules besides the matrix).

I will make my comment an answer:
Try one of Arduino supported RTC's boards. The most popular (and simple) are: DS1302, DS1307, PCF8563, and - very nice, precise DS3231 (my fav). Hook any of them up to your Arduino, add some (readily available) libraries, tweak a little and voila. The RTC will work from coin battery (or high capacity capacitor called supercapacitor, like this one)
Most (if not all) of mentioned RTC have 'alarm' function: you can set up your system to wake up your Arduino from sleep (sleep state to save battery) and gradually light up the LED.
To limit current of Arduino try removing LED, or - better - try to use Arduino Pro Mini. To modify it for better power saving see here
EDIT:
There are some other low-power boards:
Moteino
Rocket Scream Mini Ultra
JeeLink
Also, (as mentioned in one of comments) you can try one of ESP8266 and push it to one of many sleep modes. Try this link.


text:
Adding Library to my sketchbook
Hey so basically I have my Arduino uno r3 setup with my RFID-RC522. I am looking to add this library to so I can use the examples alongside the ones I already have.
https://github.com/BoolLi/RC522_RFID_NFC_Utilities
I haven't been able to add them correctly and hope someone can help me out doing this. I currently have these ones already added and working correctly:
https://github.com/miguelbalboa/rfid

https://www.arduino.cc/en/Guide/Libraries

@Majenko I am not able to do these. I have been fiddling around with them through various ones of these methods. For example the add library from zip throws this error:Arduino: 1.8.0 (Linux), Board: "Arduino/Genuino Uno"
Specified folder/zip file does not contain a valid library

Well, it doesn't help that the author of that library doesn't know the first thing about formatting a library...

Have a look at a good library and see what is wrong with this one.  Usually its the structure or the textfile, or the name.

Download https://github.com/BoolLi/RC522_RFID_NFC_Utilities/archive/master.zip
Copy the folder RC522_RFID_Utilities from the downloaded file to {sketchbook folder}/libraries. You can find the location of your sketchbook folder in the Arduino IDE at File > Preferences > Sketchbook location.
If you're using Arduino IDE 1.6.5-r5 or older restart the Arduino IDE. If using a newer version no restart is necessary.

The other three folders in the downloaded file are example sketches, not libraries. After installing the RC522_RFID_NFC_Utilities library following the instructions above you will be able to use them. You can store those folders anywhere you like but you should not put them directly under the libraries folder as this will cause warning messages about invalid libraries on every compilation. If you do want to bundle them with the RC522_RFID_NFC_Utilities library, as is customary, you can do this:

Create a folder named examples in {sketchbook folder}/libraries/RC522_RFID_NFC_Utilities
Copy the example sketch folders (NDEFFormattingExample, etc) from the downloaded file to the examples folder you created.
Restart the Arduino IDE if it's running.

The example sketches will now be accessible via File > Examples > RC522_RFID_NFC_Utilities.

Thanks this was helpful. My issue was I never knew to take the Utilities folder and put it into the library and then have the examples within it. They are showing up fine for me now. Now just to try and sort the compiling error :)

source: Stack Exchange

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

sort: votes


text:
I can send on software serial, but not read?
I've been cracking my head over this for a long while.
Like many before me, I'm trying to send and receive data from a HM-10 bluetooth module, arduino mega adk and the app called BLE Scanner. I've figured out receiving alright. Whatever I write into the serial monitor, shows up on the app. Whatever I write into the software serial, shows up. However, I haven't figured out how to read from the software serial. The available function never gets triggered, and always printing out the software serial read is always -1

The app supports sending data over bluetooth as well. However, using:
    #include <SoftwareSerial.h>
SoftwareSerial blueSerial(14, 15); //RX, TX
  blueSerial.begin(9600);
  Serial.begin(9600);
while (1)
  {
    blueSerial.listen();
    if (Serial.available()) {
      Serial.println("Writing");
      blueSerial.write(Serial.read());
      Serial.println(Serial.read());
      Serial.println(blueSerial.available());
    }
    if (blueSerial.available()) {
      Serial.println("Blueserial writing");
      Serial.write(blueSerial.read());
    }
}

The listen function is used out of pure desperation.
How do I fix this? This should be working right? Since I want to be sending AT commands to the bluetooth modules at some time and read their output, getting this to work is really important.

Have you tested the HM10 using a usb to serial adapter?

What do you mean? The Arduino is connected to the laptop, and I'm reading of Arduino IDE's Serial Monitor. I don't have any special cables but the one it came with(the one that puts the code in the board)

what is while(1)? let the loop() loop

Why on earth are you using software serial????

How do you take this tone and not suggest an alternative? @Majenko

Because I'm royally fed up with seeing people do it. I would love to know why they do it.

What do you expect me to give you right here? Mathematical analysis on why hardware serial didn't work on my literal first project in arduino but software at least nudged my progress a bit? I don't know, one worked a bit, one didn't work at all.

If hardware serial isn't working then you are doing something fundamentally wrong.

If hardware serial doesn't work, then you have a problem with either your hardware or your code. When you have a problem, the right approach is to troubleshoot it: find out what is wrong and fix it. You can ask for help here if needed. If you just give up and switch to software serial, then instead of fixing the initial problem you are just creating another problem.

Possibly the built-in UART (Hardware Serial) assigned to the same pins is interfering with SoftwareSerial? If you really want to us SoftwareSerial, try it on a pair of pins that has no hardware UART attached.
And/or try SoftwareSerial (again, on a non-UART pair of pins) to connect to your PC (after uploading; you can't upload with it), and use Serial1 to connect to your device. This isn't the recommended or easiest way but it might help debug the problems you're seeing.

On Mega you don't need to use SoftwareSerial. Mega has 4 Serials. Connect the module to RX3/TX3 like on the Fritzing in your question and use Serial3 in sketch.
void setup() {
  Serial.begin(9600);
  Serial3.begin(8600);
}

void loop() {

  while (Serial.available()) {
    Serial3.write(Serial.read());
  }
  while (Serial3.available()) {
    Serial.write(Serial3.read());
  }
}

I have to confirm, that what worked on UNO over SoftwareSerial was not working on Mega ... but switch to Serial2 instead worked.

@Uli, on Mega not all pins support SoftwareSerial

If SoftwareSerial is not working then simply do not use it.
You shouldn't be using it anyway.
You have a Mega with 4 UARTs. You are using a pair of the UART pins, and yet you are using SoftwareSerial.
Don't.
instead use the SerialX object (where X is the number by the TX and RX for the pins) to communicate.
SoftwareSerial is only for those times when you don't have enough hardware UARTs, and you have plenty.

Serial3 didn't work in either direction which is why I switched to software serial in the first place

@Juraj I rewired the whole thing a bunch of times, it's now on Serial with TX->1 and RX->0 . Same issue throughout.

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


text:
Arduino baud rate 8 times too high?
I'm having a strange issue where in order to get the expected serial output on my serial monitor, I have to set the baud rate on my serial monitor to be 8 times higher than the rate that i set in my Serial.begin(). For example, Serial.begin(4800) works with a serial monitor baud rate of 38400.
The setup is an atmega328P and an atmega8u2 built up on a breadboard similar to an UNO R1. I followed Nick Gammon's tutorial and his scripts to flash the 328P with the bootloader (http://www.gammon.com.au/forum/?id=11637), and I used the DFU programmer (on OS X) to flash the 8u2. When I plug my computer into the USB connector on the breadboard, the device correctly shows up as an Arduino Uno in my computer's devices list using lsusb. I can also flash sketches to the 328P using the breadboard tutorial (https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard).
The fact that I get the expected results on my serial monitor (even though it's at the wrong baud rate) leads me to believe my hardware is set up correctly. I'm thinking that it could be a bit/byte confusion in the firmware, has anyone encountered something like this or have ideas? I currently can't flash sketches over the USB connector and I believe it is due to the baud rate mismatch.

Sounds like F_CPU is not the same as the actual frequency of the chip. Check your board configuration and your fuse settings.

The trick though is to find if it's the 8U2 or the 328P that is the wrong speed. You really need a scope or logic analyser for that. Or another USB to UART adaptor that you know can work at the right speed.

There are two baud rates you need to diagnose.  One is the baud rate the ATMega8U2 runs at, and the other is the baud rate the ATMega328P runs at.
You need to work out which one is being calculated wrong:

The ATMega8U2's baud rate is set by the USB connection when you open the port
The ATMega328P's baud rate is set by your sketch

Obviously, the two have to match.  However, a baud rate isn't just set as a number, it's calculated as a fraction of the CPU clock.
If the CPU clock on just one of the chips is different to what the firmware or sketch expects then the calculation for the baud rate will be wrong.
An example:
Your ATMega328P is expected to be running at 1MHz - however, the fuse settings have it set to run from the internal 8MHz clock.  That means everything on that chip will run 8× faster than expected, so you have to compensate with a lower baud rate.
Another example:
Your ATMega8U2 is expected to be running at 16MHz - however, the fuse settings have it set to run at 2MHz.  That means everything on that chip (except the USB which is clocked separately) will run 8× slower than expected, so you have to compensate on the ATMega328P with a lower baud rate.
So check the fuse settings on both chips. Make sure they are set to the right speeds for your firmware and boards.txt file settings.
Also, you should look at getting a cheap oscilloscope or logic analyser. That would allow you to monitor precisely what is going on with the communication between the two chips and work out if the baud rate is actually 8× faster than expected (ATMega8U2 at fault), or the normal speed but you have to specify it as a lower number (ATMega328P at fault).

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


text:
Arduino Micro interference between analog inputs
I'm building a MIDI controller with the Arduino Micro, hooking a bunch of knobs up to the analog inputs. Currently, I'm getting analog in 9 being influenced by analog in 10: analogRead(9) returns a number close to analogRead(10) and doesn't give the voltage that I'm reading with a multimeter.
What could be causing this interference?

I looked around for a while and eventually thought to put the multimeter probe on the top pin instead of on the soldered header, and got no voltage across it.
If you're experiencing a strange interference between two analog inputs, double-check your solder joints again, one of your inputs might be floating (not connected to high or ground).


text:
String to equation problem
My project is to create a decimal adder via voice recognition. Its like a calculator that only does addition. I am using hc-06 bluetooth module to convert my voice to a string. Let's say for example, I say "21+22" then the lcd would print "21 + 22 = 43". I have no problem in displaying my voice message on the lcd. My problem is that the string can't evaluate the equation. I used toInt() but it only recognizes the first integer. Is there a code to recognize the string and convert numerical values to int separated by + then evaluate it by adding the 2 intergers?

Please show us the sketch you are using.

The standard IO library (sscanf) can help you with that:
String s = "21+22";
int x;
int y;
int items = sscanf(s.c_str(), "%d+%d", &x, &y);
if (items != 2) /* error handling */
int z = x + y;

Cheers!

There is no one single function for performing a calculation from a string like you are after in C.
Instead you will have to parse and split your string up into chunks and convert the two numbers into integers (maybe confirming that there is a + between them) and perform the calculation on those two individual integers.


text:
attachInterrupt for mega 2560 not triggering
I recently bought a mega 2560 to toy around with as a hobby. It's pretty fun so far, but I've recently gotten stuck while trying to use attachInterrupt with a button. I'm using the CHANGE mode, and have read the documentation pretty thoroughly ( I think ).
I've looked up multiple questions and tried to fix my setup and I still can't seem to make it work.
Here's my code:
int buttonPin = 18;
int ledPin1 = 11;
int ledPin2 = 9;
int ledPin3 = 5;

int value = 0;

void setup() {
  //declare inputs and outputs
  pinMode(buttonPin,INPUT_PULLUP);
  pinMode(ledPin1,OUTPUT);
  pinMode(ledPin2,OUTPUT);
  pinMode(ledPin3,OUTPUT);

  //create interrupt for button
  attachInterrupt(digitalPinToInterrupt(5),count,CHANGE);

  Serial.begin(9600);
}

void loop(){
  if(value == 0){ digitalWrite(ledPin1,HIGH);}
  else{ digitalWrite(ledPin1,LOW); }

  if(value == 1){ digitalWrite(ledPin2,HIGH);}
  else{ digitalWrite(ledPin2,LOW); }

  if(value == 2){ digitalWrite(ledPin3,HIGH);}
  else{ digitalWrite(ledPin3,LOW); }

  delay(500);
  Serial.print(digitalRead(buttonPin));

}

//count occurs when button is pressed
void count(){
  //incremement a counter
  value++;
  //reset counter from 3 to 0
  if(value >= 2){ value = 0; }
}

It's a pretty simple sketch. I'd attach a picture of my current setup but I don't really think It's needed. The button is indeed working as I'm debugging using serial.print().
If not clear, the objective of the sketch is to change the LED lit when the button is pressed. Currently, the variable value is stuck at 0.

//create interrupt for button
attachInterrupt(digitalPinToInterrupt(5),count,CHANGE);

The code does not match the comment.
attachInterrupt(digitalPinToInterrupt(buttonPin),count,CHANGE);

Thanks. This doesn't quite make sense to me though, the documentation for attachInterrupt says I should use 5 instead of 18... https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

I'd like to upvote your answer but I'm not high enough in reputation

It says if you are going to use the interrupt number instead, that you should use 5. But then you wouldn't use digitalPinToInterrupt(), since that is already the interrupt number. It also recommends that you don't use the interrupt number.

Silly mistake for me to make. Thanks again for the help!


text:
How to send int[][] as a byte array through Serial
I have int arr[50][2]; and I need to send it through Serial. But I don't know how to do it. is it possible?

In what format? binary data or readable ascii? seperated with comma's?

@Jot Is it possible to get the same array on another side?

No, unless you make code that can do that. The most common way is to use Serial.print and transmit each element of the array (that is 100 times the Serial.print). You could transmit a single binary block of data, but the computer might have the MSB at the lower byte and the Arduino at the higher byte or vice versa. You need a very accurate description of the data which is transferred. It can be defined as a single block of 200 bytes consisting of 2 byte signed integers with MSB first with start byte and end byte and a crc checksum.

I forgot to mention to select a high baudrate. Not 9600 but 115200 or higher. The output tx buffer is 64 bytes, and if the tx buffer is filled, the Serial.print will wait and that will delay the sketch.

Send it to what through serial? A PC, another arduino, a printer, something else?

@Craig to another arduino

serial communication is like a tennis ball launcher .... in your example, it will fire 100 tennis balls at you, one after another .... it is up to you to arrange them any way you want after you catch them .... therefore, you have to know in which sequence they were fired

In the comment you write that the receiving end is an Arduino too. Then you can send the data in binary form.
To send the array:
Serial.write((byte*) arr, sizeof(arr));

(byte*) is cast of the memory location of arr to a byte array
sizeof returns the size of the array in bytes

To receive the binary data you must know the size. Here we read 100 16-bit integers:
Serial.readBytes((byte*) arr, 100 * sizeof(short));

Function readBytes is one of the 'timed' functions of Stream. It waits for the next byte (until timeout).
If one Arduino is 8-bit and the second is 32-bit, then use the type short instead of int, because the size of type int is different, but the type short is 16 bit long on all Arduinos.


text:
Arduino does not respond to button press suddenly
I have used this program to control relays based on commands from a serial input or control the relays with a button. Single click for a particular pin toggle and double click is like a master switch.
The code works well normally but sometimes the button just does not respond. the button works without flaw if I remove serial communication and EEPROM part of the code.
Here is the Arduino code
#include <EEPROM.h>
#include <Arduino.h>
#include <avr/wdt.h>

int pins[]={14,16,17,18,19};    //TODO: Set Switch Configuration
int no_of_switches=5;

String names, req, s;

void setup() {

  //Setting up for switches

  // initialize the pushbutton pin as an input:
  for(int i=0;i<6;i++)
  pinMode(i+3, INPUT);

  //Common pin pull up resistor
  pinMode(2,OUTPUT);
  digitalWrite(2,HIGH);

  //Setting up for relays
  Serial.begin(115200);

  for(int i=0;i<6;i++)
  {
    pinMode(i+14, OUTPUT);
    digitalWrite(14, 0);
  }

  Serial.setTimeout(4);

  names="";
  int i=0;
  char data;
  EEPROM.get(i, data);

  while(data!='^')
  {
    names+=data;
    i++;
    EEPROM.get(i, data);
  }
  names+='^';

   wdt_enable(WDTO_4S);
}

void loop() {
  wdt_reset();
  for(int i=0;i<=no_of_switches;i++){
    int b = checkButton(i);
    if (b == 1) clickEvent(i);
    if (b == 2) doubleClickEvent(i);
    if (b == 3) holdEvent(i);
    if (b == 4) longHoldEvent(i);
 }

  if (Serial.available()) {
    req = Serial.readString();
    s = "";

  if (req.indexOf("gpio") != -1)
  {
    String val = req.substring(req.lastIndexOf("gpio")+4);
    int index = val.toInt()-1;

    digitalWrite(pins[index], !digitalRead(pins[index]));

    s += pins[index];
    s += " is ";
    s += (digitalRead(pins[index]) == HIGH) ? "ON  " : "OFF  ";
  }
  else if (req.indexOf("status") != -1){
    String response_code="";
    for(int i=0;i<no_of_switches;i++){
      response_code=response_code+(digitalRead(pins[i])==HIGH?1:0);
      }
    s += response_code;
  }
  else if (req.indexOf("setstate") != -1){
    String val = req.substring(req.lastIndexOf("setstate")+8);
    for(int i=0;i<no_of_switches;i++){
      if(val.charAt(i)=='1')
      digitalWrite(pins[i],HIGH);
      else
      digitalWrite(pins[i],LOW);
      }
    s += "saved";
  }
  else if (req.indexOf("setname") != -1)
  {
    String val = req.substring(req.lastIndexOf("setname")+7);
    for(int i=0;i<val.length();i++)
    EEPROM.put(i, val.charAt(i));
    names=val;
    s="saved";

  }
  else if (req.indexOf("names") != -1)
    {
      s=names;
    }
  else
  {
    s="invalid request";
  }
  Serial.println(s);
}
}
//=================================================
// Events to trigger

void clickEvent(int pos) {
  digitalWrite(pins[pos],!digitalRead(pins[pos]));

}
void doubleClickEvent(int pos) {
  boolean bol=!digitalRead(pins[pos]);
   for(int i=14;i<=19;i++){
    digitalWrite(i,bol);
    }
}
void holdEvent(int pin) {
}
void longHoldEvent(int pin) {
}

//=================================================
//  MULTI-CLICK:  One Button, Multiple Events

// Button timing variables
int debounce = 20;          // ms debounce period to prevent flickering when pressing or releasing the button
int DCgap = 250;            // max ms between clicks for a double click event
int holdTime = 1000;        // ms hold period: how long to wait for press+hold event
int longHoldTime = 3000;    // ms long hold period: how long to wait for press+hold event

// Button variables
boolean buttonVal[] = {HIGH,HIGH,HIGH,HIGH,HIGH,HIGH};   // value read from button
boolean buttonLast[] = {HIGH,HIGH,HIGH,HIGH,HIGH,HIGH};  // buffered value of the button's previous state
boolean DCwaiting[] = {false,false,false,false,false,false};  // whether we're waiting for a double click (down)
boolean DConUp[] = {false,false,false,false,false,false};     // whether to register a double click on next release, or whether to wait and click
boolean singleOK[] = {true,true,true,true,true,true};    // whether it's OK to do a single click
long downTime[] = {-1,-1,-1,-1,-1,-1};         // time the button was pressed down
long upTime[] = {-1,-1,-1,-1,-1,-1};           // time the button was released
boolean ignoreUp[] = {false,false,false,false,false,false};   // whether to ignore the button release because the click+hold was triggered
boolean waitForUp[] = {false,false,false,false,false,false};        // when held, whether to wait for the up event
boolean holdEventPast[] = {false,false,false,false,false,false};    // whether or not the hold event happened already
boolean longHoldEventPast[] = {false,false,false,false,false,false};// whether or not the long hold event happened already

int checkButton(int buttonPin) {
   int event = 0;
   buttonVal[buttonPin] = digitalRead(buttonPin+3);
   // Button pressed down
   if (buttonVal[buttonPin] == LOW && buttonLast[buttonPin] == HIGH && (millis() - upTime[buttonPin]) > debounce)
   {
       downTime[buttonPin] = millis();
       ignoreUp[buttonPin] = false;
       waitForUp[buttonPin] = false;
       singleOK[buttonPin] = true;
       holdEventPast[buttonPin] = false;
       longHoldEventPast[buttonPin] = false;
       if ((millis()-upTime[buttonPin]) < DCgap && DConUp[buttonPin] == false && DCwaiting[buttonPin] == true)  DConUp[buttonPin] = true;
       else  DConUp[buttonPin] = false;
       DCwaiting[buttonPin] = false;
   }
   // Button released
   else if (buttonVal[buttonPin] == HIGH && buttonLast[buttonPin] == LOW && (millis() - downTime[buttonPin]) > debounce)
   {
       if (not ignoreUp[buttonPin])
       {
           upTime[buttonPin] = millis();
           if (DConUp[buttonPin] == false) DCwaiting[buttonPin] = true;
           else
           {
               event = 2;
               DConUp[buttonPin] = false;
               DCwaiting[buttonPin] = false;
               singleOK[buttonPin] = false;
           }
       }
   }
   // Test for normal click event: DCgap expired
   if ( buttonVal[buttonPin] == HIGH && (millis()-upTime[buttonPin]) >= DCgap && DCwaiting[buttonPin] == true && DConUp[buttonPin] == false && singleOK[buttonPin] == true && event != 2)
   {
       event = 1;
       DCwaiting[buttonPin] = false;
   }
   // Test for hold
   if (buttonVal[buttonPin] == LOW && (millis() - downTime[buttonPin]) >= holdTime) {
       // Trigger "normal" hold
       if (not holdEventPast[buttonPin])
       {
           event = 3;
           waitForUp[buttonPin] = true;
           ignoreUp[buttonPin] = true;
           DConUp[buttonPin] = false;
           DCwaiting[buttonPin] = false;
           //downTime[buttonPin] = millis();
           holdEventPast[buttonPin] = true;
       }
       // Trigger "long" hold
       if ((millis() - downTime[buttonPin]) >= longHoldTime)
       {
           if (not longHoldEventPast[buttonPin])
           {
               event = 4;
               longHoldEventPast[buttonPin] = true;
           }
       }
   }
   buttonLast[buttonPin] = buttonVal[buttonPin];
   return event;
}

Do you have external pull-up resistors as you are using INPUT mode for the inputs?

If it stops working after a random time, I would say it looks like a memory exhaustion problem. You could periodically print the available RAM to make sure: code to do so is widely available. If that is indeed the problem, using statically allocated character arrays instead of String objects should help.

Could it be that the processor is busy dealing with the serial or EEPROM code when you press the button and you release it before the processor has returned?

Yes, I do have pull-up resistors for the button. Normally the button works consistently. But all of a sudden it stops working

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


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

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

void loop()
{
    OCR2B = 80;
}

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

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

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

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

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

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

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

authors: Сергей Хомяков


text:
Arduino controlled relay for certain duration of time
I am using a relay on my Arduino Uno and i want it to be on LOW for a calculated interval of time, let's say ftime=7 seconds, and after that i need it to be set as HIGH (no power through relay). My code below makes no changes to the relay state. How would that be possible? I tried to use "delay()" too (which i know that is generally a bad idea), but had no success.
 unsigned int interval = ftime*1000; //ftime in ms
do
  {
  digitalWrite(Relay1, LOW);
  }
  while(timeElapsed < interval);
digitalWrite(Relay1, HIGH);

Also, if i try without:
digitalWrite(Relay1, HIGH);

relay is LOW (motor running) but it never returns to HIGH obviously.

You don't show us how timeElapsed is updated. But according to your functional description, why shouldn't it work to pull Relay1 low, wait for interval milliseconds, then pull it high again? Code is like digitalWrite(Relay1, LOW); delay(interval); digitalWrite(Relay1, HIGH);.

delay() is to be avoided because, while it is delaying, the Arduino cannot do any useful work (other than interrupts). In particular, if it has any kind of user interface, it will not respond to user input while delaying. However, if your Arduino really has nothing else to do, then delay() is fine, and it's the simplest solution.

you need to update the timeElapsed variable inside the while loop:
 unsigned int interval = ftime*1000; //ftime in ms
 unsigned long startTime = millis();
do
  {
      digitalWrite(Relay1, LOW);
      timeElapsed = millis() - startTime;
  }
  while(timeElapsed < interval);
digitalWrite(Relay1, HIGH);

Another way is to create a state machine make startTime a global and update the logical state (and the pin) when the time is elapsed.
unsigned long startTime;
bool relayLOW = false;

void loop(){

    if(relayLOW && millis() - startTime > interval){
        digitalWrite(Relay1, HIGH);
        relayLOW = false;
    }
    if(!relayLOW){
        bool closeRelay= //decide if relay needs to be triggered
        if(closeRelay){
            startTime = millis();
            digitalWrite(Relay1, LOW);
            relayLOW = true;
        }
    }
}

Made the changes but i get an error after the do/while:
Soft WDT reset
ctx: cont
sp: 3fff0850 end: 3fff0a50 offset: 01b0

stack>>>
3fff0a00:  3ffef964 3ffef458 3ffef964 40203807
3fff0a10:  0000078c 0000001c 3ffef6c0 40106bad
3fff0a20:  00000000 00000000 00000001 3ffefa24
3fff0a30:  3fffdad0 00000000 3ffefa1c 40205894
3fff0a40:  feefeffe feefeffe 3ffefa30 40100a28
<<<stack<<<
ΖεΦΤΖU)�ώ

I would be interested if it's not difficult to to show me a state machine example.

The problem with this code is that it does busy waiting without reseting the watchdog. It loops the entire time until the time has elapsed, but the Arduino watchdogs bites after 5 seconds without exiting the loop function or executing a delay() call (even with 0 as argument). The result is that your Arduino resets after a watchdog reset.

I believe i understand the situation. If i understand correctly, if the time was below 5 seconds, the error/reset would not occur. However, i cannot figure out how i will solve that? Any ideas?

As Maximillian Gerhardt suggested you could insert a delay(0); into your  while loop, which will reset the watchdog timer

@GalinhoSalonica I've updated the answer

@ratchet freak closeRelay should be global boolean, obviously?

@GalinhoSalonica ah no you can declare it inside the if where the comment is. It's only used inside that point.

Perfect answer and the second approach is working perfectly too. I can confirm after trying to make it work and succeeding in both ways. Thanks to all of you guys.


text:
Arduino Uno R3 to Wemos D1 R2 project migration - Pinout problems
So i've chosen to purchase a Wemos D1 R2 board in order that my old Arduino Uno R3 projects can get some new IoT features. However, even if my code is working in Uno perfectly, i want to test it using D1 before adding features. My problem is that, even if i have found tables showing differences between the 2 boards' pinouts, i cannot understand the correspondence between the pinouts.
So i am giving you the table below. Let's say i want to define echo and trigger pins for a sensor in my code. For example:
#define TRIGGER_PIN 4
#define ECHO_PIN 3

That would be pins D3 and D4 at my Uno. But i cannot understand which those pins would be in Wemos D1 R2. Also, my two boards can be seen below for comparison

The tricky thing with the WeMos boards is the pin notation is different from other Arduino boards.
Sometimes you will see the digital pins on Arduino boards referenced with the Dn notation. For example: "Connect the HC-SR04's Trig pin to D4 on the Uno". In fact some boards such as the Nano even use the Dn pin notation on their silkscreen. This is just a way of further differentiating the pins from the An pins. You will only refer to that pin by the number 4 in your code.
The WeMos boards are different. You actually need to use D3 and D4 in your code to control the pins marked D3 and D4 on the silkscreen:
#define TRIGGER_PIN D4
#define ECHO_PIN D3

We can take a peek at the source code of the ESP8266 core for Arduino to see why:
https://github.com/esp8266/Arduino/blob/2.4.0/variants/d1_mini/pins_arduino.h#L40-L50
static const uint8_t D0   = 16;
static const uint8_t D1   = 5;
static const uint8_t D2   = 4;
static const uint8_t D3   = 0;
static const uint8_t D4   = 2;
static const uint8_t D5   = 14;
static const uint8_t D6   = 12;
static const uint8_t D7   = 13;
static const uint8_t D8   = 15;
static const uint8_t RX   = 3;
static const uint8_t TX = 1;

Now you can see that if you use your original code:
#define TRIGGER_PIN 4
#define ECHO_PIN 3

That would actually be referring to the pins marked D2 and RX on the WeMos D1 R2!

Perfect answer to sort that out. To the point and clear! Thanks.

If i choose to use numbers with Ds, f.e. TRIGGER_PIN D4, will i connect jumper wire of trigger to D2(Arduino pin) or to D4 (physical D4 on Wemos)?

Use the Dn names, as marked on the WeMos board, in your code and the pin with that marking will be used. i.e. if you write D4 in your code then connect the wire to the pin marked D4 on the board.


text:
Using the physical serial port on a BSFrance LoRa32u4?
I can use the serial-over-USB channel by simply using Serial in my code.
The LoRa32u4 has an RXD1 and TXD1 pair on pins 20/21 (Arduino 0/1).

https://docs.bsfrance.fr/documentation/11296_LORA32U4/LoRa32u4_pinout_diagram.pdf
How do I configure and use this serial port (for receiving NMEA GPS)?

[ATmega32U4-based boards use] Serial1 to communicate via TTL (5V) serial on pins 0 (RX) and 1 (TX). Serial is reserved for USB CDC communication. For more information, refer to the Leonardo getting started page and hardware page.


text:
Increasing number of iterations not increasing time
I am using Arduino Uno with Atmel Atmega328. I am using micros() function in Arduino IDE to measure time taken for execution. Here is my code:
void setup() {
    Serial.begin(9600);
}

void loop() {
    unsigned long a = micros();
    for (unsigned long j = 0; j < 100; ++j);
    Serial.println ((micros() - a));
    delay(1000);
}

The output comes as 4. But if I increase the number of iterations in the for loop to say around 1000000000 it still shows that for loop takes same time of 4. Is there a function which I can use to measure time properly in arduino?

The compiler has realized that your loop doesn't do anything useful and therefore optimized the whole thing away. Thus you are just timing how long it takes to do nothing. (You didn't get a result of zero, because calling micros will itself take time).
BTW, the granularity of micros is 4 µs, so you won't get a reading of 1 or 2. The code actually probably only took a couple of microseconds.
You need to do something that the compiler thinks "does something", like this:
void setup() {
    Serial.begin(115200);
}

volatile byte b;

void loop() {
    unsigned long a = micros();
    for (unsigned long j = 0; j < 100; ++j)
      b++;
    Serial.println ((micros() - a));
    delay(1000);
}

By making b volatile the compiler cannot decide that b isn't doing anything useful, so now the timings make sense.
I got 72 for 100 iterations and 144 for 200 iterations.

Is there a function which I can use to measure time properly in arduino?

Your time measurement is fine. Your interpretation of the results indicates you didn't realize how smart the compiler is. :)

You can see what the compiler did if you examine the generated code:
    unsigned long a = micros();
  d8:   0e 94 d2 00     call    0x1a4   ; 0x1a4 <micros>
  dc:   6b 01           movw    r12, r22
  de:   7c 01           movw    r14, r24
    for (unsigned long j = 0; j < 100; ++j);
    Serial.println ((micros() - a));
  e0:   0e 94 d2 00     call    0x1a4   ; 0x1a4 <micros>
  e4:   ab 01           movw    r20, r22
  e6:   bc 01           movw    r22, r24

As you can see, between the two calls to micros there isn't any sort of loop.
To find the assembled code you can follow the steps documented here.
Basically, turn on "verbose compiling" which will show near the end of the verbose output the full pathname of the ".elf" file. Then use a command (terminal) window to enter this command:
avr-objdump -S xxx.elf

You may want to redirect the output to a file:
avr-objdump -S xxx.elf > myfile.txt

Depending on how the Arduino IDE was installed you may have to find the pull pathname of avr-objdump and use that instead of just the program name.

To force iterations I ususally use for(...) { asm volatile("nop"); }.

Good idea. In reality the OP probably wants something "real" timed eventually so the problem will just go away when the loop does something useful.


text:
Is there a key switch for Arduino?
I am trying to make a launch controller, which will turn on with a key. Like the one in this photo below:

this is not an arduino related question and shopping questions are frowned upon here

Check for example here for a key switch (see picture below).
As you can see it has two pins. If the pins are connected the switch is closed (same like a normal switch). So you can just connect one wire to VCC / 5V and the other via a high value resistor to a GPIO pin and check for LOW or HIGH.
(note: in practice it's possible to use almost any (electric/mechanical) component as long as the number of pins is not too high to be reasonably used by an Arduino).

Re “one wire to VCC / 5V and the other [...] to a GPIO pin”: for reading the state of the switch, you will need either a pullup or a pulldown resistor. You can use the internal pullup if you connect the other end of the switch to GND.

A key switch is just a normal switch. What you do with it depends on how you wire it and code for it.

Sorry I wasn't clear enough. I meant where can I find one and buy it.

Not really well seen to provide buy link here. Any shop that cRry switches should also stock there. Ask your favorite local or online shop.


text:
Connect Arduino to Socket IO Webserver via Esp8266
As part of a project I want to receive data on my arduino uno via a sensor, which is working fine. This data should be sent to a webserver where a node js with socket io is running. Therefore i bought a esp8266 and the corresponding adapter (https://www.amazon.de/gp/product/B01LZLVEJ4/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1).
In the IDE I have the following code:
    #include <SoftwareSerial.h>

    SoftwareSerial esp8266(2, 3);

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(115200);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.println("Started");

      // set the data rate for the SoftwareSerial port
      esp8266.begin(115200);
    }

    void loop() {
      if (esp8266.available()) {
        Serial.write(esp8266.read());
      }
      if (Serial.available()) {
        esp8266.write(Serial.read());
      }

    }

I use the serial monitor to perform my AT Commands and it seems to work some times, however there seems to be a problem with the output, for example if I type the command AT+CWLAP to display the Access Points. If I do so, it outputs something like:
    +CWLAP:(3,"WLAN-32CC39",-73,"10:c6:0f:2c:32:cc",1,65,0)
    +CWLAP:(3,"F1e:,:oMc:0(x8:1LN⸮⸮⸮:b),k7:,(-,36Ao-2,
    (e0e,C".66,Cwe8:"+L,:"+27:6L W79",944,Ab,::0(ot230( -5,CTO940PBc,63+3y8:")3,dc3
    "P4-ze6P!"80,3716

I should also note, that even if I input the same, the response differs, and sometimes it is just single characters that are wrong, e.g. "wigi" instead of "wifi". I tried different baud's for the esp8266 but the current one produces the least problems. So my questions here are:
1: Is there anything I am currently doing wrong while connecting to my local wifi network?
2: If there is a connection made, is there any way to connect to a socket io server as a client? Most Tutorials I have found have the arduino as a server. However, I want to have it as a client which communicates to a server. Therefore it should both be able to send and receive messages to/from the server.
Thanks in advance!

The baud rate is way too high for SoftwareSerial, try 9600 baud. Don't use AT commands. Either use a library that handles it for you, or program the ESP8266 directly. (I prefer the latter.) By the way, you have been ripped off on that adapter, you can get a WeMos D1 mini for $3.50 (which includes a USB connection etc. for programming).

@tttapa Hello, thanks for the fast answer. I tried switching the baud rate, but when I set the esp8266 rate to 9600, there is no answer after the "AT" command. Even though you said not to use the AT commands, shouldn't it at least work? I searched for libraries but did not find any. By programming myself you mean writing directly in the code to the serial? Sorry I am not really comfortable with arduino development. Also what is wrong with the adapter, does the WeMos D1 do the same thing as the esp8266 and adapter combined? Thanks in advance

Programming it directly means you program the ESP8266 (it is a very powerful microcontroller) instead of the Arduino or as well as the Arduino. It is much easier, more flexible, and more efficient than using AT commands. Take a look at the link I posted in my previous comment.
How did you change the baud rate? You have to use AT+CIOBAUD=9600 (send it at a baud rate of 115200), then reupload the Arduino sketch with a baud rate of 9600 instead of 115200, then it should work.

@tttapa Oh yes I see, I will try that then I think. Setting the baud rate via AT command makes sense, I tried that with both baud rates on 115200, and then executed your command. It returned "ERSOR", and I don't mean "ERROR". That is one of those weird character switches it constantly makes. Also do you have any experience with connecting to a websocket btw?

try AT+UART_DEF=9600,8,1,0,0

@Clueless: Please check my answer below, as Juraj said, you need AT+UART_DEF to set the baud rate permanently.

Using the ESP8266 in general
The easiest, most flexible, and most efficient way is to program the ESP8266 directly.
If it is possible, have it replace the Arduino entirely. To do this, it is best to get an ESP8266 development board that breaks out all IO pins and has a USB interface for easy programming. Programming these development boards is just like programming an Arduino: plug in the USB connection and hit upload in the Arduino IDE. One of my favourites is the WeMos D1 mini (around $3.50 from China).
The ESP8266 is a very powerful microcontroller on its own: it has a 32-bit processor that runs 10 times faster than an Arduino Uno, it has up to 4MB of flash memory (vs 32KB on the Uno), 160KB of RAM (vs 2KB on the Uno). It has 11 digital IO pins, an analog input, support for I²C, SPI, PWM, etc., just like an Arduino. If you use AT commands, you don't use its full potential.
Your specific situation
Given that you already bought an ESP-01 + adapter that only gives you access to the UART, connecting the sensor to the ESP directly is probably not possible.
In this case, you can do one of three things:
1) Program the ESP8266 directly:
Write a program that just reads a number from the serial port, and sends it to the server over WiFi.
This is the easiest, because you can use all features of the ESP8266, and you don't have to change the program that you wrote for the Arduino (it should just measure the sensor value, and send it to the ESP8266 over the serial port, this is exactly the same as sending it to the serial monitor on your computer).
2) Don't program the ESP8266, but use an AT commands library on the Arduino. (For example WiFiEsp)
The downside is that you have to make significant changes to your Arduino sketch, and that you cannot use all of the functions and resources of the ESP.
3) Control the ESP8266 using AT commands yourself, without any libraries.
This is very cumbersome, and is a complete waste of time, IMHO.
Practical
Programming the ESP8266 directly
To program the ESP8266 directly (both with an Arduino and stand-alone), you need a USB-to-Serial converter. You can either use something like an FT232 (3.3V) or an Arduino. How to program it is covered here. If you use an Arduino as USB-to-Serial adapter, the right connections are TX-TX, RX-RX.
Using AT commands or an AT commands library
If your Arduino has a hardware UART that is not used for programming the Arduino (e.g. Arduino Mega, Arduino Leonardo, Arduino Due, ...), you can use this UART for communicating with the ESP8266. The right connections are TX-RX, RX-TX. You can use any baud rate that's supported by both devices (9600 - 921600).
If your Arduino doesn't have an extra hardware UART, you'll have to use the UART on pins 0 and 1, that's used for programming, and you'll have to disconnect the ESP8266 every time you upload new firmware to the Arduino.
Alternatively, you can use SoftwareSerial. Keep in mind that this is far from an optimal solution, as it uses a lot of resources, it is very slow, and data might get corrupted if you spend a lot of time in interrupts on the Arduino.
To use the ESP8266 with SoftwareSerial, you need to lower the baud rate to 9600 baud. To do this, first upload an empty sketch (bare minimum) to the Arduino to make sure that the hardware UART is not used. Then connect the ESP8266 to pins 0 and 1: TX-TX, RX-RX.
Open the Serial Monitor from the Arduino IDE, and select the baud rate that the ESP8266 is currently operating at. (This is probably 115200, but it could be something else.) Select "Both NL + CR" as the line ending, and send "AT" (without the quotes) to verify that it is working. If everything works, it should answer with "OK". If it doesn't, check your hardware, or try a different baud rate. Finally, send "AT+UART_DEF=9600,8,1,0,0" to set the baud rate to 9600 baud. Then change the baud rate of the serial monitor to 9600 as well. Send "AT" again to verify that it is working.
Now you can connect the ESP8266 to the SoftwareSerial pins, using a baud rate of 9600 baud.
Edit: The WebSocket protocol is not supported using AT commands, so you have no other choice but to program the ESP8266 directly.

WiFi Link firmware and library https://github.com/jandrassy/arduino-library-wifilink/blob/master/README.md

you can use websockets vith WiFi Link library WiFiClient object

btw: WiFi Link firmware is a sketch for the esp8266

Wow, thank you botch soo much for that detailed answer, I will look into it, and am optimistic. Thanks for being patient, it is appreciated!


text:
Limiting Data Output Frequency from ADXL345
I have a working ADXL345 connected to an Arduino UNO, I need to limit the rate at which the ADXL345 takes in readings. I am using the SparkFun library for this sensor. I have read about the delay function and it works in the loop function but I was wondering if there might be a better way that is much more efficient?

Everytime you get a value from the sensor (for example with getX() or others) the library communicates with the sensor over I2C or SPI. So you can limit the usage of these function in your sketch. One way is with using delay(), but this is considered unefficient in most cases, since you are basically busy waiting during execution of delay(). You will not be able to do anything else in the future during this time span (if you want to add functionality to your device).
It's better to use non-blocking code, that only checks, if it is time to do something and if not going further through the program. Image like you yourself would bake a pizza. You would not stare at the clock for 20 min, until the time is up. You would periodically check, if the time has come to take the pizza out.
You can achieve this on an Arduino with use of the millis() function, which returns the number of milliseconds since the last powerup/reset. (Note that it overflows after about 50 days). There are plenty of tutorials for that out there. You can start with the BlinkWithoutDelay example from the Arduino IDE, which perfectly shows, how this is to be coded.
Note: If you are using the sensor with a battery, then you might want to limit its power usage. For this the library can set the corresponding registers in the sensor to set the datarate in the sensor (The rate at which the data in the sensor is updated). A smaller rate will lower the power consumption. So you can set the rate at about the rate of the reading in your sketch.


text:
ADXL345 Data Rate seems to depend more upon Baud rate than the actual Data Rate that I set
I have an Arduino UNO that is connected to an ADXL345. The problem is I need to collect data at 50Hz at least. The ADXL345 according to its Data sheet can go up to 3200Hz without any problem. I am using the Adafruit library using I2C interface but the accelerometer does not go above 10-12Hz as reported by the getDataRate() function of Adafruit library.
Im trying to set the data rate like this:
accel.setDataRate(ADXL345_DATARATE_100_HZ);

The strange thing is that the data rate is depended more upon increasing the baud rate at the beginning of my setup function. If I set this to 38400 I get around 90-92 readings every second. I have setup my code in a way that every measurement from the accelerometer is recorded with the timestamp down to seconds. This is a snapshot of the output from the serial monitor.
Data Rate:    9 Hz
------------------------------------
Sensor:       ADXL345
Driver Ver:   1
Unique ID:    12345
Max Value:    -156.91 m/s^2
Min Value:    156.91 m/s^2
Resolution:   0.04 m/s^2
------------------------------------

Range:         +/- 8  g

84.00,18:40:4,15/7/2018,0.59,9.14,2.82
85.00,18:40:4,15/7/2018,0.59,9.14,2.86
86.00,18:40:4,15/7/2018,0.63,9.10,2.86
87.00,18:40:4,15/7/2018,0.55,9.10,2.82
88.00,18:40:4,15/7/2018,0.55,9.10,2.82
89.00,18:40:4,15/7/2018,0.59,9.10,2.82
90.00,18:40:4,15/7/2018,0.59,9.10,2.82
91.00,18:40:4,15/7/2018,0.55,9.10,2.86
92.00,18:40:4,15/7/2018,0.55,9.10,2.86
93.00,18:40:4,15/7/2018,0.63,9.10,2.90
94.00,18:40:4,15/7/2018,0.63,9.10,2.90
95.00,18:40:4,15/7/2018,0.63,9.06,2.82
96.00,18:40:4,15/7/2018,0.63,9.06,2.82
97.00,18:40:4,15/7/2018,0.59,9.06,2.82
98.00,18:40:4,15/7/2018,0.59,9.06,2.82
99.00,18:40:4,15/7/2018,0.59,9.10,2.82

Is it a problem with the code, or the adxl345?

You do know that sending data through serial takes time, don't you?
You are sending 41 bytes per reading. The serial port has a 64 byte buffer. By the second reading the buffer is full and all printing blocks until there is room in the buffer.
At 38400 baud that's sending 3840 bytes per second. With 41 bytes per reading that's 93.66 readings per second (not including the time taken to do the actual reading) that you can squeeze down the serial port.
Either run at a faster speed, or reduce the quantity of data you're sending per reading - or do both.

Sure I increased the baud rate now to 115200 without changing the data rate of ADXL345, now I get around 280-290 readings on my Serial Monitor per second which means that this bottleneck has been removed?, but getDataRate still shows 9Hz when it is actually set to 100Hz.

Also why am I getting 280-290 readings when they should be somewhere around 100 readings per second?

How often you read has no bearing on how often the ADXL samples. You just get multiple readings the same.

The value returned by getDataRate isn't a Hz value - it's a number that equates to one of the ADXL_DATARATE_x_HZ enumerations. https://github.com/adafruit/Adafruit_ADXL345/blob/master/Adafruit_ADXL345_U.h#L77

Oh I got it, thanks :) Just one last query though, I need to collect data at 50Hz for an activity tracking machine learning algorithm, which from my understanding meant for every second 50 values in the x,y,z axes have to be collected. If I adjust baud rate so that I get 'around' 50 values every second in the serial monitor, does that mean the values line up with the actual Data Rate of the accelerometer?

You should use the interrupt output (or the data ready signal in the ADXL's registers) to get each data point when it has actually been produced.

Alright, thanks for putting me down the right path, will look into this.


text:
Capturing interrupt on both edges when it's set on RISING or FALLING
I've been trying to capture rising edge of an IR sensor output. This sensor's Vcc connected to Arduino 5V and it has a digital output pin. I've observed the digital output pin on an Oscilloscope. It's not noisy.
When I attach a rising edge interrupt on digital pin 2. It somehow captures both rising and falling edges. This response is the same for when it's set for FALLING or CHANGE.
I've tried code at below both on Arduino Uno and
volatile bool caughtAnInterrupt = false;

void setup() {

  Serial.begin (19200);

  pinMode(2, INPUT);

  attachInterrupt(digitalPinToInterrupt(2), test, RISING);
}

void loop() {

  if (caughtAnInterrupt){

    Serial.println("Rising edge detected");

    caughtAnInterrupt = false;
  }
}

void test() {

  caughtAnInterrupt = true;
}

How much time between rising and falling edges, and what are you detecting, a square edge?

@MichaelT IR sensor outputs digital high when it has a object in front of it. So, it might be any time between rising and falling edges. As I specified in the answer, I found the solution. Probably I didn't observed signal properly on Oscilloscope and the signal had debouncing problem.

I've solved the issue with the reply by eventHandler to another post. Here it is;

The problem you are having is because the button glitches are
  producing many interrupts on each button press. You can find a good
  description and a way of solving it using hardware here.
Let me explain, when you press the button, the mechanical contact will
  have a transcient state in which it will fluctuate ON-OFF for a short
  period of time. The same effect might happen when you release the
  button.
One way of solving this problem is using a capacitor parallel to the
  load. Another "easier" way would be done by software. The idea is to
  set a fixed arbitrary time in which you don't allow new interrupts.
  You could use the millis() or micros() library to set this time. The
  code would look something like this.
unsigned long lastInterrupt;

void ngt()
{

  if(millis() - lastInterrupt > 10) // we set a 10ms no-interrupts window
    {

    state = !state;

    lastInterrupt = millis();

    }
}

This way you don't process new interrupts until 10ms have elapsed.
Note: adjust the time to your requirements.


text:
Testing a capacitor with a nodeMUC Lolin V3
Apparently it's possible to test the capacitance of a capacitor with an arduino. In this thread, someone tries to do the same on a NodeMCU but the conclusion is that it's enough to get the change in capacitantce, not the real value, and it's not "really stable" (reliable?).
I would like to get the real value of the capacitance (not just the change of the capacitance). Is there a way to do it with a NodeMCU Lolin v3?
If yes, how?
If no, will an arduino clone (like Elegoo or Geekcreit) be precise enough to give a real value of the capacitance?

An arduino uno has a high current output for a digital output pin and a high impedance analog input. The nodemcu has neither. An arduino uno clone is okay. Try a few examples that you can find. Some are accurate for small capacitance values, such as 100pF. You can start with this good example: https://www.gammon.com.au/forum/?id=12075 Please tell us what this is for. If you want to measure the soil moisture with a capacitance meter, then I think this is the wrong way.

Thanks for the link, this is a very good example. I just want to be able to test my capacitors, to see if they are working and to get their capacitance value.

And by the way, I have seen this 3€ arduino uno, do you think it will be precise enough for testing capacitors.

Yes, that will work. You need an extra driver for the ch340g usb serial chip.


text:
Arduino restarts when a function is called
When I call a function, get_split(), the Arduino restarts. I have tried to find what is causing this, but I have had no luck. Here is my code:
std::vector<std::vector<std::vector<std::vector<float>>>> get_split(std::vector< std::vector< float > >& dataset) {
  std::vector<int> class_values; // declares vector 'class_values'
  for (int i = 0; i < dataset.size(); i++) { // loops through each value in dataset (the dataset contains vectors)  and appends the last value in each vector to class_values
    class_values.push_back(dataset[i][dataset.size()]);
  }
  std::vector<std::vector<std::vector<float>>> b_index;
  b_index.push_back(std::vector<std::vector<float>>(999));
  std::vector<std::vector<std::vector<float>>> b_value;
  b_value.push_back(std::vector<std::vector<float>>(999));
  std::vector<std::vector<std::vector<float>>> b_score;
  b_score.push_back(std::vector<std::vector<float>>(999));
  std::vector<std::vector<std::vector<float>>> b_groups;
  for (int i = 0; i < dataset[0].size(); i++) {
    for (int j = 0; j < dataset.size(); j++) {
      std::vector<std::vector<std::vector<float>>> groups = test_split(i,  dataset[j][i], dataset); // gets the split of the dataset (assigns each vector in the dataset to either 'left' or 'right')
      float gini = gini_index(class_values, groups); // calculates the gini
      if (gini < b_score[0][0][0]) {
        b_index[0][0][0] = i;
        b_value[0][0][0] = dataset[j][i];
        b_score[0][0][0] = gini;
        b_groups = groups;
      }
    }
  }
  std::vector<std::vector<std::vector<std::vector<float>>>> vals;
  vals.push_back(b_index);
  vals.push_back(b_value);
  vals.push_back(b_groups);
  return vals; // returns the values.
}

This code is meant to check the gini of splitting a certain function (the gini_index() function works fine). Then it calls test_split which assigns the vector values into two sub-vectors in the vector groups, left and right. Then I just choose the split with the lowest gini.
When I delete everything in the function it doesn't restart, but I have deleted the first for loop, and also the part where it returns a vector, but still no luck. Also when deleting the for loop underneath the declaration of b_groups, it still doesn't work. I don't think it is a memory/storage issue because the Arduino IDE says that I'm only using 3% of that.
PS: I have used the library StandardCplusplus library to include vectors.

Have you tried calculating the cyclometric complexity of this code?  It looks horrible.  I think it is a memory issue, probably a segmentation violation.  The order or you loops looks quite strange, the inner and then the outer.  Have you tried running this on a desktop (Linux or Windows) to get some debug data.

I think this is a pure coding error, so you might get better feed back on Stackoverflow.

@Matt Okay - thanks. Sorry for asking this, but when you ask if I have tried running this on a desktop, what do you mean by that? Do you just want my to move my code to a desktop computer and upload it from there?

Please calculate the amount of memory you are allocating on the heap. My guess is that you have allocated more than the 8K byte available. Trim your data structures. Even the mega is a MCU. Program accordingly, i.e. with limited resources in mind.

Your code is very complex and running it in an environment where you have limited debug facilities is making life worse for yourself.
When an Arduino reboots it is usually because it has thrown a memory error.  This happens when you try and access memory that is no longer your program's to access (or never was yours).  In this case I originally suspected, based on the complexity of your code, that you were accessing a vector element that you could no longer access.
To prove this I 'ran it on a desktop', in my case a Windows 7 box with Visual Studio 2015 (but you could have used Linux, GCC and GDB).  This meant I wrote a little wrapper program and stubbed the functions you called.  This resulted in the error message shown below.
This is my 'desktop' code:
#include <vector>

std::vector<std::vector<std::vector<float>>> test_split(const int& i, const float& f, std::vector< std::vector< float > >& dataset)
{
    std::vector<std::vector<std::vector<float>>> vals;
    return vals;
}

float gini_index(const std::vector<int>& class_values, const std::vector<std::vector<std::vector<float>>>& group)
{
    return 1.0f;
}

std::vector<std::vector<std::vector<std::vector<float>>>> get_split(std::vector< std::vector< float > >& dataset) {
    std::vector<int> class_values; // declares vector 'class_values'
    for (int i = 0; i < dataset.size(); i++) { // loops through each value in dataset (the dataset contains vectors)  and appends the last value in each vector to class_values
        class_values.push_back(dataset[i][dataset.size()]);
    }
    std::vector<std::vector<std::vector<float>>> b_index;
    b_index.push_back(std::vector<std::vector<float>>(999));
    std::vector<std::vector<std::vector<float>>> b_value;
    b_value.push_back(std::vector<std::vector<float>>(999));
    std::vector<std::vector<std::vector<float>>> b_score;
    b_score.push_back(std::vector<std::vector<float>>(999));
    std::vector<std::vector<std::vector<float>>> b_groups;
    for (int i = 0; i < dataset[0].size(); i++) {
        for (int j = 0; j < dataset.size(); j++) {
            std::vector<std::vector<std::vector<float>>> groups = test_split(i, dataset[j][i], dataset); // gets the split of the dataset (assigns each vector in the dataset to either 'left' or 'right')
            float gini = gini_index(class_values, groups); // calculates the gini
            if (gini < b_score[0][0][0]) {
                b_index[0][0][0] = i;
                b_value[0][0][0] = dataset[j][i];
                b_score[0][0][0] = gini;
                b_groups = groups;
            }
        }
    }
    std::vector<std::vector<std::vector<std::vector<float>>>> vals;
    vals.push_back(b_index);
    vals.push_back(b_value);
    vals.push_back(b_groups);
    return vals; // returns the values.
}

int main(void)
{
    std::vector<std::vector<float>> dataset;

    std::vector<std::vector<std::vector<std::vector<float>>>> result = get_split(dataset);

    return fgetc(stdin);
}

Now you need to workout where it is crashing, easy in Visual Studio but very difficult on an Arduino.  However I would look at simplifying the code too.

I couldn't do all the work for you :)

You might want to look at the line b_score.push_back(std::vector<std::vector<float>>(999)); I suspect that is where the problem is (and the two similar lines above)

Yes, that did turn out to be the issue. Thank you very much


text:
Moving cursor on LCD and changing highlighted value
I have the code shown below. The goal is to change the value of hours, minutes or seconds based on where the cursor is placed.
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2); //format of display
}

void loop() {
    int hours = 11;
    int minutes = 11;
    int seconds = 11;
    lcd.setCursor(0,0);
    lcd.print(hours);
    lcd.print(":");
    lcd.print(minutes);
    lcd.print(":");
    lcd.print(seconds);
    lcd.noBlink();
    delay(300);
    lcd.blink();
    delay(300);

    if (buttons & BUTTON_RIGHT) {
      move cursor right;
      if(lcd.setCursor == lcd.setCursor(0,3) {
        minutes += 1 }

}

I though of a way to do this. I would have three variables and print each of these out with a default value. With the use of the buttons, the user should be able to move the blinking cursor to hours, minutes or seconds, and increase or decrease the value of the variable.
I would do this by seeing what location the cursor is at. For example, if the cursor was on minutes, I would write something like if(lcd.setCursor == lcd.setCursor(0,3) or lcd.setCursor == lcd.setCursor(0,4)) { minutes += 1}.
Of course these functions don't exist, so I am wondering what I can do to move a cursor and check its position.
Thanks in advance

Just keep track on where you put your cursor.

Firstly, you should set the time variables outside the main loop (as a global variable). If you put them in the main loop, the time would always reset to 11:11:11 after 0.6s of delay.

lcd.setCursor == lcd.setCursor(0,3)

I dont think you can do this (unless the function returns you with the location of the cursor, have to check the header file of the library).
Instead, you should keep track of the location of the cursor with another variable (as mentioned by gre_gor), say int curLoc. But note that you have to keep track of the range of values it can go. (0 < curLoc < 16)
To summarise, the code could look like this:
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

int hours = 11;
int minutes = 11;
int seconds = 11;

int curLoc = 0; //Current cursor location (x-axis)

void setup() {
  lcd.begin(16, 2); //format of display
}

void loop() {
  lcd.setCursor(0,0);
  lcd.print(hours);
  lcd.print(":");
  lcd.print(minutes);
  lcd.print(":");
  lcd.print(seconds);
  lcd.noBlink();
  delay(300);
  lcd.blink();
  delay(300);

  //move cursor right;
  if (buttons & BUTTON_RIGHT) {
    //Keep the tracker in range
    if(curLoc >= 0 && curLoc < 16){
    curLoc += 1;
    }

    if(curLoc == 3)
    {
      minutes += 1
     }

}


text:
How would I go about powering addressable RGB LED light strip? [Arduino Nano]
The addressable RGB LED I have is WS2812B. I plan on controlling the LEDs via an Arduino nano. I have a total of 188 LEDs to supply power to.
Would I require anything between the addressable RGB LED strip and the 12v power supply?
Would I require a 1000uF capacitor?

Would I require anything between the addressable RGB LED strip and the 12v power supply?

A suitable 5V regulator (assuming 5V LED strip)

Would I require a 1000uF capacitor?

For what? A suitable 5V regulator won't need one. An unsuitable one would be improved by it, but still be unsuitable.

Regarding the 1000uF capacitor - I was just guessing from looking a diagrams which included what I would be using.

Electronics is not about guesswork. It's about hard and fast rules and formulae.


text:
Parsing data in arduino?
I just started working with Arduino and in my project I am trying to achieve the COMM between two Arduino using HC-05 in master and slave mode respectively, I configured it all successfully.
Now I want to send three HCSR-04 distance sensors data from master Arduino to slave Arduino via HC-05. I am sending each sensor data separated by " | ". following is the example format., which I got in serial monitor by connecting the master Arduino directly to PC via USB.
168|200|76
167|200|68
166|200|76
168|200|77
Now the problem is I am not able to read and parse this on the slave side. I tried with serail.readbytesuntill but I could not succeed. Please help me out that how I can read it and parse it.
Thanks in advance.

what does this mean? not able to read and parse ...... you either get no data, so there is nothing to parse or you get data, but you are unable to parse it    .............. what does this mean? I could not succeed ..... please describe what actually happens

it would be helpfull if you add the parts of your code ment for sending and reciving the data. Without it is difficult to find an answer.

As you can see from the comments Birender Brar, we need more information to be able to help you.
One way to accomplish your goal would be to:
Use Serial.readBytesUntil('\n', buffer, length) on the slave device to "read" the data in to a char array. The serial monitor can be set to automatically send a \n character for testing purposes, but your code on the master will have to do this. Send the data 168|200|76 with a \n appended to the end of the data: 168|200|76\n
Parse the data. Here is a example sketch that parses the data in to a integer array.
// Use Serial.readBytesUntil('\n', buffer, length)
// to fill the char array / string.
char str[] = "168|200|76\n";

// Set array size to maximum number of integers you will receive.
uint16_t myArray[3];

void setup(){

  Serial.begin(9600);

  int counter = 0;
  char* pch = strtok(str, "|");

  while(pch != NULL){
    myArray[counter] = atoi(pch);
    pch = strtok(NULL, "|");
    counter += 1;
  }

  // Print out the contents of the integer array.
  for(int i = 0; i < counter; i++){
    Serial.println(myArray[i]);
  }
}

void loop(){}


text:
Button that increments a counter
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0,0);

}

void loop() {
  uint8_t buttons = lcd.readButtons();
  int a;
  if (buttons) {

    lcd.clear();
    lcd.setCursor(0,0);

    if (buttons & BUTTON_UP) {
      a+= 1;
      lcd.setCursor(0,0);
      lcd.print(a);
    }
  }

I am trying to make a counter that increments everytime the button UP is pressed. Currently, all it is doing is printing 1 everytime the button is pressed. Any help would be nice! Thanks!

Try "static int a = 0;"

Your code, simplified, is:
void loop()
    int a;
    a += 1;
}

The problem here is that, by putting the declaration of your counter variable within the loop() function, you've made it local to that function. Every time loop() is called, a new variable a is created, initialized to zero, and then incremented.
You want to move the declaration outside of loop(), creating a global variable that will remain in existence and maintain its value after loop() exits, so that the value is still there when loop() is called again:
int a = 0;
void loop() {
    a += 1;
}

(This could also be done with a static variable, but that's probably beyond the scope of this question.)


text:
Make action happen after time is passed using interrupts
I am trying to create a code which prints to the LCD a message once a certain time is passed.
#include <Time.h>
#include <TimeLib.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  setTime(02, 10,00, 14, 03, 2016);

  //pinMode(13, OUTPUT);
  pinMode(2, INPUT);
  digitalWrite(2, LOW);
  attachInterrupt(0, blink, CHANGE);
}

void loop() {
  lcd.setCursor(0, 1);
  char time_out[16];
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());//use %x to get hex
  lcd.print(time_out);

  int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
  lcd.print(totalSeconds);
  if(totalSeconds > 7806) {
    digitalWrite(2, HIGH);
  }
}

void blink() {
  lcd.print("time passed");
}

The setup uses the Time lib to set a date. It also  sets pin 2 as an INPUT and sets it it LOW. The attachInterrupt checks if pin 2 (0), changes, then function blink should execute.
In the loop, I am creating a string that prints out the time and displaying it to the LCD. I am also converting the time to seconds, so that I can easily compare two times. After 6 seconds (the timer starts at 7800), I am changing the value of pin 2 to HIGH.
This should indicate a change in its state and should and trigger blink, but it does not. Can anyone spot the mistake I made? Thanks in advance.

Check what actually happens if you write to a pin that is defined as input. This does not work as you are assuming.

Which board are you using ?

Since I don't have enough reputations to comment on your question I am going to drop my two cents here.
Since your question is a little bit vague, I am going to suppose that you don't want any external interrupts thus, you don't need to use the attachInterrupt function. I am going to suppose that there is no need to use timers' interrupts as well.
Have a look at the following code:
#include <Time.h>
#include <TimeLib.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  setTime(02, 10,00, 14, 03, 2016);
}

void loop() {
  char time_out[16];
  lcd.setCursor(0, 1);
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());//use %x to get hex
  lcd.print(time_out);

  int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
  lcd.print(totalSeconds);
  if(totalSeconds > 7806) {
    blink();
  }
}

void blink() {
  lcd.print("time passed");
}

You should know the following:
Commands inside void loop() is going to be executed for ever again and again. Especially lcd.print(time_out);. You had better refresh the LCD every 1 second.
After 6 seconds blink() is going to be executed many times (maybe forever) since it is inside the loop and if(totalSeconds > 7806) is going to be always true.
If you have any question let me know in the comment section.

To do what you want, pin 2 would need to be an output.  As an input you have no control over its state when you write it low.  It may be hanging there floating in a high state and when you write high to it and turn on the pullup that may or may not actually be a change of state.
Doing a print to the LCD may not work in an ISR.  Remember that during the ISR all other interrupts are disabled and depending on how your lcd library works it may not print anything from inside the ISR.
Even if it does print "time passed" upon being triggered by the line at the end of loop, a few microseconds later loop would repeat and that would be overwritten by the stuff that loop writes to the screen.  So even if it did work you'd never know.

Instead of having your ISR print something to the screen, have it turn on an led or something so you know it actually triggered.
Try this instead and see if it is closer to what you want: (uncompiled and untested as I don't have the libraries)
#include <Time.h>
#include <TimeLib.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

boolean passed = false;

void setup() {
  lcd.begin(16, 2);
  setTime(02, 10, 00, 14, 03, 2016);

  //pinMode(13, OUTPUT);
  pinMode(2, OUTPUT);
  digitalWrite(2, LOW);
  attachInterrupt(0, blink, CHANGE);
}

void loop() {
  if (passed) {
    lcd.setCursor(0, 1);
    lcd.print("time passed");
    while(1);  // freeze here time is up
  }
  else {
    lcd.setCursor(0, 1);
    char time_out[16];
    sprintf(time_out, "%02u:%02u:%02u", hour(), minute(), second()); //use %x to get hex
    lcd.print(time_out);

    int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
    lcd.print(totalSeconds);
    if (totalSeconds > 7806) {
      digitalWrite(2, HIGH);
    }
  }
}

void blink() {
  passed = true;
}


text:
Using EEPROM to write a counter value
I have made a program that increments a counter everytime the up button is pressed. I am trying to write this value to EEPROM, so that when I turn my board off and on again, the value before power off is shown on screen.
I wrote this code but the value doesn't seem to be written to EEPROM. The counter incrementation works fine.
#include <EEPROM.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

int addr = 0;
byte value;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0,0);
}

int a;
void loop() {
  uint8_t buttons = lcd.readButtons();
  if (buttons) {

    lcd.clear();
    lcd.setCursor(0,0);

    if (buttons & BUTTON_UP) {
      a+= 1;
      EEPROM.write(addr, a);
      value = EEPROM.read(addr);
      lcd.print(value);
      delay(100);
    }
  }
}

Thanks for the help!

The only time you read the EEPROM is right after writing it, which is pointless. You need to EEPROM.read() in setup() if you want the value restored at boot time.

That did the trick. Appreciate it man!

Also you only want one value to store the counter in, not two. Either a or value - take your pick.

The EEPROM.read and EEPROM.write read and write only a single byte. You can use EEPROM.put and EEPROM.get to read and write an (unsigned) int or a (unsigned) long.

I see you always use address 0, since EEPROM has a limited write life (like 10K or so), maybe it's best to use difference addresses. 10K presses is a lot, but not unrealistic over a long time probably.

@MichelKeijzers: The EEPROM is rated for 100K write cycles.

My normal EEPROM method is to set a variable to the desired value, along with a timestamp variable. Reset the timestamp variable every time the button is pressed. Then when a certain time has elapsed since the last press write the value to EEPROM. That way if you press the button 50 times in quick succession you only get one write to EEPROM. A couple of seconds delay on the write works well.

just add a = EEPROM.read(addr); in your setup
also, you can remove byte value and use a you wrote to memory in the previous line


text:
Connect Multiple L293D Motor Controllers to Arduino
I would like to connect 3 L293D Motor controllers to an Arduino Uno with the hopes of powering 6 different dc motors. I was just wondering how to wire this being that one motor controller (which allows for 2 dc motors to be controlled) already takes up most of the pins on the Arduino, thanks.
Below is the wiring diagram for how I am hooking up 1 L293D motor controllers to the Arduino.

Hey you can use Adfruit Motor Shield v2 [https://www.adafruit.com/products/1438] it allows 2 connections for 5V 'hobby' servos, Up to 4 bi-directional DC,Up to 2 stepper motors.

If you want to make your own circuit.. then you need two IC 74HCT595(8-bit serial-in, serial or parallel-out shift register). You have to wiring with your arduino and L293D you can go this way..
 . This Circuit diagram is an Idea, don't think its actual circuit you have to modify this schematic accroding to your application.
Data Sheet link 74HCT595 DATASHEET

if I were to wire exactly this diagram, however, would it still work for controlling 6 dc motors?

The suggestion of using an Adafruit Motor Shield V2 for Arduino seems fairly good, although that particular shield controls only four DC motors at once.  That shield has a dedicated PWM driver chip on it, which removes the overhead of motor and speed control from the MCU.  That might allow you to drive four motors via the shield, and two via wires from the Arduino; or, stack two motor shields on the Uno.
If you definitely want to drive six motors from the Arduino, you may need to add a couple of control chips.  You could add a 74HCT04 hex inverter and a 74LS595, to create inverted drive signals and enable signals.  For example, the first PWM drive would go to L293 pin 1A and to '04 pin 1A; the first '04 output, 1Y, would drive L293 pin 2A.  One of the '595 outputs would go to L293 pin 1,2EN.
Alternately, you could use two '595s, with outputs to control L293 pins 2A; 4A; 1,2EN; and 3,4EN on each of three L293's.  The six PWM outputs from the Uno would go to 1A and 3A on the several L293's.  Using motor shields probably is a better idea, however.


text:
Using a transistor to get 100mA on a IR led
What i saw is that the led use 1.3V on 100mA with a 1:10 Cycle (100ms). Im currently at 30mA using only a 100 resistor, but the range of the led is 20cm at max, i want to get at least 2 meters.
Since i know the max output of the Arduino pin is 40mA i need to use a transistor to get the 100 i want. And that is the problem, i read a lot about how transistors works but i can't yet understand how can i achieve 100mA using a transistor.
I did the math using 5v and got 37R.
Is this correct? So i need to use a 37 ohms resistor to get the 100mA i want?
And this resistor is going between the digital input and the transistor base, correct?
Im using a NPN 2n2222 and reading the datasheet 100mA is easy job for this transistor.
I appreciate any help.

you want to saturate the 2222, then pretend avail ma is infinite, resist from there

Sorry i forgot to reply, but thanks a lot @dandavis your comment helped me a lot.

@dandavis what do you mean by "saturate"? what equations should be used?

@shinzou: that's now explained in the accepted answer

Here is a diagram from Peter Bennett's answer to an  Electronics Stackexchange question,  How much voltage to give my IR LED?:

As you can see, the current-limiting resistor is in series with the IR LED and the transistor's collector.  The base resistor is large relative to the current limiting resistor, because this transistor amplifies base current by a factor like 100.
The 1000 Ω base resistor is ok for loads into the neighborhood of 100 mA; if you plan to drive a larger load, use a smaller base resistor.  As noted in the 2N3904 datasheet, hFE may be as small as 30 when  IC = 100 mA.  To ensure transistor saturation, arrange that  hFE*(VCC-VBE)/RB exceeds desired collector current.
2N2222 specifications are similar to those of the 2N3904 mentioned in the question, but hFE drops off more slowly (as IC increases) for the 2N2222.
See the Electronics Stackexchange question linked above for more discussion and further links.

I have some questions, can i use the 5V arduino output as the source of energy to the led? (in the diagram is the 3.3V input).
I did the math here and i got 22.5R for 80mA instead of the 18R he said is nedded to get 80mA, why i got a different number? For the voltage i did 3.3V - 1.5V (the current of the ir led).
How can i know the correct number of the base resistor? Could i use lets say a 10kR?
Nevermind about the first question, i saw after that the led actually use 1.8V

I edited a bit about the base resistor, and included an equation about it.  With R1 = 10KΩ, Vcc = 5, Vbe = .7, you would get 0.43 mA into the base, and say 43 mA load current (if hFE is 100); so 10KΩ is too much resistance.  Re using  5V arduino output for LED current, most Arduinos are ok supplying a few hundred mA to auxiliary circuits like LEDs, if incoming raw voltage is not too high.  The descriptions at arduino.cc sometimes say how much current can be drawn through the onboard regulator, but to be certain may require reading the regulator's part number and looking it up on the web.

I see, eletricity is hard to gasp but im slowly learning. Thanks for all the help.

What are the parameters for hFE*(VCC-VBE)/RB in the picture? Also where are they in the transistor's spec?

For the 2N3904 shown in the diagram, DC Current Gain hFE and Base-Emitter Saturation Voltage VBE(sat) are shown on page 2 of the spec sheet, in the “ON CHARACTERISTICS” table.  Re other parameters used in the  hFE*(VCC-VBE)/RB equation: VCC depends on Arduino supply voltage, and  RB = R1.

Increasing the power to the LED isn't the best way of increasing the distance. In fact it's the worst way.
The 100mA is only for a small duty cycle. You can power it with 100mA but only for a fraction of the time. The overall average light output won't be any more than at 30mA.
The problem you are actually suffering from is the fact that your receiver can't distinguish the LED's light from the background light. That is simple to overcome though. You just need to modulate your LED with a high frequency (typically 30kHz or higher) and perform a high pass filter and amplification on the receiver.
Exactly the same way that remote controls do it.
That way you can distinguish the LED (flashing at a given frequency) from the background light (static brightness or relatively very slowly changing).

I know i can only power for a fraction of time. Thats why i said it was a 1:10 cycle (1 cycle on and 10 cycles off with 100ms per cycle).
Im already sending the signal with 32kHz and i can't filter the receiver since i didn't make it, im only doing a controller not a receiver.
Anyway it worked as far as i know. The led is receiving about 70mA. What was before a 30cm range is now about 7m range. So i guess i did something right sending more amperage. In theory i could go even further and try to reach 80mA but im happy with the final result.
Anyway thanks for the tip.


text:
Arduino connection to brainwave analyzing module
I want to connect a TGAM module (detecting brainwaves) to an Arduino Uno. I know little of electronics, can someone advise me? To which pin of the Arduino should I connect the TGAM? How to get the right electrical supply from the Arduino to the TGAM? Here is data about the TGAM module: http://www.seeedstudio.com/document/pdf/TGAM%20Datasheet.pdf
The R pin on the TGAM module is providing digital data as an asynchronous serial stream of bytes: http://developer.neurosky.com/docs/doku.php?id=thinkgear_communications_protocol

As per the datasheet you provided, it is quite straight forward.
It can be connected to RX (pin 0) and TX (pin 0) pins of the Arduino Uno.
But, the pins have to be crossed;
Arduino RX (0) <> TGAM T (TX)
Arduino TX (1) <> TGAM R (RX)
Arduino 3.3V <> TGAM + (VCC)
Arduino GND <> TGAM - (GND)
Good luck.


text:
Port is not available
I'm trying to connect my Arduino Galileo to Linux via Arduino IDE. Sometimes I'm able to do so, but other times I ge the following error 'Board at /dev/ttyACM0 is not available'. With dmesg I can see that the device is not recognized, a deeper look at this issue led me to find out that a ls on /dev/ttyACM0 shows this:
-rw-r--r-- 1 root root      296 Apr  8 20:14 /dev/ttyACM0

Here I notice that there's a missing 'c' before the permissions that is common to every other /dev/tty*. I would like to know the reason why and if this is the cause for my problem. This seems to be suspicious..or maybe I'm mistaken...please correct me if I'm wrong.

If "c" is missing then it's a regular file. Probably something tried to open it with the O_CREAT flag without the device being there, and that created the file. You may get some clue as to what it was if you cat the file.

@Majenko is there a way to 'revert' it?!

Delete the file, then plug the board in.

Well...it worked! Not sure why, but this /dev/ttyACMO always end up to be a regular file, and I have no clue of what is responsible for it


text:
Why is CLK_FLASH separate from CLK_CPU?
The ATmega328P has a separate clock signal for Flash and EEPROM (CLKFLASH) than it has for the RAM (CLKCPU). Why is this?

It's to do with programming the chip. When you are programming the chip using an external programmer you need the flash and EEPROM to be running. However you don't want the CPU to be running since you are doing things with the flash that it would normally access. By having the CPU (and RAM) on a separate clock you can clock the flash without clocking the CPU and all is well.


text:
Do AVR delay functions (_delay_us() and _delay_ms()) use timers?
I'm trying to determine if the AVR delay functions _delay_us() and _delay_ms() use timers in such a way that I can't use those timers for other functionality in my code. If so, what timer does it use?
For reference I'm using an Arduino Uno with ATmega328, but I imagine if it's an AVR function it must work similarly on other devices.

No, these macros expand to calls to __builtin_avr_delay_cycles(),
which are compiled into delay loops. It should be noted that:

the arguments to these macros should be compile-time constants, they
can be floating point
the macros are cycle-accurate, e.g. _delay_us(0.125) will take
exactly two CPU cycles on an Uno
whereas the CPU time used by the call is exactly what you ask for,
the physical time will be larger if the call gets interrupted.

Thank you! I was worried I wouldn't be able to use one of the timers if I used the delay functions.

No.
The long answer is that you can delay via timers, a little bit more painfully within the Arduino framework, or much more efficiently if you are willing to move outside of the arduino framework.
I wrote a set of systick clones for many of the popular 8bit mcus precisely for that.


text:
Which of the clock sources are actually internal to the ATmega328P?
I am trying to determine exactly what all of the fuse settings correspond to on the ATmega328P. The options for the CKSEL bits are:

1111-1000: Low Power Crystal Oscillator
0111-0110: Full Swing Crystal Oscillator
0101-0100: Low Frequency Crystal Oscillator
0011: Internal 128kHz RC Oscillator
0010: Calibrated Internal RC Oscillator
0000: External Clock

Clearly, the clocks labeled "internal" are part of the "guts" of the microcontroller. No external components are required to use those clock sources. The external clock is clearly an external source.
My question is this: are the low power, full swing, and low frequency sources built in to the microcontroller itself, or do they require an external crystal oscillator to be purchased and connected to the clock pins? This is not 100% clear from reading the data sheet. (Although I am under the impression that they are not internal to the device.)

If it requires a crystal, as the ones in question clearly state, then obviously you need to connect a crystal (and load capacitors).  Or use a ceramic resonator.
Only those labelled as internal are internal. Everything else is external.

Thanks. That's what I thought, but the fact that it said "external" for one, and not the others, confused me.

An external clock is a specific physical thing - as is a crystal.


text:
What is the purpose of the I/O pin capacitor on the AVR microcontroller?
What is the purpose of the capacitor on the I/O pins on the ATmega328 (I imagine it's on other AVR microcontrollers as well)? Is it to reduce noise from other parts of the microcontroller?

To make explicit the implicit parasitic capacitance on the pin.

So, it's not actually a capacitor, but just drawn in to the schematic to demonstrate that the pin has capacitance?

Correct. The input is actually the gate of a MOSFET. That gate acts like a capacitor. So they show it as one in the simplified block diagram.

The pin does not have a capacitor added to the integrated circuit (IC). Rather this capacitor is drawn to show that the input has capacitance that you need to be aware of.
The input drives a MOSFET - and as we know, MOSFETs have some parasitic capacitance.
For more information on parasitic capacitance of MOSFETs see these pages:

MOS Transistor parasitic capacitances - OnMyPHD.com
MOSFET Parasitic Capacitance and Its Temperature Characteristic - ROHM


text:
How to get location of the hand indoors
I made a glove that tracks the positions of the fingers, but I don't know how to get the location of the hand relative to the person using them. Any suggestions? It should be quite accurate but I would really like to make even a rough prototype of it.
Ps. I'm using a Arduino Nano (atmega328p) to send and process the positions of the finger to a Java application through serial if you wanted to know.

Are you talking about a person and their own hand/fingers?

Yes. It reads the positions using a pressure sensors.

I think the easiest option is to measure the angles of the shoulder, elbow and wrist. Then use some math to calculate the position of the hand, with respect to the shoulder.

The only way to check the relative position is, first to define, what is the absolute position of a person, is it his other hand, his heart, his head, his foot?
When you defined the absolute position of the person, then you need to use a sensor at that absolute position that can measure the current position, e.g. GPS (if outside), but this is not accurate.
You also can use a gyroscope or device similar to what you use for the glove. When you initially keep them together you now the relative position (around 0.0). Than you can track movement differences of both the glove and the absolute position, send it to the glove (or vice versa) and calculate the difference. There might be calibration issues.
Another way is to use a camera and continueously check for a line of sight signal (IR, led), but this also can have issues (like distance measurement, what if there is no line of sight etc).

I tried using visual tracking but it might be quite impractical. Leap Motion has done some good work with hand tracking but I have no idea how they have accomplished it.

GPS would be way too for hand location. Ultrasonic sensing might work but I guess it might bounce from every object and create false readings.

I also don't have experience with this. I had a similar problem. Tracking the relativie position of a moving person and a static object, but even that is hard (line of sight, MPU6650 seems unreliable after half an hour, but maybe there are better gyroscopes. But you have two moving 'objects' (hand + absolute position). Also you can use one static object, and two relative positions (glove + absolute person) and send changes to the static object, but it will have also cons.

And ultrasonic does not work when line of sight is not present.