text:
Integrating Shift Registers into 7 Segment LED Circuit
I'm trying to implement a shift register(s) into my circuitry and program to control two seven segment LEDs that would count up from 00 - 99. So far I have a fairly straightforward code (at least, I think. It's my first time experimenting with creating my own void functions) that controls the 7 segs in this manner, but I end up using every single digital pin on my Uno. Here it is:
const int led1a = 13;
const int led1b = 12;
const int led1c = 11;
const int led1d = 10;
const int led1e = 9;
const int led1f = 8;
const int led1g = 7;
const int led2a = 6;
const int led2b = 5;
const int led2c = 4;
const int led2d = 3;
const int led2e = 2;
const int led2f = 1;
const int led2g = 0;

void setup() {
    pinMode(led1a, OUTPUT);
    pinMode(led1b, OUTPUT);
    pinMode(led1c, OUTPUT);
    pinMode(led1d, OUTPUT);
    pinMode(led1e, OUTPUT);
    pinMode(led1f, OUTPUT);
    pinMode(led1g, OUTPUT);
    pinMode(led2a, OUTPUT);
    pinMode(led2b, OUTPUT);
    pinMode(led2c, OUTPUT);
    pinMode(led2d, OUTPUT);
    pinMode(led2e, OUTPUT);
    pinMode(led2f, OUTPUT);
    pinMode(led2g, OUTPUT);
}

void loop () {
    led1_0();
    led2_run();
    led1_1();
    led2_run();
    led1_2();
    led2_run();
    led1_3();
    led2_run();
    led1_4();
    led2_run();
    led1_5();
    led2_run();
    led1_6();
    led2_run();
    led1_7();
    led2_run();
    led1_8();
    led2_run();
    led1_9();
    led2_run();
}

void led1_0() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1e, HIGH);
    digitalWrite(led1g, HIGH);
    digitalWrite(led1f, LOW);
}
void led1_1() {
    digitalWrite(led1a, LOW);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, LOW);
    digitalWrite(led1e, LOW);
    digitalWrite(led1f, LOW);
    digitalWrite(led1g, LOW);
}
void led1_2() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1e, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1c, LOW);
    digitalWrite(led1g, LOW);
}
void led1_3() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1e, LOW);
    digitalWrite(led1g, LOW);
}
void led1_4() {
    digitalWrite(led1a, LOW);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1g, HIGH);
    digitalWrite(led1e, LOW);
    digitalWrite(led1d, LOW);
}
void led1_5() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1g, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1b, LOW);
    digitalWrite(led1e, LOW);
}
void led1_6() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1g, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1e, HIGH);
    digitalWrite(led1b, LOW);
}
void led1_7() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, LOW);
    digitalWrite(led1e, LOW);
    digitalWrite(led1f, LOW);
    digitalWrite(led1g, LOW);
}
void led1_8() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1e, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1g, HIGH);
}
void led1_9() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1g, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1e, LOW);
}
void led2_0() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2e, HIGH);
    digitalWrite(led2g, HIGH);
    digitalWrite(led2f, LOW);
}
void led2_1() {
    digitalWrite(led2a, LOW);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, LOW);
    digitalWrite(led2e, LOW);
    digitalWrite(led2f, LOW);
    digitalWrite(led2g, LOW);
}
void led2_2() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2e, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2c, LOW);
    digitalWrite(led2g, LOW);
}
void led2_3() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2e, LOW);
    digitalWrite(led2g, LOW);
}
void led2_4() {
    digitalWrite(led2a, LOW);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2g, HIGH);
    digitalWrite(led2e, LOW);
    digitalWrite(led2d, LOW);
}
void led2_5() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2g, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2b, LOW);
    digitalWrite(led2e, LOW);
}
void led2_6() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2g, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2e, HIGH);
    digitalWrite(led2b, LOW);
}
void led2_7() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, LOW);
    digitalWrite(led2e, LOW);
    digitalWrite(led2f, LOW);
    digitalWrite(led2g, LOW);
}
void led2_8() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2e, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2g, HIGH);
}
void led2_9() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2g, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2e, LOW);
}
void led2_run() {
    led2_0();
    delay(1000);
    led2_1();
    delay(1000);
    led2_2();
    delay(1000);
    led2_3();
    delay(1000);
    led2_4();
    delay(1000);
    led2_5();
    delay(1000);
    led2_6();
    delay(1000);
    led2_7();
    delay(1000);
    led2_8();
    delay(1000);
    led2_9();
    delay(1000);
}

So how would I reduce the amount of pins used while still keeping functionality? I have two 74HC595N shift registers at my disposal.
Thanks!

I have done exactly this, to great effect.
int clockPin = 4;
int dataPin  = 2;
int oePin    = 3;

// Here are the digits from 0 to 9, as bitmaps.
// You will need to work out which segments are which,
// according to your wiring, and make your own.
unsigned char digitmaps[]={0x7b,0x11,0xe3,0xb3,0x99,0xba,0xfa,0x13,0xfb,0xbb};

void setup() {
  pinMode(clockPin,OUTPUT);
  pinMode(dataPin,OUTPUT);
  pinMode(oePin,OUTPUT);
}

void sendnumber(unsigned int number, int oePin,int dataPin,int clockPin) {
   digitalWrite(oePin,LOW);
   shiftOut(dataPin,clockPin,MSBFIRST, digitmaps[(number/10)%10]);
   shiftOut(dataPin,clockPin,MSBFIRST, digitmaps[number%10]);
   digitalWrite(oePin,HIGH);
 }

void loop() {
  for (int i=0; i<100; i++) {
    sendnumber(i,oePin,dataPin,clockPin);
    delay(1000);
  }
 }

The crux of the matter is shiftOut, which shifts 8 bits out the dataPin, toggling the clockPin as it goes, high bit first (MSBFIRST), looking up the pattern in the table. dataPin goes to serial in on the FIRST shift register, clockpin to BOTH clocks, oePin to BOTH OE and another one, I think store register? Q7' or QH' (depending on your docs - it's the overflow pin) of the first goes to the serial in of the second, and +5v & GND, as per normal, and the 8 parallel out Q0-Q7 go to the pins on the 7-segment.
If there's anything unclear, or anything I've missed, let me know. My example shows 2 digits, but any number will work, up to the available power.
Things might be clearer if I convert the digitmaps to binary. The below compiles to the same thing as the one above.
unsigned char digitmaps[]={
   B01111011, // 0
   B00010001, // 1
   B11100011, // 2
   B10110011, // 3
   B10011001, // 4
   B10111010, // 5
   B11111010, // 6
   B00010011, // 7
   B11111011, // 8
   B10111011}; // 9

This is because, in my wiring, from left to right the bits represent in the 8 on my display: center,bottom left,bottom,right bottom,top left,decimal point/not used,top,right top. You can see that the digit "1" has 2 1's in it: the 4th (right bottom) and the last (right top). An 8 has all of the bits set to 1, except position 6 - because that's the decimal point. Send individual bits (e.g. B00010000) to see which segments shows up, make a map, and then combine them.

It looks like you may have a stray semicolon after your void sendnumber function, but other than that, it looks great! Thanks for this!

The code had a lot of other stuff in it, because obviously something that just counts to 99 repeatedly isn't that useful. I cut & paste bits, just quickly wrote the rest. Post edited to remove stray semicolon. I write in too many languages to keep them apart without a compiler to help me :)

Ahh, gotcha. Could you point me in the direction of a guide to learning how to express digits "as bitmaps" as you have done? I'm not finding any relevant answers online.

This is the same thing you are doing in your code, with 7 digitalWrite(ledXX, LOW);  statements, but do it all in one go. Try sending 1,2,4,8,16,32,64 and 128 to figure out which segment is which, then add them together - e.g. when you send a 1, it might light up the top-right segment, 16 might be the bottom right segment, so to display a 1, you can light both of these up  by sending 1+16=17. So, the number shown in my bitmap as 0x11 (the second one, as the first one is 0!), should be replaced by the number 3. I used hexadecimal as I am familiar with this; 0x11 is hexidecumal for 17.

You could also express the same number as binary - B00010001 - each 0 or 1 will represent one segment. Which segment is which depends on which pin on the chip you connect to which wire on the display.


text:
Measuring Time Between Inputs
I'm trying to measure the amount of time that has passed between every time a reed switch mounted on a wheel is activated to calculate the speed of a bike in miles per hour and display it on two 7 segment LEDs. This is what I have so far (without 7 seg code, as that works):
const int reed = A3;
float circumference;
float pi = 3.141592653589
unsigned long time0 = 0;
unsigned long time1;
unsigned long revolutionTime;

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

void loop() {
  circumference = (pi * 26); //26 = the diameter of the wheel
  int reedState = digitalRead(reed);
  if (reedState == HIGH) {
    time1 = millis();
    revolutionTime = (time1 - time0);
    time0 = time1;
    int mph = ((circumference / revolutionTime) * (3600000 / 63360)); //this is the conversion from inches/millisecond to miles/hour.
    Serial.println(mph);
    //And I'd print the result on the 7 segment displays here
  }
}

This code results in around 25 printed entries in the serial monitor from a single activation of the reed switch, all of which consist of randomly alternating values of either 0 or 4571.
Following each step of the code, I assume that the program would generate a garbage result for the first entry (because the time before the reed is activated for the first time could vary greatly), but that following entries would be the correct mph displayed on the 7 segment displays until the reed switch is activated again and a new mph is calculated.
So how would I go about modifying the code to get useful data?

Where is the debouncing?

@IgnacioVazquez-Abrams If I include a debouncing portion, would the Arduino still register every reed switch activation at high wheel speeds?

That depends. Do you expect the wheels to spin in excess of 10kRPM?

As an aside you may find the shock of cycling too great for the reed switch and might want to use a hall sensor instead.

I like to think I'm fast, but I'm no where near that fast. I'll look into adding in that debounce.
And what do you mean when you say "the shock of cycling?"

Not every bike ride is on smooth, even ground. Rough terrain may cause damage or spurious inputs.

Currently your code is not working, because Arduino is fast enough to check the closed switch state many times before it opens again, so before calculating a new speed value, you need to see LOW on the input.
Still, there are at least 2 better ways to do what you want.
pulseIn() - a function intended just for what you are trying to do: measuring lenght of a pulses. If your switch is active HIGH, you need to measure length of a LOW pulse:
unsigned long duration;
duration = pulseIn(reed, LOW);
// calculate speed basing on duration (in microseconds)

Keep in mind, that pulseIn() is a blocking function, so no code will be executed, until it receives the pulse. You can counter it bu specifying a timeout, after which, the program will continue.
External interrupts are an another approach. Interrupt handling routines are executed when a specified event occurs, no matter if the microcontroller is busy doing something else or not. They would guarantee, that you will not miss any pulse even if they would have frequency in order of kHz.
volatile unsigned long lastTime = 0;

void setup() {
    attachInterrupt(0, readTime, RISING);
}

void readTime() {
    unsigned long t = millis();
    // calculate speed basing on t - lastTime
    lastTime = t;
}

Interrupt handling routine should be as short as possible. Avoid using delays in it, doing Serial.print and other communications. Also, millis() and micros() will not increment during execution of interrupt handler.
Debouncing - even with above two methods, things may still not work properly. The most probable cause would be switch "bouncing". You can counter it by

software debouncing  - delaying after pulseIn() or ignoring interrupts for some period of time after first interrupt is detected
adding a small (10-100nF) capacitor at the input, that will act as a low-pass filter, cutting out short pulses
using not a reed switch, but a hall sensor with hysteresis

A: Use interrupts to detect the state change on the reed switch
B: Use a hall sensor instead of the reed, they do not suffer switch bounce
C: Use a debounce circuit, a 74HC14 with a small capacitor connected between ground and the input
Put a 4K7 resistor as pullup between VCC & the input
Put a 100 ohm resistor on the wire coming from the Reed, which is connected to GND on the other side
The 100 ohm prevents discharge damage to the contacts from the capacitor and suppresses RF interference
Ground all unused inputs and feed the output of the active channel to the Arduino
The 74HC series are 3v3 & 5V compatible, the 74HCT series is only 5V compatible but are more suited as level shifters from 3v3 signals to 5V output
D: use a software debounce routine

As the 74HC14 is an inverter, you can use a second one to invert the signal, then feed 2 inputs to the Arduino, this will make it easier to write 2 interrupt routines to detect the state changes and measure the time period between pulses

Your test if (reedState == HIGH) does not tell you when the reed
switch is activated, it tells you when it's active, which is not the
same. You should instead look at when the switch transitions from LOW
to HIGH, which means you also have to remember the last state.
For example (untested):
void loop() {
    static int lastReedState;
    static unsigned long lastTransition;
    int reedState = digitalRead(reed);

    // On a rising transition of the reed switch:
    if (reedState == HIGH && lastReedState == LOW) {

        // Compute time since last valid transition.
        unsigned long now = millis();
        unsigned long revolutionTime = now - lastTransition;

        // Debounce: this transition is valid only if enough time has
        // elapsed since the last valid one.
        if (revolutionTime > 20) {

            // Compute and report speed.
            int speed = circumference / revolutionTime;
            Serial.println(speed);

            // Remember this transition.
            lastTransition = now;
        }
    }

    // Remember last state.
    lastReedState = reedState;
}

This assumes circumference has already been calculated and has the
appropriate unit (miles⋅ms/h if you want the speed reported in mph).
Actually it could be a compile-time int constant (4641), which would
avoid having floating point calculations at run time.

Imagine your wheel rotating very slow ... imagine time was slowed down.  Imagine the magnet comes to the reed sensor and closes the switch.  You will now take a measurement.  The Ardunio code loop will end and immediately restart ... because time has been slowed (in our story), the wheel will have barely moved and AGAIN you will take another measurement because the reed switch is STILL closed because the magnet hasn't moved far enough.
I believe you need to change your logic such that after you detect the reed switch closing, you then need to detect that the reed switch is OPEN again ... before once more looking for the reed switch to close. Something like:
if (reedState == HIGH) {
   // do something
   while(digitalRead(reed) == HIGH) {
      // do nothing
   }
}

source: Stack Exchange

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

sort: votes


text:
Storing in a global variable using inline assembly
What I'm trying to do is pretty basic: I have a global variable and I'm trying to store some value in it (specifically, the SP_H and SP_L values).
The variable is an array of structs and I'm trying to access one of those structs.
This is what I am doing:
typedef struct_t { uint8_t sp_h, sp_l; } struct_t;

struct_t arr[MAX_STRUCTS];

void some_inline_assembly_function()
{
  volatile asm(

  // Determine where to store the new SP_H and SP_L register

  "lds r26, ???                \n\t" // <-- How do I store the address
                                            of arr[0].sp_h or arr[0].sp_l
                                            in the X registers (r26,27)
  "lds r27, ???                \n\t"

  // This part stores the stack pointer low and high byte indirectly
     using the X registers (r26,27), which is what I want.

  "in    r0, __SP_L__          \n\t"
  "st    x+, r0                \n\t"
  "in    r0, __SP_H__          \n\t"
  "st    x+, r0                \n\t"
  ::);
}

If this looks familiar, it is because it probably is. I'm trying to implement simple context switching (pushing the entire task context into the stack and retrieving another one). What I'm trying to accomplish is storing the current PC_H and PC_L to a global variable so that the "shceduler" knows where to start popping the registers and restore the context.
Yes, I know FreeRTOS does this. I need to know how to do this myself.
Thanks a bunch.

Did you try to just use arr in the assembly?

I've just seen people pop the registers onto the stack in a particular order, and then change the stack pointer(s) to another stack.

Probably a stupid idea, but why not write it in C, compile it, and run avr-objdump -S  against the elf file, and see how the C compiler does it.

The address you are looking for is a symbol known by the linker. Then
you can have the linker put the value of the symbol straight into your
code: no need to load from memory. In other words, you use the ldi
instruction to load the required address as an immediate value. You
should also reverse the order of the struct definition, since you are
storing SPL at the lowest address.
typedef struct { uint8_t sp_l, sp_h; } struct_t;

struct_t arr[MAX_STRUCTS];

void some_inline_assembly_function()
{
  asm volatile(
    // Determine where to store the new SP_H and SP_L register
    "ldi r26, lo8(arr)     \n\t"  // X is loaded with the symbol arr
    "ldi r27, hi8(arr)     \n\t"  // which is the address of arr[0].sp_l
    // Here you may want to add 2 * an array index.

    // This part stores the stack pointer low and high byte indirectly
    // using the X registers (r26,27), which is what I want.
    "in    r0, __SP_L__    \n\t"
    "st    x+, r0          \n\t"
    "in    r0, __SP_H__    \n\t"
    "st    x+, r0          \n\t"
  ::);
}

Notice the lo8() and hi8() assembler macros: they split the address
into low and high bytes. Actually the assembler translates them into
R_AVR_LO8_LDI and R_AVR_HI8_LDI relocations records, and the
linker does the real job.
Edit: I think I just realized why you were thinking of using lds
in the first place...
Instead of using array indices, you may want to access the array through
a pointer (declared struct_t *pointer). When programming in C or C++,
a pointer identifier behaves, for most purposes, just like an array
identifier. However, at the assembly level, using a pointer involves an
extra indirection, as you have to read the contents of the pointer from
RAM. In this case you would indeed be using lds instructions:
; Copy the global 'pointer' into the X pointer register.
lds r26, pointer    ; low byte
lds r27, pointer+1  ; high byte

As a side note, if you are programming in C++, then you have to declare
extern "C" any identifier that you want to use both in C++ and in
assembly. Otherwise the C++ compiler will
mangle its name and you
would need to use the mangled name in the assembly source.

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


text:
Can't you easily use "quadrature" incremental rotary encoders at 2X or 4X their number of "stops"?
I bought a 12-step "quadrature" incremental rotary encoder as an input device for a project I'm working on.
When I wrote the code to track "ticks" of rotation, I made it respond to any change in the "A" pin. As a result, I got 24 steps, not 12. They appear to be evenly spaced, and still correctly indicate clockwise or counter-clockwise rotation.
It occurs to me that if I track changes of state in both the "A" and "B" pins, as long as I reverse the logic for identifying clockwize vs. counterclockwise rotation, I could get a 48 step count from the same encoder.
Thus isn't it straightforward to get 2X or 4X the steps from a quadrature  rotary encoder simply by interpreting the signals differently?

would that still work correctly when starting and stopping? it would seem the direction could be ambiguous if only one pin changed...

No, with quadrature encoding you can tell the direction based on one pin state change and the state of the other pin.

please clarify what this means got 24 steps

Yes, you are correct. You can track 48 different positions per rotation.

@Gerben, can you submit an answer (with a little more detail) so I can accept it? my naive code using digitalRead of the 2 pins is missing positions unless I rotate the encoder slowly. I found some code online this morning that uses pin interrupts. I gather that's the way to go?

My "answer" is the same as Jose's, just more to the point. Avoid using digitalRead, as it's pretty slow. Using interrupts would be the way to go. Depending on the amount of contact bounce, you might need to add some debouncing hardware (RC filter), so your software doesn't get flooded with interrupts, and miss some change.

Ok, I'll rewrite my code using interrupts and port registers. It's been several years since I dealt with pin reading using port registers, so I'll have to go do some digging. I've also never done interrupt handlers on Arduino before. I take it the ISR has to be a global function? (in the rest of my project I'm using C++ objects for things like sensor handles, so would prefer it to be an instance method, but I'm guessing nope.)

Maybe the encoder you got is being incorrectly described?  I have a handful of the little thru-hole rotary encoders popular in Arduino module kits and they have 12 detents for one rotation, but they are actually 48-position-per-rotation encoders. When I use them, I have to divide the tick count by 4 to have one physical "click" count as one tick in my code.
For some of these, it's fairly straightforward to open them up and remove the detent, and thus get a higher-resolution, smooth spinning encoder. Unfortunately, others, such as the ones I have, are difficult to open without destroying them, and since they physically snap to the detents, aren't usable at the proper resolution.
The method you note, where you track the high/low change in either direction of both outputs is the normal way to read quadrature encoders.

The one I bought is a 12-step encoder, but doesn't have detents. From what I've read the norm is to only track rising edge changes on one of the channels, which would give me 12 steps.  Thus your answer confuses me.

Mine is a Bourns PEC11-4020K-S0012 (Jameco part 2277703) encoder with switch.

Reading the datasheet shows it's described as "12 pulses per 360deg rotation". Clearly they mean 12 pulses (up, then down, then back up; or down, then up, then back down) on one channel, and not 12 level changes. I suppose what's "normal" depends on a lot of things. Many Arduino scripts use a less useful process of looking for a rising edge on one channel and then checking the other channel to determine the "direction" of rotation. But that wastes so much information!

"12 pulses" means 12 rising pulses on a single channel in this case. My point is that depending on how you write your code, you can  treat that as 12, 24, or 48 steps plus direction information, and without having to divide the tick count by anything.

The answer to my question is yes.
Normally you only count the falling edge of one of the outputs of an incremental encoder as a pulse. That gives you the specified number of ticks for that kind of encoder - 12 ticks per turn in the case of my encoder.
If you instead write your code to respond to either rising or falling edge changes on one of the pins, you get 24 ticks per revolution.
If you instead write your code to respond to rising or falling edge changes on either pin, you get 48 ticks per revolution.
The code I came up with looks like this:
void setup() {
  //Use this setup code for 12 ticks/revolution
  attachInterrupt(digitalPinToInterrupt(rotaryPinA), encode, FALLING);

/*
  Use this setup code for 24 ticks/revolution
  (trigger interrupt on rising and falling edge)
  attachInterrupt(digitalPinToInterrupt(rotaryPinA), encode, CHANGE);
*/

/*
  Use this setup code for 48 ticks/revolution
  (trigger interrupts on rising and falling edge of either pin)
  attachInterrupt(digitalPinToInterrupt(rotaryPinA), encode, CHANGE);
  attachInterrupt(digitalPinToInterrupt(rotaryPinB), encodePinB, CHANGE);
*/

//The rest of your setup code...
}

And the interrupt service routines (ISRs):
void encode() {
  rotaryValueChanged = true;
  //Read the PinA & PinB (Digital Pins 2 & 3) using port register PINE, 4th and 5th bit
  //Fast equivalent to pinAState = digitalRead(rotaryPinA) == LOW
  bool pinAState = (PINE & (1 << 4)) == 0;
  bool pinBState = (PINE & (1 << 5)) == 0;
  rotaryValue +=  (pinAState == pinBState) ? -1 : 1;
}

void encodePinB() {
  rotaryValueChanged = true;
  //Read the PinA & PinB (Digital Pins 2 & 3) using port register PINE, 4th and 5th bit
  bool pinAState = (PINE & (1 << 4)) == 0;
  bool pinBState = (PINE & (1 << 5)) == 0;
  rotaryValue +=  (pinAState != pinBState) ? -1 : 1;
}

If you only set up one interrupt on rotaryPinA, the 2nd interrupt method never gets called.
The code above is specific to the Arduino Mega 2560 and other boards that have the same pin to register mappings. It uses interrupts so it doesn't miss state changes in the pins, and reads the pin states using port registers for speed.
Note that if you're only adding a falling edge interrupt you can skip the read of pin A (since when the pin state falls it will, by definition be at a logic 0 whenever the ISR gets called.)
To get this to work well I had to build the RC filter circuit described in the spec sheet for my encoder:
https://www.bourns.com/docs/Product-Datasheets/PEC12R.pdf
The diagram looks like this:

And I had to add Schmitt triggers between the filter outputs shown above and the input lines to the Arduino.
Without the Schmitt triggers it gets jitter when the voltage from the filter doesn't switch between HIGH and LOW values fast enough. The Schmitt triggers exclude spurious readings from those "dead zone" voltages.
With those changes the readings from the encoder are quite good, although it still measure ± 1 tick or so per revolution for some reason.
I wish now I had bought the version of the encoder that has detents so it rotates in discrete clicks.

I find it somewhat surprising that you had to add Schmitt triggers, as the Arduino already has built-in Schmitt triggers on all its digital inputs.

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


text:
Can I put a resistor in the ground connection of my DHT22 sensor?
I'm building a project that uses a couple of Adafruit DTH22 temp/humidity sensors. (https://www.adafruit.com/product/385)
I have them wired into my project box through 3.5mm mini plugs (The kind that are commonly used by stereo earbud headphones for MP3 players.)
More than half the time, when I plug/unplug one of my sensors, my Arduino restarts.
My guess is that as I plug in the plug, it sometimes momentarily shorts +5V and ground, causing the +5 source to my Arduino to lose voltage.
These sensors apparently draw single-digit mA of current at peak (like 1.5mA, according to the spec.)
Could I wire a 120Ω or 150Ω resistor in line with the ground connection to the DHT22? This would limit the max current it could carry to around 40mA, which would not be a problem for my power supply (which is fed through the USB port on the Arduino, and thus is limited to 500mA.) Putting a resistor on the ground would limit the current to ground from either the VCC connection to the sensor or the data connection. It would also cause a small loss of voltage to both the data line and the VCC connection.
Would the serial connection between the DHT22 and my Arduino tolerate a 120Ω resistor, even if I connect it via ≈15M of 28-gauge wire?
I could also put the resistor into the VCC wire, but that would only current-limit a VCC-to-ground short, not data-to-ground.

perhaps you need to determine the cause for the resets before you start formulating a solution ..... how are the mini plugs wired?

Outer barrel: ground Middle: hot. Tip: Data

They work just fine unless I plug/unplug them while the arduino is powered up. It seems fairly likely that the act of plugging a mini-plug into the socket might momentarily short one or more of the pins together, and if +5 and ground were to touch, it would exhibit exactly that symptom.

If you were to change your wiring so that data was in the middle, that would cure your problem without resorting to fudges, yes?

Likely yes, that would cause it to connect +5 to data, or data to ground as the connector is pushed home. However, I've got 5 different sockets on my project, all of which follow this wiring convention, so it would be a bunch of rework to change it (Changing both the socket wiring and the cables)

Adding current limiting resistors would be much simpler if that would work.

A resistor could help, the DHT only draws microamps, iirc.

Wow... 5 sockets... That's a huge amount of work. I suggest you take this opportunity to do it right before you add any more sockets...

DuncanC, a signal is relative to ground, you can put a resistor in the 5v line. With the plug on the sensor side and according to @Majenko the 5v at the tip, data in the middle, extra resistor of 150Ω from arduino 5v to "tip" (deepest part in the socket). I think that should work. Are they all gold plated or at least sturdy connections?

They're sturdy connections. I don't think they're gold plated however.

Your case :
   Check wire (shors ?) and pin configuration (out ??)
General :
 No resistor in a ground path.
Decoupling supply :
  one can insert a 100 Ohms resistor between the arduino +5V and the +5V sensor : but ALWAYS use a decoupling capacitor : connect a 100µF betwen +5V sensor and groud. One can add a 100nF ceramic in paraller for digital devices.
Safety in case of bad I/O config :
  Using a 1kOhms restisor between Arduino and Device is good, if next to the Arduino (not at the other end of sensor cable, or use 330 Ohms at eatch end of cable).

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


text:
Will a simple RC filter work with my mechanical rotary encoder, or do I need a Schmitt trigger?
I bought some incremental rotary encoders online  https://www.bourns.com/docs/Product-Datasheets/PEC12R.pdf
The spec sheet for those suggests a filter circuit for the outputs of the encoder that looks like this:

Adding that filter reduces, but doesn't eliminate, spurious signals from the encoder. I wanted to avoid adding Schmitt triggers or other solid state components since I don't have a lot of room left on my proto board for an IC, but I'm beginning to think I will have to add something with hysteresis since any filter that reduces jitter will also slow the rise time/fall time for the output of the encoder and keep it in the "gray area" between LOW and HIGH for a digital signal for too long.
Is there a way to wire these encoders and/or software that lets you read from them with simple passive filtering and/or software rather than adding something like a latch or Schmitt trigger for debouncing?

How fast are you turning the encoder? Are you measuring the speed of a motor? Using it for human/user input?

Look at the datasheet. These are manually turned encoders.

Duplicate of question here  https://electronics.stackexchange.com/questions/423688/how-do-you-pick-component-values-for-a-debouncing-filter/423695?noredirect=1#comment1052330_423695

@CrossRoads, is it bad form to ask related questions on different Stack Exchange sites? My question on the electronics SE site started out asking about picking component values, and then evolved into a more general question about debouncing. This thread is specifically about how to debounce my rotary encode for use with an Arduino.

Have you tried this library https://github.com/buxtronix/arduino/tree/master/libraries/Rotary with the interrupt.ino https://github.com/buxtronix/arduino/blob/master/libraries/Rotary/examples/interrupt/interrupt.ino sketch?

I've seen circuits where they added a diode, so the capacitor charges/discharges instantaneously, but get's RC-filtered in the other directions. In you'r case your interrupts triggers on a falling edge, so you connect the diode via the switch to ground, and have the pull-up resistor "slowly" charge the capacitor back up, when the switch is open. Not sure if this is really "better".

which problem are you having, too fast (jitter) or too slow (missing clicks)? GPIOs don't usually flip on a dime, and you can adjust the rc values to adjust the edge times if needed.

"which problem are you having, too fast (jitter) or too slow (missing clicks)". Seems to be jitter, but it's a bit hard to tell. Jitter will happen even if the signal is debounced, if the slope of the high/low and low/high transitions is too gradual and spends too much time in the "forbidden zone" of in-between voltages. (I think that's what is happening.)

I just added a Schmitt trigger to my circuit in addition to the RC filter shown in my question (an MC14584BCP). That seems to remove the jitter, but it seems to still under or over-count occasionally. (Using an ISR that reads the pins using port registers, so it should be plenty fast.)

See my self-answer and the edit to it. IT should be possible to do the debouncing in software, and the code is very close but not quite there.

Having just chased a problem using a software based debounce for several days, what I'll add is that for the encoders I was using (green no-name Chinese ones), if you put 10mA though the contacts then the signal is a LOT better.   So change the 10k to 470 Ohms.
Or if using 3.3V use 330 Ohms.  Solved all my problems.

The answer seems to be no. I added the RC filter suggested by the manufacturer and the results still jump around (The values sometimes increase by several steps at once, or decrease even when turning the decoder clockwise.)
I added a CMOS Schmitt trigger and it resolves the problem.
I really don't understand why that is, since apparently Arduino digital inputs have integrated Schmitt triggers. This thread from the Arduino forum discusses it at length:
http://forum.arduino.cc/index.php?topic=452599.15
The only thing I can think of is that the hysteresis band of the built-in Schmitt triggers is too narrow (2.08 - 2.63V at VCC of 5V and typical operating conditions) and the filtered voltage still bounces between those values.
I'm using a MC14584B Schmitt trigger that I had lying around, and it looks like it's hysteresis band is ≈2.1V to 2.7V (typical at 25°C) which is slightly wider and goes slightly higher than the hysteresis range of the Arduino itself.
The differences seem quite small though, so I'm confused as to why the Schmitt trigger eliminates the "bobbling" of values I'm seeing.
I could add delay based debouncing code to my Arduino program, but the decoder handler is written as an ISR and those are supposed to be as fast as possible, and the millis() function is supposed to be quite slow, making it difficult.
EDIT:
I asked a related question regarding filter component values on the EE stack exchange, and somebody there pointed out that I should only be seeing "bounce" on one pin at a time, and that I should be able to reject spurious changes purely through software. I'm trying to do that now.
My new code looks like this:
bool rotaryValueChanged = false;

bool pinAHasChanged = false;
bool pinBHasChanged = false;

enum ChangeTypes {
  fallingA,
  changingA,
  changingAOrB
  };
ChangeTypes changesToDetect = fallingA;

void encode() {
  pinAHasChanged = true;
  //Read the PinA & PinB (Digital Pins 2 & 3) using port register PINE, 4th and 5th bit
  //Fast equivalent to pinAState = digitalRead(rotaryPinA) == LOW
  bool pinAState = (PINE & (1 << 4)) == 0;
  bool pinBState = (PINE & (1 << 5)) == 0;
  //Ignore state changes to pinA unless pinB has changed since the last change.
  //Also only pay attention if this is a falling edge
  //or we're tracking both rising and falling edge changes
  if (pinBHasChanged && (pinAState == false || changesToDetect != fallingA)) {
    rotaryValue +=  (pinAState == pinBState) ? -1 : 1;
    rotaryValueChanged = true;
    pinBHasChanged = false;
  }
}

void encodePinB() {
  pinBHasChanged = true;

  //Unless we're counting 48 ticks/rotation, don't count PinB changes.
  if (changesToDetect != changingAOrB) {
    return;
  }
  //Read the PinA & PinB (Digital Pins 2 & 3) using port register PINE, 4th and 5th bit
  bool pinAState = (PINE & (1 << 4)) == 0;
  bool pinBState = (PINE & (1 << 5)) == 0;

  //Ignore state changes to pinB unless pinA has changed since the last change
  if (pinAHasChanged) {
    rotaryValue +=  (pinAState != pinBState) ? -1 : 1;
    rotaryValueChanged = true;
  }
}

void setup() {
  attachInterrupt(digitalPinToInterrupt(rotaryPinA), encode, CHANGE);//FALLING
  attachInterrupt(digitalPinToInterrupt(rotaryPinB), encodePinB, CHANGE);
  //More setup code here...
}

This code is written to handle 3 possible options:

Only falling edge state changes on pin A (12 steps/rotation)
Rising or falling changes on pin A (24 steps/rotation)
Rising or falling state changes on either pin (48 steps/rotation.)

The key part of this is to have interrupts on both pins. When one pin changes, its interrupt handler sets a "this pin changed" bool to true. In the ISR (Interrupt Service Routine) for the other pin, it only pays attention to a state change if the other pin has changed. That way, when Pin A changes states, if it bounces, the other pin should not bounce at the same time and so unless pin B has changed, I can simply ignore additional changes to Pin A and handle my debouncing in software, and without having to do timing delays which are too slow for an ISR.
However, the code above doesn't quite work. Sometimes I get bogus reverse rotation readings. If I'm rotating the encoder clockwise, the values I get increase one by one as expected, but occasionally decrement by 1 and then go back to incrementing.
What am I doing wrong?
Since the bouncing should only ever occur on one pin at a time, the above code should give correct readings from a bare rotary encoder without any hardware debouncing needed, but it doesn't.
My test case is only counting falling edge transitions for Pin A of my encoder, so picking up spurious counterclockwise rotation readings suggests that sometimes Pin B is changing state at the same time as pin B. That shouldn't happen, so I'm confused.

Have a look at MC14490 hardware debouncer.

First of all, I would question the usefulness of debouncing a rotary
encoder. I would expect to have contact bounce only when the contact is
transitioning from HIGH to LOW or vice-versa. At this transition
point, both the HIGH and LOW readings are in a sense correct. A
non-debounced reading should then display a rotary angle that briefly
changes back and forth between two consecutive positions, with no
cumulative error.
I would suggest you forget about debouncing and just look at the state
changes. If you think you do need debouncing, handle it downstream, by
periodically querying the “raw” angle and updating the “debounced”
angle:

if the raw angle is more than one unit apart from the debounced angle,
bring this difference back to one unit.
if the raw angle has not changed since a fixed count of milliseconds,
then make the debounced angle equal to the raw angle.

Second point: you are not looking at the falling edged of input A, you
are looking at the rising edges. This is because pinAState
uses negative logic: it is true when the pin is LOW. It shouldn't
make a big difference though in terms of the logic of the code.
Third point: there is some flaw in your counting logic. I will not try
to analyze it in detail, as the whole debouncing concept you use does
not make sense to me, but only provide an example of how it can fail.
Let's assume the encoder is in the position where both inputs are LOW,
and you wiggle it a little bit so that each input, in turn, gives a
positive pulse, like this:
                _       _       _       _       _       _
input A      __/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____
                    _       _       _       _       _       _
input B      ______/ \_____/ \_____/ \_____/ \_____/ \_____/ \_

rotaryValue      0     |   1   |   2   |   3   |   4   |   5

Here, rotaryValue is incremented on each rising edge of input A, save
for the very first one. In this case, the expected behavior is for this
variable to stay, say, within [−1, +1].


text:
Does this sound like a good approach to decoding a dumb keypad?
The background:

I bought a "dumb" 8-pin 4x4 keypad for use in a project. (This one: https://www.sparkfun.com/products/14881
It has a wire connected to each row, and a wire connected to each column. When you press a key, it connects a row pin and a column pin. You have to use GPIO outputs to send +5V down one row/column at a time, and then use inputs to look for a HIGH on a corresponding set of pins from the other dimension, which indicates a connection between a specific row/column pair.)
I found a framework, MultitapKeypad, that at first appeared perfect. It is a nice clean C++ object with a simple main method, getKey(), that returns a struct with information about the key the user pressed. It detects long presses and repeat presses, things I plan on using.
However, when I looked into it I found things were not as good on the inside. The getKey method uses a while (no key pressed) loop that loops forever. The author's solution to not locking up the Arduino any time you are waiting for a keypress is to provide a callback function that the library calls from the while loop.
The idea of turning a sketch's control flow completely upside down and having to do all your app's event handling from the callback of a keypad class just seems wrong. Then control flow from the app's main loop has to go through the keypad's callback when I'm waiting for keys, or through some other flow otherwise.
The framework also makes use of delay() in it's debouncing, another no-no for apps that manage multiple things at once.
I was therefore thinking of writing my own keypad handler.
My current project, a power controller for lights, chargers, and a humidity controlled warm air dryer will run all of those things simultaneously. It has a back-lit LCD for a display, and uses a motion sensor and photoresistor to turn lights on when it detects motion in low light.
It puts the LCD to sleep if it doesn't detect motion or any user input from it's various switches for an extended period.
When I integrate a keypad into the project I would also like to add keypresses to the list of things that keeps the display awake. I don't see an easy way to do that with the LCD library I was using.

My proposed design:
I was thinking of wiring the keypad with all of the row pins connected to a 9th pin with diodes, anodes pointed towards the 9th pin. I'd set that 9th pin up in INPUT_PULLUP mode and attach it to an interrupt, set to trigger on FALLING signal (or perhaps CHANGE. See below.) The row pins would all also be configured as INPUT_PULLUP. The column pins would all be set up as outputs, and driven LOW.
When the user pressed a key, it would connect one of the column pins to a row pin. That would pull that row pin's input LOW, and also pull the interrupt pin LOW, triggering the ISR (Interrupt service routine).
In the ISR I would use port registers to switch all the column pins to HIGH, and then toggle one column pin at a time back to LOW, looking for a row pin to also drop LOW. If one and only one column going LOW triggers one and only one row to go LOW, I know only one button is pressed, and know the row/column combo, and hence the key that was pressed. If multiple columns trigger a row, or more than one row drops to LOW, I know more than one key is pressed. (I could use that info to report multi-key presses if I need to, although >2 keys at a time gets messy fast.)
Once I have a key I could add the key code for that key to a simple ring buffer and set a "key ready" flag. (My ring buffer might contain structs with more than just a key code, like up/down events, time stamps, etc.)
The rest of my sketch could then query my keypad for "key ready" and read one or more keys as needed. I'd provide housekeeping functions for clearing the key buffer, a way to detect buffer overflows, etc.
I guess I'd actually want interrupts on both falling and rising state change, so I could detect key up events and track the duration of key presses.
I'd also need to add debouncing of some sort or another. I could use a simple RC filter on each input pin, but I don't have a lot of room left on my project breadboard and that would require 4 capacitors and 8 resistors.
From what I've read the millis() function is a little slow and best avoided in ISR routines. Is there a fast alternative to get the current clock value directly in an ISR? If so I could use software to debounce the keys.
Are there any obvious flaws in my plan? Does using an ISR like this sound reasonable? The Keypad actually doesn't short the row/column pins together. It uses variable resistances between the row/column combinations, I guess so that you can use a voltage divider and an analog input to figure out which key was pressed based on the measured voltage. The docs for the keypad say the resistance for a row-column pair varies from 10 to 625 ohms. I'm assuming that the key resistance is low enough that even with signal diodes in the circuit, the closed switch resistance should be enough to pull my interrupt pin and my row pins to LOW.
I suppose I could also tie all the columns and all the rows together, hook it to a voltage divider, and see if I could decode the key using an analog input. That would let me do all that decoding with a single pin.
Alternatively, are there other keypad frameworks that handle 3x4 and 4x4 keypads and offer things like repeated taps, long taps, and allow you to trigger events on ANY key press (So I could keep my LCD display awake.)

This is a proposed combined hardware/software solution. I haven’t built or written anything yet, so I don’t have any code to post. I’m hoping somebody with more experience than me can me about the relative merits of what I’m proposing.

Where did you read that the millis function is slow? It is very fast. What is wrong with the rest of your sketch? Does the loop function run 10 times of more per second? then you don't need interrupts. You could use a timer that generates an interrupt (maybe 20 times per second or more) and scan the whole keyboard in the interrupt. That makes it also easier to debounce. Perhaps it is possible to use a transistor that detect a press in the keyboard instead of so many diodes. Have you build a ringbuffer before? I think that ringbuffer code is in the arduino libraries, but I'm not sure.

I’m using 2 DHT22 temp/humidity sensors. The library for reading them stalls the event loop for ≈250ms per read, and I read both every 2 seconds, so the event loop is stalled 1/4 of the time, for 1/4 second each time.

Sounds like X-Y problem. You want to read a keypad with quick response to user input, but you have a blocking function, which prevents your code from running, forcing you to rely on interrupts or timers unnecessarily. Internet search for "DHT22 arduino non blocking" shows that there are other solutions that eliminate the block when reading the sensors.

Thanks for that suggestion. I will indeed look at those alternatives. I also want to look at better libraries for my keypad.

I think the magic keywords are "non blocking" and/or "timer". https://www.eevblog.com/forum/beginners/4x4-keypad-arduino-non-blocking/msg1236988/#msg1236988 Here's a forum post that has example code for a keypad function similar to your structure, except that this person sets up Timer1 on the Arduino to fire on a regular basis, calling an ISR that scans the keys. It doesn't require an external interrupt or a pin change interrupt, only a timer interrupt. It scans fast enough for human interfacing (claim of 160uS to scan keypad?)

I made a simple RF remote control using a very similar method with a 4x4 kepyad, with diodes connected together to trigger an interrupt and read a keypress. After any keypress, the interrupt woke the processor (unmodified 8 MHz Promini with Atmega328P), it used keypad.h library to detect the pressed key, sent that out via a short RF burst (433 MHz transmitter) using the library (8 years ago now, drawing a blank on the name) that became the Radiohead library (find it on github), then went back to sleep. Lasts about a month on 2000mAH (or so?) LiPo battery that is secured to the bottom of the board.
As I recall, I had to write the outputs opposite of their normal state before going to sleep mode for the interrupt to work correctly, then restore them before reading the keypad.h value. Then put them back in opposite state before going back into sleep mode.  Works well, but I only transmit one key at a time.  I don't have complete details here, can post them when I get home later.  You can see a picture of the remote at the bottom of this site - sorry about the scrolling, I managed to overwrite my index.html file that had link/tabs to jump to the various areas that my son did up for me.  http://www.crossroadsfencing.com/BobuinoRev17


text:
What is the state of Arduino pins when the arduino is unpowered?
I'm building a control box to provide logical control of power outlets.
I'm using a 4 channel 5V optically isolated relay system to control 4 separate outlets.
To use optical isolation you connect arduino +5V to the VCC line, and logic inputs to the 4 channels of the relay unit, and connect a separate +5V supply to run the coils of the relays.
To energize one of the relays, you pull that control line LOW. To de-energize the coil, you drive the line HIGH.
If I power on the relay but leave the Arduino unpowered, all the relay coils energize.
Do Arduino pins float when it is powered down, or are they grounded?
Could I wire a pullup resistor to the inputs? And how would I do that without losing optical isolation? If I connect my pullup resistors to the +5V for the relays, the relay's +5 is connected to the Arduino's logic lines. If I instead use the Arudino's +5 rail, then when the Arduino is powered down, it's +5V line is dead.

Did you remove the jumper between VCC to JD-VCC?

PS why do you want optical isolation? The relays already provide galvanic isolation.

Yes, I removed the jumper so the 2 +5v supplies are isolated.

connect the opto-isolator LED between two of the digital pins ..... if the pins float or if the pins are both the same level then the opto-isolator will not activate

You mean use one of the Arduino pins as the VCC for the Arduino, and the other as the logic input? Then use the pin connected to VCC as a power switch? I like it. It still doesn't protect the Arduino from +5 coming into it's logic lines while the Arduino is unpowered however.

would an nchannel fet between the logic's gnd and the AVR's gnd prevent the intrinsic pull-down? you can then use the fet as a "relay enable" by driving its gate high, or simply tying it to the AVR's VCC

The pins have input protection diodes that clamp the pins to Vcc and Gnd. If a pin gets to >VCC +0.5V the positive diode clamp conducts and Vcc is powered via the internal Vcc bus, and if a pin get to < -0.5V the negative diode clamp conducts.  With Vcc = 0V, the pin could act as if it were a low, but more generally folks see the chip acting like it was phantom powered and attempting to run code with perhaps unpredictable results.  That's why the datasheet says to not drive the pins when th chip is unpowered.  If the clamp current becomes too much, the diode can blow, and either just the one pin is impacted, or the whole chip dies and it will feel warm/hot to the touch when powered up.
So don't power up the relays without also powering up the Arduino.

the circuit is wired only to Arduino VCC and pin on the LED side of the optocoupler  https://i.sstatic.net/14WTN.jpg

Hmm, that doesn't seem like the Opto could be turning on its output transistor then. Some relay boards have a jumper that connects the VCCs together. If you measure pins 1 and 4, is 1 low and 4 high?

My goal is to not power the relay without powering the Arduino. However, it would be bad if the AC power is on and the relay's power supply is "lit" but the Arduino's power supply fails or the Arduino fails to power up. In that case my outlets would all be turned on.

I have my project built so I can plug a computer into the Arduino's USB, in which case it draws it's power from USB and the relay is powered from a separate supply.

That would work.  Or use a 5V wallwart into the USB connector to keep the Arduino powered, if you don't need PC connectivity all the time.

Right, but my question is, how do I handle the error case where there is power to the relay board and the AC source, but not to the Arduino? (Simple case: I forget to plug the USB cable into the Arduino. More serious case: The Arduino's power supply fails or the Arduino fails to start for some reason.)

I guess there's no good answer other than "Don't do that." I might need a power transistor (like an N-channel MOSFET on the relay power supply, with it's gate controlled by a logic line from the Arduino.

or a relay board with coil powered if signal is HIGH

As it turns out my question was a bit of an X/Y problem. I wanted to know what the pins on the Arduino do when the board is unpowered, because I was feeding +5V into the VCC input on my relay board when the Arduino was unpowered, and having the relay control lines connected to Arduino pins.
If you remove the jumper on my relay board, it has a VCC line that ONLY powers the logic level inputs to the relay control optical isolators  and a JVCC line that drives the relay coils. (The VCC line might also power the optical isolators and the other CMOS circuitry on the board, I'm not sure.)
I have my Arduino wired to a USB input that is driven by a regulated AC power supply when it's running stand-alone, and from my computer when it's being programmed. Sometimes I forget to plug the AC powered USB cable into the Arduino when I switch to running it stand-alone off of AC, and in those cases the relay lines tend to energize when I don't want to, and I end up driving +5V into the Arduino's relay control GPIO lines, which is not a good idea.
The simple answer is to connect the +5V line from the Arduino to the VCC pin on the relay board. Then when the relay's JVCC is powered but the Arduino is not, the VCC line to the relay and the control lines to the relay are all unpowered, so the relay is off.
Duh.


text:
Does Arduino C++ support dynamic arrays of objects
My C++ is seriously out-of-date, and I'm working on a project that will be juggling multiple timed actions at the same time, with a menu system to manage the interface and control those timed actions (A multi-channel power outlet controller.)
To do the control I'm planning to have an array of objects that get serviced every time through the event loop. I'm currently using a static C array of objects, but I'd like to use a dynamic C++ array where I can add and remove objects as needed.
I know that some features of the C++ standard library are not supported on Arduino. I think C++ calls smart arrays vectors, and believe vectors are part of the standard library, which isn't supported/fully supported on Arduino. Is there some sort of dynamic array class available?

https://github.com/maniacbug/StandardCplusplus

what for a dynamic array? take as static array the maximum you can/need. there is no other process that could use the memory. on a simple AVR MCU with no concurency, you can exactly plan the memory

Even if it would be possible to use dynamic arrays, I would not recommend it, especially not on an Arduino Uno/Mega with only 2 or 8 KB memory.
Instead, create a static data element (e.g. array) that has a (reasonable) maximum number of created elements. This also has the benefit that the constructor will not be called after initialization, thus no variance in execution time (construction of objects can take time).
To manage multiple items within this data element, you can:

Using a ring buffer, this is the normal way to store items on one side, and process them from the other (so-called FIFO, first in first out).
Using a stack (for LIFO, last in last out).
For arrays, keep one variable that holds the number of elements currently filled.

Old-school C coding. Sure, I'm familiar with those techniques. I've been working too long on devices with tons of memory and plenty of processing power. It's been a long time since the days when I had to write apps in 8-bit assembler. These days I've come to rely on higher level constructs built into the language/OS. It's an adjustment for sure, and it's strange to have a language like C++ on a microcontroller. Causes some cognitive dissonance.

A simple singly linked list would work too.

@DuncanC I have the same issue ... being a software engineer, I think in lists, (dynamic) arrays, stacks, queues etc. A single linked list also is dynamic. Things get complicated when you need to insert elements in an existing list (and removing in some cases).

"Things get complicated when you need to insert elements in an existing list"? How so? Inserting and removing items seems easier with a list, not harder. Easier in some ways than a fixed array with empty flags for each entry

@DuncanC In a list it is easier, but that's dynamic, I mean within arrays, it's easier to remove items (by using a boolean array to show which elements are empty), but adding new items can only be done at the empty spaces (previously deleted array elements) or at the end. A list is always easier, but you need to allocate space for every element separately, thus it is a dynamic data type.

Actually, why bother with a boolean array? Just use NULL for empty slots, and check for NULL before acting on an entry in the array. Then I can add memory management that destroys objects as they are removed.

@DuncanC You are right, I will remove it from the answer.


text:
Standard Length Messages over RS-485
I am a bit confused. So I want to send messages between two arduinos over RS485, but these are not fixed length, naturally, I have to send the length of the message or add a delimiter to understand that my message has ended.
Suppose, now I create a placeholder for the message, and both ends communicating are receiving the placeholder, rather than the message itself. This placeholder is x bytes long always, and each arduino can look it up from its memory what message corresponds to the placeholder.
Lets say I create a message.h file with contents like this
#define A "First Message"
#define B "Second Message"

When the two devices are communicating, they send each other A or B, and the Arduino looks it up in its .h file what A and B mean.
My question is when the Arduino recieves the A, it recieves a character 'A', but how can I use this to fetch the value assigned to variable A in memory?

Seems you #define A you arduinos will see the stuff in the " " and not just A

There is no "variable A" - there is only a macro called "A" which gets replaced by the contents of the #define for "A" at compile time.
You have to remember that the "A" that the Arduino receives is just a number.  It is only us humans who choose to associate that number with the letter A, and write software that takes that number and display it as an A.  The letter A is number 65.  The mapping between numbers and letters is called ASCII - or American Standard Code for Information Interchange.
What you do with that number is entirely up to you.  If you want to use it to display pre-defined messages, then there's a number of ways you could do it.  You could:

Use a series of if statements to compare the number you have
Use a switch/case construct in a similar way
Store the messages in an array and use the received number as the index

For string constants the last option is tricky to get right on an Arduino where there is very limited RAM - you have to ensure that you use PROGMEM and access it properly, and doing that from an array is not as trivial as it would otherwise be.
The best method would probably be the switch/case option:
switch (letter) {
    case 'A': Serial.println(F("First Message")); break;
    case 'B': Serial.println(F("Second Message")); break;
}

I have a write-up about RS485 including a small library to handle this situation.
It can be downloaded from http://www.gammon.com.au/Arduino/RS485_protocol.zip.

Library features

Handles "packets" of between 1 and 255 bytes.
Uses a "begin packet" character (Start of Text, STX, 0x02) to reliably indicate that a packet is starting.
Uses an "end packet" character (End of Text, ETX, 0x03) to reliably indicate that a packet is ending.
Each data byte (other than STX/ETX) is sent in a "doubled/inverted" form. That is, each nibble (4 bits) is sent twice, once normally, and once inverted. Thus the only valid values for each nibble are:
0F, 1E, 2D, 3C, 4B, 5A, 69, 78, 87, 96, A5, B4, C3, D2, E1, F0

The inverse (ones complement) of 0 is F, hence 0 becomes 0F. The inverse of 1 is E, hence 1 becomes 1E. And so on.
This guards somewhat against "bursts" of noise. A burst of either 0s or 1s is unlikely to corrupt a byte preserving this normal/inverse relationship. Also there are only 16/256 valid combinations, so noise has only a 6% chance of becoming a valid byte.
Because of this, also, the STX and ETX characters cannot appear in ordinary data (they are not one of the 16 valid values).
Each packet is followed by a CRC (cyclic redundancy check). This is a further test that the packet was received completely. It guards against noise, or possibly some bytes just becoming missing.

More details on the linked page, but basically you provide a few functions to:

test if a byte is available for reading
read a byte
write a byte

These could be with SoftwareSerial, HardwareSerial, or whatever you choose.
Then you either send or receive a "packet" which is the data you want transmitted to the other end.
There is a "blocking" and "non-blocking" version. The blocking version (when reading) waits for an entire packet to arrive. The non-blocking one lets you do other things while waiting for the entire packet.


text:
Analog Pins are sensing Values
I used the example code AnalogReadSerial and tried it on all analog pins from A0 to A7. None of the analog pins were connected to anything so I expectedy to get 0 in the serial monitor. But as it turns out, I was wrong. Only pin A7 shows 0 to 19 values on the serial monitor. The rest have values ranging from 100 to 300 for pins A2, A3, A4, A5 and A6. The worst performers are A1 and A0 with values from 921 to 1023 showing on the serial monitor. What is the cause of this and how will I fix it?

None of the analog pins were connected to anything so I expected to get 0 - what you should actually expect is an undefined value. how will I fix it? - don't try to read "floating" or unconnected pins. The action has no meaning.

The ADC is multiplexed across the pins, and will carry a small charge from pin to pin.  If you want them to be zero, tie them to ground.
This answer, https://arduino.stackexchange.com/a/575/6628 , suggests pulling them to ground for higher accuracy.

This is normal, as the unconnected pin may float from GND to VCC. You may  enable internal pull-up (to VCC). This is normal for all high-z inputs. If you read digital port you'll see that it floats too. Sometimes you can change digital I/O input value just by waving your hand above the board.
For that reason we always tie high-z inputs to something. You can leave it floating - it won't damage anything, but the value obtained from free-floating input is useless.


text:
USB Device not Recognised - Custom Wattuino Nanite 841
What I have done:
I have made a custom Nanite 841 which uses an ATTINY841 microcontroller.
I have used the schematics from Wattuino to design my circuit, my PCB was made using a router with all excess copper removed.
I have built the circuit and have ensured that every component and track does not short circuit.
I have successfully uploaded the Wattuino bootloader using ISP.
The Problem:
The problem that I am getting is when the microcontroller is connected to any computer I get an error message saying...

"USB device not recognised"

The device status shows this...

Windows has stopped this device because it has reported problems.
  (Code 43)
A request for the USB device descriptor failed.

I hope you can help as this is a bit of a bummer after just building my new device. Thank you for your time.

Is it a double sided board? I don't see any traces going from the USB to the VCC and GND pins of the attiny. Without power the chip won't run (per see)

-1 Your PCB does not match your schematic.  In addition to the ground problem,  it shows a 14 pin IC while the MCU you show has pins up to 16 and then a pin 20.  This question is not answerable due to its self contradictions, so it needs to be closed.

According to Github: micronucleus/micronucleus
 :

Windows machines will need to install the libusb drivers found in the /windows_drivers folder.  Clean Micronucleus devices without uploaded userprogram will not time out and allow sufficient time for proper driver installation. Linux and OS X do not require custom drivers.

Make sure you have installed the device drivers.

Also you need to attempt an upload shortly after reset:

The bootloader allows uploading of new firmware via USB. In its usual configuration it is invoked at device reset and will identify to the host computer. If no communication is initiated by the host machine within a given time, the bootloader will time out and enter the user program, if one is present.

See the troubleshooting page Code 43: Windows has stopped this device because it has reported problems from Microsoft.

You should be able to use a spare Uno or similar device to check the chip response. See Sketch to detect Atmega chip types.
Possibly you have the "divide clock by 8" fuse set. You could clear that if so.


text:
Programming "Arduino" code to AT90S8515?
I found (from a previous life) an STK500 and a couple AT90S8515's in the recesses of my basement..  that I would like to put to use.
Is there a way in which I can write "arduino code" for the 8515?  I know that it's basically C/C++.
I also know that the 8515 doesn't have, or support, a bootloader like the Mega series of ICs do..  so I expect that I will need to program it using the STK500.
I downloaded AVR Studio, but I will admit, I became very lost, very quickly.
Thanks for any direction!

Theoretically yes, once you write a core (1.5.x/1.6.x) for it. I'm not sure if the IDE has a configuration for the STK500, but it should be easy enough to add (since avrdude already supports it).

In Atmel Studio 7 you can create a project on Arduino Code.
For instance if you have a code for an Arduino UNO, it will ask for path of the sketch(a.ino file) and ask for device here it will be Atmega 328.
Now you can build the solution and it will generate code for Atmega 328.
Now you can rebuild the same solution by changing the device now select  AT90S8515.
In my case I built the code for a Atmega328. then rebuilt it by changing device to Atmega8. It worked


text:
Can the SPI pins of an Arduino be separated from SPI?
Are the SPI pins on the ICSP header of an Arduino Uno "separable" from the correspondent I/O pins - when one chooses to the use the ICSP header can the corresponding I/O pins be used for something else?

Pin assignment isn't about electrical engineering? That's quite a strict definition. While this could exist on the Arduino site, this is perfectly on topic for this site.

@AdamDavis Olin no doubt meant that anything with the word "Arduino" in it cannot be about electrical engineering. It may take him a decade or few to realise otherwise.

Where does it specify that Arduino.StackExchange is only about Arduino questions related to electrical engineering?  According the this page (http://arduino.stackexchange.com/tour) asking a question about the IDE is acceptable.   I don't think this SPI / pin question is off-topic at all.

@cbmeeks - the comments you responded to here were added to the question while it was at electronics.stackexchange.com, not here.

No.  Those pins are not separate on the microcontroller itself.  If you need to use SPI and still need more pins you may use analog inputs as digital inputs or outputs.  Otherwise you'll probably have to use an expander of some sort, or use a Mega or Due for additional inputs or outputs.

Actually, it can. You just can not use them at the same time. One needs to be careful to wire it in ways not to comprise the shared functions. Where MISO can be used as GPIO-INPUT and MOSI/SCK can be used as GPIO-OUTPUT, avoiding any pull up/downs, etc... As such electrical items may interfere with the ICSP.
For example I use the ICSP programming, along with the MISO, MOSI and SCLK pins as hard SPI and use them as Bit Bang one-wire, all on the same board and same wires. I simply ensure the SPI is properly configured each at each use.
One additionally needs to ensure that any peripherals on the shared SPI/ICSP lines are guaranteed to be in reset. Such as a pull down on such devices reset pins. Or a Pull Up on their ChipSelects. Noting that ATmega's GPIO pins are Hi-Z out of reset and during the ICSP.


text:
LiPo battery charger
Is it possible to build a battery charger with just an arduino UNO board (and perharps some passive components)?. It's a 3.7V 550 mAh LiPo Battery. I understand I need to monitor the charge and the current flowing into the battery to properly (as in safely) charge it.

I'll assume that you are trying to charge from a 5V "USB" source.
If you only want to use a UNO + passive components then the hardware intensive method of application note AVR146: Lithium-Ion Battery Charging via USB with ATmega16/32U4 which Ignacio suggests does not meet your need. This is a capable charger but the UNO would not be the major part of it.
"Normal" charger
The use of any of the available LiIon charger ICs is an easy and low cost way of adding a charger. These ICs and all related components can cost as little as a few dollars. But ...
UNO + one resistor very low current charger:
If using a UNO with no external active parts the current drive rating of the UNO pins limits the maximum current able to be provided. If you really want to meet your specification you can achieve a few ten's of mA charge using with a UNO and a few resistors (possibly just one.)
Super simple good capability charger
But, a good compromise can be achieved using a UNO (or similar) + one transistor plus a few resistors and capacitors. This can achieve all the usual basic capabilities

Low current "trickle up" for very low voltage cells
Constant current charge until Vmax is reached
Constant voltage charge until I_cutoff is reached.
Terminate and stay active until recharge needed.

I will only outline the basic system here. More can be said as and if required.
The main point of note s that in its simplest form the charger uses a linear charging mode so a modest amount of heat needs to be dissipated in the control transistor. Max power dissipation for a A max charge rate would be 2 Watts when the battery was at 3V and full charge was wanted from 5V in.
Power dissipation = (Vin - Vbattery) x Icharge
Worst case here = (5V - 3V) x 1A = 2 watts.
A buck converter could be used (UNO controlled) if desired.
A transistor Q1 connects Vin to battery
Q1 can be PWM controlled by the Uno.
Battery current is monitored by a small resistor Rcur from B- to ground (or in B+ lead)
Vbattery is monitored with an ADC channel (ADC1 or ADC_V)
Current is measured by measuring voltage across Rcur with an ADC (ADC2 or ADC_I).
If Rcur is from B- to ground then V Rcur = V ADC2. If Rcur is in B+ lead V across Icur = V_ADC2 - V_ADC1.
Q1 on state can be varied by PWM from Uno to control battery current. PWM voltage is smoothed by an RC low pass filter to allow smooth DC control.
Charging:
The following steps constitute the standard LiIon charging algorithm implemented by most charger ICs. Variations can be made.

If Vbat < 3V set Ichg to Itrickle by PWMing Q1 and reading battery current.
While 3V <= Vbat <= 4.2V chg at Imax for battery.
When Vbattery = V-max = 4.2V adjust Ichg with PWM to hold Vbat at 4.2V until   Ichg falls to desired fraction of Imax.
Turn off chg voltage fully and monitor Vbat to restart charge at Vbat = Vrestart - maybe 4.0V or as desired.

Yes, it is. AVR146 describes how to charge a battery using a ATmega16U4/32U4 (Leonardo), but there is nothing specific to that chip regarding the actual charging, and the serial communication can easily enough be ported to the ATmega328P.


text:
what the benefit uploading hex file merely to arduino board?
What the benefit of uploading merely hex file to avr based board like arduino uno Since the arduino ide it self will send intel hex file to the board after compile .ino file to hex file by the avrdude compiler (https://github.com/arduino/Arduino/wiki/Build-Process)?

The data is send to the bootloader, and the bootloader writes it to flash memory. Can you explain your question? What else would you want to upload to the arduino board?

i just wondering if there is sketch speed execution difference betwen uploading .ino file and uploading pure hex file whether via usb or isp

If you want to upload the same sketch to many  Arduinos compiling it again and again would take much longer. Or if you create a firmware ànd don't want to disclose the source code, you can distribute it in compiled form.

In some languages an accent can be used to emphasize a word, but the other accent is used (á). What is ànd?

@Jot, I don't know. I wrote it on an Android phone with on screen keyboard which has only English characters

i just want to know if there is significant speed difference in user program excecution between .ino file and hex file

ino file is not executable. it is a source code. an input for the compiler

@juraj i do agree with you reffer to link i attached with my question. but when you googling "send hex file to avr board" and some short of that  you will find alot talking around that concept. what dou you think

The page describes what happens when you push the Upload button in IDE. The "send hex file to avr board" is about sending a ready hex file. It is the last chapter of the "build process". What is unclear?

if the arduino ide via uart connection send hex file extracted from .ino file to arduino board after upload button pressed why so many avr anthusiast talking about send hex file to avr board like http://www.hobbytronics.co.uk

because AVR was here long before Arduino. and the multiuploads

so you are saying coding with .ino or send hex file to arduino board will result the same in term of program speed execution

the hex created from that ino will be always the same. if you write in assembler language or low level C, the hex will be different and the program possible faster.

thank you bro its clear now that asm c and ino created different hex file. again thank you.


text:
Arduino Relay Shield
I am wondering if this Arduino Relay Shield design would be good enough to handle 120v 1amp The transistor is a 2n4401. Also The Two capacitors on the other 3 circuits would be going to ground opps its to late for this

You seem to be missing some earth connections: bottom of  C3,C5,C7,

please explain the wiring on the output side, preferably draw in the supply and load.

The relays have 5 pins. Th logical arrangement is the 2 coil pins at ine end and the 3 contact pins together ar the other end. That way there is maximum coil to contacts separation. Some relays (and notably low cost Chinese ones used on premade relay shields) have the contact "common" pin at the coil end between the coil contacts. That means there is a short path from low voltage coil to high voltage contacts. This is gross stipidity but very common.

As already mentioned, everything to the left of the relays is completely irrelevant when it comes to what the system can cope with.  It's purely down to the relays what voltage and current they can deal with.  As far as the circuit goes there's nothing wrong with it that I can see at first glance.
So to go from there to an actual physical shield there are a number of things you do need to consider:

Ensure that the relays have a rating at least as high as the expected maximum voltage and current, ideally derate it by at least 50%.  For CFLs (which present an inductive load as well as a resistive load) you want to dereate it even more.
Ensure that the mains voltage track layout is kept well away from the low voltage digital signals and ground plane.
Ensure that the mains voltage tracks are sized appropriately and kept as short as reasonably possible.  Use a track width calculator to get the right width.
Be sure to use appropriate connectors for the mains power.  They need to be able to cope with as much current and voltage as the relays and at the same time be safe.
Keep all mains voltages away from human contact.  This means no exposed live metal on the upper side of your board where it can be inadvertently touched.  Any components with exposed leads that have mains voltage in them should have their leads insulated.
Be absolutely certain that, since this is a shield, no mains voltages even come close to the Arduino the shield is plugged into.  This is especially critical around such areas as the USB socket where through-hole components (like screw terminal blocks) are likely to short circuit and cause very very nasty things to happen.

Remember: Mains voltages are dangerous, caution and safety should be your first concern over everything else!
One more tip: Do all your mains experimentation as safe as possible.  Either ensure that you have an ELCB and an RCD on your ring main / power outlet (with the former you must ensure that you have your earth wires connected properly), or even better (and what I would certainly recommend above all else), use an Isolation Transformer to separate you from the mains circuit entirely.  With an Isolation Transformer electrocution is only possible if you contact both terminals at once as opposed to just one terminal of the normal mains supply.
Edit: One thing that does puzzle me with your circuit is how you have wired up the common pin of the relays.  That part of the circuit makes no sense to me at all.  You should have 2 connections to each relay - in and out where in connects to the NO and out connects to the common pin¹.  The only way your arrangement could work would be to designate one relay as a master power control and that one has the main power coming in which then feeds through to the common rail to supply the other three relays.  If this is what you want, then you will have to ensure that the relay designated as master (and its connector) has at least three times the capacity of the other three relays and connectors (or all four relays have at least three times the capacity you would otherwise need).

¹ Note: doing it this way around ensures that when the relay is in the off position the NC pin isn't live.  The only pin that would ever be live is the common pin.  Safety first...!

Yes the relays are rated 250v 10amps, They wont be pushing anything to hard, Just A microwave fan, also only two relays can be on at once. As for the common pin it seems that i forgot to add that as the AC in for the relays. It wont be on a trace. I plan on using 22awg wire to make a physical connection

The critical part is the relay.
I'd want relays with rated to switch the load and and handle the cold current that the lamp wants.
I also want to see a good creepage clearance distance between digital side and the relay outputs.  Relays which put the common contact between the coil terminals are probably a bad choice here, relays that instead have the contact terminals at one end and the coil terminals at the other make the PCB layout easier.

The relays are rated 250v 10amps as for the coil clearance i dont quite understand what you mean.

250V 10A sounds suitable for lamps up to 100W or so,  the other bit is  about creepage distance (edit)  you don't want to suddenly find that your arduino is live.


text:
Count RISING edges of a wave form by using ARDUINO
I have realised an electrical circuit that gives 5V in output. When I press a button, it gives 0V.
So I have in output a square wave (5V - 0V).
I would like to count how many times I press the button, by using an Arduino MEGA AT2560.
I have written this code below, but it doesn't work, because when I press the button, it increase the counter three or four times.
For example: I press the button 5 times, but the counter has arrived to 30!
#include <SD.h>
#include <SPI.h>

unsigned int count_hall_f = 0;

void setup()
{
  Serial.begin(9600);
  attachInterrupt(0, interrFront, RISING); //18
}

void loop(){

}

void interrFront() {
  count_hall_f++;
  Serial.println(count_hall_f);
}

An example of the result is:
1 <- I pressed here
2
3 <- I pressed here
4
5
6
7
8
9
10
11
12 <- I pressed here
13
14
15
16

Research a technique called debouncing.

Yeah, I've used a RC filter and it does work. I have choosen the values of R and C by experiments. Do you have a suggest for choose these values?

I have choosen the values of R and C by experiments. Do you have a suggest for choose these values?

I have a page about switches - somewhat down the page is a discussion of debouncing, including some calculations which show how you can calculate the debounce time. With the switch pin pulled high by the internal pull-up (something you don't appear to be doing), and a 1 µF capacitor, that gives you a debounce of about 35 ms.

Example schematic:

Results on input pin:

(Maths supporting that figure on the above page).

Note that it is important to have a pull-up or pull-down for your switch or it will read random values if not closed.

Simple way to do it: since the first interrupt, wait a pre-determined amount of time (depends on the button you use, could be 100us to few tens of ms) and check again that the value is what triggered the interrupt.
This will kill the effect of the mechanical bounces.
You can even disable interrupts during the delay.
There are much more sophisticated way to do it, but this should be good enough to get you started on the way to debounce your inputs.


text:
Utilizing 3G/4G connection as gps
Is it possible to get GPS data without using a GPS, but instead using the internet provided from a 3G or 4G connection to get GPS data?
Maybe if you used the HTML5 geolocation API somehow?
I have already used a GPS module together with a GSM modem, but i only used the GSM modem for SMS and not potential internet capabilities.
The beneftis from this , besides cost, would be a smaller program, intended for arduino nano, as TInyGPS and TinyGPS++ libraries are already big enough.
So my question really is twofold:
1. Is there any way to utilize the internet connection from GSM modems (besides the obvious SMS/call function)?
2. Is there a way to utilize the internet connection to get GPS data, without using an actual GPS module?

Step 1: read the manual for the modem.

Regarding the GPS library, check out NeoGPS.  It's faster and more robust than other libraries, and it can be configured to be really small, depending on how many GPS "fields" you really need (not all, I bet).  The examples are structured correctly, and can be modified without breaking them.

You cannot get GPS data without getting GPS data. That's like wanting to get milk from a cow without using a cow.
Some GSM modem modules also include a GPS chip. If yours does you can use that. If not then the closest you can get is:

Country (or maybe city) the IP address is registered in
Cell ID and location of the tower you are communicating with

Both of those are only very rough "somewhere within this square few miles" or "somewhere in this country" kind of data. Any more than that and you need GPS.
Mobile phones augment the GPS / Cell data with WiFi data by matching BSSIDs with an online database (within Google etc) to get rough location information.

Thanks! Do you know a reference where i can browse a list with available GSM modems that include GPS to find one i can use?


text:
SSD1306 OLED LCD Library Errors
Recently i bought an "Serial 128X64 OLED LCD Display SSD1306".
I searched for available libraries and tried to find the best one to use before actually experimenting with this device.
I came across a hackaday article mentioning a "HIGH SPEED SSD1306 LIBRARY"
So that drew my attention and got on with it. This is the link to the afforementioned library for the Arduino DUE.
DayOLED_SSD1306
Right from the beginning i had some trouble with the wiring.
I wired 3.3 volts to input, GND, RES, DC, CS pins are wired according to the library example..
But the library contains no info on how to wire D0 and D1 pins. Since this OLED works both I2C and SPI, i thought maybe these two pins are ommited.
So i hooked it up, load up the example code and got compilation errors.
Here are the errors:
C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawPixel(int16_t, int16_t, uint16_t)':

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:114:14: error: 'swap' was not declared in this scope

     swap(x, y);

              ^

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawFastHLine(int16_t, int16_t, int16_t, uint16_t)':

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:598:16: error: 'swap' was not declared in this scope

       swap(x, y);

                ^

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawFastVLine(int16_t, int16_t, int16_t, uint16_t)':

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:666:16: error: 'swap' was not declared in this scope

       swap(x, y);

Anybody got a clue what is going on with the swap() function?
Maybe it's deprecated?
Anyone has managed to get this library working?
Or maybe has managed to get this Display working even with another library?

I have managed to get this somewhat working with these 4 libraries:
#include <SPI.h>,
#include <Wire.h>,
#include <Adafruit_GFX.h>,
#include <Adafruit_SSD1306.h>.
These should all be in the include library in the ide.
Hope this helps!

I've had good success with the u8g2 library for the small I2C OLEDs.
u8g2 on GitHub


text:
Where to declare timer interrupt variables?
I have a situation where the majority of the code is residing inside timer interrupt functions.
Setup() does what it has, loop() basically reads ADCs and then all the code is inside timer interrupts.
void loop()
{
  //Read the ADCs
  while((ADC->ADC_ISR & 0x1CC0)!=0x1CC0);   // wait for ADC 0, 1, 8, 9, 10 conversion complete.
  in_ADC0=ADC->ADC_CDR[7];                  // read data from ADC0
  in_ADC1=ADC->ADC_CDR[6];                  // read data from ADC1
  POT0=ADC->ADC_CDR[10];                    // read data from ADC8
  POT1=ADC->ADC_CDR[11];                    // read data from ADC9
  POT2=ADC->ADC_CDR[12];                    // read data from ADC10
}

void TC4_Handler()
{
 if (effect==0)       {/*HERE THE CODE FOR EFFECT 0*/}
  else if (effect==1)  {/*HERE THE CODE FOR EFFECT 1*/}
    else if (effect==2){/*HERE THE CODE FOR EFFECT 2*/}
      else             {/*HERE THE CODE FOR EFFECT 3*/}

  // We need to get the status to clear it and allow the interrupt to fire again
  TC_GetStatus(TC1, 1);
}

The user selects the effect he wants via a button and a hardware interrupt.
What happens when the timer interrupt function ends? Do we go back to loop(), or the timer function is re-run?
In this example, all the vars needed inside each functino of the timer interrupt are declared globally.
I was considering if i can declare variables inside each function in the Timer Interrupt function.
Therefore, we would save space, by not declaring variables that are not run at the moment. And we would only initialize variables for the effect we want.
Is this possible? Because if the effect i have just selected just re-loops, maybe its not wise for vars to get re-initialized  (and their values re-set) each and every time it is looped.
So ultimately, variables taht will be used inside a timer interrupt function, globally or locally?

If they are only used in the interrupt then yes they can be declared in the interrupt. If you want them to retain their value from one call to another they must be declared static, and then they will be the same as global variables as far as memory allocation is concerned.


text:
Control air conditioner using Arduino
I followed a couple tutorial on how to receive and send IR codes to control air conditioner the receiving part is working fine and I copied the IR data of the remote control but the problem I am having is sending these codes via IR led can't seem to get it to work can someone help me please.
This the code to send the date via IR LED
#include "IRremote.h"
IRsend irsend;
void setup()
{

Serial.begin(9600);
}

int khz=38; //NB Change this default value as neccessary to the correct modulation frequency
// ON and 2O C° with 1 FAN heat
unsigned ON[] ={4400,4300,550,1600,550,500,600,1550,550,1600,550,500,550,550,550,1550,550,550,550,500,550,1600,550,500,600,500,550,1550,600,1550,600,500,550,1550,600,500,550,500,600,500,550,1600,550,1550,550,1600,550,1600,550,1550,600,1550,600,1550,550,1600,550,500,550,550,550,500,550,550,550,500,550,550,550,1550,550,550,550,500,550,1600,550,500,550,550,550,500,550,1600,550,500,600,1550,600,1550,550,500,600,1550,550,1600,550,1550,600};
unsigned OFF[] ={4350,4350,550,1550,550,550,550,1600,500,1600,550,550,500,550,550,1600,550,550,500,550,550,1600,500,550,550,550,500,1600,550,1600,550,500,550,1600,550,550,500,1600,550,1600,550,1600,550,1600,550,500,550,1600,550,1550,550,1600,550,550,500,550,550,550,500,550,550,1600,500,550,550,550,500,1650,500,1600,550,1600,550,500,550,550,550,500,550,550,550,500,550,550,550,500,550,500,600,1550,550,1600,550,1600,500,1650,500,1600,550};

void loop() {

irsend.sendRaw(ON, sizeof(ON)/sizeof(int), khz);
delay(5000);
irsend.sendRaw(OFF, sizeof(OFF)/sizeof(int),khz);
delay(5000);
}

The problem is my A/C doesn't detect IR codes.

How is your IR system wired?

Don't know I am kind of a beginner at this. How can I tell ? @Majenko

You should know how it's wired, since you wired it up. Show us a photo, or at least a wiring diagram.

Possible duplicate of control air conditioner using arduino


text:
How do you combine 2 different sketches together
(Before you down-vote this, note that it is a "ringer" to answer a FAQ, with a self-answer.)
This question comes up all the time. How do you combine 2 different sketches together? Say I have a sample sketch for a DTH temp/humidity sensor and another sketch for a LCD sensor. How do I combine them?

Possible duplicate of How to combine two different sensor sketches to one complete sketch?

This question comes up all the time. I'll explain what you need to do in general terms. Try it, and if you have problems, post a question showing your 2 starting sketches, your attempt at combining them, and detailed info on what goes wrong.
There are 3 basic parts to the main.ino file of an Arduino sketch:

The declarations:

#includes
#defines
global variables

The setup() function
The loop() function.

You need to merge those parts separately.

You should merge the subsections of the declarations together (Put all the #includes together, all the #defines together, and all the global variables together. Remove any duplicate #includes.

If there are any duplicate #defines or global variables, you need to figure out how to resolve that. If the symbol and the name are the same

The same applies to the two setup()-functions you want to merge. Also, duplicate parts usually need to be there only once (considering things like Serial.begin(...)).
Also the two loop()s are combined the same way, but if you make use of delay()s you must keep in mind that these will sum up in the final sketch, making it slower than the initial sketches were. It might also might (probably won't) work correctly. You will likely need to refactor your code to use millis() instead of delay().

After combining two sketches this way your global variables will be shared. You'll need to resolve any naming conflicts, or rename global variables that are different in your source sketches but should be the same. You may also have shared resources like sensors and LCD displays.
(Note that if the 2 sketches use the same resource for different things it gets more complicated, e.g. using the same pin for different purposes, using the same timer in both sketches, or using the same interrupt. Those things will require analysis and case-by-case changes.)

See for example this answer with examples

To isolate some conflicts in the code, you can rename the bits setupLCD(), setupDTH(), loopLCD(), loopDTH() and call and manage the interactions in setup(){setupLCD();setupDTH();} and loop(){loopLCD(); loopDTH();}

@DaveX, not a bad idea, although that won't help with conflicts in globals.

@DuncanC -- agree.  As you say, conflicts will require analysis and have to be dealt with on a case-by-case basis.