text:
How to control a large number of devices with an Arduino
I'm doing some initial research on a project I have in mind. I am super new to all this Arduino stuff so taking it slow and gathering lots of info.
I want to control around 1000 small linear actuators to push/pull a very small load. The purpose of this question is specifically how to manage that many devices. The devices won't ever need to start their own transmissions so the Arduino can get everything done by polling them ...I hope ...and I don't think it would be a lot of data to each device but I imagine overall it may be. I want to control each device at the "same" time, all with the same cabling distance (around 2m). From what I can tell, a CANbus  is exactly what I need, where I can assign a unique ID to each device (node) and then write some code to control the network array.
In summary, is a CANbus the ideal bit of hardware here to work with an Arduino to control in real time such a high number of devices?
Thanks,
Nick.
Edit: Sorry for the vagueness, I'm very new to all this so really just looking for keywords to help scope my project out before asking more complex specific questions. It's difficult to formulate what's in my head to experienced people without sounding like a goose. I'm experienced on the software side, but the hardware i/o is all brand new.
Ultimately, I am wanting to sample a grey scale image/sequence of images and depending on the value sampled in a 0-255 range which is mapped to the extension capabilities of each actuator to extend/contract in that pixel.
Hope that is more helpful. Thanks.

Perhaps edit your question to clarify some things.  Why do your devices (linear actuators) need to send any data to the Arduino?  Does "control each device at the "same" time" mean you want all the devices to move simultaneously, or just that all of them are in-circuit ready to be controlled?  If the latter, what are your desired and required limits on reaction times and position update frequency?

CAN bus is a solution but possibly overkill for what you want. How are actuators powered and switched. On/off or linear control.  They will need power switching . CAN bus will require node electronics per actuator. CAN bus physical layer is almost identical to RS422 hardware and you can implement multi slave R@422 hardware very cheaply. 1000 devices will require proper design of bus loading for any system and depending on whether control is open loop (one way) or closed loop (to and fro data) a star network topology may suit. More information will help people provide better answers.

@jwpat7 ...have added more project details. The actuators won't ever need to communicate back to the Arduino ...yes I mean move each device  simultaneously and at the number i am investigating, I think will need some special attention in the design.

@Russell McMahon ...thanks very much for your reply. I have updated my question with some more info but your reply is super helpful and helps me expand my research. I have no time limit and this is a learning experience for me so thanks for your suggestions, I can further look into what you have mentioned. I have allot of programming experience but not for devices or in electrical design.

What kind of control signal do your actuators expect?

An ordinary (ATmega-based) Arduino is the wrong choice for this job.  Consider you would use half your RAM just keeping track of the desired state of each actuator.  There are far more capable processors at similar price points for the bare chip, and actually quite a bit cheaper assembled on a board.  Of course you should start by proving your concept with only a handful of actuators, but you might as well start on a platform that is a plausible fit for your goal.

@Edgar Bonet ...that's completely open at the moment. I've not settled on anything in particular. Very early stages so am also looking into what would be the best fit. The biggest question I have at the moment is, can I control that many devices simultaneously. If you have any suggestions, would be super to hear them.

@Chris Stratton ...this is my number one concern at the moment for me as a total novice. Allot of devices and yeah will need to track where they are in realtime. I do plan to start with a proof of concept but am no where near that yet. I want to collect as much info first so I can put a design together. Would REALLY like to hear your suggestions on what might be more capable. Thanks very much.

First thing to do is figure out what it takes to control a single device in the manner you need.  Then think about the required per-device electronics, as that is what will kill your cost/complexity.  You might look at WS2812/etc LED strings for inspiration, or even (if you current requirements are tiny) drivers.  In terms of the master controller, the decision will be driven a lot by the complexity of decision making.  If that requires something the power of a PC, you'll be looking at a comparable embedded board (Beaglebone, etc).  If not, probably an ARM Cortex M0, M3, or M4.

@Chris Stratton ...excellent this is a great start. Thanks very much. Will start looking into these options. Much appreciated. Cheers

Can you expand info on time requirements? How long is acceptable to change 1000 units? How many max can change at once? How important is synchronisation of movements? Afuller explanation of what it does and how may help ensure answer matches need.

This is just a suggestion, certainly not the only possible approach.
Step 1: Get a handful of small linear actuators with a builtin
controller. Some actuators have no controller, and will require one
H-bridge and one analog input each. You do not want these. I have seen
some actuators with built-in controllers that can be driven just like
servos, I would suggest you get some of those. At this point you should
carefully look at costs when choosing the actuators.
Step 2: Learn how to drive those actuators from an AVR-based
Arduino, like an Arduino Uno, using the Servo library. I believe you can
drive up to 12 actuators with a single Arduino.
Step 3: Drive them using two Arduinos in a master-slave
configuration. The master would be a beefy Arduino, like a Mega or a
Due. It would send commands to the slave using, say, an I2C bus. After
sending the set points for the actuators, it would send a "go" order to
the I2C broadcast address. The slave would be the Uno. It would
interpret the commands and actually drive the actuators.
Step 3b: Change the master's program to pretend it is controlling
many slaves, and a total of 1000 actuators. In reality, all the
slaves would have the same I2C address: that of the unique slave
actually available. This will tell you whether your master is powerful
enough for the job, and you will see how the performance scales.
Step 3c: Optimize the slave's code. Try to have it work with an
8 MHz clock, and use as little flash and RAM as possible.
Step 4: Replace the slave Arduino with a bare AVR chip. You will
have to learn how to program it via ISP, but the information is widely
available. An Uno is an ATmega328P at heart, but depending on the
program size, you may get away with an ATmega48A, which is the same
thing only with less memory, and dirty cheap. Or even with a still
cheaper ATtiny. If you can make your program work with an 8 MHz
clock, then use the internal oscillator, which will save you having to
buy an external resonator. All this is to keep the costs reasonable.
Step 4b: Test, test, test. Last chance to change your mind before
committing big bucks.
Step 5: If everything works at this stage, it's time to scale up.
The same master Arduino, and one bare AVR for each dozen actuators, each
with it's own I2C address.

Thanks very much Edgar ...as good a place than any to start. Very much appreciated :) cheers

@NickvanDiem: I just added a few sub-steps.

.@Edgar Bonet ...worthy additions, thank you :) ...do you offer a consultanting service for Arduino projects?

Not formally, but if I can help, and you provide some contact info in your profile, I would be happy to give a try.

.@Edgar Bonet ...great have updated! Ping me a msg


text:
Relationship between baud rate and the frequency of vibration read using ADXL
I am doing a project using Arduino Uno and ADXL 345.
I am quite new to this and I came across this post  in the link" : https://www.sparkfun.com/tutorials/240. Here, a user had posted the below question in the forum.
"Im trying to use this accelerometer to test various frequencies of vibration on a cantilevered beam and I wanted to know what the maximum vibration frequency I could find with using this accelerometer, connected to a 16MHz processor, connected to my laptop. I’m mainly a mechanical person, but after doing some research I found the following: Accelerometer has a maximum of 3200Hz output data rate (so maximum frequency would be 1600Hz) Processor can execute 16,000,000 instructions/sec so this probably is okay Communication rate is 9600 bits/sec so in the program above we read at a minimum 6 bytes for each axis, so that’s 24 bits, leaving you able to read 9600/24 = 400 reads/sec resulting in a one to be capable of reading vibrations at 200Hz. If I bump up the baud rate to 115200, I should be able to then read 4800 times a second, thus measuring 2400Hz vibrations?"
But I do not see any replies to this question. I feel the above analysis mostly makes sense. It would be helpful if someone could confirm that the above analysis is right. If not right , then why isn't it right?
Thanks

Firstly, the datasheet for the accelerometer suggests using >=2Mhz SPI communication rate with 3200 or 1600 Hz output data rate operation.
Since the Arduino SPI library default clock is 4Mhz, the Arduino can handle 3200 Hz sampling, so the maximum frequency you could distinguish would be 1600 Hz.
So the Arduino and accelerometer can detect vibrations up to 1600Hz.
Next, you send the data to your laptop. At 9600 BAUD, you are correct in saying that since the data is 24 bits, it will only update your laptop with the Arduino's measured frequency at 9600/24 = 400 Hz. So 400 times a second the Arduino could tell the laptop what frequency it measures, the measurement having a maximum frequency of 1600 Hz.
For the Arduino to simply pass the raw data to the laptop at 3200 Hz, you would need 24 bits * 3200 Hz = 76800 BAUD minimum.
The measurement data is in any case limited by the accelerometer sampling rate of 3200Hz.

Thanks for your response. But I don't understand the line "the Arduino can handle 3200 Hz sampling, so the maximum frequency you could distinguish would be 1600 Hz." Why is it 1600Hz when the sampling rate is 3200Hz. I am new to this. It would be helpful if you explain this. Thanks

According to the Nyquist Theorem, you need to sample twice as fast as the highest frequency you want to measure.  For Ex, if the signal you wish to measre is a 1MHz sine wave, you have to sample at AT LEAST 2 M Samples per second (MS/s) to ensure that the 1MHz frequency component of the signal is detected.
However, sampling at exactly 2 times the highest frequency is often unacceptable, especially where the shape of the signal is important.  When sampling a pure sine wave, I generally make sure to sample at at least 10 times the frequency of that sine wave to see the shape of the signal.

Typical serial encoding is more like 10 bit periods per byte, so 24 bits becomes 30 byte times.  But 3200 * 30 should just fit in 115200 baud, which is within the capability of a sound Arduino setup.  It will mean using binary encoding though, and with a divisible-by-three size, which is ugly.  I'd consider trying to pack the data to two bytes.

source: Stack Exchange

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

sort: votes


text:
How to use the 0.91' 128*32 OLED by arduino pro mini?
I buy a OLED as picture below, I want to use https://github.com/adafruit/Adafruit_SSD1306 to control it. But the example of https://github.com/adafruit/Adafruit_SSD1306 can't be compiled. The error as the second picture below. How should I to use this OLED ?

It looks like there is more to the error message that isn't shown in your image. Instead of posting an image of text, copy and paste the error text into your question.

@josecanuc  I have add it. Could you help me ? Thanks.

In addition to installing the Adafruit_SSD1306 library, you also need to install the Adafruit_GFX library, which is a dependency of the SSD1306 library.

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


text:
Why after the reset the program vanish?
I buy a stm32 board as picture below, I connect the Boot0 to 3.3 and use the serial port  download the program.
I use the library https://github.com/rogerclarkmelbourne/Arduino_STM32
The second and third picture is my program. After I download the program, the led on board shine and the serial is normal, but after I press RESET on board, it is not shine. Seemly, the program vanish.
Why it is so ? And how to let the program in board after press reset ?

By connecting BOOT0 to 3.3V you are telling the chip When I reset for whatever reason you must go into the bootloader.
So you reset, and it goes into the bootloader. You then upload your sketch.
At that point the programming software tells the bootloader "Ok, you are done now. Run the program". And it does.
Until you reset. And because you are telling it to go into the bootloader with BOOT0 it dutifully does so, waiting for you to load a new program.
The old program is still there, but you just aren't letting run, since you are insisting that the chip go into the bootloader when you reset.
In order to get your program to run and not the bootloader you must disconnect BOOT0 so it doesn't enter the bootloader.
You only need to connect the BOOT0 when you want to put a new program on there.

From http://wiki.stm32duino.com/index.php?title=Bootloader

Activating the bootloader is done through forcing two boot pins (and
  then resetting the MCU). Many boards have one or more boot pins
  exposed as jumpers or push buttons.
Normal boot (to user firmware, which may be a secondary bootloader):

Boot0 LOW
Boot1 LOW

Allow firmware upload through USART1:

Boot0 HIGH
Boot1 LOW

After uploading new software through the serial, move Boot0 back to GND so that the MCU loads the firmware you uploaded, rather than it's internal serial bootloader.

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


text:
Speed of comunication by SI4463 under RH_RF24.h
As in this SO question, I use use a RH_RF24.h to control an SI4463. In RH_RF24, there is not anything about the speed of communication. I need the way to control the speed of communication. Because I want to take high speed of communication when Rssi is strong and slow speed when weak (for reliability).
How should I to do it ?

Brief look at the docs suggest you define the modem config (modulation type and speed) using one/some of these values : http://www.airspayce.com/mikem/arduino/RadioHead/structRH__RF24_1_1ModemConfig.html

@KennetRunner  Thanks. Seemly , I can use setModemRegisters(prop_2003) , or  prop_2004, prop_2005 to set data rate (in fact, I am not sure whether I can do so ). But , I don't know the data rate of them .For example , what is the data rate of prop_2004, how to find it ?  Besides, when I low data rate, whether rate of messy code will become low ?

According to RH_RF24.h setModemRegisters takes a ModemConfig struct.  prop_2003, prop_2004 and prop2005 are part of that struct and it's the value of these 3 bytes that sets the datarate.
Datarate is a 24bit unsigned value (hence the 3 bytes in the struct). prop_2003 is the MSB and prop_2005 the LSB.

prop_2003 default is 0x0F
prop_2004 default is 0x42
prop_2005 default is 0x40

meaning the default data rate is 0x0F4240 ( = 1Mbps)
This application note on the API gives more details (around page 99).

What is the mean of 1Mhz ? It means I can communicate by speed of 1000000 bps ? But I rember the speed of SI4463 is slow. Besides , how to use setModemRegisters ?  For example ,because datarate is a 24bit unsigned value . How to write parameter of setModemRegisters ? Just setModemRegisters(prop_2003, prop_2004,prop_2005)   ?

Or just setModemRegisters(0x0F4240)   ? And could you help me in this question http://arduino.stackexchange.com/questions/31150/how-to-use-setmodemregistersin-rf24 ? Thanks very much.

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


text:
How to use get_properties to get RSSI in RF24?
As picture below, how to use get_properties ? I fail to understand AN625, how to use get_properties to get RSSI ?

Adding source code based on RH_RF24 functions.

#include <SPI.h>
#include <RH_RF24.h>

// Singleton instance of the radio driver
RH_RF24 rf24;

uint8_t Recieve_Data[20];

uint8_t receive_buffer[RH_RF24_MAX_MESSAGE_LEN];
uint8_t receive_buffer_length = sizeof(receive_buffer);

uint8_t Rssi;

unsigned long Micro_Time;

uint8_t status[8];
uint8_t buf[RH_RF24_MAX_MESSAGE_LEN];
uint8_t len = sizeof(buf);

void setup()
{
  Serial.begin(115200);
  if (!rf24.init())
    Serial.println("init failed");
  // Defaults after init are 434.0MHz, modulation GFSK_Rb5Fd10, power 0x10
   while(!rf24.setFrequency(443));
  rf24.setModemConfig(rf24.GFSK_Rb50Fd100);  //设置成GFSK_Rb50Fd100
}

void loop()
{
  rf24.setModeRx();
  delay(100);
  rf24.setModeIdle();
  rf24.command(RH_RF24_CMD_GET_INT_STATUS, NULL, 0, status, sizeof(status));
  Serial.print("Id   ");
  for (int i = 0; i <= 8; i++)
  {
    Serial.print((uint8_t)status[i]);
    Serial.print("   ");
  }
  Serial.println();
  /*
    if (status[2])
    {
      uint8_t modem_status[6];
      rf24.command(RH_RF24_CMD_GET_MODEM_STATUS, NULL, 0, modem_status, sizeof(modem_status));
      delay(100);
      for (int i = 0; i <= 6; i++)
      {
        Serial.print(modem_status[i]);
        Serial.print("   ");
      }
      Serial.println();
    }
  */
  delay(400);
}

What part are you using, as that function is only available for Silicon Labs Si4460/4461/4463/4464 family of transceivers chip, and the equivalent HopeRF RF24/26/27 family of chips and the HopeRF RFM24W/26W/27W modules

@Gerben  I use Si4463.

As coded in the "Github - lora_chisterapi/lib/radiohead/RH_RF24.cpp", firstProperty = (GROUP << 8) + (START_PROP) and uint8_t* values + uint8_t count are used to stored the read properties.

@J.Piquard  Could you write an example, I don't understand it well. Seemly, I can get RSSI just use RH_RF24::command as in web you given.

Instead of using the command() as a static call (RH_RF24::command), the best approach should be to use a class instantiation and declare a RH_RF24 rf24; before setup() function and initialize the instance with a rf24.init() call. So, could you provide what source code you have tried in your Arduino in order to give you a more concrete example ?

@J.Piquard  I am very sorry, I don't know how to edit code, so , although I have add them in my question , but they are not clear.

@lanse7pty, I have formatted your added source code, but wait for the peer review. Your source code seems good, but be careful with the use of sizeof(status) in the request rf24.command() (only available when the size of the item is 1 = sizeof(uint8_t)) then i <= 8 in the for-loop display.

By using the RH_RF24 rf24;(Singleton instance of the radio driver), read a series of properties is really simple.

The properties shall be in the same GROUP,
Up to 16 properties could be read in the same request,

Hereafter is a example to read from SYNC_CONFIG to SYNC_BITS_7_0 (5
  properties).

Step 1 - Declare your own uint8_t sync_stat[5]; or use the still declared uint8_t status[8];.
 uint8_t sync_stat[5];

Step 2 - The firstProperty is in fact the first property to be read and count is the number successive properties to be read (from SYNC_CONFIG = 0x1100 to SYNC_BITS_7_0 = 0x1104.
// And check the returned code
if (rf24.get_properties(SYNC_CONFIG,sync_stat,5)) {
    // sync_stat[0]= SYNC_CONFIG
    // ...
    // sync_stat[4]= SYNC_BITS_7_0
}

Then, the equivalent command() is:

uint8_t buf[3];
buf[0] = SYNC_CONFIG >> 8;
buf[1] = 5;
buf[2] = SYNC_CONFIG & 0xff;
if (rf24.command(RH_RF24_CMD_GET_PROPERTY, buf, sizeof(buf),sync_stat,5)) {
    // Same array
}

authors: Дем'ян Пиріг

authors: Евгений Степанов


text:
BLE Python with GUI on OSX
Has anyone connected BLE devices with Python + GUI on OSX? I've looked into a few libraries (most are old), but one that has the most success if Adafruit's BlueFruit library. However, this library works poorly with GUI's since it requires use of the main event loop (which GUI's usually use). After doing a bunch of Google searches, I couldn't find any good examples of using a GUI with Python + BLE. There seems to be no good BLE libraries for Python either.
Specifically looking for help integrating BLE with Kivy, but other GUI toolkit examples should be fine.
Also trying to gauge interest in this to see if I can do development to solve this (if it really is a problem).

I'm voting to close this question as off-topic because it is not about Arduino but rather desktop GUI software for OSX.  Perhaps you can solve your difficulty using multiple threads (or programs) and pipes or mailboxes between.

If you are still searching for a lib check out:
https://github.com/adafruit/Adafruit_Python_BluefruitLE
Its specifically made for BLE communication on OS X or Linux by wrapping the corebluetooth and its Linux equivalent bluez in a python lib. Windows is not supported at this moment.
Unfortunately there is no documentation to it. You will have to read the examples and search for specific functions in the lib manually.


text:
Interleave Assembly and Source for avr-objdump
Trying to get avr-objdump to generate a listing that interleaves the assembly with the source code. I've tried a bunch of debugging arguments in different configurations but I can't seem to get it. The best I could do was getting it to interleave the object with line numbers from the assembly (avr-objdump -lS spi.o)
Original Makefile
Here's my current Makefile:
PREFIX=avr-
CC=${PREFIX}gcc
OBJCOPY=${PREFIX}objcopy

BIN=knightrider
MCU=attiny85
OBJS=../src/tinySPI.o src/knightrider.o

PROG?=atmelice_isp
PORT?=usb

CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

${BIN}.hex: ${BIN}.elf
    @mkdir -p bin
    ${OBJCOPY} -O ihex -R .eeprom build/$< bin/$@

${BIN}.elf: ${OBJS}
    @mkdir -p build
    ${CC} ${LDFLAGS} -o build/$@ $?

install: ${BIN}.hex
    avrdude -c ${PROG} -P ${PORT} -p ${MCU} -U flash:w:${BIN}.hex:i -qq

clean:
    rm -f build/*
    rm -f bin/*

fuses:
    avrdude -c ${PROG} -P ${PORT} -p ${MCU} -U lfuse:w:0x62:m -U hfuse:w:0xDF:m -U efuse:w:0xFF:i -qq

What would I need to change in order to run avr-objdump and get an interleaved listing of an .o and its corresponding .c (e.g. spi.o and spi.c)?

First make sure you add -g to all your compilation commands.
Then you can run avr-objdump -S build/spi.elf (for instance).
Also I see you're missing the MCU definition in your link command. Without that it won't link in the proper C startup routines and your program will most probably not run.
Here is a makefile I use:
PREFIX=avr-
CC=${PREFIX}gcc
CXX=${PREFIX}g++
LD=${PREFIX}ld
AS=${PREFIX}as
OBJCOPY=${PREFIX}objcopy
OBJDUMP=${PREFIX}objdump

BIN=blink
MCU=atmega328p
OBJS=blink.o

CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
CXXFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections -fno-exceptions
LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

${BIN}.hex: ${BIN}.elf
    ${OBJCOPY} -O ihex -R .eeprom $< $@

${BIN}.elf: ${OBJS}
    ${CC} ${LDFLAGS} -o $@ $?
    ${OBJDUMP} -S $@ > ${BIN}.dis

install: ${BIN}.hex
    avrdude -C ./avrdude.conf -c usbasp -p ${MCU} -U flash:w:${BIN}.hex
 -qq

clean:
    rm -f *.o *.elf *.hex

fuses:
    avrdude  -c usbasp -p ${MCU} -C avrdude.conf -U lfuse:w:0xff:m -U h
fuse:w:0xd6:m -U efuse:w:0x05:m -qq

That is some serious make-fu and I'm currently reading "GNU Make" before I come back to it.

Nothing that amazing really. It's mostly variable substitution and the use of the fact that Make already knows how to compile files as long as you set the right program and the flags to use with it. No need to specify each and every fole manually, just the list of objrct files and Make works the rest out for itself.

I'm back, it works great! Only problem is that it spits objects into the source folder; I want the objects to go into the build folder.

For that you're going to need to add a .c.o recipe possibly. Using separate folders like that gets a little tricky with make.

Nailed it with a few filename functions, thank you so much!


text:
ATtiny85 SPI with Timer 0
Trying to shift out from ATtiny85 to a shift register using the USI in SPI mode. I have Timer 0 running as slowly as possible (checked it was running by temporarily changing it to toggle a pin with an LED attached.) I have LEDs hooked up to USCK and DO so by rights I should be able to see them blinking as it sends.
What else do I need to do in order to get it shifting out in sync with Timer 0? All the examples I've looked at so far strobe the USI clock manually.
#include <avr/io.h>

int main(void){
    DDRB = (1 << DDB2) | (1 << DDB1); // USCK & DO Output
    DDRB &= ~(1 << DDB0); // DI Input
    PORTB |= (1 << DDB0); // Pullup Resistor for DI

    TCCR0A = (1 << WGM01); // Timer 0 in CTC Mode
    OCR0A = 0xFF; // Timer 0 Compare A
    TCCR0B = (1 << CS02) | (1 << CS00); // Prescaler / 1024

    USICR = (1 << USIWM0); // USI 3 Wire Mode
    USICR |= (1 << USICS0); // Timer 0 for USI 4-bit Clock Source

    USIDR = 0x7F; // Why you no go? :c

    USISR |= 0x08; // Set Counter to 8
    USISR = (1 << USIOIF); // Clear Counter Overflow

    while(1);
    return 0;
}

I think it should be: USISR = _BV(USIOIF);

This is a good question, but not related to Arduino. I think you could re-ask it on Electric Engineering stack exchange.

"This flag is set (one) when the 4-bit counter overflows (i.e., at the transition from 15 to 0). If the USIOIE bit in USICR and the Global Interrupt Enable Flag are set an interrupt will also be generated when the flag is set. The flag will only be cleared if a one is written to the USIOIF bit. Clearing this bit will release the counter overflow hold of SCL in two-wire mode."
So it's set when it overflows and you clear it by setting it? What the f- Atmel. :I

Yepp, you have to think as the hardware guys do :)

Still doesn't work. :c I've resorted to strobing it manually for now.

Did you forget to load the counter and clear flags in USISR?

It still isn't doing anything (updated code snippet.)


text:
RF24 communication between Leonardo and Micro not responding
I have Arduino Leonardo and Micro. I can't manage them to communicate via nRF24L01. I made a receiver and sender sketch to test it and can't see any respond. I tested the same code on two arduino nano and they work fine.
I connected the pins correctly using the ICSP pins in Leonardo and corresponding pins (not ICSP) dedicated for SPI in Micro.
Please could someone tell me what am I missing in porting sketch from nano-nano to leonardo-micro?
Here are the sketches:
PS some additional channels are left to see what I expected from working sketch.
Receiver module:
//NRF24
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
RF24 radio(9, 10);
byte addresses[][6] = {"1Node", "2Node", "3Node", "4Node"};

int channel = 1;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  radio.begin();
  radio.setAutoAck(1);
  radio.setRetries(15, 15);
  radio.openReadingPipe(1, addresses[0]);
  radio.openReadingPipe(2, addresses[1]);
  radio.openReadingPipe(3, addresses[2]);
  radio.openReadingPipe(4, addresses[3]);
  radio.startListening();
}

void loop() {
  // put your main code here, to run repeatedly:
  while (radio.available()) {
    char theMessage[13];
     radio.read(&theMessage, 13);
     Serial.println(theMessage);
     if(theMessage == "testingsend"){
       //this is removed in nano
      digitalWrite(13,HIGH);
      delay(50);
      digitalWrite(13,LOW);
     }
  }
}

And the sender:
//NRF24
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
RF24 radio(9, 10);
byte addresses[][6] = {"1Node", "2Node", "3Node", "4Node"};

int channel = 1;

void setup() {
  // put your setup code here, to run once:
  radio.begin();
  radio.setAutoAck(1);
  radio.setRetries(15, 15);
  radio.openWritingPipe(addresses[channel]);
}

void loop() {
  // put your main code here, to run repeatedly:
  char theMessage[13] = "testingsend";
  radio.write(theMessage, sizeof(theMessage));
  memset(theMessage,0,sizeof(theMessage));
  delay(300);
}

Have you tried using the ICSP header on the Micro? Since it's unlikely that your code is the problem, try other combinations to pin-point the issue like, Leonardo-Nano and Micro-Nano.

Currently I test with micro-nano, changed pins on micro to ICSP and nothing happens. I'm reading about Leonardo/micro and i read that the SS pin works different but I don't know if it's issue here.

Ok I solved the issue, somehow I had to use 10 uF capacitor instead of 4.7 uF

Where did you have a capacitor?


text:
get current time in nanoseconds
On Arduino due, Is this possible to get the current time in nano seconds?
At 84Mhz, I guess it will always be a multiple of ~12ns.
And a perfect solution would read a register/variable rather than call a function. Because I want to avoid the cost of calling a function which is in order of microseconds.
what about counting clocks since start of execution. is this possible?

Yes, it should be.  At least according to the Cortex M3 Technical Reference Manual that I think I downloaded from ARM.  (DDI0337E_cortex_m3_r1p1_trm.pdf)
In section 11.5 of said manual, there is a register called DWT_CYCCNT (Data Watchpoint and Trace Cycle Count Register) which is incremented once per clock cycle when the appropriate flag of the DTW_CTRL (DWT Control) register is set.
This flag is unset on reset of the CPU so it needs to be set manually (unless it is done by the Arduino IDE, but checking the header files of the IDE, it doesn't look like it as unlike many other CPU registers, there is no Arduino REG_ define for these registers).
This untested code should be usable as the basis for your own code.  I suggest you add some serial initialisation in there and dump the value of currentCycles to the serial log to test it.  I am away from my hardware at the moment so can only test that it compiles.
#define REG_DWT_CTRL (*(unsigned int*)0xE0001000U)      /* Data Watchpoint and Trace Control Register */
#define REG_DWT_CYCCNT (*(unsigned int*)0xE0001004U)    /* Data Watchpoint and Trace Cycle Count Register */

#define CYCCNTENA ( 1 << 0 )                            /* DWT CTRL Cycle Count Enable Bit */

void setup()
{
    REG_DWT_CTRL |= CYCCNTENA;
}

void loop()
{
    unsigned int currentCycles = REG_DWT_CYCCNT;
}

Edit:
Note that the counter is a 32 bit register, so at 84 MHz it will reset every 51.13 seconds.  It is a read only register so writing to it will have no effect (you cannot manually reset it that way).

You probably mean (*(volatile unsigned int*)...).


text:
Read OUTPUT pin value in Arduino Due
I am trying to read the value of an output pin. online forums say that digitalRead(pinNum); should work, but that is not the case here. digitalRead always returns 0 (LOW).
This is the code:
int pin = 22; // or 13, or 3 ...
void setup()
{
  Serial.begin(9600);
  pinMode(pin,OUTPUT);
}
void loop()
{
  digitalWrite(pin,HIGH);
  delay(100);
  Serial.println(digitalRead(pin));
  delay(100);
  digitalWrite(pin,LOW);
  delay(100);
  Serial.println(digitalRead(pin));
  delay(100);
}

printed values:
0
0
0
...

That method only works on AVR based systems.  It exploits a "feature" whereby the IO pin, when in OUTPUT mode, is also in INPUT mode at the same time, and reading the pin reads the value that the pin is being driven to by the digitalWrite function.
The same is not true of the Due, which is an ARM based system.  The IO pins function completely differently and the same "feature" cannot be used.
You will have to remember the state of the pin yourself.

I cannot upvote yet, but thank you!

Majenko's answer basically explains the cause - apparently on the SAM3X8E reading the input data register will not show the state being driven on output lines in the way it would on some other devices like the AVR.
However the conclusion that "you will have to remember the state of the pin yourself" is not correct.
According to the data sheet, the output data state can be read from the relevant port's PIO_ODSR register.   That the Arduino libraries don't do this could be an oversight, but probably is an efficiency decision, as they would need to examine the direction of each pin to determine the register to read for its state.
It would not be hard to make your own functions or macros to read the PIO_ODSR - you could model them on the digitalInput() ones.

try editing...
Serial.println(digitalRead(pin));

to .....
Serial.println(digitalRead(pin), DEC);

This works on my arduino Leonardo.

No.  The actual issue has already been explained.  This question is about a Due and arrises from differences between that and more classic AVR Arduinos.

Feed the output to a (spare) input pin and digitalRead() that pin!

Actually the output data can be read in software, it just needs to be read from a different register than the input data.


text:
Sketch Upload to LinkIt ONE Timeout
I've just bought a new LinkIt ONE IoT prototyping board, and I'm having trouble getting started with it.
I'm working on a mac. I've installed the LinkIt ONE SDK onto my Arduino IDE as specified in the instructions here: http://labs.mediatek.com/fileMedia/download/5fed7907-b2ba-4000-bcb2-016a332a49fd
When I go to upload my first sketch to my board, the sketch compiles and goes through uploading, but before it uploads, it stops uploading and the Arduino IDE perpetually tells me "Uploading...". When I look at the console below, it's telling me this:
[txd] AT

[txd] AT

[medrv]: Time out call back

[error] time out
[medrv]: Kill timer, event is AT_TIMEOUT

I've read some forums about an issue similar to this on the MediaTek website, but they don't help with the issue on the Mac. The ability to use LinkIt ONE on a Mac is new only this month, so I believe if we come up with a fix for this issue, it will help lots of people in the future who have this similar problem.

Disclaimer: I do not have access to one of these devices to test this on.
Section 3.4.1 of LinkIt's developer's guide (which you linked to) seems to indicate that it is necessary to install COM port drivers on OS X before you can communicate with the board. The [txd] report is communication from your computer to the board, so it seems like you are never establishing a connection. The suggestions in the developer's guide are as follows:

If you are using a LinkIt ONE development board on Mac OS X 10.10, then a USB driver is required to enable connectivity with and firmware updates on the LinkIt ONE development board. The OS X 10.10 built-in generic CDC ACM USB driver is not compatible with three ports available on the LinkIt ONE development board. The steps to install a custom driver to enable the BROM port for Firmware Updater are as follows:

Extract the content of the zip file available in LinkIt ONE SDK software’s Driver folder (see 2.3.2, “Installing LinkIt ONE SDK”) named MacOS_USB_COM_Driver_BM_xxx.xx.x.zip.

Run the installation package (BMCDCACM_Driver_v115.05.0.mpkg) and click Next to install it.

Wait until driver installation has finished, then restart your Mac.

BROM USB driver installation is now complete and you have access to the MTK USB Serial ports.


text:
Can't drive long NeoPixel strips with Due or Duemilanove?
I spent a significant part of today developing a sprite movement library for a 30-pixel NeoPixel strip using my Arduino Duemilanove (ATmega 168). It works like a charm. However, if I change N_LEDS to a significantly higher value, the program seems not to run. I can't get it to run on the Duemilanove for a strip of longer than 50.
In fact, (see the below code) a relatively high N_LEDS value won't even allow the test patterns to run as defined in setup(). This leads me to believe that inexplicably the constructor for Adafruit_Neopixel is failing.
A friend of mine (who has the ultimate application for this) is hoping to drive a strand of 750 LEDs using this code on an Arduino Due. I can't imagine memory would be an issue with the Due, so what's going on here?
Headers:
#include <Adafruit_NeoPixel.h>

#define PIN    6
#define N_LEDS 30      // <-- If this number is > ~50, nothing happens
#define MAXSPRITES 5
#define MIN_UPDATE_INTERVAL_IN_MS  15
#define MAX_UPDATE_INTERVAL_IN_MS  40
#define SENSOR_TIMEOUT_IN_MS  2000
#define SCANNER_WIDTH  9

Strip declaration:
Adafruit_NeoPixel strip = Adafruit_NeoPixel(N_LEDS, PIN, NEO_GRB + NEO_KHZ800);

setup() and loop():
void setup() {
    randomSeed(analogRead(0));

    strip.begin();

    darkenStrip();

    manager = new SpriteManager();
    manager->Add(new TestPatternSprite(0, 0xff0000));
    manager->Add(new TestPatternSprite(5, 0x00ff00));
    manager->Add(new TestPatternSprite(10, 0x0000ff));
}

loop() {
    ...
}

Are there any coding mistakes in the above that wouldn't allow us to run this code on the Due? Or is this a known limitation?

Your question doesn't make it clear that you have tried the above code on a Due, and it failed. I thought you were saying that you tried it on a Duemilanove and it failed after a certain number of pixels. So you really have two problems? The number of pixels on the Duemilanove, and the fact that it doesn't light any (significant number of) pixels on the Due? Is that right?

Your Duemilanove only has 1k of RAM. That's not much. Each pixel takes 3 bytes of RAM (R/G/B). So (say) 60 pixels would be 180 bytes. That's less than 1k, but there would be other uses of RAM in your sketch.
750 LEDs sounds like pushing it for the low-RAM Arduinos.
You might want to look at NeoPixels Revealed: How to (not need to) generate precisely timed signals The author managed to drive over 1000 NeoPixels with a Duemilanove.
I'm not sure if that applies to your exact type of NeoPixels, but it is worth considering.

Ok, but upon reading my post, I think I wasn't entirely clear. Our desired configuration is on the Due -- we were only using the Duemilanove for testing. Any reason this wouldn't work on the Due?

The fact that it works up to some magic number would appear to indicate that RAM, and not something else, is the problem. So quite possibly it would work on the Due. Since the Due has 3.3V on its pins you would need to check this is adequate to drive the Neopixels, or maybe get a level shifter. Since the Due has 96k of RAM that may be enough to drive your intended number of pixels. There may possibly be some subtle issues in the library, regarding addressing that large an array, I couldn't say for sure. You would have to try it. :)

Thanks! But it doesn't. :-/  Perhaps the voltage is an issue; I believe the tests we had done on the strip only illuminated one pixel at a time. It's possible that maybe the voltage drop of lighting up multiple LEDs is enough to drop the voltage below some critical threshold for pixels. Still, I'd expect to see some kind of partial effect at least. Thanks for the help!

What is powering the Neopixels? Assuming they are running at 5V the 3.3V from the Due may be marginal in terms of being considered HIGH. I would try the level-shifter to see if that helps.


text:
How to read all avaiable data from a Serial stream and then stop
I am trying to read data from the Serial port in my Arduino, store it in a buffer and when all the data has been read stop reading and then start using the data (the talkMIDI() function). The Arduino succesfully some bytes from Serial but not all of them and then hangs without stopping before the end.
void loop() {
  if (!stop)
  {
    char in = Serial.read();
    if (in != -1)
    {
      buffer[pos] = in;
      pos++;
      Serial.write("read");
      Serial.print(pos);
      Serial.print("\r\n");
    }
    if (in == 126)
    {
      stop = 1;
      Serial.write("STOP");
    }
  }
  else
  {
    if (cursor < pos)
    {
      talkMIDI (buffer[cursor], buffer[cursor+1], buffer[cursor+2]);
      cursor = cursor+3;
      delay(500);
    }
  }
}

After manually sending a 126 value (~) character, I get a "STOP" response on the Serial line but Arduino doesn't start executing the code from the else branch (the talkMIDI() part -- the function doesn't even get called once).

Where do you declare stop? Maybe it's not the same stop at the top of the loop.

stop is declared globally at the beginning.

Then it must be the cursor < pos test.

How do you mean?

You should read this: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

Looking at it quickly, if stop is set, then the reason for not executing the code in the else branch would be the expression (cursor < pos). Maybe put a Serial.println in the branch (before the if) to confirm that the else is getting executed.

Trying to send multiple characters for each received character is not likely to work well unless the characters are sent to the Arduino with substantial delays in between them.


text:
On Arduino Due webserver, there is a 5 second delay on Windows, only when connected via native port
My Due webserver was working perfectly fine for months when connected to Linux via the native port.
But when connected to Windows 10 via the native port, if the Arduino webserver is idle for about 5 minutes (when no client calls a webpage), then there is a strange 5-10 second delay before the webpage is able to load. This delay doesn't happen when connected to the webserver via the programming port.
It almost seems like maybe Windows is putting the port to sleep when it notices an idle delay, and then it has to wait for the port to wake up before it can call the webpage.
On the Windows "Power Settings" I set the computer to never go to sleep, and also in the Power "Advanced Settings" I disabled the USB "selective suspend".
Do you have any ideas why there would be this strange delay only on Windows and only when connected via the native port?

ADDITIONS: I made a simplified example that reproduces the problem on my machine. I wonder if anyone can see any problems with this code.
First, the python code. Note that if the python script is never run, there are no delays on the Arduino webserver, and everything works as expected.
import serial, sys

SERIALPORT = "COM5" # Change this to your serial port!

# Set up serial port
try:
  ser = serial.Serial(SERIALPORT, 115200, timeout=0)
except serial.SerialException:
  sys.exit()

ser.write("Hello World")
print("Hello World")

ser.close()

And below is the simplified Arduino code. It's just a simple webserver that serves a page that has a "reload" button that reloads the page. You can hit "reload" as many times as you want, and the program never freezes. But if you run the python code above and then try to reload the page, there is a long delay (anywhere between 10-60 seconds by my current estimate).
If you comment out all of the "SerialUSB.print" lines that are anywhere in the loop (in this simplified case, there's only 1 line at: "SerialUSB.println (data);" in the processData function), then the webpage never freezes, even if you run the python code frequently.
In my real-world example, my python code was running once a minute, causing random freezes. If I stopped the python code from running, then there were no more freezes on the webpage. I ended up commenting out all of my SerialUSB.print statements that were in the loop, and that way I could have the python code running on schedule, and my program had full functionality (except for the loss of SerialUSB.print).
#include <Ethernet.h>

byte mac[] = {
  0x04, 0xBA, 0xB0, 0xCC, 0xDF, 0x04
};
EthernetServer server(80);
EthernetClient client;

const byte MAX_INPUT = 25; //for processIncomingByte

void setup ()
{
  SerialUSB.begin (115200);
  Ethernet.begin(mac);
  SerialUSB.print("server is at ");
  SerialUSB.println(Ethernet.localIP());
}  // end of setup

bool processIncomingByte (const byte inByte)
{
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;
  switch (inByte)
  {
    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte
      if (input_pos == 0)
        return true;   // got blank line
      // terminator reached! process input_line here ...
      processData (input_line);
      // reset buffer for next time
      input_pos = 0;
      break;
    case '\r':   // discard carriage return
      break;
    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1)) input_line [input_pos++] = inByte;
      break;
  }  // end of switch
  return false;    // don't have a blank line yet
} // end of processIncomingByteWeb

void processData (const char * data)
{ //Note: since there are no GET requests in this simple example, I removed the parts for processing GET.
  SerialUSB.println (data);
  if (strlen (data) < 4)
    return;
}  // end of processDataWeb

void loop ()
{
  client = server.available();
  if (client) {
    boolean done = false;
    while (client.connected() && !done)
    {
      while (client.available () > 0 && !done)
        done = processIncomingByte (client.read ());
    }  // end of while client connected

      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println();
      client.print("");
      client.print("Reload");
      delay(10); client.stop();
  }
}  // end of loop

This is not technically a problem for me anymore, except for having had to comment out all my "SerialUSB.print" statements. But I am interested in learning what is causing this strange behavior.
Note: the "processIncomingByte" and "processData" functions are mainly from Mr. Gammon's writings and tutorials, and they are working flawlessly for me in 2 other Arduino webservers I have running. I wanted to note this because if I had written the functions myself, then obviously they would require much more scrutiny.

How does the USB port relate to the Due running as a webserver?!

Good point! I guess that adds to the mystery! I can't figure out why there would be a delay (only after being idle) with the native port, but no delay with the programming port... and only on Windows.

But you still haven't mentioned how you are making the Due a webserver.  It's a subtle hint to say "We need to see and understand your setup and your code" before we can help you out.

I'm sorry. I'm using an ethernet shield. This setup was working flawlessly for months on Linux, and works fine on Windows only when the Due is connected via the programming port. My code is too long to post or to simplify for the forum, but basically it's nothing unique, and it's mostly just using code from Nick Gammon's tutorials. I prefer to have it connected via the native port because some of my push-buttons send keystrokes to the computer. I rarely push those buttons (only once or twice a day), so it's doubtful that the sending of the keystrokes is related to the delay.

Re "My code is too long to post" -- arduino.stackexchange pages use scrolling windows to display code.  If the problem is a code issue, show the code.  People who answer questions effectively often like to determine for themselves what can be ruled out – typically they've seen hundreds of instances where someone says, "It can't be that" but it is

Okay, thanks for the advice. I'll try to format the code for posting here later. It will take me a while though, so I don't imagine I'll get it done until tomorrow.

I found out some new important info: There's a python script that sends data to the Due via the serial port every minute. When I stop the scheduled task from running the python script, there are no more delays for the webserver. Whenever I had attached the Due via the programming port, I didn't have the python script send the data to that port, and I'm pretty sure that's why there was never a delay with the programming port. When I edited the python script to send data to the Due's programming port number, it had the effect of resetting the Due every minute. (cont...)

So when the Due is connected via the native port the python script ends up causing it to have long delays. When it's connected via the programming port the python script causes the Due to reset once every minute. When the python script is disabled then there are no problems. I'm pretty sure this is a problem with my python code, so I'm not sure if it belongs here. I was having other problems porting my python code to Windows, and I learned that python scripts need some modifications when moving from Linux to Windows. BTW the script basically sends weather and email data to the Due.

If your Due program is written properly then it shouldn't cause any delays. If it's not written properly (and serial code so often is not written properly) then it's possible to see delays.  Post your Due code - at least the portion of it that deals with the serial.

Thanks @Majenko. I think I narrowed it down, and soon will be able to share some code that replicates the exact problem. Basically the sketch only freezes on SerialUSB.print("whatever");. When I comment all of those out of my code, then everything works perfectly. There seems to be no problem with Serial.print or Serial2.print.

I made a simplified version that reproduces the problem, and added the code to the post above. Thanks everyone for reading!

Consider an alternative approach to the problem.  I lost about a weeks worth of work assuming Windows 7 networking worked.  When I used wireshark (on the Windows computer and on an independent Linux computer connected using an Ethernet Hub), I found that Windows can fail a network and not really tell you about it.  I was able to run ping from Windows. It will appeared to make several attempts.  However, wireshark saw absolutely no attempt on Windows part to put anything on the network.  So, we turned to Linux to finish up development work. My bet, Windows momentarily failed your network.

@Jerry - Do you connect using IP addresses or names?  Also IPv4 or IPv6?

@Matt - IP addresses only, and IPv4.

@Jerry - Damn, thought it might be a WINS issue and adding your host to /etc/hosts might have fixed it.

@Matt - Thanks for sharing your ideas. I would love to eventually figure this out some day. I've been discovering from other peoples' experiences that there are some strange quirks with the Arduino Due, and now that the board is technically officially discontinued from the Arduino product line, I'm not expecting the stranger bugs to get ironed out. I'm still open to the idea that it might be a Windows networking problem, and every once in a while I do experiments with it (including those suggested here), but so far I've found nothing.

This is speculation as it may be nearly impossible for any given person to simulate your network (for example, not only the version of Windows you are running but all the drivers installed and hardware specific to your Ethernet interface ... to only mention a few variables).
Consider using a network monitor to capture all communications set out by the Windows computer.  Consider the Windows computer occasionally failing your network.  Consider the delay you experience may be the time it takes for Windows to recover from what it thinks is a bad network.
The observation is that Windows sends out many autonomous messages over a new network in a "discovery" mode.  The suspicion is that the lack of response to some or all of these messages will result in Windows failing a network.
Windows does have ways of reporting the status of networks that vary with the version of Windows. But these methods (menus) can be frustrating to use as they don't appear to update often enough to reflect the true behavior of traffic coming out of the Windows computer.
Regardless, test if the state of the network is always good.  Also, test if connecting equipment Windows might expect on a functioning network (for example, a router with a DHCP server) improves the response time.  This, as an effort / test to determine if Windows is more responsive while connected to a healthy / active network.


text:
Any way to include the text of a file inside a sketch, to make it shorter and neater?
I'm wondering if there is any way to include the text of a file into a sketch by using a single placeholder command, similar to the "#Include" command when using Server Side Includes on .shtml files.
I'm sorry if I'm not wording this correctly. It was hard for me to phrase it and also hard for me to search about it, since the nouns seem so generic.
I understand that some parts of code can be separated out into their own functions, and that those functions could be saved in a different .ino file. But I'm wondering about for the cases that can't be separated out into functions (like for declarations at the beginning of a sketch, or an area in loop() that would require too many variables to be passed to the function).

EDIT: I think I should've been more specific:
In one example, I have lots of html code being served from the loop() function. The Arduino webserver is serving a complex page that shows about 100 buttons on the webpage. I would like to separate the page-serving code to a separate .ino file and have it opened as a separate tab in the Arduino IDE. That way it's easy for me to open that tab whenever I want to modify the webpage, but also the code for serving the page won't take up so much space in my main file. The code isn't completely html (it has lots of functions and conditionals), so that's why I can't just save it as an external .html file and have it served from that file.
As another example: At the top of my sketch I have lots of defines for wireless signals that need to be sent. They look like this:
const unsigned long a1o = 4216115, a1c = 4216124, a2o = 4216259, a2c = 4216268, a3o = 4216579, a3c = 4216588, a4o = 4218115, a4c = 4218124, a5o = 4224259, a5c = 4224268; //remote control 1

There are 10 lines of code that look like that, and I never have to modify them because they're all constants. When I'm searching for bugs in my code, I never have to refer to those lines, and they're usually just in my way.

Yes. It's called #include.

cases that can't be separated out into functions. This sounds very wrong. If you can't break you code into smaller chuck, creating separate files isn't going to much, and will probably make your code even harder to understand.

In those -few- cases where there are really complex sets of parameters, the usual solution is to pass them through a struct.

Or you can use global variables... Or just use the include (remember to call your file "xxx.h" instead of "xxx.ino", otherwise the compiler will try to compile it twice, thus giving errors)

Thanks for responding! Could you guys please look at the edit I made at the bottom of the question, and tell me what you think?

I'm surprised that #include can be used like that, because the official Arduino page on Include says this: #include is used to include outside libraries in your sketch. But if it works for things other than libraries, maybe it would be a good solution for me! I'll try it out after I get some further input.

@Jerry Check my answer... you can use it as long as you use it properly ;)

You should also use PROGMEM, otherwise those variables also end up in RAM. See Putting constant data into program memory (PROGMEM) for details.

Usually you should not define a variable inside a header file. If, for example, you write
// file myvars.h
int var_a = 10;

// file main.ino
#include "myvars.h"

// file another.cpp
#include "myvars.h"

the linker will fail, because there are two definitions of the same variable var_a.
The correct way to do it is to declare a variable as extern inside the header file, then define them into a cpp (or ino) file just once. I mean
// file myvars.h
extern int var_a;

// file myvars.cpp
int var_a = 10;

// file main.ino
#include "myvars.h"

// file another.cpp
#include "myvars.h"

This way you will be able to access var_a from both main.ino and another.cpp. If you don't want to add another cpp file for the definitions, you just have to provide the definition inside ONE of the ino or cpp files you already have.
So, in your case, just make two more files:
file remote_control_1.h:
extern const unsigned long a1o, a1c, a2o, a2c, a3o, a3c, a4o, a4c, a5o, a5c;

file remote_control_1.cpp:
#include "remote_control_1.h"
const unsigned long a1o = 4216115;
const unsigned long a1c = 4216124;
const unsigned long a2o = 4216259;
const unsigned long a2c = 4216268;
const unsigned long a3o = 4216579;
const unsigned long a3c = 4216588;
const unsigned long a4o = 4218115;
const unsigned long a4c = 4218124;
const unsigned long a5o = 4224259;
const unsigned long a5c = 4224268;

and in your files just write #include "remote_control_1.h" to access those variables

As suggested in comments, you can use #include statements to include texts of files into a sketch.  For example, suppose files c1.h,  c2.h,  c3.h,  c4.h, and  c5.h are in directory ~/sketchbook/tincludes, along with the file tincludes.ino, which is as follows:
#include <Streaming.h>
void setup() {
  const long int
#include "c1.h"
#include "c2.h"
#include "c3.h"
#include "c4.h"
#include "c5.h"
 etc=5   ;
  Serial.begin(115200);
  Serial << z1o <<  z1c <<  z2o <<  z2c <<  z3o <<  z3c <<  z4o <<  z4c <<  z5o <<  z5c;
}

Further, suppose c1.h ... c5.h each contain one line of code, as follows:
==> c1.h <==
  z1o=25829, z1c=9774,

==> c2.h <==
  z2o=7850, z2c=25585,

==> c3.h <==
  z3o=7103, z3c=17981,

==> c4.h <==
  z4o=30827, z4c=24511,

==> c5.h <==
  z5o=4167, z5c=10036,

Then the sketch will compile ok, and the sketch-lines with const long int through etc=5   ; will compile the same as if they were replaced by
const long int z1o=25829, z1c=9774, z2o=7850, z2c=25585, z3o=7103,
     z3c=17981, z4o=30827, z4c=24511, z5o=4167, z5c=10036, etc=5;

This will work only if you include the h files just once. As soon as you include them in two cpp/ino files you will get linker errors. The usual way is to split definition and declaration in two files and use extern to notify the linker to search for them somewhere else. Check my answer for what i think is the correct way to deal with shared variables


text:
What could make an LCD stop working permanently after being connected for 5 seconds to Arduino?
I was using a 20x4 LCD connected to Arduino Uno via a common I2C adapter board. Everything was working perfectly, including the LCD. I had it running like this for a couple of days without any problems.
My next step was to connect the LCD to a Nano instead in order to make the package smaller. The exact same code from the Uno was uploaded to the Nano, and I connected the wires in the exact same way. The major difference here was that I soldered the wires onto the Nano, because I didn't want to use headers. I did a continuity test for shorts and the connections seemed to be fine. There are only 4 wires between the Arduino and LCD adapter board: 5v, ground, SDA and SCL.
The Nano powers up fine, and the LCD powers up fine, but immediately the LCD shows the following:

That had never happened when I had the LCD connected to the UNO.
After that, the LCD stops working completely, even when I move it back to the UNO. It just constantly displays those 2 lines. (Adjusting the contrast makes the boxes appear or disappear).
After the first LCD seemed permanently broken like that, I tested it on a 2nd brand-new LCD. First I connected it to the same Uno with the same code, and everything was working perfectly. I re-uploaded that same code again to the Nano, just to make sure everything was in sync. Then upon connecting the 2nd LCD to the Nano, immediately it displayed those 2 lines. I disconnected it right away (within 5 seconds), and tried to put it back on the Uno, but still the display is corrupted. I've tried other sketches, but both of these displays seem to be broken and never display anything except for those 2 lines.
Even if I just connect 5v and ground to the LCD, no matter from what source, it just constantly displays those 2 lines.
Any ideas as to what could "break" an LCD so quickly like that, and if it's possible fix it?
Edit:
As per Gerben's suggestion, I removed the I2C backpack and hooked the LCD up directly. This was the 2nd one I had broken, the one where I'm more certain of its entire (short) history. I ended up with the exact same result. Adjusting the pot only makes the boxes appear or disappear. I tried skipping the Arduino completely and giving it 5v power from an adapter, and it still has the same result.

Is this on the end of your long wires in your other question?

The first LCD was, but for the 2nd LCD I tested it with short 6" jumpers. I never put the 2nd LCD (which also broke right away) at the end of the long wires.

Also I have a 16x2 LCD (smaller) connected to a Nano via the same I2C adapter, with more complex code, and at the end of a 10' cable, and that has been working perfectly for a few weeks now.

Try removing the backpack, and connect the LCD directly to an Arduino. That way you know if it's the backpack or the LCD that's broken.

I just tried removing the backpack and connecting it directly, and I ended up with the same result. I added the new information to the bottom of my post.

Do you get the same results in both 8-bit mode and 4-bit mode?

It took me a while to figure out how to use 8-bit mode (followed these instructions: https://electrosome.com/interfacing-lcd-arduino-uno/, where it seems that the unused pins are just pulled to ground), and I got the same result. I want to note that the boxes show up on the LCD immediately when it's powered, whether from an Arduino or from a 5v adapter, before the LCD even has time to read anything from the Arduino.

I am having exactly the same problem. I reordered a new LCD (looks identical to yours) and it worked first time, then started displaying those lines. Did you manage to solve this?

Try in your code lcd(0x27,16,2); insted of lcd(0x3f,16,2);

It's unlikely that you have killed the unit as this is pretty hard to do from the data interface and your picture is typical for an LCD that has not gone through the initialization sequence.  A dead LCD driver will usually display nothing and what your picture shows is that the LCD controller itself is operating.  If anything is dead, I would suspect the I2C interface board as this would yield the same result you are seeing.  It may also be that the timing of the I2C interface is right on the edge which may explain why a long cable'd setup is working.
Note that if the initialization is not done, no other commands will work.  Note also that the initialization timing and sequence of events is ABSOLUTELY CRITICAL and missing any single step or time requirement will give the result you are showing.
Starting at page 10 of this instructional PDF is my favorite and the basis of my driver that I have been using since the 80's.

The driver I use works on every display I have ever hooked to it, regardless of changes in the particular project's processor clock speed because I paid strict attention to the worst case timing requirements.  If the timing of the I2C interface violates one LCD it may not violate another, i.e. one display can tolerate bad timing while another can't.  There are also issues if the LCD driver uses the busy flag or not:  Blind data transmission without reading the LCD's busy state will work if the LCD is fast enough and the driver is slow enough, otherwise 'No bueno!' plus the interface is not going to operate at its maximum speed.  When using the busy flag (Bit 7 of the interface) there is solid handshaking which confirms (Instead of "Trusts") that the LCD is ready for the next cycle and allows operation right up to the limit of performance.
What I would suggest is that you put the interface on a logic analyzer and verify that the timing is not being violated.
Timing tolerances and variation between parts is like lug nuts on a car... If you car has 5 lug nuts per wheel, it will probably work with 3 or even 2 but NOT UNDER ALL CONDITIONS.  SOME LCDs will be happy with bad timing but ALL LCDs NEVER will be.

Thanks! This is some amazing information. I need to read more about this, and later on I'll try some experiments, but I was wondering if anyone can answer these questions: Why would LCD initialization get messed up with the Nano but not the Uno? Also why would it get messed up with a 20x4 LCD, but not with a 16x2 LCD (which works fine with the exact same code on both the Uno and Nano, but obviously the last few characters and 2 lines are missing). BTW once I searched for "Arduino LCD initialization", I found some posts on SE and the Arduino forum about the same issue.

Thanks for the excellent additional information. I'll accept this as the answer once I have more time to experiment and understand it fully. It seems that this information might be relevant to many people who are having this problem. I'm also interested in seeing/learning an Arduino-specific solution, for example a library that is more reliable or a modification to existing popular libraries.


text:
How to use setModemRegisters in RF24
The below picture is the introduction of setModemRegisters .

First: What is the mean of ModemConfig* config? I mean: how to write the parameter. Maybe just give a example, and it will be better if it's suitable for this SO question.
Second: What is the mean of data rate? It is the speed of SPI between the SI4463 and MCU or speed of two SI4463  ?
Third, What is the mean of bandwidths? I never saw it...

Thanks for any help .

ModemConfig * config is a pointer to a ModemConfig struct.
You need to create a ModemConfig struct, populate it then pass a pointer to it in the call to the setModemConfig() function.
Something like this:
// create the struct
ModemConfig mc = ModemConfig();

... //populate the struct values

// then call the function
setModemConfig(&mc);

The datarate is the rate at which you are sending information over the radio channel (not between the MCU and the Si4463).
The bandwidth is the range of frequencies used in the radio transmission (e.g. in FSK if a low/0 is 99.95MHz and a high/1 is 100.05Mhz then the bandwidth would be 100Khz)

Thanks very much . I write a code in below . Is it right ?


text:
Making two points on a tm1637 display blink [ Solved ]

Hello! In my project, using a display controlled by a TM1637, I want to make the two points on the middle of the screen blink (as every clock does).
The following example, provided by the library I'm using, makes the two points blink as I want (tm1637.point(POINT_ON/POINT_OFF); is what enables/disbales the point):
#include <TimerOne.h>
#include "TM1637.h"
#define ON 1
#define OFF 0

int8_t TimeDisp[] = {0x00,0x00,0x00,0x00};
unsigned char ClockPoint = 1;
unsigned char Update;
unsigned char halfsecond = 0;
unsigned char second;
unsigned char minute = 0;
unsigned char hour = 12;

#define CLK 2//pins definitions for TM1637 and can be changed to other ports
#define DIO 3
TM1637 tm1637(CLK,DIO);

void setup()
{
  tm1637.set();
  tm1637.init();
  Timer1.initialize(500000);//timing for 500ms
  Timer1.attachInterrupt(TimingISR);//declare the interrupt serve routine:TimingISR
}
void loop()
{
  if(Update == ON)
  {
    TimeUpdate();
    tm1637.display(TimeDisp);
  }

}
void TimingISR()
{
  halfsecond ++;
  Update = ON;
  if(halfsecond == 2){
    second ++;
    if(second == 60)
    {
      minute ++;
      if(minute == 60)
      {
        hour ++;
        if(hour == 24)hour = 0;
        minute = 0;
      }
      second = 0;
    }
    halfsecond = 0;
  }
 // Serial.println(second);
  ClockPoint = (~ClockPoint) & 0x01;
}
void TimeUpdate(void)
{
  if(ClockPoint)tm1637.point(POINT_ON);
  else tm1637.point(POINT_OFF);
  TimeDisp[0] = hour / 10;
  TimeDisp[1] = hour % 10;
  TimeDisp[2] = minute / 10;
  TimeDisp[3] = minute % 10;
  Update = OFF;
}

I tried to do it as it was the famous "blink", but nothing works.
Here's what I have done:
#include "TM1637.h" // Library for the 4-Digit Display
#include "RTClib.h" // Library for the RTC
#include <SoftwareSerial.h>

#define CLK 6
#define DIO 7

TM1637 tm1637(CLK,DIO);
RTC_DS1307 RTC;

const int fotoRes = 2;

SoftwareSerial mySerial(10, 11);

void setup()
{
  pinMode(fotoRes, INPUT);

  RTC.begin();
  RTC.adjust(DateTime(__DATE__, __TIME__));

  tm1637.init();
}
void loop()
{
  DateTime now = RTC.now();

  tm1637.display(0,now.hour()/10);
  tm1637.display(1,now.hour()%10);
  tm1637.display(2,now.minute()/10);
  tm1637.display(3,now.minute()%10);

  tm1637.point(POINT_ON); //Like blink example.
  delay(500);
  tm1637.point(POINT_OFF);
  delay(500);
}

EDIT: tm1637.set(0-7) ONLY set the brightnes of the screen. What makes the two pints appear is tm1637.point(POINT_OFF/POINT_ON). I'm asking how can I do to make these two points blink. Thanks.
Arduino UNO R3, DigitalTube library by Grove

Instead of showing us someone else's code that does work, why not show us your code that doesn't work? We can't help you with your code if you show us something completely different.

By delaying for 500ms you are going to take longer than 1second to complete loop(), so the clock will drift quite rapidly and you will see it jumping 2 seconds at a time.  You haven't issued a tm1637.set(); call, is that relevant?

tm1637.set(0-7) is for adjusting the brightness of the display. If it's not declared on the scetch, the brightness for the display will be "typical_brightness" (2).

OK, but does set(7) work? Does it make the display very bright, and set(1) make it dim? If it doesn't even do that, then you've got a bigger problem - like maybe you haven't connected CLK to pin 6 and DIO to pin 7 on your breadboard.

Solution: After a lot of time, I've found the solution to it. Just I have to check if the seconds given are even. If seconds are even, enable both points using tm1637.point(POINT_OFF);.

sorry, disable is the right word there

Calling the point() method only updates a flag; you see the effect the next time you try to display a number. You can use something like this:
void show_time(DateTime &t){
  tm1637.display(0,t.hour()/10);
  tm1637.display(1,t.hour()%10);
  tm1637.display(2,t.minute()/10);
  tm1637.display(3,t.minute()%10);
}

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

  tm1637.point(POINT_ON);
  show_time(now);  // changes take effect here
  delay(500);
  tm1637.point(POINT_OFF);
  show_time(now);
  delay(500);
}

Using delay(); makes the void loop() waits x milis. So, it's a clock, and using that will make my clock go slow.

@spund3 Your question says you want it to be like the Blink example, which is what this is. Your example uses delay(). Have you tried running this code yet? If this isnt what you want then perhaps you should re-phrase your question.

@spund3 Your question says you want it to be like the Blink example, which is what this is. Your example uses delay(). Have you tried running this code yet? If this isnt what you want then perhaps you should re-phrase your question.

I was refering to the final result of the blink example, where the led blinks. I appreciate a lot your solution, but I've found mine yesterday. Thanks!

@spund3 Okay. The final result is still what you expect. You can run it to find out, so I can know if this is a valid answer for anyone else who has a similar question.

This is how I did it just use modulus and it will show the dots every even number of seconds then there is no need for delay --->
if (currentSeconds % 2==0) { tm1637.point(POINT_ON);  } else { tm1637.point(POINT_OFF); }

I haven't used the TM1637 code, but I (think I) understand how it works.
In the original code is the following:
void setup()
{
    tm1637.set();
    tm1637.init();

But in your code you only do the following:
void setup()
{
    ...
    tm1637.init();

Have you tried adding the tm1637.set(); line in?

Yes, and tm1637.set(0-9) only adjusts the brightness of the entire display. What enables/disables the points is tm1637.point(POINT_OFF/POINT_ON


text:
Is there any way to separate this short code into its own function? (webserver, trying to use client.print outside of main loop)
I have an arduino webserver that uses the following code:
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Content-Type: text/html"));
client.println();
client.println(F(""));
...
if (fan1Toggle == 0)
    client.print(F("Fan1•On
"));
else
    client.print(F("Fan1•Off
"));

if (fan2Toggle == 0)
    client.print(F("Fan2•On
"));
else
    client.print(F("Fan2•Off
"));
...

The page is pretty long, allowing the user to toggle over a dozen different switches. Some of the code checks to see the state of a certain switch, and then displays a green or red bullet ("&#8226", like •) on the page if the switch is on or off.
Since the code for the colored bullet is repeating, I wanted to make a function for it. Then I would just call (for example) "displayBullet(fan1Toggle);", and it would determine if fan1 was on or off, and display the correct color depending on the state.
I tried to create the following function:
void displayBullet(int toggle) {
if (toggle == 0)     //switch is off, so display red bullet
    client.print(F("•"));
else    //switch is on, so display green bullet
    client.print(F("•"));
}

But then I got an error saying that "'client' is not declared in this scope".
Is there any way to work around that error, so that I can get the displayBullet() function I want? Or is this something that can't be shortened like this, because the "client" function has to be inside the main loop?
Thanks!

You can pass client to the function by reference, like this:
void displayBullet(EthernetClient & client, int toggle)
  {
  if (toggle == 0)     //switch is off, so display red bullet
    client.print(F("•"));
  else    //switch is on, so display green bullet
    client.print(F("•"));
  }

Now it knows about client. Make sure you pass client when you call it:
displayBullet(client, 1);

Thanks a lot!! That's very useful information to know, and I'm sure it'll help me in the future with other similar problems.


text:
After moving project from Arduino Mega to Due, pushbuttons now erratically toggle multiple buttons
I've had a project running successfully for months on an Arduino Mega, and today I tried to swap the Mega for a Due to increase the speed. After making the change, the entire project is working successfully except for a strange problem with the pushbuttons.
I have 5 momentary pushbuttons that toggle different controls (they simply send a wireless signal to toggle different AC outlets). After moving the project to the Due, when 1 button is pressed, it ends up toggling 2 other buttons at the same time.
Originally I was using the internal pullups to detect when the buttons were low, but also I've tried connecting them to the Due's 3.3v to detect when they're high, and both times I experienced the exact same behavior.
Is there any reason why there would be this difference in pushbutton-reading behavior between the Mega and the Due? Could it be that the Due is more sensitive to noise? How could I fix this?
The wires connecting to the pushbuttons run about 8 feet. I never had a problem with this setup while running the sketch on the Mega.
Below is the relevant code that detects button presses:
#include <Wire.h>
#include <SPI.h>
#include <Ethernet.h>
#include <RCSwitch.h>
#include <Servo.h>
#include <Event.h>
#include <Timer.h>
#include <dht.h>
#include "RTClib.h"

const byte nl1ButtonPin = 40, nl2ButtonPin = 42, nl3ButtonPin = 44,  pumpButtonPin = 5, irButtonPin = 27,

unsigned long buttonPressTime1, buttonPressTime2, buttonPressTime3, buttonPressTime4, buttonPressTime5;  // when the switch last changed state

byte oldButtonState1 = HIGH, oldButtonState2 = HIGH, oldButtonState3 = HIGH, oldButtonState4 = HIGH, oldButtonState5 = HIGH;

const unsigned long debounceTime = 100;

void setup() {
  pinMode(nl1ButtonPin, INPUT_PULLUP); pinMode(nl2ButtonPin, INPUT_PULLUP); pinMode(nl3ButtonPin, INPUT_PULLUP); pinMode(pumpButtonPin, INPUT_PULLUP); pinMode(irButtonPin, INPUT_PULLUP);
}

void loop() {
 byte buttonState1 = digitalRead(nl1ButtonPin);
  if (buttonState1 != oldButtonState1)
  {
    if (millis () - buttonPressTime1 >= debounceTime)
    {
  buttonPressTime1 = millis ();  // when we closed the switch
  oldButtonState1 = buttonState1;  // remember for next time
  if (buttonState1 == LOW) {
    Serial.println("button1 LOW!");
    toggleLight1();
   }
 }
}

   byte buttonState2 = digitalRead(nl2ButtonPin);
  if (buttonState2 != oldButtonState2)
  {
    if (millis () - buttonPressTime2 >= debounceTime)
    {
      buttonPressTime2 = millis ();  // when we closed the switch
      oldButtonState2 = buttonState2;  // remember for next time
      if (buttonState2 == LOW) {
        Serial.println("button2 LOW!");
        toggleLight2();
      }
    }
  }

byte buttonState3 = digitalRead(nl3ButtonPin);
if (buttonState3 != oldButtonState3)
{
  if (millis () - buttonPressTime3 >= debounceTime)
  {
    buttonPressTime3 = millis ();  // when we closed the switch
    oldButtonState3 = buttonState3;  // remember for next time
    if (buttonState3 == LOW) {
      Serial.println("button3 LOW!");
      toggleLight3();
    }
  }
}

byte buttonState4 = digitalRead(pumpButtonPin);
if (buttonState4 != oldButtonState4)
{
  if (millis () - buttonPressTime4 >= debounceTime)
  {
    buttonPressTime4 = millis ();  // when we closed the switch
    oldButtonState4 = buttonState4;  // remember for next time
    if (buttonState4 == LOW) {
      Serial.println("button4 LOW!");
      togglePump();
    }
  }
}

byte buttonState5 = digitalRead(irButtonPin);
if (buttonState5 != oldButtonState5)
{
  if (millis () - buttonPressTime5 >= debounceTime)
  {
    buttonPressTime5 = millis ();  // when we closed the switch
    oldButtonState5 = buttonState5;  // remember for next time
    if (buttonState5 == LOW) {
      Serial.println("button5 LOW!");
      toggleHeater();
    }
   }
  }
}

On the serial output, pressing one button shows 2 other buttons as low. So, for example, pressing button2 might show: "Button2 LOW!, Button4 LOW!, Button1 LOW!". There doesn't seem to be any clear patterns with which other 2 buttons get simultaneously pressed. Remember that this exact same code and hardware setup was working perfectly for months on the Mega, which makes me believe maybe it's something related to the Due (maybe 3.3v, maybe stronger PU resistors, etc).

You need a pull-up or a pull-down, depending on how the button are wired. Are you grounding them or connecting them to Vcc? Without that you will definitely get erratic results. See Switches tutorial.

I forgot to mention that I'm using the internal pullups. Also I've tried using a 20k resistor instead of the internal pullups, but got the same results. The switches aren't toggling randomly. The problem is that when any button is pressed, it ends up toggling the other switches as well. I love your tutorials BTW, and I got my debounce code from that specific tutorial.

Glad you like them. :) Can you post more (or all) of your code? I don't see 4 buttons being tested there, only one. You could also try a lower-value resistor (eg. 1k).

Try increasing debounceTime

Gerben: I've tried debounceTime of 1000ms, and I got the same result. NG: Is it proper to paste all 1050 lines of code? :) I just updated the post and added more code. There might be simple typos due to the transfer. Today I'll probably be experimenting with the wiring, and also (like NG said) with different resistor values. Maybe the difference could be due to the Due's stronger PU resistors? The Mega uses between 20-50k for the PUs, and the Due uses between 50-150k. I've already tried 20k though (without the internal PUs) and that didn't work.

I don't think this would cause the multiple button press issue you report, but you are not initialising your buttonPressTime variables before you first read them which may cause some issues.

The problem ended up to be a 5-way tact switch that for some reason wasn't working well with the Due. This same switch has worked perfectly for months with the same code and wiring on the Mega. Here is a link to the switch: http://tinyurl.com/plnbv8z. I had a 2nd brand new one on hand to test out, and it resulted in the same problem of causing multiple button presses on the Due. After switching to regular tact pushbuttons, everything worked fine. Does anyone know why a certain switch would work perfectly well with a Mega, but not on a Due? Any ideas on how to make the switch work?

After examining the switch more closely, I noticed small resistors on it. I tested them at 10k. Then I saw that the description of the item says that it includes pullup resistors so that the switch reads LOW when pressed. It says that the power leads can be reversed so that it reads HIGH when pressed. I've tried many different combinations after learning this, including not using the Due's internal pullups, but still have had no success. Either no switches work, or they are toggled nonstop, or 1 switch toggles all the others. Do you think it might work if I remove those on-board resistors?

I think I can explain this. You have set up a rather complex (and incorrectly wired) network of resistors. Your switch has pull-up resistors, clearly connected together, and then to the "+" pin. The other side of the switches would go to ground.

Note that I don't have anything connected to the VCC of the switch ...

Right, so your setup looks like this:

Now with no switch pressed they will all read high due to the Due's pull-up (which by the way is around 100 k compared to the Mega's 50 k.)
Now you press a switch. The naturally grounds that switch so it reads LOW. However it also pulls down neighbouring switches through the 10 k resistor network. So each switch now is in the middle of a voltage divider. There is 20 k going to ground and a couple of 100 k going to Vcc, like this:

This voltage divider would be enough for that pin to register as LOW, and indeed that would be repeated for each pin.
Adding your carefully calculated resistor between the "-" pin and ground is just changing the voltages a bit.
The correct solution is to connect the "+" pin to Vcc so that it acts as a proper pull-up. And get rid of that resistor in series with ground.

It probably worked on the Mega because of the different pull-up resistance when you activated the internal pull-up which would have changed the calculations for the voltage divider.
I've worked out what I think the voltages will be. Note that the supposedly open switches will actually have 1.1 V on them, which as far as I can tell from the datasheet is in the "undefined" territory between LOW (max 0.99 V) and HIGH (minimum 2.31 V).
Reasoning: You can effectively consider that the 4 open switches have 4 x 110 k between them and 3.3 V in parallel. In other words, 27.5 k. With a voltage divider now between that and the 10 k to ground, you have:
10 / (10 + 27.5) * 3.3 = 880 mV

So, there will be 880 mV on the common point (which is "+" on the board).
Now for each switch you have a voltage divider of:
10 / 110 * (3.3 - 0.880) = 220 mV

Add to that the 880 mV at the common point and we have:
0.88 + 0.22 = 1.10 V

Thanks , NG! That analysis is amazing. I'm glad you could confirm it was a complex and messy situation. Everything else worked fine with the board-change from Mega to Due, and in a few hours I had everything else working: servos, relays, RTC, sensors, wireless transmitters, etc. But this simple tact switch took me 2 days of debugging!

Do you see any scenario where those on-board pullup resistors might be useful while using an Arduino?

Sure, just use them as intended. After all, 100 k is pretty weak for a pull-up. Over a long cable run as you described (8 ft) they might be unreliable. Run an additional line for power and supply the pull-up through the board.

I finally got it working. The problem was with this 5-way tact switch being initially incompatible with the Due: http://www.ebay.com/itm/5-Channel-Way-Tactile-Switch-Breakout-Module-Converter-Adapter-Board-Arduino-/141745152805 . As you can see from the picture and the description on that page, the switch includes pullup resistors on the board. I measured those resistors at 10k Ohms. For some reason the switch worked perfectly fine with the Mega's pullup resistors, but didn't work with the Due's.

After much experimentation, I found that the switch will start working if I add a 14.7k resistor between the switch and ground. The Due's internal pullups still had to be activated, otherwise it seemed the switch was firing constantly. When I used a 10k resistor, the center button on the switch wasn't working. And when I used 20k and higher resistors, many of the buttons weren't working.
I posted this as an answer because the switch is finally working the way I want it to. But I'm still curious to know if anyone has a reason why there would be a necessity to have a 14.7k resistor on the ground of this switch in order to make it work with the Due. Note that I don't have anything connected to the VCC of the switch (though I have experimented with it before).

After I moved the switch from next to the board where I was experimenting with it, back to the end of an 8' long copper cable where it was supposed to be, the 14.7k ground-resistor trick stopped working. I ended up just removing all the on-board PU resistors, and then it worked perfectly, just like as if it was a collection of regular tact pusbutton switches.


text:
How to correctly set PWM to control servo angle in AVR?
I've stumbled upon timer configuration to handle my sg-90 servo and my Arduino UNO.
What I did:

Set the prescaler to 64 and mode to fast PWM of 16-bit timer.
The frequency is 50hz so the ICR1 is set to 4999.
And now I don't know what to do next to set the values of OCR1A without guessing them.

From my understanding: If the period is now set to 20ms then for sg-90 servo:
From documentation: http://www.ee.ic.ac.uk/pcheung/teaching/DE1_EE/stores/sg90_datasheet.pdf

Angle 0 should be 1ms (1/20 = 0.05), so OCR1A = 4999 * 0.05 ~= 250
Angle 90 should be 1.5ms (1.5/20 = 0.075), so OCR1A = 4999 * 0.075 ~= 375
Angle 180 should be 2ms (2/20 = 0.1) so OCR1A = 4999 * 0.1 ~= 500

But it doesn't work like that. I've figured out that values are 125, 370, 615 - I've found these numbers in the internet (not in English language) but that guy didn't explain how he got them.
Could someone explain it to me where these numbers come from or where my calculations are incorrect.
It's not a problem with servo because with Arduino servo library everything works fine.
Solution:
The document I've attached is incorrect the pulse range of miliseconds is not 1-2ms but 0.5-2.5ms and everything fits correctly.
Below is my current code:
#define F_CPU 16000000UL

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdbool.h>

#define PRESCALER_64 (1 << CS11) | (1 << CS10)
#define FAST_PWM_A (1 << WGM11)
#define FAST_PWM_B (1 << WGM13) | (1 << WGM12)

int main(){

    TCCR1A = FAST_PWM_A | (1 << COM1A1);
    TCCR1B = FAST_PWM_B | PRESCALER_64;
    ICR1 = (F_CPU / 64 / 50) - 1;

    DDRB |= (1 << PB1);

    while(true){
        OCR1A = 125;
        _delay_ms(2000);
         OCR1A = 370;
        _delay_ms(2000);
        OCR1A = 615;
        _delay_ms(2000);
    }

}

research what signals servos expect to receive ... not an Arduino related question

jsotola is right, this is an AVR question, not an Arduino question, it might be better posted on StackOverflow. Anyway, if your timer period is 5000 cycles, your calculations look correct to me. (I haven't checked the timer setup.) Don't you have an oscilloscope to watch the signal? -- Concerning this "other guy": Since any fool can post stuff on "the net", doubt any information, especially if it is not explained. The difficulty today is to filter the 1% of good things from the crap.

why not use a library?

OK, I figured it out. The problem is in the document. The pulse width is not in range 1-2ms but 0,.5-2.5ms.

OK, I figured it out.
The document I've attached is incorrect, the pulse range of milliseconds is not 1-2ms but 0.5-2.5ms and everything fits correctly.


text:
How to convert array of chars to array of ints?
I have a rather newbie question but I can't figure it out.
Lets say I have this char array:
char array[] = "10,11,12,1,0,1,0";

How can I convert it to an array of int like this?
int arrayINT[] = {10,11,12,1,0,1,0};

Are you sure those arrays contain what you want them to? In the first case, are you looking for an array which contains the values 10, 11, 12, 1, 0, 1 and 0?  (That's not what you have -- you have a string containing an ASCII 1, an ASCII 0, an ASCII comma, and so on.) And the second one I'm almost certain isn't what you want - it's an array of pointers to very short strings (if the compiler even allows it).

yes i know, i'm building http server and this is a part of a string that i recieve from my web page

OK. Do you want it to end up as int arrayINT[] = { 10, 11, 12, 1, 0, 1, 0 } ?

Yes, it seems that Majenko's answer below is working properly :)

I'll edit your question then, so it asks what you want.

Yes of course :)

If you have a C string containing ASCII numbers with a common delimiter (comma in this case) you can use the strtok() function to split it into individual strings.  Then you can use atoi() to convert those individual strings into integers:
char array[] = "10,11,12,1,0,1,0";
int intArray[7]; // or more if you want some extra room?

int ipos = 0;
// Get the first token from the string
char *tok = strtok(array, ",");
// Keep going until we run out of tokens
while (tok) {
    // Don't overflow your target array
    if (ipos < 7) {
        // Convert to integer and store it
        intArray[ipos++] = atoi(tok);
    }
    // Get the next token from the string - note the use of NULL
    // instead of the string in this case - that tells it to carry
    // on from where it left off.
    tok = strtok(NULL, ",");
}

Note that strtok() is a destructive function. It will decimate your existing string with NULL characters as it slices it up.

Amazing, this is working. I knew about strtok() and atoi() but couldn't get them working properly. Thanks very much!!

A major improvement would be counting the commas in the string and allocating an array of the approriate size. On the other hand, why not convert the nth value at runtime?


text:
How to send unmodulated IR-Signal via cable?
I need to generate en (extended) NEC signal. I have connected an Arduino with a display-device via an IR cable.
Arduino --> IR-cable --> IR-input of display device
IR-cable:

One plug is cutted and the 3 wires are connected with the arduino.
The arduino should generate NEC Signals, and the display shall react to it. Basically the arduino acts like a wired remote control.
The problem is: There are many tutorials around, that show how to do this with a sensor (e.g by using this library). But none of the tutorials says how to do it with a cable.
I found out, my previous attempts all failed, because I tried to generate a modulated NEC-signal to the display. The display however does not understand it, because there is no device that demodulates the signal. The IR sensor normally does this, which is missing in this case.
e.g.
This is, what an modulated NEC signal looks like:
00 4e ff 61
The library generates the moduled signal (pulse bursts) and this is how it works for IR sensors.
But how do I have to send my IR-command, that the display understands it? How do I send a not-modulated IR signal?
The following graphic demonstrates the issue:

I do not have IR-LED Transmitter, Amplifier, Limiter, Band Pass Filter, Demodulator, Integrator, Comparator....
I just want to create the green Output-signal directly from my Arduino

Does this cable thing have a datasheet?

I have updated my post

There are two major components to an infra-red signal.  One is the high frequency carrier wave signal that pulses the LED on and off.  This frequency has to match that of the receiver and is used with either a high-pass or band-pass filter to filter out ambient IR light and allow it to only react to a real signal.
The second component, and it sounds like this is the one you are interested in, is the on-off pulsing of that carrier wave in different combinations and with different timings to denote binary 0 and 1.
Without knowing what your cable actually is, and we'd need to see a datasheet to get all the proper information, all this is just surmising.
I would imagine that you provide power and ground to the emitter cable, and the third pin is a logical "on/off" signal that enables and disables the carrier frequency to the LED.  That would allow you to send any codes you like as long as you know the timing of the signal.
In the library you link to is all the timing you need in the ir_NEC.cpp file.  The times are defined as:
#define NEC_BITS          32
#define NEC_HDR_MARK    9000
#define NEC_HDR_SPACE   4500
#define NEC_BIT_MARK     560
#define NEC_ONE_SPACE   1690
#define NEC_ZERO_SPACE   560
#define NEC_RPT_SPACE   2250

The actual data format is defined in the sendNEC function:
void  IRsend::sendNEC (unsigned long data,  int nbits)
{
    // Set IR carrier frequency
    enableIROut(38);

    // Header
    mark(NEC_HDR_MARK);
    space(NEC_HDR_SPACE);

    // Data
    for (unsigned long  mask = 1UL << (nbits - 1);  mask;  mask >>= 1) {
        if (data & mask) {
            mark(NEC_BIT_MARK);
            space(NEC_ONE_SPACE);
        } else {
            mark(NEC_BIT_MARK);
            space(NEC_ZERO_SPACE);
        }
    }

    // Footer
    mark(NEC_BIT_MARK);
    space(0);  // Always end with the LED off
}

The mark and space functions take a number of microseconds to perform either an ON or OFF of the PWM signal.  That is somewhat simpler for you, since it is just an ON or OFF of a digital IO pin to control the output of the emitter cable.  So where you have a MARK you turn on the output, then delay for the specified time. For a space you turn off the output and again delay for the specified time.
So you can just replicate the operation of that sendNEC function but with your own output control and timing in it instead of using the functions in that library.

Edit: It seems the cable doesn't need power - just provide the ground connection and the signal connection.  Of course, this is assuming that it isn't just an LED on a wire.  If it is just an LED on a wire then you would need to just use the library you link to as it is.

You probably want to make sure the voltage level of the power wire is the same as the arduino. Otherwise you should buffer the signal.

@Gerben Everything should be made clear by the datasheet that doesn't seem to be forthcoming.

"So you can just replicate the operation of that sendNEC function but with your own output control and timing in it instead of using the functions in that library." This is exactly the point. I do not know how my own output should look like. I don't really understand the difference between "modulated" and "unmodulated"-signals. So how for example does my code 004eff61has to be sent?

Voltage Level of cable and arduino are both 5V

The difference between modulated and unmodulated is that the modulated is a series of pulses of a pwm signal, and unmodulated is a series of pulses of just steady 5v.

I needed the same thing, so I created a library for it: https://github.com/dennisfrett/Arduino-Direct-NEC-Transmitter.
It basically just pulls the pin high and low with the correct timings for the NEC protocol.


text:
Just sanity-checking a concept... poor man's self-monitored alarm system
If I wanted to throw together a simple burglar-alarm system that had wireless sensors talking to an Arduino (which would then send me an SMS message via cellular shield as a silent alarm telling me which alarm sensor had changed state_)... what technology would you recommend for the sensor-to-arduino signalling?
It needs to be something that draws little or no power until the alarm is triggered, resistant to radio interference, and as always cheap is a huge plus.... but I haven't gotten much beyond that.
(Of course if anyone's already implemented something like this and there are descriptions/sketches I can adopt and adapt, feel free to point me in the right direction.)
EDIT: To provide more info,this is a wood-framed house, 2 storey plus basement, brick chimney possibly in the way. No straight-line distances greater than 60 feet. Wifi, wireless phone, usual electronics and a wood shop I'm still putting together. Shouldn't be difficult, I just want a robust solution in case a friend asks me to replicate it... and for purely aesthetic reasons.

What sort of range do you need from sensor to Arduino, and what sort of adventure will the transmission signals have - standard house with a few internal walls, big open-plan workshop with near line-of-sight to each sensor, or a shop that sells radio jamming devices that can never be switched off ?

NRF24L01+ for communication. Extreme low power if not sending. Detects packet loss, and automatically resend the packet.
You would however need a small arduino board at the sensor, to read the sensor, and signal to NRF24L01 to send a message.
You'll have to put the arduino in to low power sleep mode to get some good battery life. Either have the sensor wake the arduino up with an interrupt, of poll the sensor like every half second, and immediately go back to sleep.

That sounds good. See Power saving techniques for microprocessors. For extremely low power you would need switches to wake the Arduino (eg. reed switches on doors and windows).

extremely low power is only needed if you are running on a coincell or something. The overhead of running a watchdog timer, and waking up once or twice a second, to take a measurement, only means a few less weeks of battery life on e.g. AA batteries (with still more that a year of runtime). Use this tool to calculate battery life to give you an indication. Sometimes it just isn't worth the effort, just to get a few percent extra battery life.

It's more than a few percent. You can budget for a current draw of 100 nA with no watchdog timer in full sleep mode, and 6.5 µA with the watchdog timer enabled. So that is 65 times the current draw. Now I do indeed have a gadget lying around running from AA batteries that has lasted a couple of years, using the watchdog timer, but it would last even longer if it didn't need to use it.