text:
Determining direction from IMU accelerometer data
I am learning how to integrate sensors on arduinos and read their data.
My ultimate purpose is to place the IMU on a robot and use it in determining the robots location in an environment.
Using the following code, I am able to get accelerometer and temperature data:
// (c) Michael Schoeffler 2017, http://www.mschoeffler.de

#include "Wire.h" // This library allows you to communicate with I2C devices.

const int MPU_ADDR = 0x68; // I2C address of the MPU-6050. If AD0 pin is set to HIGH, the I2C address will be 0x69.

int16_t accelerometer_x, accelerometer_y, accelerometer_z; // variables for accelerometer raw data
int16_t gyro_x, gyro_y, gyro_z; // variables for gyro raw data
int16_t temperature; // variables for temperature data

char tmp_str[7]; // temporary variable used in convert function

char* convert_int16_to_str(int16_t i) { // converts int16 to string. Moreover, resulting strings will have the same length in the debug monitor.
  sprintf(tmp_str, "%6d", i);
  return tmp_str;
}

void setup() {
  Serial.begin(9600);
  Wire.begin();
  Wire.beginTransmission(MPU_ADDR); // Begins a transmission to the I2C slave (GY-521 board)
  Wire.write(0x6B); // PWR_MGMT_1 register
  Wire.write(0); // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
}
void loop() {
  Wire.beginTransmission(MPU_ADDR);
  Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) [MPU-6000 and MPU-6050 Register Map and Descriptions Revision 4.2, p.40]
  Wire.endTransmission(false); // the parameter indicates that the Arduino will send a restart. As a result, the connection is kept active.
  Wire.requestFrom(MPU_ADDR, 7*2, true); // request a total of 7*2=14 registers

  // "Wire.read()<<8 | Wire.read();" means two registers are read and stored in the same variable
  accelerometer_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x3B (ACCEL_XOUT_H) and 0x3C (ACCEL_XOUT_L)
  accelerometer_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x3D (ACCEL_YOUT_H) and 0x3E (ACCEL_YOUT_L)
  accelerometer_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x3F (ACCEL_ZOUT_H) and 0x40 (ACCEL_ZOUT_L)
  temperature = Wire.read()<<8 | Wire.read(); // reading registers: 0x41 (TEMP_OUT_H) and 0x42 (TEMP_OUT_L)
//  gyro_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x43 (GYRO_XOUT_H) and 0x44 (GYRO_XOUT_L)
//  gyro_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x45 (GYRO_YOUT_H) and 0x46 (GYRO_YOUT_L)
//  gyro_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x47 (GYRO_ZOUT_H) and 0x48 (GYRO_ZOUT_L)

//  // print out data
  Serial.print("aX = "); Serial.print(convert_int16_to_str(accelerometer_x));
  Serial.print(" | aY = "); Serial.print(convert_int16_to_str(accelerometer_y));
  Serial.print(" | aZ = "); Serial.print(convert_int16_to_str(accelerometer_z));
//  // the following equation was taken from the documentation [MPU-6000/MPU-6050 Register Map and Description, p.30]
  Serial.print(" | tmp = "); Serial.print(temperature/340.00+36.53);
//  Serial.print(" | gX = "); Serial.print(convert_int16_to_str(gyro_x));
//  Serial.print(" | gY = "); Serial.print(convert_int16_to_str(gyro_y));
//  Serial.print(" | gZ = "); Serial.print(convert_int16_to_str(gyro_z));
  Serial.println();

  // delay
  delay(1000);
}

Giving me output like the following:
aX =   3526 | aY =   -968 | aZ = -11988 | tmp = 25.89
aX =   3478 | aY =   -936 | aZ = -12020 | tmp = 25.91
aX =   3530 | aY =   -922 | aZ = -12002 | tmp = 25.91
aX =   3490 | aY =   -896 | aZ = -12006 | tmp = 25.94
aX =   3498 | aY =   -898 | aZ = -12036 | tmp = 25.91
aX =   3520 | aY =   -916 | aZ = -12050 | tmp = 25.91
aX =   3466 | aY =   -924 | aZ = -11960 | tmp = 25.91
aX =   3492 | aY =   -944 | aZ = -12026 | tmp = 25.92
aX =   3510 | aY =   -924 | aZ = -12048 | tmp = 25.91
aX =   3440 | aY =   -942 | aZ = -11980 | tmp = 25.91
aX =   3514 | aY =   -924 | aZ = -12066 | tmp = 25.91
aX =   3484 | aY =   -944 | aZ = -11968 | tmp = 25.92
aX =   3490 | aY =   -944 | aZ = -12012 | tmp = 25.92
aX =   3458 | aY =   -952 | aZ = -11944 | tmp = 25.92

What I need to know is how do I determine what direction my robot is moving in based on the accelerometer output?

You can't with any great accuracy.
The acceleration vector from the accelerometer is a combination of two things:

Gravitational acceleration
Acceleration due to change in the robot's velocity.

If the robot is travelling at a constant speed, there is no acceleration due to change in velocity, so the accelerometer will only be measuring gravity. No idea then how far the robot has gone.
If the robot is turning on the spot, again there is not acceleration change. So you don't know which direction the robot is facing!
You can get a rough idea of speed by integrating the acceleration, and distance by integrating speed. However any errors quickly accumulate, and thus the absolute distance may be very poor.
To get velocity (speed with a direction) or absolute position, you will need a magnetometer or gyroscope to estimate rotation.

You haven't described your robot but if it is a typical wheeled vehicle that can drive forward and backward, the accelerometer can give you one of those two directions (which is already known because you or your sketch commanded it). If in addition your robot can steer, the the accelerometer will give show a side force (aka centripetal acceleration or centrifugal force) in the direction of the turn.
Figuring out how much the robot turned (in order to get its current direction) is mathematically straight-forward but practically, it is noisy and subject to accumulating errors, as already pointed out.
If knowing orientation, thus direction of travel, is your goal, wouldn't a electronic compass (magnetometer) be of more help?

First you have to test, in which orientation the sensor on the IMU board is mounted. You can use your test sketch for this. If you don't move the sensor it will show you the gravitational force, which always points down. Orientate the IMU in such a way, that aX and aY are near zero. Now you know where up and down are. Move the IMU to the sides, until you found the direction, where only aX changes considerably, while aY is staying near zero. Then you have found the next direction.
Finally mount the IMU in your robot in the found orientation. Since you know, which of aX, aY and aZ change with which direction, you know the direction of the robots movement.


text:
Can I use arduino and mobile phone screen to make a touch board?
I'm new to Arduino, I want to use Arduino and a mobile phone screen to make a simple touch board.
This phone screen I mean, is like this:

Can I connect it to Arduino, and when my fingers touch the screen, Arduino can get the events?

From what I can tell, Nintendo DS screens are easy to inference (they even have breakout boards) and very cheap, but they are resistive, thus they need pressure to use. They aren't the kind on a iPhone, and are only one touch point.

Without details we can't answer the question.  You will need technical specs and/or a datasheet for the screen.

First, find a suitable phone screen! Good luck. Most of the touch screens that I have found are resistive, and will never feel like an iPhone. Try googling "Arduino touch screen". Adafruit have a promising one.
Once you find your screen, you will need to interface to it. With luck it will come with a pre-built library. Otherwise you will be up for quite a lot of coding.

source: Stack Exchange

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

sort: votes


text:
Need some help with controlling a fan through PWM
So lately I've been trying to control the speed of a 120mm 4-pin computer fan using PWM. This is what I've got so far, with the part above void loop() being from this thread
// Definition of Arduino type
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define  IS_MEGA  (1)
#define  IS_UNO   (0)
#else
#define  IS_MEGA  (0)
#define  IS_UNO   (1)
#endif

// Analog output (i.e PWM) pins. These must be chosen so that we can change the PWM frequency without affecting the millis()
// function or the MsTimer2 library. So don't use timer/counter 1 or 2. See comment in setup() function.
// THESE PIN NUMBERS MUST NOT BE CHANGED UNLESS THE CODE IN setup(), setTransistorFanSpeed() AND setDiodeFanSpeed() IS CHANGED TO MATCH!
#if IS_UNO
// On the Uno we can only use the OC1B pin, so these pin numbers are both 10
const int transistorFanPin = 10;     // OC1B
const int diodeFanPin = 10;          // OC1B
#else
// On the Mega we use OC1B and OC1C
const int transistorFanPin = 12;     // OC1B
const int diodeFanPin = 13;          // OC1C
#endif

// Definitions for PWM fan control
const unsigned char maxFanSpeed = 80;   // this is calculated as 16MHz divided by 8 (prescaler), divided by 25KHz (target PWM frequency from Intel specification)

void setup()
{
  // Set up the PWM pins for a PWM frequency close to the recommended 25KHz for the Intel fan spec.
  // We can't get this frequency using the default TOP count of 255, so we have to use a custom TOP value.

#if IS_UNO

  // Only timer/counter 1 is free because TC0 is used for system timekeeping (i.e. millis() function),
  // and TC2 is used for our 1-millisecond tick. TC1 controls the PWM on Arduino pins 9 and 10.
  // However, we can only get PWM on pin 10 (controlled by OCR1B) because we are using OCR1A to define the TOP value.
  // Using a prescaler of 8 and a TOP value of 80 gives us a frequency of 16000/(8 * 80) = 25KHz exactly.
  TCCR1A = (1 << COM1B1) | (1 << COM1B0) | (1 << WGM11) | (1 << WGM10);  // OC1A (pin 9) disconnected, OC1B (pin 10) = inverted fast PWM
 #ifdef FAN_AUDIO_TEST
  // test code to get 440Hz output (= concert A) to test the logic
  OCR1AH = 0;
  OCR1BL = 71;  // 50% duty cycle
  TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12);  // TOP = OCRA, prescaler = 256

  OCR1AL = 141; // TOP = 141, 16000000 / (256 * 142) = 440.014
  OCR1BH = 0;
 #else
  OCR1AH = 79;
  OCR1AL = 0;  // TOP = 79
  TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);  // TOP = OCR0A, prescaler = 8

  OCR1BH = 0;
  OCR1BL = maxFanSpeed;  // max fan speed (i.e. pin 5 initially low all the time)
 #endif

  TCNT1H = 0;
  TCNT1L = 0;
#else

  // On the Mega we use TC1 and OCR1B, OCR1C
  TCCR1A = (1 << COM1B1) | (1 << COM1B0) | (1 << COM1C1) | (1 << COM1C1) | (1 << WGM11) | (1 << WGM10);  // OC1A disconnected, OC1B = OC1C inverted fast PWM
  TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);  // TOP = OCR1A, prescaler = 8
  TCCR1C = 0;
  OCR1AH = 0;
  OCR1AL = 79;  // TOP = 79

  OCR1BH = 0;
  OCR1BL = maxFanSpeed;
  OCR1CH = 0;
  OCR1CL = maxFanSpeed;

  TCNT1H = 0;
  TCNT1L = 0;
#endif

  // We have to enable the ports as outputs before PWM will work.
  pinMode(transistorFanPin, OUTPUT);
  pinMode(diodeFanPin, OUTPUT);
  pinMode(A0, INPUT);
  Serial.begin(9600);
}

// Set the transistor fan speed, where 0 <= fanSpeed <= maxFanSpeed
void setTransistorFanSpeed(unsigned char fanSpeed)
{
  OCR1BH = 0;
  OCR1BL = fanSpeed;
}

// Set the diode fan speed, where 0 <= fanSpeed <= maxFanSpeed
void setDiodeFanSpeed(unsigned char fanSpeed)
{
#if IS_UNO
  OCR1BH = 0;
  OCR1BL = fanSpeed;
#else
  OCR1CH = 0;
  OCR1CL = fanSpeed;
#endif
}

void loop() {
  if (analogRead(A0) >= 800) {
    setTransistorFanSpeed(80);
    Serial.println("HIGH");
    Serial.println(analogRead(A5));
  } else {
    setTransistorFanSpeed(0);
    Serial.println("LOW");
    Serial.println(analogRead(A5));
  }
  delay(100);
  Serial.println("I'm running.");
}

In the serial monitor I'm getting the output I'm expecting ("HIGH" and 1023 when I've bridged the arduinos 5V pin to A0), but the signal doesn't seem to have any effect on the fan at all. In the thread linked above there's talk about this being an inverted fast PWM signal, and that it's assumed I'm using an opto isolator. Could this be why the signal doesn't have an effect on the fan? If anyone out there has any experience on this and are able to help me, that would be greatly appreciated.. :)

How did you connect the fan? What does "no effect" mean? Is the fan not running, or doesn't it run slower than usual? More info on these kinds of fans

The fan runs at full speed with and without a PWM signal.

@Gerben also, I connected the fan correctly according to the article you linked. Negative and positive power directly connected to a 12V power supply, and the 4th pin (PWM) to the arduino.

Did you connect the ground of the fan (/12volt powersupply) to the ground of the arduino? If you don't connect the grounds, there is no path for electrons to flow.

What is the frequency of pulses in Arduino PWM? I've seen a passing reference to it only being 500 Hz. If the fan needs a 25KHz signal, that wouldn't do it. In fact, if it is anything other than the frequency the fan is wired for, it won't work.

@DuncanC Both the thread I linked in my original post, and the comments in the code I pasted explain how the frequency is changed to 25KHz.

@Gerben thanks, this solved it for me. :)

Little side note, turns out the fan inverts the meaning of the duty cycle, so a 0% duty cycle means the fan runs at 100% speed, and a 100% duty cycle means no speed, or slowest speed the fan can go (varies from fan to fan it seems). This also explains how the fan runs at 100% when there is no PWM signal present.

Kind of makes sense. If you connect the fan to an old motherboard with only 2 pins, you'd want the fan to run at full speed.

You need to connect the ground of the fan (/12volt power-supply) to the ground of the Arduino. If you don't connect the grounds, there is no path for electrons to flow.

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


text:
Non-blocking strobing code?
I'm trying to figure out how to create some non-blocking code to strobe some RGB leds with analogwrite  7 times a second; I'm really not to sure how to go about this. If anybody could give me some help that'd be great! :)

Which part of the code did you want to unblock?

By non-blocking I mean not using the delay function. And the question is stated above, perhaps you don't understand?

analogWrite() doesn't call delay().

Look at the BlinkWithoutDelay example

Blink with out delay uses boolean which just turns it on or off if I understand correctly. I need to change the current state which could be 0-255 to the specified new one, and back. I'm not sure how I would use boolean variables then.

@ignacio. So heres the deal: I'm using the analogwrite pwn to control an RGB LED. But I want it to STROBE  (on then off) at a specific Hertz. So say normally to do thay you would call analogwrite X then delay for specified period then analogwritelow; so on so forth etc... I can't use delay as it will.block other code. So I need to do it using timers. How would I go about it using timers?

With either an overflow ISR or CTC and a compare ISR.

Care to explain that more?

See the timer section of the MCU datasheet, the interrupt section of the Arduino reference, and the interrupt section of the AVR LibC documentation for more details.

What you want can be achieved with your MCUs timers and their associated interrupts. Timers are basically counters that run inside your hardware and they run decoupled from your code. Since one usually knows how fast these timers tick (e.g. how long it takes to count from one to two and so on) you can specify events that happen when a certain amount of timer ticks passed.
I suggest you have a look at SimpleTimer and Timer1 (the second page is only for ATmega168/328)
Both pages include some code samples where they specify some method that will be called every x milliseconds.

SimpleTimer isn't a hardware timer solution. In fact, it won't work if you have blocking code...

Timers are the best way to go, (much) less overhead and you don't have to worry about it elsewhere in your code (other than managing variable use between your main loop and your ISRs).
But I do have a habit of doing things the hard way in code first and then move to timers once I've got it the way I'd like.
Here is sample code to flash the on board LED X times per second, I have calculated it to mean, ON 7 times per second and OFF 7 times as well (meaning, there is a change of state 14 times per second).
This code isn't efficient, it doesn't take into consideration that the value is already set or not, it just writes the value that it should be right now.
Finally, to go to analogWrite and use PWM, just change:
digitalWrite(LED, HIGH);

to
analogWrite(NEW_PIN, PWM_VALUE);

code:
#define LED               13
#define TIMES_PER_SECOND  7

const int M1 = 1000 / TIMES_PER_SECOND;
const int M2 = 1000 / TIMES_PER_SECOND / 2;

void setup(){
  pinMode(LED,OUTPUT);
}

void loop(){
  if(millis()%M1<M2){
    digitalWrite(LED, HIGH);
  } else {
    digitalWrite(LED, LOW);
  }
}

Remember there is overhead with digital (and analog) writes, so (as I mentioned) you could check to see if the value is set already or not and skip the write.


text:
Homebrew Arduino using ATMEGA328P, ISP or ICSP?
I plan on creating a homebrew Arduino breakout board using the ATMEGA328P smd version. I'm geeting confused by the wealth of information out there as to whether I should be using ICSP or ISP to program it. It is a blank chip, aka no Arduino bootloader on it yet. I'd rather not have to buy a specialized programmer to burn the bootloader, I do have another Arduino I could use to burn the bootloader and upload sketches to it with.
So the question is; Do I use ISP or ICSP, or both?

To program it you could use an ISP programmer. In which case you would not need the bootloader. You can use an Arduino as an ISP programmer, but that's not really a long term solution, as you can no longer use the arduino for anything else.
The other option is to program it using a usb-to-serial. In this case you do need the arduino bootloader. To program this bootloader (once) you can use the above method, using an arduino board.
Third option would be implement USB into the bootloader, just like the completely Open Source Pro Trinket (bootloader and schematic). You'd have to add some resistors, zener diodes and a usb plug (just strip an old usb cable). A bit more technical and challenging, but definitely the cheapest

Using an Arduino as an ISP in no way means you cannot use it for other purposes - load the ISP sketch, add your reset defeat component, use it to ISP your target, remove the component, load a different sketch...

ICSP is used for PICs, not AVRs. Use ISP, which can be performed either by an Arduino via ArduinoISP or by a dedicated programmer.

I'm currently holding an Arduino Uno that has a 6 pin male header that says on the silk screen next to the header "ICSP".

Yeah, it's mislabeled. It's supposed to read "ISP".

The OP question still remains I think: I would interpret it as: "should I use a programmer or an Arduino as ISP? What are the advantages of each?"

I think both terms mean pretty much the same thing. In-System-Programmer vs In-Circuit-Serial-Programmer. I didn't know one was PIC, and the other AVR. I usually call it ICSP, as ISP sounds a lot like SPI (and both use MISO, MOSI, SCK).

@Gerben: At a high level, I agree. At a low level, they are subtly different (ICSP more resembles AVR's HVSP at the electrical level, but uses different signaling).

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


text:
How to send the MFRC522 RFID module into sleep mode?
I'm trying to get the power consumption of a MFRC522 RFID module down, currently while running it consumes about 4mA. There should be a way to put it into sleep mode, I just can't find any documentation on it. I'm using the module with a arduino currently if that helps; and this is the module itself : MFRC522

http://www.nxp.com/documents/data_sheet/MFRC522.pdf
Look at section 8.6.2   Soft power-down mode.

I still don't get how to implement this in my arduino code.

First, that wasn't your question. Secondly, you didn't say how you connected it. Are you using SPI or UART? What library are you using?

I didn't know there was anything other than an SPI library for it; but currently using SPI.

Two questions, one answer. I'm done helping you.

Sam, it sounds like you're asking two different questions: "How do I put the MFRC522 into sleep mode?" and "How do I send commands, such as the soft power-down command, from an Arduino to the MFRC522?". I suggest you open a separate, independent question to ask that second question, as recommended by http://meta.stackexchange.com/questions/39223/one-post-with-multiple-questions-or-multiple-posts .


text:
Arduino ESP8266 receive email?
Is there a sketch that supports the receiving of email using the Arduino environment on the ESP8266? I can only find support for sending email. I know it's possible because the NodeMCU environment supports it. Any help is appreciated!

receiving e-mail as in acting as an e-mail server, or simply pulling e-mail from another server?

Pulling email from another server

In that case it depends on the interface of the other server that you are pulling the mail from - the easiest might be from a web interface, in which case something like this could work

Once you know how to connect to any server and send messages to it, retrieveing emails is just a matter of sending right messages (=commands).
Here below follows an "IMAP tutorial", i.e. guide to which commands to send to an IMAP server to search and retrieve messages.
Note: once you connect to the IMAP server, the first command to send is the login command:
foo login user password

"foo" is just a session identifier, not a keyword. "login" is the keyword.
Once you get the welcome message, you can start sending more commands:
Select the proper folder:
. SELECT "INBOX"

Look for desired message (strings are always considered substrings, so no wildcards are needed):
. SEARCH FROM "user@example.org" SUBJECT "some keywords here"

This will result in list of matching messages, with search results formatted as follows:
* SEARCH 5 10 456

This means messages n.5, n.10 and n.456 match the query.
If examining just the subject (which may contain keywords and switch as required) is not enough, the whole body can be retrieved, both marking the message as read or leaving it untouched:
. FETCH 5  BODY[TEXT]

or
. FETCH 5  BODY[TEXT].PEEK

End IMAP session with:
. logout

For experiments from Windows using telnet:
telnet mailserver.domain.com 143

Reference:
https://www.skytale.net/blog/archives/23-Manual-IMAP.html


text:
Arduino Leonardo timing Inconsistency
I've got a question regarding the use of Millis() on a Leonardo Arduino. I'm currently using it to time 4 seconds elapsed while sending a serial message every second. These messages play a sound. On the fourth message the sound is different to signify that the Arduino has started an event.
I'm running into an issue where the sounds are occasionally being played sporadically without a consistent 1 second between them. I'm wondering if there is a better way of doing what I'm doing? During the timing the Arduino is doing nothing else, and the receiving computer is also generally not doing anything taxing. Is this even an issue from the Arduino side? My receiving program is written in C# using System.IO.Ports.SerialPort.
The reason this is done through Arduino is because the event started by the Arduino needs to correspond exactly to the sounds, though if this remains unresolved I will need to rework this.
Edit: Code as requested.
void setup()
{
    //Setup Code
}

void loop()
{
    //Code that handles other serial messages and various states
    if (isSpecificState == true)
        onSpecificState();
}

void onSpecificState()
{
    //Setup to handle state

    long holdStart = millis();
    long holdDuration = 0;

    boolean print1 = false;
    boolean print2 = false;
    boolean print3 = false;
    boolean print4 = false;

    while(holdDuration <= 4000)
    {
        if (holdDuration >= 4000 && !print4)
        {
            Serial.println("tt_sound:2");
            print4 = true;
        }
        else if (holdDuration >= 3000 && !print3)
        {
            Serial.println("tt_sound:1");
            print3 = true;
        }
        else if (holdDuration >= 2000 && !print2)
        {
            Serial.println("tt_sound:1");
            print2 = true;
        }
        else if (holdDuration >= 1000 && !print1)
        {
            Serial.println("tt_sound:1");
            print1 = true;
        }
        holdDuration = millis() - holdStart;
    }

    //Handle state
}

As I mentioned in the comments, the Arduino is doing nothing else while the timing is happening.

Can you post your Arduino code so that we see if there is an issue in there?

Why the downvote? @jfpoilpret code is up, its painfully simple though.

Added clarification, the reason I didn't post the code initially is because 95% of the time it works flawlessly. There are however occasions caused by circumstances I haven't figured out in which the sounds are off. This is what I need help with.

Why not use another timer to schedule them?

Have you tried printing the value for holdDuration and see if it is consistent?

Just to clarify: I did not downvote your question. About your code, I doubt you always pass in the first if, typically that first if should be located after the while loop. Important question: what are the types of holdDuration and holdStart?

@IgnacioVazquez-Abrams Could you elaborate? I'm not sure I understand. @Craig I haven't, I've not been able to consistently reproduce the issue. @jfpoilpret Didn't mean to imply you had, was an open question :) Both holdDuration and holdStart are of type long, same as millis() return type.

I think millis() is actually unsigned long but that is probably not the issue unless you are running for more than 24 days.

Please post the entire code, not just the part that, I presume, is inside the loop function.

Notice items 2 and 3 in this answer: http://electronics.stackexchange.com/a/126063/8627 You may be able to pin point if this is the issue by disabling USB communications and switching to UART combined with a UART-to-USB cable.

Thoughs:
Unfortunately I have been unable to get to the bottom of this issue. I noticed the problem tends to happen the first time the interaction starts after the computer and Arduino are idle.
Without knowing too much about how the serial communication is built I'm guessing that without traffic the connection is put to sleep, or generally inactive, and the sound delay is a result of the connection needing to re-initialize or something of that nature. I cant recall a time when the issue occurred and I had a recent correct previous interaction. Once it works any immediate retrial will also behavior correctly.
Solution:
I have since moved my timing/sound playing component within my C# app. The Arduino now signals the start of the timer, and then end of the timer with an immediate start to my event.

There is only a very slight chance that you meet the holdDuration >= 4000 condition in the while loop. Only when holdDuration will be exactly 4000 the while loop will be executed AND the subsequent test in the if statement will pass.
The serial print commands can easily take long enough to have millis() jump from a number less than 4000 to a number higher than 4000 in a single pass of the while loop.
To prove this assumption, increase the while test to holdDuration <= 4100 and see if the intermittent effect goes away.


text:
How can I control Servo motor properly by using TimerOne and ServoTimer2 Library?
In this project I want smooth rotation of the Servo(Pin (D10) periodically where period time select by a potentiometer(actually I will use pressure sensor in this pin now it is unavailable to me so I am using g potentiometer).The Time period controlled by by a potentiometer position(two) change at Pin A0.Two Led(blue & red) (D7,D9)(in this pin I will use two valve controller servo) blink with same period and other yellow Led blink same period but oppositely.All working except Servo which rotation is not smooth .It's rotation sometime maintain proper period and sometime unnecessarily stop.Before I tried TimerOne and Servo Library but they are creating some conflict and not uploaded to Board.I am using Arduino Uno Board.What change should I do either in Circuit or in Code.I am new in this field.Any kind help would be grateful for me thank you.And my code is
#include <TimerOne.h>
#include "ServoTimer2.h"
const int potPin = A0;
const int bluePin =7;
const int redPin =8;
const int whitePin = 9;
const int yellowPin = 11;
const int myServoPin = 10;
ServoTimer2 myServo;
int angle;
int speed;
int potVal;
int breathPress;
int lowPress=12;
int upPress=24;
int lowCount=0;
int upCount =0 ;
int time1;
int time2;
int timeDiff;
int temp;
int potPin1 = A2;
int breathRatio;
int ratioVal;
void setup() {
  pinMode(potPin,INPUT);
  pinMode(bluePin,OUTPUT);
  pinMode(redPin,OUTPUT);
  pinMode(potPin1,INPUT);
  pinMode(whitePin,OUTPUT);
  pinMode(yellowPin,OUTPUT);
  myServo.attach(10);

  Timer1.initialize(100000);
  Timer1.attachInterrupt(Blink);
  Serial.begin(9600);
 }

void loop() {
  breathRatio=analogRead(potPin1);
  ratioVal = map(breathRatio,0,1023,1,6);

  digitalWrite(bluePin,HIGH);
  digitalWrite(yellowPin,HIGH);
  digitalWrite(whitePin,LOW);
  myServo.write(90);

  delay(timeDiff);
  digitalWrite(bluePin,LOW);
  digitalWrite(yellowPin,LOW);
  digitalWrite(whitePin,HIGH);
  myServo.write(60);
  delay(timeDiff);

}

void Blink(){
  potVal = analogRead(potPin);
  breathPress = map(potVal,0,1023,0,30);
  Serial.print("Pressure=");
  Serial.println(breathPress);
  Serial.println(time1);
  Serial.println(time2);
  Serial.print("Time Difference :");
  Serial.println(timeDiff);
  if(breathPress<10){
  digitalWrite(redPin,LOW);
  }
  if(breathPress>27){
    digitalWrite(redPin,LOW);
  }
  else {
    digitalWrite(redPin,HIGH);
  }
  if ((breathPress - 10 )<= 0){
    lowCount = 1;
    upCount =0;
    time1 = millis();
  }
  if((breathPress - 27)>=0){
    lowCount = 0;
    upCount = 1;
    time2 = millis();
  }
  if(time1-time2 >= 0){
    timeDiff = time1-time2;
  }
  else{
    timeDiff = time2-time1;
  }

And output showing
13096
14994
Time Difference :1898
Pressure=15
13096
14994
Time Difference :1898
Pressure=15
13096
14994
Time Difference :1898
Pressure=15
13096
14994
Time Difference :1898
Pressure=15

your post looks like a book exploded ... you will wait a long time before someone spends their time reading that wall of words ... sentences have a space after a period ... related thoughts are grouped into paragraphs

If you used a "Blink Without Delay" style if statement and millis to handle the timing for both this and the leds then you could use the normal Servo library and your life would be much much much easier.

You copied your question text 2 times into the question. I removed the duplicated text for you

What you are claiming does not makes sense to me. In your code you are not moving the sensor smoothly. You are setting it to 60 and 90 degrees successively. You don't control the movement between these values. That's, what the servo does. It moves directly, where you tell it to move. You cannot control how the servo moves between two values, that you set. To move slower (you could call that smooth) between the values, you would need to set the inbetween values for the servo. So instead of going directly from 60 to 90, you would go in steps, from 60 to 61, to 62, ... to 89, to 90 degrees.
Also you are not controlling the servo with the Timer1 library, at least not directly. You measure a time difference with the library. This time difference is then the time, that the servo will stay in the current position, until it is moved again.

Note, that this
if((breathPress - 27)>=0)

is an over-complicated way of writing
if(breathPress >= 27)

by using for loop?actually I tried that but there is no motion of Servo.

Yes, for example with a for loop. We don't see your former code. Also your current question is rather ill stated. I understood about half of it. Please improve your question, so that it is more clear, what your problem is. If you already knew, that you need to use a for loop, why not asking about why your for loop code does not work?

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


text:
Pushbutton and switch case
I am developing a project for my college.
PROJECT OUTLINE:
There are 3 sensors (Temp., Accelerometer & Humidity) will read the respective parameters continuously. in between if I press 'PushButton1' for 2 seconds  the Arduino must enter into programming mode.
The programming mode has 6 Switch cases. Each case gets selected one after one on the even of 'PushButton1' gets pressed for short time.
Also if I press 'PushButton1' again for 2 seconds in Programming mode the Arduino should come out of the programming mode.
PROBLEM:
In my current sketch I have to press 'PushButton1' for 2 seconds in Programming Mode for 2 seconds to change the case. Also I don't understand how to get out of the Switch Case loop.
The sketch is attached with this topic.
const int btn = 2;
const int ledPin =  13;
int selector = 0;
boolean  volatile wait = false;
const unsigned long event=2000;
unsigned long a=0;
unsigned long b=0;
unsigned long c=0;
void setup()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(btn, INPUT);
attachInterrupt(digitalPinToInterrupt(btn),decoder,CHANGE);
}

void loop()
{
  while(wait) {  }
  if (digitalRead(btn) == LOW) {
    a = millis();
  }
  else
  {
    b = millis();
    c=b-a;
    Serial.println(c);
        if (c>=event)
            {
              doSwitchStatement();
              selector++;
              if (selector >6)
                  {
                  selector = 0;
                  delay(500);
                  }
            }
  }
  wait = true;
  interrupts();

}

void decoder()
{
  noInterrupts();
  wait = false;
}

void doSwitchStatement()
{
  switch(selector)
  {
  case 0:
    Serial.println("Case 0");
    break;

  case 1:
    Serial.println("Case 1");
    break;

  case 2:
   Serial.println("Case 2");
    break;

  case 3:
   Serial.println("Case 3");
     break;

  case 4:
   Serial.println("Case 4");
    break;

  case 5:
  Serial.println("Case 5");
    break;

  case 6:
  Serial.println("Case 6");
    break;

  }
}

Using a blocking while statement on your loop and an interrupt is an ugly way to accomplish what you are trying to do. Your implementation will freeze the app in that while(wait) loop except when the button state changes, meaning you can't do anything else but respond to button state changes.

Where is your code to read and display the sensor values?

I would do it as a simple state without the blocking while
define two bools
bool buttonPress = false;
bool inMenu = false;

and add it to the loop.To differentiate between different press lengths you need to define them. There is nothing like an "automatic" short press recognition. Also use variables which are "speaking" making it easier to read code for others.
const unsigned long buttonPressLong = 2000;  // 2 seconds
const unsigned long buttonPressShort = 250;  // 0.25 secondis feasable
const unsigned long buttonPressDebounce = 50;
// debouncing for too short presse Thanks Edgar Bonet
unsigned long buttonPressStart = 0;

The program below does what you want (tested on my uno test lab). As Edgar Bonet commented before you should also debounce the button (look it up in WiKi) to exclude unwanted effects The times I use are practical on my hardware, so you could play around by looking at the serial monitor.
const int btn = 2;
const int ledPin =  13;
int selector = 0;
const unsigned long buttonPressLong = 2000;  // 2 seconds
const unsigned long buttonPressShort = 250;  // 0.25 secondis feasable
const unsigned long buttonPressDebounce = 50;  // debouncing for too short presse Thanks Edgar Bonet
unsigned long buttonPressStart = 0;

bool buttonPress = false;
bool inMenu = false;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(btn, INPUT);
  }

void loop() {
  if (digitalRead(btn) == LOW && !buttonPress ) {
    buttonPressStart = millis();
    buttonPress = true;
  }
  // The routine is only triggered if a previous pressing took place, otherwise it's ignored
  else if (digitalRead(btn) == HIGH && buttonPress) {
    if (millis() - buttonPressStart > buttonPressLong && millis() - buttonPressStart > buttonPressDebounce && inMenu) {
      Serial.print("Long press: ");
      Serial.println(millis() - buttonPressStart);
      buttonPress = false;
      inMenu = false;
    }
    if (millis() - buttonPressStart < buttonPressShort && millis() - buttonPressStart > buttonPressDebounce && !inMenu) {
      Serial.print("First short press ");
      inMenu = true;
    }
    if (millis() - buttonPressStart < buttonPressShort && millis() - buttonPressStart > buttonPressDebounce && inMenu) {
      Serial.print("Short press: ");
      Serial.println(millis() - buttonPressStart);
      doSwitchStatement();
      selector++;
      if (selector > 6) {
        selector = 0;
        delay(500);
      }
      buttonPress = false;
    }
  }
  // Here you could do other stuff as it is non blocking
}
doSwitchStatement(){...}// Stays the same as yours

Look at the code used as it is non blocking (of course there is room for improvement) but as a starter for your further experiments ...

Thanks a lot for such a great help. I am putting my entire Project theme again.

Please mark as accepted and thanks for the feedback


text:
Sending wireless data over with xbee s1
I am following this tutorial to learn about Arduino wireless communication. I have 2 Arduino unos with Xbee S1s sitting on Xbee Pro shields.
I've programmed the Xbee S1s by screening into the /dev/tty/* and configuring them with: +++, ATID1234, ATMY1000 (ATMY1001), ATDL1001 (ATDL1000) and ATWR. I've double checked the values to ensure they are correct.
So i've created a super simple Sender and Receiver package:
Sender.ino
int counter = 0;

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

void loop() {
  Serial.println(counter++);
  delay(1000);
}

Receiver.ino:
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("Looping");
  while (Serial.available() == 0);    // wait
  int counter = Serial.parseInt();
  Serial.println(counter);
  Serial.flush();
  delay(500);
}

So first of all, when I upload my program to my arduino, I make sure that the S1s are not attached to the Pro shields which is attached to the unos.
When both of my unos are powered, I see a red light blinking but no indication of "busy blinking" which is supposed to happen when two XBee S1s are connected to the same channel. I am currently seeing a consistent blinking at about 1 second frequency.
Can someone tell me why I am only able to see "Looping" in my Serial monitor on my receiver?

So I was just hacking around and I finally figured out what went wrong! Apparently, there's a switch "XBEE/USB" that needs to be switched to XBEE for BOTH shields. After that, everything works as planned

Please add that as an answer, and accept your own question, if you solved it.

blah reported:

So I was just hacking around and I finally figured out what went wrong! Apparently, there's a switch "XBEE/USB" that needs to be switched to XBEE for BOTH shields. After that, everything works as planned.

Can someone vote this up please to remove it from the unanswered queue?


text:
ATmega32u4 bootloader
Hey all this would be my first encounter needing to burn the Arduino IDE bootloader onto a blank ATMega32u4 that I bought from Digikey.
What all do I need to buy in order to program the bootloader for that chip? In the manual for the 32u4 it says it comes with a bootloader but I'm guessing its not the arduino bootloader?
Is the pinout for the ISP all that I would need in order to upload the Arduino bootloader?
I've seen this post:

but I wont be using the through-hole design.. its going to be the surface mount SMD kind so i wouldn't be able to put that on a breadboard.
So would it be as simple as breaking out the ISP pins on the 32u4 and just hooking those up to a Arduino Duemilanove board even if its not the same ATmega chip (As in copying the atmega32u4 arduino to the Duemilanove and then transferring that to the 32u4?)?

Are you planning to connect to it via USB?

The ATmega32U4 already comes programmed with a bootloader that allows programming via USB; once you've added the basic hardware for a USB connection you should be able to use AVRDUDE, FLIP, etc. to upload firmware to the device.
Having said that, putting an ISP connection as per AVR042 is highly recommended regardless.

I know I'm late here, but I'm very interested as to how exactly I would add this "basic hardware"?


text:
Replacing stock String.cpp with smaller version
Hey all I am wondering if it's possible to modify the WString.cpp file to only include the commands that I need for my project since that file is so large.
I am using a Digispark arduino that is Attiny85 which only has about 6k flash memory after bootloader.
Needless to say I am almost out of flash memory and I still need to do a few things.
I am reading from a serial port (in this case, using DigiCDC for a virtual serial port).
How can I overwrite the default Strings class that looks like its built in to the IDE with my own modified String class so I can get a smaller footprint?
Thanks!

Write your own core.

Just don't use String - which is recommended regardless.

@Majenko What can I use in place of String if I have the serial.read() data coming in as 255,255,255 which in itself crashes the ATTiny. I can only send it 255,2 without it crashing.

Character arrays. Pure C. You might like to read these: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/ https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

If you're crashing trying to read serial data, it isn't a flash-capacity problem; you're running out RAM. Using char-arrays instead of Strings will probably help there, too, but you'll need to look at your RAM memory allocations, too. Lots of globals, f/ex, will occupy memory that might otherwise be available for temporary use. Do they really need to occupy space for the entire run duration? If not, allocate ones that don't as local memory in the functions to that do use them; it gets returned when the function exits.

You can make a copy of WString.cpp, edit it, and add it to your project.
Note however that:

You will have to define every method that you use. Otherwise the
linker will pull WString.o from the Arduino core library in order to
resolve the missing methods, and then it will complain that some
methods have been defined twice.
Just pruning WString.cpp from unused methods will not help: the
linker is already doing that for you.
To know which functions/methods of your program are taking too much
flash, you can use the command
avr-nm --size-sort -Crtd program.elf.
I second Majenko in recommending against String objects if possible.


text:
Adafruit_NeoPixel define pin for different setups
I am looking for a way of defining multiple pins for my RGB strips. Currently the defined variable is set with the pin within it. This works just fine if I only had one RGB strip connected to the Arduino but I have 4 so I will need to define.
I currently run this code here:
#include <Adafruit_NeoPixel.h>
#include <avr/power.h>

int rgb1 = 18;
int rgb2 = 17;
int LEDs = 11;
int ledFadeTime = 5;

Adafruit_NeoPixel strip1 = Adafruit_NeoPixel(LEDs, rgb1, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip2 = Adafruit_NeoPixel(LEDs, rgb2, NEO_GRB + NEO_KHZ800);

void setup() {
  strip1.begin();
  strip1.show(); // Initialize all pixels to 'off'
  strip2.begin();
  strip2.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOutStrip1(0, 0, 255, ledFadeTime); // Blue
  rgbFadeInAndOutStrip2(255, 0, 0, ledFadeTime); // red
}

void rgbFadeInAndOutStrip1(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip1.numPixels(); i++) {
        strip1.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip1.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip1.numPixels(); i++) {
        strip1.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip1.show();
     delay(wait);
  };
};

void rgbFadeInAndOutStrip2(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip2.numPixels(); i++) {
        strip2.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip2.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip2.numPixels(); i++) {
        strip2.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip2.show();
     delay(wait);
  };
};

Which works when trying out just one out of the 2. But when the LEDs fade out it has a pause (i still see a hint of blue on the strip). If i comment all the code out for the second strip2 and run that, it pulses just fine without the hint of blue or the delay to start bright again.
What could I be doing incorrectly?

The WS2812 is very sensitive to timing on the data line, so your use of delay() function, which blocks, might be preventing the data stream from updating fast enough. You need need to do this in the "BlinkWithoutDelay" style or eventually you'll run into the situation where the WS2812 does random things because it's waiting for an update, which you've blocked with "delay" - see video... https://www.youtube.com/watch?v=3VZgaJBrZD8

The “hint of blue on the strip” is a consequence of your second loop in rgbFadeInAndOutStrip1() ending with the test b > 0.  Because of that, the last strip1.setPixelColor() call sets the color to (0,0,1), a faint blue, instead of (0,0,0), off.  Here is some revised code that works ok:
#include <Adafruit_NeoPixel.h>
#include <avr/power.h>
enum { rgbPin1=8, rgbPin2=7, LEDcount=11, ledFadeTime=5};

Adafruit_NeoPixel strip1 = Adafruit_NeoPixel(LEDcount, rgbPin1);
Adafruit_NeoPixel strip2 = Adafruit_NeoPixel(LEDcount, rgbPin2);

void setup() {
  strip1.begin();
  strip1.show(); // Initialize all pixels to 'off'
  strip2.begin();
  strip2.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOutStrip1(0, 0, 255, ledFadeTime); // Blue
  rgbFadeInAndOutStrip2(255, 0, 0, ledFadeTime); // red
}

void fadeStrip(Adafruit_NeoPixel *strip, int bval, int bdir, uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b=0; b<255; ++b) {
    bval += bdir;
    for(uint8_t i=0; i<strip->numPixels(); ++i) {
      strip->setPixelColor(i, red * bval/255, green * bval/255, blue * bval/255);
    }
    strip->show();
    delay(wait);
  }
}

void rgbFadeInAndOutStrip1(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  fadeStrip(&strip1, -1, 1,   red, green, blue, wait);
  fadeStrip(&strip1, 255, -1, red, green, blue, wait);
}

void rgbFadeInAndOutStrip2(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  fadeStrip(&strip2, -1, 1,   red, green, blue, wait);
  fadeStrip(&strip2, 255, -1, red, green, blue, wait);
}

Note, since I ran tests on an Uno rather than a Leonardo, I attached pixel strings to pins 7 and 8 rather than 17 and 18.  I used enum to define constants, rather than declaring constants as variables, and factored some common code into functions rather than reduplicating it.
Following is another program (which I call neocycle6) you can use to test two strips.  Note, it only counts colors down to 1 rather than 0 because I like the effect of leftover pixels glowing faintly.  Also note: the round boards I used have only 7 LEDs each, so I set PixelCount to 7, not 11; this uses pins 7 and 8, not 17 and 18; I don't drive the brightness beyond 77 since the LEDs are so bright anyway; and it doesn't have an
#include <avr/power.h> statement, which you can add if needed.
// Drive 2 sets of 7 ea. WS2812 NeoPixels through sets of colors.
// jw 11 September 2015
#include <Adafruit_NeoPixel.h>

// Select pin# connected to NeoPixels strand, and number of NeoPixels.
enum { PixelPinA=7, PixelPinB=8, PixelCount=7 };
// Create a NeoPixels device structure
Adafruit_NeoPixel pixelA = Adafruit_NeoPixel(PixelCount, PixelPinA);
Adafruit_NeoPixel pixelB = Adafruit_NeoPixel(PixelCount, PixelPinB);

void setup() {
  byte i, j=0;
  pixelA.begin();               // Init. NeoPixel data structure
  pixelB.begin();               // Init. NeoPixel data structure
}

uint8_t c=1, d=1, p=0, v=1;
void loop() {
  c += d;
  if (c>76)
    d = -1;                     // Go down when done going up
  else {
    if (c<2) {                  // Set up for next pixel
      d = 1; p = (p+1)%PixelCount;
      if (!p) ++v;              // Rotate the weights to next color
    }
  }

  pixelA.setPixelColor(p, c*(v&1), c*((v&2)/2), c*((v&4)/4));
  pixelB.setPixelColor(p, c*((v&2)/2), c*(v&1), c*((v&4)/4));
  pixelA.show();               // Show updated colors
  pixelB.show();               // Show updated colors
  delay(9 + 300/c);            // Ramp small numbers more slowly
}


text:
External power supply?
I have a project where I'm looking to power 120 RGB LEDs in a strip (WS2812B).
Obviously an Arduino Micro cannot supply this amount of current so I'm looking to use an external 5V/4A switching power supply (wall-wart) to power the LED's as well as the Arduino.
My question is, can I just split the power from the wall-wart providing 5v_reg directly to the 5V pin on the Arduino Micro and 5v_reg to the LEDs Vss?
It it necessary to use extra bypass capacitors in this case?

My question is, can I just split the power from the wall-wart providing 5v_reg directly to the 5V pin on the Arduino Micro and 5v_reg to the LEDs Vss?

Yes. As long as it is a clean regulated 5V supply.

It it necessary to use extra bypass capacitors in this case?

No.

Great. Are there specified limits as to what voltage range is acceptable to apply to the 5V pin, assuming the regulated supply is non ideal?

The datasheet for the ATmega32U4 seems to suggest VCC = 2.7V to 5.5V although I'm not sure on this.

That is correct. However at lower voltages you run into instability with the clock being too fast. Best stick to 4.5V - 5.5V.

Great, thank you for the practical answer.

authors: Павел Князькин


text:
I am making my blinds automatic, but I don't want to use a delay
I am trying to make it so I can pull the time so that they open at 8 am and close at 10 pm. The loop is already set up to open and close the blinds completely.
#include <CheapStepper.h>

CheapStepper stepper;

boolean moveClockwise = true;
int motorPostion = 10;
boolean up = true;
boolean down = false;

void setup() {
  Serial.begin (9600);
  Serial.println ("Ready to start moving");
}

void loop() {

    for (int i = 1; i < 16384; i++)
      {
      stepper.step (moveClockwise);
      Serial.println (i);
      int nStep = stepper.getStep();

      if (nStep%4096==0) {
        Serial.println ("Moved full rotation Clockwise");
        }
     }

    for (int i = 16384; i > 0; i--)
      {
      stepper.step (!moveClockwise);
      Serial.println (i);
      int nStep = stepper.getStep();

      if (nStep%4096==0) {
        Serial.println ("Moved full rotation Counter Clockwise");
      }
    }
  }

what is your question? ... please format all of your code, not just a part of your code.

So, are you asking about how to write non-blocking code (Then look at the BlinkWithoutDelay example and tutorials about the millis() function), or are you asking about how to do things at a specific time of the day (In that case you need an RTC)?


text:
DS2413 One Wire IC read and store the addresses of individual IC's
Hy,
Here I using 10 DS2413 to control gpios, it works very well with arduino ,I read the 10 ic address and store it in a 2D array, I want to control the individual IC using their address .Here all works well. My problem is the Ic address are not store in arrange wise manner. For ex, I have 10 IC's, Each IC's have unique address, The address of first IC1 is store in arr1, address of ic2 is arr2 and address of ic3 is store in arr3..... what i need is If i Swap the IC1 and IC2 the address of IC2 is store in arr1 and IC1 address is store in arr2.

Can you show us the sketch you're using?

1-wire has no concept of bus position, only the logical order of the ROM addresses.

The OneWire system has no concept of the arrangement of the bus. All it knows is the addresses, and it always searches for those addresses in a pre-defined order.
No matter what arrangement you have on the bus the devices will always be found in the same order.
You can think of it akin to a teacher taking the register in class. They call out the names in alphabetical order and the pupils answer (if they are there). All it tells the teacher is who is there and who isn't. It doesn't give them any information about where in the class the pupil is sat.
You can read more about how the address searching is done here.


text:
Sending >255 bytes array to arduino
I am trying to send a 50x50 bitmap bytearray from my python client to arduino where it should be displayed on a screen.
I need to receive 350 bytes to have the data to show the bitmap but as soon as i initialise the array with > 255 elements it does weird things (i guess because of the memory):
When initialising the array with size 254 it does the expected:

Transmission of 350 completed in 2.805466s (arduino) Received: 253
  elements

with size 350 I only get

"Received: 93 elements"

How can i split the bytes i receive with the available memory and then build the bitmap accordingly or what is a better way to do it? I would like to have it transmitted via serial rather than building the qrcode in arduino (as i couldn't get the libraries required working in my setup).
My python client does basically this:
for element in qrCodeBytes:
    countElementsSent+=1
    ser.write(element)
    print("Sending " + str(element))
ser.write("$".encode()) #stop char

My arduino code is based on the popular Serial input basics guide
https://forum.arduino.cc/index.php?topic=288234.0
 const byte numChars = 254;
 byte receivedChars[numChars]; // an array to store the received data

boolean newData = false;

void setup() {
 Serial.begin(114000);
 Serial.setTimeout(10000);
 Serial.println("<Arduino is ready>");
 display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3D (for the 128x64)
 display.clearDisplay();
 display.display();
}

void loop() {
 recvWithEndMarker();
 showNewData();
}

void recvWithEndMarker() {
 static byte ndx = 0;
 char endMarker = '$';
 char rc;

 // if (Serial.available() > 0) {
   while (Serial.available() > 0 && newData == false) {
     rc = Serial.read();
     if (rc != endMarker) {
       receivedChars[ndx] = rc;
       ndx++;
       if (ndx >= numChars) {
         ndx = numChars - 1;
       }
     }
     else {
     receivedChars[ndx] = '$'; // terminate the string
     Serial.println("Received: " + String(ndx) + " elements");
     ndx = 0;
     newData = true;
     }
   }
}

void showNewData() {
 if (newData == true) {
 Serial.println("This just in ... ");
 display.clearDisplay();
 drawBitMap(receivedChars,50,50,0);
 display.display();
 newData = false;
 }
}

void drawBitMap(unsigned char *img, int width, int height, int position){
  if (position ==0){
   display.drawBitmap(128/2-(width/2), 64/2-(height/2), img, width, height, 1);
  } else if (position == 1){
   display.drawBitmap(128-62,1, img, width, height, 1);
  } else if (position == 2){
   display.drawBitmap(0,5, img, width, height, 1);
  }
}

what does this mean ?  it does weird things

Sorry i will clarify in the post,
if i initialise the array with size 254 it does the expected:
Transmission of 350 completed in 2.805466s
(arduino) Received: 253 elements
if i initialise the array with 350 i get "Received: 93 elements"

const byte numChars = 350;? max byte is 255. and you have ndx as byte too.

Thanks for pointing out the byte issue. I found out that the library i am using from adafruit does only support bitmap data located in program memory using the PROGMEM directive. I assume there is not much i can do now with this, i'll have to look for other means of creating this qrcode

You use type byte for the variable ndx. Type byte is 8 bits, so the max value is 255. The variable ndx is incremented and after 255 it continues counting from 0.


text:
Problems with NodeMCU and Relay
I've connected the MCU to a cheap chinese 24/12v to 5v car phone charger and hooked some wires to a relay.When I try to program doesn't matter if the pin is set to high or low , as soon as I touch the "IN" wire from the relay into any of the selected pins, the relay auto actives.
here is the schematic
The charger input is hooked to a 12V drill battery for tests and the output to arduino is an usb port that I soldered wires to it's respective poles.
USB from Chinese charger Positive pole ------- NodeMcu Vin
USB from Chinese charger Negative pole ------- NodeMcu GND
USB from Chinese charger Positive pole ------- Relay   VCC
Relay Ground --------------------------------- NodeMcu Gnd
Relay DataPin -------------------------------- NodeMcu D0 or D1

And here's the code:
int port = D0;
int portB = D1;

void setup() {
Serial.begin(115200);
pinMode(port,OUTPUT);
pinMode(portB,OUTPUT);

digitalWrite(port,HIGH);
digitalWrite(portB,LOW);

}

void loop() {

}

But the result is that the relay will always be on activated ( IN pin = Low ) even connected to D0 that is high... Any ideas ?

Sorry, fixed , " it " was referring to the relay data pin

you probably have one side of the relay connected to the positive voltage .... connecting the other side of the relay to a pin overloads the pin circuitry and activates the relay

the relay might want more than 3.3v to indicate high, try feeding it 5v to the relay data pin and see if it activates. if so, it's designed for 5v arduino devices, not 3.3v. FWIW, i've bought several kinds and this is common amoung single-relay modules, bit for whatever reason, all the few kinds of 2-relay modules i've bought work fine with my nodeMCUs.

note that you can also use a logic level mosfet's S-D pins to connect the relay data line to ground, and use a 100k resisistor from 5v to relay data in to pull it up; when you set the pin high, it turns on the gate and pulls the 5v signal down ground. i like the irlz44n for most 3.3v applications.

some relays hold the coil at LOW signal and release at HIGH

I will try  the  options above then I get back with the results and I may not be able to get a irlz44n , and yes my relay holds on low, but even plugging D0 that is set to high, it holds the coil like if it is low

Oh and the charger output is 5V and its connected to the Mcu's Vin and the relay vcc

than it is clear that 3.3 V is not HIGH signal for the relay working at 5 V

Does your nodemcu directly feed the relay?
If so, 3.3v (nodemcu output high level) is not enough to activate it.
I would use a transistor like a s8050 to Power it (do not forget the freewheel diode on the relay coil)

You are right, I've completely forgot that the Mcu's digital is 3.3v instead of 5v and it wasn't able to properly control the relay, thank you very much.

@LucasMedeiros, it was in comments by dandavis

you can try to feed the esp 3.6v or 3.7v instead of 3.3v; should work fine (within/cose to ESP spec) and might be enough to trigger the relay on HIGH, since VCC (and thus D1@HIGH) will be raised.


text:
APA106 random color when power applied
The APA106 RGB LED is usually blue when 5VDC is applied. Sometimes it is a random color when turning the power supply on and off. How to keep it a consistent color when power is applied?
Normal:

Sometimes:

It’s for an Arduino project, I’ve just isolated the problem to the LED. Dozens of these exhibit this behaviour. The PCB board in the pictures is just a breadboard power supply.
Update: DIN to GND still exhibits the same behaviour.

Here is a demo of the problem. 90% of the time at power up the LEDs is blue, but occasionally the color is random like pink or white.
YouTube link to a 38s clip of the problem manifesting
Update: At Robert's suggestion, I modified the V-USB bootloader to send the control bits and timings to immediately turn off the APA106 LED. There is still an extremely brief blue pulse (or random color) because power applied to the LED is always faster than any CPU process. It's not perfect, but better.

Did you apply a RESET pulse/code (DIN to GND)? Might need to be longer than 50us.

Leaving the DIN pin floating will give undetermined results. Try connecting the DIN pin to ground.

@Gerben Great thought, but DIN to GND still exhibits this behaviour. Also in my Adruino project the DIN pin is connected to the GPIO and not left floating. I’ve isolated the issue to the LED. Thx.

@MikaelPatel These LEDs are straight out of the manufacturer’s packaging and 90% of the time are blue when they are powered. I’ve removed all Ardruino circuity to demonstrate this issue.

Wire it to the MCU such that power is first applied to the LED under control of the sketch when the sketch is prepared to immediately set the initial color you want. The time taken to accomplish the (power up, set initial color) will have to be less than the eye's ability to perceive the possible color glitch (which, being relatively slow compared to the Arduino, it should be pretty easy to do).
Update:

There is still an extremely brief blue pulse

That remaining delay is probably the IDE's reset-pulse duration plus the Arduino board's R-C delay on the reset pin. It's probably the best you can do without a lot of hardware (e.g. a switch on every R/G/B pin, designed to power-up "off".)

Thanks, Robert. In lieu of anything else I can do, I modified the bootloader to send the control bits to turn off the APA106 LED. There is still an extremely brief blue pulse because the power is always faster than any CPU process. The random color still manifests, but it's brief. Thanks for the suggestion.


text:
Running code through functions
I am making a led cube where sequential lighting is used. So basically i need to repeat my commands for a given time. After much reasearch nothing turned up so decided to ask here.

Here is the code i need to reproduce in a working format
void loop(){
  runfor(500){
    DigitalWrite(5,HIGH);   //this is the command to be executed in other
                            //function
  }
}
void runfor(uint32_t duration){
  int timer = millis();
  while((millis()-timer)<=duration){
  //DigitalWrite(5,HIGH); will execute here
  }
}

So basically DigitalWrite(or any other code if used) will be repeatedly executed for 500 milliseconds

EDIT due to misunderstanding the question.
If you want to be able to pass instructions into a function, you will have to have a function for each set of instructions (that is, you cannot pass arbitrary statements as a function parameter), and then you adjust your runfor() function to accept a pointer-to-a-function parameter.
typedef void (*callback_function)(void);  // defining the type here makes the code easier to read when used in other places.

void runfor(uint32_t duration, callback_function patternCode){
  uint32_t timer = millis();
  while ((millis()-timer)<=duration) {
    //get these commands from caller function
    patternCode();
  }
}

void pattern1() {
  // Light pattern #1
}

void pattern2() {
  // Light pattern #2
}

void setup() {
  // Setup code
}

void loop() {
  runfor(1000, pattern1);
  runfor(2000, pattern2);
}

ORIGINAL ANSWER
Your starting pseudo-code is nearly there.
void runfor(uint32_t duration){
  uint32_t timer = millis();
  while ((millis()-timer)<=duration) {
    //get these commands from caller function
  }
}

Changes I made:

change int to uint32_t to accommodate all possible values of millis().
change for keyword to while, which is the correct keyword for the loop type you want.
added semicolon after your timer assignment, per C syntax.

Im sorry, I'll edit my post. Thanks for informing!

I’m not sure I understand. What kind of answer are you looking for?

jose can u c  I mean a reform to the code so it basically 'accepts' function from say loop() and runs the commands in the ensuing { } braces. Also can you please post comments on my questions to the question comments so that others can understand?

Your timer variable wants to be uint32_t.

@A.Shetye The code sample provided in the answer does what you are asking. Your initial example in the question was very close to correct already!

I suppose I am misunderstood. The // part here is not any sample code. So if i do runfor(50){ <place code here} from say loop(), it should run the given code for 50 milliseconds. So i suppose my current code cant do that?

I changed my answer, now that I understand you.


text:
Lipo Battery level display using nodemcu
I'm designing a connected collar for pets for a project, for this I am using a nodemcu on ESP8266 powered by a Lipo battery I'm guessing around 1000mAh of capacity is enough for a respectable autonomy (? any advices).
Lipo model : https://www.lipolbattery.com/lithium%20polymer%20battery.html
In order to charge the battery I have found this USB LiPo charger (https://learn.sparkfun.com/tutorials/lipo-usb-charger-hookup-guide/all), my first question is: Is it still usable for higher capacity LiPo batteries (1400mA)?
Also I would like to display the battery level via and RGB LED (example: green is for battery FULL battery and RED for LOW battery level in need of charging) is there any way to do this? Thank you

Measuring LiPo capacity is tricky. I would suggest investing in a "Fuel Gauge" chip to measure it for you. (Eg: https://www.sparkfun.com/products/10617)

I found his project any suggestions?
https://www.teachmemicro.com/arduino-lipo-battery-monitor/

Answering the second question "Also I would like to display the battery level...?" (next time, please open a new question for that):
To measure the module voltage level (a.k.a. VCC) of a NodeMCU (which is just a board containing an ESP8266 chip) programmed in Arduino IDE (which I assume given that you ask on the arduino stackexchange), this here applies:

To read VCC voltage, use ESP.getVcc() and ADC pin must be kept unconnected.
  Additionally, the following line has to be added to the sketch:
ADC_MODE(ADC_VCC);
This line has to appear outside of any functions, for instance right after the
  #include lines of your sketch.

Source: ESP8266 Arduino reference
So you could just drive a red and a green LED (don't forget the mandatory current limiting resistor) from any other two pins of your NodeMCU. Then switch them in your sketch if VCC falls below 3.2V (you may need to experiment with that because of measurement tolerances; a sketch to start with that would be here.

It is still usable for higher capacities. I recommend you tp4056 and some step up converter.
You can use resistor divider (that drops safely voltage to nodemcu 3.3v) and connect its output to an analog pin of your nodemcu. Values of resistors must be high, like 10k.
You can simply connect your diode to nodemcu and code if voltage is less than 3.2v let the red diode turn on, when above 3.8v let the green diode turn on


text:
Print uint8_t in arduino
I'm learning esp8266 using arduino IDE. I'm still a beginner in development board programming. What I've been trying to do is use a crypto library. I am trying out AES in arduino and I chose that library because it seemed complete, and was one of the only library that used ECB. My problem is whilst calling the encrypt function, I get confused with the output.
This is what I've done so far.
#include <Crypto.h>
#include <AES.h>
#include <string.h>

AESSmall128 aes128;

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

  uint8_t key = (uint8_t)1234567654321234;

    aes128.setKey(&key, 16);

    uint8_t output = 0;

    Serial.println("before");
    Serial.print(output);

      uint8_t input = (uint8_t)9164567654321234;

    aes128.encryptBlock(&output, &input);
    Serial.println("after");
    Serial.print(output);

}

void loop()
{
}

When I print output it returns 252. What is 252? Why only 252? It seems really short looking at it. Why doesn't it output strings?

Have you seen the example? https://github.com/rweather/arduinolibs/blob/master/libraries/Crypto/examples/TestAESSmall/TestAESSmall.ino

Hey. I've tried the examples. They don't output any results from the encryption/ decryption. The test examples are for "performance checks". I've got this question done, look at Jose's answer. Thank you.

uint8_t is an Unsigned 8-bit Integer, and so the range of values it can represent are 0 to 255.
When you typecast your long/large values to uint8_t, you basically only show the least-significant 8-bits.
However, the decryptBlock() and encryptBlock() functions expect an array of bytes, not a single byte.
The library you link to notes, right in the linked position, that the output and input parameters must be at least blockSize() bytes in length. Referencing blockSize(), it notes that this function always returns 16. So you need to pass an array of uint8_ts of at least 16 length.
When you define your variables for the key, plaintext, and ciphertext, you need to not define then as a single byte type, but as an array of bytes:
uint8_t[16] key =    {1,2,3,4,5,6,7,6,5,4,3,2,1,2,3,4};  // This is not a good key, btw
uint8_t[16] output = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
uint8_t[16] input =  {9,1,6,4,5,6,7,6,5,4,3,2,1,2,3,4};

(When passing an array, you don't need to dereference the variable, so call aes128.setKey(key, 16);, etc. Omit the &)
Each of the 16 bytes can have a value in the range 0 to 255. They do not have to be limited to single-digit numbers; I just copied/translated what you wrote to demonstrate the example. You could set your key in this way:
uint8_t[16] key =    {66,127,164,72,68,158,148,255,23,36,226,192,198,248,251,221};

You can also refer to bytes with a 2-digit hexadecimal representation:
uint8_t[16] key =    {0xa6,0x09,0x81,0xc5,0xb8,0xf6,0x9a,0x33,0x75,0x24,0xff,0x79,0xd3,0x48,0x4f,0x1d);

UPDATE to address strings
A C-style string is a sequence of bytes, with type char to indicate ASCII data, though any byte-wide type could work in theory. The sequence of bytes ends with a value of 0 (i.e., 0x00, not the ASCII character '0'), so you must remember that the termination byte takes up a byte of memory.
To initialize your key with a string:
const unsigned char[17] key = "helloareyouarehi"; // 16 characters, and 1 byte termination means 17 total bytes reserved in memory.

I have not investigated how the crypto library you are using handles C-style strings, so let's assume it does not acknowledge them at all, and we will have to null-terminate our strings ourselves.
char[17] output = {0}; // Initialized to all zeros
char[17] input = "iwanttoencryptme";

aes128.encryptBlock(output, input);
output[16] = 0x00; // Just to be safe, put the null terminator in the last slot.

Serial.print(output);

If the encryptBlock() function only changes 16 bytes in the output array, then the 17th (zero) could remain from the initialization, but not knowing whether the function preserves strings, it is better to be safe than sorry.

Hello @jose, thanks so much for replying. Before I continue, yes I do know it's not a good key, I'm just trying out the library for fun. I have a better understanding now after you explained that it represent values between 0-255. Now my question would be, do those numbers represent ASCII values?

ASCII values are bytes, but they typically range only from 0 to 128, and even smaller for printable ASCII. If you want to start working with strings instead of arrays of numbers, you have to take extra care when reading and writing the string data.

Okay, lets say I wanted my key to be "helloareyouarehi", how would that be represented as array of uint8_t? And to output the array of uint8_t?

Oh yea, isn't it meant to be uint8_t key [] =    {1,2,3,4,5,6,7,6,5,4,3,2,1,2,3,4};  syntax wise?

Array initialization can have explicit or implicit sizing. It's my preference to explicitly define the array size.

Okay Jose, Im testing it now. I will tell you in a few minutes how it goes.

I get an error:
error: invalid conversion from 'char*' to 'const uint8_t* {aka const unsigned char*}' [-fpermissive]

What statement triggers that error?

in the encrypt function, though i casted it to (uint8_t*) but now my output is 0⸮⸮⸮⸮X⸮,O⸮e⸮ unreadable characters.

I dont have enough rep, do you mind bringing this to chat? or maybe i can contact you personally?

Let us continue this discussion in chat.

The uint8_t is exactly 8bits wide, so it can hold values from 0 to 255. Your number however is about 54bits wide.
I think you should use the array.
Also numeric literals are usually int type, so even if you do have enough space for it, it gets wrong value. Something like uint64_t value = UINT64_C(1234567654321234); must be used


text:
Cannot run WiFi sketch on ESP-01
I can upload simple sketch on my ESP-01 like:
void setup() {
  Serial.begin(115200);
  Serial.println("Hello there");
}
void loop() {
  Serial.println("Hello from loop");
  delay(1000);
}

I also ran successfully the sample ESPWebServer -> HelloServer
But if just modify my sketch to include #include <ESP8266WiFi.h>
#include <ESP8266WiFi.h>

void setup() {
  Serial.begin(115200);
  Serial.println("Hello there");
}
void loop() {
  Serial.println("Hello from loop");
  delay(1000);
}

I got this result in the serial monitor:
  ets Jan  8 2013,rst cause:4, boot mode:(3,7)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

My ESP-01 is connected to my computer through FT232RL FTDI with the following cabling:

FTDI GND - GND
ESP TX - FTDI RX
ESP RX - FTDI TX
ESP VCC - VCC 3.3V
ESP GND - GND
ESP CH_PD - VCC
ESP GPIO2 - VCC
ESP GPI00 - GND to upload sketch, VCC to run sketch

Here is a picture of my cabling (the USB of both the TTL and power supply MB102 are connected to my laptop):

Also, regularly my sketch fails to load correctly:
-Sometimes it does not load at all and I get this after compilation before uploading starts:
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

- Sometimes it fails at the end of the upload:
Uploading 256064 bytes from C:\Users\20000263\AppData\Local\Temp\arduino_build_32221/ESP01-Basic.ino.bin to flash at 0x00000000
................................................................................ [ 31% ]
................................................................................ [ 63% ]
................................................................................ [ 95% ]
..........warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_DATA) failed
warning: espcomm_send_command: wrong direction/command: 0x01 0x03, expected 0x01 0x04
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

Any idea about what is wrong ?

FTDI adapters often don't provide enough current to run the power-hungry wifi features of the ESP8266. So as soon as you fire up wifi, you brownout the chip and cause it to reset.
Use a battery, a dedicated ESP8266 flasher, a 3.3v LDO, or something besides the on-board 3.3v connection the USB-Serial adapter provides.

I already have a separated power supply for the ESP8266 of this type: MB102 breadboard power supply module


text:
Different Arduino packages on Raspbian
I'm working on using my Raspberry Pi (Raspbian) to upload sketches. However, I'm not sure which package is appropriate for command line usage (like described here on Github).
It seems like sudo apt-get install arduino would install the whole IDE, not just the command line. It seems like arduino-core would be more fitted for this purpose. However, the repository has a note online to use a package called arduino-mk for a CLI, which is what I want. However, this concerns me in the repository's page:

This package will install a Makefile to allow for CLI programming of the Arduino platform.

(Emphasis mine)
What exactly does this mean? What are the differences between the three packages available?

I have not actually interacted with the debian packages, but If I'm reading this right, this how they are organized:
arduino: The whole java IDE and avr code libraries
arduino-core: the libraries and code that comes with arduino to be compiled for avr
arduino-mk: a makefile for compiling arduino code without the IDE (but no code)
The normal arduino package has a command line interface, but the code for this is (currently) very closely tied to the java GUI code and cannot be used without the whole thing being installed. To make using the raw atmel avr tools easier, the makefile is available; However, the makefile does not include all of the cpp libraries that come packaged with the arduino installation that a normal arduino sketch would reference (Arduino.h, Servo, SPI, etc). The arduino-core package exists to bring in all this supporting code.
I imagine it is done with these three packages so if you already have arduino installed, the makefile will not bring a second copy of all the libraries with it.
The makefile is a configuration for the gnu make software. There is some information on the specific usage of the arduino makefile on its github page here

Previous versions of arduino-mk had a dependency on arduino, which was everything, but with the split out of arduino-core, which both of the other packages now depend, arduino only includes the ide, everything else is in core so that you do not need the ide to develop, compile and load standard projects to your Arduino. I have only used the ide for less than 15 minutes And do all my work using vi and the command line. the makefile allows you to compile ino files with a make just by linking it into your project directory, it also has options for uploading using make.


text:
Is `millis()` affected by long ISRs?
I have a project that uses timers and interrupts frequently. A lot of CPU time is spent handling ISRs over an extended period of time.
Would this affect code inside the main loop that relies on the millis() function since a significant amount of time is spent processing the ISRs?

Also, anything based on millis() will also fail?
I think the (new softwarebased) servo library and maybe even softwareserial(?) may also get timing issues? Though I'm not sure if they're both based on that.

After some digging around in the core, it seems like Arduino updates millis() with a 8 bit timer: it uses overflow with a prescaler value of 64. In simpler terms, it has it set up so a certain piece of code (the ISR) is run approximately once per millisecond on a 16MHz system (and proportionately less frequently on slower clocked systems).
When that ISR is ran, it increments a variable that is used by the millis() function.
So, even if some non-interruptable code is being ran for a fraction of a millisecond, it won't matter since the bit for that interrupt vector will still remain set.
However, there is a problem when the ISR is ran less often than it should be triggered. This may be a result of using noInterrupts() for an extended period of time or when too many other interrupts are being ran and there is not enough CPU for all of the tasks. If a lot of the other ISRs have a higher interrupt priorities, it is possible that the code for the millis() may never be ran. In this case, you would have more serious issues than this, but it is something to keep in mind when you're writing code.
The general rule of thumb of ISRs still apply: keep it short!!!
Note: if you require extreme accuracy, the built in function isn't the best choice. A RTC is a good idea for long term time keeping.

I think you can have interrupts, interrupting other interrupts-routines (by calling sei() inside the ISR). But it's a slippery slope. E.g. memory overflows can occur a lot faster.

micros() appears to have the same issue, and in my test gave the same wrong time as millis().

The issue is not limited to ISRs. The write() function in Adafruit's TLC59711 library disables interrupts for possibly many milliseconds, causing my initial attempt to time this function using micros() to fail.

@UlrichStern, Tehee, adafruit makes you think their library is super fast, by pausing your "timing benchmark" ;D

@Paul, when timing Adafruit's library, the return value of micros() still increased enough that the runtime was not obviously wrong and I got fooled for a while.  :)  (Adafruit did not disable interrupts to fool me, I think, see my library's Wiki.)

Would this affect code inside the main loop that relies on the millis() function since a significant amount of time is spent processing the ISRs?

To put a figure on it for you ...

Frequency of the Timer 0 overflow ISR being called
The code called by the (default) Timer 0 overflow interrupt vector (TIM0_OVF_vect) is used by millis and micros to help return their results. Its purpose is to count Timer 0 overflows.
To get accurate results this ISR must not miss an overflow. The timer is configured to tick every 4 µs on a 16 MHz system (because of the prescaler of 64: 64 * 62.5 ns = 4000 ns) and overflow every 1.024 ms (1024 µs) - because it overflows after 256 ticks ( 4 µs * 256 = 1024 µs ).
Since there is only one overflow flag, if the ISR misses an overflow then both millis and micros will be out by 1.024 ms (or more, if it misses multiple overflows).
To be certain of catching that overflow, the ISR therefore has to be called within 1.024 ms (probably slightly less because of the time taken to enter the ISR, so say: 1 ms).

Interrupt priority
On the Atmega328P (such as used in the Arduino Uno) these are the interrupt vector priorities:
 1  Reset
 2  External Interrupt Request 0  (pin D2)          (INT0_vect)
 3  External Interrupt Request 1  (pin D3)          (INT1_vect)
 4  Pin Change Interrupt Request 0 (pins D8 to D13) (PCINT0_vect)
 5  Pin Change Interrupt Request 1 (pins A0 to A5)  (PCINT1_vect)
 6  Pin Change Interrupt Request 2 (pins D0 to D7)  (PCINT2_vect)
 7  Watchdog Time-out Interrupt                     (WDT_vect)
 8  Timer/Counter2 Compare Match A                  (TIMER2_COMPA_vect)
 9  Timer/Counter2 Compare Match B                  (TIMER2_COMPB_vect)
10  Timer/Counter2 Overflow                         (TIMER2_OVF_vect)
11  Timer/Counter1 Capture Event                    (TIMER1_CAPT_vect)
12  Timer/Counter1 Compare Match A                  (TIMER1_COMPA_vect)
13  Timer/Counter1 Compare Match B                  (TIMER1_COMPB_vect)
14  Timer/Counter1 Overflow                         (TIMER1_OVF_vect)
15  Timer/Counter0 Compare Match A                  (TIMER0_COMPA_vect)
16  Timer/Counter0 Compare Match B                  (TIMER0_COMPB_vect)
17  Timer/Counter0 Overflow                         (TIMER0_OVF_vect)
18  SPI Serial Transfer Complete                    (SPI_STC_vect)
19  USART Rx Complete                               (USART_RX_vect)
20  USART, Data Register Empty                      (USART_UDRE_vect)
21  USART, Tx Complete                              (USART_TX_vect)
22  ADC Conversion Complete                         (ADC_vect)
23  EEPROM Ready                                    (EE_READY_vect)
24  Analog Comparator                               (ANALOG_COMP_vect)
25  2-wire Serial Interface  (I2C)                  (TWI_vect)
26  Store Program Memory Ready                      (SPM_READY_vect)

You can see from that list that TIMER0_OVF_vect is number 17 on that list, so any earlier priority interrupt would take precedence, for example external interrupts, pin change interrupts, the other timers (however not SPI / Serial / ADC / I2C).
If an overflow had just happened then you would have practically 2 ms of grace (because you have 1 ms before the next and then another 1 ms before you need to notice it). However if the overflow is about to happen then you only have the 1 ms grace period.
I mention this because if you have an external interrupt 0 event (INT0_vect) and the ISR takes 500 µs, and then external interrupt 1 event (INT1_vect) during that time (so another ISR will be serviced) then the timer interrupt might be blocked for a while.
That is why all ISRs should be short. It isn't good enough that some of them are.

Re-enabling interrupts
I strongly recommend against this. The libraries are not designed to be re-entrant, and once you start enabling interrupts in one ISR you may find that it itself is called again when it is half-way through being called the first time. You may also conceivably interrupt a library function (eg. memcpy) that was not designed for it.
And, of course, if you are re-enabling interrupts inside an ISR because the ISR takes a long time: well, that is the exact situation when you may trigger this re-entrancy.

More information:

Interrupts
Timers
Millis overflow

The timer interrupt can even disrupt measurement of pulses using micros() from an on change interrupt.  The timer interrupt takes around 6.5us on Arduino Uno or mega.  If a change interrupt takes place just after the timer interrupt, then the change interrupt will be delayed by up to 6.5us until the timer interrupt completes.  In addition, the microsecond count is only updated once every 4us, introducing further uncertainty up to 4us.
So the measurement may be up to 10.5us out.  This should be considered when measuring pulse lengths.

ABSOLUTELY
any ISR that is long will prevent millis() from incrementing. It can be dubiously slow skew of this clock.
The ISR function always start off with blocking interrupts with the cli() command at start and finish by enabling them with the sei() command. Blocking other ISR's along with Timer0's OverFlow interrupt which is used for increamenting the millis counter.
Any extended use of noInterrupts() or cli() or implied use with ISR's should be carefully short in duration. There is no general harm in executing either of interrupts() or sei() with in the ISR, as to allow interrupts again.
Example:
in the VS1053 library I have Data Request on an INT pin. Which's ISR may read from the SdCard, which can take a very long time. So I re-enable the interrupts() before reading the SdCard, but still in the ISR.

In you example the main loop is never resumed during that long interrupt routine, right? So that's a downside. Good to know enabling interrupts inside other interrupts isn't as "dangerous" as I though.

I think only an ISR (or chain of ISR's) longer than a millisecond will prevent it form interrupting. You can block it 0.5ms and it will update as the very next thing to do (interrupt).


text:
Writing and reading an ID to/from an Arduino reliably
I need a way to both ID (a sketch/compiled hex) and later on, identify based on this ID the project that got uploaded to my Arduino microcontroller. As of right now, I have explored multiple options for storing the ID and reading the ID from the Arduino. The ID would be a custom string or later on multiple strings. Here are the 3 options I have been thinking about with their pros and cons:

Option 1:
Writing: A custom function that would be added to every sketch before compilation, containing the ID information and a serial connection setup
Reading: The function would dump the ID over the serial connection using a fixed baud, after this, the projects original serial and baud would be initialized. The microcontroller would need to be rebooted in order for the user to be able to read the ID from it.
Pros: Easy to implement.
Cons: Would require manual or software restart of the microcontroller in order to read the ID

Option 2:
Writing: writing the ID to the EEPROM
Reading: reading the ID from the EEPROM over the serial connection.
Pros: Would probably not interference with the original code
Cons: it wears the EEPROM, it might need its own function in the sketch to read the ID from the EEPROM thus making it a complicated Option1.

Option 3: Editing the HEX file to include a signature
Writing: add the ID to the hex file itself (hex editing), after compiling it.
Reading: dumping the hex file and decoding the string.
Pros: No baud or serial needed to be set?
Cons: Probably slow, can end up producing a bad hex file, hard to implement properly with larger ID-s and structures

Example data:
project="marlin2.1",
config="prusa",
version="8.80",
env1="pin2"
As said, the basic idea is storing an ID but I would late want to expand this and store more information like a struct.  This solution should be able to Target as many Arduino models as possible. I am looking for the best way that I might have missed to achieve this task or any recommendations.

Which Arduino...?

Please tell what the ID is for (add the extra information to your question). Reading the eeprom does not wear it. With Option 1, the arduino dumps data by itself. That is odd. There are at least 10 other options. An other option is to include a .h file that has a generated ID. The compiler can put the compilation date and time in the sketch. The smallest arduino board can still do some decrypting, so you might put an encrypted ID in the arduino. Some arduino boards have a microcontroller that has an ID of its own. All the 1-Wire devices have an ID, just add a 1 dollar 1-Wire device. and so on.

I have added some examples to the top post. And about the eeprom I was talking about constantly rewriting the eeprom that it might wear it, every new sketch would have its own data set that would be readable from the Arduino using the computer.

Option 1 and 3 are kind of identical.

Option 3 would eliminate the need to setup a serial connection in every sketch. And I don't know if its possible to dump the hex file from every Arduino model. But beyond these points yes, option 1 and 3 are almost identical. I did not try option 3 in practice yet, but I think that it is possible to achieve a working edit/write/read/decode process.

I'd go with #2. If you are concerned that you will eventually burn-out your EEPROM (100.000 write cycles per ATmega328 ds), try writing a macro, which will dictate at which upload you want new ID to be written in EEPROM.
Heck, instead of writing all of these onboard, why don't you maintain an offline lookup database and encode things yourself? It would still require writing to EEPROM but you could encode your information in a couple of ints.


text:
The reason for signal not going back to LOW
I have written a simple Arduino sketch, that shall produce a clock signal.
Here is the code:
void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(8,HIGH);
  delayMicroseconds(500);
  digitalWrite(8,LOW);
  delayMicroseconds(500);
}

Namely the pin 8 of Arduino Uno is periodicaly set to HIGH and LOW.
The output that I receive, for three different frequencies, is:

My question is: Why is falling edge not as sharp as rising edge? As can be noted, for high frequencies the signal wouldn't go to LOW after all.

I don't know the details of Arduino hardware, but don't you need to explicitly configure pin 8 to be an output in your setup() function? It looks like you're just enabling/disabling a pullup by default.

@DaveTweed No, it appears that the problem is the OP hasn't declared pin 8 as output.

@DaveTweed Indeed, declaring a pin as output, produced a nice square wave. Can you please elaborate on reasons behind this (e.g. what you mean by enabling/disabling a pullup by default) and that would be answer to this question.

The pin is not configured as OUTPUT.
By default, all of the GPIO pins on pretty much any microcontroller are configured as inputs following reset. This prevents the chip from "fighting" an external device that might be driving any of those pins before the firmware has had a chance to configure the GPIO correctly.
On the MCU used on the Arduino, the output latch controls the state of an internal pullup resistor when the pin is configured as an input. Your code was simply enabling and disabling this resistor. When you set the pin low, it makes the pin open-circuit, and you see a slow decay of voltage through your oscilloscope probe.


text:
Mac Power via Keyboard Shortcut?
many mac keyboards have a power button. Is there a way to mimic this power button shortcut from an arduino?

Perhaps you could be clear what you mean by "mimic". Do you want your Arduino to be able to turn on (or off) your Mac without manual intervention?

Also, what keyboard? Some Mac laptops have a power button for the computer, where others have one to shut off the wireless keyboard.

You have to research HID keyboard codes and its protocol. The power button is a regular key on the keyboard with a specific key code and specific a data frame. Leonardo can probably do it, most somewhat older design Arduino's can't act as a USB HID.

The Arduino can emulate a keyboard from which you can send a series of keystrokes to turn off the computer. Not sure you'll be able to mimic the hardware button. There are a few questions that are related: http://arduino.stackexchange.com/search?q=hid+is%3Aquestion

I have a mac mini rack holder that has a front panel with power button. It connects and controls the mac mini with USB only. I want to replicate this power signal sent over the USB with an arduino instead.

@Brian you'll have to try connecting that USB device to another OS (that most likely won't respond to the press) and use some kind of keylogging software to detect what character code it sends to the computer. If you can figure that out, it's easy to do this on the Leonardo (although still possible on the Uno, but a bit harder).

There are multiple ways to do that.

You could use an Arduino Leonardo as a keyboard, then send a shortcut command to shut down or sleep the computer. You can edit these from System Preferences>Keyboard>Shorcuts>Services.
The keycode 0x66 does not work for mac, but may for other operating systems source
You could write a small program (I'd do it in Python) which communicates with the Arduino over the serial port and shuts down the Mac if the Arduino wants it to.
You could sacrifice an USB keyboard and use a relay to "press" the power key.