text:
Understanding the relationship of Pulse and Stepper RPM
This may be a better question for the Physics StackExchange so tell me if I should move the question.
I have a pretty simple script that I'm using to control the RPM of my stepper motor:
void loop(){
  digitalWrite(PIN, HIGH);
  delayMicroseconds(wait);
  digitalWrite(PIN, LOW);
}

as you can see it's just producing a pretty standard pulse, I have my Arduino connected to a driver that manages the motor. The wait variable comes from a second order equation I derived from measuring the RPM with a Tachometer and tweaking the value.
// From data RPM = 31729/x + 17.327 thus x = 31729/(RPM-17.527)
wait = M/(RPM-C);

It works pretty well, I get readings consistently within only 1 - 2 rotations off. But the slope and intercept seem completely arbitrary to me. Is there a chance it has to do with the clock speed of the Arduino? I'm using an Uno and from playing around with the numbers I can't seem to find a relationship. From what I can tell, the driver looks hardwired so I don't think it has much to do with the equation.
Any idea what these values, the slope/intercept mean?
Equation: RPM=31729/wait + 17.327 M:31729 and C:17.327

I wonder if this generates a proper pulse. It needs a delay after digitalWrite(PIN, LOW);

There's definitely a clock dependent granularity and additional delay among other potential problems.  For steady rotation, consider using a hardware timer to drive a pin, or failing that trigger an interrupt so that at least the overall rate remains constant.  There should be a fixed factor of step rate as long as the system is operating properly, but there will be both a rate and am acceleration at which it starts skipping steps, especially under load or resonance.

The real answer to this question requires understanding exactly what hardware you have. The formula, assuming one step per pulse, is that the delay should be:
wait = (MicroSecondsPerMinute)(1/RPM)(1/PulsesPerRevolution) - overhead
where overhead is the extra time it takes to run digitalWrite twice and loop. It is small, but if it were zero your code would not work because the amount of time your signal is LOW would be zero as well.
Your numbers suggest Pulses Per Revolution is around 1891. This will be the product of how many steps per revolution the motor is wired for and how many bits of microstepping the driver is doing. A 225 step motor with 3 bit microstepping (8 fractional steps per "true" step) would have PPR of 1800 for example. Your number does not precisely match any common setups, but is exactly in the range expected, with 1600 and 2000 being normal for small steppers.
Because of the "overhead" term, RPM as a function of wait should not be linear. Your constant value should be a function of RPM; in fact, when RPM gets much larger than the number of Microseconds per minute it should converge to being equal to RPM. In this case your RPM is so low that approximating it to 17 is probably valid and all error too small to notice. It could be causing some of the oddness of your PPR value though.

one pulse equals one step of stepper and rpm is how many rotation stepper makes in one minute.
Try to understand the stepper.h library and Accelstepper library


text:
Guide to code for multitasking and non blocking timers
I'm beginning to do kind of sophisticated things (well.. for my entry level skill) and I have to control a display with 3 LED and 4/5 types of events and status.
I'm using the BlinkWithoutDelay example duplicating all the variables for different status/events but the code is really messy, full of puzzling nested if statements.
How to simplify the things? I don't know what to choose, because OOP could be a choice but I think it will hurt the low-memory thing inside the Arduino Uno/Leonardo. Interrupts could be another choice but I think they are like threads, and following the KISS principle I'd like to stay away from them.
So, can someone advice me some article/tutorial/code-to-read/whatever to understand how to use a lot of LEDs and keep a lot internal status without screw my brain?
EDIT:
It is a little bit hard to reproduce a simple skelton of my messy code, but it looks like this (in pseudocode maybe)
void loop() {
    if(state==0) handleState0();
    if(state==1) handleState1();
    if(state==2) handleState2();
    if(state==3) handleState3();
    readButtons();
    readSensors();
    …
}

// this is a block of variables that I have to copy-and-paste
// every time I have to blink a led (hoping that there is
// nothing blocking that can skrew up everything)
unsigned long previousMillis_1 = 0;
const long interval_1 = 1000;
int ledState_1 = LOW;

void handleState1() {
  // Green led blinking, yellow is fixed
  // this is a copy-and-paste code hard to maintain,
  // easily broken from any blocking call (like also I2C)
  // and hard to refactor or isolate
  unsigned long currentMillis_1 = millis();
  if(currentMillis_1 - previousMillis_1 >= interval_1) {
    previousMillis_1 = currentMillis_1;
    if (ledState_1 == LOW) ledState_1 = HIGH;
    else ledState_1 = LOW;
    digitalWrite(pinGreen, ledState_1);
    digitalWrite(pinYellow, LOW);
}

unsigned long previousMillis_2 = 0;
const long interval_2 = 1000;
int ledState_2 = LOW;

void handleState2() {
  // Yellow led blinking, green is fixed
  // same as before
  unsigned long currentMillis_2 = millis();
  if(currentMillis_2 - previousMillis_2 >= interval_2) {
    previousMillis_2 = currentMillis_2;
    if (ledState_2 == LOW) ledState_2 = HIGH;
    else ledState_2 = LOW;
    digitalWrite(pinYellow, ledState_2);
    digitalWrite(pinGreen, LOW);
}

void handleButtonPressed() {
  // this skrew everything and because is blocking
  // and should be inserted in the main loop with
  // some global variables: active/disable, counter,
  // and non-blocking vars like previousMills, interval, etc etc
  Serial.println("\ndisplayAccessDenied");
  for(int i=0; i<3; i++) {
    digitalWrite(pinRed, LOW);
    delay(100);
    digitalWrite(pinRed, HIGH);
    delay(100);
  } digitalWrite(pinRed, LOW);
}

I feel a little bit lost but all the Arduino example arounds are super simple and to make a middle-level LED interface I have to screw my minds with something that is not working as 100% and other than Arduino I find only super-hard articles on microprocessors with low-level C code. But the pasted example is not working at 100% AND super hard to read, maintain, etc.

I'd suggest you to take a look at Cosa framework for Arduino (https://github.com/mikaelpatel/Cosa): powerful and quite easy to use, fully OOP but still has a small memory footprint and excellent performance.

Could you post your code? Different problems have different (optimal) solutions. PS. interrupts are nothing like threads. Maybe not the best place to start as a beginner, but they can be extremely powerful. I don't think they are against the KISS principle. You could e.g. have the main loop check all the events, and have an interrupt set the led in accordance with some variables set in the loop.

ok I have edited. so.. interrupt are not the devil.. any advice on some middle-level guides/article about it?

You can try:
http://bleaklow.com/2010/07/20/a_very_simple_arduino_task_manager.html It's simple but powerful.

interrupt are not the devil - see Interrupts

It is not really clear what you want here...
If you want to execute things in a certain time, then take a look at http://playground.arduino.cc/Code/Scheduler
Or, if you want more than just that (multiple tasks, preemptive multitasking) https://launchpad.net/arduos (arduOS can also just serve to run things in a certain time, but without having to use a function all the time)
While OOP MIGHT take more program memory, an object without virtual functions only takes the RAM the variables in it take (if you have a byte (1 byte) and an int (2 bytes) in an object it would take 3 bytes)
On the AVR-architecture (the one most Arduinos use) the program is directly executed from a flash-memory and only the variables are in the RAM
The if-state-handling you are doing there can be done easier using arrays like:
typedef void(*handler)(void)
handler stateHandlers[STATES] = {&handle1, &handle2, &handle3 ...
// handle? are functions without the () !
void handleState(int state)
{
    if(state >= STATES)
        return;
    stateHandlers[state]();
}

Obviously, you can also use arrays to store the states of the LEDs.
Also note that HIGH is just 1 and LOW is 0, so technically a bit would be enough to store the states.

Cosa supports a large number of mechanisms for multi-tasking. The latest addition is an abstract class for Jobs (delayed or periodic functions) and Job Schedulers. This abstraction allows functions to be scheduled on micro-, milli- and seconds level.
To get started please see the Cosa example sketches. If you have an Logic Analyzer (Salea Logic for instance) there are a number of example sketches that show pulse generation.
There is also a binding of the Job Scheduler to a seconds tick level. This is abstracted to Clock and Alarms.
For higher abstraction of multi-tasking Cosa also implements FSM, Proto-threads, Threads (multi-stacks), UML Capsules, and more.

Does it support forced preemption? Semaphores? I had a cursory look but couldn't find them at glance.

The Threads (see Cosa/libraries/Nucleo) are not forced preemption. It is collaborative, i.e. need to call yield(), delay(), etc. There are semaphores and some basic message passing support. The Job and Job::Scheduler can be used in a forced preemption fashion as the dispatch is from ISR and can be modified to run() within the ISR context. The simplest of all the multi-tasking abstractions is the periodic block (See Cosa/Periodic.hh and the macro periodic(timer, ms)).

Ok, thanks for confirming. For my needs, the lack of forced preemption is already disqualifying.

It is a question about resources. Cosa supports AVR MPU from ATtiny to ATmega. With only 0.5-1 Kbyte SRAM it is a challenge to allow thread stacks and ISR frames and still have memory over for the application. It is very much a trade off. The mechanism in Cosa can be used with forced preemption but that is not in the open-source version. Cheers!

Here's an example of blinking two LEDs independently:
// Which pins are connected to which LED
const byte greenLED = 12;
const byte redLED = 13;

// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long greenLEDinterval = 500;
const unsigned long redLEDinterval = 1000;

// Variable holding the timer value so far. One for each "Timer"
unsigned long greenLEDtimer;
unsigned long redLEDtimer;

void setup ()
  {
  pinMode (greenLED, OUTPUT);
  pinMode (redLED, OUTPUT);
  }  // end of setup

void toggleLED (const byte which, unsigned long & whenToggled)
  {
   if (digitalRead (which) == LOW)
      digitalWrite (which, HIGH);
   else
      digitalWrite (which, LOW);
  // remember when we toggled it
  whenToggled = millis ();
  }  // end of toggleLED

void loop ()
  {
  // Handling the blink of one LED.
  if ( (millis () - greenLEDtimer) >= greenLEDinterval)
     toggleLED (greenLED, greenLEDtimer);

  // The other LED is controlled the same way. Repeat for more LEDs
  if ( (millis () - redLEDtimer) >= redLEDinterval)
    toggleLED (redLED, redLEDtimer);

/* Other code that needs to execute goes here.
   It will be called many thousand times per second because the above code
   does not wait for the LED blink interval to finish. */

  }  // end of loop

Note that instead of copying and pasting the blinking code, I made a generic function. That way any bugs are easily fixed.

For more LEDs you could use an array:
const int NUMBER_OF_LEDS = 5;
// Which pins are connected to which LED
const byte LED_PINS [NUMBER_OF_LEDS] = { 8, 9, 10, 11, 12 };
// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long LED_INTERVALS [NUMBER_OF_LEDS] = { 200, 400, 100, 1000, 2000};
// Variable holding the timer value so far. One for each "Timer"
unsigned long timeLEDtoggled [NUMBER_OF_LEDS];

void setup ()
  {
  for (int i = 0; i < NUMBER_OF_LEDS; i++)
    pinMode (LED_PINS [i], OUTPUT);
  }  // end of setup

void toggleLED (const byte which, unsigned long & whenToggled)
  {
   if (digitalRead (which) == LOW)
      digitalWrite (which, HIGH);
   else
      digitalWrite (which, LOW);
  // remember when we toggled it
  whenToggled = millis ();
  }  // end of toggleLED

void loop ()
  {
  // see if it is time to toggle the LEDs
  for (int i = 0; i < NUMBER_OF_LEDS; i++)
    if ( (millis () - timeLEDtoggled [i]) >= LED_INTERVALS [i])
       toggleLED (LED_PINS [i], timeLEDtoggled [i]);

  /* Other code that needs to execute goes here. */
  }  // end of loop

If anything, the above code is simpler, but it blinks 5 LEDs at different rates. Now you can have more sophisticated tests than that, but the general concept is the same.

References

How to do multiple things at once ... like cook bacon and eggs
State machines

Use the NonBlockingSequence library. It has clean examples for applying blinking sequences without delay. (Example Link)
    #include <NonBlockingSequence.h>

class Blinking_Led{

  private:
  // Declare Sequence
  ClassNonBlockingSequence<Blinking_Led> Sequence;

  // led pin
  byte _pin;

  // Define step-functions
  bool led_on(){
    digitalWrite(_pin,1);
    return true;
  }
  bool led_off(){
      digitalWrite(_pin,0);
      return true;
  }

  public:
  Blinking_Led(){};
  void init(byte pin,unsigned long pause){

    // define the led pin
    _pin=pin;
    pinMode(_pin,OUTPUT);

    // This line explain important fact for the Sequence
    Sequence.AttachedObj(this);
    // Sequence should use steps defined inside this class only

    // Add steps
    Sequence.AddNewStep(&led_on);
    Sequence.AddDelayInMillis(pause);
    Sequence.AddNewStep(&led_off);
    Sequence.AddDelayInMillis(pause);
    Sequence.Repeat();
    // repeat the sequence infinite number of times

  }

  Blink(){ // use familiar name for led
    Sequence.DoSequence();
  }

};

// Declare new objects
Blinking_Led Led1;
Blinking_Led Led2;

void setup() {

  //  Led.init( pin , blinking time )
  Led1.init(13,200);
  Led2.init(12,1500);

}

void loop() {
  // put your main code here, to run repeatedly:
  Led1.Blink();
  Led2.Blink();
}

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

source: Stack Exchange

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

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

sort: votes


text:
How to detect the direction of a rotary encoder?
I'm trying to detect the direction of rotation for an incremental rotary encoder. I'm supposed to get +1 for clockwise and  -1  for counter-clockwise. However, I receive random values. Any help appreciated.
Following is the code.
const int encoderPinA = 7;
const int encoderPinB = 12;
int val;
int encoderPos = 0;
boolean encoderALast = LOW; // remember the previous pin state

void setup() {
  pinMode(encoderPinA,INPUT);
  pinMode(encoderPinB,INPUT);
  Serial.begin(9600);
}

void loop() {
  analogWrite(3,250); //powering motor
  val = encoder_direction();
  // receive the direction for clockwise 1 and for counter clock wise  -1
  Serial.println(val); // print it in serial monitor
}

int encoder_direction() {
  boolean encoderA = digitalRead(encoderPinA);
  if ((encoderALast == HIGH) && (encoderA == LOW)) {
    if (digitalRead(encoderPinB)) {
      //encoderPos --;
      encoderPos = -1;
    } else {
      //encoderPos ++;
      encoderPos = 1;
    }
    return  encoderPos;
    // return the value either 1 or -1
  }
  encoderALast = encoderA;
}

// using digitalread() code  for four encoders
const int ENCODERS = 4; // the number of encoders
const int encoderPinA[ENCODERS] = { 7, 8, A1 , 2 };
// encoderA pins on 2 and 4
const int encoderPinB[ENCODERS] = { 12, 5, 4 , A2 };
// encoderB pins on 3 and 5
int encoderPos[ ENCODERS] = { 0, 0, 0, 0 };
// initialize the positions to 0
boolean encoderALast[ENCODERS] = { LOW, LOW, LOW, LOW };
// holds last state of encoderA pin

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

int updatePosition(int encoderIndex) {
  boolean encoderA = digitalRead(encoderPinA[encoderIndex]);
  if ((encoderALast[encoderIndex] == HIGH) && (encoderA == LOW)) {
    if (digitalRead(encoderPinB[encoderIndex]) == LOW) {
      //encoderPos[encoderIndex]--;
      encoderPos[encoderIndex] = -1;
    } else {
      //encoderPos[encoderIndex]++;
      encoderPos[encoderIndex] = 1;
    }
    Serial.print("Encoder ");
    Serial.print(encoderIndex+1,DEC);
    Serial.print("=");
    Serial.println (encoderPos[encoderIndex]);
  }
  encoderALast[encoderIndex] = encoderA;
}

void loop() {
  updatePosition(0);
  updatePosition(1);
  updatePosition(2);
  updatePosition(3);
}

// using direct access to digitalread code in order to process faster
int val[4];
int encoderPos = 0;
boolean encoderALast[4] ={LOW, LOW, LOW, LOW};
// remember the previous pin state

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

void loop() {
  for (int ii=0; ii<4;ii++) {
    encoder_direction(ii);
  }
}
int encoder_direction(int m) {
  boolean encoderA;
  boolean encoderB;
  if(m == 0) {
    encoderA = (PIND & _BV (7)) == 0;
    //   digitalRead(7) encoderPinA
    encoderB = (PINB & _BV (4)) == 0;
    // digitalRead(12) encoderPinB
  }
  if (m == 1) {
    encoderA = (PINB & _BV (0)) == 0;
    // digitalRead(8) encoderPinA
    encoderB = (PIND & _BV (5)) == 0;
    // digitalRead(5) encoderPinB
  }
  if (m == 2) {
    encoderA = (PINC & _BV (1)) == 0;
    // digitalRead(A1) encoderPinA
    encoderB = (PIND & _BV (4)) == 0;
    // digitalRead(4)  encoderPinB
  }
  if (m == 3) {
    encoderA = (PIND & _BV (2)) == 0;
    // digitalRead(2) encoderPinA
    encoderB = (PINC & _BV (2)) == 0;
    // digitalRead(A2)  encoderPinB
  }
  if ((encoderALast[m] == HIGH) && (encoderA == LOW)) {
    if (encoderB == LOW) {
      //encoderPos --;
      encoderPos = -1;
    } else {
      //encoderPos ++;
      encoderPos = 1;
    }
    Serial.print(" Encoder ");
    Serial.print(m+1);
    Serial.print(" = ");
    Serial.println(encoderPos);
  }
  encoderALast[m] = encoderA;
}

I don't think its possible using only 2 detector and detect only based on the order of activation.

when this is in the loop works fine. But, now I  want to use function. The problem is I can not retrieve correct value from function's output.

I have a page about rotary encoders - in that I show how you can detect encoder changes (and direction) using one interrupt pin and another pin, like this:
// Wiring: Connect common pin of encoder to ground.
// Connect pin A (one of the outer ones) to a pin that can generate interrupts (eg. D2)
// Connect pin B (the other outer one) to another free pin (eg. D5)

volatile bool fired;
volatile bool up;

const byte encoderPinA = 2;
const byte encoderPinB = 5;

// Interrupt Service Routine for a change to encoder pin A
void isr ()
{
  if (digitalRead (encoderPinA))
    up = digitalRead (encoderPinB);
  else
    up = !digitalRead (encoderPinB);
  fired = true;
}  // end of isr

void setup ()
{
  pinMode (encoderPinA, INPUT_PULLUP);     // enable pull-ups
  pinMode (encoderPinB, INPUT_PULLUP);
  attachInterrupt (digitalPinToInterrupt (encoderPinA), isr, CHANGE);   // interrupt 0 is pin 2

  Serial.begin (115200);
}  // end of setup

void loop ()
{
static long rotaryCount = 0;

  if (fired)
    {
    if (up)
      rotaryCount++;
    else
      rotaryCount--;
    fired = false;

    Serial.print ("Count = ");
    Serial.println (rotaryCount);
    }  // end if fired

}  // end of loop

In the main loop you just need to test the boolean fired to see if the encoder changed, and up to see if it went up (otherwise it went down).

I receive random of these values ...

I think with your code you need to detect a change - that is, if the encoder pin is now HIGH but was previously LOW.

Solution for 4 encoders

The problem is I am working on four encoders ...

I have reworked my code to use pin-change interrupts instead of external interrupts.
// Wiring: Connect common pin of encoder to ground.

volatile bool fired;

const byte ENCODERS = 4;

typedef struct
  {
  int aPin;     // which Arduino pin for the "A" side
  int bPin;     // which Arduino pin for the "B" side

  // values below are calculated at run-time
  volatile byte * aPort;  // which processor port the A side is plugged into
  volatile byte * bPort;  // which processor port the B side is plugged into
  byte aBitMask;   // which bit in the A port
  byte bBitMask;   // which bit in the B port
  byte whichInterrupt;  // which pin-change interrupt port (0, 1, 2)
  byte oldValue;   // old value of A port (to see if it changed)
  int count;       // current encoder counter
  } encoder;

 volatile encoder encoders [ENCODERS] =
  {

 // A   B  pins  (eg. D4 and D8, D5 and D9 and so on)

  { 4,  8 },
  { 5,  9 },
  { 6, 10 },
  { 7, 11 },

  };  // end of encoders

void checkForPinChange (const byte which)
  {
  for (byte i = 0; i < ENCODERS; i++)
    {
    if (encoders [i].whichInterrupt == which)
      {
      byte newValue = *(encoders [i].aPort) & encoders [i].aBitMask;
      if (newValue != encoders [i].oldValue)
        {
        bool up;
        byte bPort = *(encoders [i].bPort) & encoders [i].bBitMask;
        if (newValue)
          up = bPort;
        else
          up = !bPort;
        fired = true;
        if (up)
          encoders [i].count++;
        else
          encoders [i].count--;
        encoders [i].oldValue = newValue;
        }  // end of if value has changed
      }   // end of if this is the right interrupt number
    }     // end of for each encoder
  } // end of checkForPinChange

// handle pin change interrupt for D8 to D13 here
ISR (PCINT0_vect)
 {
 checkForPinChange (PCIE0);
 }  // end of PCINT0_vect

// handle pin change interrupt for A0 to A5 here
ISR (PCINT1_vect)
 {
 checkForPinChange (PCIE1);
 }  // end of PCINT1_vect

// handle pin change interrupt for D0 to D7 here
ISR (PCINT2_vect)
 {
 checkForPinChange (PCIE2);
 }  // end of PCINT2_vect

void setup ()
{
 Serial.begin (115200);
 Serial.println ("Starting ...");

 PCIFR  |= bit (PCIF0) | bit (PCIF1) | bit (PCIF2);   // clear any outstanding interrupts

 for (byte i = 0; i < ENCODERS; i++)
    {
    pinMode (encoders [i].aPin, INPUT_PULLUP);
    pinMode (encoders [i].bPin, INPUT_PULLUP);
    // convert pin number to port, mask, etc. for efficiency

    // Input port
    encoders [i].aPort = portInputRegister (digitalPinToPort (encoders [i].aPin));
    encoders [i].bPort = portInputRegister (digitalPinToPort (encoders [i].bPin));

    // Which bit in the port to test
    encoders [i].aBitMask = digitalPinToBitMask (encoders [i].aPin);
    encoders [i].bBitMask = digitalPinToBitMask (encoders [i].bPin);

    // Which interrupt number (0, 1, 2)
    encoders [i].whichInterrupt = digitalPinToPCICRbit (encoders [i].aPin);

    // activate this pin-change interrupt bit (eg. PCMSK0, PCMSK1, PCMSK2)
    volatile byte * ICRmaskPort = digitalPinToPCMSK (encoders [i].aPin);
    *ICRmaskPort  |= bit (digitalPinToPCMSKbit (encoders [i].aPin));

    // enable this pin-change interrupt
    PCICR |= bit (digitalPinToPCICRbit (encoders [i].aPin));

    } // end of for each encoder

}  // end of setup

void loop ()
{
  if (fired)
    {
    for (byte i = 0; i < ENCODERS; i++)
      {
      char buf [10];
      sprintf (buf, "%5d", encoders [i].count);
      Serial.print (buf);
      }
    Serial.println ();
    fired = false;
    }  // end if fired

}  // end of loop

The code is general enough to handle 1 to x encoders (eg. 10 encoders) - within reason! You need to have 2 pins spare per encoder (the third pin goes to ground). One of the pins needs to be capable of pin-change interrupts (on the Uno that is all of them).
The code sets up to detect an interrupt on the "A" side of the encoder and tests the value on the "B" side to see if it was turned clockwise or counter-clockwise.
I am getting results like this (with 2 encoders connected):
   16  -19    1    1
   17  -19    1    1
   18  -19    1    1
   19  -19    1    1
   20  -19    1    1
   21  -19    1    1
   22  -19    1    1
   23  -19    1    1
   23  -20    1    1
   23  -21    1    1
   23  -22    1    1
   23  -23    1    1
   23  -24    1    1
   23  -25    1    1

The other two are showing as "1" (that is, not turned yet).

I see. The problem is I am working on four encoders, Therefore, I trying to realize by status change detecting.

It's always helpful to give as much detail as you can in the question. Then we don't have to guess, and we don't give an answer which doesn't suit your situation.

And if I may say, your posted code in the question doesn't have four encoders in it.

Nick, I think it would make sense to update your code to say pinMode(encoderPinA, INPUT_PULLUP); instead of  digitalWrite (encoderPinA, HIGH);     // enable pull-ups

ok, I got to different code for four encoders.

The one is using digitalread() and the other one is using fast access to digitalinread() which was on your post. But none of them work.

I mean they do not work when rotating simultaneously.

If motors rotate separately, then both codes working fine. But the problem is usually motors run at the same time.

it would make sense to update your code - you are right. I have updated the answer. The original code was written quite a while ago.

I got to different code for four encoders - you can probably do it with pin-change interrupts. I'll look at that tomorrow. You may want to see my page about interrupts

See my amended reply which shows how to handle four encoders.

Using polling to read multiple encoders may work if you program quite carefully and if you dedicate the processor just to reading encoders; but generally, interrupt-driven encoder processing has a higher likelihood of working ok.  The example below uses pin-change interrupts to read from three rotary encoders that are attached to PD2...PD7, ie, six consecutive bits of port D.  It can be extended to more encoders by adding another pin-change ISR to handle another interrupt vector, or by using PD0 and PD1 as encoder inputs.  (However, PD0 and PD1 are RX and TX on the Uno I'm testing with, and I'm using Serial for test output.)
Example: rotors3.ino
/*  Rotors3 -- JW, December 2016 -- Uses 4-state state-machine
 *  implementation of rotary encoding for KY-040 rotary knobs.  The
 *  state-machine picture in a Feb 4, 2014 7:40 PM post at
 *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
 *  by Anthony Seely shows counts increasing on transitions 10 -> 11
 *  -> 01 -> 00 -> 10 and decreasing on transitions the other way.
 *  The ISR in this program decodes those transitions using logical
 *  operations on variables `changes` and `wayflag`.  Transitions
 *  between 00 and 11 or 10 and 01 are invalid and ignored.
 */

volatile byte abOld;        // Old state
volatile byte changedCount; // Change-indication
volatile int count[3];      // current rotary count

void setupRotors3(byte ioMode, byte enablePCI) {
  pinMode( 2, ioMode); //  2, PD2   PCINT 18
  pinMode( 3, ioMode); //  3, PD3   PCINT 19
  pinMode( 4, ioMode); //  4, PD4   PCINT 20
  pinMode( 5, ioMode); //  5, PD5   PCINT 21
  pinMode( 6, ioMode); //  6, PD6   PCINT 22
  pinMode( 7, ioMode); //  7, PD7   PCINT 23
  if (enablePCI) {
    PCMSK2 |= 0xfc; // Set mask for bits of interest
    PCIFR  |= 0x04; // Clear PC interrupts if any
    PCICR  |= 0x04; // Enable PC interrupts
  }
  abOld = changedCount = count[0] = count[1] = count[2] = 0;
}

void setup() {
  setupRotors3(INPUT_PULLUP, true);
  Serial.begin(115200);
  Serial.println("Starting Rotary Encoder Test");
}

// On interrupt, read input pins, compute new states, and adjust
// counts.  This code depends on encoder data appearing like ddccbbaa,
// ie data is in properly paired consecutive port bits.
ISR(PCINT2_vect) {
  byte abNew = PIND & 0xfc; // Read pins  2, 3, 4, 5, 6, 7,
  byte changes = abNew^abOld;   // Use XOR to flag changed bits
  char wayflag = 2*abNew^abNew; // Use XOR to get state-bits
  byte test2;
  for (byte i=0; i<3; ++i) {
    // For PD2-7, low 2 bits aren't relevant.  Move the shifts to
    // end of for loop if low 2 bits carry encoder info.
    wayflag >>= 2;      // Discard low state-bits
    changes >>= 2;      // Discard low change-bits
    test2 = changes & 3;    // Get 2 bits of interest
    if (test2==1) {
      count[i] += 1-(wayflag&2);
      changedCount = true;
    } else
      if (test2==2) {
        count[i] -= 1-(wayflag&2);
        changedCount = true;
      }
  }
  abOld = abNew;        // Save new state
}

void loop() {
  if (changedCount) {
    changedCount = false;   // Race condition can be ignored
    for (byte i=0; i<3; ++i) {
      Serial.print(count[i]);   // Announce counts
      Serial.print("  ");
    }
    Serial.println(millis());   // Announce change-time
  }
}

Note, setupRotors3() and a few other statements in the program were generated using the ISR-framework-generating Sketch from an answer to an earlier question.  If you need to use other input pins than those shown in the program above, you can use the framework generator to produce a setup routine and port-I/O statements for them.
Following is some output from the program as above, from when I turn two of the three 60-counts-per-turn encoders as fast as I can by hand, for half a turn each at the same time (about 4 RPS, or 240 RPM).
-2  1  0  1127
-2  2  0  1133
-2  3  0  1148
-2  4  0  1155
-3  4  0  1165
-3  5  0  1166
-4  5  0  1169
-4  6  0  1170
-5  6  0  1174
-5  7  0  1177
-6  7  0  1178
-6  8  0  1181
-7  8  0  1184
-7  9  0  1187
-8  9  0  1189
-8  10  0  1190
-9  10  0  1196
-9  11  0  1197
-10  12  0  1200
-10  12  0  1201
-11  12  0  1205
-11  13  0  1207
-12  13  0  1210
-12  14  0  1211
-12  15  0  1215
-13  15  0  1216
-13  16  0  1220
-14  16  0  1221
-15  16  0  1224
-15  17  0  1226
-16  17  0  1229
-16  18  0  1230
-17  18  0  1234
-17  19  0  1235
-18  19  0  1239
-18  20  0  1241
-19  20  0  1243
-19  21  0  1247
-20  21  0  1248
-21  21  0  1251
-21  22  0  1252
-22  22  0  1255
-22  23  0  1258
-23  23  0  1259
-24  23  0  1263
-24  24  0  1264
-25  24  0  1266
-25  25  0  1269
-26  25  0  1271
-27  25  0  1275
-27  26  0  1275
-28  26  0  1280
-28  27  0  1281
-29  27  0  1284
-29  28  0  1288
-30  28  0  1291
-31  28  0  1301
-31  29  0  1341
-32  29  0  1346
-32  30  0  1385
-33  30  0  1389

Looks like we had similar ideas. I didn't spot your answer until I had rewritten my code. :) We even have similar debugging output.

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


text:
sprintf trouble
char cTime[22];

sprintf(cTime, "%04s/%02s/%2s:%02s:%02s:%02s", year(), month(), day(), hour(), minute(), second());

This sprintf line causes this error:**B0100000063f694Š
Could someone help me debug this?
Thank you.

%s is string macro but output of year(),... is probably an integer type. Use %d or %u macros in format.

Yes - try making each of the %-specifiers match the kind of conversion you want for each variable in the rest of the call. F/ex, %d converts an integer to a string in decimal radix, %f converts a double to a number with a decimal fraction, etc. In all cases, the output will be as characters; you don't need to specify that.


text:
Arduino Yun's sample "Bridge" code not working
I'm new to the Arduino world (or the electronics world for that matter).
I have the Arduino Yun and the WifiStatus code works fine (so does the HttpClient).
But every time I try to run the bridge sample code, all I see is the pin 13 led light up, and the browser commands don't work.
PS: I have updated the open-wrt to ver. 1.3.
Any thoughts on why this would be happening?
Edit 1:
I have tried to reboot arduino using the hardware switches as well as from the web console. The blink sketch works fine, so does the WifiStatus code and the HttpClient code.
The other problem I face after every few uploads is that the IDE is stuck at "Uploading...". I have tried to give it more time (even an hour). But then I had to unplug it from the Mac and restarted. Then it worked but only for a few times.
But this problem is not specific to the Bridge code. The uploading issue has occurred with other sample code as well. But at least the code worked.
Edit 2:
This is the result from the command ls /dev/tty.*
/dev/tty.Bluetooth-Incoming-Port    /dev/tty.usbmodem1431
/dev/tty.Bluetooth-Modem

Welcome to Arduino SE! Can you please edit your questions with more details? Do you have anything connected? Can you add more information about what you've tried, etc? As far as we know, the official code should work. It's really hard to diagnose this without any other information. Does the "blink" sketch work? Does uploading fail? Thanks!

when the problem occurs can you open the terminal and post the result of ls /dev/tty.*

This is the result from the command
" /dev/tty.Bluetooth-Incoming-Port /dev/tty.usbmodem1431
/dev/tty.Bluetooth-Modem "

I ended up doing two things. First I got a replacement hardware. That made the bridge code start working.
And I also changed the port from /dev/tty.usbmodem1431 to /dev/cu.usbmodem1431. As shown in the picture below. That fixed the issue with IDE getting stuck at "Uploading...".
Not sure if this fix will last.


text:
How do I set up an Arduino to be a wireless HID?
The question below describes how to set up an Arduino as an HID (Human Input Device -- like a keyboard, mouse, etc.).  How can I set up an Arduino as a wireless HID?
I'm flexible as to the wireless format.  Bluetooth, USB receiver, or any other format is acceptable.
Arduino as USB HID

This has been done with ESP32. If you connect a bluetooth module to the Arduino, that might work as well.

@ThomasWeller, this looks like what I need.  If you make it into an answer I'll accept it.

I'm not sure for Arduino, but it has been done with ESP32. If you have not yet spent the money into a Bluetooth module for Arduino, you'll find that the ESP32 is not expensive either.
You can find the code on Github. The author uses a TinyPico because it's pin compatible with one of his earlier projects. IMHO, any ESP32 should do as well.
The key thing is to
#include <BleKeyboard.h>

the ESP32 BLE Keyboard library that you need to download and install. That library comes with example code that should be easy to adapt to your needs.
You can program the ESP32 in Arduino IDE, but you need to add support for the boards by adding a URL to the board manager.
Have fun with the project. It sounds very interesting. Maybe I try that myself.

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


text:
How are libraries added to the Arduino library manager?
Who curates the list of libraries in the Tools / Manage Libraries menu, and what is the procedure for submitting code for consideration?

https://github.com/arduino/Arduino/wiki/Library-Manager-FAQ

You have to submit a ticket to the Arduino GitHub page. If you want to do this in an automated fashion, you can use this python program. Make sure beforehand that your library fits the Arduino library specification.


text:
Error Uploading Arduino Sketch to Arduino Pro Mini
I got an error "stk500_getsync() not in sync resp=0x00" when I tried to update an Arduino Pro Mini with an FTDI Basic Breakout 5V/3.3V - Micro USB. Maybe someone has instructions on how to resolve this issue. I use the last version of Arduino IDE.
All standard stuff like drivers, ports installed and configured.
I have communication with controller and I receive answers from it, but when I try to flash the firmware I get that error.

It's your COM port or your board selection.
I often use the Pro Mini and an Uno and when I forget to change either the COM port or the board to which I have to upload the sketch to, that error message happens.

I updated question.

Maybe wrong driver. There is only one FTDI driver.


text:
Undefined reference to stdlib (strtof) while compiling
I'm trying to run the AzureIoTProtocol_MQTT/esp8266 example, but I get linker errors:

Archiving built core (caching) in:
  /var/folders/fj/y3vtrz597kv4885q1b_5qypr0000gn/T/arduino_cache_934614/core/core_esp8266_esp8266_d1_mini_CpuFrequency_80,UploadSpeed_921600,FlashSize_4M3M_e1e103f2055a19e071ac9522162e1787.a
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function sscanfd':
  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:2826:
  undefined reference tostrtoull'
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function
  sscanfllu':
  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:2826:
  undefined reference tostrtoull'
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o:(.text.CreateAgentDataType_From_String+0xac):
  undefined reference to strtof'
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function
  CreateAgentDataType_From_String':
  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:3571:
  undefined reference to `strtof' collect2: error: ld returned 1 exit
  status

The issue can be broken down to the call to strtof function call. I get the same error with only this very simple code snippet:
#include <stdlib.h>

void setup() {
  char szOrbits[] = "686.97";
  float f;
  f = strtof (szOrbits, NULL);
}

void loop() {
}

Tested environment: Mac OS X 10.13.2 with Arduino 1.8.3 AND Windows 10 with Arduino 1.8.5.

Its because the "strtof" function resides in "stdlib.h",
"Stdio.h" deals with i/o tasks.
Since you din't include you get that undefined reference error.
Correct that and compile again. Hopefully the error shall be resolved, else reply in the comments.

Update1:
After digging around standard gcc stdlib definitions and avr-gcc definitions found out that the above solution works for a gcc and not avr-gcc especially the 8-bit ones which the arduino IDE compiles for uno and the works as expected for 32bit processors like of Due.
Cite:

https://www.arduino.cc/reference/en/language/variables/data-types/double/
https://www.arduino.cc/reference/en/language/variables/data-types/float/

Reason:
The size of the double and float is the same, ie: 4 bytes
and even if you use double its actually the float itself and wont gain any precision advantage.
Solution:
Since the size of the double and the float is same there is not point in having two function definition doing the same job.
so

Use "strtod"  instead of "strtof" or
Define a macro #define strtof(A, B) strtod(A, B) in the begning of your sketch so that the "strtod" handles the functioning of the "strtof".

changed to stdlib.h and same error.

@appsthatmatter i have updated my answer for your error. do check.

thanks for the answer. Since the function is used in a third party library I can not change it easily to float. But anyway, I managed it to run with this steps (replicable on Mac and Windows): 1) clean install of Arduino IDE, 2) install ESP8266 via git (see the README), 3) verify the program once for Board NodeMCU 1.0 (ESP 12-E).

Its because you haven't added the core of esp8266 to the arduino IDE.
you are defaulting it to the "UNO" board and compiling it.
so you get that error for which i have explanation
here: https://arduino.stackexchange.com/a/48719/3557
solution for your problem is simple added the esp8266 core and select the right board and compile again.
Cite: https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/installing-the-esp8266-arduino-addon
Follow above link and install the esp8266 core.


text:
Dallas Temperature Sensor DS18B20 not showing correct Result with Ethernet Shield
I am using Arduino Uno R3 board and a wiznet W5100 ethernet Shield. The temperature from the One wire sensors before using Ethernet Shield was showing correct. However later after connecting the shield, the temperature is showing to be 85. The server and everything else works fine, but the data is all wrong. Now I am pretty sure the connections are correct and it is not in parasite mode. Any suggestions of how I might get the accurate reading ?
/*
  Web Server

  A simple web server that shows the value of the analog input pins.
  using an Arduino Wiznet Ethernet shield.

*/

#include <SPI.h>
#include <Ethernet.h>
#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 2

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
            0xF0, 0xBF, 0x97, 0x67, 0xF6, 0x98
        };
IPAddress ip(192, 168, XXX, XXX);

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
EthernetServer server(80);

void setup() {
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    sensors.begin();
    while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
    }
    // start the Ethernet connection and the server:
    Ethernet.begin(mac, ip);
    server.begin();
    Serial.println(sensors.getTempCByIndex(0));
    Serial.print("Siddhartha Temperature ");
    Serial.print("server is at ");
    Serial.println(Ethernet.localIP());
}

void loop() {
    // listen for incoming clients
    EthernetClient client = server.available();
    if (client) {
        Serial.println("new client");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {
                char c = client.read();
                Serial.write(c);
                // if you've gotten to the end of the line (received a newline
                // character) and the line is blank, the http request has ended,
                // so you can send a reply
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    client.println("Content-Type: text/html");
                    client.println("Connection: close");
                    client.println("Refresh: 2");
                    client.println();
                    client.println("<!DOCTYPE HTML>");
                    client.println("");
                    // output the value of each analog input pin
                    for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
                        float sensorReading = sensors.getTempCByIndex(0);
                        client.print("Temperature ");
                        client.print(analogChannel);
                        client.print(" is ");
                        client.print(sensorReading);
                        Serial.println(sensorReading);
                        client.println("
");
                    }
                    client.println("");
                    break;
                }
                if (c == '\n') {
                    // you're starting a new line
                    currentLineIsBlank = true;
                }
                else if (c != '\r') {
                    // you've gotten a character on the current line
                    currentLineIsBlank = false;
                }
            }
        }
        // give the web browser time to receive the data
        delay(1);
        // close the connection:
        client.stop();
        Serial.println("client disconnected");
    }
}

The power-on reset value of the temperature register is 85 degC. Is it possible that something is interrupting the power to your sensors?

I highly doubt that ! I checked it using the multimeter, and everythings connected just as fine.

It looks like digital pin 2 might be connected (solder jumper) to the INT pin of the W5100. Try using pin 3 instead.

The Solution was actually much simpler. Apparently the Ground on the voltage I/O ports wasn't the right place to connect the ground terminal of the sensor. rather The Ground of the Digital I/O should be connected. Mistake retrieved by trail and error!! Its working just fine now.


text:
Initialize a "Matrix" object in my own library?
So, I'm trying to make a custom library to drive a 8x8 Bi-Color LED Matrix from 2 MAX7219's that incorporates two "Matrix" objects from the "Matrix" library and I cannot, for the life of me, figure out how to initialize them in my class. Can someone help me? By the way, I have been programming for 8 years, and consequently have a decent knowledge of the topic! Here is my current code:
header file
#include "Arduino.h"
#include "Matrix.h"
#include "Sprite.h"

class ZackBiColorMatrix{

    public:

        ZackBiColorMatrix(byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG);

        Matrix r;
        Matrix g;

        void setLED(byte col, byte row, byte val, char color);
        void writeSprite(byte x, byte y, Sprite sp, char color);

    private:

        byte redData;
        byte redLoad;
        byte redClock;

        byte greenData;
        byte greenLoad;
        byte greenClock;

};

and the .cpp file:
#include "Arduino.h"
#include "Sprite.h"
#include "Matrix.h"
#include "ZackBiColorMatrix.h"

ZackBiColorMatrix::ZackBiColorMatrix (byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG) {

    redData = dataR;
    redLoad = loadR;
    redClock = clockR;

    greenData = dataG;
    greenLoad = loadG;
    greenClock = clockG;

    r = Matrix (redData, redClock, redLoad);
    g = Matrix (greenData, greenClock, greenLoad);

}

void ZackBiColorMatrix::setLED (byte col, byte row, byte val, char color) {

    if (color == 'g') {

        g.write (col, row, val);

    }
    else if (color == 'r') {

        r.write (col, row, val);

    }

}
void ZackBiColorMatrix::writeSprite (byte x, byte y, Sprite sp, char color) {

    if (color == 'g') {

        g.write (x, y, sp);

    }
    else if (color == 'r') {

        r.write (x, y, sp);

    }

}

Also, I use the Eclipse Arduino IDE if that matters.

What you have in your constructor is perfectly valid C++, and it will initialise the member variables.

This is a C++ question actually.
In C++, you initialize class members in the class constructor definition by using a "member intialization list" as follows for your example:
ZackBiColorMatrix::ZackBiColorMatrix (byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG)
:   r(dataR, clockR, loadR),
    g(dataG, clockG, loadG) {
    ... Additional initialization here
}

This is a special C++ construct (note the colon : after the constructor declaration but before its implementation).
Also note that, in your example, I think you don't need to declare redData, redLoad, redClock, greenData, greenLoad, greenClock, sicne they are not being used once your 2 Matrix fields have been initialized.
Hence you could simplify your class further, I think.

Hey @ZackElec, if the answer helped you, please consider accepting it. You can do it by clicking the checkmark on the left-hand side of the question, just below the up/down vote arrows and the question vote count. Once you get 15 reputation points, you can also upvote the question. Thanks!!


text:
Faster GPS update rate for parser
I really hope somebody can help me.
I need help making my code receive updates faster to the parser...I need the received GPS coordinates (Latitude and Longitude) to update 5 or more times a second, currently it locks when stationary. Can somebody help?
code:
#include <TinyGPS.h>

/* This sample code demonstrates the normal use of a TinyGPS object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/

TinyGPS gps;
//SoftwareSerial ss(4, 3);

static void smartdelay(unsigned long ms);
static void print_float(float val, float invalid, int len, int prec);
static void print_int(unsigned long val, unsigned long invalid, int len);
static void print_date(TinyGPS &gps);
static void print_str(const char *str, int len);
//double getCurrentLatitude();
//double getCurrentLongitude();

//double cLatitude = 0.0;
//double cLongitude = 0.0;
//
//double getCurrentLatitude(){
//  return cLatitude;
//}
//
//double getCurrentLongitude(){
//  return cLongitude;
//}

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

//  Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
//  Serial.println();
//  Serial.println("Sats HDOP Latitude      Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
//  Serial.println("          (deg)         (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
//  Serial.println("------------------------------------------------------------------------------------------------------------------------------------------");

  Serial1.begin(9600);
}

void loop()
{
  double flat, flon = 0.0000000000000;
  unsigned long age, date, time, chars = 0;
  unsigned short sentences = 0, failed = 0;
  //static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

//  print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
//  print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
  gps.f_get_position(&flat, &flon, &age);
//  gps.f_get_position(&cLatitude,&cLongitude, &age);

  //print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);
  //print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);

  float lati = (float)flat;
  float longi = (float)flon;

  Serial.print("     ");
  Serial.print(lati, 8);
  Serial.print(" ");
  Serial.print(longi, 8);
  smartdelay(0);
  //cLatitude = flat;
  //cLongitude = flon;
//  print_float(getCurrentLatitude(), TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);
//  print_float(getCurrentLongitude(), TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);

//  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
//  print_date(gps);
//  print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
//  print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
//  print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
//  print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
//  print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
//  print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
//  print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);
//
//  gps.stats(&chars, &sentences, &failed);
//  print_int(chars, 0xFFFFFFFF, 6);
//  print_int(sentences, 0xFFFFFFFF, 10);
//  print_int(failed, 0xFFFFFFFF, 9);

  Serial.println();

  smartdelay(1000);
}

static void smartdelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (Serial1.available())
      gps.encode(Serial1.read());
  } while (millis() - start < ms);
}

static void print_float(float val, float invalid, int len, int prec)
{
  if (val == invalid)
  {
    while (len-- > 1)
      Serial.print('*');
    Serial.print(' ');
  }
  else
  {
    Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1); // . and -
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
      Serial.print(' ');
  }
  smartdelay(0);
}

/*
    If data is invalid, print out *******
    otherwise print out buffer
*/
static void print_int(unsigned long val, unsigned long invalid, int len)
{
  char sz[32];
  if (val == invalid)
    strcpy(sz, "*******");
  else
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  smartdelay(0);
}

static void print_date(TinyGPS &gps)
{
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned long age;
  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  if (age == TinyGPS::GPS_INVALID_AGE)
    Serial.print("********** ******** ");
  else
  {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ",
        month, day, year, hour, minute, second);
    Serial.print(sz);
  }
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  smartdelay(0);
}

static void print_str(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
  smartdelay(0);
}

You have smartdelay(1000); in loop().

Also, you're not going to be able to move much data at 4800 baud. You may be limited in terms of the GPS update rate by that baud-rate.

More details please. Are you using an arduino mega or an uno or what? are you using the software serial or using 2 hardware serials? What GPS device are you using? and what do you mean by locks when stationary?

Sorry, Missed the fact you're using a Due in the tags.

I assume you're using TinyGPS which I sourced from https://github.com/mikalhart/TinyGPS
I've recently done a similar thing - just trying to get the gps to work and give me as much data as possible.
The code I used to do this is here:
#include "TinyGPS.h"

#define GPS_BAUD 115200
#define PC_BAUD 115200

TinyGPS gps;

int led1 = 13;

long lat, lon;

unsigned long fix_age, time, date, speed, course;

unsigned long chars;
unsigned short sentences, failed_checksum;

void setup()
{
  pinMode(led1, OUTPUT);
  Serial1.begin(GPS_BAUD);
  Serial.begin(PC_BAUD);
  Serial1.println("");
  Serial1.println("Initializing");
  Serial1.println("");
  digitalWrite(led1, HIGH);
  delay(2000);
  digitalWrite(led1, LOW);
  delay(500);
}

void loop()
{
  while(Serial1.available()){
    if(gps.encode(Serial1.read())){
      digitalWrite(led1, HIGH);
      gps.get_position(&lat, &lon, &fix_age);
      gps.get_datetime(&date, &time);
      Serial1.println("");
      Serial1.println("Lat: " + String(lat));
      Serial1.println("Lon: " + String(lon));
      delay(3000);
      gps.stats(&chars, &sentences, &failed_checksum);
      Serial1.println("Chars: " + String(chars));
      Serial1.println("Sents: " + String(sentences));
      delay(1000);
      Serial1.println("Fails: " + String(failed_checksum));
      Serial1.println("");
      delay(1000);
    }
    Serial1.print(".");
  }
}

I was using an Arduino Mega 2560, but I think you have the same Serial ports on your Due. I connected the TX pin of my GPS ( can't remember the model but I think it was a 10Hz version of this: https://www.sparkfun.com/products/9891 ) to Serial1's RX and I used a small serial 2 row LCD display to output which was connected to Serial1's TX, hence I was using serial1 for both transmitting and receiving. If you remove the delays from the code above the data is read and then written back as fast as possible and while I never measured how many fixes I was seeing per second I'm fairly sure there were at least 5.
The code you want is probably something like this:
#include "TinyGPS.h"

#define GPS_BAUD 115200
#define PC_BAUD 115200

TinyGPS gps;

int led1 = 13;

long lat, lon;

unsigned long fix_age, time, date, speed, course;

unsigned long chars;
unsigned short sentences, failed_checksum;

void setup()
{
  pinMode(led1, OUTPUT);
  Serial1.begin(GPS_BAUD);
  Serial.begin(PC_BAUD);
  Serial1.println("");
  Serial1.println("Initializing");
  Serial1.println("");
  digitalWrite(led1, HIGH);
  delay(2000);
  digitalWrite(led1, LOW);
  delay(500);
}

void loop()
{
  while(Serial1.available()){
    if(gps.encode(Serial1.read())){
      digitalWrite(led1, HIGH);
      gps.get_position(&lat, &lon, &fix_age);
      gps.get_datetime(&date, &time);
      Serial.print("    ");
      Serial.print(lat);
      Serial.print(" ");
      Serial.print(long);
    }
  }
}

As commented by @connor-wolf above you will probably need to change the baud-rate of your communications up because otherwise you the limit of the amount of information you can send/receive per second is probably too low. The baud rate must also match the baud rate of your GPS device. Some GPS devices have an adjustable baud rate.

A quick google turned up an average NMEA sentence length of 60 bytes and if I recall correctly you may have 2 or 3 sentences to each fix? (I think the extra sentences contain extra info like satellite counts, and stuff). So assume you need 180 bytes per fix and you want at least 5 fixes per second that would be 900 bytes. In baud that is 900x8 = 7200. So assuming my estimations above are accurate or overestimated then you have enough bandwidth.
I'm not sure however if the Micro transmits/receives over serial while running the other instructions in your code - I would assume not to be safe but it's worth some research. Therefore you have to account for the time the micro spends transmitting and interpreting the data as time in the second that it can't spend receiving the data. Therefore I would suggest that doubling or even tripling the data rate would be a good idea. (as you can see from my example I just set it to as high as the GPS would go.)
Anyway. I hope all that helps.
P.S please forgive if I've used the wrong terminology for fixes/sentences or whatever


text:
IR controlled light dimmer
I am doing a project on Arduino controlled light dimmer circuit...
I have a separate circuit for zero crossing detector and IR receiver but when I am combining both of them in arduino then my IR receiver stops working and zero crossing interrupt is not detected...
Here is my code:
#include <IRremote.h>
int RECEIVE_PIN = 8;
int AC_LOAD = 3;
int dimming;

IRrecv irrecv(RECEIVE_PIN);
decode_results results;

void setup()
{
    Serial.begin(9600);
    irrecv.enableIRIn();
    pinMode(AC_LOAD, OUTPUT);
    attachInterrupt(0, zero_crosss_int, RISING);
}

void zero_crosss_int()
{
    int dimtime = 75*dimming;
    delayMicroseconds(dimtime);    // Off cycle
    digitalWrite(AC_LOAD, HIGH);   // triac firing
    delayMicroseconds(10);         // triac On propogation delay
    digitalWrite(AC_LOAD, LOW);    // triac Off
}

void loop()
{
    if (irrecv.decode(&results))
    {
        Serial.print("0x");
        Serial.println(
        results.value, HEX);
        delay(50);

        if(results.value==0xE13DDA28)
            dimming = 120;

        if(results.value==0xAD586662)
            dimming = 80;

        if(results.value==0x273009C4)
            dimming = 20;

        irrecv.resume();
    }
}

Can anyone help me with this????

Need to provide some code, libraries and description of the IO used. It is likely that is a conflict.

Add links to the circuit diagram and spec sheet of both zero crossing detector and IR-receiver.

Without looking at the code, it seems like you have a loop somewhere and the code can't get pass that loop at the right time so an event isn't registered by the code and it's "missed."

Can you clarify the sentence "my IR receiver stops working and zero crossing interrupt is not detected": how do you know that concretely, did you add some traces to show what happens?

www.instructables.com/id/Arduino-controlled-light-dimmer-The-circuit..study this instructable, I successfully implement IR remote and Light dimming by following his second option which doesn't use interrupt..

What you've described (without source code and/or a circuit diagram) sounds like you'll probably be using interrupts at least for the zero crossing detection. And probably the IR receiver too. The IR receiver is going to be your problem since the zero crossing is a very quick flag set and you're out of the interrupt.
On the other hand, the IR detection is going to take time, and if you're doing THAT in an interrupt you're going to be missing dozens of crossings.
To mix the two you can leave the zero crossing in it's own interrupt, but you're probably better off handling the IR in the loop via a state machine.
Since you say that neither are working, I'm going to hazard a guess and you're using the same interrupt or badly implemented them (possibly a timer and interrupt clash) and until you post some code people here aren't going to be able to help you any more than that.

One important problem in your code is concurrent access to dimming variable. That may not be the only problem you have though.
Indeed, deeming is accessed for writing in your loop(), but it can be simultaneously read by zero_crosss_int() function which is executed in interruption mode because it was registered as such with attachInterrupt().
Since deeeming is an int (2 bytes on AVR MCU), it cannot be read or written in just one clock-cycle (AVR is an 8-bit technology). Hence it is perfectly possible that loop() gets interrupted by zero_crosss_int() just in the middle of writing dimming, eg in:
dimming = 120;

Note that, in theory, concurrent acces in your case should not be an issue as long as dimming is never greater than 255.
How do you protect access to dimming variable?
You can do the following:
int dimming() {
    cli();
    int temp = dimming;
    sei();
}

void dimming(int value) {
    cli();
    dimming = value;
    sei();
}

And replace any direct access to the dimming variable in your code with a call to one of these functions above.
Will that fix your problem?
Maybe not unfortunately, as it is probable that mixing IRremote.h with your code brings other conflicts.
But at least, this will solve a dormant bug in your code, a complex bug that may catch you some day.

It seems that the jaydeep might have been building my circuit and  used the provided code: http://www.instructables.com/id/Arduino-controlled-light-dimmer-The-circuit/step4/Arduino-controlled-light-dimmer-The-software/
so obviously this problem has my interest.
With regard to the 'dimming' variable, that will not go beyond 128 so I might as well have used 'byte'  to define it.
The IR remote library is I presume that of Ken Shirrif and that one uses the Timer2 interrupt. In principle, combining those two interrupts shouldnt necessarily cause a problem as I have done so as well (in using the timer interrupt rather than 'delay to trigger the TRIAC).
But in that case the entire timer interrupt was handled within the period of  the mains wavelength (100 or 83 ms depending on frequency).
I don’t think the access to the 'dimming' variable -as jfpoilpret mentions- is the problem (though he makes some sound remarks), as that will just remain as is for a specific  light level.
The problem -as  is also suggested above- might well be in the fact that the IR receive takes too long.
So... disregarding interrupt priority for a moment, if the code is hanging around in the timer interrupt routine and there is a zerocrossing, that won't be detected, or, if the code is just doing a zero crossing detection, the timer is  screwed up.
In comes interrupt priority: The external interrupt has the highest priority (other than reset). So.. when  the IR receive routine is busy in the Timer service routine and a zerocrossing arrives, it will be taken out of that routine, zerocrossing will be handled and ideally, it should continue with the timer routine again.
However, your remote has no idea what is going on in the Arduino and some of the code sent will be missed.
all of this shouldn’t need to be a problem if the external interrupt was fast, but as most of the waiting is actually done within this interrupt, it could take up to almost 10mS/8.3mS (when 'dimming' approaches 128).
Solution?
Well, I can't say much about the Timer2 interrupts in Ken's library, But on 'my side' of the software, what could be done is to shorten the external interrupt by removing the delays and use (yet another) timer interrupt.
Ken uses Timer2, so this would have to be timer1.
So, whenever there is a zerocross, there is no waiting in a delay, but it will be handled by timer1
An example is given in Step 6 of my instructable. There is no guarantee this will work but there is a good chance
Let me just point out that the basic  program I supplied was just given as an example, It uses much computer time in waiting and therefore isn’t the best to combine with other actions of the processor.


text:
FTDI Cable to bypass USB for Arduino (Blend Micro) Programming
I bought a Blend Micro (an Arduino Micro with Bluetooth) a few months ago, and after my first experimentation with uploading the Blink sketch something went wrong with the USB connection--it would supply power, but no computer (Windows, OS X or Linux) would show it as a USB device, and Windows would complain that the device was somehow damaged. Anyway, when I plug the board in, it still boots up and runs "Blink" so I'd like to try to still use it.
I have a USB-to-FTDI cable, and it would seem fairly straight-forward to use that, but I'm a little uncertain to the appropriate wiring and whether I would need to tell the Arduino software somehow that I was using FTDI.
I can figure out these connections: (I think)

black to ground
red to 5V (VIN?)
orange to RX
yellow to TX

What about green and brown? Do one of those go to RST (Brown?) and MOSI (Green?)
I figured I would ask before accidentally burning something out.

A little more information as I've been Googling and reading. First of all, my FTDI cable is a Digi TTL-232R-3V3, so the wire colors are: black=GND, brown=CTS, red=VCC, orange=TX, yellow=RX, red=RTS. Looking at an Adafruit article I wonder if I'm out-of-luck in the Blend Micro being Leonardo-based and having USB managed inside the chip rather than using USB-to-serial on the board.

You could try re-flashing the bootloader using another arduino as ISP.

I'm afraid (a) that's a bit beyond by beginning experience, and (b) I think that would require on a Micro those six headers in the middle of the board, but those aren't exposed in the blend micro because the space is used by the Bluetooth chip. If booloader re-flashing can be done using the standard pinouts along the edges, can someone point me to a reference as a starting point?

You should be able to recover a Leonard-type board by putting it into DFU mode.

The six pin header is just for convenience. The same pins are also broken out on the side.


text:
Want to add an LCD display screen for the output motor
I want add an LCD display screen at output motor. When the motor runs the LCD display show like "motor 1 run forward" and "motor 1 run reverse". I want it display for all motor but I don't know how code using arduino using 16x2 LCD display screen.
int motor_forward1 = 7;
int motor_reverse1 = 6;
int motor_forward2 = 5;
int motor_reverse2 = 4;
int motor_forward3 = 3;
int motor_reverse3 = 2;
int sensor1 = 13;
int sensor2 = 12;

 void setup()
{

   pinMode(motor_forward1, OUTPUT);
   pinMode(motor_reverse1, OUTPUT);
   pinMode(motor_forward2, OUTPUT);
   pinMode(motor_reverse2, OUTPUT);
   pinMode(motor_forward3, OUTPUT);
   pinMode(motor_reverse3, OUTPUT);
   pinMode(sensor1, INPUT);
   pinMode(sensor2, INPUT);
 }

 void loop()
 {
   if (digitalRead(13) == HIGH)
   {
     print
     digitalWrite(motor_forward1,1);
     digitalWrite(motor_reverse1,0);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,1);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,0);
     delay(1000);
   }
   else if (digitalRead(12) == HIGH)
   {
     digitalWrite(motor_forward2,1);
     digitalWrite(motor_reverse2,0);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,1);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,0);
     delay(1000);
   }
   else
   {
     digitalWrite(motor_forward3,1);
     digitalWrite(motor_reverse3,0);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,1);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,0);
     delay(1000);
   }
   delay(5000);
 }

Other than the LiquidCrystal library?

From this instructable:
// include the library code:
#include <LiquidCrystal.h>

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

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print(" **Text for line 1 of LCD**");
  lcd.setCursor(0, 1);
  lcd.print(" **Text for line 2 of LCD**");
  // THE REST OF YOUR SETUP
}

void loop() {
    if (digitalRead(13) == HIGH) {
        // I assume this is the motor going forward
        lcd.print("motor 1 run forward");
    }
}

"Install" is a bit facetious though, since it comes with the IDE these days.

Wasn't aware of that :)

@circuitBurn Thanks for your code. But I have used arduino pin 5,4,3 and 2. need connect parallel to LCD screen?


text:
Potentiometer won't work
I'm trying to get the potentiometer seen at the top left of the photo to work, essentially as a dimmer. I've managed to upload the Arduino sketch, but it isn't working. Any help would be greatly appreciated!
NB: I have little-to-no electronics experience so my understanding of jargon is limited.
Thanks!
/*
 SENSOR_LIGHTS: Potentiometer >> LED (Single Channel Script)

 This example dims light levels using an LED on pin 11
 and a potentiometer on A0.

 Created by Ryan Achten | SOMA | somavisions.com

 This example code is in the public domain.
 */

int potentLevel;
int ledLevel;

//*************************CHECK*****************************

int led = 11;           // the pin that the LED is attached to
int inputPin = A0;      // the pin that the potentiometer is attached to

//*************************CALIBRATE*************************

const int numReadings = 1;  //change this to alter the number of values to be averaged
int potentMin = 280;
int potentMax = 700;        //maximum output from potentiometer
int loopDelay = 100;       //delay time between loops. Too low may cause overclocking
//                            while too high may cause delayed sensor response

//***********************************************************

int potentAve = 0;
int readings[numReadings];
int index = 0;
int total = 0;

// the setup routine runs once when you press reset:
void setup()  {

  //*************************POTENT >> LED SETUP CODE*************************

  Serial.begin(9600);

  pinMode(led, OUTPUT);

  //***************************SMOOTH SETUP CODE*****************************
  // initialise all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading++)
    readings[thisReading] = 0;

}

//****************************SMOOTH LOOP CODE****************************

void loop()  {

  total= total - readings[index];
  readings[index] = analogRead(inputPin);
  total= total + readings[index];
  index = index + 1;

  if (index >= numReadings)
    index = 0;

  potentAve = total / numReadings;
  Serial.print("Average Potentiometer Readings: ");
  Serial.println(potentAve);

  //*************************POTENT >> LED LOOP CODE*************************

  ledLevel = map(potentAve, potentMin, potentMax, 0, 255);
  Serial.print("LED Level: ");
  Serial.println(ledLevel, DEC);
  analogWrite(led, ledLevel);

  Serial.println();
  delay(loopDelay);

}

According to your schematic, it seems that both the red and the blue wire of the potentiometer are connected to GND? If so, this will never work. What does your Serial output tell for "Average Potentiometer Readings"?

Yes, this was one problem! I'd put it in GND instead of 5V by accident. Thanks for that!

Assuming the brown board in your drawing is stripboard, I have to as the question:
What is this?

If those five wires in that column are all ground, that link is basically short circuiting your MOSFET via the green wire next to it, thus rendering your whole circuit pointless.  The LEDs will just be on full brightness permanently since the current just flows from the input power, through the LED strip, through the red/white wire, through that little white link wire, then through the green/white and/or the brown/white wires to ground.

It was a wire I was using to replace a resistor, because some classmates found that getting rid of the resistor meant that the LED strip would go all the way off, which they don't otherwise. I've given up on that and put a resistor in, and now it works. Thanks for your help!


text:
Detect if laptop is on or not?
How would I safely connect an Arduino so that it can detect if a laptop is on or off?
The Arduino would be powered separately by a normal USB charger, since it needs to be turned on even when the laptop is turned off. So I'm thinking I can connect an input on the Arduino to one of the USB ports on the laptop somehow, but how do I do this safely?
Even if I play it safe and connect a current-limiting resistor between the USB voltage and input pin, and perhaps a voltage divider, is there still a problem with connecting one device to another like this? I'm thinking that since each has its own power supply from mains, could there potentially be a problem if I connect the USB port of the laptop to a pin on the Arduino?
Do need to use an optocoupler or relay between them? Or is there an even better way of doing this that I didn't think of?

do you know that there is 5 V on USB pim if the laptop is on, and there is no 5 V if the laptop is 'off'?

@Juraj I haven't tested it thoroughly, but nothing I connect to the USB seems to have any power when the laptop is off, so I would think that the 5V is off?

By the way, consider my cheap solution. A sad part of these StackExchange forums is that people "downvote" when the don't like what you offered, Those downvotes often have  nothing to do with actual measurable data.

If your chosen power supply is of a good quality and provides proper ground isolation then it shouldn't be a problem to connect the grounds of the two systems together.
However, since there are so many bad power supplies available on the internet (and even some "good" power supplies are somewhat iffy when it comes to grounding) it is safest to hedge your bets and add your own galvanic isolation.
The simplest method is to use an opto-isolator.  Use the +5V and GND from your computer's USB port (assuming it's not an always-on charging port - look for a lightning bolt symbol) along with a resistor (470Ω - 1kΩ is good) to drive the LED side of the opto-isolator. The other side then acts as a button to the Arduino:

simulate this circuit – Schematic created using CircuitLab
In this arrangement your input will be LOW when the PC is on. Also R2 could be replaced by the internal pullup of the GPIO pin (pinMode(PIN, INPUT_PULLUP);)
As I say, this most likely won't be strictly necessary, but for the minimal cost of an opto-isolator it's silly not to add that extra layer of protection. After all, an opto-isolator is cheaper than a new Arduino or (heaven forbid) a new laptop.

I don't see any problems connecting the them together like you described.
Make sure not to forget to also connect the USB ground to the Arduino ground, so the electrons have a path to go back.
Adding a current limiting resistor is advisable, for the case that the Arduino isn't powered, but the laptop is. Resistor divider is only needed for Arduino's that run on 3.3V.

The wall-wart type USB chargers are always double insulated - you'll typically see the square within a square symbol for European markets, though one for the US market alone may not have that marking.
That means that the secondary side is free to float, and can be safely connected to the ground connection of the laptop - whose power supply will typically also be double insulated.
That means you can just connect the 5V USB output to an input on the Arduino - put a high enough current limiting resistor in to allow for differences in voltages - especially in the case that the laptop output is on when the Arduino supply is off, to avoid the input feeding the Arduino through the protection diodes.
You can use an analog input, but if you're only looking for an on/off indication, a digital interpretation would work.
Check the output of the USB socket on the laptop - some are intended to remain live for charging accessories when the laptop is powered but not on. On one of my laptops all the ports are live like this and there's nothing that indicates this.

"double insulated" has nothing whatsoever to do with what is safe or not to do with ground. It is purely to do with the way the physical device is insulated. You are thinking of "galvanic isolation" which is a completely different thing.

Double insulation to UL1097 removes the requirement that the secondary circuit, considered accessible dead metal, be grounded - in fact it forbids it, and so ensures that the galvanic isolation afforded by the separation of the windings on the flyback inductor, and the creepage spacing of the board it is attached to is not compromised by it being connected to any point of the supply that would cause a ground loop to exist when connected to other equipment, grounded or not.

You're confusing ground "earth" with ground "0v reference point in a DC circuit".

No, I'm not. Whether it's safe to connect the GND of the laptop USB port to the GND of the Arduino's supply depends on there being no other connections to both of those that could hold them at different potentials, and the connection to the supply earth through both power supplies could do that. UL unfortunately uses the term "grounding" to mean earthing in a lot of places. https://en.wikipedia.org/wiki/Ground_loop_(electricity)

What about through the Y capacitor...? The leakage current ("touch current") could be fatal to one or other device...

Wouldn't be an issue if the Arduino were designed properly. However they decided (incorrectly) connect the USB shield direct to ground at the device. Fools! There should have been a 1M (ish) ground balancing resistor in there to gently equalise the ground potential differences while you plug the cable in. That's why some devices spark when you plug usb in.

The only problems are that (a) the Laptop USB outputs 5V, and the arduino input should not exceed 3.3, and (b) when the Laptop is no longer powered, the 5V pin on its USB no longer has a defined state, and could theoretically spike.
Here's a simple and cheap way to do this with passives. The diode isolates the USB from any "back" voltage. The USB 5V is measured across the resistor, and I'd place a capacitor there to to absorb any voltage spikes from the laptop when it loses power. Finally, the second resistor also indirectly protects the digital input and acts like a voltage converter, between the 5V (4.5 after the diode) and the 3.3V the arduino wants to see. The over-voltage will simply be routed to ground via the chips internal protection diodes, and the current will be limited to about 120 microamps ( 4.5- 3.3 ) / 10K.
You could use an opto isolator, but this is a cheap solution that will work. You will have to share ground between the laptop's USB and your arduino (not shown in the diagram). That will not be an issue however. Especially considering all power adapters offer significant line-to-load isolation. By the way, the 1uF capacitor can be decreased to 100nF or less, depending on how quickly you want to respond to the power loss.

simulate this circuit – Schematic created using CircuitLab

What makes you think an Arduino has 3.3v logic?

Some are 5, some or 3.3. The OP didn't say.
https://www.arduino.cc/reference/en/language/variables/constants/constants/

99% are 5v. You chose the wrong default voltage.

Either way, the circuit show will work.


text:
How can I tell the resistance of an internal pull-up resistor?
I have a SparkFun ESP8266 Thing Dev board, to which I want to perform a digitalRead() on one of the GPIO ports. I'm using D15, and I'm configuring it for input like this
pinMode(15, INPUT_PULLUP);

It does seem to work as intended, and I am able to pull it down by connecting it to ground via a 4.7kΩ resistor.
But how do I know what the actual "correct" resistor would be? I can't find any specs for the internal pullup resistor online. On a related note, I first tried using D0, but it didn't seem to have an internal pullup resistor, since even using INPUT_PULLUP didn't turn it on.
Perhaps there are specs online and I'm just not able to find them, but is there any other way (measuring?) to find out which pins will work with INPUT_PULLUP and if so, what their internal resistance is?

What makes you believe that you need a resistor at all?

You may find this edifying though: https://majenko.co.uk/blog/measuring-arduino-internal-pull-resistors

Internal pullup resistor only gives the pin a definite input value (HIGH) if it is floating. If the pin is connected to ground then it will read LOW, regardless of whether a pullup resistor is used or not.

@gandalf61 Won't that depend on the ratio between the pullup and pulldown resistors? Of course if it's connected directly to ground, then it would definitely be low...

@Majenko Hmm... is it safe to connect a GPIO input directly to +5V or ground, without any resistor? Won't it draw an unnecessarily high current, and/or risk damaging something in the device?

D0 is io 16. it has internal pulldown. I know it from the esp8266 Arduino package online documentation

@Majenko I guess I got a bit worried about connecting anything directly to the pins since some seem to be used for various things, and some (at least the internal LED, D5) seem to be inverted (setting it to HIGH will turn off the LED, and LOW turns it on)... on the normal Arduino things seem more straightforward.

You can only do damage if the pin is set to output. When input there is nothing to damage. It is common to add a very small (100r or so) resistor in series with the output to protect it just in case.

@Juraj Hmm, by D0 I mean the pin labeled 0 on the board, and referred to as 0 and D0 in the pin overview image from SparkFun. Where exactly do you get 16 from? Either way, I can't seem to get that pin to work as expected, it might be because the docs say it's "Used in reset"....

right, io 0 is a boot configuration pin. it should have an external pull-up on board (NodeMcu and Wemos/Lolin have Dx labeled pins. you confused me with the D)

@MagnusW directly to +5V on an ESP8266, I'd limit that to +3.3V - as much as I've read that the GPIO are "5v tolerant" I'd stick to 3.3

io 0 and io 15 are with io 2 boot configuration pins of the esp8266. esp8266 dev boards have external pull-up on io 0 and io 2 and pull-down on io 15.

Thanks. Where can I find this information? The Hookup Guide I found doesn't really say much about pins 0, 4 and 15... and SparkFuns own examples seem to mostly use pin 12 as INPUT_PULLUP, which is the only one I got it to work with.

the best source is Espressif's site (esp8266_hardware_design_guidelines_en.pdf). but the information about boot pins is on many web pages about esp8266

Hmm, now I'm feeling a bit stupid... when I say pinMode(12, INPUT) - does the 12 refer to GPIO12 or to "pin 12", which in the Espressif Hardware Design Guidelines means GPIO13? It gets even more confusing when the SparkFun pin guideline refers to pin 12 as D12... Which one of all of these am I really interested in when calling pinMode()??

in Sparkfun Thing the labels and the pin numbers (even if prefixed with D) correspond to gpio numbers used by Espressif. (NodeMcu and Wemos/Lolin boards have Dx comstants and labels)

"The value of internal (built-in) pull-up resistor is between 30Kohm and 100Kohm."
Source: https://bbs.espressif.com/viewtopic.php?t=1079#p4097

did you read the accepted answer?


text:
How do I connect an accelerometer (GY-521) to a SparkFun Thing Dev (ESP8266)?
All of the wiring diagrams I've found for wiring up a GY-521 accelerometer to an Arduino have looked something like this:

I've read in several places that it needs to be connected to A4 and A5. I want to connect one to a SparkFun ThingDev, which unfortunately only has a single analog input:

Is this possible?
I only need it for a very simple application (finding out if a machine is vibrating or not).

A4 and A5 on the Arduino double as the I2C pins SDA and SCL.  You are communicating with I2C, not analog.
The ESP8266 doesn't have I2C in hardware, but there is a software-based I2C implementation which can work on any pins.  The pinout you show has I2C labeled on pins 2 and 14. While you can use those you could use any two pins of your choosing.
Note that I2C on the ESP8266 has a slightly different begin function:
Wire.begin(2, 14);

That is where the pins you want to use are assigned - in this case, pin 2 for SDA and pin 14 for SCL.

default Wire pins in pins_arduino.h for this Thing are 2 and 14. so Wire.begin() is ok