text:
Combine bits from two ports into a single byte
I'm attempting to read the values of 8 pins at a time into a byte.
The obvious answer to this seems to be the Port registers, however with the way the Arduino is wired, I'd have to split my read across two registers.
In this case, I need a way to combine the lower 5 bits of PORTB with the upper 3 bits of PORTD into a single byte.
For example, this is the physical layout with the data lines I'm attempt to read/write to and their corresponding port assignments.
             SCSI
DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0
|   |   |   |   |   |   |   |
PB4 PB3 PB2 PB1 PB0 PD7 PD6 PD5
            AVR

From what I can gather I need to use some shift operators to achieve this,
perhaps something like:
hi = PORTB & 3;
lo = PORTD >> 3;

But I'm unsure if that's correct and then how I would combine them.
Is it possible to write a macro to make getting and setting this byte easier?
Is there a good learning resource on bit manipulation like this?

OK thanks to Excel (had no idea I could do bit operations in it) I've worked out this would probably give the correct value for reading.
(PORTB & (32-1) << 3) | (PORTD >> 5)
but I'm still uncertain how to go about it for writing.

We overlapped. Is my answer clear enough, or do you need some more?

Hi gbulmer. Thanks for the answer. Indeed it's clear enough. I like method you've got for showing which bytes are being manipulated. Very clever. The only thing I need to think about is writing back to the ports without overriding, say, the serial ports.

Assuming PORTB and PORTD are correctly giving unsigned char values:
result = (PORTB << 3) | (PORTD>>5)

would do it.
As a macro:
#define SCSIBITS ((PORTB << 3) | (PORTD>>5))

Then use like this:
result = SCSIBITS

To make it clearer which specific bits are being used, write:
#define SCSIBITS (((PORTB & B00011111) << 3) | ((PORTD & B11100000) >> 5)))

It should be easier to see that the lower 5 bits of PORTB, and the upper 3 bits of PORTD are being used.
In the general case, where the values being manipulated are not unsigned char (should not be a problem in this specific case, but may be helpful to know), you might write:
#define SCSIBITS ((unsigned char)((PORTB & B00011111) << 3) | ((PORTD & B11100000) >> 5)))

or:
#define SCSIBITS ((((unsigned char)PORTB & B00011111) << 3) | (((unsigned char)PORTD & B11100000) >> 5)))

Here are a few links to bit-manipulation tutorials:
https://www.hackerearth.com/notes/bit-manipulation/
http://www.cprogramming.com/tutorial/bitwise_operators.html
http://www.tutorialspoint.com/ansi_c/c_bits_manipulation.htm

Thanks for that. I really like the little trick there to show which bits are being manipulated. Those resources look good too, though I must admit that playing with the Excel bitwise functions and getting a real-time result really made what was happening much more obvious than reading various pieces on the matter.


text:
Change input reference to 1 - 5 V
I am using a sensor which delivers a 4 to 20 mA output.
Converting this with a 250 Ohm resistor to ground I convert this to a 1 - 5 V output.
My question how can I change the 0V reference, so I can use the full spectrum
I found a way to change the 5V reference (analogReference()).
Is it possible to change the 0V reference of a input to 1V?
Any other solution to my problem is welcome as well! (As long as it doesn't involve I2C or anything which lowers my looptime drastically)

Not possible with the Uno, as it has only GND-referenced single-ended inputs.

On which board is this possible? Is there another way to use the full resolution?

Don't know for sure. The Mega is based on the ATmega2560 chip, which has differential inputs to its ADC. If those are available on the board connectors, and if you can provide your 1 V reference to the negative input, it should work.

The ADC is ground-referenced, and there's no way to change that. The question is if that's necessary. The ADC has a 10-bit resolution, that's good for 1024 different levels between 0 and 5 V. If you convert the 4-20mA with a 250 Ω resistor to a 1-5 V range you still can discriminate between more than 800 different values.
If that's not enough you can use a differential amplifier to subtract 1 V:

By choosing R3 = 1.25 R1 you convert the 0-4 V range to a 0-5 V range.

I like the differntial amplifier answer. But, what are V1 and V2? Why are you talking about 0-4 to 0-5 when I have a 1-5? Thanks in advance!

0-4v is 1-5v with 1v subtracted as the answer says.  V2 is your signal at 1-5v, v1 is 1v reference voltage.  V1 is subtracted from V2 (so 1-5 becomes 0-4) and then amplified by R3/R1 to make 0-4 into 0-5.

Use a 2nd opamp section to make a unity gain buffer (OA out to OA-) use this to buffer a pot that you adjust to 1V (Pot feed OA+,OA out to V1. ) || Make One of the R3's adjustable using a bigger value pot than R3 fixed. eg if R3 = 10K make pot say 15K so you can adjust it either side of 10k slightly. This is used to make gain of V1 & V2 inputs track. || Overall accuracy is limited by balance of resistors so use 1% or better still 0.1%. (may not need pot above if R's are matched well enough).   IF you want to avoid having to supply matched R's buy an "instrumentation amplifier" IC.

source: Stack Exchange

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

sort: votes


text:
Can I power a LilyPad with an iPhone lightning port?
I want to make a toy car that follows a black line on the ground by using two sensor on the left and right sides of the car both pointing down. The sensor converts the light into a voltage that I will use to make the car turn left or right. I know that I can use batteries, but I am still very curious to find out if I could use my iPhone to power an Arduino because I also want to make a case with different sensors in it, and it would be thinner if I didn't have to put a 9V battery in the case.

Mobile phones generally use lithium batteries. Have you considered using a thin battery, rather than a thin battery wrapped in a phone in a way that makes it difficult to get the power out of that battery? Adafruit lithium batteries; Sparkfun batteries; etc.

If the phone has an accessible battery you could conceivably use the battery terminals to power a device such as Arduino. However, I think current smartphone batteries have complex monitoring circuits so this wont work.
If it doesn't, you'd be looking at using the USB/charger port on the phone.If your phone supports USB On-The-Go, I know that it allows phones to act as USB hosts, and according to USB-OTG specifications, the host must be able to supply at least 8mA of current between 4.4V and 5.25V.
If that's enough for you it could work.

Would I need some sort of adapter that connects from the iPhone's lightning port to the Arduino? I have an LED case on my phone that draws power from the phone, so I wanted to do the same thing with an Arduino. I might be asking this in the wrong thread. Sorry if I am.

For those coming here from Google.
The short answer is:
Yes you technically can, but it wont be dirt cheap or very pretty depending on your wallet and tastes/requirements.
Longer answer:
I was researching the same thing. The problem is that Lightning connector is fairly complicated, and before it will start giving you power it requires software authentication by a chip that is built into the cable. That said you can use the USB camera connection kit or you can buy one of the IK Multimedia mini usb cables:
http://www.ikmultimedia.com/products/cat-view.php?C=spareparts
I have had success trying to tap into their cable for iRig Pro cause I happen to have one, and it gives out solid 3.3V on one of the pins which is good enough for my Arduino Mini Pro. But I would vouch that their full blown mini usb cable should be supplying regular 5V.

Try to look at the pinout of the lightning port and create your own breakout. Then you can try taking power from the iPhone.

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


text:
How do I get the Itead 3G shield to work?
I've tried a pretty standard code but the Serial Monitor yields zero response.
Using a standard Arduino Uno (tried a second one as well, just to be sure) and am now trying the second shield with this code:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

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

}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

There is nothing coming back whatsoever in the serial monitor (yep, I checked the baud rate and tried several others).
Any ideas?
What should I be seeing if anything?

What should I be seeing if anything?

Usually, a GSM module will not send (unsollicited) messages. Everything it sends will be an response to an received message.
Try sending AT (with a new line/carriage return (depending on the GSM module)) to the GSM module, it will send something like AT OK or just OK
And you didn't set the pin directions (output/input), might be doen by the serial libraries, but beter be safe if you're not sure.
Also check your wiring (jumpers on UART multiplexer in this case?) and share it with us, Rx/Tx wiring often gets messed up :)
If your GSM module has a USB connection, you might even test it with a terminal (taking out the Arduino in the middle, thus any wiring/code between.)
I also suggest you change the name of the serial connection to the GSM to something like gsmSerial rather than mySerial (which could be anything).
Be sure the 3G shield has enough power (amperes), otherwise they might reset when attempting to make an connection.
(Put the external supply in the Arduino, rather than USB powered)

I have one, and I haven't figured out how to get it to accept input, but have received responses.  Here are some things to try:

Make sure you have your jumpers set for D2 and D3.  Just telling software serial to look at 2 and 3 doesn't mean your board is jumpered that way.

Also, remember that Tx for the board = Rx on the arduino and in your code.  Software serial is (rx, tx), so (2,3) means your board will be jumpered with tx on 2 and rx on 3.

There are four LEDs on the board.  If all four aren't lit, the board is powered down, and won't do anything.

First, make sure your power switch is set right - "VCC Switch", by
the USB connector, is set to the power level of your board.  I'm
using an Uno at 5V, so for me that's set to 5V.
It's best to provide power through your barrel connector on your Arduino and connection through the USB.  GSM modules are power hogs.
With all of that plugged in, your board should show two lights, the first and third.
Now hit the "PWR" button.  The second light will come on dimly, then stronger.  Now the module has power.
Finally, the fourth light will come on when the module has detected network. At that point, the 5216 will start sending you messages.

You need to make sure your baudrate is set properly.  Anything less than a Mega can't handle communication at 115200, which is the default for the module.  At best, you'll set both Serial and SoftwareSerial for 115200 baud, and you'll get mostly correct characters from the board, but an occasional bad character.
Here are some great instructions for changing the default baudrate at Github from some JeanBritz

One caveat to those instructions: make sure you have your Itead board powered by the Uno before plugging into the mini USB.

Here's a bit of light at the end of the tunnel for you -


text:
A more elegant way to deal with timers without using delay()?
I am looking for a more elegant way to write a function that performs timer-based tasks as in the case of the code below, which essentially collects 5 sample values from a microphone module over a given period of time and then computes their average. It is important that it does not use the delay() function because other tasks are supposed to run in the background which should not be affected by the delay.
  int sensorPin = A0;
  int ledPin = 13; //  pin for the LED
  int sensorValue = 0; // variable to store the value coming from the sensor
  unsigned long timer;
  int interv = 50;
  unsigned long sampleArray[] = {0, 0, 0, 0 , 0};
  unsigned long millisaver;

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

  }

  void loop ()
  {

    if (millis() > 2000) {
      if (millis() < 2050) {
        millisaver = millis();
        timer = (int) millisaver;
        Serial.println(timer);
      }
      if ( millis() > timer && millis() < timer + interv ) {
        sampleArray[0] = sensorValue = analogRead (sensorPin);
      }
      else if ( millis() > timer+interv && millis() < timer + interv*2 ) {
        sampleArray[1] = sensorValue = analogRead (sensorPin);
      }
      else if ( millis() > timer+interv*2 && millis() < timer + interv*3 ) {
        sampleArray[2] = sensorValue = analogRead (sensorPin);

      }
      else if ( millis() > timer+interv*3 && millis() < timer + interv*4 ) {
        sampleArray[3] = sensorValue = analogRead (sensorPin);

      }
      else if ( millis() > timer+interv*4 && millis() < timer + interv*5 ) {
        sampleArray[4] = sensorValue = analogRead (sensorPin);
      }
      else if ( millis() > timer+interv*5) {
        unsigned long averageVal = (sampleArray[0] + sampleArray[1] + sampleArray[2] +sampleArray[3] + sampleArray[4])/5 ;
        Serial.println(averageVal);
        millisaver = millis();
        timer = (int) millisaver;
      }
    }
  }

Other than using interrupts?

Might be possible to adjust the ADC clock frequency to match 20 Hz and use the ADC interrupt for data collect.

yes, other than using interrupts, if possible.

@Grovelli why not an interrupt? That is precisely what they're for. The Arduino libs are great, but at some point, you're going to want to understand the actual Mcu on the board. I know the data sheets are daunting, but it is well worth diving in.

By the way, do you know what the average of a sound wave is over time? You don't need a microphone to discover that it's 0.

I should have been more precise in my description concerning what average value I want to refer to, namely the average of volume peaks (but you are right, in the present form it will be 0).

For excact timing there is feature called ADC Auto Trigger mode. For example millis() are usually counted by timer 0 overflow (on AVR based Arduinos) every 1024us (I suppose it's because of PWM - otherwise it could be set exactly to 1ms). So if you don't mind that little offset, you can configure
ADC with Timer 0 Overflow and use every 20 measure only.
But don't forget that analogRead on another pin changes ADC channel and you will get something else if you don't check it.
As an auto trigger source can be used one of these:

Free Running Mode
Analog Comparator
External Interrupt 0
Timer/Counter 0 Compare Match A
Timer/Counter 0 Overflow
Timer/Counter 1 Compare Match B
Timer/Counter 1 Overflow
Timer/Counter 1 Capture Event

For ATMega328 it can be something like this:
void setup() {
    Serial.begin(57600);

    // ADC setup is done by arduino framework, but it's possible to change it slightly (for ATMega328) :
    ADCSRB  = _BV(ADTS2); // ADTS2..0 = 100, Timer 0 overflow as trigger source
    ADCSRA |= _BV(ADATE); // enable auto trigger mode
    ADCSRA |= _BV(ADIF); // reset conversion interrupt flag (by writing log 1)

    analogRead(A0); // dummy read to set correct channel and to start auto trigger mode
}

int8_t sample_count = 0;
int8_t sample_index = 0;
uint16_t  samples[] = {0, 0, 0, 0, 0};
uint16_t sample_sum = 0;

void loop() {
    if (ADCSRA & _BV(ADIF)) {
        ADCSRA |= _BV(ADIF); // reset ADIF flag by writing logic 1 into it (mentioned in datasheet)
        if (++sample_count == 20) {
            sample_count = 0; // reset sample_count, as we wan't every 20th

            sample_sum -= samples[sample_index];
            samples[sample_index] = ADC; // read value
            sample_sum += samples[sample_index];

            if (++sample_index == 5) { // reset index and count and send average
                sample_index = 0;
                Serial.println(sample_sum);
            }
        }
    }
}

Thank you for your detailed answer! I will research on the ADC auto trigger mode as I am frankly new to it.

You probably shouldn't mess with TIMER0's timing. The Arduino libs use that timer for things like millis(). Which libraries use which timers is described here. https://arduino-info.wikispaces.com/Timers-Arduino

@RubberDuck I didn't mess with TIMER0 timing. I did't touch it at all. I've just used it as auto trigger source to perform ADC conversion every 1.024ms and I'll use every twenty measure of these.

My misunderstanding @KIIV

You didn't say what you want to do with those samples. If you want to
estimate the level of sound intensity, your whole approach is completely
wrong. First, your sampling rate (20 Hz) is way too low: you should
sample at least at twice the frequency of interest, typically at
8 kHz or more. Then you have to subtract the DC offset added by the
microphone module, then square the result in order to get an
instantaneous intensity, then low-pass filter to get a usable intensity
reading. As Majenko said, if you average (or low-pass filter) the
samples before squaring, you would detect zero sound.
I've written a sound meter program for an Arduino Uno that does exactly
that, and it's available as a GitHub Gist:
sound-meter.ino.
It uses the auto-trigger mode as explained by KIIV, but with free
running mode instead of a timer. This gives 9.6 kHz sampling rate.

My apologies, I just realized low_pass() was not a standard function off a library.

@Grovelli: It's an exponentially weighted moving average, the digital analog of an RC filter: one of the simplest low pass digital filters you can make.

You need to make a function which is pretty much completely self contained. Within the function should be a counter so it knows which sample it is on, and a timestamp to know when it should next run. The function should also inform the caller when it has a full sample set to process.
I haven't tested this (don't know if it even compiles) but something like this might work:
bool getSample(uint8_t pin, unsigned long *samples) {
    static uint32_t ts = millis();
    static uint8_t sampleNumber = 0;

    if (millis() - ts >= 50) {
        ts += 50;
        samples[sampleNumber++] = analogRead(pin);
        if (sampleNumber == 5) {
            sampleNumber = 0;
            return true; // We have 5 samples
        }
    }
    return false; // We don't have 5 samples yet.
}

// ... later ...

if (getSample(sensorPin, sampleArray)) {
    // Process Samples
}


text:
Capacitive "keys" press event registration issues
Seeing as this is my first post I would like to thank everyone ahead who take their time to delve into my whimsical code, whoever you may be, be merciful ;)
For one of my uni projects, I would like to make a physical interface that can be operated via touch "keys" that rely on the human capacitance effect. I have relentlessly researched it (as much as feasible in my time as a student for this project) and even created a working prototype with 4 unique keys.
As you will see in my code below, I am using the capacitiveSensor.h library, which I could unfortunately not find much documentation about other than a few videos and tutorials that build upon it.
I tried deciphering the workings of it by looking at its code to see if I can manipulate it for my own biddings but quickly realized it is beyond my skill to understand.
The problem I am facing right now is that while the touch keys work, they trigger each other because of the capacitance build up when one of the keys is being pressed or when the hand is close to other keys while pressing a key.
Essentially, I am looking for an algorithm that will reduce processing time & effort for the Arduino as the one I have implemented below slows it down way too much to be of any use for my project.
Sorry for the long post, here is my current code:
#include < CapacitiveSensor.h >
#include < pitches.h >

CapacitiveSensor cs_4_2 = CapacitiveSensor(4, 2); // 10M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
CapacitiveSensor cs_4_3 = CapacitiveSensor(4, 3); // 10M resistor between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil
CapacitiveSensor cs_4_5 = CapacitiveSensor(4, 5); // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor cs_4_6 = CapacitiveSensor(4, 6);

# define COMMON_PIN 4 // send pin
# define CAP_THRESHOLD 450 // overall threshold
# define NUM_OF_KEYS 4 // Number of keys that are on the keyboard
# define noteDur 50 // duration of note
# define BUZZER_PIN 12 // The output pin for the piezo buzzer
# define noMulti 0.9 // incremental factor per key
# define overkill 5 // register no touch after this cap factor is exceeded

// This macro creates a capacitance "key" sensor object for each key on the piano keyboard:
# define CS(Y) CapacitiveSensor(COMMON_PIN, Y)

CapacitiveSensor keys[] = {
CS(2), CS(3), CS(5), CS(6)
};

void setup() {

Serial.begin(57600);

// Turn off autocalibrate on all channels:
for (int i = 0; i < NUM_OF_KEYS; ++i) {
keys[i].set_CS_AutocaL_Millis(0xFFFFFFFF);
}

}

void loop() {

// needs to be repeated here to work in THIS scope
long sensor01 = cs_4_2.capacitiveSensor(30); // pin 2 is cap sensor, pin 4 is "common send"
long sensor02 = cs_4_3.capacitiveSensor(30);
long sensor03 = cs_4_5.capacitiveSensor(30);
long sensor04 = cs_4_6.capacitiveSensor(30);

Serial.println("");
Serial.print("key1");
Serial.print("\t");
Serial.print("key2");
Serial.print("\t");
Serial.print("key3");
Serial.print("\t");
Serial.print("key4");
Serial.println("");
Serial.print(keys[0].capacitiveSensor(CAP_THRESHOLD));
Serial.print("\t");
Serial.print(keys[1].capacitiveSensor(CAP_THRESHOLD));
Serial.print("\t");
Serial.print(keys[2].capacitiveSensor(CAP_THRESHOLD));
Serial.print("\t");
Serial.print(keys[3].capacitiveSensor(CAP_THRESHOLD));

// algo for key 1
if (keys[0].capacitiveSensor(CAP_THRESHOLD) > CAP_THRESHOLD &&
keys[1].capacitiveSensor(CAP_THRESHOLD) < keys[0].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[2].capacitiveSensor(CAP_THRESHOLD) < keys[0].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[3].capacitiveSensor(CAP_THRESHOLD) < keys[0].capacitiveSensor(CAP_THRESHOLD) * noMulti) {
Serial.print("key pressed on sense1");
Serial.println("");
tone(BUZZER_PIN, NOTE_A7, noteDur);

}

// algo for key 2
else if (keys[1].capacitiveSensor(CAP_THRESHOLD) > CAP_THRESHOLD &&
keys[0].capacitiveSensor(CAP_THRESHOLD) < keys[1].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[2].capacitiveSensor(CAP_THRESHOLD) < keys[1].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[3].capacitiveSensor(CAP_THRESHOLD) < keys[1].capacitiveSensor(CAP_THRESHOLD) * noMulti) {
Serial.print("key pressed on sense2");
Serial.println("");
tone(BUZZER_PIN, NOTE_B7, noteDur);

}
// algo for key 3
else if (keys[2].capacitiveSensor(CAP_THRESHOLD) > CAP_THRESHOLD &&
keys[1].capacitiveSensor(CAP_THRESHOLD) < keys[2].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[0].capacitiveSensor(CAP_THRESHOLD) < keys[2].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[3].capacitiveSensor(CAP_THRESHOLD) < keys[2].capacitiveSensor(CAP_THRESHOLD) * noMulti) {
Serial.print("key pressed on sense3");
Serial.println("");
tone(BUZZER_PIN, NOTE_C7, noteDur);

}
// algo for key 4
else if (keys[3].capacitiveSensor(CAP_THRESHOLD) > CAP_THRESHOLD &&
keys[1].capacitiveSensor(CAP_THRESHOLD) < keys[3].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[2].capacitiveSensor(CAP_THRESHOLD) < keys[3].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
keys[0].capacitiveSensor(CAP_THRESHOLD) < keys[3].capacitiveSensor(CAP_THRESHOLD) * noMulti) {
Serial.print("key pressed on sense4");
Serial.println("");
tone(BUZZER_PIN, NOTE_D7, noteDur);

}

}

Guys, I realized how to "bypass" the lag caused by the capacitance build up once a key is triggered - namely by increasing the size of the resistors (from 1k to 1mOhm) between the "keys", e.g. the aluminum foil in this case, and the Arduino input pins. What this does is reducing the maximum capacitance that can be reached on each key and so reduces the overall period needed to register the maximum capacitance, which I assume is done by some magic internally in CapacitiveSensor.h. As a result, pressing a key does not lag the Arduino nearly as much as was the case when using 1k resistors.

You might experiment with the code shown at the end of this answer.  It is fairly responsive, in the sense that readings are taken reasonably quickly (several per millisecond), which should leave a good deal of time available for other processing.
In this code, all of the pins that are on the same port are sampled at the same time.  For example, pins 2,3,5,6  on an Uno are all on port D so their four pads can be tested all at the same time.  But if the pins list includes pins from k different ports, sampling will take up to k times as long as when sampling from a single port.  For example, on a Mega2560, pins 2, 3, 5 are on port E and pin 6 is on port H, so this code's execution time when processing buttons on pins 2,3,5,6 is about twice as long on a Mega as on an Uno.
[Edit:  For Uno port-to-pin assignments, see an Arduino Uno Pinout Diagram.  On such diagrams, labels like ADC0 PCINT8 14 A0 23 PC0 show the Arduino digital pin reference number (eg, 14), analog pin label (eg, A0), its various functional designations (ADC0, PCINT8, and PC0, meaning analog input pin 0, pin-change-interrupt pin 8, and bit 0 of port C), and the physical pin number (23).   For hardware level information about Uno ports, see Atmel's document #8271.  Use Google images similarly to find other-model diagrams, eg Mega 2560 pinouts.]
You may need to tune some of the constants to fit your own circuitry or switch-function requirements.  I'm not able to tell from the question what resistor sizes you are using or what your circuit is.  For preliminary tuning, enable the secondly() function and disable testChange() functions.  If your circuit is similar to that shown below but uses higher resistances, you may need to increase nsamp, IsHighCount, and preSamp.
Here is the general idea of circuitry I used:

In the above, "Drive" refers to pin 4.  "Sense 1" ... "Sense j" (with j=4) refer to pins 2, 3, 5, 6, as in your example code.  The capacitors illustrated are tape-covered aluminum-foil pads, eg 22 x 44 mm and the resistors are 440 KΩ each (two 220 KΩ's in series).  Those resistor values produce an RC time constant of a few dozen microseconds when a button isn't touched, and a couple hundred microseconds when a button is touched.
Here is some example output:
2 on  199 7587
2 off 179 7702
1 on  196 10798
1 off 154 10802
1 on  253 10900
1 off 180 10924
2 on  219 18097
2 off 166 18134
3 on  214 21105
3 off 155 21385
3 on  227 24312
3 off 72 24535

In that output, the first column is switch number.  The last column is the current reading of millis() at time of printing.  The third column is total counts accrued from 12 sets of contact readings.  The simple-minded on/off algorithm used in the testChangeA() function is that a contact is on when its 12-sample count exceeds 180.  One could also add calibrations, adaptive threshholds, debouncing, etc to the code.
Here is the code (which was run on an Uno, but I tested most of it on a Mega also, and it should run ok on other Arduinos as well since the direct port accesses are computed via functions like portInputRegister, portModeRegister, etc in countPins7() setup before it calls portSampler7() to run the test.
/* Via serial port, tell the current time when capacitive readings on
 various digital pins show a button has been "pressed" or "released".
 JW - 25 Dec 2015

 See eg refs at http://playground.arduino.cc/Code/CapacitiveSensor and
 http://www.arduino.cc/en/Reference/PortManipulation and
 http://garretlab.web.fc2.com/en/arduino/inside/arduino/Arduino.h/digitalPinToPort.html

 */
#include <Streaming.h>      // provides nicer syntax for printing
// Set upper size on pins count per sample; #samples saved per reading;
//  #samples tossed; threshold for Button-is-on; #samples per set; etc
enum { nbits=8, nsamp=40, preSamp=1, SettleDown=90 };
enum { IsHighCount=15, SampleSets=12, IsHighTotal=IsHighCount*SampleSets };
void setup() {
  Serial.begin(115200);     // initialize serial port
}
//-----------------------------------------------------------
// portSampler7(): Sample a port nsamp times and return the results.
// Inputs:  drivePin, portCode, pinsMask, preWait.  Constant nsamp.
// Output:  array of nsamp samples.
// This version takes 8 cycles per sample, and as inputs switch
// on after about one RC time constant, on a 16MHz Arduino an
// m-count result (that is, a bit clear in m of the nsamp readings)
// suggests RC is about m/2 + preWait/2 us.
void portSampler7(uint8_t drivePin, uint8_t portCode, uint8_t pinsMask,
          uint8_t preWait, uint8_t *samples) {
  volatile uint8_t *pin, *port, *ddr;
  // pin, port, and ddr are pointers to registers with volatile
  // contents: input port, output port, direction register.
  pinMode(drivePin, OUTPUT);
  digitalWrite(drivePin,LOW);
  pin =  portInputRegister (portCode); // eg points to PIND
  port = portOutputRegister(portCode); // eg points to PORTD
  ddr =  portModeRegister  (portCode); // eg points to DDRD
  *port &= ~pinsMask;        // Turn off our pins
  *ddr  |= pinsMask;         // Make our pins be outputs, briefly
  for (uint8_t i=0; i<SettleDown; ++i) *pin;  // Delay to let pins settle low
  *ddr &= ~pinsMask;         // Make our pins be high-impedance inputs
  digitalWrite(drivePin,HIGH); // Turn on driver pin
  for (uint8_t i=0; i<preWait; ++i) *pin;  // Baseline Delay
  for (uint8_t i=0; i<nsamp; ++i) // Take and store nsamp readings
    samples[i] = *pin;
}
//-----------------------------------------------------------
/* Sample a pins-list and report results in counts array.  Eg,
   pinsList can look like "2,3,4,5,6" or "2,4,5,12,9,23,17,7"
   etc.  A list may contain digits and commas only.  Pins may be
   listed in any desired order.  Elements of counts will be in
   list-order.  Eg, in the "2,3,4,5,6" example, counts[0] is the
   count for pin 2, counts[1] is the count for pin 3, etc.  A
   larger count implies longer rise time and larger capacitance.
   Use preWait to suppress baseline-level counts (and to reduce
   sample array size) by waiting a while before beginning to sample.
 */
uint8_t countPins7(uint8_t drivePin, char *pinsList,
           uint8_t *counts, uint8_t preWait) {
  uint8_t pnum, pomask, pocode, potem, i, j, mul;
  uint8_t sampl[nsamp], pim[nbits], pat[nbits], bout=0, nat=0, pcon;
  char *c, cc;
  int usedPorts=0;  // To track which ports are done
  for (c=pinsList, counts[0]=pcon=0; *c; ++c) // Zero the counts array
    if (*c < '0' || *c > '9') counts[++pcon] = 0;
  // In each pass, group bit numbers by port and sample the port
  while (nat<pcon) { // Each loop pass sets one bit in usedPorts
    pnum = pocode = pomask = bout = pcon = 0;
    c = pinsList;
    while ((cc=*c++)) {  // Loop until c is at end of string
      if ('0' <= cc && '9' >= cc) {
    pnum = 10*pnum + cc - '0';
    if ( *c < '0' || *c > '9') { // See if pin # is complete
      potem = digitalPinToPort(pnum);  // Get port #, in range 1 to 12
      if (!(usedPorts & (1<<potem))) { // Is potem's port already done?
        if (!pocode)           // If pocode not set, set it
          pocode = digitalPinToPort(pnum);
        if (pocode == potem) {  // Process pin if it's in current port
          pomask |= (pim[bout] = digitalPinToBitMask(pnum));
          pat[bout++] = pcon; // Save location of pin's bit in results
        }
      }
      pnum = 0; // Clear # accumulator
      ++pcon;   // Count pin numbers
    }
      }
    }
    // Now pomask is a mask for all bits to be read from port pocode
    // and we are ready to sample current port
    portSampler7(drivePin, pocode, pomask, preWait, sampl);
    usedPorts |= 1<<pocode;       // Mark the port finished
    // Count up # of zeroes (ie rise times) in sampled bits
    for (j=0; j<bout; ++j) {
      int count;
      uint8_t m=pim[j];
      for (count=i=0; i<nsamp; ++i)
    count += sampl[i] & m;
      counts[pat[j]] += nsamp - count/m;
    }
    nat += bout;        // Count number of pins done so far
  }
  return pcon;          // Return # of pins processed
}
//-----------------------------------------------------------
// secondly() will report counts at start-of-second
void secondly() {
  uint8_t counts[nbits], j, nc;
  if (millis()%1000) return;    // Wait for start-of-second
  nc = countPins7(4, "2,3,5,6", counts, preSamp);
  Serial << "Counts: ";
  for (j=0; j<nc; ++j)      // Marshal output
      Serial << counts[j] << " ";
  Serial << " t=" << millis() << endl;
  while ((millis()%1000)==0) {}; // Await end-of-millisecond
}
//-----------------------------------------------------------
uint8_t ostate[nbits] = {0};
void testChange1() {
  uint8_t counts[nbits], j, nc, s;
  nc = countPins7(4, "2,3,5,6", counts, preSamp);
  for (j=0; j<nc; ++j) {
    s = counts[j] > IsHighCount;
    if (s ^ ostate[j]) {
      Serial << j << (s? " on  " : " off ") << counts[j] << " " << millis() << endl;
      ostate[j] = s;
    }
  }
}
//-----------------------------------------------------------
void testChangeA() {
  uint8_t counts[nbits], j, k, nc, s;
  int sumcount[nbits]={0};
  for (k=0; k<SampleSets; ++k) {
    nc = countPins7(4, "2,3,5,6", counts, preSamp);
    for (j=0; j<nc; ++j) {
      sumcount[j] += counts[j];
    }
  }
  for (j=0; j<nc; ++j) {
    s = sumcount[j] > IsHighTotal;
    if (s ^ ostate[j]) {
      Serial << j << (s? " on  " : " off ") << sumcount[j] << " " << millis() << endl;
      ostate[j] = s;
    }
  }
}
//-----------------------------------------------------------
// Take samples of rise times at  designated pins.  When a pin's
// time changes from small to large, report rising edge; or
// when it changes from large to small, report falling edge.
void loop() {
  //secondly();
  //testChange1();
  testChangeA();
}

Thank you for a most comprehensive answer jwpat7! I will try your solution but I have to ask - why does setting the input pins to high impedance is important? Also, I did not know of the presence of the ports you mention in your answer, is there a reference to them in the arduino documentation you could perhaps share with me? Again, thank you for taking your time to reproduce my problem here!

Each input pin is monitoring the voltage on a pad, as that voltage drops according to v(t) = v(0) * exp(-tau * t), where tau = RC time constant.  If the input pin weren't hi-Z it would affect the rate of voltage drop.  Regarding ports, see edit

@Grove, I don't understand your comment, eg what you mean by  “the pulsating nature” or by  “the on/off algorithm”.   Three notes: 1, There should be a layer of insulation (eg packing tape or a solder-resist coating) on top of each key, so it shouldn't matter to the user how the key is being tested.  2, If you mean "only test the button when it's being pressed", I don't know of a way to do that.  3, why does whatever you are referring to matter?  Ie will it save energy, time, or what?

Hey jwpat7, I deleted my original comment because I found a way to solve my problem: I was trying to attach an event to a specific key once it was pressed but used the on/off algorithm to check its state and was naturally unsuccessful because when a key was pressed it still was less than 180 at one point in the "capacitance cycle". So instead, I just used the j variable as a starting point to see which key was being pressed, as j returns a constant value, i.e. the key number.
Thank you again for your help!


text:
Python PySerial with Arduino fails byte check
I'm struggling with my first steps with Python and PySerial. I have one Arduino which reads impulses from an electricity power meter, passes the counts over to another Arduino over an RF link and then sends the data over to an Raspberry Pi. The Arduino to Arduino communication works well. However the last step of passing this to the RPi fails.
The MeterValue from the Arduino side is an unsigned Long (32 bits) and therefore split in 4 pieces of 8-bit transmissions plus a frame start and frame end:
[0x01] Frame start
[0xMeterValueByte0]
[0xMeterValueByte1]
[0xMeterValueByte2]
[0xMeterValueByte3]
[0x04] Frame end

This is my Arduino code continuously sent to the RPi in debug purpose :
void loop() {
//static test loop
Serial.write(0x01); //start frame
Serial.write(0x00);
Serial.write(0x00);
Serial.write(0x02);
Serial.write(0x04); //end frame
delay(3000);

}

This is my Python code:
Import serial
ser = serial.Serial('/dev/ttyACM0',9600)
print("Connected to: " + ser.portstr)

inputbuffer=[]
inputbuffer = [0 for i in range(10)]

while True:
    if ser.inWaiting() > 0:
        inputbuffer = ser.read(1)
        print "Byte received"
        print "Inputbuffer[0]: " + hex(ord(inputbuffer[0]))

        j = inputbuffer[0]
        print "j= " + hex(ord(j))

This check of the "j" parameter somehow fails:
        if (j == 0x1): #look for start of frame
            print "Start found\n"
            print "Filling buffer\n"
            while ser.inWaiting() < 5: #hold here until 5 bytes arrived
                pass #proceed here
            inputbuffer +=ser.read(5) #read 5 bytes

            if inputbuffer[5] == 4: #check that the message has frame end
                RXval = inputbuffer[1]
                RXval |= (inputbuffer[2] << 8)
                RXval |= (inputbuffer[3] << 16)
                RXval |= (inputbuffer[4] << 24)
                print "RXval: ", RXval
            else:
                print "RX error, no frame end\n"
        inputbuffer = []

This is the Python output:
Connected to: /dev/ttyACM0
Byte received
Inputbuffer[0]: 0x1
j= 0x1
Byte received
Inputbuffer[0]: 0x0
j= 0x0
Byte received
Inputbuffer[0]: 0x0
j= 0x0
Byte received
Inputbuffer[0]: 0x2
j= 0x2
Byte received
Inputbuffer[0]: 0x4
j= 0x4

And then it repeats. Obviously the Python code doesn't realize j == 1. How should I handle the checking of the received bytes?

I think the problem is that you can't count ;)
Spot the difference:
0: [0x01] Frame start
1: [0xMeterValueByte0]
2: [0xMeterValueByte1]
3: [0xMeterValueByte2]
4: [0xMeterValueByte3]
5: [0x04] Frame end

and:
0: Serial.write(0x01); //start frame
1: Serial.write(0x00);
2: Serial.write(0x00);
3: Serial.write(0x02);
4: Serial.write(0x04); //end frame

Your receiver is looking for a pattern of 6 bytes, but your Arduino sketch is only sending a pattern of 5 bytes.
Your check for the start character is simple enough - you solved it fine a few lines above:
print "j= " + hex(ord(j))

But you forgot to do something similar for the check:
if (j == 0x1):

That should really be:
if (ord(j) == 0x1):

Helpful, but it still doesn't solve the problem with the checking of the first byte, does it?

@Dejvid_no1 Check my edit

Excellent, that did it! So I'm getting a character via the UART and what I really wanted was the Integer Unicode representation of that character which ord() solves. One step at a time...


text:
Building Arduino Nano from components
At this stage, my finalized design includes Arduino Nano 3.0, a breakout board and a few electrical components on a breadboard.
Will there be an appreciable cost savings from not buying a ready-made Arduino? The Arduino Nano clone being used costs $17.20.
And is it a good idea if everything is soldered on to a custom fabricated PCB board, including the components of Arduino Nano 3.0? The PCB board will cost around $10 at the quantities I'm starting with.

You should also consider if you actually need all the components the Nano has.

http://www.digikey.com/product-search/en/integrated-circuits-ics/embedded-microcontrollers/2556109?k=atmega328&quantity=1 http://www.digikey.com/product-search/en/integrated-circuits-ics/embedded-microcontrollers/2556109?k=atmega168&quantity=1

You can probably do a lot better than $17 but not much better than $8:
http://www.ebay.com/itm/Mini-USB-Nano-V3-0-ATmega328P-5V-Micro-controller-Board-For-Arduino-compatible-/130977189883?pt=LH_DefaultDomain_0&hash=item1e7ed94ffb
If you don't need USB, you can use a Pro Mini and they go for about $4 and that's really hard to beat.


text:
Programming a USB mouse connected to the Intel Edison Arduino expansion board
How can I programme a USB mouse connected to the standard USB port of the Intel Edison's Arduino expansion board?  I would like to measure the displacement of the mouse and also specify the frequency of image capture using the mouse's optical sensor.  I do not know much about programming so tutorials relating to my project would be very helpful.
Thanks

Here's a simple introduction to using the USB mouse as an input device. That might be a good starting point.
http://tahmidmc.blogspot.com/2015/12/using-input-device-on-embedded-linux.html


text:
Adafruit Huzzah and SD card breakout
I have an
Adafruit MicroSD card breakout board and an Adafruit Feather HUZZAH with ESP8266 WiFi
I wired that up according to this link's last picture.
The code I am using:
#include <SPI.h>
#include <SD.h>
...
const int chipSelect = 15;
...
Serial.print("Initializing SD card...");
pinMode(SS, OUTPUT);

if (!SD.begin(chipSelect)) {
     Serial.println("initialization failed!");
     return;
 }
Serial.println("initialization done.");
...

I always get the message "initialization failed", I also tried to format my SD card to be sure to have fat32 file system on it, but had no success with that.
What can I do to debug this error further?
TIA

From experience, I know the following

Using two SPI devices sometimes does not work, especially with fake SD breakout cards. Not sure about an Adafruit, but try to use only one SPI device at the same time (to check if it works better). For my project (initial setup), I had to use a SD logger extension board instead.
Sometimes it depends on the SD card which will work. Try to use older non SDHC/XDHC cards (smaller storage normally).
Use the most simple (and preferably example circuit) to test each component separately (thus your SD breakout card) before adding others (like the WIFI component). This rules out there is no problem with other components working at the same time.

what does this mean? ... tried to format my SD card


text:
Nothing is working even though every thing is right & it is new?
I have bought a new 'SunFounder Arduino uno R3' and started learning, the first lesson was 'Blinking LED' of course.
I have done it all, connected Jumper-Wires and the Sensor and the LED light, I wrote the code:
const int ledPin = 9;
void setup()
{
   pinMode(ledPin,OUTPUT);
}
void loop()
{
   digitalWrite(ledPin,HIGH);
   delay(500);
   digitalWrite(ledPin,LOW);
   delay(500);
}

BUT NOTHING HAPPENS !!!, I checked out every thing over and over, it just does not work ???
Every thing is well about the board and the UNO R3 it is new.
I have checked the code and the connections and checked the Device Manager to know that the serial port of the arduino is 'COM3'...
I dont know what is wrong with it ?!!

have you tried the built in LED on pin 13?

I did just now "Changed the Wire from 9 to 13 and on the code too. nothing happened

No wire should be necessary; leave the arduino disconnected from everything but the PC and set ledPin to 13.

As mentioned by BrettAM, pin 13 is good for testing since nothing needs to be hooked up. Also, be sure that the Arduino IDE has been set to the correct COM port and that the model of the device has been set correctly in the menus before uploading the sketch. You did upload the sketch, right? (compiling is not enough) When you upload the sketch, does the serial transfer light blink rapidly for a brief moment to show that the upload is taking place?

I did it worked with the light inside the arduino but what about the led ? Still not working!

Yeah Every thing u said I have done it... All right but led not blinking

Can you post a good quality, well focused picture of your setup, showing where all the wires are connected?

Try another LED (of which you know is working). Don't forget the current limiting resistor. And check some other pins. Try to invert the LED, they only work one way.

Oh sorry Guys I just figured out that the bread board sends electric power in line so I have to connect every wire with the same line that fits (+side of the LED or -side) yeah I didn't know that... So sorry for westing ur time and thanks u all.

In these cases it helps to break down the problem in pieces.
If the internal LED on pin 13 blinks with your code it means that the software side is OK so far (code, Arduino type, compiling, uploading etc), so I suggest looking at the physical side of things.
Do you have a multimeter available? If so, connect it between pin 13 and ground and it should show you if the output works.
Finally, is the LED working? When you connect it between 5V and GND (with a resistor!) it should light up.

Sorry for westing ur time friend, I just didn't know that the bread board sends power in lines my bad sorry and Thank u...


text:
How to read AC Voltage in arduino uno with 12V adaptor and usb cable.?
i want to ON-OFF two lights(white and red), one from main power source(white light) and one from ups(battery). When main power is present, white light should be ON and red should be off. And when main power fails, red should be ON and White should be OFF.
I have Arduino, usb cable, external power supplier(adapter of 12V).
Can any one please suggest me how do i proceed for this ??

If your battery voltage is lower than 12 but sufficiently high to power the arduino (let's say 9V), you could put a white LED on the 12V line and a red LED on the battery line, like this:
         WHITE       RED
  _______|>|_________|<|________
 |             |                |
_|_          Arduino           _|_
 - 12V         |                -   Battery
 |_____________|________________|

This should work, as long as the LEDs can withstand the reverse voltage.
And you do not need to drive them from the Arduino.
If you still want to know the status fro mthe Arduino (mains or battery) you can sample the voltage level across the Arduino.


text:
Erroneous sensor reading while connecting extra load
I'm making a speedometer using arduino. I've made use of the interrupt pins to achieve the same. My problem is with the power source. I'm using a 12 V battery supply to power the arduino and I'm also using the same battery to use a horn. But, whenever I push the button to sound the horn, the IR sensor connected to the arduino is getting activated and I'm getting an erroneous reading. The only common thing between the arduino and the horn is the battery supply.

If the horn has a speaker coil or other magnetic actuator in it, then it will present an inductive load that may cause a voltage spike when you turn it off.  Or, if it's a buzzer, it may generate voltage spikes all during its operation.  Voltage spikes or other electrical noise are the most likely cause of the problem.
It also is possible that the horn draws enough current to drop your battery voltage so low that the Arduino or the sensors don't function reliably.
To find out which is the problem, take voltage readings with and without the horn in operation.  If you have an oscilloscope, look for spikes on system power.
Try isolating and/or buffering the Arduino's power.  If power glitches are the problem, that should fix the problem.  If the problem is electromagnetically radiated electrical noise, further isolation (eg shielding) may be needed.
To isolate the Arduino's power, either operate it from another battery (which is something you can do anyway, while diagnosing the problem) or add one diode into the Arduino's power lead and another into the horn's.  Connect an electrolytic capacitor, eg 100 to 1000 μF, from the Arduino's +V input to ground.  If necessary add ferrite beads around the power leads.
A capacitor across 12 V from the battery will buffer the power, but for more isolation and buffering you can add a buck converter which can manufacture eg +7V from a +12V input while remaining relatively impervious to spikes on the +12V.  Put the large electrolytic across the +7V if you use a buck converter.

Thank you for your answer, but the thing is the arduino itself is not resetting or switching off during the horn operation, it's perfectly driving the GUI display and other stuff it's used for. Only the values are changing. And yes, the voltage is dropping very much across the battery( low CCA, I suppose) but not directly affecting the arduino's operation.


text:
Suggestions for a program for drawing simple schematics
I'm wondering if there are free programs or web sites that let you draw simple schematics similar to this example:

https://www.circuitlab.com/ ; Fritzing ; Circuitmaker ; Eagle ; KiCad (kind of in order of complexity)

See Good tools for drawing schematics from our sister EE.SE site. It's a pretty complete list of software for drawing schematics.

While at it, see also Rules and guidelines for drawing good schematics, from the same source.

A compilation of possibilities mentioned the comments. I'll add to this as I try out the suggestions.
From @Gerben, "kind of in order of complexity":

circuitlab.com - online schematic capture and simulator (analog, digital, and mixed signal). Licensed for professional, student/educator, and hobbyist (free) usage. Officially runs in Chrome and Firefox, and they report users having success with Safari and Opera which are not officially supported.
Fritzing - cross-platform (Mac, Windows, Linux). Has Breadboard View mode with built in Arduino support that allows you to create diagrams like this one:

From there you can click on the Schematic view to route wires and convert the breadboard into a traditional schematic.
CircuitMaker - Windows only, requires creating an account.
Eagle - cross-platform (Mac, Windows, Linux), paid and free versions.
Component library collections (thanks to Marko Mackic for the idea):

Adafruit
Element14 Arduino library - requires registration, lots of other libraries as well
Sparkfun

KiCad - cross-platform (Mac, Linux (with packages for several distributions), Windows, and source code), open source and also on GitHub.

Found Autodesk's 123D Circuits in a question on Arduino Simulators (and emulators).

I've been using ExpressSCH (Express Schematic) from: http://www.expresspcb.com/
That is a free install for Windows and is pretty easy to use.
Example of its output:

It comes with quite a few symbols defined, and you can easily make your own extra ones (like the Uno I did in the schematic above).

Myself, I prefer to use Eagle, and download Sparkfun and Adafruit libraries for components based around Arduino. There you can create schematics, and create PCB layouts too.

There are many cicuit drawing softwares available on the internet.
Besides the softwares mentioned above, I would like to recommend EasyEDA editor.
It’s a free, web-based EDA suite, you can use it without installing anything.
Mac, Linux, Windows and Android,All platforms supported.
EasyEDA has simple but powerful drawing capabilities, it’s part library is quite massive and there is plenty of parts to pick from. Users can create their own symbols and footprints either by copying existing ones into My Parts then editing and saving them or by drawing them from scratch.
For example, here is a simple 555 circuit.


text:
Can external interrupts be OR'd together on the '328 (Uno)?
I'm thinking about how to handle a rotary encoder. I'm planning on using interrupts and would like to use both the 'A' and 'B' phase transitions to generate interrupts. I'm wondering if there is any reason why the signals couldn't be OR'd together to generate the interrupt so that I wouldn't need to consume both external interrupts for the encoder.

You still need to read both signals regardless, so you only end up using an extra pin.

I know I'd still need to use two pins to read the state of the encoder, but I was hoping to use one interrupt pin and one non-interrupt pin and still be able to get full resolution from the encoder.

All ATmega328P pins support pin change interrupts.

Yes, but my understanding is that the "internal" interrupt latency and/or software overhead is much higher than it is for the "external" interrupts – so I was hoping to find a way to use a single external interrupt. I have't actually measure the difference yet, so I don't know how big a hit it would be to use the internal interrupts for this application. But the question is also generally interesting if the technique could be used in other situations as well.

Regarding the notion that “"internal" interrupt latency and/or software overhead is much higher than it is for the "external" interrupts”, it certainly is true that PCI (pin-change interrupts) libraries PinChangeInt.h (deprecated) and EnableInterrupt.h have high software overhead.  By keeping track of former values, for each pin those libraries support separate callback routines for Rising, Falling, Change, High, and Low.  PCIs are grouped in sets of eight pins per interrupt vector, leading to 40 different cases of callback routines when a PCI fires.  That is, when a PCI occurs, the libraries quickly find out which set of pins changed – because that's what the hardware supports – but then they go through all eight pins on the vector one by one checking if it changed, and how it changed, then calling the callback associated with the particular pin and its particular state.
For reading pins of a rotary encoder, say a KY-040, the overhead described above can cause loss of 10%–20% of rotary counts.  If you are concerned about not losing counts, write your own ISR()-level interrupt service routine.  The example below illustrates a routine using ISR(); this example is from my answer to previous question #18221, with some comments added here and there.  See that answer for discussion of the timing data that is this program's output.  (For rotary encoder quadrature-counting, see discussion below).
/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: https://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */
#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[4]; // times of prev. rising edges
volatile unsigned long rcTimes[4]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter

// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  // Note, if using an encoder without pullups on it,
  // change INPUT in next 2 lines to INPUT_PULLUP
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt
  pinMode(A2, INPUT);
  pinMode(A3, INPUT);
  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[4]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    rcT[0] = rcTimes[0];
    rcT[1] = rcTimes[1];
    rcT[2] = rcTimes[2];
    rcT[3] = rcTimes[3];
    sei();          // reenable interrupts

    Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1]
       << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl;
  }
  sei();            // reenable interrupts
}

Note, for the above you may need to download and install Streaming.h via Streaming5.zip from arduiniana.org.
Rotary encoder quadrature-counting
The program above tracks and reports pulse-length times, instead of decoding the quadrature signals the rotary encoder provides.  The program below reports rotary encoder counts, but does so using INT0 and INT1 instead of PCIs.  You will want to combine relevant portions of the two routines together – ie, use the interrupt setup and handling framework from above, with the body of the service routine from below.  [Note, this program is from my answer to previous question #16420.  The encoder decoding code within it is faster and shorter than other decoding code I've looked at, and is fast enough to support two encoders rotating simultaneously while losing few counts.]
/*  roto_jw4.ino -- JW, 29 September 2015 --
 *  A 4-state state-machine implementation of rotary
 *  encoding for KY-040 rotary knobs.  The state-machine picture at
 *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
 *  in a Feb 4, 2014 7:40 PM post by Anthony Seely shows counts
 *  increasing on transitions 10 -> 11 -> 01 -> 00 -> 10 and
 *  decreasing on transitions the other way.  Transitions between 00
 *  and 11 or 10 and 01 are invalid.  This code detects valid
 *  transitions by (abOld xor abNew) equaling 1 or 2.  It detects
 *  up-count events by the tri-bit value ABA' (where A' is the new
 *  reading on pin A) being equal to 1, 2, 5, or 6 (a bit mask of
 *  0x66), and down-count events by ABA' being equal to 0, 3, 4, or 7
 *  (a bit mask of 0x99).
 *
 *  On a KY-040 unit I tested, there are 30 detent positions per turn.
 *  With this unit the code generates 60 counts per turn, which can be
 *  seen individually as one turns the rotor slowly.  Odd counts
 *  appear between detents, even counts at detents.
 *
 *  Set quadrature-signal pin numbers, via PinA and PinB constants.
 *  Set IPINMODE to INPUT_PULLUP if there are no external pull-ups
 *  on encoder AB pins, else set IPINMODE to INPUT
 */
enum { PinA=2, PinB=3, IPINMODE=INPUT };

static  byte abOld;     // Initialize state
volatile int count;     // current rotary count
         int old_count;     // old rotary count

void setup() {
  pinMode(PinA, IPINMODE);
  pinMode(PinB, IPINMODE);
  attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
  attachInterrupt(1, pinChangeISR, CHANGE);
  abOld = count = old_count = 0;
  Serial.begin(115200);
  Serial.println("Starting Rotary Encoder Test");
}

// On interrupt, read input pins, compute new state, and adjust count
void pinChangeISR() {
  enum { upMask = 0x66, downMask = 0x99 };
  byte abNew = (digitalRead(PinA) << 1) | digitalRead(PinB);
  byte criterion = abNew^abOld;
  if (criterion==1 || criterion==2) {
    if (upMask & (1 << (2*abOld + abNew/2)))
      count++;
    else count--;       // upMask = ~downMask
  }
  abOld = abNew;        // Save new state
}

void loop() {
  if (old_count != count) {
    Serial.print(millis());
    Serial.print("  ");
    Serial.println(count);
    old_count = count;
  }
}

Using other pins for PCIs
If you wish to monitor two rotary encoder lines using pin change interrupts on pins other than A0 and A1, you may need to replace vector PCINT1_vect with some other vector, and will need to replace the pins mask with a different one.  The following program can be used to display a table of PCI vectors, masks, etc.  (As noted in my question Why PJ0 and PJ1 are not reporting as PCINT pins, pins PJ0 and PJ1 on an ATmega-2560 board will not report correctly.)
/*  pinsList -- JW, 4 October 2015 --
 *
 *  Displays a list of Arduino pin numbers for current kind of Arduino
 *  board, along with port codes, pin-change-interrupt numbers, and
 *  pin-change-interrupt vector numbers.
 *
 *  Here are two examples of output lines for pin 11, the first for an
 *  Uno, the second for a Mega:
 *
 *        11   PB3   0x04   PWM   PCINT3  PCINT0_vect
 *        11   PB5   0x20   PWM   PCINT5  PCINT0_vect
 */
//-----------------------------------------------------------
// Given a value with 1 bit set, return bit #.  Else return 9.
byte getBitfromBV (byte m) {
  byte b=0, v=1;
  while (v) {
    if (m==v)
      return b;
    ++b; v <<= 1;
  }
  return 9;
}
//-----------------------------------------------------------
void processPinNumber(byte pin) {
  char buffi[128];      // We create text-to-write in buffi
  byte nbuff=0;         // #chars used in buffi
  byte nPCICR;          // 0, 1, or 2 for mask-register #
  byte bitInByte;       // 0 to 7 for bit in I/O mask
  byte pinPort;         // pin's port #, in range 1 to 12
  byte PCInum;          // PCINT# if pin is a PCI pin
  char *portLet = "?ABCDEFGHIJKL";

  if (pin >= NUM_DIGITAL_PINS) return;

  pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
  bitInByte = getBitfromBV(digitalPinToBitMask(pin));

  nbuff = snprintf(buffi, sizeof(buffi), "  %2d   P%c%d  0x%02x",
           pin, portLet[pinPort], bitInByte, 1<<bitInByte);

  // Indicate if it's a PWM pin
  if (digitalPinHasPWM(pin)) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "  PWM");
  } else {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "     ");
  }

  // If it's a PCINT pin, show its PCINT number and 0, 1, 2 for its vector #
  if (digitalPinToPCICR(pin)) {      // Is it a PCint pin?
    nPCICR = digitalPinToPCICRbit(pin); // 0, 1, 2 for pin's PCICR bit#
    PCInum = nPCICR*8 + bitInByte;
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff,
             "  PCINT%d  PCINT%d_vect",  PCInum,  nPCICR);
  }
  Serial.println(buffi);
}
void setup() {
  delay(50);
  Serial.begin(115200);
  delay(50);
  while (!Serial) ;             // wait for serial stream to connect
  Serial.println("\nPin#  Port  Mask  PWM   PCINT");
  for (byte p=0; p<NUM_DIGITAL_PINS; ++p)
    processPinNumber(p);
  Serial.end();
}

void loop() {
}

ISR-framework-generating Sketch
The program below generates frameworks for specified PCI pins and prints them to Serial.  See usage comments within the program.  This provides an easy way to create the basic outline of an ISR to handle PCIs.
/*  pinFunctions -- JW, 1 October 2015 --
 *
 *  Displays direct pin-access and pin-change-interrupt setup code,
 *  for inclusion in a sketch, for specified pin numbers.  The
 *  displayed code can be pasted into a sketch where execution speed
 *  matters.
 *
 *  When called with a call like `genCode ("affix", "9,11");`, genCode
 *  will produce a set of procedures: ISR routines for pins that
 *  support pin-change interrupts; get and put routines to read from
 *  or store to registers; and a setup routine.  The generated get,
 *  put, and setup routines will have names formed by suffixing the
 *  affix to get, put, and setup, respectively.  For example, if the
 *  affix is ML47 the names of generated routines will include
 *  getML47, putML47, and setupML47.
 *
 *  Generated get() and put() code is of the following forms (in which
 *  u, v are port-letters; values mu, mv, ni are numerical constants;
 *  and w is a parameter value) if all the pins, n1, ... nk in the
 *  pins-list are in port u, under mask mu:
 *
 *             return PINu & 0xmu; // Get pins n1, ... nk
 *             PORTu = PINu & ~mu | w & mu;
 *
 * For example, with Uno pins 3, 4, 6, get() and put() bodies are:
 *
 *             return PIND & 0x58;
 *             PORTD = PIND & 0xa7 | w & 0x58;
 *
 *  The following forms arise if the pins are in ports u and v; and so
 *  forth if more than two ports are involved.
 *
 *             return PINu & masku | PINv & mv; // Get pins n1, ... nk
 *             PORTu = w & 0xmu;   // Put pins <u pins>
 *             PORTv = w & 0xmv;   // Put pins <v pins>
 *
 *  genCode() does not require that all pins belong to the same port.
 *  It will produce usually-desired results if bit positions don't
 *  interfere, otherwise may not.  For example: An Arduino Uno
 *  pins-list "2,10" corresponds to port pins PD2 and PB2.  Both are
 *  in bit position 2, so get's result will be the OR of the PB2 and
 *  PD2 values, while put will store the same bit value to both pins.
 *
 *  To use the pasted code: A statement like `w = getAFFIX();` will
 *  read a set of pins and store the value in w.  A statement like
 *  `putAFFIX(w);` will write w to a set of pins.  Also, add a line
 *  like the following in setup():
 *
 *       setupAFFIX(ioMode, enablePCI);
 *
 *  In the `setupAFFIX(ioMode, enablePCI);` call, substitute an
 *  appropriate affix in place of AFFIX; substitute one of INPUT,
 *  OUTPUT, or INPUT_PULLUP in place of ioMode; and substitute 1 or 0
 *  for enablePCI, to enable or not enable pin-change-interrupt setup.
 *
 *  If you want to save room and don't plan to use pin-change
 *  interrupts, instead of merely not enabling PCI setup, you can
 *  remove the ISR routines and the `if (enablePCI) {...}` section
 *  from the pasted code.
 *
 *  Each generated ISR routines contains one line, of form
 *
 *        byte datum = PINu & mu; // Read pins <list>
 *
 *  The idea is that you will paste the generated ISR into your
 *  sketch, then populate it with appropriate interrupt processing
 *  code.  Note 1: datum contains data from one port, a port which
 *  belongs to the interrupt vector.  If you need data from other
 *  ports as well, then paste appropriate lines from the get() routine
 *  into the ISR.  Note 2: This version of pinFunctions does not
 *  announce pins that don't belong to PCI vectors, if any.
 *  (Processor pins with functions like PCINT0 ... PCINT23 belong to
 *  PCI vectors.)  You can compare the masks used in get() to those
 *  used in the ISR's to detect this.  If the masks differ, some pins
 *  aren't PCI pins.  Note 3: If multiple ports' pins belong to one
 *  vector (eg Ard#0 or PE0 for PCINT8 and Ard#15 or PJ0 for PCINT9,
 *  both on vector PCINT1_vect), a code-generation error of form "Pin
 *  x's port #y isn't #z" will appear and you will need to paste in
 *  appropriate lines from get() or otherwise manually prepare correct
 *  code.
 */

char buffi[128];        // We create text-to-write in buffi
char buffn[32];         // also in buffn
byte nbuff=0;           // #chars used in buffn
char *c;            // c points into pinsList
byte pin;           // pin number
byte nPCICR;            // 0, 1, or 2 for mask-register #
byte vecmask;           // OR of 1<<nPCICR values
byte intmask[3];        // OR of int. enable masks
byte maskBitPC;         // 0 to 7 for bit in PCI mask
byte maskBitIO;         // 0 to 7 for bit in I/O mask
byte pinPort;           // pin's port #, in range 1 to 12
byte PCInum;            // PCINT# if pin is a PCI pin

// Given a value with 1 bit set, return bit #.  Else return 9.
byte getBitfromBV (byte m) {
  byte b=0, v=1;
  while (v) {
    if (m==v)
      return b;
    ++b; v <<= 1;
  }
  return 9;
}

// Get next pin number from pinsList, and its associated reg numbers
byte getPinNumber() {
  byte cc=*c;
  if (!cc)
    return 0;
  pin=0;
  for (; '0' <= cc && '9' >= cc; cc=*++c) {
    pin = 10*pin + cc - '0';
  }
  pinPort = maskBitIO = PCInum = nPCICR = maskBitPC = 0;
  if (pin < NUM_DIGITAL_PINS) {
    pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
    maskBitIO = digitalPinToBitMask(pin);
    if (digitalPinToPCICR(pin)) {        // Is it a PCint pin?
      nPCICR  = digitalPinToPCICRbit(pin); // 0, 1, 2 for p's PCICR bit#
      maskBitPC = digitalPinToPCMSKbit(pin);
      PCInum =  nPCICR*8+ getBitfromBV(maskBitIO);
    }
  }
  if (!cc)         // At end of string? If so,
    --c;           // allow for caller incrementing c
  return 1;
}

void genCode (char *affix, char *pinsList) {
  char *portLet = "?ABCDEFGHIJKL?";
  enum { portMax=12 };
  byte readmask;        // Input-bits mask
  byte port;            // Port #

  snprintf(buffi, sizeof(buffi), "\n// %s : pins %s", affix, pinsList);
  Serial.println(buffi);

  //==================================================================
  // Generate  "byte get<affix>() { // Get pins <list>"
  //              return PINu & mu | PINv & mv | ...
  //            }"
  nbuff = snprintf(buffi, sizeof(buffi), "byte get%s () { // Get pins", affix);
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "% d,", pin);
    readmask |= maskBitIO;
      }
    }
    if (readmask) buffi[nbuff-1] = ';'; // Replace extra , by ;
  }
  Serial.println(buffi);    // Print first line of get...() function
  nbuff = snprintf(buffi, sizeof(buffi), "  return");
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    readmask |= maskBitIO;
      }
    }
    if (readmask)
      nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, " PIN%c & 0x%02x |",
            portLet[port], readmask);
  }
  snprintf(buffi+nbuff-2, sizeof(buffi)-nbuff, ";\n}"); // -2 loses extra " |"
  Serial.println(buffi);  // Print last two lines of get...() function

  //==================================================================
  // Generate  "void put<affix>(byte w) { // Put pins <list>"
  //              PORTu = PINu & ~mu | w & mu;
  //              ...
  //            }"
  nbuff = snprintf(buffi, sizeof(buffi), "void put%s () { // Put pins", affix);
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "% d,", pin);
    readmask |= maskBitIO;
      }
    }
    if (readmask) buffi[nbuff-1] = ';'; // Replace extra , by ;
  }
  Serial.println(buffi);    // Print first line of put...() function
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    readmask |= maskBitIO;
      }
    }
    if (readmask) {
      snprintf(buffi, sizeof(buffi), "  PORT%c = PIN%c & 0x%02x | w & 0x%02x;",
           portLet[port], portLet[port], (byte)(~readmask), readmask);
      Serial.println(buffi);  // Print a port-setting line of put...() function
    }
  }
  Serial.println("}");  // Print last line of put...() function

  //=================================================================
  // Generate ISR's:  Process 3 possible pin-change interrupt vectors
  vecmask = 0;
  for (byte ivect=0; ivect < 3; ++ivect) {
    byte sinPort=15;        // currently-in-use same port #
    intmask[ivect] = 0;
    byte busyvect=0;              // Assume vector not used
    byte readmask=0;              // Input mask
    // Loop to see if vector is used
    for (c = pinsList; getPinNumber(); ++c) {
      if (nPCICR == ivect) {
    ++busyvect; sinPort = pinPort;  // Bits on same port get read once
    vecmask |= 1<<ivect;
    intmask[ivect] |= 1<<maskBitPC;
      }
    }
    if (busyvect) {     // If vector is busy, create its ISR
      snprintf(buffi, sizeof(buffi), "ISR(PCINT%d_vect) {", ivect);
      Serial.println(buffi);
      nbuff = 0;
      for (c = pinsList; getPinNumber(); ++c) {
        // See if it's a PCint pin, and on the current vector
    if (digitalPinToPCICR(pin) && nPCICR == ivect) {
      intmask[ivect] |= 1<<maskBitPC;
      readmask |= digitalPinToBitMask(pin);
      nbuff += snprintf(buffn+nbuff, sizeof(buffn)-nbuff, " %d,", pin);
      if (pinPort != sinPort) {
        snprintf(buffi, sizeof(buffi), "Pin %d's port #%d isn't #%d",
             pin, pinPort, sinPort);
        Serial.println(buffi);
      }
    }
      }
      snprintf(buffi, sizeof(buffi), "  byte datum = PIN%c & 0x%02x; // Read pins %s\n}",
           portLet[sinPort], readmask, buffn);
      Serial.println(buffi);
    }
  }
  snprintf(buffi, sizeof(buffi), "void setup%s(byte ioMode, byte enablePCI) {", affix);
  Serial.println(buffi);
  for (c = pinsList; getPinNumber(); ++c) {
    nbuff = snprintf(buffi, sizeof(buffi), "  pinMode(%2d, ioMode); // %2d, P%c%d",
         pin, pin, portLet[pinPort], getBitfromBV(maskBitIO));

    if (maskBitPC)
      snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "   PCINT %d", PCInum);
    Serial.println(buffi);
  }
  Serial.println("  if (enablePCI) {");
  for (byte ivect=0; ivect < 3; ++ivect) {
    if (intmask[ivect]) {
      snprintf(buffi, sizeof(buffi), "    PCMSK%d |= 0x%02x;", ivect, intmask[ivect]);
      Serial.println(buffi);
    }
  }

  snprintf(buffi, sizeof(buffi), "    PCIFR  |= 0x%02x; // clear PC interrupts if any",
       vecmask);
  Serial.println(buffi);
  snprintf(buffi, sizeof(buffi), "    PCICR  |= 0x%02x; // enable PC interrupts\n  }\n}",
       vecmask);
  Serial.println(buffi);
}

void setup() {
  Serial.begin(115200);
  while (!Serial) ;             // wait for serial stream to connect
  Serial.println("Starting Code Generation");
  genCode ("A0A1",  "14,15\0"); // A0, A1 on a nano
  genCode ("Pair78",  "7,8");
  genCode ("Trip346",  "3,4,6");
  genCode ("Quad789A", "7,8,9,10");
  genCode ("Hex8toD",  "8,9,10,12,11,13");
  genCode ("LotsSmall", "2,6,7,8,9,10,11,12,13,14,15,19,20,21,22,28,29,30,31,37");
  genCode ("LotsBig",   "31,37,38,37,38,45,46,52,53,54,55,61,62,63,69,70,71,76");
  Serial.println("Ending Code Generation");
  Serial.end();
}

void loop() {
}


text:
Building projects on the command line using the Bare-Arduino-Project template
I'm trying to program an Adafruit Trinket using avr-gcc et. al. with the Makefile from the Bare-Arduino-Project on macOS Catalina.
I can build projects for standard boards like the Uno, but not for the Trinket. Everything works as expected using the "official" Arduino IDE (1.18.10). In the Bare-Arduino-Project Makefile I'm specifying the Trinket as:
BOARD_TAG         = trinket5
BOARD_SUB         = attiny85

I get an error from avr-gcc that mmcu is not defined. I assume this is because the command line tools aren't finding the Adafruit equivalent of boards.txt. When I look in the Arduino IDE package I don't find the Adafruit boards in boards.txt or anything that looks like the definitions for the Adafruit boards (despite having added them in the IDE).
Any ideas about how to set up support for the Trinket (or other third party boards) when using command line tools?

You  probably look at the wrong boards.txt:
# Trinket 5V Configuration
trinket5.name=Adafruit Trinket (ATtiny85 @ 16MHz)

this can be found in the boards.txt in the main directory
C:\Users\YOUR_USER_NAME\AppData\Local\Arduino15\packages\arduino\hardware

in the sub directory
\adafruit\avr
in the same main directory should  also be a folder named 1.8.2 (for ArduinioIDE 1.8.12) for the core files
if added via board-manager using this line in preferences/additional bord manager urls
https://adafruit.github.io/arduino-board-index/package_adafruit_index.json

If you did a manual installation check with this guide for pit traps.Details on using trinket with the avrdude command line can be found here

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


text:
Ethernet shield and IPv6 support
Have you heard about support for IPv6 protocol for any Ethernet shield?
As far as I know only IPv4 is supported.
Maybe some one would like to write library?

There is no library, and there physically cannot be one. IPv4 is built into the Ethernet shield itself. (It has a Wiznet 510 chip.)

Shields based on the MicroChip ENC28J60 chip (such as those sold by Ekitszone and Nuelectronics) are suitable for the implementation of an IPv6 or dual IPv4/IPv6 stack. This approach requires the TCP state machine to be implemented in software and results in more complex arduino code.

Source: this tutorial. (You may find it useful, I'd recommenced reading it.)
There is this library for IPv6 on other hardware, not for the official Ethernet shield.

While the W5100 chip does not support IPv6 at Layer 3, it does have a layer 2 mode (MACRAW) for sending Ethernet frames directly, so can be used to send and receive IPv6 in the same way as the ENC28J60.

I have been working on an IPv6 library for Arduino, called EtherSia, that works with the ENC28J60 chip, but with a lower overhead compared with libraries that use Contiki / uIP. It is comparable to the EtherCard library for IPv4.
https://github.com/njh/ethersia
While the Wiznet chips do not support IPv6 natively, they do have a MACRAW mode that allows you to send Layer 2 Ethernet frames directly. I have managed to get IPv6 working with the Wiznet W5100 and W5500 chips, which is what the official Arduino Ethernet Shield and Ethernet Shield 2 use.
So it is possible...


text:
Flashing a ATmega328 that came from an Arduino to not use an external oscillator
I have a ATmega328p chip from a kit that was supposed to be an Arduino compatible thing. I decided to go beyond Arduino and try to program the chip directly. I setup an UNO as an Arduino ISP, more or less like the image here, but added some LEDs to pins 8, 9 and 10 for feedback.

This image has this caption.

Because no external clock source is connected, the ATmega must be configured to use its internal clock.

I think this chip was flashed with whatever tells it to use an external oscillator. And I do not have an external oscillator.
So how can I tell the chip to again use an internal oscillator when using an UNO as my programmer?
» avrdude -p m328p -c avrisp -b 19200 -P /dev/cu.usbmodem1d11121

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

I assume a device id of zero means the chip is not responding with data? because it's core is not cycling?
Do I need an oscillator installed just so I can wake it it up and tell it to not use an oscillator?

If the chip was blank, it would be running at 1mHz. You'd need to lower the programming speed (avrdude -B10 ...).

@Gerben Mega, not milli ;)

Do I need an oscillator installed just so I can wake it it up and tell it to not use an oscillator?

Yes, yes you do.
Pick up a 8-16MHz crystal (not an oscillator) and two 15pF capacitors and use very, very short wires to connect them to the chip as shown in the "System Clock and Clock Options" section of the '328P datasheet. You will then be able to reprogram the fuses using AVRDUDE.

Even though an answer has been accepted, I just want to add for future viewers that you can google for arduino breadboard internal oscillator and get the text to copy into the boards.txt file.  That will allow you to use the Arduino IDE to burn the fuses.  You will be able to find versions to run at both 8mhz and 1mhz.
Also, if you have an extra Uno laying around, you could always pop the chip in there and reset the fuses, then take it out and use it on a breadboard.

But note that even though you will be able to do it via the Arduino IDE, you cannot set fuses through the serial connection; you must use ISP or HVPP in order to set fuses.


text:
Programing in Assembly for the Digispark
I've been given a digispark and am looking to write straight assembly code for it. Anyone know how to get started with this? I've been successful in getting the Arduino IDE set-up but would really like to avoid writing assembly in-line...

If you want to write assembly, ditch the arduino IDE and just use the avr toolchain straight.

@BrettAM I've really been trying to figure it out. Know of any good tutorials that might help? Appreciate the response.

Why do you want to? Seriously.

In 2021, I use VSC + Platformio.
I create a main.asm file in which I put the code from https://github.com/pda/digispark-asm.
In the "platformio.ini" file I define the digispark as :
[platformio]
default_envs = digispark-tiny
[env:digispark-tiny]
platform = atmelavr
board = digispark-tiny
I run the code, upload it to a digispark and this works amazingly well.

I've been given a digispark and am looking to write straight assembly code for it. Anyone know how to get started with this? I've been successful in getting the Arduino IDE set-up but would really like to avoid writing assembly in-line...

The Arduino IDE build support assembly files (.S). Nerd Ralph has written a  blog on the subject. There you will find all the details and how to write both inline and pure assembly files. He is really god at digging out all the details and sharing his findings.

There seems to be some specific attiny flag required but by the gcc in order to make the genereated hex file work with digispark. Take a look here https://github.com/pda/digispark-asm.

A specific flag? You mean -mmcu=attiny85?

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


text:
What is the memory expense of creating a String from a char array?
I'm writing a little API for processing email messages in Arduinos. Obviously, I need to keep memory use down, but I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.
My logic uses char arrays (so that memory is statically allocated). If my end user converts a char array to a String (so that they can easily see if an email subject startsWith() a particular word) will this result in doubling the character memory used? .. or will the String class simply include a pointer to the original char array (and just add some cruft)?
What would be the best-practice in this kind of situation?

What would be the best-practice in this kind of situation?

To not use String.

I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.

There's nothing wrong with providing an indexOf function in your API.  But you don't have to use String to implement that function when called.  You can just use the strstr function on char arrays (reference here).
I should also point out that most Arduinos do not have enough RAM for storing an email.
UPDATE 07-01-2016:
To answer the titular question, the fixed cost of using String is at least 1600 bytes of program space, more if you use more than a few methods.  The linker can throw out methods you don't use.
Then for each String variable you declare, the recurring cost is 8 bytes for the variable itself, plus the variable-size memory chunk for your character data.  This chunk is allocated from the heap, and is the size of your string plus 4 more bytes to manage the chunk within the heap.  That's a total of 12 extra bytes per String instance.
However, I did not originally answer that question because you explicitly asked about the memory expense.  This ignores other expenses that should not be ignored:

execution time - Allocating memory from the heap is really a search for a chunk of the requested size.  At the beginning it can be quick, but as the heap gets fragmented (small chunks build up) it takes longer to find a chunk.  And when the String is emptied or destroyed, the memory chunk gets put back into the heap and (possibly) merged with adjacent chunks.  Reducing the size of a String does not free up any memory.  The String maintains its maximum size until it is emptied or destroyed.
long-term stability - Embedded Systems are supposed run forever.  A primary characteristic of a system that can run forever is "deterministic."  For whatever inputs it receives, it has a predictable response and end state.  When you use the heap via String, the heap gets fragmented according to the data it handles.  This is not predictable, and it may get into a state where no memory chunk of the requested size is available.  Choke.
maintenance - because the heap state depends on the processed String data, finding the cause of the failure can be difficult.  It can fail at different times because the input data is different, and it can fail at different places in the program.

Because of these expenses, String is rarely used by an experienced developer.  Unfortunately, String is tempting to the beginner because it is easy to understand.  What is difficult to understand is the complicated, non-deterministic behaviour under the hood that inevitably leads to system failure, rending of garments and gnashing of teeth.

thanks slash-dev. I know about Arduino's limited RAM. I'm working on a Mega so it is not too bad. I am limiting the amount of text that can be read from the email. The idea is to be able to "send commands" to an Arduino via email. So the email body might only contain the text "turn thingy on"

Could I just state that I'd still like to know what is the memory expense of turning a char array into a String ...

@Etienne, response added above.  BTW, if you parse the email as it is received, character-by-character, you may not need to store and search the email text.  Instead, you only have to store the command "number" and appropriate parameter values.  Finite-State Machines are very powerful for these kinds of applications.

[I'm a year late but this or a related question gets asked often enough, I think it's worth another answer.]
With a Mega, there's enough memory to consider doing what you propose if we make some assumptions and modifications:

We know or can accept a maximum size of a string, above which, memory allocation will fail, detectably (the allocator returns a NULL pointer and the object handles the failure gracefully);
We use a non-fragmenting allocation method - statically allocated buffer pools of one or more fixed sizes - that are allocated and returned intact. No splitting or merging will take place. A given request will be filled with a buffer of the requested size or larger, if one is available.
Either the String object is modified to only use the new allocator or the system 'new()' is replaced by it.

The obvious disadvantages are:

The entire heap will not be eaten up by a fragmented memory pool. ("Heap" is that space between the statically allocated memory and dynamically growing and shrinking stack. When the stack and heap meet, your application fails).
You'll need to know something about your application's memory needs to plan the buffer pools.
You'll have to plan to prevent or handle allocation failure.

In exchange, you get:

The allocator won't crash your system.
The String object's programming advantages become available.
You'll write better code since you had to think about and plan for its needs rather than let a dumb and fragmenting allocator blindly consume the heap.

So... if you perform the analysis required to not use String (i.e., sizes and lifetimes), change the implementation of String (not the interface), and replace malloc with God's Algorithm, you could use String?  That's not String, that's the Hypothetical String of Theseus that someone could write in the future.  -_-

Are you being facetious? I have implemented just this sort of thing; not for String Object but for other allocate/deallocate system requirements. If the allocator is reimplemented, String need not be. This is not vaporware or blue sky-ing. It's quite real. Why not try it first, then critique it?


text:
How to send an email via Arduino without an email account?
Assuming I have all the necessary hardware...
I want to develop a system where you type in an email address and the Arduino will send hourly updates on attached sensors to the provided email address.
I can only get this to work if I enter my email account's username and password and send the email from the authenticated account. There's tons of examples online of this. However, I want to share it with others and I do not want my email authentication to be accessible or be attached with sending the emails.
For example, I want the email to be from a generic service like email@web-mail.com that no one can sign into and not my personal email or a Gmail account I made for the project.
Anonymous email senders have the right method, but they require human interaction to bypass Captcha or similar.
Does anyone have an idea of how to do this? Or should I make a separate webserver that handles the requests made by the Arduino and send emails through a Gmail account I made for the project?

Even if you can get a basic SMTP connection going as per the answers already given, unless you use a registered domain with the correct SPF and/or DKIM settings etc, you may well find a lot of your emails rejected, and your "from" address blacklisted as a spammer.

You may be able to do this by running the SMTP transaction yourself. You don't actually need a valid from address (though I probably shouldn't be saying that). There are a number of resouces for how to do this, here's a quick list:

Arduino Playground Email Client page
Adafruit
How to send an email with Arduino and a WiFi shield?

If you read an article telling you how to do SMTP in a generic sense (not using a particular provider's infrastructure) and it looks like they want a "real" e-mail address, you can try with a fake one. Chances are decent that it may work.
There are some fine points that may cause you grief if you go for the most simple of implementation (for example, just because my e-mail address is foo@bar.org doesn't mean that bar.org will accept an SMTP connection, the "right" way to do it is to check DNS for an MX record for bar.org).
It would be best to do (and log) any errors that you encounter. There are plenty of things that can go wrong, so tracking where it blows up will help you – or anybody who's trying to help you debug.
If you don't want to roll your own SMTPClient and FullIP look worth checking out.

I am thinking that you will have a few issues in doing this,
If you wish to, as mentioned by dlu, run the SMTP Transaction from the device yourself, you are free to do that, however, most SMTP Relays will require some sort of authentication; this is to prevent me from using a random relay to send out millions of messages.
Another issue may be that if you do setup a local relay, your ISP will block traffic on port 25, which is common; this means your mail can never be delivered to an external server.
My thoughts on the simplest way to do this would be getting a Virtual Private Server that will run the mail service and a webserver; you could then make a simple PHP script that will accept a few parameters, and send an email.
Following the above, you would only need to make an HTTP request to your server for the mail to be sent,
http://web-mail.com/sendmail.php/?to=someone@somewhereelse.com&subject=Wooo&Message=This%20is%20a%20message.


text:
How to use Infra Red (IR) to reset arduino board
I am a big noob I know that
but can this code be used to reset arduino board (instead of pressing the usual reset button on the board)
I want to reset the board as If am pressing the reset button using IR
int receiverpin = 2; // pin 1 of IR receiver to Arduino digital pin 2
#include <IRremote.h>
IRrecv irrecv(receiverpin); // create instance of irrecv
decode_results results;
void setup()
{
irrecv.enableIRIn(); // start the receiver
}
void(* resetFunc) (void) = 0; //declare reset function @ address 0

void loop()
{
 if (irrecv.decode(&results)) // have we received an IR signal?
{
if(results.value == 0x2FD847B) //if the button press equals the hex
{
  resetFunc();
}
{
irrecv.resume(); // receive the next value
}
}
}

Kind of, yes.  That doesn't actually reset the Arduino, it just sends the program to address 0.
There are two other ways of performing the reset that do a proper full reset:

Enable the watchdog timer and let it time out to reset the CPU.
Connect an IO pin to the RESET pin - keep it in INPUT most of the time but set it to OUTPUT and LOW when you want to reset.

By just jumping to address 0 you aren't resetting the internal peripherals and registers to their reset state, so things like timers and such will still be running when they shouldn't be, etc.  It's better by far to do a real reset instead of just jumping to 0 like that.

i read about both these methods and they won't allow me to reset using IR

@mostafa And what gives you that impression?

well the first one is a pre-set timer right?? no matter what when the timer run out the board will reset I can't see using IR here

@mostafa You only enable the timer when it is time to do the reset. The rest of the time it's disabled so absolutely nothing happens.

oh the second method you want me to connect an IO pin to the reset pin now I get it but won't that contain soldering ????

oh now I get it I will go see it now

@mostafa You only need to solder things if you want to do it permanently - otherwise just stick a wire into the two holes.  For the WDT there is a handy library that does it for you: https://github.com/WickedDevice/SoftReset

A WDT-reset code example


text:
RFduino and HC-05
I am developing a project with RFduino, where I need to connect HC-05 Bluetooth module to my RFduino.
I have tried to find a way to do that, with out luck.
My question: Is it possible to connect HC-05 board to RFduino?
Note: this is my first question at Arduino.stackexchange.com

Connect it to the UART pins and send the right AT commands? What part of it are you struggling with?

in RFduino there is no UART pins, therefore I was wondering if some one has knowledge about RFduino (http://www.rfduino.com/product/rfd22102-rfduino-dip/index.html)

What about pins 0 and 1 - aren't they the uart?

I will try and let you know later, thx for informative feedback so far (pin 0 and 1 are called GPIO 0/AREF and GPIO1

The lack of documentation with those boards is kind of frustrating.  Your best bet is to delve into the actual source code, where you can see in the variant.h file for the board that the "default UART pins" are 0 and 1.  https://github.com/RFduino/RFduino/blob/master/variants/RFduino/variant.h#L133

cool I will work on it right a head. and will come back with feedback

It is btw frusrating. :)


text:
How does the PID controller actually work?
Preferably PID functions on an Arduino uno or any other examples. I have been researching but many of the the websites really do not explain it.
P.S is there an algorithm for a PID? Thanks

Wikipedia explains it perfectly. Maybe the problem is that you don't understand the explanation?

@Majenko, Hmm, I'd say if people aren't understanding it perhaps the Wikipedia explanation isn't "perfect." Also, quite a few sites don't really explain the terms and what each one does (e.g., how you'd think about or tune a PID controller).

When you're asking questions about subjects you're not understanding it really helps if you can say what you've learned in your research and focus the question on the next part you'd like to understand.

https://controls.engin.umich.edu/wiki/index.php/PIDIntro

http://brettbeauregard.com/blog/2011/04/improving-the-beginners-pid-introduction/ is an excellent explanation of the http://playground.arduino.cc/Code/PIDLibrary

http://ninja-calc.mbedded.ninja/tool/pid-tuner - You can play around with a online PID simulator and see how changing the P, I and D terms affects the response.

I, also, didn't get the idea behind PID from just reading Wikipedia. After some videos/tutorials, I believe the best way to explain it is:
What is PID
PID is an algorithm. It involves three factors which can be adjusted to tune a signal.
It is often used in servo's (and things like thermostates, basic signal controllers)
Imagine this
The servo will be used in the practical examples.
A servo has:
- a current position (signal)
- the position you want the servo to be in (goal signal)
- a speed (PID output signal)
The PID output signal/algorithm makes sure that the servo reaches it's goal.
In short:
PID is an algorithm that can adjust a signal towards an setpoint. Or correct it for that matter.
It regulates how much you have to adjust the signal, without getting serious overshoot, or oscillation around the setpoint.
Detail:
P stands for proportional.
Which means that the further the servo is from it's setpoint, the more speed we want to/can give it. So that we're faster towards the set point.
This also means that we slow down as we near the set point.
Of course you can multiply each of these rules with a factor, to achieve a better balance.
I stands for integrating.
It basically comes down to the fact that it constantly keeps adding to the signal, depending on how long there is a difference between the current point and set point. This is so that if P is still a little slow, it adds some speed over time.
D stands for differentiating
It's less commonly used. (Wikipedia)
The D factor reacts on the speed of the change in value. Or speed of change in setpoint (Dutch wikipedia is not 100%, comment if neccesary :) )
These factors / the algorithm provides a smooth regulation of various systems, hence that's why it is so adjustable.
It can be used for balancing quadcopters or making your house comfortably warm (without sudden changes, or too slow changes)
Why?
How would you balance a quadcopter?
If it shifts to one side, you don't want to fully reverse the throttle.
It'll make it wobble, since you get a lot of overshoot.
Controlling things can be hard, PID is an known working algorithm for those cases. But you have to adjust the factors right to adjust it to your specific system. (They all react differently, or have to react differently).

+1, but stabilizing a quadcopter can't really be done with a single PID loop; it usually takes 2 cascading PID loops, one for rotational position and one for rotational velocity /Pedantry

@BrettAM Good point, I thought each axis could be controlled individually by a PID loop, but it might indeed make sense to couple them in some way.

You can use a single pid for each axis, roll, pitch, & yaw.  Velocity is handled by bias.  Eg https://github.com/benripley/Arduino-Quadcopter

How a PID controller works depends on the particular implementation.
There is a algorithm/library for PID on the Arduino: http://playground.arduino.cc/Code/PIDLibrary and an excellent explanation of the all of functions within it at http://brettbeauregard.com/blog/2011/04/improving-the-beginners-pid-introduction/
Over on stackoverflow and electronics, there are some good questions and explanations that might help:

https://electronics.stackexchange.com/questions/190606/understanding-a-pid-controller
https://stackoverflow.com/questions/14614124/how-do-i-use-a-pid-controller?rq=1
https://stackoverflow.com/questions/21516143/pid-control-value-of-process-parameter-based-on-pid-result?rq=1
https://stackoverflow.com/questions/13542447/i-dont-understand-integral-part-of-pid-controller?rq=1
https://stackoverflow.com/questions/21534996/pid-controller-intuition-for-when-error-0?rq=1