text:
NodeMCU ESP-12e - Timing errors
I'm using the ESP-12e with Arduino IDE. With that I'm trying to build a clock with a WS2812B LED strip matrix that I've build.
When I try to display the seconds on my matrix there are strange timing problems. It shows me the numbers how I should, the LEDs work OK but ..it misses seconds spontaneously. sometime it jumps the numbers like 00 01 03 06, sometimes 00 02 03 05.. sometimes it hangs at one number for a short time.

Is the problem in my code?
Or is it due to hardware limitations of the ESP-12e?
How can I do it better?

Here is my sketch (I removed some number definitions [...] for better overview):
#include <ESP8266WiFi.h> //WiFi
#include <Adafruit_NeoPixel.h> //LEDs
#include <TimeLib.h> //Time
#include <WiFiUdp.h> //Synchronize Time

const char* ssid = "XXXXX";
const char* password = "XXXXXXX";

WiFiClient wifiClient;

//NTP Servers
  static const char ntpServerName[] = "us.pool.ntp.org";
  const int timeZone = 1; // Central European Time
  WiFiUDP Udp;
  unsigned int localPort = 8888;  // local port to listen for UDP packets
  time_t getNtpTime();
  void digitalClockDisplay();
  void printDigits(int digits);
  void sendNTPpacket(IPAddress &address);

  // Setup Wifi
void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

/*-------- NTP code ----------*/
// ====================================

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{
  IPAddress ntpServerIP; // NTP server's ip address

  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  // get a random server from the pool
  WiFi.hostByName(ntpServerName, ntpServerIP);
  Serial.print(ntpServerName);
  Serial.print(": ");
  Serial.println(ntpServerIP);
  sendNTPpacket(ntpServerIP);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12] = 49;
  packetBuffer[13] = 0x4E;
  packetBuffer[14] = 49;
  packetBuffer[15] = 52;
  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}

// NEO PIXELS
// ====================================

// Setup
#define PIN 0
#define NUMPIXELS 224

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int individualPixels[NUMPIXELS];

// Time variables
int hs;
int m;
int s;

// For Loops
int x;

// RGB color variables
int red;
int green;
int blue;

void colorBlue(){
  red = 0;
  green = 0;
  blue = 100;
}

/* IN LOOP Light pixels corresponding to current time */
void neoPixler(){
  for (x=0; x<sizeof(individualPixels); x++){
    if (individualPixels[x]==1){
      pixels.setPixelColor(x, pixels.Color(red,green,blue)); //Set Neopixel color
    }
    else{
      pixels.setPixelColor(x,pixels.Color(0,0,0));
    }
  }
  pixels.show(); //Display Neopixel color
}

// ALL OFF
void turnOff(){
  for(x=0; x<pixels.numPixels(); x++) {
    individualPixels[x]=0;
    pixels.show();
  }
}

//Numbers
void dl_one(){
  individualPixels[160]=1;
  individualPixels[161]=1;
  individualPixels[146]=1;
  individualPixels[147]=1;
  individualPixels[116]=1;
  individualPixels[117]=1;
  individualPixels[102]=1;
  individualPixels[103]=1;
  individualPixels[72]=1;
  individualPixels[73]=1;
  individualPixels[58]=1;
  individualPixels[59]=1;
  individualPixels[28]=1;
  individualPixels[29]=1;
  individualPixels[148]=1;
  individualPixels[149]=1;
  individualPixels[112]=1;
  individualPixels[113]=1;
}
void dr_one(){
  individualPixels[172]=1;
  individualPixels[173]=1;
  individualPixels[134]=1;
  individualPixels[135]=1;
  individualPixels[128]=1;
  individualPixels[129]=1;
  individualPixels[90]=1;
  individualPixels[91]=1;
  individualPixels[84]=1;
  individualPixels[85]=1;
  individualPixels[46]=1;
  individualPixels[47]=1;
  individualPixels[40]=1;
  individualPixels[41]=1;
  individualPixels[136]=1;
  individualPixels[137]=1;
  individualPixels[124]=1;
  individualPixels[125]=1;
}
void dl_two(){
  individualPixels[152]=1;
  individualPixels[153]=1;
  individualPixels[156]=1;
  individualPixels[157]=1;
  individualPixels[158]=1;
  individualPixels[159]=1;
  individualPixels[160]=1;
  individualPixels[161]=1;
  individualPixels[144]=1;
  individualPixels[145]=1;
  individualPixels[118]=1;
  individualPixels[119]=1;
  individualPixels[104]=1;
  individualPixels[105]=1;
  individualPixels[102]=1;
  individualPixels[103]=1;
  individualPixels[68]=1;
  individualPixels[69]=1;
  individualPixels[64]=1;
  individualPixels[65]=1;
  individualPixels[22]=1;
  individualPixels[23]=1;
  individualPixels[24]=1;
  individualPixels[25]=1;
  individualPixels[26]=1;
  individualPixels[27]=1;
  individualPixels[28]=1;
  individualPixels[29]=1;
  individualPixels[30]=1;
  individualPixels[31]=1;
}
void dr_two(){
  individualPixels[34]=1;
  individualPixels[35]=1;
  individualPixels[36]=1;
  individualPixels[37]=1;
  individualPixels[38]=1;
  individualPixels[39]=1;
  individualPixels[40]=1;
  individualPixels[41]=1;
  individualPixels[42]=1;
  individualPixels[43]=1;
  individualPixels[52]=1;
  individualPixels[53]=1;
  individualPixels[80]=1;
  individualPixels[81]=1;
  individualPixels[92]=1;
  individualPixels[93]=1;
  individualPixels[90]=1;
  individualPixels[91]=1;
  individualPixels[132]=1;
  individualPixels[133]=1;
  individualPixels[130]=1;
  individualPixels[131]=1;
  individualPixels[168]=1;
  individualPixels[169]=1;
  individualPixels[170]=1;
  individualPixels[171]=1;
  individualPixels[172]=1;
  individualPixels[173]=1;
  individualPixels[140]=1;
  individualPixels[141]=1;
}

[......]

// Seconds
// ====================================
void print_numbers(byte num){
  byte num10;
  byte num1;
  num1=num%10;
  num10=(num-num1)/10;
  switch (num10){     //10...
  case 0:
    dl_null();
    break;
  case 1:
    dl_one();
    break;
  case 2:
    dl_two();
    break;
  case 3:
    dl_three();
    break;
  case 4:
    dl_four();
    break;
  case 5:
    dl_five();
    break;
  }
  switch (num1){      //1...
  case 0:
    dr_null();
    break;
  case 1:
    dr_one();
    break;
  case 2:
    dr_two();
    break;
  case 3:
    dr_three();
    break;
  case 4:
    dr_four();
    break;
  case 5:
    dr_five();
    break;
  case 6:
    dr_six();
    break;
  case 7:
    dr_seven();
    break;
  case 8:
    dr_eight();
    break;
  case 9:
    dr_nine();
    break;
  }

}
void seconds(){
/* Get current time */
s=second();
turnOff();
print_numbers(s);
neoPixler();      // Lights
}

void setup() {

  // Debug info
  Serial.begin(115200);
  Serial.println(F("Booting"));

  setup_wifi();

  // Setup UDP Time + Sync Time
  Serial.println("Starting UDP");
  Udp.begin(localPort);
  Serial.print("Local port: ");
  Serial.println(Udp.localPort());
  Serial.println("waiting for sync");
  setSyncProvider(getNtpTime);
  setSyncInterval(3000);

/* NEO PIXELS ------------------------------------------------------------------------------------------------------*/
  colorBlue(); //Standard Color
  pixels.begin(); //Begin Neopixel string
  pixels.show(); // Initialize all pixels to 'off'
}

void loop() {
  seconds();
}

It's likely the problems are in your code somewhere; but not enough information is available to say for sure.

Your first step toward debugging the problem probably should be taking any ESP-12e issues out of the mix.  At the beginning of getNtpTime() temporarily add something like return 1477897101UL + millis()/1000; to get a sync-time that advances at the correct rate and is repeatable for testing.  If the display suddenly begins updating smoothly, look for problems in your time code, else in the display code.

The technique of duplicating a whole bunch of individualPixels[116]=1; lines (with different pixel numbers) is crude, tedious, verbose, error-prone, inflexible, etc.  You might instead create some arrays and use a loop to set pixel data.  For example:
const byte L1[] = {160, 161, 146, 147, 116, 117, 102, 103, 72, 73, 58, 59, 28, 29, 148,
  149, 112, 113, 0};
...
const byte R2[] = {34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 52, 53, 80, 81, 92, 93, 90,
  91, 132, 133, 130, 131, 168, 169, 170, 171, 172, 173, 140, 141, 0};

void loadDigit(byte *pixelList) {
  for (byte j=0; pixelList[j]; ++j)
    individualPixels[pixelList[j]] = 1;
}
...
   loadDigit(L1);  // Write a left 1
...
   loadDigit(R2);  // Write a right 2

You could also create an array of addresses of number-data arrays, to get rid of the crude, tedious (etc.) switch/case statements in print_numbers().  For example:
const byte *digitsL[] = {L0, L1, L2, L3, L4, L5, L6, L7, L8, L9};
const byte *digitsR[] = {R0, R1, R2, R3, R4, R5, R6, R7, R8, R9};
...
if (num>9)
  loadDigit(digitsL[num/10]);  // Write tens digit
loadDigit(digitsR[num%10]);    // Write units digit

If your matrix is logically organized, all of the 1's in R0 are at constant offsets from the 1's in L0 (for example, 12 more), and similarly for other digits.  If that's the case, you could modify loadDigit() to take a second parameter, offset, which indicates where to place the digit in the matrix, ie, tells loadDigit() how much to add via a statement like individualPixels[offset+pixelList[j]] = 1;.  Then you could leave out the R0 ... R9 arrays (and digitsR[] as well) and use code like the following:
...
if (num>9)
  loadDigit(digitsL[num/10], 0);  // Write tens digit at left
loadDigit(digitsL[num%10], 12);   // Write units digit at right

A drawback to using const byte arrays like L0 ... L9 and R0 ... R9 is that when your program starts they get copied from PROGMEM into RAM for access.  It would make sense to declare them in PROGMEM, and use them directly from PROGMEM by appropriate changes.  [Edit: See example program, below]

Note, a string of 224 WS2812B units takes about 6.7 ms to update:  224 units x 24 bits x 1.25 μs/bit.  Each time you update your matrix of lights, the millis() counter, timer0_millis, will lose 5 or 6 ms because pixels.show() runs with interrupts turned off.  To compensate, you could add 5 to timer0_millis after each update.  To make the loss always be 5 ms instead of sometimes 5 and sometimes 6, add the following code just before pixels.show():  unsigned long now=millis(); while (now==millis());, which will stall until the end of the current millisecond.  To see how to change timer0_millis, see the  “Better Alternative” section of my answer to “How to keep accurate millis() while using ADC_sleep mode?”.

I'd remove the pixels.show() call from turnOff() because you will (I think) always be calling pixels.show() shortly after that, after loading number images, to turn on a bunch of other pixels.  That is, clear the array, fill the necessary 1's, then show, without a show between clearing and filling.

Following is an example program that illustrates storing a constant array of bytes in PROGMEM, and accessing its entries via pgm_read_byte() calls.
// Sketch that accepts a number k via serial input, and responds with
// the k-th set of numbers from among some sets of numbers stored in
// PROGMEM.  This avoids copying the array data into RAM.  jiw 31 Oct 2016

#include <Streaming.h>  // Ref: http://arduiniana.org/libraries/streaming/

// Set up datatext in PROGMEM
const byte L1[] PROGMEM = { 102, 103, 112, 113, 116, 117, 146, 147, 148,
                149, 160, 161, 28, 29, 58, 59, 72, 73, 0};

const byte R1[] PROGMEM = { 124, 125, 128, 129, 134, 135, 136, 137, 172,
                173, 40, 41, 46, 47, 84, 85, 90, 91, 0};

const byte L2[] PROGMEM = { 152, 153, 156, 157, 158, 159, 160, 161, 144,
                145, 118, 119, 104, 105, 102, 103, 68, 69, 64,
                65, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 0};

const byte R2[] PROGMEM = { 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 52,
                53, 80, 81, 92, 93, 90, 91, 132, 133, 130,
                131, 168, 169, 170, 171, 172, 173, 140, 141, 0};
const  void* Addrs[] = { L1, R1, L2, R2 };
enum { nAddrs = sizeof Addrs / sizeof Addrs[0] };

void prompt() {
  Serial << endl << "Please enter item number from 1 to " << _DEC(nAddrs) << ": ";
}

void setup() {
  Serial.begin(115200);         // init serial port
  prompt();         // Issue initial prompt
}

void loop() {
  char c, d;
  while (Serial.available()) { // Get characters
    c = Serial.read();
    if (c >= '0' && c <= '9') {
      Serial << c << endl;  // Echo the entered digit
      d = c - '0' - 1;
      if (d>=0 && d < nAddrs) {
        byte k=0, t = pgm_read_byte(Addrs[d]);
        Serial << "Set #" << _DEC(d+1) << ": ";
        while (t) {
          Serial << _HEX(t) << ' ';
          t = pgm_read_byte(++k + Addrs[d]);
        }
        Serial << endl;
      }
      prompt();         // Issue prompt after any digit
    }
  }
}

Thank you very much for your extensive answer. You just fixed my problems. "pixels.show():  unsigned long now=millis(); while (now==millis());" did the thing. Also thanks for the suggentions regarding the pixel definitions

with "const byte L1[] = (160, 161, 146, 147, 116, 117, 102, 103, 72, 73, 58, 59, 28, 29, 148,
149, 112, 113, 0);" I get "initializer fails to determine size of "L1". I also don't really get the PROGMEM thing.

@proto, those (...) initializers should have been  {...}.  (Now corrected in answer.)  See example program now at end of answer for use of pgm_read_byte() to get data from a PROGMEM array.  It ran ok on a Nano. Note, feel free to upvote answer

upvoted already but because I have under 15 rep it isn't viewed in public ;)

NTP is a protocol implemented over UDP which is a connectionless protocol.  If packets are lost then neither the client nor the server will be aware of their loss.  So on top of everything else that might be wrong your data source may also be injecting additional errors.  You should take the time from a timer on the board and update it from NTP when you receive data.

That's what TimeLib.h does.  It syncs at intervals, and the setSyncInterval(3000) statement sets the interval to 3000 seconds, or 50 minutes.  The default sync interval is 5 minutes.  Between syncs, TimeLib depends on millis().

When I'm trying it like this I get the error:
invalid conversion from 'const byte* {aka const unsigned char*}' to 'byte* {aka unsigned char*}' [-fpermissive]

    #include <ESP8266WiFi.h> //WiFi
    #include <Adafruit_NeoPixel.h> //LEDs

    // 1
    const byte L1[] = {160, 161, 146, 147, 116, 117, 102, 103, 72, 73, 58, 59, 28, 29, 148,  149, 112, 113, 0};
    const byte R1[] = {172, 173, 134, 135, 128, 129, 90, 91, 84, 85, 46, 47, 40, 41, 136, 137, 124, 125, 0};
...
    const byte *digitsL[] = {L0, L1, L2, L3, L4, L5, L6, L7, L8, L9};
    const byte *digitsR[] = {R0, R1, R2, R3, R4, R5, R6, R7, R8, R9};

    void loadDigit(byte *pixelList) {
      for (byte j=0; pixelList[j]; ++j)
        individualPixels[pixelList[j]] = 1;
    }

    void print_numbers(byte num){
      if (num>9){
        loadDigit(digitsL[num/10]); // Write tens digit
      }
      else {
      loadDigit(digitsR[num%10]);  // Write units digit
      }
    }

    void seconds(){
    turnOff();
    print_numbers(byte second());
    //print_numbers(second());
    neoPixler();
    }

EDIT:
It works when I add "const" to the loadDigit
    //0
    const byte L0[] = {156, 157, 158, 159, 160, 161, 152, 153, 110, 111, 108, 109, 66, 67, 64, 65, 144, 145, 118, 119, 100, 101, 74, 75, 56, 57, 24, 25, 26, 27, 28, 29, 0};
    const byte R0[] = {168, 169, 170, 171, 172, 173, 140, 141, 122, 123, 96, 97, 78, 79, 52, 53, 132, 133, 130, 131, 88, 89, 86, 87, 44, 45, 36, 37, 38, 39, 40, 41, 0};
    //1
    const byte L1[] = {160, 161, 146, 147, 116, 117, 102, 103, 72, 73, 58, 59, 28, 29, 148,  149, 112, 113, 0};
    const byte R1[] = {172, 173, 134, 135, 128, 129, 90, 91, 84, 85, 46, 47, 40, 41, 136, 137, 124, 125, 0};

  void loadDigit(const byte *pixelList) {
      for (byte j=0; pixelList[j]; ++j)
        individualPixels[pixelList[j]] = 1;
    }
    void print_numbers(byte num){
      if (num>9){
        loadDigit(digitsL[num/10]);
        loadDigit(digitsR[num%10]);
        }
      else {
        loadDigit(digitsR[num%10]);
      }
    }
    void seconds(){
      s=second();
      turnOff();
      print_numbers(s);
      neoPixler();
    }


text:
Sim800L's library can not compile on Arduino Due
Sim800L's library can not compile on Arduino Due. Is there any way to create a library for Arduino Due?
#include <Sim800l.h>
#include <SoftwareSerial.h>

Sim800l Sim800l;
char* text;
char* number;
bool error;

void setup(){
    Sim800l.begin();
    text = "Testing Sms";
    number = "2926451386";
    error = Sim800l.sendSms(number,text);
    // OR
    //Sim800l.sendSms("+540111111111","the text go here")
}

void loop(){
    //do nothing
}

I guess that the problem is the software serial library, too. However, I don't know how to replace this library for Arduino Due.
Any help appreciated.

Without the error it is not possible to tell you what is happening.  It like walking to a mechanic and saying your car doesn't work.  Without the car or a description of the problem he isn't going to have a scoobies.
SO  Whats the exact error message you see.

You should probably rework thinks to use one of the Due's other hardware UARTs.  If you find a generic demo for using the port (or look at the Due docs) that should be simple, and if you get the Sim800l library in question in editable form and take time to understand it you should be able to make the changes.  But you are going to need to do the work yourself, or else spend some time doing your own web searches to see if someone already has.

Error massage: Error compiling for board Arduino Due (Programming port)

First we must delete the SoftwareSerial and SIM800L libraries, then define Sim800l and assign it to Serial 3 on pins 14 and 15. In setup, call Sim800l.begin() and the rest of the code is unchanged.
#define SIM800l Serial3

void setup () {
  Serial.begin (9600);
  SIM800l.begin (9600);
  while(!Serial);
  SIM800l.write ("AT+CMGF=1\r\n");
  delay (1000);
  SIM800l.write("AT+CMGS=\"5432154552"\"\r\n");
  delay(1000);
  Serial.println("send SMS");
  SIM800l.write ("test send SMS");
  delay (1000);
  SIM800l.write ((char)26);
  delay(1000);
}

void loop (){}

source: Stack Exchange

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

sort: votes


text:
use button to select variable
i have a need to use 3 buttons a a simple option/variable selector at sketch start up ...
Pretty much at startup , script must wait for button press ( one of 3 ) , when button is pressed , use that buttons predefined string value as a variable for the loop script further down .. if wanting to change the "variable" then a reboot is required ..
i know how to digital read in the buttons , but not sure how to
1) wait for one of the buttons to be pressed to then jump to main loop
2) Associate a "string" variable to each button
thinking about it i suppose a If/Else loop will be required for the Input 'wait" and then just if the digital input (button) is pushed then continue .. am i correct ?
Ideas or better way to do it ?
Thx
Greg

1) One solution is to create a function that loops repeatedly, eg while(1), until one of the buttons is pressed. It then returns the button "number", eg 0,1 or 2.
2) In C you would usually remember the index into a string table. So one solution is to store the button number in a global variable and use it to index a "string array", something like char * buttonStrings["B1","B2","B3"]; and to get the string for a button use buttonStrings[buttonNumber];

When I am searching for something inside a loop, I find that the
simplest thing to do is to just break out of the loop once I found it.
This was frowned upon in the days when structured programming was a hot
thing, but as long as it makes things simpler, you should not be ashamed
to break:
const int button_pins[] = {2, 3, 4};
const char * const urls[] = {"foo.com", "bar.org", "baz.net"};
const char * url;  // the selected URL

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

    // Configure input pins.
    for (int i = 0; i < 3; i++)
        pinMode(button_pins[i], INPUT_PULLUP);

    // Find first button pressed.
    int i;  // button index
    for (i = 0; ; i = i==2 ? 0 : i+1) {
        if (digitalRead(button_pins[i]) == LOW)
            break;
    }

    // The button index selects the URL.
    url = urls[i];

    Serial.print("Selected URL: ");
    Serial.println(url);
}

void loop() {}

The for loop above is written as an endless loop (no end condition).
The expression i = i==2 ? 0 : i+1 means: “if i is 2, make it 0,
otherwise make it i+1”. In other words, we are endlessly looping i
over 0, 1 and 2.
Now, it may well happen that you actually do not care about which button
was pressed once you have selected the proper URL. In this case, you can
use the URL pointer as a “flag” that tells you when you can end the
loop:
// First button pressed selects the URL.
for (int i = 0; !url; i = i==2 ? 0 : i+1) {
    if (digitalRead(button_pins[i]) == LOW)
        url = urls[i];
}

Where !url means “the URL has not been found”. This works because the
C runtime initializes url to zero, which is interpreted as false in
boolean context.
Addendum: If you are likely to add new button/URL pairs, you can
make this easier by structuring the list as an array of structs:
const struct {
    int pin;          // pin number
    const char *url;  // associated URL
} buttons[] = {
    {2, "foo.com"},
    {3, "bar.org"},
    {4, "baz.net"}
    // etc. just add to this list as needed.
};
const size_t button_count = sizeof buttons / sizeof buttons[0];

Then the search becomes:
for (int i = 0; !url; i = i==button_count-1 ? 0 : i+1) {
    if (digitalRead(buttons[i].pin) == LOW)
        url = buttons[i].url;
}

You can try this. The comments in the program explain quite well.
const int buttons[3] = {2,3,4}; // buttons pins

int butStatus = 0;

void setup() {
  pinMode(buttons[0], INPUT); // declaring pins as inputs
  pinMode(buttons[1], INPUT);
  pinMode(buttons[2], INPUT);

  while(butStatus<=0) //waiting for a button to be pressed
  {
    for(int i=0; i<3; i++) //running trough the 3 buttons
    {
      if(digitalRead(buttons[i]) == HIGH)
      {
        butStatus = i+1; //set variable to the button that has been turned on
      }

      else
      {
        butStatus = 0; //if there is no button press, keep the variable at 0
      }
    }
  }
}

void loop() {
  //variable butStatus is now equal to the button that has been pressed
}

Thanks , this looks good .. one question , for the variable .. i require the variables to be URL strings  (example www.google.com) , how can i map this ?? so something like button 1 = www.google.com , button 2 - www.yahoo.com , button 3 = somesite.com

use string urls[3] = {"www.google.com", "www.yahoo.com","www.somesite.com"}. Then you can call string something = urls[butStatus];.

perfect :-) let me go play :-)

Better make that string something = urls[butStatus-1]; butStatus is 0 for no button or 1-3 for a button pressed, you need to subtract one to get back to a zero based array index.

Your code can only sense the last button.

@EdgarBonet, mind explaining a bit...

If button 2 is not pressed, you butStatus = 0; and stay in the loop.

Did you see this? butStatus = i+1

canadiancyborg,  @EdgarBonet is correct: in your code as shown, the only way the while(butStatus<=0) loop can exit is if the third button is pressed, regardless of the state of the other two buttons. Get rid of the silly-error code else { butStatus = 0; }.  Also, in string urls[3] ... perhaps you meant to capitalize string

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


text:
Which interrupts are enabled when programming an ATTiny85 with Arduino IDE?
I have programmed a tiny85 using the Arduino IDE. I am using the pulseIn() function. Wrapping it in noInterrupts()/interrupts(); appears to make the function more consistent. This would imply that interrupts are running.
Which interrupts are running? Can I disable them?
I am using the analogWrite() function to pins that have PWM support. Disabling the interrupts for a "long" time does not seam to effect these, this implies the PWMs are producing the analogue signal in hardware and so interrupts are not required.
(I know I can improve the code by not using pulseIn and using interrupts, however the question I have at the moment is which interrupts are running when I am not explicitly enabling any.)

It could depend on the arduino core you're using for the ATTiny. As there are multiple, and there is not one present in the default IDE (afaik).

The only interrupt that is always running is the one which generates the count for millis() and micros(). Disabling interrupts disables your ability to keep track of time and use delay().
Timer interrupts are also used by the tone() function and for sending / receiving serial data if the chip has a UART.
Disabling interrupts would also affect the use of external interrupts and pin change interrupts should you be using them.
It sounds, from your brief description, that you would only be effecting the use of millis() and delay() since you aren't using the other systems that use interrupts at all.

After more reading it states that the pulseIn() requires interrupts, this is a bit strange. I would not expect to see an "improvement" doing what I am doing. Perhaps the tiny85 implementation is different than the standard one. If timing is available I would expect pulseIn to use it, as the description implies, and therefore require interrupts to be enabled. What you describe makes a lot of sense, I will recheck my findings.

pulseIn() function has got a very high accuracy, to the level of us (microseconds), which millis() function has obviously not. This is why pulseIn does not use it. Note that even micros() does not offer high precision, despite its name.

Which interrupts are running?

It depends on your code which you haven't shown. The Timer 0 overflow interrupt is usually active, as that lets the library count when a millisecond is up (roughly).
If you have done a Serial.begin then serial interrupts would be active. If you have used the I2C library (Wire) then I2C interrupts would be active.
(Disclaimer: That really refers to the Atmega328P. I'm not quite so sure on the ATtiny, it would depend on what the libraries do).

Can I disable them?

If you want to. Doing noInterrupts() is the simplest way. Note that if you disable interrupts for more than a millisecond (approximately) then the time returned by millis and micros will be wrong. Plus delay won't work. Plus you won't be able to serial print properly or at all.

I am using the analogWrite() function to pins that have PWM support. Disabling the interrupts for a "long" time does not seam to effect these, this implies the PWMs are producing the analogue signal in hardware and so interrupts are not required.

That is exactly what it does. Once activated the hardware timers can generate a PWM signal purely in hardware.

There are other ways of timing intervals (than pulseIn). One method is to use one of the other timers, configured with a small, or no prescaler. Then you can measure up to very high accuracy. I have examples of that on my page about timers.
(The ATtiny85 only has two timers, so you couldn't use the second timer for measuring and do PWM output with it, however you can use Timer 0 for the PWM output). That limits the PWM frequency to its default, however you could still alter the duty cycle)


text:
How to ground a arduino with an external power-source?
I have magnet hooked up to my arduino with a Darlington Transistor, like this:

The powersource is a 12V adapter
I'm pretty new to electronics but i'm told that the transistor won't work unless the ground on the arduino is the same as the ground on the external source. How do I do this in practice? Should I run a wire from the ardunio-ground to the negative pole on the powersource? How do I tell which one is the negative one?

Your first question about this subject is from Aug 2016. You really need start with a Electricity 101 course for your own safety.

Ground is usually (though not always, but in your case it is) the point of lowest potential in a circuit. In your circuit that is the "negative" connection of the power supply. Note that the "negative" isn't actually "negative", it is zero volts when measured from the reference point of itself.
So yes, you need to know which is the "negative" connection and connect that to ground on the Arduino.
Since you already have it wired up the negative is the one which connects to the emitter of your transistor. If you don't know which that is and you just randomly connected a random wire to a random pin then you need to investigate your power supply.
The simplest way is with a Digital MultiMeter (one of the most basic items you need to own if you are working with electronics - if you don't have one then go and buy one immediately). Set it to DC Volts in the right range then connect the two probes (correctly inserted into the right sockets on the DMM) to the power supply's output connections. If the voltage reads positive then the black probe is connected to negative. If it reads a negative value then the red probe is connected to negative.
If you cannot get a DMM but you have an LED (note: a bulb will not work) and a suitable resistor (say 2.2K) you can connect the resistor in series with the LED then connect the two to the power supply. The cathode of the LED (the pin with the flat side on the case) connects to negative. Connect the power both ways round. The way round that it lights the LED is the correct way round, and you know that the connection that goes to the cathode (flat side of the lip round the bottom of the LED) is the negative.

“Since you already have it wired up the negative is the one which connects to the emitter of your transistor”  – What's that mean?  Anyhow, for a grounded-emitter low-side switch, either the battery or the transistor in the diagram in the question is backwards, an issue you might address with a correct diagram in your answer.

Majenko explained how to figure out what is what. I'm just repeating the shematics again with "additional" description:

Current limiting resistor R1 is REQUIRED, if you don't want to destroy Arduino output by over current.
About using the LED to test your power source polarity:

And again, current limiting resistor is required, or you'll burn it. As Majenko stated, it should be about 2k2.

I would be careful about "ground loops" when using two supplies connected to the mains electricity. You may get strange results. If you are using a lap top then maybe disconnect it from the charger while the PSU is plugged in the wall. Or use a battery for your coil. Or power the Arduino from a power bank. Or get a 12v USB adaptor and power the arduino from the 12v supply. Add and LED for debugging while connected to the computer. Then disconnect from the computer and plug in the 12v supply.

very useful info!


text:
How to program an nRFL01 RF module that is connected to a pc via a USB to UART/TTL adapter?
In a few of my previous questions I was told that the nRF24L01 RF Module can be connected to a pc using a USB to UART/TTL adapter. After a bit of research I understand that one way to use it is to connect it to an arduino- and then to use certain dedicated libraries like RF24.h, and nRF24L01.h to send and receive data. Though I've not been able to find any tutorial outlining the procedure for programming the nRF24L01 once its been connected to the pc.
  How do I send and receive data using my pc-interface? What software do I write and how do I write it?

No, it needs a USB to SPI interface, not USB to UART interface. That's the FT2232 not the FT232 (confusing I know).

@Majenko - actually, I believe you can do SPI with the FT232H and possibly even very slowly the everyday FT232RL.  But you are right that this is not UART functionality but a different operating mode and its corresponding host side API, and also the FT2232H/FT44232H are much better at it.

In short: whatever software you use on the remote end (rf24.h for example) you have to re-write on the PC using whatever language you can interface to the FT2232 with. That means having intimate knowledge of:

The USB to SPI adapter you choose (NOT USB TO UART!)
The low-level control and interfacing of the nRF24L01+ chip
The exact protocol used by your chosen Arduino library.

That's a lot of understanding which (by the level of your questions) is most likely way outside your area of ability.
If you equate time to money then the cost of doing what you want to do is far higher than just using a small Arduino to act as an intelligent interface between your PC and your chosen wireless system. You can discount points 2 and 3 above since they have already been done for you by the Arduino libraries and tutorials. Point 1 becomes considerably easier since you are then just talking to an Arduino using a protocol which you yourself have come up with.
So do yourself (and us) a favour and come to your senses and just plug the nRF24L01+ into an Arduino then plug the Arduino into your PC and program the Arduino to do the RF communications according to commands and instructions you send to your sketch from the PC.


text:
save bytes from Serial into ROM (EEPROM)
I am trying to save an incoming text from serial into the ROM of the Arduino using EEPROM. I found out that you can only save a byte at once. So I thought I could do it like that:

#include <EEPROM.h>

byte c;
int i; // counter for addressing EEPROM

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

void loop(){
  if(Serial.available()){ // check if there is some input form Serial
    while(Serial.available()){ // loops through every character of the Serial input
      c = Serial.read(); // saves current character into variable c in byte form
      EEPROM.write(i, c); // saves c into rom with the address i (counts up after each character)
      i++; // counts c up
    }

    // after all characters are looped through and saved into EEPROM
    Serial.println(i); // print the amount loop runs / amount of characters that are saved
    Serial.println(EEPROM.read(0)); // prints the first character of the input that got saved into EEPROM
    Serial.println("--"); // print cut for overview
    i = 0; // resets counter to 0. That way all values are goint to be overwritten if you type something new into the serial monitor
  }
}

Unfortunately that is not working at all. So what did I do wrong?

Are you sure that you don't want to read back and print the byte you wrote with EEPROM.read(i); and not always read from address 0 with  EEPROM.read(0); as you have implemented the code?

Your code makes no sense whatsoever. You should start by learning how to read serial into an array (https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/) and then copy that resultant array byte-by-byte into the EEPROM.

it does make sense. I will command it. One moment

i is used prior to being initialized.2) It assumes that all the data to be written has arrived and is sitting in the serial buffer already. Serial is slow so the chances are that it'll only get 1 byte each time it runs through that while(serial.avalible()) loop. You're only ever going to write to address 0 (other than the first byte which will go to an undefined random location)

so how would you do something like this?

How about using the EEPROMex library. I find it very useful. Can even save a whole class/struct which can be easier to expand http://playground.arduino.cc/Code/EEPROMex. Your serial should read into a large enough array or struct member, such as char[20]. Then use EEPROMex to get or save the whole thing for you.

Thank you Visual Micro. That tip helps me a lot. I guess that is the solution :)

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


text:
Maplin Bluetooth Shield for Arduino - BAUD rate
I am currently using a Bluetooth shield which i bought from maplin, see: http://www.maplin.co.uk/p/bluetooth-shield-for-arduino-n97dg.
I have got it to work perfectly on the default 38400 BAUD , but cannot get it working at any other baud rate. I am currently just modifying the base code (here) given with the device where AT commands are used to configure the module.
I have tried setting the BAUD to say 115200 and then read back the devices BAUD rate using AT commands, and while it does return that it goes to 115200 it doesn't accept any commands after that.
Can any one offer help as to how I can reliably change to BAUD rate?

Have you changed the baud rate OF your serial monitor and IN you program.

Yes I have, the setup process involving sending the AT commands seems to go through successfully but when i run the test_bluetooth method, again with the BAUD changed there as well, the test fails. I have also tried connecting it with the Android device when the BAUD is changed and there is no communication, unlike when using 38400, which communicates perfectly


text:
Arduino trim: does it remove the \n as well?
According to the manual:
https://www.arduino.cc/en/Reference/StringTrim
Trim strips one or more whitespaces from the beginning and the end. Does it also removes tabulators and \n ?
I have the following code which works:
 while (Serial.available()) {   // something came across the serial
      char c = (char)Serial.read();
      Command += c;
      Command.trim();
      if (c=='\n')
         {
           Complete =true;
         }
   if (Command.length() >0 && Complete) {

        if (Command == "LED_ON") {
               // Do stuff
        }

Although I'm not sure that it is working because of the last if statement which says: if (Command == "LED_ON") ignores the ending \n and say ok it matched OR Command.trim() really takes off that \n.
Thank you

OMG, he's using String! Argh! That's evil! I suggest you learn how to do things properly and don't rely on (broken) crutches like String. https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/ https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

I would make a general comment saying that similar functions in other programming languages that do 'trim' remove all whitespace which usually includes newlines spaces tabs carriage return etc etc. Its been confirmed that this version of trim does that but newlines and tab are generally considered whitespace in most languages.

Yes, \n is also removed.
The source for the trim() function is in WString.cpp.
void String::trim(void)
{
    if (!buffer || len == 0) return;
    char *begin = buffer;
    while (isspace(*begin)) begin++;
    char *end = buffer + len - 1;
    while (isspace(*end) && end >= begin) end--;
    len = end + 1 - begin;
    if (begin > buffer) memcpy(buffer, begin, len);
    buffer[len] = 0;
}

We can see it uses the isspace() function, but where's that function defined? WString.cpp only #includes WString.h, so we go there.
In WString.h, we can see it includes ctype.h. Time to go to the C++ Reference, which tells us that yes, \n is a "space" according to isspace(), so it is trimmed.
(note that isspace() is affected by localization settings. I'm not sure what the localization settings are when compiling for Arduino)

Whilst rchard2scout is quite right that trim will remove newlines, why not rearrange the code so it doesn't matter?
  char c = (char)Serial.read();
  if (c == '\n')
     Complete = true;
  else
     Command += c;

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


text:
NRF24L01+ unable to receive data
I have 2 Arduino UNO R3 nodes communicating using NRF24L01+ transceivers with the TMRh20 library.
Setup I have original as well as cheaper but 'compatible' arduinos. One of the nodes uses an original arduino Uno whereas the other uses the cheaper one.
Observation

The node with the cheaper Uno can transmit data (sucessfully received by the other node) but is unable to receive data.
I have a number of Rf modules and UNo boards. The observation is similar across.
Using the same configuration (rf module, connection and code) , the original uno board receives data but noot the other types.
Another thing that i observed is that the cheaper uno comes with a 12MHz oscillator on the board whereas the original one has a 16 Mhz one.Can it be the source of problem?

This article mentions something that I could not get but am suspicious of it being a possible direction to the solution to the problem, only if someone could help.

On Arduino UNO boards SPI pins are connected with some digital pins. While using modem you most remember that these digital pins won't be available.

The code was taken from here http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-ExampleSketches#bm1

Another thing that i observed is that the cheaper uno comes with a 12MHz oscillator on the board whereas the original one has a 16 Mhz one.Can it be the source of problem? - Big silver can? That's for the USB interface only. 16MHz for an ATMega16U2 (or whatever, I can never remember the silly numbers) and 12MHz for a CH340.

Although having read that somewhere already, not quiet sure if that wouldn't affect the SPI or anything to do with my setup, hence brought it out again. Thanks

No, that crystal has no connection to the main MCU at all.

@Majenko: Thanks. any insight on anything other that might help me with my problem.

Are you using the one of the library examples? Which one? No changes made to it at all? You're using hardware SPI i.e. pins 10, 11, 12, 13?

Yes, did use the library examples with pins 7, 8, 11, 12, 13. Pins 7, 8 (CE,CSN) are user configurable.

As it turns out, the culprit was the power supply on the board.
The clone came with AMS1117 based regulator for the 3.3V which it did indeed generate (3.27 measured). Using it, the reception of the RF device failed (although it could transmit data). Also had 10uF and a 0.1uF capacitor hooked up in parallel to Vdd and Gnd of the NRF24L01+, as recommended. I therefore suspected something to do with the SPI configuration.
Finally, having powered the 3.3V to the Rf device from another genuine Arduino solved the problem. Not sure if it was the 3.3V rail from the clone possibly having excessive noise which may be causing the issue, as I did not see a reasonable drop in 3.3V output of the clone while in operation.


text:
Can Atmel Studio 6 Simulator simulate SPI?
I am trying to do PAL composite video output with Arduino Nano. I am using Atmel Studio 6, not the Arduino IDE. I am sending out the picture data via SPI. On the TV I could not see the text I tried to produce, so I tried to run my program in the Atmel Studio simulator (to use it as a logic analyzer). But in the resulting stimuli file I also do not see the MOSI pin changing.
I am using the A0 pin (PORTC bit 0) to send out the sync signal, that appears correctly in the output .stim file: PORTC changes exactly at the right time. But PORTB does not change at all.
My program can definitely be buggy, but that is another topic... the question is, can Atmel Studio Simulator simulate the SPI at all?

How is this even related to Arduino?

An IDE doesn't simulate SPI. I don't understand your question. My program can definitely be buggy - without posting any code your question is very vague.

No Atmel Studio cannot simulate SPI.
The fact that you are using SPI makes me think that you are using the MAX7456 IC or even the SparkFun On Screen Display Breakout which uses this same IC.
You can generate composite video just by using a few resistors and an Arduino.
I have found a number of sites on Google who have used the Arduino to output PAL composite video to display the Pong game on an old TV.

http://searle.hostei.com/grant/AVRPong/index.html
http://www.makeuseof.com/tag/how-to-recreate-the-classic-pong-game-using-arduino/
http://www.instructables.com/id/2-player-Pong-using-Arduino/
http://forum.arduino.cc/index.php?topic=8708.0
http://apcmag.com/arduino-project-7-build-a-retro-gamebox.htm/
http://electronics.divinechildhighschool.org/Home/electronics-spring-2012-1/arduino-pong

Arduino PAL output is bad, takes a LOT of processing power and doing overlays is even harder. Using MAX7456 is just a lot of easier, although you might have a few other problems with it.


text:
multiple multiplexer (4051) - how to process the inputs?
I have my Arduiono which has only a limited amount of Inputs/Outputs. But in my project I will have to attach a ton of potentiometers/buttons/LEDs, so I will have to use the IC4051-Multiplexer/Demultiplexer.
I have understood how to switch the Inputs/Outputs via the 3-Bits. But I don't get it, how to connect multiple ID4051s and process the signals(?)
Can someone explain that to me?

The 4051s are only useful, for your potentiometers. For leds, I'd use shift-registers. For buttons you could use input-shift-registers. Though there are better options. E.g. chips that can scan a matrix of buttons, or chips that send you an interrupt, if one of the buttons is pressed (so you don't have to constantly poll the button states.
As to the original question. You can connect the S1, S2, S3, and Z pins of multiple chips to the same pins on the Arduino. You need to use a different Arduino pin for each of the chips E pin.
You can then set the E pin of the chip you want to read to LOW. You then set the correct S1-3 pins to select which output/input of that chip you want to connect to. You then read the value from the Z pin.
I hope that makes sense. Otherwise, let me know.

Re “You need to use a different Arduino pin for each of the chips E pin”, one can instead use a 74LS138.  This uses 3 address lines to select 1 of 8 outputs to pull low.

I have no experience of this chip but I would guess that you would need to connect the child level multiplexer to the output of the parent and use the outputs to drive the address lines.
You could look at an MCP23008 or MCP23016, these are 8 and 16 bit GPIO expanders that you control via I2C.  You can have 8 of the MCP230008 (64 pins) before you need to look at I2C bus expanders (which you can get).  I think its the same for the 16 bit version, but you would need to double check.


text:
int VS uint8_t VS uint16_t
This question is quite clear. What are the differences between an int, an uint8_t, and an uint16_t. I know it has to do with bytes and memory but can someone clarify me a bit?
Things I want to know:
1- How much memory does each take.
2- When to use what.
3- In the end of the day, are they that different?

Beware that the compiler does not do arithmetic with anything smaller than int. E.g. (uint8_t) 200 + (uint8_t) 200 does not overflow: the terms are promoted to int before the addition and the result is (int) 400.

You can decipher most of them yourself.

A u prefix means unsigned.
The number is the number of bits used. There's 8 bits to the byte.
The _t means it's a typedef.

So a uint8_t is an unsigned 8 bit value, so it takes 1 byte. A uint16_t is an unsigned 16 bit value, so it takes 2 bytes (16/8 = 2)
The only fuzzy one is int. That is "a signed integer value at the native size for the compiler". On an 8-bit system like the ATMega chips that is 16 bits, so 2 bytes. On 32-bit systems, like the ARM based Due, it's 32 bits, so 4 bytes.  Of the three it is the only one that changes.
Personally I rarely use int and always use uint8_t etc., since the variable type is the same no matter what architecture you compile for.  When you use int you can run into problems if you had a program that worked fine on a 32-bit ARM but then doesn't work right on an 8-bit ATMega, since the int can only store a fraction of the range of numbers on the 8-bit system compared to the 32-bit system.

Can I make an uint8_t array?

You can make an array of any data type.

Can I use it like this too: uint8_t function()

Yes. uint8_t is the same as "byte" or "unsigned char".

If you need negative values, you need to use signed integers. E.g. int16_t.


text:
Arduino Uno + aRest + ESP8266
So, I can use the aRest library to program to the ESP8266 standalone, but if I have the ESP8266 connected to the Arduino Uno, can I still use the aRest library? Or will this no longer work?  I am trying to send a request to the Arduino unit that will toggle a pin to turn on/off via the aRest library.  Thanks!
aRest can be found here: https://github.com/marcoschwartz/aREST

Please edit your question. It currently needs more detail on what you are trying to achieve and is too broad and unclear what you are asking.

Why don't you just try it? :)
In overview of GitHub repo, first sentence, it says: "A simple library that implements a REST API for Arduino & the ESP8266 WiFi chip." Next paragraph confirms it.

It is for the chip itself, not when the chip is connected to the Arduino unit.  The chip can be a standalone microcontroller

If it works on Arduino unit itself, it can be made to work with ESP8266 for sure, right? Maybe just there it no ready code, you need to edit a bit.

It doesn't work on the Arduino itself, it works with a wifi chip like the CC3000 connected to the Arduino, or the ESP8266 standalone.  Haven't seen anything that has it using an ESP8266 connected to an Arduino


text:
How to keep track of if data is outdated
I have a large set of data and it is refreshed every 30 seconds or so. However, not all data is refreshed every time. It is possible that no new data for a particular calculation isn't received for even a few hours. For this reason I need to track what data is possibly outdated, but hasn't been updated (maybe due to technical malfunctions or a sensor is down). I was thinking about creating an additional (large) 2d array to do this, and increment some sort of counter. This way if a particular spot is at 1000 this means it is old. When new data is received it can be reset to 0. However, this seems like a slow, ineffective way to do this. How could I keep track of data more efficiently?

It depends what form the data takes.

Also what you are using the data for.

@Majenko the data is all integers stored in arrays. It is just being stored and displayed on a webpage. So it'd be great to have some indication of what data on the page is old

What range are the values?

@Majenko -1 (indicating no data available) to 1000

You could add a timestamp for each value (or set of values). It would hold the time when the value(s) was latest updated.

OK, so you have three possible states for your values:

No valid data (-1, or 0xFFFF in 16-bit 2's complement)
Valid data (0 to 1000, or 0x0000 to 0x03EB in 16-bit)
Valid but "old" data.

If you first check for invalid data before thinking about "old" data (invalid data is never considered "old") then you just have two states:

Valid data (0 to 1000, or 0x0000 to 0x03EB in 16-bit)
Valid but "old" data.

As you can see the highest 6 bits of the stored value aren't used at all except for storing -1 for invalid data (hence checking for that first). So you could utilize those 6 bits to store all sorts of things. In 6 bits you can store the values 0 to 63. That could be the number of seconds since the last time you got some data.
By masking and shifting you can separate out the two values:
val = data[x] & 0x3FF;
sec = data[x] >> 10;

Every second add one to the seconds count of each and every data entry that is less than (say) 60.
val = data[x] & 0x3FF;
sec = data[x] >> 10;
if (sec < 60) sec++;
data[x] = val | (sec << 10);

Now each entry in your array knows how old it is (up to 1 minute), and if it's older than a certain threshold (30 seconds? 45 seconds? you choose) then you consider it "old" and display it as such.
You can make it easier to program by using a union/struct combination:
typedef union {
    int16_t rawval;
    struct {
        unsigned value:10;
        unsigned seconds:6;
    } __attribute__((packed));
} data_t __attribute__((packed));

If your data array is now made up of that type instead of integers:
data_t data[500];

you can now access:

data[x].rawval as the raw 16 bit signed value (to look for -1).
data[x].value as the unsigned 10 bit value from 0 to 1000.
data[x].seconds as the unsigned 6 bit value from 0 to 63.

Updating the seconds then becomes as simple as:
if (data[x].seconds < 60) data[x].seconds++;

When you store a new value using
data[x].rawval = sensor.getValue();

the seconds is automatically overwritten with 0 which resets the count for you.
And both methods give you data ageing without using a single byte more memory.

Rather than frequently updating a time flag for each data item, you can store a “generation number” for each item.  Maintain a “current generation number” currentGen and at intervals add one to it.  If the interval at which you increment currentGen is 20 seconds and you store 16-bit generation numbers, rollover will occur about every 15 days.  [20*2¹⁶/3600/24 = 15.17 days.]
For example, suppose your data structure has fields for item.value and item.gen.  Whenever you store a new value into item.value, copy currentGen into item.gen.  Later, to tell the age of an item, use unsigned int arithmetic to subtract item.gen from currentGen.  For example, if  currentGen is 23453, an element with item.gen = 17487 is about 33 hours old.
Note, if item age ever exceeds 15.17 days, it will wrap around to zero.  It that's a concern, either use a larger datatype for item.gen, or update currentGen less frequently, for example every two minutes for a 90-day wraparound or every 8 minutes for a 364-day wraparound time.


text:
How to automate an electric kettle?
I have this tea kettle, which requires pressing two buttons one after the other ("on" and "prog") to start.
I'd like to automate that action (tying it to Tasker on my phone), and am wondering what's my simplest/cheapest option. My communication options are either WiFi or Z-Wave/ZigBee.
I'm assuming Arduino Uno Wifi is an option, but that seems like a huge overkill given how simple what I want to do is. Are there any other simpler/cheaper tools that I could use to do this?

... ESP8266... ?

WiFi is IMHO better, since you probably already have a WiFi network. And your phone supports WiFi. Otherwise you'll need some IP-to-ZigBee gateway. The ESP8266 is very nice, there are pretty neat little "dev boards" with USB, which make programming an easy job.

You may wire the buttons and transistor (bjt or fet) parallel. This way the device will still work with the normal buttons.

If you want to connect to your phone, you'd be better of using Bluetooth.

@Gerben the kettle is too far from my bedroom for that to work

You could use lots of options to control it from Mbed boards to the Uno with a wifi shield, to a raspberry pi to .... the list goes on.  But if it were me I would use the something like the ESP8266 which cost less than $10 usd and can be programmed with the arduino IDE (I'm assuming that is useful given the community this was posted in).  There are also lots of tutorials available online for this kind of thing.
To trigger the button you have two options: a non-destructive one and a destructive one.  For the non destructive one, use something like a solenoid in a custom mount or a servo and small lever arm to push the button.  The benefit to this is that if you change your mind you just have to move the device and you still have a perfect unharmed kettle.  Plus, you can still use it if your device breaks or malfunctions.
For the destructive option, open up the kettle to get at the buttons or button pads and solder a wire to each side.  If you're lucky you can do this so that it can still be put back together and the original button still work.  One option is to use a relay to connect them.  You can use a small solid state relay or a larger coil relay; both would be under a couple of dollars and not large enough to be too obtrusive.  Using a relay is nice since you don't have to worry about which voltages are being used on which side of the button and it isolates the microcontroller from the kettle better.  (Actually some relays are polarized so if it doesn't work, switch the wires and try again).  Another option is to use an  optoisolator like this one.  It is polarized so if it doesn't work switch the wires.  Another option is to use a mosfet.  I believe it will work if you get an N channel mosfet with a Vgs (gate to source voltage) less than 3.3V.  Hook up the Source pin to the more negative of the two button leads and the Drain to the other.  Hook up the gate to a pin on the micorcontroller.  Also, you should put a resister between the gate and the source pins.

Thanks! What resistor should I add if I use this transistor: IRLZ24N?

It's just a pull down resistor so a wide range would work.  I'd use a 10k just because I've got a lot laying around.  Anything 1k-25k should be fine.

Here's another article that may be of use: http://little-scale.blogspot.com/2016/05/circuit-bending-basics-two-easy-was-of.html

Replace your button with a relay and use a microcontroller to switch it.
It will be cheaper to use an ESP6266, which could be programmed with the Arduino IDE and the same Arduino code works on it. It will be perfect as it has got just 2 GPIO ports and it will just be the size of your thumb.

Calm down, you don't need a full relay to emulate a small switch, a MOSFET would be good enough.

Also, the ESP8266 has more then 2 GPIOs, I mean WAY more. You just have the ESP8266 ESP-01 breakout, the first on which has only 2 GPIOs. The ESP-12 has many more and with a custom PCB, you can have access to all of them.

This is simply a suggestion. It is not in your list of communication protocol that you listed but this could work great.
A good and reliable way is to use an GSM shield with and Arduino. The GSM shield could receive a text such as "on" or "off" and could interpret those messages to control your kettle.
To emulate the switches, you can use 2 MOSFET. They act like an electronic in the sense that when you apply 5V (PNP transistor), it lets current pass and will cut the current flow when there is no voltage applied to it.
NOTE: GSM modules are quite cheap if you know where to get them. I recommended getting a chinese version because they usualy work fine for me and there price is way lower.

Hmm, I het have to find a decent+cheap GSM module. But WiFi will do in this case, since I suppose the device will always be within range of the WiFi. So you can eaily get away with a ~4$ ESP8266-12 dev board.

Pay and extra 4$ and you get something that works everywhere. https://www.amazon.com/SIM800L-Quad-band-Network-Breakout-Module/dp/B017I6QC8C/ref=sr_1_7?ie=UTF8&qid=1478086767&sr=8-7&keywords=gsm+arduino

Nice, considering I've worked with the SIM900, I should be able to figure out how to get this one working.

Probably a dumb question, but I know basically nothing about GSM aside from my phone having it. Wouldn't said module need a sim card/service connection to work?

Yes it does need a SIM card

@canadiancyborg so I'd need to pay monthly fees to a cellular provider to use this? Those would greatly exceed whatever the costs of the GSM shield are, so I don't really understand this suggestion..?

Well I have a cell with unlimited data and I remove its SIM card when I need to use it in my projects.


text:
How do I hook up a 3V device to a 74AHCT125 (Quad Level-Shifter)?
I have this level shifter that I'm trying to feed a 5V power source and then hook up a 3V device.

I've got the 5V source hooked up fine (on the top pinouts), but having trouble figuring what the "power out" would be that's 3V.
Here's the data sheet.

That's because it can be used to shift 3V to 5V, not 5V to 3V.

It's not a level shifter. It's a buffer chip that can be used to level shift in one direction only.
It is good for shifting from a low voltage logic signal (3.3v, say) up to a 5V logic signal. It can't shift down from 5V to 3.3V.
Basically it works by having a fixed voltage that it considers to be a logic HIGH, and any voltage above that will be output as 5V. Any voltage below will be output as 0V.  This is the "TTL Logic Level" specification in the datasheet.
So if you have a sensor that emits a 3V logic signal the HIGH logic value will be above its fixed threshold and will trigger a 5V HIGH on the output.
In contrast "CMOS" logic uses a percentage of the supply voltage to set the thresholds (usually > 0.6 x Vcc), and a 3V signal is less than that (3.3V is about bang on it, so is "iffy"), so won't work (or not reliably).

The datasheet would let you think it cannot shift in that direction, but it's the chip recommended by Adafruit to do so : https://www.adafruit.com/product/1787
The "trick" is to feed it 3V power. It seems it will then happily accept 5V input and produce 3v outputs.


text:
Why is communication between a Python program and Arduino not producing the expected result?
I have written some Arduino code (with help from the post Serial Input Basics). On serial I send some data and, based on certain values sent, certain LEDs will be lit. Here is the Arduino code:
const byte numChars = 32;
char receivedChars[numChars];
char tempChars[numChars];        // Temporary array for use when parsing

// Variables to hold the parsed data
//char messageFromPC[numChars] = {0};
int cmd = 0;
int pitch = 0;
int velocity = 0;
int integerFromPC = 0;
int int2FromPC = 0;
boolean newData = false;

void setup() {

    // Put your setup code here, to run once:
    Serial.begin(9600);//set baud rate

    //Configure pins 2:5 as OUTPUT
    pinMode(2,OUTPUT);
    pinMode(3,OUTPUT);
    pinMode(4,OUTPUT);
    pinMode(5,OUTPUT);
    pinMode(13,OUTPUT);
}

void loop() {
    recvWithStartEndMarkers();
    if (newData == true) {
        strcpy(tempChars, receivedChars);
        // This temporary copy is necessary to protect the original data
        // because strtok() used in parseData() replaces the commas with \0.

        parseData();
        showParsedData();
        if(cmd==144 && velocity!=0){
            switch(pitch){
                case 30:
                    digitalWrite(2, HIGH);
                    break;

                case 31:
                     digitalWrite(3, HIGH);
                     break;

                case 32:
                    digitalWrite(4, HIGH);
                    break;

                case 33:
                    digitalWrite(5, HIGH);
                    break;

                default:
                    break;
            }
        }
        if(cmd==144 && velocity==0){
            switch(pitch){

                case 30:
                    digitalWrite(2, LOW);
                    break;

                case 31:
                    digitalWrite(3, LOW);
                    break;

                case 32:
                    digitalWrite(4, LOW);
                    break;

                case 33:
                    digitalWrite(5, LOW);
                    break;

                default:
                    break;
            }
        }
        newData = false;
    }
}

void recvWithStartEndMarkers() {

    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // Terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    }
}

void parseData() {      // Split the data into its parts

    char * strtokIndx;  // This is used by strtok() as an index

    strtokIndx = strtok(tempChars, " "); // Get the first part - the string
    //strcpy(messageFromPC, strtokIndx); // Copy it to messageFromPC
    cmd = atoi(strtokIndx);

    strtokIndx = strtok(NULL, " ");      // This continues where the previous call left off
    //integerFromPC = atoi(strtokIndx);  // Convert this part to an integer
    pitch = atoi(strtokIndx);

    strtokIndx = strtok(NULL, " ");
    velocity = atoi(strtokIndx);         // Convert this part to a float
}

void showParsedData() {
    Serial.print("Comm ");
    Serial.println(cmd);
    Serial.print("Ptch ");
    Serial.println(pitch);
    Serial.print("Velo ");
    Serial.println(velocity);
    Serial.println("\n");
}

Now this works perfectly with sending data from the Arduino's serial monitor, so for example if I type the following on serial monitor:
<144 30 45>

Then the LED I expect to get lit does, and I can turn it off by:
<144 30 0>

Now, I want to send this data from a Python (2.7) program which I am reproducing here:
#!/usr/bin/env python
import time
import serial
ser = serial.Serial('/dev/cu.usbmodem1421', 9600)
noteOn = 144
veloMid = 75
veloSilent = 0
def sendData(cmd, pitch, velocity):
    global ser
    cmd = bytes(cmd)
    pitch = bytes(pitch)
    velocity = bytes(velocity)
    ser.write("<")
    ser.write(cmd)
    ser.write(pitch)
    ser.write(velocity)
    ser.write(">")

while 1:
    notes = range(30, 34)
    for note in notes:
        sendData(noteOn, note, veloMid)
        time.sleep(2)
        sendData(noteOn, note, veloSilent)

The idea was to do the same thing I was doing manually in serial monitor, except using a Python script. But this produces no result. I see the RX and TX pins on the Arduino toggling, so it looks like the program is indeed communicating with the Arduino. In the Python IDE I wrote a few lines as follows to read the data from Arduino:
import serial
ser = serial.Serial('/dev/cu.usbmodem1421', 9600, timeout=5)
while True:
    data_raw = ser.read()
    print data_raw

With above code I receive the following characters in the Python IDE:
C
o
m
m

P
t
c
h

V
e
l
o

I have a feeling there is some mismatch between the data types of the data I am sending between the Python script and the Arduino, but I am not sure exactly what this mismatch might be.

Why am I not seeing the values of cmd, pitch and veocity being printed out from the serial.read() although the other strings "Comm   Ptch   Velo" are printed?
What dataype is serial.write passing on that might than be causing mismatch with my Arduino code?

This is how you format code: Use the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you. It was hard work changing your tags (from I don't know where) into what works here.

In your test with the serial monitor you are putting spaces between each number. Using my logic analyzer I got this being sent from your Python code to the Arduino:

No spaces, right? So the Arduino is receiving:
<1443175>

And since you are using a space as a numeric delimiter your decoding isn't working.

Something like this is probably warranted:
    ser.write("<")
    ser.write(cmd)
    ser.write(" ")
    ser.write(pitch)
    ser.write(" ")
    ser.write(velocity)
    ser.write(">")

Nick....You are a genius!!! The spaces were exactly the problem. I completely forgot the spaces when I switched to the python code. After correctly formatting my output string things work as I want. Many thanks for your suggestion. I also apologize for the formatting issue. I will keep your suggested link handy next time I submit a question.


text:
Help with 1-Wire to I2C translate
Please, someone.
I want to use a temperature sensor (DS18B20) in an I2C only shield (Tentacle Mini), but this sensor is One Wire only. Can I write an I2C code to change the 1-Wire to I2C for this sensor? I think to use the (DS2482-800) bridge, but I don't know how to do...
Thanks!

Can't you connect the one-wire device (and if needed pullup resistor) to some other pin at the header rather than through the shield?

I recently wrote a Cosa TWI device driver for the DS2482. The example sketch actually uses a DS18B20. For further details please see https://github.com/mikaelpatel/Cosa/tree/master/libraries/DS2482.

An alternative is to use the I2C SDA pin to both I2C and 1-Wire.

As you said, the DS18B20 uses One-Wire interface. I2C is a Two-Wire interface. Pratically, you can't use the Arduino to translate that, BUT I found the  DS28E17, a module that could translate the the 2 methods of communication. It should work but I havent tested it.

The DS28E17 is a 1-Wire slave to I2C master bridge device that interfaces directly to I2C slaves at standard (100kHz max) or fast (400kHz max). Data transfers serially by means of the 1-Wire® protocol, which requires only a single data lead and a ground return. Every DS28E17 is guaranteed to have a unique 64-bit ROM registration number that serves as a node address in the 1-Wire network. Multiple DS28E17 devices can coexist with other devices in the 1-Wire network and be accessed individually without affecting other devices. The DS28E17 allows using complex I2C devices such as display controllers, ADCs, DACs, I2C sensors, etc. in a 1-Wire environment. Each self-timed DS28E17 provides 1-Wire access for a single I2C interface.
Hope I helped you.

authors: 鼎点娱乐代理--平台总代


text:
Does 'digitalPinToInterrupt' work with analog pins
I have an interrupt signal attached to the A12 pin of an Arduino Mega 2560.
Would the following source line activate the interrupt processing?  I am calling the digitalPinToInterrupt function on an Analog pin.  It compiles fine.
attachInterrupt(digitalPinToInterrupt(A12), MessageFromIOBInt, FALLING);

where my interrupt code is
void MessageFromIOBInt(void) {
    ++gNumInterrupts;
}

What Arduino board are you using?

I am using MEGA 2560

Interrupts only work on interrupt pins. Trying to translate a pin number into an interrupt number for a pin that isn't an interrupt pin will never work.

External Interrupts: 2 (interrupt 0), 3 (interrupt 1), 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2). These pins can be configured to trigger an interrupt on a low level, a rising or falling edge, or a change in level.

Many pins (including the analog pins) can use the pin change interrupt. This requires an external library which has its own way of interfacing with them (see the examples).

Does 'digitalPinToInterrupt' work with analog pins?

It works in the sense that it compiles. When executed, for a pin that is not one of the interrupt pins it will return the value NOT_AN_INTERRUPT.
Thus a sensible test would be to check whether or not you get NOT_AN_INTERRUPT returned from digitalPinToInterrupt(A12).
A quick test confirms this:
void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.println (digitalPinToInterrupt(A12));
}  // end of setup

void loop () { }

Output:
-1

In Arduino.h is this define:
#define NOT_AN_INTERRUPT -1

I have a page about interrupts. On that page, amongst other things, is a list of external interrupt pins for various Arduinos:

You can see that the pins on the board labelled D2, D3, D18, D19, D20, D21 are the only ones which support these sorts of interrupts (external interrupts). Various other pins support pin-change interrupts.
On the Mega2560 in particular these pins are supported for pin-change interrupts:

10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69)

As Majenko mentioned, you use pin-change interrupts in a different way, possibly using the PinChangeInt library, or just accessing the registers yourself as described on the page I mentioned above.


text:
How to measure free RAM on an Arduino Due in Runtime?
I use this Library to measure my free RAM on a Mega in runtime. But this Library does not work on the Due.

Try this library https://github.com/mpflaga/Arduino-MemoryFree

As mentioned by Mikael Patel in a comment, the library from Arduino-MemoryFree
 should do it. A minimal sketch that seems to work on the Due:
extern "C" char* sbrk(int incr);

int freeMemory() {
  char top;
  return &top - reinterpret_cast<char*>(sbrk(0));
}

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.print ("Free memory is: ");
  Serial.println (freeMemory ());
}  // end of setup

void loop () { }

I'm not totally convinced that this gives the correct figure. The figure returned by the library above for my Uno was too high (2297 bytes).

It seems to work fine after a call to malloc(), which is needed to initialize __brkval. I would return &top - ( __brkval ? __brkval : &__heap_start); in order to have something that works also when not using malloc().

I thought it might be something like that. After all, not everyone uses malloc.

Try to use this method:
int freeRAM() {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

The question was about a Due. When I tried your code on my Due I got -28 bytes of RAM, which is hard to believe.


text:
Replacing stock String.cpp with smaller version
Hey all I am wondering if it's possible to modify the WString.cpp file to only include the commands that I need for my project since that file is so large.
I am using a Digispark arduino that is Attiny85 which only has about 6k flash memory after bootloader.
Needless to say I am almost out of flash memory and I still need to do a few things.
I am reading from a serial port (in this case, using DigiCDC for a virtual serial port).
How can I overwrite the default Strings class that looks like its built in to the IDE with my own modified String class so I can get a smaller footprint?
Thanks!

Write your own core.

Just don't use String - which is recommended regardless.

@Majenko What can I use in place of String if I have the serial.read() data coming in as 255,255,255 which in itself crashes the ATTiny. I can only send it 255,2 without it crashing.

Character arrays. Pure C. You might like to read these: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/ https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

If you're crashing trying to read serial data, it isn't a flash-capacity problem; you're running out RAM. Using char-arrays instead of Strings will probably help there, too, but you'll need to look at your RAM memory allocations, too. Lots of globals, f/ex, will occupy memory that might otherwise be available for temporary use. Do they really need to occupy space for the entire run duration? If not, allocate ones that don't as local memory in the functions to that do use them; it gets returned when the function exits.

You can make a copy of WString.cpp, edit it, and add it to your project.
Note however that:

You will have to define every method that you use. Otherwise the
linker will pull WString.o from the Arduino core library in order to
resolve the missing methods, and then it will complain that some
methods have been defined twice.
Just pruning WString.cpp from unused methods will not help: the
linker is already doing that for you.
To know which functions/methods of your program are taking too much
flash, you can use the command
avr-nm --size-sort -Crtd program.elf.
I second Majenko in recommending against String objects if possible.


text:
Writing a float to a BLE characteristic. What data format?
I am currently working on a python-based Bluetooth Low Energy client for OS X and I got stuck while trying to write a remote float characteristic value.
First of all: my setup is an Arduino 101 with integrated BLE module and a Macbook. On the Arduino side the code is working well, I can read and write BLE characteristic's from a BLE explorer app on my phone.
Also I did achieve to read out the characteristics float values in my python script on the Macbook. Yet I did not fully understand what exactly I am doing. After requesting the characteristic's value from the peripheral, the peripheral answers and I get what I think is binary data? I could manage to unpack the data to a float by using.
     def characteristic_to_float(data):
        float_value = struct.unpack('f', data)[0]
        return float_value

The received floats are correct. But I couldn't get my python code to properly write a float value to the peripheral. I tried this:
    a_number = 5.3

    def float_to_characteristic(float_value):
        val = struct.pack('<f', float_value)[0]
        return val

    characteristic_1.write_value(float_to_characteristic(a_number))

The python code itself will run through without an error, but the Arduino doesn't receive the data. I am sure of that, because I implemented a function on it that sends out a Serial print when a characteristic has been written.
Remember the characteristics are read & write and I could verify this by using my phone. I think I got something wrong with the struct.pack thing, since I can't find any information about what data format is needed...
Does someone know how I can pack or convert the float to the right data format? Unfortunately the lib I use (Adafruit BluefruitLE) does not have a documentation.
Thanks!

Try packing and then unpacking the value entirely in python as a test.  Try sending the packed value from the arduino back to it directly as a test.  Figure out how to dump the bytes of the packed value as hex from python for verification, etc...

I could solve the issue by taking another look in the documentation of the struct lib in python. I tested different pack and unpack methods and wondered where the [0] in my code came from (I did copy it from somewhere). So what I found working for my setup simply is:
def float_to_characteristic(float_value):
       val=struct.pack('<f',float_value)
       return val

When I send this packed value through BLE the Arduino will accept it.

Two solutions came to my mind if am gonna do your thing,
1) convert the number to a string char by char and send it as it is then unpack it as char by char , for example 5.3 -- > "5.3" it will be received then you have to decompose it 5 and . and 3 (inefficient solution because of conversion of types will be alot)
2) calculate the number of decimal digits and send it with the number something like:
5.3 ---> 53 and one decimal point, you would send it as
53:1 and then unpack it and reconstruct it
the second solution would be better for me since i have to send it as 2 things
number: decimal point
and then reconstruct it, this library will ease the reconstruction of decimal point sent by 53:1 (if you want to send floats in two directions)
SimpleSerialExtractor

I used this way:
define a BLE format descriptor (0x2904)
Attach the descriptor to the characteristic
struct BLE2904_Data {
  uint8_t m_format;
  int8_t m_exponent;
  uint16_t m_unit;
  uint8_t m_namespace;
  uint16_t m_description;
} __attribute__((packed));

struct BLE2904_Data desc1;   // must remain valid memory for ArduinoBLE

  desc1.m_format = 0x14;  // float
  desc1.m_exponent = 0x0;
  desc1.m_unit = 0x2728;  // voltage
  desc1.m_namespace = 1;
  desc1.m_description = 0x10f;

  BLEDescriptor voltageLabelDescriptor("2904", (uint8_t*)&desc1, sizeof(desc1));
  batteryLevelCharacteristic.addDescriptor(voltageLabelDescriptor);

The 2904 descriptor sets the data type see here for more details:

authors: Сергей Анисимов


text:
Arduino - Turn on LED when Potentionmeter is used
I'm very new to the Arduino/Microcontroller-world, so please be patient :)
I have 4 potentiometers and I want my LED to blink up, when one of these is beeing used.
So far., so good.. the potentiometers are sending singnals to my inputs A0-A3. In the code I read and buffer the values of send to the inputs, so when a new value is recieved (potentiometer is beeing used), the funcion blinkLED() is beeing triggered:
int ledPin = 13;

int pin[] =             {A0, A1, A2, A3};
int cc[] =              {20, 21, 22, 23};
int potiValues[] =      {0,  0, 0, 0};
int potiValuesTmp[] = {0, 0, 0, 0};

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

void loop() {
    // READ EVERY PIN
    for(int i=0; i<=3; i++){
        potiValues[i] = map(analogRead(pin[i]), 0, 1023, 0, 127);
        if(potiValues[i] != potiValuesTmp[i]) {
            // NEW VALUE RECIEVED - MAKE OUTPUT
            Serial.println("Pin ");
            Serial.print(pin[i]);
            Serial.print(" - ");
            Serial.print("Value: ");
            Serial.print(potiValues[i]);
            blinkLED();
        }
        potiValuesTmp[i] = potiValues[i];
    }
}

void blinkLED() {
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
}

It somehow works on the emulator circuits.io, but I'm not sure if I did it right(?) Maybe someone could have a look and tell me, what to improve?
But my main question is:
When the function blinkLED() is triggered, there is this delay,.. does the whole loop()-function wait, too?

Put a resistor in series with your LED or it will damage both the LED and the Arduino. 150 Ω or higher would be suitable. See LED calculator.

When the function blinkLED() is triggered, there is this delay,.. does the whole loop()-function wait, too?

Yes, when you call a function it doesn't return until it is done, and delay is blocking.
You can rewrite a bit like this:
int ledPin = 13;

int pin[] =             {A0, A1, A2, A3};
int cc[] =              {20, 21, 22, 23};
int potiValues[] =      {0,  0, 0, 0};
int potiValuesTmp[] =   {0, 0, 0, 0};

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

unsigned long lastFlash;
int flashesToGo;
const unsigned long flashTime = 50; // ms

void loop() {
    // READ EVERY PIN
    for(int i=0; i<=3; i++){
        potiValues[i] = map(analogRead(pin[i]), 0, 1023, 0, 127);
        if(abs (potiValues[i] - potiValuesTmp[i]) > 3) {
            // NEW VALUE RECEIVED - MAKE OUTPUT
            Serial.print("Pin ");
            Serial.print(pin[i]);
            Serial.print(" - ");
            Serial.print("Value: ");
            Serial.println(potiValues[i]);
            flashesToGo = 10;
            potiValuesTmp[i] = potiValues[i];
        }
    }

   // flash LED if required

   if (flashesToGo > 0)   // need more flashing?
      {
      // is it time to toggle the LED?
      if (millis () - lastFlash >= flashTime)
        {
        // toggle LED
        if (digitalRead (ledPin) == HIGH)
          digitalWrite (ledPin, LOW);
        else
          digitalWrite (ledPin, HIGH);
        // remember when we did it
        lastFlash = millis ();
        // count down
        flashesToGo--;  // one less flash
        } // end of time for another flash
      }
   else
     digitalWrite (ledPin, LOW);  // ensure LED off

}

What this does is add to the main loop a few lines of code that toggle the LED after a certain time is up (50 ms currently). It counts down the number of toggles from a desired starting point (eg. 10) until they are all done. This means that the LED will flash without blocking.
Each time you detect a new analog reading the number of flashes is reset back to the maximum.

I modified your test for if the analog reading changed to be:
if(abs (potiValues[i] - potiValuesTmp[i]) > 3)

I found that without that, the LED flashed continually because the readings were slightly different each time (eg. 51, 52, 51, 50) which would probably just be error in the ADC reading.
With that change, it doesn't count as "changed" unless the reading changes by 3 (you could make it more, or less than that).

I want the LED to blink up just once - when I turn one of the potentiometers

In that case change:
flashesToGo = 10;

to:
flashesToGo = 2;

That is one HIGH and one LOW (one flash in total).

Yes, the main loop (aka void loop) will have to wait during the delay. One method of escaping that problem is to use the millis() function. There is an example code called "blinkWithOutDelay" (or something like that). It pretty much uses the ATmega's internal timer. This method is more for advanced users. The millis() functions is will return you the number of milliseconds since the start of your program.
Also, potentiometers are always in use. They will report back data everytime. Its not like if it had too fixed states like ON or OFF. So the problem is that they are all in used at the same time. You might consider changing the values of potiValuesTmp. My varying that variable, you can make it so that at least one potentiometer has to be higher then a certain point.

Hey, thank you very much, I will have a look on the mentioned example.
Just to verify I have not misunderstood you with this potentiometers.. I did this in my code, didn't I ? I mean, I buffer the values in the array so I can detect, when a potentiometer is beeing.. "used" :) .. or, did I get something wrong here?

well, if they aint all at the zero position, they will be considered as USED in your program

by used you mean used one time, right?.. but not "used live" (sorry I don't know how to say that) .. I want the LED to blink up just once - when I turn one ot the potentiometers .. just like a status-LED which says "here.. you just did something"

change all the vals of potiValuesTmp[] to 512

sorry, I don't get it :/

can you please explain it to me, what/how you mean that?


text:
Timer2 "Clear OC2B on Compare Match" not working as expected in CTC mode
This is a follow up to my previous question.
I have Timer2 in CTC mode, with TOP=OCR2A set to 150 (with a prescaler of 8, giving a 75us timing interval).
The datasheet states that setting COM2B1 to 1 in TCCR2A will "clear OC2B on compare match" (= Arduino pin D3) when you are in CTC mode.
I would like to use this functionality to get a "pwm" signal with a period of 75us, with duty cycle determined by OCR2B. I realize that this is a very convoluted way of achieving this, but eventually I want to be continually be changing OCR2B to get a (rapidly) varying duty cycle.
In the compare channel A interrupt I would like to turn D3 high, relying on the "clear on compare match" feature of channel B to turn it low a small interval later.
I have the following minimal(-ish) example:
#define OCIEA 1
#define CA21 1

void setup() {
  // PD3 as output
  DDRD |= (1 << PD3);

  // Pause the timers so they sync up
  GTCCR = (1<<TSM)|(1<<PSRASY)|(1<<PSRSYNC); // Halt all timers

  // Reset timer
  TCNT2 = 0; // set timer2 to 0 (8-bit timer)

  // Enable CTC mode
  TCCR2A = (1 << WGM21); // Timer 2 in CTC (TOP = OCR2A)

  // Clear output pins on compare match
  TCCR2A |= (1 << COM2B1); // Clear OC2B on match

  // Set prescaler
  TCCR2B = (1 << CA21); // set timer 2 divisor to 8

  // Set output compare
  OCR2A = 150; // Determines TOP for Timer2

  // Determines the pulse width
  OCR2B = 75; // Timer 2 output B (controls OC2B = PD3 = D3)

  // Enable interrupts for timer 2
  TIMSK2 = (1 << OCIEA);

  // Set the timers going again
  GTCCR = 0; // release all timers
}

ISR(TIMER2_COMPA_vect)
{
  TCCR2A &= ~((1 << COM2B1) | (1 << COM2B0)); // Disable clear OC2B on match
  DDRD |= (1 << PD3); // Enable output
  PORTD |= (1 << PD3); // Output high
  TCCR2A |= (1 << COM2B1); // Enable clear OC2B on match
}

void loop() {

}

Ideally the ISR would just consist of PORTD |= (1 << PD3); but this does not give my desired 50% duty cycle, but apparently it's impossible to write to the pin with COM2B1 enabled, so I tried various combinations of disabling it and reconnecting the pin but all I am getting is a very, very short pulse. It looks like as soon as COM2B1 is re-enabled, the pin goes low, even though a compare match on channel B should not have happened yet.
Setting COM2B0 instead of COM2B1 works as expected: the pin toggles state (but this is not what I want).
Why does this not work the way I expect it to, and is there a way to get my desired behavior? Also, if this is not possible, what on earth is the purpose of the clear on compare match feature if you can't turn the pin on at all when using it?
I have discovered I can sort of get the behavior I want by setting COM2B0 instead of COM2B1 (toggle on match rather than clear on match) and forcing a compare match in the interrupt (toggling the pin off) so that later the "real" toggle on match will turn it off. However, this is not ideal (as if the real and forced match overlap, I would lose track of the pin's state), and I'm still wondering what the purpose of the clear on match functionality is if it just forces the pin low.

I think a potential solution might be to, in the interrupt, activate set on match, force a match, and then set it back to clear on match (and possibly force a match again if I detect the forced and "real" matches overlapped). I can't try this out until this afternoon, and it still seems needlessly complicated.

Why don't you use mode 7 instead of mode 2? Mode 7 combines CTC with fast PWM, which seems to be what you want, although it's not officially called “CTC” (but why would you care about the official name?).

Use Edgar's solution. Or use ISR(TIMER2_COMPB_vect) to set the pin to low, but this isn't ideal.

That makes sense. It seems I should have read the answers I got to my original question more carefully. Thanks. I'm not sure if I should delete this now (since a more careful reading of the original question solves my problem), but I am still interested why what I came up with doesn't work and what the use of "clear on match" in CTC mode is. Also, I think this is a strong case of me suffering from the XY problem.

The PWM modes manage pin at both ends of the cycle.
The point of the CTC modes is that they manage the pin only at one end of the count, but allow you to manage the other end explicitly.
To manage both ends explicitly, you use normal mode.
To set the OC2B bit with FOC2B in the TCCR2B with your interrupt:
ISR(TIMER2_COMPA_vect)
{
  TCCR2A |=  (1 << COM2B0); // Set OC2B on Compare Match
  TCCR2B |=  (1 << FOC2B ); // Force Output Compare B OC2B
  TCCR2A &= ~(1 << COM2B0); // Clear OC2B on Compare Match
}


text:
High errors in transmission (completely eliminated by adding delay): What's the issue?
I am using a two Arduino setup with two XBee radios. One radio is sending data and the other is receiving data. I am sending three sensor readings following a protocol which uses three bytes for each sensor reading. Byte one is sensor information, byte two is data, and byte three is for error checking. When I run the set up for about 5 minutes I get approximately 47% errors in transmission. Once one error occurs, there seems to be an avalanche of errors. However, when I add delay in between sending bytes (100ms between bytes and 1s between sensor) it works perfectly. I've tried expanding the hardware buffer, but this didn't work.
        delay(2000);

        // Calcuate weather parameters for serial and web
        calcWeather(); // Go calc all the various sensors

        // send weather out to serial port
        if (prevtemplm34_1 == templm34_1) // 2 in a row must be the same to send
        {
            Serial.write(0);
            Serial.write(templm34_1);
            Serial.write(templm34_1 ^ 0);
        }

        // send weather out to serial port
        if(prevtemplm34_2 == templm34_2) // 2 in a row must be the same to send
        {
            Serial.write(1);
            Serial.write(templm34_2);
            Serial.write(templm34_2 ^ 1);
        }

        // send weather out to serial port
        if(prevtemplm34_3 == templm34_3) // 2 in a row must be the same to send
        {
            Serial.write(2);
            Serial.write(templm34_3);
            Serial.write(templm34_3 ^ 2);
        }
        delay(2000);

The code for parsing received data is:
int readData ()
{
// There must be at least three available bytes to satisfy the protocol
// Otherwise, wait until three bytes have arrived to read anything
if (Serial.available() >= 3) {

      // Read the next three byte in the serial buffer
      incomingByteOne = Serial.read();
      Serial.write("Byte One: ");
      Serial.write(incomingByteOne);
      Serial.println();
      incomingByteTwo = Serial.read();
      Serial.write("Byte Two: ");
      Serial.write(incomingByteTwo);
      Serial.println();
      incomingByteThree = Serial.read();
      Serial.write("Byte Three: ");
      Serial.write(incomingByteThree);
      Serial.println();

      // XOR the first and second incoming bytes so that the result can be checked against the third error checking byte
      byte xorValue = incomingByteOne ^ incomingByteTwo;
      Serial.write("XOR VALUE: ");
      Serial.write(xorValue);
      Serial.println("Number of Errors: ");
      Serial.println(numberOfErrors);
      Serial.println();
      Serial.println();
      if(xorValue != incomingByteThree) {
        numberOfErrors++; // Add one to the total count of number of errors in transmission
      }
      else {
        // Mask for retrieving the five rightmost bits from incomingByteOne (00011111)
        byte maskForSensorNumber = 0x1f;

        // Shift incomingByteOne right 5 times in order to obtain the three bits representing the unit number
        int unitNumber = incomingByteOne >> 5;

        // AND incomingByteOne with the mask in order to retrieve only the five righmost bits representing the sensor number
        int sensorNumber = incomingByteOne & maskForSensorNumber;

        // Store the data for the correct sensor on the correct unit
        data[unitNumber][sensorNumber] = incomingByteTwo*1;
     }
}
}

What could be causing the transmissions to work fine with delay, but not otherwise?

You are probably just transmitting too fast.
Your receiver is writing at least 80 bytes of debugging information (if
I counted it right) for every 3 bytes of incoming data. Since both input
and debug output happen at the same baud rate, this means the receiver
can only cope with an input data rate equal to 3/80 = 3.75% of
the nominal baud rate.
I would expect no errors at the very beginning of the program run,
because the debugging info is written to a RAM buffer. Only when that
buffer fills up the receiver is slowed down by every Serial.write()
and Serial.println() it performs.

Thanks @EdgarBonet. When I expanded the receiving and transmitting buffers of the receiver unit to 1,024 bytes, I still had errors after just 7 or so transmissions (just under 600 bytes including debugging). Do you think adding delay is probably one of the better ways to fix this?

@tpm900: Yes, or maybe show less debugging info.

I actually only added the debugging after I saw issues with the transmissions. However, I do have approximately 100 writes to a Client (e.g. client.println("..."). Does this also affect the buffer?

I do not know what your client looks like, but it is likely that the println() can block.


text:
Sending Analog Data with and IR LED
This is the idea. I have 2 Arduinos. One with an IR LED and the other with an IR receiver. I want to read the values of multiple sensors and transmit it to the other Arduino via IR. I know how to send data like a fixed HEX code but I dont know how to send values from a potentiometer.
Just think of how a quadcopter sends and receives data from the joysticks, thats somewhat what I want to do.
[EDIT]
This is a precision of what I want to do. I'll read the values of let's say 2 potentiometers, map the values from 0-99, and then I want to send it to the other Arduino with IR and not anything else.

The protocol used by toy IR helicopters has been thoroughly reverse engineered and documented, you should be able to find it with a web search.

Is your question: "How do I send a variable by IR as opposed to a constant?" Or is there more to it?

@NickGammon, yes.

Well, if you can manage with 8-bit data, just send a byte at a time. Otherwise you need some sort of protocol, like <123> and have the receiving end detect the delimiters. That's what the answer by axa said.

Seems to me you first need to establish a protocol.  Could just be a simple one you make up,  with it you will eventually find that repetition and retransmission will need to be explored, and you may want to include things such as a CRC if the application suits it; or not...
As part of the thought process you need to look at your sensors, see how they put out their data, you seem to indicate analog, so that would be read on an a to d converter and that d value might be directly sent as the data part of your chosen protocol.
Or some joysticks packages might have have a I2C or SPI driver built in to which the A to D wouldn't be required.
But using IR you will find timing and validation very important so that the receiver knows where the beginning and end of data is at.
Thinking about it there must some libraries out there already.
Or entirely completed projects to study.
Now you didn't ask but if reliable communication is desired you might want to go wired serial or use a managed protocol like an Ethernet peripheral.