text:
Is there a way to traverse a filesystem and read files with an arduino?
I recently got into arduino and I want to set up something big. My project will need the arduino to be able to get into a specific directory of a windows (later may change to linux but for now windows) computer which will have some files with values required for the arduino to run.
Is it possible to set it to go to a fixed path and open a file with a specific name and get it's contents?
Ideally I would want those values to be stored to my micro sd so I do not load too many things on memory as my board is a Leonardo and the code is quite extensive already. (The board can be changed if needed)
Any help/ideas are appreciated!

what kind of files are on the windows machine that you wish to retrieve?  .....  set up a web server on the windows machine .... the Arduino could get the files as a web client

The Arduino has no access to the file system on a PC.  All it has is a serial connection with which it can communicate with some program running on the PC. The code that is handling the PC's file system would have to run on the PC itself.

Leonardo has USB for HID.

@Juraj how would that help?

It would not. But it is not true that it has only a 'serial' connection. (and I know that USB is serial communication too)

@Juraj Strictly speaking, yes it is true. The "S" in USB stands for Serial. It has a serial connection - over which a number of protocols are layered. One of which itself emulates another serial connection.

I was slow with edit of comment

so Win+E starts Explorer, some shortcut goes into path field, type in the path, Enter, Tab to pane. the 'serial' HID can do this

But how do you then get the data back to the Arduino? It can't see the screen.  You'd basically have HID writing a program on your PC that reads the data and sends it down through the CDC/ACM channel. Quite a task, and really a bit silly. Just write the program for the PC and have it communicate through CDC/ACM alone - that way it doesn't mess with your desktop session and interrupt you. Or use a network connection instead and collect the data from a website / online service.

I only wanted to indicate how the idea of controlling the PC could emerged

This could get complicated.
You'll need to develop a USB interface on your Arduino to "talk" to the PC.  Then you'll need to write an application (use whatever language you feel comfortable with - that's an entire religious discussion for another place and time) that "listens" for the Arduino's USB connection and does most of the legwork.  Think of the PC application as sort of a "script server", allowing the Arduino to make cryptic requests ("FCNT" requests a 'File Count' on your target PC folder, that sort of thing) which the PC application will then return data from, as needed.  (In the previous example "FCNT" gets a file count of a predetermined folder - which would return a four-byte [integer] value revealing the results of the file count.)  From this point you could add additional scripts and functionality, allowing your Arduino to make abbreviated (sometimes wonky-seeming) calls to the PC, and have the PC do what is necessary to fulfill those requests.
In the example I hastily described above, your Arduino sends "FCNT" and then "listens" to the USB interface, eagerly awaiting the return value that it knows will be a four-byte response.  If the PC application were properly programmed, you could get slick with your command calls, sending "XFR #" which asks the PC application to "transfer file [#] to me" at which time the Arduino goes into "paddle board" mode, where it receives data from USB and immediately transfers it to the MicroSD until  is "seen" in the data stream, at which point the Arduino returns to normal code operations mode.
Of course, your PC application will need to be extremely fault-tolerant in order to prevent sending your Arduino bad data or worse, sending it into a state that can't be easily recovered, such as if the Arduino "thinks" it's expecting a file and goes into "wait for transfer" state, but the file it requested doesn't exist because it got deleted sometime between the file count request and the transfer request.  The Arduino would appear to be "hung up" because it would be in "File Transfer" or "paddle board" mode, and not looking for other messages or awaiting other operator stimulus.
Due to the different architectures, there really is no simple way to interface an Arduino to a PC.  Sorry about that.


text:
Avrdude fails to verify after upload
I'm using the most recent Arduino IDE to upload a sketch to an Arduino Uno, and the upload seems to succeed, but the final verification step fails with the error:
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: reading input file ".build_ano/uno/firmware.hex"
avrdude: writing flash (30908 bytes):

Writing | ################################################## | 100% 5.01s

avrdude: 30908 bytes of flash written
avrdude: verifying flash memory against .build_ano/uno/firmware.hex:
avrdude: load data flash data from input file .build_ano/uno/firmware.hex:
avrdude: input file .build_ano/uno/firmware.hex contains 30908 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 3.96s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x7800
         0xff != 0xfe
avrdude: verification error; content mismatch

avrdude: safemode: Fuses OK (H:00, E:00, L:00)

avrdude done.  Thank you.

I've re-ran the upload several times, and tried different USB cables, but I get the exact same verification error each time. Does this mean the upload effectively failed (presumably because the flash memory has gone bad), and that my sketch is not running on the Arduino? Is there any way I can fix this?
I tried uploading to a different Arduino Uno, and I received the exact same error.

Try uploading a simply sketch link blinking the onboard LED on pin 13.

@AndreCourchesne, That works. I only get the error for my sketch.

Genuine Arduino or cheap chinese knock-off?

I think your sketch is to big. The Uno has 32k of flash. 2k is used by the bootloader leaving 30k or 30720 bytes. Your binary is 30908 bytes.

So here is my official answer ;-)
Your sketch goes above the 30k flash available on the Arduino Uno.
Yes the Uno has 32k of flash, but 2k is used for the Arduino bootloader. if you convert 0x7800 in decimal that gives you 30720 which is exactly 30k. And your sketch is 30908 bytes so it's 188 bytes too long.
Try optimizing it.
A second alternative would be to use the Optiboot bootloader replacement (https://github.com/Optiboot/optiboot) which only uses 512 bytes.

This seems to be the cause. I flashed a bootloader from a more recent Arduino IDE. I'm assuming it comes with that more efficient bootloader, because it fixed the error.

source: Stack Exchange

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

sort: votes


text:
Arduino servo seems to time out after code runs for some amount of time
I am running a simple servo program that swings the servo back and forth, it is essentially pressing a button continuously. However, after some time the servo stops moving and it seems like the code stops. I have no code in the program to tell it to stop and I am uploading from a sketch. Can anyone tell me why the servo will stop after some amount of time? is this some kind of safety or programmatic end that is used when you use the sketch compiler to run code?
Here is my code:
#include <Servo.h>

int servoPin = 9;
Servo servo;

int servoAngle = 0;

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    servo.attach(servoPin);
}

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

    int randnum = rand()%(40000-1000 + 1) + 1000;
    int randnumreturn = rand()%(600-350 + 1) + 350;
    servo.write(45);
    delay(randnum);
    servo.write(22);
    delay(randnumreturn);
}

What is your power source?

my laptop, i have the board plugged in through the usb cable used to download code onto the board

How long do you normally have to wait for it to stop? Is your laptop going to sleep?

int in AVR architecture is signed 16 bits. This means 40000 is actually an overflow if it gets assigned to an integer. It would work in most cases, but when the resultant number is > 32767, you would get a minus value, which may cause delay not to work properly.
In order to solve the issue, you may either use long int for randnum or use a random interval smaller than 32768.
Edit: I did some calculation, if you hit exactly 40000 you would delay for 4294974529 milliseconds (+/-1). Any value over 32767 will cause delays that are extremely long.

Actually, 40000 is a long int literal, and the whole expression at the right of = is computed as a long int. The overflow happens when that expression is assigned to int randnum.

I'd suggest you complete your answer by mentioning what to do to solve the problem rather than just explaining it. Here, this is a matter of changing declarations of random and randumreturn to unsigned int.

@EdgarBonet I am clarifying so that it would be understood better.

@jfpoilpret Or using a value less than 32767. I am updating for possible solutions.

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


text:
Sending data via bluetooth
I am trying to both send and receive data using bluetooth module.
Receiving data works fine with this code:
void setup() {
    Serial1.begin(9600);
    Serial.begin(9600);
}

void loop() {
    if (Serial1.available()) {
        Serial.println(Serial1.read());
    }

    delay(20);
}

But I cannot send any data. This is what I am doing:
void loop() {
    if (Serial1.available()) {
       Serial.println(Serial1.read());
    }

    delay(20);

    if (digitalRead(bluetoothInput) == HIGH) {
        Serial1.write("2");
        // only "send" prints. Nothing in android terminal
        Serial.println("send!");
        delay(1000);
    }

    delay(20);
}

What am I doing wrong?
I am using Arduino Leonardo and Bluetooth terminal app on Android device.

Are you actually using softwareserial?  On the leonardo you are probably using the hardware UART, so you should remove that tag.  In terms of your problem, have you received any data?  If it is failing in both directions you likely have not paired the devices, have the baud rate misconfigured or your Android app is broken.

As I wrote receiving data works fine. I cannot only send data from arduino. And I've deleted the tag. Thanks for noticing.

Do you have BT module with 5V to 3.3V level shifter? Does BT module works if you wire it as loopback (tx pin connected to rx pin without arduino)?

I've tried connecting it as loopback but it doesn't work either. My module is Sparkfun mate gold

I've found the problem
It should be:
Serial1.println("2");

instead of:
Serial1.write("2");


text:
creating table in 24LC256
here i am doing some project with the help of Arduino UNO with External EEPROM (24LC256),
 All i want to create table and wants to  store all  data into  24LC256 External EEPROM,there are many library for internal EEPROM to create table with limited data as per size of arduino EEPROM but i have huge data to store so have to use External eeprom to do, so  i can't find any proper library for doing that.!
can anyone tell me how to do that...
any suggestion..Please help me..
thanking you..

I don't quite understand the question. Are you looking for an Arduino library to use (read from and/or write to) the 24LC256?

Creating tables is a database thing. What are you actually trying to do?

Simplest way to create a table is to view it as a vector of struct's. For performance it is good to make the struct size a multiple of the EEPROM page size.
struct row_t {
  ... column fields ...
};

uint32_t row_addr = TABLE_START_ADDR;
row_t data;
data.column = value;
...

eeprom.write(row_addr, &data, sizeof(data));
row_addr += sizeof(row_t);
...

Basically you need to map a two/multiple dimensional table onto a one dimensional address space (of the EEPROM). The programming language can help with some of the calculations (and hide them).
Cheers!

Exactly i want to know what's library do i have to used and how...?

Did you do a web-search or check the arduino playground? You could for instance start here; http://playground.arduino.cc/Main/LibraryForI2CEEPROM


text:
GSM module connected with arduino uno giving garbage values in response
I connected a GSM module with the Arduino UNO. The connections are as follows:

Gnd of gsm -----> Gnd of arduino
TX of gsm  -----> pin 9 of arduino
Rx of gsm  -----> pin 10 of arduino

GSM is powered from a 9V-1Amp wall adapter.
The GSM is performing according to all the AT commands (like making a voice call, hanging a call, answering a call) which are given, but it is displaying garbage values on serial monitor in response.
Here is the code:
#include <SoftwareSerial.h>
SoftwareSerial myserial(9, 10);

void setup() {
    Serial.begin(115200);
    myserial.begin(9600);
    myserial.println("ATDXXXXXXXXXX;");
    delay(30000);
    myserial.println("ATH");
}

void loop() {
    if (myserial.available()>0){
        Serial.println(myserial.read());
    }
}

What could be reasons for the GSM to output garbage values and how can I resolve it?

115200 baud is at the top end of what software serial can handle. It's probably failing miserably. Better to use hardware serial on a board with multiple UARTs.

@Majenko from the code, the OP is using SoftwareSerial at only 9600 then that should be fine.

@jfpoilpret It was hard to tell since the code was such a mess. Yes, I could have formatted it myself, but that's the job of the OP to do. If they can't even be bothered to do that, then... meh...

Could you post the garbage (and its value in hexadecimal if unprintable) you get?

    Serial.println(myserial.read());

myserial.read() returns an integer. That integer is either the ASCII code of the next character in the buffer, or -1 if there is no character to read.
You then print that integer, each one on its own line.
So the response "OK\r\n" from, say, "AT\r\n" would look like:
79
75
13
10

Instead you need to write the data, not print it:
Serial.write(myserial.read());

Also, the way you have written your code, you will get no response for 30 seconds - that is, until everything has already happened. Only after it has all finished will you get some feedback - and that may not be complete since you may overrun the buffer depending on what the modem sends.

I tried using Serial.write() in place of Serial.println() but still I am getting the garbage values. The module is not responding even while sending an AT command through Serial Monitor.


text:
Arduino Uno alarm interrupt
I am trying to create a temperature-humidity monitor using Arduino and I want to power it using a battery. So, power efficiency is of interest. I am trying to put the Arduino to sleep for x-time (10sec for testing now). I am using a DS3231 alarm as an interrupt on pin 2 to wake-up. I am using the tutorial here along with its associated RTClibExtended library. Here is the code I am using:
#include "DHT.h"
#include <RTClibExtended.h>
#include <Wire.h>
#include <LowPower.h>
#include <stdlib.h>
#include <avr/interrupt.h>      // library for interrupts handling
#include <avr/sleep.h>          // library for sleep
#include <avr/power.h>          // library for power control

#define DHTPIN 7     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
#define wakePin 2    //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW

RTC_DS3231 rtc;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int interval_sec=10; //An alarm every 10 sec
DHT dht(DHTPIN, DHTTYPE);

void setup () {

  Serial.begin(9600);

  delay(3000); // wait for console opening

  /**RTC**/
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

  /**INTERRUPT**/
  //Set pin D2 as INPUT for accepting the interrupt signal from DS3231
  pinMode(wakePin, INPUT);
  Wire.begin();
  //clear any pending alarms
  rtc.armAlarm(1, false);
  rtc.clearAlarm(1);
  rtc.alarmInterrupt(1, false);
  rtc.armAlarm(2, false);
  rtc.clearAlarm(2);
  rtc.alarmInterrupt(2, false);

  //Set SQW pin to OFF (in my case it was set by default to 1Hz)
  //The output of the DS3231 INT pin is connected to this pin
  //It must be connected to arduino D2 pin for wake-up
  rtc.writeSqwPinMode(DS3231_OFF);

  Serial.println("Initialisation complete.");
  delay(100); //Allow for serial print to complete.
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    /**Temperature and Humidity**/
    // Reading temperature or humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
    float h = dht.readHumidity();
    // Read temperature as Celsius
    float t = dht.readTemperature();
    // Read temperature as Fahrenheit
    //float f = dht.readTemperature(true);

    // Check if any reads failed and exit early (to try again).
    //if (isnan(h) || isnan(t) || isnan(f)) {
    if (isnan(h) || isnan(t)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }

    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C\t");

    delay(3000); // wait for console

    /**INTURRUPT**/
    DateTime nextAlarm = now + TimeSpan(0, 0, 0, 10);
    Serial.print("Alarm at:");
    Serial.println(nextAlarm.hour());
    Serial.println(nextAlarm.minute());
    Serial.println(nextAlarm.second());
    rtc.setAlarm(ALM1_MATCH_HOURS, nextAlarm.minute(), nextAlarm.hour(), nextAlarm.second());   //set your wake-up time here
    rtc.alarmInterrupt(1, true);
    delay(3000); // wait for console
    attachInterrupt(0, wakeUp, LOW);       //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);   //arduino enters sleep mode here
    detachInterrupt(0);                                    //execution resumes from here after wake-up
    //When exiting the sleep mode we clear the alarm
    rtc.armAlarm(1, false);
    rtc.clearAlarm(1);
    rtc.alarmInterrupt(1, false);

    Serial.println();
    delay(3000);
}

void wakeUp()        // here the interrupt is handled after wakeup
{
}

The Arduino is going to sleep as expected, but not waking up. Where am I going wrong?
Here is the output:

Initialisation complete. 2017/6/7 (Wednesday) 12:42:49 Humidity: 36.90
  % Temperature: 25.60 *C
  Alarm at:12
  42
  59

After trying for a few hours, I was able to figure it out.
The change required is:
rtc.setAlarm(ALM1_MATCH_HOURS, nextAlarm.second(), nextAlarm.minute(), nextAlarm.hour (), 1);   //set wake-up time here

So, in the original code, the order of arguments as well as the number of arguments passed to rtc.setAlarm() was wrong. Even though we are not interested in the "day" part (last argument) for setting the alarm, it requires a value. Using ALM1_MATCH_HOURS ensures that we match the alarm time to seconds, minutes, and hours ignoring the day part.
Improvement
Instead of hardcoding the alarm interval, the global variable called interval_sec can be set at the top and used to set the alarm time:
DateTime nextAlarm = now + TimeSpan(0, 0, 0, interval_sec);

In RTClibExtended.h it is important to always include all arguments: seconds, minutes, hours, daydate. If 0 value is used then this means "always" for that argument.
Example:
RTC.setAlarm(ALM1_MATCH_SECONDS, 30, 00, 0, 0); // activate every minute at 30 seconds
RTC.setAlarm(ALM2_MATCH_MINUTES, 0, 01, 0, 0); // activate every hour at 01 minutes
RTC.setAlarm(ALM1_MATCH_HOURS, 33, 18, 0); // activate every day at 18:33

(note: this example is copied from RTClibExtended.h examples, author does not adhere to his own rule to include seconds, even in ALM2. But it works).
Any suggestions or corrections are welcomed!


text:
driver is not showing up in Port assignments mac
arduino nano, the driver is not showing up in Port assignments. It has worked with this operating system before. I’ve messed something up.  “OS X EI Capitan ver. 10.11.3 I have check the posts but the serial port is a no show

Genuine Arduino nano, or cheap Chinese copy?

If the port showed in earlier versions of OS X, but never showed after upgrading to El Capitan, then you probably used an unsigned driver, which is no longer allowed by Apple's new System Integrity Protection (a.k.a. "Rootless"; more details in a WWDC session).
Any unsigned drivers will have been disabled during the upgrade process. Even more, SIP does not allow any non-Apple files in /System, /bin, /sbin and /usr (except for /usr/local), so anything you had put in there will have been moved away as well. To see what has been disabled:

ls -l "/Incompatible Software"
ls -lR /Library/SystemMigration/History/Migration-*/QuarantineRoot/*

To get it working again: find a signed driver, or Switch off SIP.


text:
(Arduino Uno) Is my code for a follow the sun project valid? We want the motor to stop when both photoresistors have the same amount of light
int RlightPin=0;  //pin for right Photoresistor
int LlightPin=1;  //pin for left Photoresistor
int TranslateAnalogR=0;
int TranslateAnalogL= 1;
#include <Servo.h> //Servo library.
int pos=90; //Declare and initialize the variable pos.
int servoPin=9; //Servo connected to pin 9
int servoDelay=10; //Time motor waits before working again.
Servo myArms; //Servo object called myArms

void setup() {
Serial.begin(9600); //Start serial communication.
pinMode(7,OUTPUT);
pinMode(servoPin,OUTPUT);
myArms.attach(servoPin);

}

void loop() {

Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
TranslateAnalogR=analogRead(RlightPin); //Read the right photoresistor value

Serial.println(analogRead(LlightPin));    //Write the value of the left photoresistor to the serial monitor.
TranslateAnalogL=analogRead(LlightPin);  //Read the left photoresistor value

if(TranslateAnalogR=TranslateAnalogL){        //If Photoresistor Value is above 355 the motor will stop
myArms.write(pos); // sets the servo position according to the scaled value
delay(servoDelay);// waits for it to get to the position

}

if(TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL) { //If Photoreistor R is not equal to L and higher than L move until equal
for (pos=0; pos>=40; pos=pos+1)  {
  myArms.attach(servoPin);
  myArms.write(pos); //send servo to pos
  if(TranslateAnalogR=TranslateAnalogL){
  myArms.detach();}
}
}

if(TranslateAnalogL=!TranslateAnalogR && TranslateAnalogL>TranslateAnalogR){    //If Photoresistor L is not equal to R and higher than R move until equal
for (pos=0; pos>=40; pos=pos-1){
   myArms.attach(servoPin);
   myArms.write(pos); //send sevo to pos
   if(TranslateAnalogL=TranslateAnalogR){
   myArms.detach(); }

}
}

}

Does it compile? Does it work?

TranslateAnalogR=TranslateAnalogL should be TranslateAnalogR==TranslateAnalogL (== is equals; = is assignment).  In TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL you don't need the first part. If one value is bigger than the other they can't be the same. So the first part is superfluous.

for (pos=0; pos>=40; pos=pos-1){ doesn't do anything (yet).

run it and test using a flashlight (torch)

There are many issues with this code:
pinMode(7,OUTPUT);

What is this pin for? Why do you set it to OUTPUT and then never
actually output anything? If the pin is in use, you should declare a
constant for it, like
const int fooPin = 7;

and then use the constant instead of the bare number 7.
Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
TranslateAnalogR=analogRead(RlightPin); //Read the right photoresistor value

analogRead() is a slow function, and it is quite inefficient to do the
analog to digital conversion twice. You can instead
TranslateAnalogR = analogRead(RlightPin);
Serial.println(TranslateAnalogR);

As a matter of style, I would remove the comments. Commenting code is
generally considered a good practice, as long as the comments tell
something non obvious, like giving the “big picture” or the rationale
for doing something in a particular way. Paraphrasing in English what
the code already says in C++ is useless.
Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
//...
Serial.println(analogRead(LlightPin));    //Write the value of the left photoresistor to the serial monitor.

You won't know what value corresponds to the left and what value
corresponds to the right. I would instead do something like:
Serial.print("L: ");
Serial.print(TranslateAnalogL);
Serial.print(", R: ");
Serial.println(TranslateAnalogR);

Then:
if(TranslateAnalogR=TranslateAnalogL){        //If Photoresistor Value is above 355 the motor will stop

You mean ==.
if(TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL) { //If Photoreistor R is not equal to L and higher than L move until equal

The first test is redundant. If R>L, then obviously R≠L.
    for (pos=0; pos>=40; pos=pos+1)  {
        myArms.attach(servoPin);
        myArms.write(pos); //send servo to pos
        if(TranslateAnalogR=TranslateAnalogL){
            myArms.detach();
        }
    }

This is a very contrived way of searching the optimum. Normally you
attach the servo once and keep it attached all the time. Then you adjust
the position until you see the same illumination on both LDRs. This way
you keep track of the correct position and you need not redo the whole
angle scan every time. Also, this will not work for three reasons:

You mean TranslateAnalogR==TranslateAnalogL rather than
TranslateAnalogR=TranslateAnalogL
TranslateAnalogR and TranslateAnalogL are not updated within the
loop, you need to explicitly perform an analog read.
The loop will run too fast for the servos to follow the requested
positions.

Later:
    for (pos=0; pos>=40; pos=pos-1){

The loop is backwards. You probably mean
    for (pos=40; pos>=0; pos=pos-1){

Here is my take at this, completely untested:
#include <Servo.h>

// Pinout.
const int PIN_LDR_R = 0;  // right photoresistor
const int PIN_LDR_L = 1;  // left photoresistor
const int PIN_SERVO = 9;  // servo

const int SERVO_DELAY = 20; // time motor waits before working again

int pos = 90; // servo position in degrees
Servo servo;  // servo object

void setup() {
    Serial.begin(9600);
    pinMode(PIN_SERVO, OUTPUT);
    servo.attach(PIN_SERVO);
}

void loop() {
    // Read and report light levels.
    int level_L = analogRead(PIN_LDR_L);
    int level_R = analogRead(PIN_LDR_R);
    Serial.print("L: ");
    Serial.print(level_L);
    Serial.print(", R: ");
    Serial.println(level_R);

    // Adjust the servo position.
    if (level_R > level_L && pos < 180)
        ++pos;
    if (level_R < level_L && pos > 0)
        --pos;

    // Update the servo.
    servo.write(pos);
    delay(SERVO_DELAY);
}

A few things worth noting:

Constants are qualified as const (it helps the compiler optimize and
catch bugs) and spelled in full caps (a common stylistic convention).
The servo position is adjusted step by step, one degree per loop
iteration. No need to perform a full scan every time.
The program does not do anything special when the light levels are
equal, because in that case there isn't actually much to do.
I increased the delay between servo updates to 20 ms, as
the serial communication alone can take close to 19 ms per
iteration.
You may want to add some hysteresis in order to avoid the servo
jitter when it has found the optimum.

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


text:
Regarding running multiple functions using millis
I have been writing code for measuring when the digital signal comes and goes (ON and OFF respectively). I have done the part calculating a single system's downtime (difference in timings between ON and OFF from the system), but when I'm not able to scale up to multiple systems when I try to copy the same code which worked above. So it would be helpful if anyone could provide some insight into how it can be done plus explaining with the code would help.
My code:
unsigned long a=0, b=0, difference;
void setup()
{
  Serial.begin(9600);
  pinMode(2, INPUT);
  Serial.print("start");
  Serial.print(",");
  Serial.print("stop");
  Serial.print(",");
  Serial.print("minutes");
  Serial.print(",");
  Serial.println("seconds");
}

void loop()
{
 //delay(1000);
 int A = digitalRead(2);
 if(A == LOW)
 {
  b = millis();
 }
 if(A == HIGH)
  {
     a = millis();
     display_output();
   }
 delay(3000);
}
void display_output()
{
 int minutes, seconds, sec;
 difference = a - b;
 seconds = int(difference/1000);
 if(seconds >= 60)
 {
  //sec = seconds;
  seconds = seconds%60;
  minutes = minutes+1;
 }
 //minutes = int(seconds/60);
 Serial.print((a/1000)+1);
 Serial.print(",");
 Serial.print((b/1000)+1);
 Serial.print(",");
// Serial.print(difference);
 //Serial.print(",");
 Serial.print(minutes);
 Serial.print(",");
 Serial.println(seconds);
 //Serial.println(",");
}

The question is not very clear.  Are you trying to measure the time between two events in time?  What do you mean by "scale up to multiple systems"?  Interrupts are another way to measure the change of logic state in a signal

Yeah, I'm measuring the time difference between the time when a signal comes to the Arduino from my machine and when the signal stops. I have multiple machines working simultaneously at different stages and I have to do a project on how often and how long the machines are down. I programmed for one machine and it was working normally, but when i try to program for two or more machines ( note that two machines may go down with some error at same time), i get some random value.

First of all, you should notice there is a problem with your logic:
 int A = digitalRead(2);
 if(A == LOW)
 {
  b = millis();
 }

Here you are testing the state of the pin. If it's LOW you take a
record of the time. This is wrong. What you want to record is the time
at which the inputs falls, not when it's LOW.
This is called state change detection. In order to implement
it, you have to compare the pin state that you just read with
the previous state. The correct condition is “if the pin was HIGH
last time I read it and is now LOW”:
// Global variable:
int pin_state = HIGH;

// Within loop():
int new_pin_state = digitalRead(2);
if (pin_state == HIGH && new_pin_state == LOW) {  // it just fell
    time_of_fall = millis();
    pin_state = new_pin_state;
}

Note that this assumes that the default state is HIGH. If the pin
turns out to be LOW at power-up, then the code will assume it just
fell when the program started.
Next, you have to remove any occurrence of delay() from your code.
That will only make your timings wrong. At this point you have
non-blocking code that can easily be adapted to handle multiple input
channels.
Then you have to identify the variables that are channel-specific, and
have a per-channel version of each variable (arrays are useful here).
Then your code only needs to loop through the arrays.
Instead of having multiples arrays, you can make the code cleaner by
grouping all the channel-specific data into a single data structure:
struct Channel {
    byte pin;
    byte state;
    unsigned long fell, rose;  // times of fall and rise
};

This way you can have a single array that holds all the data for all the
channels:
const int CHANNEL_COUNT = 5;

Channel channels[CHANNEL_COUNT] = {
    { 2, HIGH, 0, 0 },
    { 3, HIGH, 0, 0 },
    { 4, HIGH, 0, 0 },
    { 5, HIGH, 0, 0 },
    { 6, HIGH, 0, 0 }
};

The code now becomes quite simple: you just loop through the array and
handle one channel at a time:
void setup()
{
    for (int i = 0; i < CHANNEL_COUNT; ++i) {
        pinMode(channels[i].pin, INPUT);
    }
    Serial.begin(9600);
    Serial.println("pin,fell,rose,low time");
}

void loop()
{
    for (int i = 0; i < CHANNEL_COUNT; ++i) {
        Channel &c = channels[i];
        byte new_state = digitalRead(c.pin);
        if (c.state == HIGH && new_state == LOW) {  // input fell
            c.fell = millis();
        }
        else if (c.state == LOW && new_state == HIGH) {  // input rose
            c.rose = millis();
            display_channel(c);
        }
        c.state = new_state;
    }
}

The function display_channel() is left as an exercise to the reader
;-) (hint: it's prototype should be
void display_channel(const Channel &c); in order to avoid
unnecessarily copying the data structure.
Next step in code modularity would be to turn the Channel structure
into a class with a proper constructor, and make display_channel() a
method of that class.

What about a link to the state-change-detection example? https://www.arduino.cc/en/Tutorial/StateChangeDetection

This code looks neat and will definitely try with this one. I don't know much about constructors and structure things. Will learn about that. I used a delay in my program so as not to have too many data points and instead the data once in two or three seconds will be enough plus its not a time critical application, so I don't know if using millis function is overkill for my application. Thank you though :)

@Jot: Good idea. I added the link.

@RajeshAnand10: 1. Learning about object-oriented programming (classes with constructors and methods) is useful, but you can live without it for simple projects like this. 2. delay() was useful in your previous version only because you got the logic wrong. Once you properly detect state changes, it serves no useful purpose. 3. What do you mean by “overkill”? Do you believe millis() is more heavyweight than delay()? It's not. For your particular problem, it's the right tool for the job.

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


text:
Getting issues while using SoftwareSerial
I am trying to read string send from esp8266 esp01 to Arduino mega. When I use normal Rx and Tx ports, it works properly but when i am initializing new serial port using SoftwareSerial then nothing is being shown on the serial monitor.
Please help me as i have been stuck and trying to solve this for weeks now.
Below are the code for esp8266 and Arduino mega

Code for ARDUINO MEGA

#include<SoftwareSerial.h>

SoftwareSerial myS(4,5);

String data="true";

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
myS.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(myS.available()){
  data=myS.readString();
  }
  Serial.println(data);
  //Serial.write(data);
  delay(2000);
}

Code for ESP8266

void setup() {
  Serial.begin(9600);     // Initialize the Serial interface with baud rate of 9600
}

// the loop function runs over and over again forever
void loop() {
  if(Serial.available()>0)    //Checks is there any data in buffer
  {
    Serial.print("We got:");
    Serial.print(char(Serial.read()));  //Read serial data byte and send back to serial monitor
  }
  else
  {
    Serial.println("Hello World..."); //Print Hello word every one second
    delay(1000);                      // Wait for a second
  }
}

Moreover, i have tried read() as well instead of readString(), but it does not work either. I have also tried switching Rx and TX pins meaning connecting Rx->Tx, Tx->Rx and vice versa i.e. Rx->Rx and Tx->Tx, but it does not work in any of the case.
Any help or suggestion will be appreciated.
Thanks

Why are you using SoftwareSerial on a Mega?!?!

Rx->Tx is correct, not the other way around. Also, the atmega2560 has more serial interfaces, so softwareserial is not a good choice

SoftwareSerial only works on a few select GPIO pins on the Mega. Specifically those pins that have PCINT on them.
But that is irrelevant. There is no reason to use SoftwareSerial on a Mega except in exceptional circumstances.  You have four hardware UARTs on the Mega, so there is no call to use SoftwareSerial.  Use the real UART pins and objects:
Serial -> RX(0) / TX(1)
Serial1 -> RX1(19) / TX1(18)
Serial2 -> RX2(17) / TX2(16)
Serial3 -> RX3(15) / TX3(14)

Just replace all references in your code to the SoftwareSerial instance with Serial1 (delete the #include and the object instance constructor) and use TX1 and RX1 to connect your module:
String data="true";

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    Serial1.begin(9600);
}

void loop() {
    // put your main code here, to run repeatedly:
    if(Serial1.available()){
        data=Serial1.readString();
    }
    Serial.println(data);
    //Serial.write(data);
    delay(2000);
}


text:
How to diagnose unresponsive Leonardo serial port?
I was using an Arduino Leonardo (in the form of an RPI hat) to control a single DC motor via a motor controller. I have it wired to set Phase and Enable to control motor speed and direction, and I read sensors on the motor's encoder to directly measure motor speed.
I triple checked all my wiring, and a test program I wrote to spin the motor at half-speed seemed to work just fine. Then it suddenly stopped working. Now, when I plug the Leonardo into my machine, the ttyACM0 device does not appear, and I seem to have no way to communicate with it anymore.
I've noticed that when I press the reset button, the Leonardo's status light flashes for a few seconds and ttyACM0 does momentarily appear. But as soon as the flashing stops, ttyACM0 disappears again. I tried upload a new sketch when the device reappears, but I get a "broken pipe" error.
What's going on here? Did I somehow fry my Leonardo, or is it possible I just screwed up the serial port? How do I fix it?
Edit: For the host, I've tried Ubuntu 14 running on a Raspberry Pi 2 and a generic 64bit laptop.
Edit: My setup() is simply:
void count_pan_changes(){
    /*
    CW  => 11,00,11,00,...
    CCW => 10,01,10,01,...
    */
    int a = digitalRead(MOTOR_ENCODER_A_PIN);
    int b = digitalRead(MOTOR_ENCODER_B_PIN);
    int direction = (a == b) ? +1 : -1;
    motor_controller.record_direction(direction);
}

void setup(){
    attachInterrupt(digitalPinToInterrupt(MOTOR_ENCODER_A_PIN), count_pan_changes, CHANGE);
}

Edit: I'm not sure why, but when I disconnected the Leonardo from it's 5V UBEC power supply and powered it directly from my laptop via USB, then ttyACM0 suddenly came back. However, when I reconnect it to its own power supply, I again have problems connecting to it. The first upload and serial terminal seem to work, but as soon as I disconnect, further uploads/serial connections seem to fail with a "broken pipe" error. I'm powering it via a UBEC by connecting the 5V and Gnd lines to one of the Leonardo's GVS headers (i.e. it's not going in through any onboard regulator on the Arduino or RPi). Should this work? The motor is behind a separate UBEC.
Edit: Now power cycling isn't even fixing it. I tried erasing the contents using:
avrdude -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -e

as explained here. This keeps /dev/ttyACM0 from disappearing, but if I try and upload a sketch using ano upload, I still get the error:
IOError: [Errno 32] Broken pipe

Can you describe your host environment?

If you watch dmesg -w on the Linux machine (I assume you're working on some flavor of Linux) you'll see kernel messages from the USB sub-system. While doing that try resetting the Leonardo and watch the messages. They may give you some clues.

Does the setup() contain "while (!Serial);" to give the Serial startup time?

@MikaelPatel, No. I posted my setup() code.

I think this might be a bug in Arturo. This is how I was able to fix my Leonardo:

Fix disappearing /dev/ttyACM0 by pressing reset to temporarily bring it back, then erase all content with:
avrdude -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -e
Now /dev/ttyACM0 stays there, but trying to upload my sketch throws a broken pipe error.
Upload a blank sketch using the Arduino IDE.

Then I could upload my sketches normally.

Since your code does not open the serial port, it is entirely expected that the serial port will appear briefly on reset, and then disappear. Initially it appears as the bootloader looks for a new sketch, and disappears because your code does not open Serial.
If you time it correctly you should be able to upload a new sketch after pressing Reset. You need to press Reset fairly precisely after the IDE announces that is uploading. You only have a window of a second or so.


text:
Storing an array of function pointers
I have some Arduino code that looks like:
char packet = ser.read();
switch(packet){
    case 'a':
         someobj.somefunc();
         break;
    case 'b':
         otherobj.otherfunc();
         break;
    ...
}

I've added a few large libraries that are now causing my sketch to exceed the Arduino Uno's memory. I've done all the usual tricks to reduce memory usage, like using F(), removing unused variables and functions, but I'm still 5% over the memory limit.
I tried commenting out various parts of my code to see what was taking up so much space, and I found removing this switch statement freed up a whopping 20% of memory.
Since it acts like glorified array index, I was wondering if it could in fact be replaced with an array of function pointers, with the packet variable serving as the array index. e.g.
uint packet = ser.read();
func_array[packet]();

Although the class instance types are arbitrary, the methods all return the same type and take no arguments.
How would you write an array of pointers to arbitrary class instance methods in Arduino C/C++?

Are you talking about flash or RAM? F() helps with RAM, not with flash.

This all gets very much trickier than just an array of function pointers.
Your functions are methods in unknown objects. As such you can't have one single type that stores pointers to the functions in different objects.
The simple reason is that C++ changes the function prototype for you.  For instance, it changes:
class MyClass {
    public:
        int myFunction(int size) { ... }
};

into:
int myFunction(MyClass *this, int size) { ... }

For another class you end up with something like:
int myFunction(MyOtherClass *this, int size) { ... }

And that is a problem, because although you started with functions that, to you, look the same, they are actually very different. So you can't have one function pointer array with one type that can store either.
One possible method is to use polymorphism, where you have one interface class that defines the interface your other classes use:
class MyBaseClass {
    public:
        virtual int myFunction(int size) = 0;
};

class MyClass : public MyBaseClass {
    public:
        int myFunction(int size) { ... }
};

class MyOtherClass : public MyBaseClass {
    public:
        int myFunction(int size) { ... }
};

You can then access myFunction() in either object as if it were in the class MyBaseClass.  Instead of then storing pointers to the functions within the classes you can then store pointers to the classes themselves:
MyBaseClass *classes[2];

classes[0] = (MyBaseClass *)&myClassInstance;
classes[1] = (MyBaseClass *)&myOtherClassInstance;

And then access the functions:
x = classes[i]->myFunction(z);

However, this is all probably very much a moot point.  The switch statement in your code is most likely not what is using all the memory, but all the classes are. By removing the switch you are most likely then not actually doing anything with the classes you have included, and so the linker is then stripping out all that now unreferenced code. A single switch, unless it is an absolutely mammoth bit of code, won't take 20% of the Uno's flash.

Thank you, I had been trying to use a base class, but I wasn't sure of the exact syntax. You nailed it perfectly.

This is not a direct answer to your question, as I have no such answer,
and I believe the answer you are seeking would be of no use to you.
The problem with your question is that your method of testing memory
usage is heavily flawed. By removing the switch statement, you most
likely have allowed the linker to remove lots of methods referenced by
it, leading to huge memory savings. Those savings do not mean the
culprit is the switch statement itself.
The correct way to test static memory usage is to use either
avr-objdump or avr-nm. You have to find where the IDE puts the
compiled elf file, then you can issue the command:
avr-nm --size-sort -Crtd my_program.elf

This will give you a list of all symbols in your program sorted by size.
Symbols of type 't', 'w' and 'd' (upper or lower case) eat flash.
Symbols of type 'd', 'b' and 'v' eat RAM.

You're right, this is arguably really what I'm looking to do. I had Googled for ways to analyse Arduino memory usage but I didn't find anything. I'm glad there's a simple method after all.

I'm not sure if it will not blow your memory limit as every pointer takes up 16 bits. But in C you usually do it this way:
void func1() {
    puts("Hello");
}

void func2() {
    puts("World!");
}

void func3() {
    puts("Array of Size 4");
}

void func4() {
    puts("with Pointer");
}

void func5() {
    puts("to a Function with no arguments");
}

void func6() {
   puts("with return type void");
}

void (* myFunc[6])() = { func1, func2, func3, func4, func5, func6 };

int main(int argc, const char * argv[]) {
    for (int i = 0; i < 6; i++) {
        myFunc[i]();
    }

    return 0;
}

For explanation of
void (* myFunc[6])()

You read form inside to outside looking first to the right then to the left
The variable is named myFunc.
myFunc

My func is an array of size 6.
myFunc[6]

Each of those entries is a Pointer.
* myFunc[6]

Now we need parentheses to make clear, that we have a Pointer to a function with no arguments.
(* myFunc[6])()

And its return type is void.
void (* myFunc[6])()

Hope this helps a bit.

The OP is talking about pointers-to-member-functions - but you've given a VERY good breakdown of pointers-to-functions in general. However, to make it easier do this: declare a typedef as follows: typedef void Fn();. That's a declaration of a type-of function. You can now declare variables of pointers-to-that-type as follows: Fn *fn_p; Which means that you can declare your array (not the OP's array) as Fn *myFunc[6] = { func1, func2, ... }; Neat, huh!


text:
NRF24L01 Connection Not Working
I have an ATTiny85 connected to an NRF24L01+ module using this wiring diagram: diagram. The ATTiny85 periodically goes in and out of sleep to send some value to a receiver, an Arduino Uno. If the ATTiny is running off the Arduino power supply (3.3v), everything works correctly. When I run the ATTiny off of a separate CR2032 coin cell that delivers around 3v, the Arduino never receives any data. I have a status LED hooked up to the ATTiny to ensure that the ATTiny is waking correctly, which it is. Here's the code for both:
EDIT:
Connecting it to an external 3.3v not from the Uno makes everything work - why wouldn't the coin cell's voltage work? I think everything is rated below 2.8v, the CR2032 minimum.
ATTiny Code
#include <avr/sleep.h>
#include <avr/interrupt.h>

// Routines to set and claer bits (used in the sleep code)
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

#define CE_PIN 3
#define CSN_PIN 3 //Since we are using 3 pin configuration we will use same pin for both CE and CSN

#include "RF24.h"

RF24 radio(CE_PIN, CSN_PIN);

byte address[11] = "SimpleNode";
unsigned long payload = 0;

void setup() {
  radio.begin(); // Start up the radio
  radio.setAutoAck(1); // Ensure autoACK is enabled
  radio.setRetries(15,15); // Max delay between retries & number of retries
  radio.openWritingPipe(address); // Write to device address 'SimpleNode'
  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);
  delay(500);
  digitalWrite(4, LOW);
  delay(500);
  digitalWrite(4, HIGH);
  delay(500);
  digitalWrite(4, LOW);
  delay(500);
  digitalWrite(4, HIGH);
  delay(500);
  digitalWrite(4, LOW);
  delay(1000);
  setup_watchdog(6);
}

volatile int watchdog_counter = 0;

ISR(WDT_vect) {
  watchdog_counter++;
}

void loop()
{
  sleep_mode(); //Go to sleep!

  if(watchdog_counter >= 5)
  {
    digitalWrite(4, HIGH);
    watchdog_counter = 0;
    payload = 123456;
    radio.write( &payload, sizeof(unsigned long) ); //Send data to 'Receiver' ever second
    delay(1000);
    digitalWrite(4, LOW);
  }
}

//Sleep ATTiny85

void system_sleep() {

  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System actually sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out

  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON

}

// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
// 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
void setup_watchdog(int ii) {

  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

Receiver Code
#define CE_PIN 7
#define CSN_PIN 8

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

RF24 radio(CE_PIN, CSN_PIN);

byte address[11] = "SimpleNode";
unsigned long payload = 0;

void setup() {
  while (!Serial);
  Serial.begin(115200);
  radio.begin(); // Start up the radio
  radio.setAutoAck(1); // Ensure autoACK is enabled
  radio.setRetries(15,15); // Max delay between retries & number of retries
  radio.openReadingPipe(1, address); // Write to device address 'SimpleNode'
  radio.startListening();
  Serial.println("Did Setup");

}

void loop(void){
  if (radio.available()) {

    radio.read( &payload, sizeof(unsigned long) );
    if(payload != 0){
        Serial.print("Got Payload ");
        Serial.println(payload);
    }
  }
}

Is the problem here that the ATTiny and Uno need to be turned on at the same time to establish a connection, or is it something to do with the battery, or something else entirely? Any help would be appreciated.

Yes, receiver needs to be listening while another one is transmitting to receive packets.

Also, try setting the PA level lower.

Coin cells can't deliver a lot of current. To account for the short bursts of higher current (during transmission) you can put a capacitor in parallel to the battery.

Good call, I'll try it with a capacitor. Would 10uF be not enough, or too much?

Experiment. Also set the PA level lower so that the radio would consume less power. https://tmrh20.github.io/RF24/classRF24.html#adedac579590a668ae97baccab284de8a (You are using https://github.com/TMRh20/RF24, right?)

Didn't know that I could do that with the RF24 library, thanks. I'll try some different capacitor configurations.

I was just researching the exact question and I have some bad news.
The ORIGINAL nrf24l01+ alone use around 10-12 ma in transmitting, but unoriginal might even draw more. (https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss_Preliminary_Product_Specification_v1_0.pdf)
Nevertheless a standard CR2032 battery is simply not made to supply more than a few milliamps at the best, leaving your nrf24L01+ lacking enough current.
There is something called shockburst which can lower your consumption considerably at the cost of range - but if it will succeed in transmitting with one CR2032 I'm not sure about.
Edit:
If you add a capacitor you need to cover at least a 10ma drain for around 15ms (turn on - send - turn of immediately), that will require a minimum of a 200µF capacitor at 3V to be able to deliver the current while keeping above 2.0v.

Hmmm... this is very good to know. I had some 100µF capacitors lying around and, after testing, it appears that it is transmitting, albeit after setting the PA level to its lowest setting. Not sure if it works on a higher PA level. Looks like that capacitor seemed to do the trick.

Glad to hear it, I used values think you should have enough power

I tried to say you likely have enough capacitance for high PA level if it is burst only. Otherwise you could add more capacitors - or switch to a power source with higher current capabilities


text:
ArduinoMEGA: 64 digital inputs cause random digitalRead values
I have 64 hall effect sensors (magnetic field sensors) (DRV5023AJQLPG) connected to an Arduino MEGA 2560. For that, I use 48 digital pins and 16 analog pins as digital input pins. The program in the Arduino continuously reads out those 64 digital input pins (in a for-loop) and sends out a serial byte, to a laptop via a usb cable, whenever one of those input pins changes between LOW and HIGH. I also use the ATmega2560’s internal pullup resistors to prevent irregular readouts of the input pins when the sensor is not giving a 0v output (i.e. when it isn’t measuring a strong enough magnetic field).
Everything is working fine when I only physically connect up to 16 of the sensors. The laptop then only receives bytes that correctly tell when a sensor measures a state-change.
However, when I start connecting more of those 64 sensors, then the laptop starts receiving irregular streams of bytes, erroneously suggesting that all the connected sensors measure changing magnetic fields (HIGH and LOW readouts).
I can think of two reasons why these irregular readouts occur:
1. Either, the ATmeag2560’s internal pullup resistors arent working as I think they should.
2. Or, the arduino board and >16 hall effect sensors combined are pulling to much current.

Pullup resistors not working?
When testing with only 16 sensors connected, it is a stable, properly working setup. When I explicitly don’t use the pullup resistors in the program then the setup does start behaving irregular, also with just 16 sensors. So the internal pullup resistors seem to be properly activated by the program.
Arduino + 64 sensors draw to much current?
Besides powering the Arduino board and sensors via the usb cable (providing 500mA), I’ve also tried external power sources that provide 1 or 2A. I’ve also powered the Arduino board via an external 5v, +1A voltage regulator, bypassing the Arduino’s onboard voltage regulator. This all doesn’t seem to make a difference in the system’s irregular behaviour. When measuring those setup’s current usage (with amperage meter) it didn’t go above 250mA.

Calculating the combined current usage (using datasheet info), I came to this:
- sensor operating current:             2,7 mA
- sensor output current when in ‘active’ state:     0,25 mA
- TOTAL current of 64 sensors   (3mA*64=)       192 mA
- Arduino MEGA current (approx)             150 mA
- TOTAL current of 64 sensors + Arduino MEGA:       **342 mA**

So, both the calculated and measured current usage seem within the range of what can be handled by mentioned power sources.
I’m kinda stuck now. Can anyone suggest anything that might cause this problem? Or point to incorrect thinking of me? Thanks for any responses.

'Schematic' (only showing first 8 sensors connected. The ArduinoMEGA is connected to a computer via a usb cable with disabled power line):

Top-side: the hall effect sensors and Vcc an GND rails:

Bottom-side: ArduinoMEGA + the 64 red sensor output lines to the input pins:

Below is the Arduino code:
/*
Arduino to Pd protocol

 Placing or removing a chess piece sends only one byte.
 There’s no other serial data being communicated.

 event:                     byte value:
 placing a chess piece on a square:     0-63
 removing a chess piece from a square:          64-127

 ArduinoMEGA pin to byte value mapping:
  byte      pin
  0     6
  1     7
  2     8
  3     9
  …
  46        52
  47        53

  48        A0 (analog 0)
  49        A1
  50        A2
  …
  62        A14
  63        A15

*/

byte prevSquares[64];  // array that holds previous readouts
byte i;                // variable used in for-loops
byte sensorValue;      // variable temp storing of digitalread

void setup() {
  Serial.begin(9600);
  for (i = 0; i < 64 ; i++) {
    pinMode(i+6, INPUT_PULLUP);  // activate pullup resistor
  }
  for (i = 0; i < 64 ; i++) {
    prevSquares[i] = digitalRead(i+6);
  }
}

void loop() {
  for (i = 0; i < 64 ; i++) {
    sensorValue = digitalRead(i+6);
    if (sensorValue != prevSquares[i]) {
      // chess piece was placed or removed from square
      if (sensorValue == 0) {
        // chess piece was placed
        // send serial byte (0-63):
        Serial.write(i);
      }
      else {
        // chess piece was removed
        // send serial byte (64-127):
        Serial.write(i + 64);
      }
      //update prevSquares array:
      prevSquares[i] = sensorValue;
    }
  }
}

Personally I think that 64 sensors is just a waste of space... You can wire them in 8 rows of 8 sensors, enable a single row and then read it, then pass to the next one. Anyway what is the error stream? all high, all low, change continuously? And does it do this on all the pins or just on some of them?

The stream consists of highs and lows, continuous change. It's occurring  at any moment on, say, half of all pins, or more, but which pins is changing over time. The stream does look like as if the pullup resistors are not in use.
(BTW: the sensors are powered (connections: ground, Vcc, output) and have an internal state. Using a matrix of 8x8 would turn them on/off all the time and they'd loose their internal state.)

Then I'd use some multiplexers... Or 16bit port expanders.. Because personally I don't like filling a board's pins with sensors, otherwise you won't be able to add other stuff.. Anyway.. You did all the tries with the same firmware (so compiling for 64 sensors even when using 16 of them)? Did you connect the new sensors with the board shut down or not? From the datasheet the atmega should be able to handle currents up to 200mA, and your circuit draws approx 50mA for the uC and 16mA for the pullups, so it should be fine

Yes, I've done all the testing with the software reading all 64 input pins, also when fewer sensors were connected. I (in)activated sensors by (dis)connecting the ground to those sensors, while the Arduino board remained powered. To be clear: The sensors are not powered through the atmega pins, but get their power from the arduinoMEGA board's ground and 5v pins (so, from the on board voltage regulator), and I've also tested it with an external +1A voltage regulator).

Did you try to leave all 64 sensors powered and (in)activate all of them by (dis)connecting the signal wire instead of the ground wire?

I just did that. It gives similar result, except it already becomes unstable when >8 sensors are connected.

Have you tried actually measuring the current use, instead of only calculating? Try adding some capacitors to the voltage supply near the sensors, as noise might be an issue here. PS you can multiplex the output pins only, so can keep the sensors powered on. Enable external pull-ups on a single row, and then read all the columns. Similar to how a keypad is multiplexed.

Like most 8 bit AVR processors, the ATmega2560 has a current limit of 200mA, so as long as the sensors are attached directly to the microcontroller, it does not help you to provide more power to the board.

How are all these sensors physically arranged? How are they connected? Is there a breadboard involved? (Just thinking about noise and cross-talk) Also, looking at the datasheet for the sensor, and it specifies a 10K pullup, however, AVR internal pullups are generally in the range of 30~60K, which might be too little and causing slow rise times.

It is actually a little more nuanced than a 10k resistor, there is an allowable range based on the supply voltage, see equation 3 of page 16 http://www.farnell.com/datasheets/1888830.pdf and then based upon the value you pick for the resistor, you calulate a value for the capacitor. Either way it would help if you could share your schematic and the capacitor values just to verify that his is set up properly.

It might be best to just stop using internal pullups anyway as the resistor is being used as part of a low pass filter. By you using internal pullups you are betting the entire performance of the filter on the accuracy of that resistance value, which isn't particularly accurate or stable.

I was recently testing something else (an old phone) and found the internal pull-ups were insufficient for reliable operation. Wiring in 64 of them could be a pain (although you could get a few resistor arrays). How about using some analog multiplexers?

Have you tried decoupling your power supply with a 0.1uF ceramic and a 100+uF electrolytic?

@EdoPaulus it is really strange.. Another test you can do is to actually measure what is on the pin: this way you can understand if it is the sensors fault or the uC fault. Moreover at least as a test you can try to separate the uC power supply from the sensors. Or place the sensors in groups of 8, for instance, and separate the power (for instance place a diode (anode +5V or better a higher one, cathode Vcc of the sensors group) and a capacitor (between Vcc of the sensors group and ground) in the range 10-100uF.

Thanks for all the suggestions. I've added some photos and a schematic of the setup. My next plan is to add external pull-up resistors to all the inputs and not use the internal pull-ups. For the value of the resistors I'll use the equation mentioned by @jake-c ( equation 3 of page 16 link )

@Gerben I'm curious, though: How does one multiplex the output pins while keeping the sensors powered? I've read a bit more into multiplexing, but keypad multiplexing seems to only involve momentary buttons and diodes, no continuous power on ICs for every sensor. Is there maybe a link that gives more info on this? ty.

@EdoPaulus Have a look at this schematic I cobbled together. You enable the pull-up for only a single row at a time. You add diodes to prevent connecting to rows together. Because of the diodes you need a pull-down resistor on the columns to get a strong LOW signal. Make sure R7-9 are higher value resistors than the pull-ups.

Perhaps you have to put a 10k resistor between the signal and the ground of the hall effect sensor to avoid electrical disturbance.
Regards,
Guillaume

After seeing your schematic, I think the general problem here is that you need to more closely read and follow the datasheet for this part. A lot of times, when you are hobbling a project together at a small scale there are a lot of things you can ignore and get away with, but as you scale up, all the rounded corners start to add up. In this case, you can get away with 16, but once you start adding too more, it becomes too much. Let's go over a few:
Pull up resistors
Like I mentioned in the comments, relying on the internal pull ups is probably not a good idea. In my personal experience, they are only really good for adding a quick button input for debugging purposes. I'm not sure specifically what would cause issues only after 16 sensors. It could be that collectively internal pullups are subject to a different and lower current limit, but I'm not familiar enough with the internal architecture of the ATMega2560 to do more than just speculate.
Whatever the case, the best practice here would be to use separate external pull up resistors, within the specifications of the datasheet. (See equation 1 on page 13 of the datasheet.)
Decoupling Capacitor
Per the datasheet, page 17:

A 0.01-µF (minimum) ceramic capacitor rated for VCC must be placed as close to the DRV5023 device as possible.

This capacitor is referred to as C1 in the datasheet figures and is required. This type of capacitor is called a decoupling capacitor, and one of the things it does is provide a local energy storage, so that when the sensor starts pulling a little extra current, it doesn't have to wait for the regulator to respond, it has some local energy already.
Your schematic indicates a single 1uF capacitor on the output of the voltage regulator, however, there are no capacitors for the sensors. The one capacitor is only for output filtering for the regulator, and will not satisfy any decoupling needs of the sensor.
Filtering Capacitor
Referred to as C2 in the datasheet, this an optional capacitor to filter out high frequency noise. This isn't needed in most cases, in fact, per the datasheet, page 13:

Most applications do no require this C2 filtering capacitor.

However, your project might not fall into "most applications" and there are a few things specifically that worry me.

You have long wires that are basically acting as antennas that will capture any nearby noise.
You have long power lines running parallel to your signal lines which can cause stray inductance which leads to other interesting things. (With the thickness of the plywood separating them, this might not be an issue, but it is something to be aware of).

I would definitely try the first two ideas above to begin with, and only pursue this as a last resort. The  only way to know for sure if this is something you need is to stick an oscilloscope on the line and see how noisy it is, but that is not something you probably have handy.
Other Concerns
I'm just a little bit worried about voltage drop. Depending on the gauge of wire used, with all the sensors connected, at the end of a strand you might have a non-negligible voltage drop.
With that many wires running together into the Mega, there might be cross talk problems.
Another common problem with scaling up is that there is a higher probability of having faulty components. This is especially with this part which per the datasheet indicates that is particularly sensitive to ESD. It could be that there is a dead sensor that has failed in such a way that it is causing problems for the other sensors. Maybe go through and test all 64 sensors, 8~16 at a time to make sure that separately they all work, and that the issue only occurs when all of them are connected.
Other Ideas
Many other comments on the question have suggested a multiplexer and/or multiplexing and I will just briefly echo that here. Multiplexers are typically used in situations where you don't have enough pins and you want to split a single pin to multiple other pins. While that isn't an issue here with the Mega (it appears you have enough pins to do what you are wanting to do), there are other benefits that can be derived from multiplexing this.
For example, one thing you could do is split up the board into 8 - 2 x 4 chunks and then have a multiplexer (such as a 4051 or a 74151) local to each chunk. Then you would have just 8 short wires going into the multiplexer, as opposed to having long antenna-like wires heading to the Mega. This could improve overall signal integrity.

Thanks for all these elaborate replies! I've just tried adding external pull-up resistors (22k) but that didn't make the system stable. I'm now gonna try adding those decoupling capacitors. I'm thinking of using 0,01µF (with ±20% tolerance), or would it be better to go for 0,1µF?
If that still doesn't work, I'm gonna use some type of multiplexing. I have a couple of IO expanders at hand with I2C communication. Or would 4015s be better? (Then I can probably also replace the MEGA with a common Arduino UNO)

And yes, I tested all sensors separately and they work fine. Also, I indeed have no oscilloscope at hand.

Adding decoupling caps has made it stable! For now, I've just added one 0,1µF ceramic cap per row of 8 sensors, to test it. That seems to work. Later on, I will probably buy and add a 0,01µF cap for every sensor. Also, I'll still double check with internal and external pull-ups. Thank you Jake, and also thank you @gerben.


text:
Computer to Arduino to hardware, controlling on / off state of hardware via user input on computer
First time coding for Arduino. I'm working on code to operate an electronic valve switch. We have a laptop connected to an Arduino Mega, and that Arduino is hooked up to the valve (hardware) on Pin 53.
I was trying to work off of the "blink" example originally, but that gives no basis for user prompted control. Basically I want to have the computer ask me if I should turn it on or off, type in my response (I was using "HIGH" for on and "LOW" for off, as in voltage control), and have that activate or deactivate the hardware.
My main problem right now stems from how best to ask for that input. I've been trying to work with the Messenger.h library thus far. I'm definitely getting hung up on how to define the pin, or what the simplest method for user input would be. (HIGH or LOW? 0 or 1? Something else?)
Code is below. Thanks!
#include <Messenger.h>

Messenger message = Messenger();

// Variable definitions. Switchinput is what the user commands, current state is whether the air is flowing or not.
boolean currentstate;
boolean switchinput;
String pin53; // Something is up on this line?? How to define this pin??

// FUNCTION DEFINITIONS
// Startup fxn
void start()
{
  Serial.print("LOW = off, HIGH = on. Switch is ");
  Serial.println(currentstate);
  Serial.print("Enter LOW to turn on or HIGH to turn off: ");
  switchinput = Serial.read();
}

// Go off to on
void offtoon()
{
    digitalWrite(pin53,HIGH);
    currentstate = switchinput;
}

// Go on to off
void ontooff()
{
    digitalWrite(pin53,LOW);
    currentstate = switchinput;
}

// Stay same -- already off
void staysameoff()
{
  if ((currentstate = switchinput) && (switchinput = LOW))
  {
      void start();
  }
}

// Stay same -- already on
void staysameon()
{
  if ((currentstate = switchinput) && (switchinput = HIGH))
  {
    void start();
  }
}

// Running actual code
void setup()
{
  // initialize digital pin 53 as an output.
  pinMode(pin53, OUTPUT);

  // Sets default state to switch being off (Off = LOW, On = HIGH)
  String currentstate = LOW;
}

void loop()
{
   if ((currentstate != switchinput) && (switchinput = HIGH))
  {
      void offtoon();
  }

  if ((currentstate != switchinput) && (switchinput = LOW))
  {
      void ontooff();
  }

  if ((currentstate = switchinput) && (switchinput = LOW))
  {
      void staysameoff();
  }

  if ((currentstate = switchinput) && (switchinput = HIGH))
  {
      void samestayon();
  }
}

if ((currentstate = switchinput) && (switchinput = LOW)) - this (and all similar lines) are wrong. You use == for comparing, not =.

{ void start(); } - that does not call the function start. Don't use the word void here.

String pin53; - not a String. Try: const byte pin53 = 53; - although what that achieves I am not sure. How about: const byte valvePin = 53;

As for reading serial input, see How to process incoming serial data without blocking

Fixed the first three comments-- those are all things I really should've caught.
So this works pretty similarly to the state machine example on your link, right? Except I've only got two possible inputs, whereas that has three options. Correct?

@CEL If you have fixed Nick's comments can you update your code, because I was about to flag them up too :)

@CEL I appreciate this comment is a bit off target, but you might want to look at using parameters to the functions you have written to reduce the amount of code you have.  i.e. void offtoon() and ontooff() could become
void changeState(const int& newState)
{
digitalWrite(pin53, newState);
currentstate = switchinput;
}

Please amend your question with your updated code (which unfortunately makes the comments here look silly). Or, post underneath (in the question) the corrected code which is probably better. Edgar Bonet's solution looks pretty good to me.

This seems way too complex for your purpose:

you really do not need to do anything to stay in the same state
if you want to switch the valve ON, no need to check whether it's OFF:
there is no harm in switching ON a valve that is already ON.

Here is a simplified version of the program:
void setup()
{
    Serial.begin(9600);
    Serial.println("Type '0' to turn OFF, '1' to turn ON");
}

void loop()
{
    int command = Serial.read();
    if (command == '0') digitalWrite(53, LOW);
    if (command == '1') digitalWrite(53, HIGH);
}

Notice that Serial.read() returns -1 if there is nothing in the input
buffer, and since -1 is neither '0' nor '1', this will not change the
output.
If you want to use more elaborate commands (not single characters), you
may want to take a look at this simple command-line
interpreter. It is intended to be easy to adapt to
different purposes.

Thank you! I've only got one switch with two states happening for now, but I'm going to be working with multiple states later on as more components are added. Single digits might still work for that but for other users who aren't me later on it might be worth switch over to the single command line interpreter.


text:
Variables not initialized in Class Constructor
I'm creating a library driver for AdaFruit's GFX library. During Constructor initialization, all the variables (set in another .cpp) are returned as zero. This code has several modular files to separate graphics functions from graphics primitives from device interfacing. What am I doing wrong?
In the Arduino sketch I call the class constructor: MB_GFX_SPI (in file MB_GFX_SPI.cpp).
In the Constructor I'm call a function: mbR.SetMatrixSize (in another file raster.cpp).
Also in the Constructor I call a function: clearScreen (in the same file MB_GFX_SPI.cpp).
The test variable  mbR.r_totNumChannels set in clearScreen is returned with 99.
All the variables set in mbR.SetMatrixSize return zero.
//Test Sketch
//Initialize both the Adafruit library and the current library.
//Instantiate an object mbGFX so all Adafruit GFX and MB_GFX add-on functions are addressed as mbGFX.xxx();
MB_GFX_SPI mbGFX = MB_GFX_SPI(Period, numCathodeLeds, numAnodeLeds, CathodeSSPin, AnodeSSPin);

//In file MB_GFX_SPI.cpp

MB_GFX_SPI::MB_GFX_SPI(int Period, int numCathodeLEDS, int numAnodeLEDS,
      int CathodeSSPin, int AnodeSSPin)
      : Adafruit_GFX(numCathodeLEDS, numAnodeLEDS) {

  mbR.SetMatrixSize(numCathodeLEDS, numAnodeLEDS);
  clearScreen(0);
}
void MB_GFX_SPI::clearScreen(uint16_t color) {
   mbR.r_totNumChannels = 99;   //test set value
}

//In file mb_raster.cpp

void mbRasterClass::SetMatrixSize(int numCathodeLeds, int numAnodeLeds){
//cathodes require 1 byte per channel
//anodes require 1 bit per channel

    int numAnodeChannels = numAnodeLeds;
    int numCathodeChannels = mbX.pin2pin * numCathodeLeds; //times 1 or 3

    r_numCathodeRegisters = (int)((numCathodeChannels+7)/8);   //select next higher number of registers
    r_numCathodes = 8 * r_numCathodeRegisters;  //must be whole 8 bit registers - is every single chatode pin
    r_numAnodeRegisters = (numAnodeChannels+7)/8;       //round up to next register number
    r_numAnodes = 8 * r_numAnodeRegisters; //must be whole 8 bit registers
    r_PWMBufferSize = r_totNumChannels = r_numAnodes * r_numCathodes;

    r_PWMBuffer = (uint8_t *) realloc(r_PWMBuffer, r_totNumChannels); //resize array for PWMBuffer
}

can you give a function that shows what isn't working in code? something you would expect to do one thing, but isn't working out that way? I'm not certain I know what you mean by "the variables return zero". Also some more information about the members of an MB_GFX_SPI, and where mbR comes from.

Try initializing mbGFX with its regular constructor (GFX_SPI mbGFX(...);) instead of using copy-initialization (GFX_SPI mbGFX = MB_GFX_SPI(...);).

First, I would do what Edgar Bonet suggested, call the normal constructor:
MB_GFX_SPI mbGFX (Period, numCathodeLeds, numAnodeLeds, CathodeSSPin, AnodeSSPin);

Second, I'm not keen on what you are doing in the constructor for a variable which appears to be at global scope (mbGFX).
See What's the "static initialization order fiasco"?
Basically you cannot assume that constructors in different compilation units are called in any defined sequence, you also cannot assume that the system has been initialized yet (ie. init() called).
Thus, things that address the hardware (eg. clearScreen(0);) may not work properly, or at all.

thanks for additional suggestions. I've recently installed Visual Studio+Visual Micro and have been tracing the initialization process.

authors: วิภาวรรณ เบียดกลาง


text:
I bought USB > FT232RL, can I use it to program a bootloader onto an Arduino?
I bought this thing off of eBay:

eBay Link

Will it allow me to program an ATmega[xxx] (Arduino clone) with a bootloader?
 --> If so, how would I go about it? What should I do, and what should I certainly not do?
 --> If not, what do I need (or where can I learn) to be able to use an Arduino clone with the Arduino IDE?

I'm a bit new to Arduino, and since I learned that a fair amount of the clones being sold on eBay don't have a bootloader, I wondered how to fix this. (and the "barebones" seem to be quite a bit cheaper)

Answer - summarized from different answers below (as I can only mark one answer below as accepted):

Can you use an FT232R to burn a bootloader onto an AVR (such as an ATmega328)?

=> Yes you can, though it's a bit annoying to do, as it's slow and a bit more complicated than just plug and play. See the first part of Chris Stratton's answer below.

I already have a working Arduino style board, can I use that?

=> Yes, you can use for example a UNO-style board to program another. This process is explained here: http://arduino.cc/en/Tutorial/ArduinoISP, which was referenced in the second part of Chris Strattons' answer below.

The two options above are too much of a hassle for me, or I don't have an Arduino yet/available, is there another option?

=> Yes, you can buy a USB to ISP (In-System Programmer) board/programmer. They're pretty cheap and are called USBISP or USBASP for example. Here's an example: http://www.ebay.com/itm/180980285082, referenced at the end of MatsK's answer. (or an even cheaper one: http://www.ebay.com/itm/390806886235).

None of the Arduino clones I bought (from several web stores) came without a boot loader. They were all programmed with bootloader / blink example. How did you determine there is no bootloader on it?

Because I asked the seller, for example the Mini Pro on the page doesn't have one: http://www.ebay.com/itm/400683486113 (while their 'Nano' does).

In fact, you can, but you are unlikely to enjoy it as it will be fairly slow.
While this module is intended for serial communications - which the ATmega won't support until it has a bootloader on it - the chip around which it is built can also be operated in "bitbang" mode:
http://www.ftdichip.com/Support/Documents/AppNotes/AN_232R-01_Bit_Bang_Mode_Available_For_FT232R_and_Ft245R.pdf
Using reconfigured pins of this wired to the ISP pins of your target, and an implementation of the ISP algorithm running on the PC, it will indeed be possible to load a bootloader on to a new ATmega chip.  However, USB is not designed for this type of usage - it is meant to move large blocks of data, rather than to efficiently do sequences of tiny operations.  The result is that the loading process will be drastically slower than with other methods.  You may also spend a fair amount of time tracking down software to do it, or writing your own.
If you have an already working Arduino-style board available, you can use that to program your new chip:
http://arduino.cc/en/Tutorial/ArduinoISP

avrdude has a number of programmer entries with ft232r in the name, implementing various bitbang configurations for FTDI chips, so the software side is pretty much solved. That said, I agree with @ChrisStratton that it's not much fun.

Drastically slower, meaning a few minutes instead of seconds, or even more? (ballpark number's fine).
That would only be the first time then, for burning the bootloader? Because after the bootloader's been put in it can be programmed through a serial connection, meaning seconds, right?

I expect it would take less time to run than it would to find the software to do it that way, but yes, the bootloader is fairly small and only needs to be loaded once.

Ok, that's what I figured. I think I'll be using your second suggestion since I already have a UNO clone.

You must use a ISP or (HV)PP programmer in order to write the Arduino (or similar) bootloader to the chip first. Only once you have done so will you be able to program it via a serial connection.

Will it allow me to program an ATmega[xxx] (Arduino clone) with a
  bootloader?

NO. The serial device can only be used when the Atmel ATmega chip has a bootloader burned onto it.

--> If so, how would I go about it? What should I do, and what should I certainly not do?

To burn a bootloader onto a Atmel AVR chip you need a "AVR ISP (In-System Programmer)".
There is a small 2x3 pin contact on your Arduino board.
In the Arduino IDE under the menu "Tools", "Programmer" you will find the different "AVR ISP (In-System Programmer)" that you can use.
Please note that some programmer have an 2x5 pin ISP contact and if that is the case you will also need to buy a 2x3 to 2x5 adapter.
Ref.: http://arduino.cc/en/Hacking/Bootloader

--> If not, what do I need (or where can I learn) to be able to use an Arduino clone with the Arduino IDE?

Most Arduino clones bought on ebay have info witch clone of Arduino they are.

I'm a bit new to Arduino, and since I learned that a fair amount of
  the clones being sold on eBay don't have a bootloader, I wondered how
  to fix this. (and the "barebones" seem to be quite a bit cheaper)

Im a bit confused, I have bought ~10 Arduino clones from ebay and all had a bootloader. And they are clones of UNO, Nano, Leonardo and Mini Pro and that is what I uses for settings in my Arduino IDE.
I'm interested in witch ebay clones that doesn't have a bootloader, could you post a comment with that info?
I use a USBASP (example: http://goo.gl/kCiMd) as my external programmer.

The serial device can only be used when the Atmel ATmega chip has a bootloader burned onto it. — This is true, as far as that goes, but the FT232 also has bitbang mode.

"Most Arduino clones bought on ebay have info witch clone of Arduino they are." > I'm not confused about which clone/model they are, just curious about how to burn the bootloader ;)
I asked a seller of a 'Mini Pro' on the following page whether it has a bootloader, and he says it doesn't: http://www.ebay.com/itm/400683486113 (while their 'Nano' does).

DaJF it was not my intention to be condescending.

No problem, I didn't interpret it that way, just wanted to clarify :)
The fact that you haven't come across a clone without a bootloader gives me hope I won't either, so thanks for the info.


text:
Power suply for MicroSD card breakout board
I'm developing a project and I need to connect to my Arduino Mini with a SD card breakout board. The problem is that I can't plug it directly to the Arduino since it is already powering some sensors and a BITalino, and I was told that it would, for some reason, be better to connect an external battery to the SD board.
My question is if i can supply this  MICROSD CARD BREAKOUT BOARD+ with a 3.7V battery, instead of a 5V.
Thank you!
Description:

Onboard 5V->3V regulator provides 150mA for power-hungry cards
3V level shifting means you can use this with ease on either 3V or 5V systems

I don't see why you can't use the same power supply. Using a separate battery seems silly to me.

SD cards don't use much juice, you could probably run them of off GPIO pins pulled low/high

My question is if i can suply this MICROSD CARD BREAKOUT BOARD+ with a
  3.7V battery, instead of a 5V.

Yes you can supply MICRO SD Card Breakout with 3.7 volt battery as it has onboard voltage regulator which will provide required voltage to the board.

I was told that it would, for some reason, be better to connect an
  external battery to the SD board.

Because every sensor will take 3V - 5V as per its requirement. So some time Arduino can not be able to provide 3.3 - 3.5 volt to SD Card board and there could be no data logging or some wrong data logging to SD card. Thus it is advised to do such.

The "some reason [it would] be better to connect an external battery to the SD board" is that you need to make sure that the controller chip and SD card are getting enough power that it can write reliably.
To figure out whether and what kind of external power you need you start with the specifications. The first clue is in the general product description to which you linked; it says that it has an "Onboard 5v->3v regulator" that "provides 150mA for power-hungry cards." This is a good start, but you'll see below that we'll need further information from a link on the tutorial page.
Linear power regulators give a fixed voltage output (in this case, 3 V) from a higher voltage input. To work properly they need an input voltage a bit higher than their output voltage; the minimum difference between the two is called the dropout voltage. From the schematic we can see that the board is using an LP298x regulator. A datasheet for a (hopefully typical) part from that series indicates that dropout voltage is 300 mV or 0.3 V. 3.7 V is considerably higher than 3 V + 0.3 V, so you're very likely to be ok in that respect with your external battery. (We also note here that the input voltage can range up to 16 V; we'll use this information later.)
The other thing you need to look at is whether you can supply enough current to the board and card that, under all reasonable circumstances, they can function properly. From the original description you know the board uses a 150 mA regulator which means that the designers expect that you'd never need more than that. (And if you do, the card isn't going to get it anyway.)
For simplicity it's easiest just go go with being able to provide 150 mA or more on the regulator's input, regardless of voltage. (In theory you can supply less power on input if you're giving it a higher voltage, because P = EI, but it's not generally worth the time and effort to go there for a hobbyist project.)
Batteries have a discharge rates known as C rates, and unless you know what you're doing (I don't :-)) your best bet is to stay well within the standard discharge rate as specified by the manufacturer. Adafruit sells a typical 3.7v 1200mAh Lithium Ion Polymer Battery; looking at its datasheet we see that the standard discharge current is 0.5 C5 A, which is 0.5 * 1200 mAh / 1 h = 600 mA, plenty more than you need. So if you're using that battery you'd be safe. (I started out by looking at the 500 mAh battery which has a  0.2 C5 A = 100 mA standard discharge rate; my guess is that that's fine because the maximum discharge rate is 1 C5 A, but this has implications on battery capacity and the like so I'd ask someone first.)
But it would be nice to use your existing power supply for the card rather than use a separate battery, I'm sure. Your best bet for that is the suggestion from  Enric Blanco: use an external power supply that can deliver enough current to both the Arduino Pro regulator and the SD Card breakout board regulator that they'll both be happy.
Sadly, Adafruit's Ardiuno Mini product page gives no indication of current requirements. However, a quick look at the v5 schematic we can see that it's using an LP2985AIM5-5.0 regulator and a web search turns up a product page for this that says it's rated at 150 mA.
Add the 150 mA for the Arduino Mini to the 150 mA for the SD card board and you can figure that any external power supply that is giving more than 300 mA at the minimum 7 V input voltage specified for the Arduino Mini should be just fine. The 7 V should also be ok for the SD card board regulator since, even if it's a slightly different model from our spec. sheet, it's unlikely to have a maximum voltage hugely below the 16 V for that part. But you could check the exact part your board is using if you're worried.

You just need to bypass the Pro Mini regulator in order to avoid loading it too much, because the uSD Card board already has one.
Instead of connecting the uSD Card breakout board to the VCC pin, connect it to the RAW pin. Provided that your power source (3.7V battery? wall adapter?) can source enough current for the Pro Mini plus the uSD card board (something that's very likely), everything will be fine. No need to add any extra power source.
The regulators in those boards have very similar dropout characteristics (300-400mV).

Yes you can give power supply to MICROSD CARD BREAKOUT BOARD from a 3.7V battery It has Onboard LP98x Voltage regulator winch provide 3.3V regulated power supply.
Take reference from here Schematic of MICROSD CARD BREAKOUT BOARD

authors: Константин Агеев


text:
Stepper motor control
I'm using Arduino to control a stepper motor. I need it to make one revolution and then stop. I'm new to this and haven't ran it yet. Will this do for me?
#include <Stepper.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  myStepper.setSpeed(60);
}

void loop() {
  myStepper.step(stepsPerRevolution);
}

No, that will not do what you want. That will continuously rotate the stepper round and round and round.
The clue as to why is in the name of the function you put the myStepper.step call: "loop". That function repeatedly loops around over and over again, so your step function will be called over and over again.
There is one piece of information lacking from your thinking at the moment, and that is when do you want the stepper to rotate? If it's just once when you turn the power on then it's as simple as doing everything (including calling myStepper.step) in setup() and leaving loop() empty. If not, then you will need to add appropriate logic to only run the step function when the required conditions are met.

what if I want it to make just 10 revolutions and then stop.

The same way as for 1 revolution but with 10x the steps?

Yes, though another option is to put a for loop around the step command.  For a few rotations just multiplying the count works, but the count argument appears to be limited to +32767 or -32768 (on an ATmega)


text:
Connecting Bluetooth module to Arduino Uno without RX/TX pins
Can I connect a Bluetooth module to usual digital pins, other than D0/D1 (RX/TX) pins as the shield is already using the D0 and D1 pins?
My Bluetooth module is an HC-05 MODULE.

Please be more specific. What Bluetooth module? What do you mean as in "0,1 pins" in comparison to "normal digital pins"? You mean IO pins from the Arduino instead of ICSP?

Google SoftwareSerial

Classic Arduinos use pins 0 and 1 for serial communication to the host computer, so it is problematic to connect a bluetooth module there anyway - it can be done, but basically means that programming the board and communicating with it by serial will not work (at least not reliably) until the interfering bluetooth module is removed or disabled.  For these boards you need to use a software serial instance to talk to the module, and you can put it on most any digital pins.
ATmega32u4 boards like the Leonardo do not have debug/programming on pins 0 and 1 but do have a hardware UART there, so those would be the best choice for a bluetooth module, but you can still use software serial.
The Arduino Mega has additional hardware serial pins that would be good choices, but you can use software serial.
Various ARM based boards with Arduino ports typically have additional hardware serial pins which you should use.  Software serial may or may not be an option on these (it's not that an implementation cannot exist, but that software serial is generally disadvantageous, so when a chip has more hardware UARTs that particular function may not be ported).

you can define pin and can use after defining int RX=any pin TX=any pin

Define any two PWM to RX/TX it will work do not use 0,1 it will give serial communication error...


text:
Error trying to compile an example from newly added Arduino menu library
I added the ArduinoMenu library https://github.com/neu-rah/ArduinoMenu and when I try to compile one of the examples, I get following error.

Using library LiquidCrystal at version 1.0.5 in folder: C:\Program Files (x86)\Arduino\libraries\LiquidCrystal exit status 1 Error compiling for board Arduino/Genuino Mega or Mega 2560.

How can I fix this?

We need the full error output, not just the last couple lines that happened to be visible. If you were observant you would have seen that there is a scroll bar on the right side of the black console window at the bottom of the Arduino IDE window that indicates you can scroll up to see more text. Spend some time reading those errors and doing research to see if you can figure out what's wrong on your own. After that if you still can't solve the problem click the button on the right side of the orange bar after an error "Copy error messages" then edit your question to include the full error.

I think you have to add your library in the library folder. Below is the path of that folder. It will help you.
C:\Program Files (x86)\Arduino\libraries

You should never install a library to the Arduino IDE installation folder because it will be lost if you update to a new version of the IDE. If you're doing a manual library installation you should always install them to the libraries subfolder of the sketchbook folder. The location of the sketchbook folder can be found at File > Preferences > Sketchbook location.

@per1234 Yes, you're right. But everyone uses this method and it's working fine.

@per1234... This is the simplest way to add library by just copy and paste.

there are better places for libraries. the install folder is for core, and customizing it is asking for trouble

@Hasan if by "everyone" you mean unfortunate beginners who found some bad advice on the internet. And no, it's not working fine, as I already explained.

@karanrp it's no more simple than installing to the sketchbook folder and much less so when you update and find all your 3rd party and custom libraries have disappeared.

please install from arduino ide library manager

Can you compile the LCD example for that board?
just to make sure you have LiquidCrystal library ok.
Then tell us what was the example? There are hardware specific examples.
Also try to compile the serial menu example, just to make sure that ArduinoMenu library is ok for your board.

authors: Назар Онищенко


text:
Arduino & ESP8266
I connect my ESP to Arduino to my PC.
If I send AT commands from my serial monitor, I receive full response. I use 115200 and both NL & CR in my serial monitor.
ESP TX is connected to TX Arduino, same for RX.
The problem is when I try to send commands from my Arduino code. I don't receive any response. I use same 115200 both for serial and for ESP8266.
I user this code:
#include <SoftwareSerial.h>
SoftwareSerial esp8266(0,1);

void setup()
{
    Serial.begin(115200);
    esp8266.begin(115200);
}

void loop()
{
    sendCommand("AT+GMR\r\n");
}

String sendCommand(String command, const int timeout, boolean debug)
{
    String come = "";

    while(esp8266.available())
    {
        char c = esp8266.read(); // read the next character.
        Serial.write(c);
        come += c;
    }
    Serial.println(come);
    return come;
}

I can't see what is wrong here and why that works with just the Serial Monitor.

Where is the godsbedamned website which is telling people to use SoftwareSerial on pins 1 and 0 so I can wipe it of the face of the earth?!?!

You connected Tx>Tx and Rx<Rx. You have no V dividers. HOW DOES IT WORK?!?!?!?! (me confused af) please post a picture of your circuit

@Majenko a search for "SoftwareSerial esp8266(0,1);" shows it literally everywhere.  I'm generally negative on the canonical question idea, but that and duplicate closes might be warranted.

@Dat Ha - Yes, TX to TX and RX to RX in certain cases can be correct. See my answer.

When you are using Arduino board just as USB --> RS232 converter then you have to, as you said, connect TX to TX and RX to RX. But when you want communication between microcontroler and ESP then you have to connect TX to RX and RX to TX. Here I explained that in details.

Make a choice:

Are you using pins 0 and 1 for communicating with the PC, or
Are you using pins 0 and 1 for communicating with the ESP8266?

You cannot do both.
Move the ESP8266 onto some other pins.

For esp8266 like in my code up

@Corneliu then your Arduino cannot communicate with the PC, which means you will need to remove the Serial.xxx lines and find some other way of telling if your program works.  That path is not recommended.  Rather, move your ESP8266 to different pins.

Ok. I move esp to pin 2 and 3; I set : ESP8266.begin(115200);  And in my loop i have :  ESP8266.println("AT\n");   And in my serial monitor i got : ƒÿ

Have you got it wired right? Your nominated TX pin through a voltage divider to ESP8266 RX, and ESP8266 TX to your nominated RX?

Are you sure the baudrates of both devices (and serial monitor) are set right? If one is wrong, it's very likely to receive weird characters