text:
Connecting to the Sparkfun Redboard on Mac OS X Sierra
I'm trying to connect to my Sparkfun Redboard (Arduino UNO compatible) on Mac OS X 10.12.3 (Sierra). The board comes with a USB mini to USB A FTDI cable. The board lights up and gets power over USB, but I don't see the right USB serial port in the Arduino IDE (I only see the Bluetooth port).
I've installed the VCP FTDI drivers v2.3 to no avail. When that didn't work, I also installed the CH340 CH341 drivers (but I doubt I need those). Rebooting the computer didn't help either.
I can only load the FTDI VCP v2.3 drivers using an explicit command sudo kextload /Library/Extensions/FTDIUSBSerialDriver.kext/. When I run kextstat | grep FTDI, I get:
 155    0 0xffffff7f83892000 0x7000     0x7000     com.FTDI.driver.FTDIUSBSerialDriver (2.3) ECC3AF36-431D-370D-86F2-5237785E9CF8 <127 41 5 4 3 1>

But it still doesn't show up in the Arduino IDE.
I've heard that Apple's own USB FTDI drivers (AppleUSBFTDI) could cause problems, but it seems these are never loaded. If I try to unload the Apple FTDI driver (sudo kextunload –b com.apple.driver.AppleUSBFTDI), I get the following:
(kernel) Kext com.apple.driver.AppleUSBFTDI not found for unload request.

Failed to unload com.apple.driver.AppleUSBFTDI - (libkern/kext) not found.
Any tips are welcome. Thanks!

I'm using MacOS Sierra and an Arduino Pro Mini (from Sparkfun) with a breakout USB-to-UART board that uses an FTDI FT232 chip. I'm using the default Apple FTDI drivers (the ones that are bundled with Sierra) and I'm having no problems whatsoever.
Some people have reported problems using the manufacturer (FTDI) drivers that they had already installed after upgrading to Sierra. Some of them solved it by uninstalling the conflicting drivers and relying on the default Apple FTDI drivers uninstalling the conflicting drivers and relying on the default Apple FTDI drivers instead. It's worth a try.
OTOH, the CG340 driver doesn't currently work under Mac OS Sierra. Fortunately, Adrian Mihalko patched the driver and made it available at GitHub, along with some troubleshooting instructions.


text:
How to make a servo sweep from 0 to 180 on press of a button on PS2 controller? (without delay)
I am working on a project that requires the servo to make a complete sweep once on pressing a button say r2 on the pS2 controller. I am using the Arduino Mega 2560,a PS2 controller clone, Bill porter's Ps2x library.
I have figured out a way to do so by adding a delay to the code but when the delay is used I can't use other parts of my project. What should I do?
int pos = 0;    // variable to store the servo position
int button = 2;  // The button will be on Pin 7
void setup()
{
myservo.attach(9);  // attaches the servo on pin 9 to the servo object
pinMode(pos, OUTPUT);
pinMode(button, INPUT);
digitalWrite (button, LOW);
}

void loop()
{
if(ps2x.ButtonPressed(PSB_RED))

for(pos = 0; pos < 90; pos += 90)  // goes from 0 degrees to 90 degrees
{                                  // in steps of  degree
 myservo.write(pos);

}
  if(ps2x.ButtonReleased(PSB_RED))

 for(pos = 90; pos>=90; pos-=90)
 {
myservo.write(pos);
delay(50);                             // waits 50ms for the servo to reach the position

What should you do? Well, at first you can simplify the answerer's task by actually posting the code you are using, so everybody can check and suggest you the modifications..

You need to look at interrupts.  Rather than delay you should keep looping until the next time to do something occurs.

yes interrupts could be be used but i have 5 motors , 2 stepper motors to control excluding the servos. wont interrupts make the code more complex?An example would really help.

If you already have the code, if you have a good understanding of how it works it shouldn't be too difficult to implement, but you would multitasking it by creating several objects that use a central time value. It should all be here, if you follow them and read them they can explain better than I: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview

Thank you that helped a lot but , i am using an approach similar to the one described here http://playground.arduino.cc/Code/AvoidDelay

source: Stack Exchange

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

authors: Роман Шабалин

sort: votes


text:
Controlling 4 LED strips
I have 4 single color LED strips which I would like to control individually with one remote controller - turn them on/off an dim them. So far I only have my LED strips (They are about 3.5 meters of length combined), an 80W power supply and an Arduino Uno. I'm new to this kind of stuff. Could you help me with the setup. What parts do I need?
EDIT:
So I decided to go with an Arduino Nano. First, I'll try to power up only one strip. My question now is, how to power up the Nano. All the setups I found, have an USB cable connected to the nano to power it up. Can I connect my 12V+ to the VIN?
EDIT2:
Take a look at my setup. Is that OK?

Thanks

Are the LEDs 12 or 5V?

The LEDs are 5050 12V 60leds/m

So far your question is hard to answer because there are so many varieties of LED strip out there. Could you please provide details on what LED strip you are using (a link to a online electronics shop is ok). If you know any details on how to drive these LED strips (eg on/off, I2C, SPI etc).

Its this strip:
http://www.dx.com/p/72w-6000lm-3500k-300-5050-smd-led-warm-white-light-strip-white-yellow-5m-12v-305265#.WKWy7aptn0M
and my power supply is 12V 7A

The product page of the Arduino Nano states “Input Voltage: 7-12 V”. So, yes, you can power it with 12 V at Vin.

You will need several things.
First I assume that the power supply is a 12V power supply. If it isn't, better to get one (3.5m of leds can be 4.2A, so even a 12V 5A supply is fine). Note: you didn't specify the led size, so the current can vary a lot. But a standard one is a 60 leds/m 5050 leds, which means 60mA/5cm, or 4.2A for a 3.5m strip.
Anyway you will need a 12V power supply to power both the strips and the arduino (through the Vin pin).
You will then need a way to control the leds from the arduino. Since the required current is too high for the arduino, you will need to put a transistor. I tend to prefer nMOS over NPN, but just because of the way I learned them. Anyway just get a low-side transistor (either an nMOS or an NPN) capable of handling the required amount of current (at least a couple amperes, better if they are >5A) and the proper circuit to turn them on. Usually you will just need one or two resistors. You will need to connect the +12V to the plus terminal of the leds, the drain (or collector) of the transistor to the ground pin of the led you want to control, the source (or emitter) of the transistor to ground and the gate (or base) of the transistor to the arduino through the proper circuit.
Then the remote controller. You did not specify what kind of remote controller you want to use, but usually you can cope with a IR receiver (e.g. the TSOP382 or any other) and the proper decoding. A lot of remote controllers are already mapped in the library IRremote; you just have to read the value it provides; inside the arduino you will need to save the codes for the commands (you will have to train it first) and then simply compare.
This is a generic answer, because you did not provide any details. If, implementing this, you encounter any problem open a specific question with what you did up to that point.

authors: شعبان بِن صلاح

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


text:
Does Arduino sent output to TX pinout?
I am beginner at Arduino,i tried to read as much as i can but i am not sure if i am doing good.I would like to send a specific code for a (non PC) device through the TX pinout when i push the button which is wired to the Pin 2.I have writtem this small code to check it:
int buttonUPpin = 2;
int UpinStatus=LOW;

void setup() {
  Serial.begin(9600);
  // put your setup code here, to run once:
pinMode(buttonUPpin, INPUT_PULLUP);
digitalWrite(buttonUPpin,HIGH);

}

void loop() {
  // put your main code here, to run repeatedly:

UpinStatus=digitalRead(buttonUPpin);

if(LOW==UpinStatus)
{
Serial.print('A');
digitalWrite(1,LOW);

}

}

When i push the button i can see at serial monitor the 'A' character but i am not sure if this character was also sent out to the TX pinout since the TX led is not blinking only the RX led.

You haven't set pinMode for pin 1 and using pin 1 will interfere with the serial monitor (never use 0 and 1).
#define buttonUPpin = 2;
#define LedPin = 3;
int UpinStatus = LOW;

void setup()
{
    Serial.begin(9600);
    pinMode(buttonUPpin, INPUT_PULLUP);
    pinMode(LedPin, OUTPUT);
    // digitalWrite(buttonUPpin,HIGH);  // Don't think this is right

}

void loop()
{
    UpinStatus=digitalRead(buttonUPpin);
    if(LOW==UpinStatus)
    {
       Serial.print('A');
       digitalWrite(LedPin, LOW);  // Not sure if High or Low depends on you circuit
    }
}

If you start the Serial it takes over the TX and RX pins and it ignores pin mode settings (and digitalWrite too).
Btw TX and RX LEDs are driven by USB to Serial interface chip so you don't have any control of it either.

in this case how can i be sure that the desired output was sent out?

If you mean TX/RX LEDs, then they are blinking if you're receiving data from computer (RX), or if you're sending data to the computer (TX). If you mean logic state on pin, you can't use pins 0 and 1 with Arduino Serial.

Rx led is blinking when i push button2 but there is no tx led blinking in the same time(to send to the tx pinout)


text:
Relay does not trigger
Its my first attempt to work with relay
I tried to test my relay with this simple code
int Relay = 2; void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(Relay,OUTPUT);
}

void loop() {

  digitalWrite(Relay,HIGH);
  delay(1000);
  digitalWrite(Relay,LOW);
  delay(1000);
}

Connected to
IN -> Digital 2
GND -> GND
VCC -> 5V
The only thing is happened is the LED of the relay blinking in every sec. but can not hear the clicking sound from the relay box or testing with a multimeter's diode function the two(NC and COM) OUTs aren't close
I tried to test other relays(from the same type) but does not do anything else.
thank you for your help
What can be wrong?

Can you try the relay without arduino? 5V->5V, GND->GND, IN->0V/5V should simulate the arduinos programm. If it does not click, it may be damaged.

NC is "Normally Connected" - this contact is connected to COM ("common") if coil of the relay is not powered - the relay is disconnected.
NO "Normally Open" is connected to COM when the coil of the relay is powered - the relay is connected.
Some relays have the coil powered when the signal from MCU is LOW.
If the coil of the relay doesn't click, but the signaling LED lights up, then VCC is not connected. Check if you plugged the wire really to 5 V on Arduino side.

You need to define Relay.  If the LED on the relay module is blinking, then you must have defined as pin 2 output, but omitted it from the code you posted.  Please post all of the code!
It is good practice for all user variables to start with lowercase, e.g. relay not Relay.  Then the code becomes:
relay = 2;
void setup(){
pinMode(relay,OUTPUT);
digitalWrite(relay,"LOW");
}

void loop(){
digitalWrite(relay,"HIGH");
delay(1000);
digitalWrite(relay,"LOW");
delay(1000);
}

If the relay still does not click on/off, test the microcontoller voltage output on the relay pin using your voltmeter.  Check the relay is not dead or mis-wired.

sorry the relay was defined just made a mistake when copying the source code

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


text:
Slower nRF24L01 round trip delay than expected
Short/summary
I expected that the round trip delay of a nRF24L01+ would be less than 1 ms. In practice I see around 3 to 5 ms and other sources have similar values. Does anybody know why this round trip delay is so long?
In short: nRF24L01+, adapters for them, tmrh20 RF24 library, 16 byte payload, highest speed.
Below is the full problem and related info.
Problem description
I received my nRF24L01+ radios and they work much better so far than my 433 MHz radios.
However, still with my nRF24L01 I get response times which are much lower than I expected.
I used the sketch of Example using dynamic payloads (which I increased to 16). The library I use is from tmrh20.github.
I also reduced the characters written to serial (and increased it to 250K) and some other small changes.
Transmitter code
Below is the code for the transmitter (manually removed receiver code and role switching code since that works/was not used except for first time)
/*
   Dec 2014 - TMRh20 - Updated
   Derived from examples by J. Coliz <maniacbug@ymail.com>
   http://tmrh20.github.io/RF24/pingpair_ack_8ino-example.html

   Results:
  PA                          MAX
  Retries                    2,8   2,4   2,8
  AutoAck                     True       False True
  EnableAckPayLoad            True
  PayLoadSize                  16          16    8   32
  DynamicPayLoad              True                        False True
  CRC Length                   16                                 8

  Failures / 25 iterations     0-1  3-4  ???         24??

  write min [us]              812    (792)    625         652   644
  write avg [us]              2618           2106              2251
  write max [us]              6224   (804)   5756        5756  7724

  logdata[m][n] = millis()       4                  us
  write:                       812..6224 (avg 2617) us
  available:                    28..  32            us
  read                         100                  us
*/
#include <SPI.h>
#include "RF24.h"

RF24 radio(7, 8);
uint32_t counter = 0;

static const int NR_OF_LOG_ITEMS = 10;
static const int LOG_LENGTH = 25;
uint32_t logData[LOG_LENGTH][NR_OF_LOG_ITEMS];
uint8_t currentLogLine = 0;

void setup()
{
  for (int m = 0; m < LOG_LENGTH; m++)
  {
    for (int n = 0; n < NR_OF_LOG_ITEMS; n++)
    {
      logData[m][n] = -1;
    }
  }

  Serial.begin(250000);
  Serial.println(F("TRANSMITTER SPEED TEST"));

  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setRetries(2, 8);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.setPayloadSize(16);
  radio.enableDynamicPayloads();
  radio.setCRCLength(RF24_CRC_16);

  byte addresses[][6] = {"1Node", "2Node"};
  radio.openWritingPipe(addresses[0]);
  radio.openReadingPipe(1, addresses[1]);
  radio.startListening();

  radio.writeAckPayload(1, &counter, 16);
  //radio.printDetails();
    radio.stopListening(); // Takes 336..348 us

}

uint32_t response = 0;

void loop(void)
{
  uint32_t response;

  uint32_t time = micros();
  logData[currentLogLine][1] = micros();

  if (radio.write(&counter, 16))
  {
    logData[currentLogLine][2] = micros();
    if (!radio.available())
    {
      logData[currentLogLine][3] = micros();
      Serial.print(F("Got blank response. round-trip delay: "));
      Serial.print(micros() - time);
      Serial.println(F(" microseconds"));
    }
    else
    {
      logData[currentLogLine][4] = micros();
      while (radio.available())
      {
        logData[currentLogLine][5] = micros();
        unsigned long timer = micros();
        radio.read(&response, 16);
        logData[currentLogLine][6] = micros();
        logData[currentLogLine][7] = response;
        logData[currentLogLine][8]++;
        Serial.print(F("Got response "));
        Serial.print(response);
        Serial.print(F(" round-trip delay: "));
        Serial.print(timer - time);
        Serial.println(F(" microseconds"));
        counter++;
      }
    }
  }
  else
  {
    logData[currentLogLine][9] = micros();
    Serial.println(F("Sending failed."));  // If no ack response, sending failed
  }

  if (counter == LOG_LENGTH)
  {
    for (int m = 0; m < LOG_LENGTH; m++)
    {
      Serial.print("Location ");
      Serial.print(m);
      Serial.print(": ");
      for (int n = 0; n < NR_OF_LOG_ITEMS; n++)
      {
        Serial.print(logData[m][n]);
        Serial.print("  ");
      }
      Serial.println("");
    }
  }
  currentLogLine++;

  delay(100);  // Try again later
}

Receiver code
Below is the code for the receiver (manually removed transmitter code and role switching code since that was not used)
/*
   Dec 2014 - TMRh20 - Updated
   Derived from examples by J. Coliz <maniacbug@ymail.com>
*/
#include <SPI.h>
#include "RF24.h"

RF24 radio(7, 8);
uint32_t counter = 0;

void setup() {

  Serial.begin(250000);
  Serial.println(F("RECEIVER SPEED TEST"));

  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setRetries(2, 8);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.setPayloadSize(16);
  radio.enableDynamicPayloads();
  radio.setCRCLength(RF24_CRC_16);

  byte addresses[][6] = {"1Node", "2Node"};
  radio.openWritingPipe(addresses[1]);
  radio.openReadingPipe(1, addresses[0]);
  radio.startListening();

  radio.writeAckPayload(1, &counter, 16);
  //radio.printDetails();
}

void loop(void)
{
  byte pipeNo = 0;
  uint32_t response = 0;
  while ( radio.available(&pipeNo))
  {
    radio.read( &response, 16);
    // Since this is a call-response. Respond directly with an ack payload.
    response++;
    radio.writeAckPayload(pipeNo, &response, 16); // This can be commented out to send empty payloads.
    Serial.print(F("Loaded next response "));
    Serial.println(response);
  }
}

Resulting log fragment
Below are the results:
TRANSMITTER SPEED TEST
Got response 26 round-trip delay: 1960 microseconds
Got response 1 round-trip delay: 1964 microseconds
Got response 2 round-trip delay: 876 microseconds
Got response 3 round-trip delay: 880 microseconds
Got response 4 round-trip delay: 1960 microseconds
Got response 5 round-trip delay: 4128 microseconds
Got response 6 round-trip delay: 6296 microseconds
Got response 7 round-trip delay: 880 microseconds
Got response 8 round-trip delay: 884 microseconds
Got response 9 round-trip delay: 3044 microseconds
Got response 10 round-trip delay: 880 microseconds
Got response 11 round-trip delay: 880 microseconds
Got response 12 round-trip delay: 884 microseconds
Got response 13 round-trip delay: 876 microseconds
Got response 14 round-trip delay: 1964 microseconds
Got response 15 round-trip delay: 1956 microseconds
Got response 16 round-trip delay: 4128 microseconds
Got response 17 round-trip delay: 3044 microseconds
Got response 18 round-trip delay: 4128 microseconds
Got response 19 round-trip delay: 1964 microseconds
Got response 20 round-trip delay: 4124 microseconds
Got response 21 round-trip delay: 8452 microseconds
Got response 22 round-trip delay: 880 microseconds
Got response 23 round-trip delay: 1960 microseconds
Got response 24 round-trip delay: 884 microseconds
Location 0: 4294967295  12328  14216  4294967295  14248  14280  14384  26  0  4294967295
Location 1: 4294967295  115260  117152  4294967295  117184  117216  117316  1  0  4294967295
Location 2: 4294967295  218152  218956  4294967295  218988  219020  219120  2  0  4294967295
Location 3: 4294967295  319916  320728  4294967295  320760  320788  320888  3  0  4294967295
Location 4: 4294967295  421684  423576  4294967295  423608  423636  423736  4  0  4294967295
Location 5: 4294967295  524572  528628  4294967295  528660  528692  528792  5  0  4294967295
Location 6: 4294967295  629624  635844  4294967295  635876  635912  636012  6  0  4294967295
Location 7: 4294967295  736844  737660  4294967295  737688  737720  737820  7  0  4294967295
Location 8: 4294967295  838616  839428  4294967295  839460  839492  839592  8  0  4294967295
Location 9: 4294967295  940388  943364  4294967295  943396  943424  943524  9  0  4294967295
Location 10: 4294967295  1044356  1045168  4294967295  1045200  1045232  1045332  10  0  4294967295
Location 11: 4294967295  1146168  1146980  4294967295  1147012  1147040  1147140  11  0  4294967295
Location 12: 4294967295  1247972  1248784  4294967295  1248816  1248848  1248948  12  0  4294967295
Location 13: 4294967295  1349784  1350588  4294967295  1350620  1350652  1350756  13  0  4294967295
Location 14: 4294967295  1451592  1453484  4294967295  1453516  1453548  1453648  14  0  4294967295
Location 15: 4294967295  1554524  1556412  4294967295  1556440  1556472  1556580  15  0  4294967295
Location 16: 4294967295  1657448  1661508  4294967295  1661536  1661568  1661668  16  0  4294967295
Location 17: 4294967295  1762544  1765516  4294967295  1765548  1765580  1765680  17  0  4294967295
Location 18: 4294967295  1866552  1870612  4294967295  1870640  1870672  1870772  18  0  4294967295
Location 19: 4294967295  1971648  1973540  4294967295  1973572  1973604  1973704  19  0  4294967295
Location 20: 4294967295  2074580  2078636  4294967295  2078668  2078696  2078804  20  0  4294967295
Location 21: 4294967295  2179680  2188060  4294967295  2188092  2188124  2188224  21  0  4294967295
Location 22: 4294967295  2289096  2289912  4294967295  2289940  2289972  2290072  22  0  4294967295
Location 23: 4294967295  2390904  2392800  4294967295  2392832  2392860  2392960  23  0  4294967295
Location 24: 4294967295  2493832  2494644  4294967295  2494676  2494708  2494808  24  0  4294967295

And here some processed (with Excel) results:
    write   available   available   read
    us  us  us  us
    1..2    2..4    4..5    5..6

    4060    32  28  100
    816 32  28  100
    6224    32  32  100
    2980    32  28  100
    1896    32  28  100
    816 32  32  100
    1896    32  32  100
    812 32  32  100
    2976    32  32  100
    2976    32  32  100
    816 28  32  100
    4060    32  32  100
    816 32  28  100
    4060    28  32  100
    816 32  32  100
    816 28  32  100
    1896    32  32  100
    5140    32  28  100
    6220    32  36  100
    816 32  32  100
    4060    32  32  100
    2980    28  32  100
    4060    32  28  100
    816 32  28  100

min     812 28  28  100
avg     2617.666667 31.33333333 30.83333333 100
max     6224    32  36  100

The main chunk is the write which takes 812..6224 us (with an average of 2617 us). Probably this big variance is due to retries, but still the lowest 812 us is more than expected:
Summary of results
I did some more tests, I will not put all log/intermediate results here, but the following table shows some tests:
  PA                          MAX
  Restries                    2,8   2,4   2,8
  AutoAck                     True       False True
  EnableAckPayLoad            True
  PayLoadSize                  16          16    8   32
  DynamicPayLoad              True                        False True
  CRC Length                   16                                 8

  Failures / 25 iterations     0-1  3-4  ???         24??

  write min [us]              812    (792)    625         652   644
  write avg [us]              2618           2106              2251
  write max [us]              6224   (804)   5756        5756  7724

  millis()  [us]                4
  available [us]              24/32
  read      [us]               100

Conclusion of results

Changing the number of retries lower than 2 (= 500 us), 8 (retries) results in too many errors, and does not lower the minimum, just the maximum, but with errors so useless
AutoAck always returns in 7u92-804 us, but I need AutoAck in my project
Changing payload to 8 results in a minimum of 625 us
Changing payload to 32 resulted in too many errors
Disabling dynamic payload resulted in a minimum of 652 us
Changing CRC length to 8 results in 644 us

Expectations
When I use the calculation in the datasheet, I come to the following results:
Datasheet  https://www.nordicsemi.com/eng/nordic/download_resource/8765/2/84238108/2726
Table 15
                Item                          Value Unit    Item              Value Unit
T_OA            Time on-air                 0.0001005 s     Preamble              1 byte
T_ACK           Time on-air Ack             0.0001005 s     Address               5 bytes
T_UL            Time upload                 0.000512  s     Payload              16  bytes
T_ESB           Time Enh Shock-Burst Cycle  0.0008785 s     CRC                   2 bytes
Back and forth?                             0.001757  s     packet Control field  9 bits
                                                            Air data rate   2000000 bits/s
                                                            SPI data rate    250000  bps  (guess)
                                                            T_stby2a        0.00013 s
                                                            T_IRQ          0.000006  s

According to the formulas, I would get around 0,875 ms (probably one way) and about double back-and-forth. Btw, I don't understand why T_OA is not in the formula.
However, I get as minimum 0,812 which may be some rounding/timing inaccuracy.
Conclusion
The retries are causing the longer writes. The minimum is similar to the calculated value from the datasheet.
Question

Home come there are so many retries?
Should I check for noise on channels?

Background
What I hoped for was to send a 32 (but 16 is ok too) byte message, than after 5 ms another message, and have the ack of the second message back within like 6 ms or so (including the 5 ms delay between the first and second message to be sent). This means the sending and receiving of an ack should take about 1 ms (which is well within the 0,256 ms calculated above).
Setup
Note my Uno's with nRF24L01 are about 1 meter apart, settings: 2 mbps, set retries(2, 4), enable ackpayload/dynamic payloads.
RF Radio hardware
The RF radios I'm using are nRF24L01+ like this:

Datasheet: PDF Download
Update: I see people use various capacitors and/or a voltage regulator.
I did not do that, but I have a an adapter from 5V->3.3V specifically for the nRF24L01 (like this). I think there is already a voltage regulator and needed capacitors on this board. As far as I know the IC on the adapter is the voltage regulator and the capacitor (one) is probably just above the GND/VCC connection in the picture above. Or a second capacitor left of the MI/IRQ

Results

You are not new here, so it should beyond obvious to you by now that this is unanswerable without your code.

@ChrisStratton I added the code (and indeed, it was not a good idea to link to the code and manually write some differences. So I added the code for the transmitter and receiver (but manually removed code that was not used/needed to make a 'minimal' code example.

Might want to check the actual frame size. There are a lot of "extra bits"; preamble, address, control, check-sum and there is also the PLL lock time to consider. Need a link to the manual :)

You might want to update the code so that the call to micros(), 32-bit calculation, number to string conversion and Serial print is included. Measure first-print after.

@MikaelPatel I will check into that ... there might be more bytes than expected, also I added a link to a datasheet: http://www.nordicsemi.com/eng/nordic/download_resource/8041/1/45228426

@MikaelPatel ... but I will try first myself, also with changing the measuring (I don't need necessarily the conversion of bytes and calculations, since in my 'real'  program there are other calculations needed (much more, but hopefully not more than 1 ms).

@MikaelPatel: According to par 7.3 from the datasheet the preamble is 1 byte, addres 5 bytes (max), packet control field 9 bits, crc 1-2 bytes, so in total 9 bytes + 1 bit ... however I see there are some calculations which I'm going to do this evening when I have more time to add to the question above.

radio.enableAckPayload();
Disabling ack (or well, not enabling it) will improve the speed of transmission.

@Avamander I know, but I need the acks (or I have to change the roles, which also takes a lot of time).

Disable (or don't enable) dynamic payloads then?

I'm going to do some tests with that too (although I might need dynamic payloads eventually).

@Patel: I checked the datasheet and seems my minimum is very much like the calculated value from the datasheet :-) ... the retries is the problem now.

@Avamander That saves a bit, but I may also need it in my project (see number under summary/conclusion of results)

Could the last answer in this post give you a lead?
https://forum.arduino.cc/index.php?topic=171611.0

@MatsK well I found that the times I get are very similar to the table above that answer, so I cannot expect more from it. There are already capacitors on the adapter board, however, when I will use a 3.3V AVR I will use the capacitor like that answer (Adding 100uF).


text:
Easy way to upload sketches using MIDI (without RX pin removed)
I noticed when I use sketches with MIDI (using RX/TX), before uploading I have to remove every time the RX wire ... is there an easy way to prevent this?
(I'm thinking about making a push button/toogle for this to prevent it, but maybe there is an easier way).
Update: I use an Arduino Uno

@CL: Updated my question (sorry for not mentioning)

To allow the bootloader on the Arduino MCU to communicate with the USB chip, the TXD/RXD pins are connected:

These connections have 1 kΩ resistors so that the signals of the USB chip do not interfere with your own hardware too much. However, this means that your own hardware can easily override those signals.
In this case, your MIDI hardware actively drives the RXD line to a high level.
You is no way to work around this in software.
You could try to replace the optocoupler's pull-up resistor (270 Ω) with a 10 kΩ resistor, which would make the USB controller's signals ten times stronger than the MIDI ones, but this might make the signal edges too slow.
To reliably prevent conflicts, you have to add a disable function to the MIDI receiver, or power it down, or disconnect it.

Thank you very much for this clear answer (and also the background).
I will order a toggle or switch that keeps state (like on/off) to hardware-wise open or close the connection from RX to the MIDI circuit, so I don't have to switch it on/off.
I don't like to take out the MIDI connector (they are quite well connected), and removing the cable is a bit tedious :-) Also I don't want to mingle with the MIDI ' quality'  since I will need all messages to be received well.

I changed to a Mega, using 3 channels for MIDI and one for debugging; eventually I might use all 4 for debugging.


text:
H11L1 opto isolator does not pass signal to Arduino (correctly)
I have made a very basic test circuit for the opto coupler H11L1 ('similar'datasheet: http://www.datasheet4u.com/datasheet/H/1/1/H11L1_MotorolaInc.pdf.html))
I use the test circuit:

simulate this circuit – Schematic created using CircuitLab

The LED and 470 ohm resistor is only for testing.
U1 is the Arduino (software serial pin 9/11) and U2 is the H11L1.
The LED is flashing similar to the RX led on the Arduino.
Also I tested before in an even simpler circuit that the signals from the H11L1 pass through pin 4 (although inverted, which seems to be normal).
However, I don't receive any data in the Arduino (I tried different Arduinos, different speeds, different H11L1).
The data I receive from the (hardware) serial/debug terminal:
0
0
0
0

etc.
My sketch:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(9, 11); // RX, TX

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

void loop()
{
    mySerial.write('A');
    while (mySerial.available())
    {
        Serial.println(mySerial.read());
    }

    delay(100);
}

How can I get the correct signal? (meaning 'A' are printed instead of 0's?
Update
New sketch (not having the duplex problem):
#include <SoftwareSerial.h>

SoftwareSerial mySerial(12, 13); // RX, TX

void setup()
{

  Serial.begin(115200);
  mySerial.begin(115200);
}

void loop()
{
  Serial.print("Write: A ");
  mySerial.write('A');

  while (mySerial.available())
  {
    Serial.print((int) mySerial.read());
  }

  Serial.println("");

  delay(100);
}

Output:
Write: A
Write: A
Write: A
Write: A

etc.
Update
Problem solved: I put it in an answer for clearity.

First, try looping back the Arduino's RX/TX lines to verify you do not have a full verses half duplex problem.

@st2000 I don't receive anything (guess I have that problem) ... what can I do about that (?), never heard of it (in Arduino context at least)

I'm still looking around.  When looping back, you are depending on the Atmel processor hardware to buffer up received data while your software is busy transmitting it.  Then you are depending on the Arduino serial libraries to get that buffered data (if there is any) after the it was already received.  It is like talking and listening at the same time.  Instead of the usual taking then listening in turn.

(ok in that case I need to change my sketch a bit) ... btw, for this test I put a wire directly between pin 9 and 11 (without any resistor) ... hope that is the correct way?

I am fairly sure the UART connected pins are similar or the same as GPIO.  Interestingly, I can't find an exact match to this problem (if in fact it is a problem).  Most use the UART to send messages followed by and EOL like an '\n".  So they write sketches which expect to talk in turn.  You, on the other hand, probably need to write a sketch which will work byte by byte.  This assumes the Atmel processor you are using can only buffer 1 UART byte.  Take a look at "Serial.readBytes()" to get some ideas.  This is a long way to go just to test the optical coupler.

Perhaps I should add.  In the real world, I would write an interrupt routine to handle the received data.  All it would do is maintain a buffer of received data that is long enough to contain any expected messages until I could get around to reading it.  So when I'm off sending data I will not miss any data being sent to me.  I am not sure how the Arduino serial libraries are written.  But they need to be simple so as to be small and compatible with as many other Arduino libraries as possible.

@st2000 I tried also to print a newline after the A, but it also does not make a change.
Using an interrupt routine for a test seems a bit overkill (in that case I rather wait for the Mega ... or use my old optocouplers which already work, but the H11L1 are a bit smaller.

R2 and R3 form a voltage divider that prevents a proper high voltage; you have to connect the LED to 5V as shown in Transistor's answer. And the real MIDI circuit has more than one 220 Ω resistor; you can increase R1 to 1 kΩ. Anyway, for loopback testing, a direct connection 11 → 9 is OK.

Try without SoftwareSerial: write 0/1 manually to pin 11, then wait a little, read the input from pin 9, and output that value to a LED connected to another pin. Use a delay of one second or so to be able to observe it. If this works, then the problem is not with the hardware.

@CL: That will probably work ... since I tested with putting the Anode to +5 or GND directly to see the LED and that is either on or off, but the problem is with 'faster' (Serial/MIDI) circuits.

@CL: Problem is solved ... see my answer (I had two use two H11L1's because of the inversion... you told me about it, but didn't think it was needed in this case, but it seems it is.

Isn't the problem that you need a second serial for debugging output? If might be a better idea to make that the software serial.

I already made a successful optocoupler test with Serial (using 2 Arduino Uno's, one for sending, one for receiving). But I still didn't get good MIDI information ... I think it has to do with the edge speed ... I can buy a better oscilloscope, but even that wouldn't 'fix' the problem.

@ForTheOneWhoDownvotedHundredOfMyQuestions: please mention why you downvoted, so I can improve it if needed.

simulate this circuit – Schematic created using CircuitLab
I'm not sure I can help much with the MIDI problem but I can help with the schematic. I've reorganised it for clarity. Since the opto-isolator has an open-collector output any loads it is driving should be connected to supply + rather than common.

With the LED only for testing, the actuall pull-up is missing.

Sure. He can put the actual pull-up back when finished testing.

I built the circuit and do not see a change ... also the LED is not burning/flashing, but that is related to the pull-up ... but how I should connect that (?)

I like how @Transistor cleaned up your circuit.  It should work.  CL is correct, you had a voltage divider before and your test LED may have caused problems.  Note, different Arduinos can use different processors with different internal hardware.  Not all processor UARTs are alike.   Some have more hardware buffering which off loads the burden of serial timing from the software.  There is a balance between cost, hardware features and software complexity.  Welcome to Firmware land.

R3 and D1 provide the pull-up. The open-collector output will pull it down when turned on giving almost 5 V across the R3 - D1 combination.

@Transistor ok (thought it was missing in the diagram, thought that R3 would be the pullup (but of course the LED itself also is taken into account)

@st2000 I tried two Arduinos, but none of them are 'official'... and maybe my experience as software engineer does not make it easier in this case (it either works or doesn't work)

Yes, you've discovered the difference between software and firmware :)!  It's the particular processor the board uses (Mega uses ATmega2560 while the Uno uses ATmega328P).  Most copies use the same Atmel chip.  But the bigger and more elaborate boards use complex chips. Some with ARM cores.  It will be these differences in chips which may turn out to make your (high level) code work differently (better) in some cases.  If you really need this (full duplex all the time?) to work, I would try that other serial library AltSoftSerial that @jot suggested if you can.

So far I'm not successful (thought it worked, but it seems not) ... not even with the other serial library (so far).

Although not really the solution ... somehow it works and your circuit made it easier ... now I'm going to add components so it looks more like the MIDI circuit, but I have at least a working version.

MIDI is a more time critical application.  You may want to search for a MIDI centric Arduino library instead of relying on a general serial port library.  In the end, you may find, to get the best performance, you will have to write your own Arduino C++ libraries & learn how to handle interrupts.  Again, welcome to firmware.

Rule of thumb: never use SoftwareSerial (unless you have to, and even then you should avoid it).
The SoftwareSerial works better with higher baudrates. The lower the baudrate, the more trouble you get. Unless you aim for a high baudrate of 115200, then SoftwareSerial can cause troubles again. Remember that using SoftwareSerial means that there is not much else you can do in your sketch.
When SoftwareSerial is used with a very low baudrate of 300, then it could even disturb the receiving of data of other hardware serial ports. Because SoftwareSerial disables interrupts during transmitting and receiving, the lower the baudrate, the longer the interrupts will be disabled.
The SoftwareSerial can not transmit and receive at the same time, and that is what you are doing.
A Arduino Leonardo, Micro, or Arduino Mega 2560 board have unused hardware serial port(s). Use one of those to do tests with a serial port.
As soon as you start using SoftwareSerial for a test, you are actually testing the SoftwareSerial itself.
There is an alternative, the AltSoftSerial Library. it can receive and transmit at the same time. Use a baudrate that is not too high, 9600 baud should be fine.

I will try with higher baudrates ... also I changed my sketch (but without much improvement).
To be honest, I have a Mega, but I don't 'dare' to use it, since that one is now on a breadboard circuit that I'm for sure knows it works (and by disassembling it, I'm afraid I don't have any working solution). I have ordered a new one, and will test it again when I receive it.

To the best of my knowledge, “Software Serial works better with higher baudrates. The lower the baudrate, the more trouble you get” is false.  In general, software serial is incapable of handling data rates like 115200 without high incidence of errors.  OTOH, it should handle 4800, 9600, etc ok

MichelKeijzers, The SoftwareSerial is useless for you, it can not transmit and receive at the same time. @JamesWaldby With lower baudrates, the interrupts are disabled for longer time. With a full sketch and lots of things going on, it will cause a lot of trouble for sure.

I tried with 300, 9600 and 115200 (no changes) ... probably the duplex is the main problem ... I will try this test again when I have the new Mega.

In the Arduino IDE, in the Library Manager, search for: altsoft. Install the "AltSoftSerial by Paul Stoffregen". Find which fixed pins are for RX and TX ( https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html ). Use 9600 baud, and it should work.

I'm afraid it doesn't work ... going to wait for my new Mega (should arrive any day).

Problem solved:
I created a setup with two Arduino Uno's, one which sends the information by a hardware UART, one that receives it. The reason to do this is not to use a software serial and having no problems with the duplex. I thought I need a Mega, but with two Uno's it is also possible.
However, this did NOT solve the problem.
What solved the problem was to use TWO opto-isolators. The H11L1 inverts the signal, and it seems I had to connect the output of the first H11L1 to the input of a second and now it works.

Or invert the connection of the optocoupler's LED (anode to power, cathode to TX), like in the MIDI circuit.

Oh of course (thought it was in sending, but if inverting that way is possible, than it's even better). Just doubting if the MIDI functionality will work (since it will be functionally similar as now) :-(

@CL: Thanks for your remark ... this was the solution .... now I can finally replace my 6N137s by H11L1's ... thanks for your remark and patience (same for all others who helped me).

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


text:
Are static variables in a function bad?
For my code I use a couple of static variables.
But when I search the internet, they seem "evil".
For example: I have a function which will be executed every loop (5ms looptime).
to increase the speed I added some static variables to it.
Is the way I am doing this bad? Are there simple solutions for it?
Code:
int ProgFormula() {
  static int StartPosition;
  static int DeltaPosition;
  static int LoopTime = 5;
  static int AccelerationLoops;
  static int TotalLoops;
  static int EndOne;

  static float VelocityLoop;
  static float VelocityFactor;

  int Setpoint;

  if (Iteration == -1) {
    StartPosition = PID.ActualPosition;
    DeltaPosition = abs(SetPosition - StartPosition);
    VelocityLoop = Velocity / (1000 / LoopTime);
    TotalLoops = DeltaPosition / VelocityLoop;
    if (TotalLoops <= (AccelerationLoops * 2)) {
      AccelerationLoops = (TotalLoops / 2);
      VelocityFactor = (VelocityLoop * 0.5 / AccelerationLoops) / 2;
    }
    else {
      AccelerationLoops = 70;

      VelocityFactor = VelocityLoop * 0.5 / AccelerationLoops;
    }
    TotalLoops = DeltaPosition / VelocityLoop + AccelerationLoops;
    EndOne = (VelocityFactor * pow(AccelerationLoops, 2));
  }
  else if (Iteration >= 0 && Iteration <= AccelerationLoops) {
    if (StartPosition < SetPosition) {
      Setpoint = VelocityFactor * pow(Iteration, 2) + StartPosition;
    }
    else {
      Setpoint = -VelocityFactor * pow(Iteration, 2) + StartPosition;
    }
  }
  else if (Iteration > AccelerationLoops && Iteration <= (TotalLoops - AccelerationLoops)) {
    if (StartPosition < SetPosition) {
      Setpoint = VelocityLoop * Iteration - EndOne + StartPosition;
    }
    else {
      Setpoint = -VelocityLoop * Iteration + EndOne + StartPosition;
    }
  }
  else if (Iteration >= (TotalLoops - AccelerationLoops) && Iteration <= TotalLoops) {
    if (StartPosition < SetPosition) {
      Setpoint = -VelocityFactor * pow((TotalLoops - Iteration), 2) + DeltaPosition + StartPosition;
    }
    else {
      Setpoint = VelocityFactor * pow((TotalLoops - Iteration), 2) - DeltaPosition + StartPosition;
    }
  }
  else {
    Setpoint = Setpoint;
  }
  return(Setpoint);
}

Is it better to avoid statics? If so why?
Thanks in advance,
Koen

Why do you need static variables in the above example? I can't see them being any use here. If you just want a variable that you can change easily because you're 'tweaking' your code (e.g. changing LoopTime so you get as many loops per second without compromising accuracy) then pull that variable into global scope; you can #define <name> <value> or const <Type> <name> = <value>. These declarations/definitions get 'smoothed out' by the compiler and so don't take up any program memory.

to increase the speed I added some static variables to it. - how does that increase the speed?

pow(AccelerationLoops, 2) - you want fast speed but then you call a function that will be slow?

I am still a newbie haha, hmm better replace that pow function...

No but my idea was to calculate some variables infront (iteration -1) how could i use those  otherwise?

So you mean you want to 'create' variables so that they already exist before you start the beefy calculations, thus saving time? I don't think it works like that. All the calculations after the if (iteration == 1) is going to get torn apart by the compiler and then rearranged as optimally as it thinks it can be. If you need execution of these to be quicker, you might be better off asking in StackOverflow, as this topic transcends Arduino and is definitely within the realm of programmers and compilers.

That too, but I actually meant the calculations of the statics at iteration == -1. Won't this save? If not, I can make those local

I understand better what you are attempting now. I gather you call the function with Iteration == -1 at some stage to "preload" the static variables, and then multiple times with other iteration values. To answer better we would need to know how often you do that. For example, do you do 1000 iterations before re-calculating the static variables? Or three iterations? Judging by the fact that you get PID.ActualPosition in the "preload" part, you must be calling it with Iteration == -1 reasonably often.

Hello Nick, yes you are right, when the function "starts up" it is calledwith Iteration -1. The amount of iterations it takes is depended on the DeltaPosition and the Velocity. Normally this will 500+

There is no point in making LoopTime static, as it is set on every call to the function. The whole point of static is to make sure the contents of the variable is preserved between calls. Static locals are much like globals in this respect, only they have a restricted scope. On the other hand, Setpoint should probably be static, otherwise it seems it may be returned uninitialized. And the line Setpoint = Setpoint; has no effect.

I made up a test by adding enough to the posted code to get it to compile:
float ActualPosition, SetPosition, Velocity;

int Iteration;

int ProgFormula() {

  static int StartPosition;
  static int DeltaPosition;
  static int LoopTime = 5;
  static int AccelerationLoops;
  static int TotalLoops;
  static int EndOne;

  static float VelocityLoop;
  static float VelocityFactor;

  int Setpoint;

  if (Iteration == -1) {
    StartPosition = ActualPosition;
    DeltaPosition = abs(SetPosition - StartPosition);
    VelocityLoop = Velocity / (1000 / LoopTime);
    TotalLoops = DeltaPosition / VelocityLoop;
    if (TotalLoops <= (AccelerationLoops * 2)) {
      AccelerationLoops = (TotalLoops / 2);
      VelocityFactor = (VelocityLoop * 0.5 / AccelerationLoops) / 2;
    }
    else {
      AccelerationLoops = 70;

      VelocityFactor = VelocityLoop * 0.5 / AccelerationLoops;
    }
    TotalLoops = DeltaPosition / VelocityLoop + AccelerationLoops;
    EndOne = (VelocityFactor * pow(AccelerationLoops, 2));
  }
  else if (Iteration >= 0 && Iteration <= AccelerationLoops) {
    if (StartPosition < SetPosition) {
      Setpoint = VelocityFactor * pow(Iteration, 2) + StartPosition;
    }
    else {
      Setpoint = -VelocityFactor * pow(Iteration, 2) + StartPosition;
    }
  }
  else if (Iteration > AccelerationLoops && Iteration <= (TotalLoops - AccelerationLoops)) {
    if (StartPosition < SetPosition) {
      Setpoint = VelocityLoop * Iteration - EndOne + StartPosition;
    }
    else {
      Setpoint = -VelocityLoop * Iteration + EndOne + StartPosition;
    }
  }
  else if (Iteration >= (TotalLoops - AccelerationLoops) && Iteration <= TotalLoops) {
    if (StartPosition < SetPosition) {
      Setpoint = -VelocityFactor * pow((TotalLoops - Iteration), 2) + DeltaPosition + StartPosition;
    }
    else {
      Setpoint = VelocityFactor * pow((TotalLoops - Iteration), 2) - DeltaPosition + StartPosition;
    }
  }
  else {
    Setpoint = Setpoint;
  }
  return(Setpoint);
}

void setup ()
  {
   ProgFormula ();
  }  // end of setup

void loop ()
  {

  }  // end of loop

Disassembling this I got the following assembler:
000000a8 <_Z11ProgFormulav>:
  a8:   6f 92           push    r6
  aa:   7f 92           push    r7
  ac:   8f 92           push    r8
  ae:   9f 92           push    r9
  b0:   af 92           push    r10
  b2:   bf 92           push    r11
  b4:   cf 92           push    r12
  b6:   df 92           push    r13
  b8:   ef 92           push    r14
  ba:   ff 92           push    r15
  bc:   0f 93           push    r16
  be:   1f 93           push    r17
  c0:   cf 93           push    r28
  c2:   df 93           push    r29
  c4:   00 91 0c 01     lds r16, 0x010C
  c8:   10 91 0d 01     lds r17, 0x010D
  cc:   8f ef           ldi r24, 0xFF   ; 255
  ce:   0f 3f           cpi r16, 0xFF   ; 255
  d0:   18 07           cpc r17, r24
...
 4ec:   cb 01           movw    r24, r22
 4ee:   df 91           pop r29
 4f0:   cf 91           pop r28
 4f2:   1f 91           pop r17
 4f4:   0f 91           pop r16
 4f6:   ff 90           pop r15
 4f8:   ef 90           pop r14
 4fa:   df 90           pop r13
 4fc:   cf 90           pop r12
 4fe:   bf 90           pop r11
 500:   af 90           pop r10
 502:   9f 90           pop r9
 504:   8f 90           pop r8
 506:   7f 90           pop r7
 508:   6f 90           pop r6
 50a:   08 95           ret

0000050c <setup>:

So that function (ProgFormula) has taken up:
0x50a - 0xa8 = 1122 bytes

Now by removing the "static" declarations, like this:
   int StartPosition;
   int DeltaPosition;
   int LoopTime = 5;
   int AccelerationLoops;
   int TotalLoops;
   int EndOne;

   float VelocityLoop;
   float VelocityFactor;

It now compiles to:
000000a8 <_Z11ProgFormulav>:
  a8:   6f 92           push    r6
  aa:   7f 92           push    r7
  ac:   8f 92           push    r8
  ae:   9f 92           push    r9
  b0:   af 92           push    r10
  b2:   bf 92           push    r11
  b4:   cf 92           push    r12
  b6:   df 92           push    r13
  b8:   ef 92           push    r14
  ba:   ff 92           push    r15
  bc:   0f 93           push    r16
  be:   1f 93           push    r17
  c0:   cf 93           push    r28
  c2:   df 93           push    r29
  c4:   c0 91 04 01     lds r28, 0x0104
  c8:   d0 91 05 01     lds r29, 0x0105
  cc:   8f ef           ldi r24, 0xFF   ; 255
  ce:   cf 3f           cpi r28, 0xFF   ; 255
  d0:   d8 07           cpc r29, r24
...
 27e:   cb 01           movw    r24, r22
 280:   df 91           pop r29
 282:   cf 91           pop r28
 284:   1f 91           pop r17
 286:   0f 91           pop r16
 288:   ff 90           pop r15
 28a:   ef 90           pop r14
 28c:   df 90           pop r13
 28e:   cf 90           pop r12
 290:   bf 90           pop r11
 292:   af 90           pop r10
 294:   9f 90           pop r9
 296:   8f 90           pop r8
 298:   7f 90           pop r7
 29a:   6f 90           pop r6
 29c:   08 95           ret

0000029e <setup>:

That is now:
0x29e - 0xa8 = 502 bytes

Conclusion
Adding "static" has made the function over twice as long. Presumably it is also slower. After all, those extra instructions have be doing something.

to increase the speed I added some static variables to it.

Your belief that making variables static increases the speed does not seem to be supported.

Hmm that is a huge difference. Unfortunately that is not what I meant. When Iteration == -1, then those variables are calculated. These variables will be used in further iterations. Because I intitialized them as statics they remember their value, now these do not have to be calculated over and over again. But is it worth the memory loss?

Could you actually time the functions? I don't fully trust your assumption about longer code being slower, since it doesn't account for how much might be skipped/replayed by jumps.

@KoenR - can you please run a test and post the calculated values when Iteration == -1? I tried timing the two methods but without knowing what values you are using the results are pretty meaningless. Or you could simply time it yourself, by calling micros() at the start, and again at the end, subtract one from the other, and work out which is faster.

@BrettAM - you are quite right to not trust assumptions. I try not to make them if I can, however in this case without any knowledge of the figures involved, I had to guess.

@NickGammon timed the calculations. WOW! When using the static variables the calculation took +- 150 micros. Now if use it the formula without the statics it will take an astonishing 0 - 4 microseconds to calculate. Then I realised that the compiler still exists. All my variables were predefined (not changing). Now I runned it like it should, all the iterations with a static variable took 50 micros whereas the one without took 200 micros. In the end, statics are sometimes viable I guess

When using the static variables the calculation took +- 150 micros. - I'm not sure if you are saying it took more or less there. However it looks like static variables worked for you in this case. :) It is always nice to test these ideas. Sometimes it is hard to predict what the compiler will do to your code.

A lot what you are seeing here may be due to the the compiler's ability to keep local variables in registers rather than in memory.  In a situation where that does not apply (due to program complexity, architectural limits, or a volatile keyword), it may come down more to the availability of other base + offset indexing modes vs. stack pointer + offset ones.

You comparison is flawed because you replaced static variables with automatic variables, which changes the semantics of the program, as static variables remember their values between calls. C.f. the compilation warnings you get: “XXX may be used uninitialized in this function”. For the comparison to be fair, you have to replace the local statics with global variables. My tests show static variables have no size penalty.

Your comparison - whose? If I understand correctly the suggested code uses Memoization to save calculating things as often. The savings probably need to be measured empirically, because the cost of calculating the static variables (as opposed to register variables) would not be nil. Whether or not you get the benefit would depend on how often you have to recalculate.

to increase the speed I added some static variables to it. Is the way
  I am doing this bad? ... Is it better to avoid statics? If so why?

I use this technique too ... IMHO it is neither good nor bad.  In a logger, for instance, all the wall clock time stamp information has to be looked up (perhaps time(0)), and formatted at least once in any given second.  I use function static variables to prevent duplicating that effort for the 10's to 100's (or even more on a really fast machine) of log entries that happen in the same second.
I suspect your saying "to increase speed" is what the other answers focus on, and many contributors in SE jump on the 'premature optimization' concept. I think you unintentionally misled them.
Maybe your audience would respond more positively to the term 'memoize' ... this technique avoids some work (when it can).
And, just to be complete - Wikipedia agrees with you:

In computing, memoization is an optimization technique used primarily
  to speed up computer programs by storing the results of expensive
  function calls and returning the cached result when the same inputs
  occur again.

Note 1. I think memoization implies that there is work that need not be duplicated every time through the function (sometimes only initialization) ... thus there often will be an if-clause to skip over the un-necessary work.
Note 2. static is not the only way to hold onto previous values, but is probably somewhat more appropriate for a function when you do not want a class object (to hold the previous values).
Note 3. 'memoize' has impact because it avoids work, and this speeds up the whole system.

That is exactly what I meant. This function will be called every 5 milliseconds. So that is why I wanted to know which is faster. But next time better to call memoize

Any style recommendation is going to be a bit subjective and conditional, but the biggest problem I see here is that the function can only be running one set of variables at a time. What if you wanted to do two of the task your ProgFormula function is a part of simultaneously? You have no way to switch the state of those variables between calls.
You could make a struct to store the state that your function modifies, that way the calling code could swap out the state between calls. Or you could wrap it in a class so the calling code can make as many instances as it needs and not worry about the data each owns.
As a side note, Premature optimization is the root of all evil. The state you are storing is built with a few subtractions and divisions, but the pow function your loop sometimes calls may be the part dominating its running time.

I know it are some beefy calculations, for now those cannot be replaced. Luckely this function will not be called twice, once every loop. If one of the variables change then the Iteration starts at -1 again. I did remove the pow function, rather complex for a simple square


text:
Implementing DES or AES Encryption with DateTime Synchronization on Uno
We are trying to implement AES or DES encryption using an Arduino Uno.
We have a keypad module attached that will be used to input integers. A String should be generated based on the entered data and encrypted using AES or DES.
We have tried several online libraries with no success due to the constraints put on the "plain text" size.
An example pseudo-code for the above:
string key = "This is a key";
string plain = "This is the keypad input" + keypadInput + "and some other random stuff"; <- This should have any size.

var cipher = AES.encode(plain, key);
print(cipher);

var decoded = AES.decode(cipher, key);
print(decoded);

Could someone please point to the right direction on how to do this?

Can you explain what was wrong with the libraries you looked at? I don't think AES or DES is simple enough to just paste in an answer.

We have tried several online libraries with no success - what online libraries? Your question is very short on detail.

It seems that if value of plain is larger than 16 characters the library will encrypt the first 16 characters only... Is this an Arduino Uno limitation?

So what you need then is to figure out how to pad and then break a message into the 16 byte chucks specified by AES reversably.

How is this doable? Given the character restriction... Can you provide a sample so that I can look into it more? Thanks @BrettAM

Its really simple. Just encrypt the first 16 bytes, then the next 16 bytes and so on. If you are left with, say, 5 bytes, append 11 bytes of zeros and encrypt that. Decryption is the same but instead of appending zeros, you cut off trailing zeros.

Would encrypting the 16 bytes and then append the next 16 bytes and so on result to the same output as if the whole plain text was encrypted in the first place in one go?

We thought about this by the way and figured out that the other party can decrypt whatever is encrypted from the arduino given that it knows the key provided above. However, will this be a problem to the other party trying to decrypt? Given that the output of the encryption will vary based on keypadInput...?

We have no experience with the byte[] objects and whatnot.

Might be time to do a few tutorials. You won't get far programming if you don't learn how to use arrays.
The string class is part of the STL (Standard Template Library) which does not come pre-installed on the Arduino (however you can download it if you want to).
The Standard Template Library (STL) for AVR with C++ streams

Briefly, however you could do something like this:
char key [20] = "This is a key";
char keypadInput [16];  // whatever they entered

char plain[80];

strcpy (plain, "This is the keypad input");
strcat (plain, keypadInput);
strcat (plain, "and some other random stuff");

The example code doesn't have any size checking. You would want to make sure that you don't put more than 79 characters into "plain" (to allow for the terminating 0x00 character). For example, look up strncat.

Can you please elaborate on how DES or AES as described in the question can be implemented?

Have you done much research? Have you Googled Arduino AES encryption like I just did? I got this as the first hit:
Topic: new AES library - Arduino Forum

I've written an AES (Advanced Encryption Standard) library for Arduino.  It supports 128, 192 and 256 bit key sizes.  Code space overhead is about 4KB I think, each instance requires 240 bytes RAM for subkeys.  Fairly tightly coded and checked against official test vectors for ECB mode.  Also CBC mode supported.

It seems that if value of plain is larger than 16 characters the library will encrypt the first 16 characters only... Is this an Arduino Uno limitation?

I don't want to seem unhelpful, but you really should do some research before asking these questions. From Wikipedia - Advanced Encryption Standard (AES):

AES is a variant of Rijndael which has a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits.

A "fixed block size of 128 bits" means you encrypt 128 bits at a time, that is, 128/8 = 16 bytes.
So no, it is not an Arduino Uno limitation, it is the way AES works.

Also see Wikipedia - DES.

In the case of DES, the block size is 64 bits.

So DES does 8 bytes at a time.

What you can do with a password is to hash it, for example: Secure Hash Algorithm or MD5 (amongst others). These algorithms take a variable length string and return a fixed "hash". In the case of MD5 the output is a 128-bit field.
You could then encrypt that 128-bit hash, if you want to keep it a secret.

Would encrypting the 16 bytes and then append the next 16 bytes and so on result to the same output as if the whole plain text was encrypted in the first place in one go?

The suggestion by @BrettAM was, if you want to encrypt more than 16 bytes, do them 16 bytes at a time, padding if necessary the final block.
eg.
AAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBB CCCCCCCCCC000000
      encrypt        encrypt          encrypt
LLLLLLLLLLLLLLLL MMMMMMMMMMMMMMMM NNNNNNNNNNNNNNNN
      decrypt        decrypt          decrypt
AAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBB CCCCCCCCCC000000

In this example the final block was padded with zeros. Now the receiving end decrypts in 16-byte blocks.

Can you please elaborate on how DES or AES as described in the question can be implemented? Or the proper way to do so? Thanks

So i should md5 the string and then apply AES on it?

That was my suggestion, yes.

Hashes are better if the idea is to make this a password system. What do you really hope to get by encrypting the hash though? The password still produces the same, unique, 128-bit string each time, its just a bit different now.

I agree with @BrettAM however the original question specifically asked about We are trying to implement AES or DES encryption using an Arduino Uno. Without knowing more details about this project it is hard to give a definitive answer. A straight hash might fall victim to a dictionary attack, whereas if it was encrypted, and if the key was not known, that might protect it.

I suppose that would be different, but I think salting is the more traditional solution. Either way someone holding the hashed password wouldn't be able to produce a hash collision without a little bitstring stored on the chip.

The purpose of this is that the key stored on the chip is known by another private party and it is the only one who can decode it. Would storing the key on the chip be reversible in any way?

I think you should start a new question, like "can an encryption key stored on a Uno be discovered?" - this is really a new topic.


text:
Arduino Uno powers off when circuit plugged in to +5V and GND pins
I have a max7219 driving an 8 digit 7 segment LED array with forward current of 20mA and typical forward voltage of 1.85V. I'm trying to power this through my arduino UNO (which itself is drawing power from USB), and have the max7219 chip's +5V and ISet(+resistor) and ground pins connected to the respective pins on the arduino.  When I try to plug this in, the arduino will not power up, but removing the jumpers from +5V and GND allows the arduino to power up.
I have confirmed with my multimeter that there is no short between any of the power cables on my led circuit.
The voltage supplied by the arduino works normally if I connect it up to a simple resistor and led on a breadboard.
The voltage across the +5V & GND pins on the arduino drops from 5V to 0V if the jumpers are inserted whilst the arduino is powered up.
I thought perhaps the circuit was trying to draw too much power from the USB, so tried higher resistor values than my initial resistor (20K), to no effect.
What else could be causing this?

Are you running the Arduino direct from the computer's USB port or from a USB hub?  If the latter, is it a powered or an unpowered hub?

Your circuit is using to much power. This will trip the resettable fuse on the Arduino. That's why 5v will go to 0v. Since the max7219 shouldn't draw the 500mA needed to trip the fuse, you probably miswired something. Could you add a picture of your wiring?

@Gerben It may not be. It may be the USB host port being shut down through too much current draw. An unpowered hub will (should) shut down at more than just 100mA.

@Majenko Different result, but still the same cause. PS I've seen unpowered hub with no fuses at all. And motherboards with 900mA fuses (2 ports per fuse I think; maybe).

It's a usb3 port directly from the mobo. The general consensus is too much current draw, which is what i suspected. Now to work out why...I don't think a picture will help much - the circuits on two sided protoboard and a lot of wires are hidden under the displays. I must have miswired something, perhaps transposed the max +5v and Iset wires. That could explain it. Thanks for the comments.

@Gerben It doesn't have to be a fuse - most commonly it's active power switching managed by the hub chip.  Also 900mA is fine for CDP - in fact it may be a little low ;)

Active power management in an external hub (especially enforcing a 100mA limit) is theoretically possible, but quite rare.  Most have polyfuses, at most.

I'm voting to close this question as unanswerable as the poster's rebuilding of the circuit demonstrated that it was a transient wiring fault, not anything a stack exchange site can help with.

and have the ... ISet(+resistor) and ground pins connected to the respective pins on the arduino.

What pin on the Arduino?
The ISet resistor should go to +5 V - don't connect it to an Arduino pin (unless you mean the +5 V Arduino pin). See diagram:

I had a 7-segment display working fine on an Arduino via the USB, see photo:

More details here: Interfacing LED displays with the MAX7219 driver

Sorry for the confusion. I did indeed mean that ISet was connected to the +5V pin on the arduino. I managed to get it going fine on a breadboard, I guess I must have shorted something when wiring/soldering my final board.
However, my circuit doesn't include the capacitors in the top left of your schematic (and indeed I don't see them in your photo). What purpose do they serve?

You are right, I didn't have them. However they are in the schematic as the standard recommended decoupling capacitors - read the link for more information. The larger one provides an "energy well" to cope with fluctuations in the supply voltage over the connecting wires, the smaller one smooths out sudden spikes in Vcc which might cause the digital logic to misbehave.


text:
How do I connect a temperature and heartbeat sensor to an Arduino Uno?
I have been using a temperature sensor and heartbeat sensor separately and I am trying to code for temperature and heartbeat sensors. How do I get its output on the Arduino IDE's Serial Plotter?
Code of temperature sensor:
int val;
int tempPin = 1;

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  val = analogRead(tempPin);
  float mv = ( val / 1024.0) * 5000;
  float cel = mv / 10;
  float farh = (cel * 9) / 5 + 32;

  Serial.print("TEMPRATURE = ");
  Serial.print(cel);
  Serial.print("*C");
  Serial.println();
  delay(1000);

  /* uncomment this to get temperature in farenhite
    Serial.print("TEMPRATURE = ");
    Serial.print(farh);
    Serial.print("*F");
    Serial.println();
  */
}

Please show us your entire sketch and tell us which sensors you are using.

How do I connect a temperature and heartbeat sensor to an Arduino Uno? Buturlin has the only correct answer here: you will have to read the datasheet for the temperature and heartbeat sensors to know how to work with them. that goes for any other sensors you may attach to your arduino. no exception. any answer not utilizing that piece of information is a wrong answer.

That doesn't answer the question.

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review

If you separate your code into functions you may understand what you want to do better.
In the listing above, you have code that reads the temp and prints the temp.  So creating two functions ReadTemp() and ShowTemp() will make the code in loop look cleaner and easier to read.  i.e.
void loop()
{
    const float cel = ReadTemp();
    DisplayTemp(cel);
    delay(1000);
}

float ReadTemp(void)
{
    val = analogRead(tempPin);
    float mv = ( val/1024.0)*5000;
    float cel = mv/10;
    // float farh = (cel*9)/5 + 32;
    return cel;
}
void ShowTemp(const float& cel)
{
    Serial.print("TEMPRATURE = ");
    Serial.print(cel);
    Serial.print("*C");
    Serial.println();
}

In you sketch for the hearbeat monitor you should have some code that reads the heartbeat and some that prints it.  If you create two functions ReadHB() and ShowHB() you will be able to easily add them to the above loop function.
I've never used the serial plotter, but if you wrap it in a function called PlotTemp() and PlotHB() then you can slot them in instead of the Show functions.


text:
Combing two codes to make it work on the same time but not affecting the other code?
I am trying to make a game where there are arrows going towards an object (in this case I printed x) and you have to evade the arrows. When you press the button it is supposed to print x on the top row and clear the bottom row with printing nothing and if you don't press the button its supposed to print x on the bottom row and nothing on the top. Then the for loop is supposed to print arrows randomly going from right to left.
Problem: When I actually run the code I only see the x every time the arrow hits the (0,1) or (0,0) position.
I want the x to be there all the time.
#include <LiquidCrystal.h>
// init the lcd display according to the circuit
LiquidCrystal lcd(12, 11, 6, 5, 4, 3);

String line2 = " x ";
int xPosition;
int yPosition;
int yConstant;

void setup()  {
  lcd.begin(16, 2);
  // put your setup code here, to run once:
  int switchState = 0;
  pinMode(7, INPUT);
  int leftjump = 0;
  pinMode(8, INPUT);
}

void loop() {
  ///////////////////////////////
  //supose tp print arrow randomly going from right to left
  xPosition = 15;
  yPosition = random(0, 10);
  if (yPosition > 5) {
    yConstant = 1;
  }
  else yConstant = 0;
  lcd.setCursor(xPosition, yConstant);
  for (int xPosition = 15; xPosition > 1; xPosition--) {
    lcd.print("<-");
    delay(100);
    lcd.clear();
    lcd.setCursor((xPosition), yConstant);
  }
  ////////////////////////////
  // suppose to print x on the top row and print nothing on buttom row
  //and otherwise when button is not pressed print x on bottom and
  //print nothing on top row
  int rightjump = 0;
  rightjump = digitalRead(7);
  if (rightjump == 1 ) {
    lcd.setCursor(0, 0);
    //delay(10);
    lcd.print(line2);
    //delay(200);
    lcd.setCursor(0, 1);
    lcd.print("  ");
  }
  else if ( rightjump == 0 ) {
    lcd.setCursor(0, 1);
    //delay(10);
    lcd.print(line2);
    //delay(200);
    lcd.setCursor(0, 0);
    lcd.print("  ");
  }
}

There is one big problem with your program, and it is here:

delay(100);

Using delay() is bad practice. The Arduino does nothing useful while
delaying. Quite importantly, it cannot respond to user input. And to
make matters worse, you have this delay inside a loop. This means your
program will be stuck inside the loop for 1.4 seconds. And during
this time it will not take care of reading the button, nor drawing the
player on the screen.
The solution is to use millis() to manage your timings, and never
block your program while waiting for something. The approach is well
explained in the Blink Without Delay Arduino tutorial. In a
nutshell: on every loop iteration, you check the clock and, if it's time
to do some particular task, you do it. If it's not time, well, you
simply don't do it. Most importantly: you don't wait. If you don't do
something on this loop iteration, no worries, you will do it on some
other iteration.
With this approach, there are some pieces of information (e.g. arrow
position) that will have to be remembered from one loop iteration to the
next. This can be done by storing that in global variables. I prefer to
to use static local variables though, to keep the information confined
to where it belongs.
Here is my try at your loop(). Notice that both the arrow and the
player are managed through the same pattern:
if (it needs to be updated right now) { update it; }
void loop() {
    static uint32_t last_arrow_move;  // last time the arrow moved
    static int arrow_x, arrow_y;
    const int player_x = 0;
    static int player_y;

    // Update the arrow position every 100 ms.
    if (millis() - last_arrow_move >= 100) {
        last_arrow_move += 100;

        // Erase the arrow at its old position.
        lcd.setCursor(arrow_x, arrow_y);
        lcd.print("  ");

        // Move one cell to the left.
        arrow_x--;

        // If too far left, then send a brand new arrow.
        if (arrow_x < 2) {
            arrow_x = 15;
            arrow_y = random(0, 2);
        }

        // Draw the arrow at its new position.
        lcd.setCursor(arrow_x, arrow_y);
        lcd.print("<-");
    }

    // Get the updated player position.
    int new_player_y;
    if (digitalRead(7) == HIGH) {  // "jump" button pressed
        new_player_y = 0;
    } else {
        new_player_y = 1;
    }

    // Update the player if he moved.
    if (new_player_y != player_y) {

        // Erase the player at its old position.
        lcd.setCursor(player_x, player_y);
        lcd.print(" ");

        // Move.
        player_y = new_player_y;

        // Redraw at the updated position.
        lcd.setCursor(player_x, player_y);
        lcd.print("x");
    }
}

You have a nested loop. When your for loop is finished moving the arrow to column 0 then, and only then, the " x " is displayed, exactly as predicted. You can start by drawing the x from inside the for loop (before the delay) that will make it visible all the time.
It's a start anyways.

Combing two codes to make it work on the same time but not effecting the other code?

the simplest would be to have two arduino and run each piece on one of them.

is there a way to it with one arduino because i need it on one lcd, the only problem is that i need the x to be there all the time.

technically, no. arduino has one execution unit so at any given point in time, it is either running code A, nothing else. for you to run both pieces on one arduino, you have to relax your constraints. no other way around that.

it runs on both but i just need the x to show all the time.

Is there a way to show the x all the time, without having it clear with the for loop.


text:
Connecting my Arduino with Bluetooth
What I want to do is to create a temperature measurement bracelet that you wear on your wrist.
So it takes data from the sensors and sends them to the PC.
What I am using to do that:

an Arduino Uno
a temperature sensor
a Bluetooth module to connect with Arduino Uno
a mobile phone
a PC

I will connect Arduino Uno with the Bluetooth module so it sends data to the mobile for example.
Since I am a beginner I do not have it very clear. Do I need a GPRS SIM (SIM900A for example or whatever) for this to function or just the Bluetooth connection is enough?
Specify that the question is very basic because I am a beginner.

You’d be better off with something like Adafruit’s Bluefruit Feather LE. It has a smaller foot print and a pre-programmed BLE chip on board that you interact with via UART & AT commands.

You should only need the Bluetooth module, not a Sim card.  The HC-05 and HC-06 are Bluetooth modules that are commonly used with Arduinos, are relatively inexpensive, are fairly small, and there's quite a bit of documentation out there on how to use them.

Ok. I agree but this module can be used in a arduino just to improvise. But to create the real bracalet wouldn't it be a little bit innaproporiate to integrate Bluetooth module in it?

It might be a little big for a bracelet, but it could work.  Some Arduino Nanos come with BLE built-in, but watch out for the one's that say they do but don't.  I bought 5 from China with the description saying it had BLE built-in, but I couldn't find how to enable it or the chip/antenna on the board.  The Nano or a smaller Arduino would work fine in a bracelet.  Some Smart watches are huge, so a large bracelet isn't necessarily a bad thing.

The idea is that Bluetooth  and SIM can be substitute of one another?

Yes and no.  Both can allow wireless communication, but in different ways.  With a sim card, you could cut out the phone entirely and connect to the PC more directly, but it's likely to cost you for the service.  It may also pull more power than the Bluetooth module, but I don't have any specific examples on that, as I haven't used a sim card.

But Bluetooth cannoct send data to laptop directly too? Without using mobile?

If your PC/laptop has a Bluetooth module, it can.  However, Bluetooth only has a range of about 30 ft., without extra gear to extend the range.  The likely device to usually be within range of your bracelet is your phone.  Granted, you can store your data on the bracelet until you get in range of your PC, which is what many off-the-shelf bracelets do.  A sim card wouldn't let you directly connect at all.  The sim card would basically give you access to the internet and allow you to post to a website, not your computer.

Assuming the mobile device to which you are connected by bluetooth is always kept near the bracelet, you don't need a GPRS module. The mobile device, then, would use it's network connection (either GPRS, LTE, WiFi, etc.) to communicate the data to the PC for processing or storage.


text:
how can i fix the error ? stk500v2_getsync(): timeout communicating with programmer
I bought this Chinese Arduino Mega 2560 16AU.
This was the first time to deal with Arduino boards. When I try to upload a sketch I always get this error:
stk500v2_getsync(): timeout communicating with programmer
I successfully burnt a bootloader to it using an Arduino uno,
but the same error is there.
Finally I discovered the the loop test is not working, and only the LX LED flashes once  when I enter a letter in the serial monitor.

It's our old friend the CH340G again, isn't it?
You've been sold a dud, I'm afraid. The USB chip used there is dead. It happens a lot with those cheap Chinese boards. You should still be able to use the board with an external FTDI adapter by wiring it in to TX->RX, RX->TX and DTR->RESET (via a 100nF capacitor) with power and ground connected of course.
There is also a slim chance that the CH340G may interfere with the TX/RX pins, in which case you may need to remove it. Simply cutting the pins on it with an xacto knife then removing the stumps with a soldering iron and tweezers would do the job.

If You Downloaded the driver it should be fine!
https://github.com/jimaobian/CH34x_Install_V1.3


text:
How to get HTTPS on Arduino?
Put plainly: is there a way to get an HTTPS connection on the Arduino?
I have been looking in to it, and I have found it is impossible with the standard library and the Ethernet shield, but is there a custom library that can do it?
What about a coprocessor, i.e. like the WiFi shield has? Anyone know if the Arduino yún has ssl?

you might be interested in this: http://stackoverflow.com/questions/15830333/arduino-due-https-support

The first question is "how can you get a connection with the Arduino?". If you use (eg) SIM800, it has HTTPS included.

MCUs mounted on Arduinos don't have the horse power to handle https connections.
Yún does handle https on the linux side, with software like curl, wget or python. Your sketch can just delegate the task to the linux side.
While curl works fine, despite having python preinstalled, you need to manually install python-openssl, since it's not available out of the box (due to disk space constraints)

When you say "Yún does handle https on the linux side" do you mean Arduino Yún or the Yún Shield ?

curl wget or python has nothing to do with https

(Disclaimer: I'm actually the author of the evothings.com article)
The Arduino UNO is more than capable at doing TLS. I've just finished up a blog post series on the topic. I have a working example of an Arduino UNO doing elliptic curve cryptography (sect163r2) to exchange an AES-128 key for continued communication.
http://ardiri.com/blog/utls_defining_lightweight_security_for_iot_part_1
...
http://ardiri.com/blog/utls_defining_lightweight_security_for_iot_part_8
I took an alternative approach to trying to make a true HTTPS connection - instead, this is using the same protocols under the hood but using an insecure communication channel to do so. Pretty much TLS on HTTP.

I list this as an answer for the sake of having it linked here. It is not full https yet but he is working on it and it may be doable in the future
http://evothings.com/is-it-possible-to-secure-micro-controllers-used-within-iot/
here is a benchmark he did encrypting a message using a 1024 bit public key
Arduino UNO       16Mhz AVR               ==> 12596 ms*   8504 ms#
Arduino Leonardo  16Mhz AVR               ==> 12682 ms*   8563 ms#
Arduino Mega      16Mhz AVR               ==> 12596 ms*   8504 ms#
Arduino Due       84Mhz ARM               ==>  1032 ms*
Arduino Yún       16Mhz AVR + 400Mhz MIPS ==>   707 ms*
Intel Galileo     400Mhz x86              ==>   192 ms*

This is as far as he has gone with it but is in the process of setting up a test server to work on seeing how close to a full ssl/https implementation he can pull off.

Could you please put the most interesting details from the link you posted so that readers can see right away if it is worth reading further or not? Otherwise your answer would not follow SE policies and would have to be closed.

I don't think it is possible due to the size and complexity of the SSL Library, because the Arduino would most likely be under powered. That being said you could make the requests to a regular server and use some sort of PHP script to proxy the request to the HTTPS server. Not sure how well it would work though.
You may be interested into looking at this.

Using of WiFi shield can be a solution - it supports HTTPS.
https://www.arduino.cc/en/Reference/WiFi101

As Federico Fissore says above, the Yún can only handle HTTPS (or SSL, whatever you want to call it) on the Linux side of the Yún.
The first way to do it is using Python with Python OpenSSL. The way you do this is by issuing the following commands via SSH or YunSerialTerminal:
opkg update
opkg install python-openssl

opkg update will make sure the package list is up-to-date, and then opkg install installs Python OpenSSL. And then you can talk to the Arduino using Python. This page on the Arduino website should help you in using Python with Arduino.
You could also use curl with the -k option in your sketch. For example:
Process process;
process.runShellCommand("curl -k http://example.net");
while(p.running()); // this waits for the command to be done before continuing

Also, if you want to download a file, you could use wget. This would require you to upgrade wget by again issuing these commands via SSH or YunSerialTerminal:
opkg update
opkg upgrade wget

And then you can just do this in your sketch:
Process process;
process.runShellCommand("wget http://example.net");
while(p.running()); // this waits for the command to be done before continuing

is it also possible using Arduino Yún Shield ? instead of Arduino Yún !


text:
Can a function be called automatically when an input changes?
Currently, my sketch is checking an input pin every time round the main loop. If it detects a change, it calls a custom function to respond to it. Here's the code (trimmed down to the essentials):
int pinValue = LOW;

void pinChanged()
{
    //...
}

void setup()
{
    pinMode(2, INPUT);
}

void loop()
{
    // Read current input
    int newValue = digitalRead(2);

    // Has the input changed?
    if (newValue != pinValue) {
        pinValue = newValue;
        pinChanged();
    }
}

Unfortunately, this doesn't always work properly for very short changes on the input (e.g. brief pulses), especially if loop() is running a bit slowly.
Is there a way to make the Arduino detect the input change and call my function automatically?

What you are looking for its a External Interrupt

You can do this using external interrupts. Most Arduinos only support this on a limited number of pins though. For full details, see the documentation on attachInterrupt().
Assuming you're using an Uno, you could do it like this:
void pinChanged()
{
    //...
}

void setup()
{
    pinMode(2, INPUT);
    attachInterrupt(0, pinChanged, CHANGE);
}

void loop()
{
}

This will call pinChanged() whenever a change is detected on external interrupt 0. On the Uno, that corresponds to GPIO pin 2. The external interrupt numbering is different on other boards, so it's important to check the relevant documentation.
There are limitations to this approach though. The custom pinChanged() function is being used as an Interrupt Service Routine (ISR). That means the rest of the code (everything in loop()) is temporarily stopped while the call is executing. In order to prevent disrupting any important timing, you should aim to make ISRs as fast as possible.
It's also important to note that no other interrupts will run during your ISR. That means anything relying on interrupts (such as the core delay() and millis() functions) may not work properly inside it.
Lastly, if your ISR needs to change any global variables in the sketch, they should usually be declared as volatile, e.g.:
volatile int someNumber;

That's important because it tells the compiler that the value could change unexpectedly, so it should be careful not to use any out-of-date copies/caches of it.

regarding the "brief pulses" mentioned in the question, is there a minimum time the pin must be at a state for it to trigger the interrupt? (obviously it'll be much less than polling, which depends on what else is happening in the loop)

@sachleen That will work as long as it does not happen during the execution of an ISR function (as explained in the answer); that's why pinChanged() should be as short as possible. Hence typically the minimum time should be the time to execute the pinChanged() function itself.

+1 for this very detailed answer which includes all imortant stuff one must care about when using interrupts!

In addition to declaring shared globals volatile, if the global variable is wider than 1 byte, as someNumber is, you must protect against the pin-change interrupt occurring between byte accesses by the program. A statement like someNumber +=5; involves adding the low bytes and adding the high bytes with carry included. These two (more, for wider variables) must not be divided by an interrupt. Turning the interrupts off and restoring them before and after the operation (respectively) is sufficient.

@sachleen - regarding the minimum pulse size. It is hard to find a definite answer in the datasheet, but judging by the timing for pin-change interrupts, they are latched within half a clock cycle. Once the interrupt is "remembered" it stays remembered until the ISR kicks in and deals with it.

Any state of change on any pin configured as digital input can create an interrupt. Unlike the unique vectors for the interrupts causes by INT1 or INT2 the PinChangeInt feature uses a common vector and then Interrupt Service Routine (aka ISR) for this vector needs to then determine which pin changed.
Fortunately PinChangeInt Library makes this easy.
PCintPort::attachInterrupt(PIN, burpcount,RISING); // attach a PinChange Interrupt to our pin on the rising edge
// (RISING, FALLING and CHANGE all work with this library)
// and execute the function burpcount when that pin changes

In the event that you want to detect a voltage passing a threshold, rather than being merely HIGH or LOW, you can use the analog comparator. Example sketch:
volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop

This can be useful for things like light-detectors, where you might need to detect a change from (say) 1V to 2V on an input.
Example circuit:

You can also use the Input Capture Unit on the processor, which will remember the exact time of certain inputs, by saving the current count of Timer/Counter 1. This lets you store the exact (well, almost exact) moment that the event of interest occurred, rather than introducing the delay (of probably a few microseconds) before an ISR can be used to capture the current time.
For timing-critical applications, this can give somewhat increased accuracy.
Example application: Turn your Arduino into a capacitor tester