text:
How can I make this button toggle the position of a servo?
I am trying to make something so when I press the button it sets the position of the servo to 50 and then when I press it again, it sets it to 150. The button is momentary not a toggle switch. This is what I have come up with so far. I would also like to account for button bounce. Hope someone can help. Thanks in advance!
#include <Servo.h>

Servo myservo;  // create servo object to control a servo

// variables will change:
int pos = 0; // variable to store the servo position
int buttonState = 0; // variable for reading the pushbutton status
int button_mode = 1; // Variable for the button's current state.
// button_mode = 1 when the button is up, and 0 when the button is pressed.
// This variable is 'static' and persists because it is declared outside a function.

void setup() {
  myservo.attach(8); // attaches the servo on pin 9 to the servo object
  Serial.begin(9600); // Initialize the Serial port at 9600 baud.
  pinMode(9,INPUT); // Set Digital pin 9 to an input so it can monitor the button.
}

void loop() {
  buttonState = digitalRead(9);
  if ((digitalRead(9) == LOW) && (button_mode == 1)) {
    // Check Digital pin 9 to see if it's pressed.
    pos = 150; //set servo position variable to 150
    myservo.write(pos); //set servo postion to 'pos'
    delay(1000); // wait 1 second
    button_mode = 0; // Button was up before, but is pressed now. Set the button to pressed
    Serial.println("Button has been pressed."); // and report that to the serial monitor.
  } else if ((digitalRead(9) == HIGH) && (button_mode == 0)) {
    pos = 50;
    myservo.write(pos);
    delay(1000);
    button_mode = 1; // Button was down before, but is released now. Set the button to
    Serial.println("Button has been released"); // released and report that to the serial monitor.
  }
  delay(100); //small delay to account for button bounce
}

The code is not well structured. Here is what I would do:
if (button_pressed()) { //test to see if button is pressed
  button_state +=1; //increment button
  if (button_stat & 0x01) {//if lsb set
    myservo.write(SERVO_POS1); //set servo position 1
  } else {
    myservo.write(SERVO_POS2); //set servo position 2
  }
}

You can debounce if you wish in button_pressed().

Do something like this:
int angles[2] = {0,180}
bool state = 0;

then:
if(button == PRESSED)
  state = !state;

finnally, to control the servo:
Servo.write(angles[state]);


text:
Serial.print start prints unreadable character without any reason
I wrote the following code. The idea is to execute some AT command on my ESP-01 module. The problem is that first command is execute without problem, the second sometimes but the reply on AT+GMR is the following:
    AT
OK
AT+GMR

AT version:1.1/0.0(May 11 3016 18:09:57)
SDK version:1.5.ar.0
AR)�WS�TZ�j
C�j�L�AZCA�O�C�

FINE

The problem is that, after some thing that I don't understand, the formatting (maybe the baud change?) gone wrong. Then the reply of the following commands became unreadable. Any idea why it happens?
#include <SoftwareSerial.h>
#define DEBUG true
SoftwareSerial wifi(2,3);

void setup() {
   Serial.begin(115200);
   wifi.begin(115200);
   sendCommand("AT\r\n", 2000);
   sendCommand("AT+GMR\r\n",2000);
   sendCommand("AT+CWMODE=2\r\n", 2000);
   sendCommand("AT\r\n", 2000);
   Serial.print("\n\nFINE");
}

void loop() {}

String sendCommand(String cmd, int timeout){
   wifi.print(cmd);
   return readSerial(timeout);
 }

 String readSerial(int timeout){
   long int time = millis();
   String res = "";
   while( (time+timeout) > millis() ){
        while(wifi.available()){
          char c = wifi.read();
           res += c;
        }
    }
    if(DEBUG)
       Serial.print(res);

    return res;
 }

Looks like all that String usage is making mincemeat of your heap...

So I should do not use String? How can I manage string?

Arrays of char. Here is information on how: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

I tried to use a single array of char (http://pastebin.com/K6j5nzdD) but there is no effect on output that is always unreadable after some point.

The problem was about high baud for SoftwareSerial. Changing it to 9600 the problem disappears.

Take a look at the connections check the all the connections properly i also had the same problem

source: Stack Exchange

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

sort: votes


text:
Qduino Mini bricked?
So I have been experimenting with keyboard inputs and I think I may have accidentally put a loop in my code that never actually ends the keyboard input thus not allowing me to upload any sketches to fix the problem.
Here is the error code I got when I tried to upload a blank into the qduino:
Arduino: 1.8.1 (Windows Store 1.8.1.0) (Windows 10), Board: "Qduino Mini"

Build options changed, rebuilding all
Sketch uses 4136 bytes (14%) of program storage space. Maximum is 28672 bytes.
Global variables use 148 bytes (5%) of dynamic memory, leaving 2412 bytes for local variables. Maximum is 2560 bytes.
An error occurred while uploading the sketch
processing.app.SerialException: Error opening serial port 'COM11'.
    at processing.app.Serial.<init>(Serial.java:125)
    at processing.app.Serial.<init>(Serial.java:66)
    at processing.app.SerialMonitor$3.<init>(SerialMonitor.java:93)
    at processing.app.SerialMonitor.open(SerialMonitor.java:93)
    at processing.app.AbstractMonitor.resume(AbstractMonitor.java:110)
    at processing.app.Editor.resumeOrCloseSerialMonitor(Editor.java:2240)
    at processing.app.Editor.access$2400(Editor.java:77)
    at processing.app.Editor$DefaultExportAppHandler.run(Editor.java:2315)
    at java.lang.Thread.run(Thread.java:745)
Caused by: jssc.SerialPortException: Port name - COM11; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.<init>(Serial.java:114)
    ... 8 more
Error opening serial port 'COM11'.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Ok strange, just after posting this the qduino decided to flash a different light on me so I try to upload again and it works... So apperantly just by keeping the qduino connected for some time it will start to work again...

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


text:
Failing to write to SD card using SD.h
Using a knockoff Arduino Nano (pinout seems to be the same), I would like to record data to an external SD card. I have everything hooked up (correctly I think) but I continue to fail to initialize the card using SD.begin().
Here's a snippet of code that I'm running to do this:
//Wire and MS5803_I2C libraries for communicating with the pressure sensor.

#include <Wire.h>
#include <SparkFun_MS5803_I2C.h>
// For the SD card reader.
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

void setup(void) {
  Serial.begin(9600); // Set baud rate.
  pinMode(10, OUTPUT); // Set data output pin for the SD card reader.
  digitalWrite(10, HIGH);
 // see if the card is present and can be initialized:
 if (!SD.begin(10)) {
   Serial.println("Card failed, or not present");
   // don't do anything more:
   return;
 }
 Serial.println("card initialized.");
  delay(500);  // Wait half a second before continuing.
}

void loop(void) {
  Serial.println("Hello Library!");
  delay(100000);
}

Here's the Nano pinout:

And a picture of the circuit.

Which version of the SD library are you using? This can be found at Sketch > Include Library > Manage Libraries... > Filter your search... > SD.

I was running 1.0.8, but I just noticed there was an update. I'll try that out now that the library is updated! Thanks - I didn't know how to do that.

I was asking because there was a bug in 1.1.0 that was causing this sort of problem and was fixed in 1.1.1 but since you were using 1.0.8 that wouldn't have been your issue.

The Sparkfun pressure sensor has a 3.3V chip and a SD memory card is also 3.3V. Your Arduino Nano is probably a 5V board. How did you connect those to the board ?
When your Nano board is 5V, you need a SD module with a level shifter for the signals.
To make it work, test either the SD or the sensor and try to make it work. When testing the SD, don't connect the sensor and don't even include the sensor library.

I've been trying to upload a picture, but it keeps failing on both this site and imgur. Any suggestions? - I might make a schematic later today and upload it. Also, no sensor is currently attached, and this code is much simplified from a larger code-base but you're probably right, I should take out the sensor library for now - good suggestion.

Alright, I added a photo of the setup currently.

Is it my eyes or there's nothing connected to D4...?
const int chipSelect = 4;

Your chipSelect/CS pin seems connected to D10.

Yes, that's a remnant of the previous code. !SD.begin(x) allows for chipSelect to be entered as x. Here I have it as 10, which as far as I can tell is the actual CS on the device. What I'm wondering is if it is !CS and if that is different from the regular Arduinos


text:
How can i provide enough power on an UNO to use the HC-12 wireless module?
Scenario:  The Uno is being powered by USB for programming, and the HC-12 wireless communications module is wired correctly.  But it will not work.
In reading through the web literature, it is mentioned that to use the HC-12 in the high-power (100 mW) mode requires a power supply in excess of what the laptop's USB port will provide.
I am finding nothing on Stackexchange that addresses this issue.
So the question is, how do I get the power to run the Uno with the HC-12?  I need to be able to periodically update the programming and test it while that auxiliary power is applied, and need to know it is safe to do so.

There two options I have found that work well.
First is a simple wall-wart that provides 12 Volts to a barrel connector, like for a CCTV camera.
Or, if I want to run the Uno from a separate higher-amperage USB charging port I have found that there are "USB A Male to CCTV male" cables that work.
Doing the latter means the Uno is running at 5V instead of utilizing the on-board regulator to drop a higher-voltage input, which only matters if your circuit expects to find more than 5 Volts on the Vin pin (although that is not supposed to be an output pin, of course).
Through thorough experimentation I've proven that both methods work.
The best part is that the Uno can easily tolerate having both CCTV-style power and also being plugged into the laptop for programming and testing (like using the serial monitor).
Lesson learned:  The HC-12 simply will not work without auxiliary power, and it is safe to provide such power while also plugging the serial port into a laptop.


text:
Trouble while using Arduino DUE as programmer
I'm trying to use the arduino DUE board as a  AVR Programmer. My target device is atmega328p. After uploading the ArduinoISP into the DUE Board. I've tried to let a pin toggle using the following code:
#define F_CPU 10000000
#include <avr/io.h>
#include <util/delay.h>

int main (){
    DDRD |= (1<< PD7);
    for(;;){
        PORTD ^= (1<< PD7);
        _delay_ms(1000);
    }
    return 0;
}

I want to use the internal oscillator and based this example  I've adjust the makefile:
DEVICE     = atmega328p
CLOCK      = 8000000
PROGRAMMER = -c arduino -P COM10 -b 19200
OBJECTS    = main.o
FUSES      = -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m

the problem that I have is that when run :
make flash

I get the following :

and yes the port COM10 is definitely correct.
does anyone have a suggestion how to solve this ?
thanks in advance !

What are the fuses on the Atmega328P? And does it have a bootloader? You can find out this stuff if you have a spare Uno or similar around.

I'm voting to close this question because questions about avrdude errors that are long abandoned without followup from the asker are effectively unanswerable.

As there's a chance a specific keyword combination will direct people here from Google, I think it's better if it's marked as duplicate, so there's a link on top of the page that contains possible steps to solve this problem.

There error you have is from avrdude failing to get a communication link established to the 'programmer' (which manipulates the target.)
Here is a link that may help with the connection
Stk500 error
Here is another relative link that may help
Arduino ISP on DUE
Best of luck.


text:
Why is integer-to-string not working in this sketch?
I am using a Pro Mini to read analog values and to send them via serial.
Goal of the sketch is to stream these values to Serial as fast as possible, to obtain a steady stream of at least 1000 readings per second. For this reason I reduced the ADC prescaler and I increased serial speed.
I tested sending binary values with Serial.write and it works (it's the fastest), I tested Serial.print (it's the slowest), and I tested an optimised conversion integer-to-string (found on StackOverflow) in association with Serial.write.
This optimised conversion is faster than Serial.print (it would allow me to send the full strings within the given timeframe), but it gives me wrong values. I cannot understand why it happens, the code looks fine to my not-so-expert eye.
A correct stream as sent by Serial.print would be (spaces added for clarity):
3075 \t 2800 \t 4132 \n

"Wrong values" means that the last value gets repeated for all the three columns:
4132 \t 4132 \t 4132 \n

What is the issue in my code regarding the int2str conversion?
Since I cannot get one measurement taken and sent every 500 us, I would like to use the optimised routine to get plaintext readings at 1000 us intervals.
The source code follows. I cut out the function slimADC because it was tested as working, while I left all the 3 methods for sending data via serial: binary, optimised, Serial.print.
#include <digitalWriteFast.h>

volatile unsigned long previousMicros, currentMicros;

#define SAMPLES 8
volatile unsigned int valuesX;
volatile unsigned int valuesY;
volatile unsigned int valuesZ;

char* x;
char* y;
char* z;

void setup() {
// set pins, ADC prescaler and initialise ADC
  pinModeFast(A0, INPUT);
  pinModeFast(A1, INPUT);
  pinModeFast(A2, INPUT);
  ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear bits
  ADCSRA |= bit (ADPS0) | bit (ADPS2);  // 32: 32 us per ADC
  slimADC(0);
  slimADC(0);

// initialise Serial
  Serial.begin(250000);
  Serial.write("\n");
  Serial.write("\n");
  previousMicros = 0;
}

void loop() {
  currentMicros = micros();
  if ((currentMicros - previousMicros) < 1000) { return; }
  previousMicros = currentMicros;

// ADC readings, repeated SAMPLES times
  valuesX = 0;
  valuesY = 0;
  valuesZ = 0;
  for (uint8_t i = 1; i < SAMPLES; i++) {  // 8*3*32=768 us
    valuesX += slimADC(0);
    valuesY += slimADC(1);
    valuesZ += slimADC(2);
  }

// SERIAL TRANSMISSION

// fastest
//  Serial.write(valuesX / 256);
//  Serial.write(valuesX % 256);
//  Serial.write("\t");
//  Serial.write(valuesY / 256);
//  Serial.write(valuesY % 256);
//  Serial.write("\t");
//  Serial.write(valuesZ / 256);
//  Serial.write(valuesZ % 256);
//  Serial.write("\n");

// good
  x = int2str( valuesX );
  y = int2str( valuesY );
  z = int2str( valuesZ );
  Serial.write(x);
  Serial.write("\t");
  Serial.write(y);
  Serial.write("\t");
  Serial.write(z);
  Serial.write("\n");

// slowest
//  Serial.print(valuesX);
//  Serial.print("\t");
//  Serial.print(valuesY);
//  Serial.print("\t");
//  Serial.print(valuesZ);
//  Serial.print("\n");
}

static int slimADC(uint8_t pin) { ... }

char _int2str[7];
char* int2str( register int i ) {
  register unsigned char L = 1;
  register char c;
  register boolean m = false;
  register char b;  // lower-byte of i
  // negative
  if ( i < 0 ) {
    _int2str[ 0 ] = '-';
    i = -i;
  }
  else L = 0;
  // ten-thousands
  if( i > 9999 ) {
    c = i < 20000 ? 1
      : i < 30000 ? 2
      : 3;
    _int2str[ L++ ] = c + 48;
    i -= c * 10000;
    m = true;
  }
  // thousands
  if( i > 999 ) {
    c = i < 5000
      ? ( i < 3000
          ? ( i < 2000 ? 1 : 2 )
          :   i < 4000 ? 3 : 4
        )
      : i < 8000
        ? ( i < 6000
            ? 5
            : i < 7000 ? 6 : 7
          )
        : i < 9000 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    i -= c * 1000;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // hundreds
  if( i > 99 ) {
    c = i < 500
      ? ( i < 300
          ? ( i < 200 ? 1 : 2 )
          :   i < 400 ? 3 : 4
        )
      : i < 800
        ? ( i < 600
            ? 5
            : i < 700 ? 6 : 7
          )
        : i < 900 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    i -= c * 100;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // decades (check on lower byte to optimize code)
  b = char( i );
  if( b > 9 ) {
    c = b < 50
      ? ( b < 30
          ? ( b < 20 ? 1 : 2 )
          :   b < 40 ? 3 : 4
        )
      : b < 80
        ? ( i < 60
            ? 5
            : i < 70 ? 6 : 7
          )
        : i < 90 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    b -= c * 10;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // last digit
  _int2str[ L++ ] = b + 48;
  // null terminator
  _int2str[ L ] = 0;
  return _int2str;
}

Appendix
The bare ADC conversions take about 768 us.
With binary data I am sending via serial 3x uint16_t plus one end of line and two tabs, meaning 9 characters per reading. At 250 kbps 8N1 the minimum time required is 324 us. Using RealTerm (for Win) I can see that I get a stram of 9k chars/s, as expected.
With Serial.print I am sending 4x string[4] (readings are always between 1000 and 9999), plus tabs and newline, meaning 15 bytes per reading. RealTerm however gives me an incoming stream of 11-12k chars/s, therefore Serial.print is too slow.
The optimised int-to-string function (even without modifying it to avoid checking for negative and for >9999, not needed in my case) still sends 15 bytes per reading, and RealTerm also shows me an actual stream of 15k chars/s, as expected.

Here is a benchmark that you might find interesting; https://github.com/mikaelpatel/Cosa/blob/master/examples/Benchmarks/CosaBenchmarkDataLogger/CosaBenchmarkDataLogger.ino It tries to answer the question if 4K ADC samples (and number conversions) per second is possible.

Well I already have 24 samples (768 us) and 3 number conversions (not sure how long they take) per millisecond. Not that different. I could probably double the conversions if I reduce the number of samples (I'm taking 8 per channel), but first I want to get the rest right :) But thanks for sharing, I starred that project for future reference. I will study it if possible.

@MikaelPatel yep, with 4 samples per acquisition and using a binary stream I get 18k chars received on the PC side for a 500 us period. It's 24 ADC conversions (3234=384 us) and 18 chars sent (9*10/250000=360 us) per millisecond!

Unfortunately with such fast serial I cannot afford to use ADC noise reduction (it would stop the IO clock used by USART), but it's not important right now.

3 number conversions (not sure how long they take). approximately 300 - 320 ticks per conversion. or 20us @ 16MIPS.

It's 24 ADC conversions (3234=384 us). try to run the adc in free-running model. you can enable the adc interrupt so the data is automatically saved in a buffer for you.

@dannyf In this specific case the time budget I have (500 us) seems to be enough for my requirements, so no need to spend more time on optimization. I will use the free running ADC for the final project (this is an intermediate step).

it took me a while and i'm still not 100% sure if I got you right. I think you have two questions:

1) how to speed up the entire execution?

the serial routines will be your biggest bottleneck. I would suggest that a) you speed up the baud rate; and b) you try to use a tx interrupt here.

2) why isn't the int2str() routine working?

because int2str() stores the converted string in a buffer (_int2str[]), which is subsequently destroyed by conversions. so for it to work, you should do something like this:
  serial.write(int2str(x)); serial.write("\t");
  serial.write(int2str(y)); serial.write("\t");
  serial.write(int2str(z)); serial.write("\n");

BTW, int2str() can be written a lot better than it is now.
edit: to add an alternate int2str() implementaton.
//positive and negative numbers
//int is 16-bit type
char *int2str2(int i) {
    static char _int2str[7];
    unsigned char tmp, str_len=0;       //converted string starts at _int2str[0]

    //process the sign
    if (i&0x8000/*<0*/) {
      _int2str[str_len++]='-';          //insert leading '-'
      i=-i;                             //make the number positive
    };

    //convert the next position (10,000)
    tmp = 0;                            //reset tmp
    while (i >= 10000) {
      i-=10000;                         //decrement i
      tmp+=1;                           //increment counter
    }
    _int2str[str_len++] = tmp + '0';    //form the msb

    //convert the next position (1,000)
    tmp = 0;                            //reset tmp
    while (i >= 1000) {
      i-=1000;                          //decrement i
      tmp+=1;                           //increment counter
    }
    _int2str[str_len++] = tmp + '0';    //form the msb

    //convert the next position (100)
    tmp = 0;                            //reset tmp
    while (i >= 100) {
      i-=100;                           //decrement i
      tmp+=1;                           //increment counter
    }
    _int2str[str_len++] = tmp + '0';    //form the msb

    //convert the next position (10)
    tmp = 0;                            //reset tmp
    while (i >= 10) {
      i-=10;                            //decrement i
      tmp+=1;                           //increment counter
    }
    _int2str[str_len++] = tmp + '0';    //form the msb

    //convert the lsb
    //tmp = 0;                          //reset tmp
    //while (i >= 100000ul) {
    //  i-=100000ul;                        //decrement i
    //  tmp+=1;                         //increment counter
    //}
    tmp = i;
    _int2str[str_len++] = tmp + '0';    //form the msb

    return _int2str;
}

here is what I would use. I benchmark against yours, converting numbers from 0 to 32767. total cycle count for yours is 10.5 million and 7.0 million for mine. Now, the actual performance will depend on a lot of factors, like your chips, compilers (I used IAR AVR), and optimization settings, to name a few.
Note: the routine was written as a generic one. if you are only converting 10-bit numbers (from a 10-bit adc for example), it can be greatly simplified, and execution time greatly shortened: <160K cumulative cycles converting numbers from 0 to 1023.

Part 2) was my actual question and your explanation is clear, I corrected my code and accepted your answer. Part 1) was more side information I put there to let the reader understand what I'm doing, I didn't expect any answer or significant improvements there. But thanks for letting me know about TX interrupts. Isn't Arduino using hardware UART (and interrupts) already? see https://www.arduino.cc/en/Reference/softwareSerial Concerning int2str: it's using basically the bisection method, I thought it was already quite efficient. Do you have a link for a better version? I'm quite beginner.

the arduino uses the hardware uart module in the avr. but uses polling in its transmission -> they want for the prior transmission to end before sending the next. the usr of isr would have allowed the mcu to do other things which uart is transmitting.

I understand how your conversion routine works, but I'm not sure why it is faster. On average you have 5 comparisons, 11 sums, 11 value assignments per decade, while the old one has 3 comparison, 2 sums, 1 multiplication (hardware in ATmegas) and 3 assignments. On my atmega328p I measured (0 to 32767) 311072 us for the old one and 325656 us for yours. avr-gcc 4.9.2 and following options: -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328. I guess that on ATtiny yours would be faster, since hardware multiplication is missing.


text:
LCD displays wrong temperature
Hi I have a program that does not work right as I aspect:
v = tempC;
h = tempC * 10;
h = h % 10;
memset(stempCA, 0, sizeof(stempCA));
sprintf(stempCA, "%+.2d.%d", v, h);

it works fine on positive temperature "+11.22"
but not for negative values : "-02.-1"
where is my mistake?
 thanx

where is my mistake? test the temperature first to see if it is negative or positive. your code works for positive temperatures only.

I think, that -1%10=-1, not 9 as you would like. I use
if (tempC<0) {print'-';tempC=-tempC;};
print tempC as usual for positive numbers

no , I put it in a Buffer for LCD display, I don't use print :                                                                 sprintf(Buffer2, "U:%s A:%s",  stempCU, stempCA);

Got i myself:                                                                                sprintf(stempCA, "%+.2d.%d", v, abs(h));


text:
How to setup HC05 Module to be distinguishable
I'm not sure if this is a dumb question, but here goes  :
I am developing an Android app that uses a custom Bluetooth device as a companion. I'm using an HC05 module to interface the device with my app. What I need is a way for me to distinguish my HC05 module from, say, some other HC05 module that might be in range.
The obvious way of doing this would be to set the device name in a certain format. But I was wondering if there was a more better approach to this.
On searching, I found that UUID's are used for a similar purpose (i.e. service discovery), but I couldn't find any further info. Is it at all possible to set a custom UUID for the HC05 module so that I can filter devices in my Android app based on that?

AFAIK not directly, but I don't think you connect to the HC05 just to say "Hey, I'm here". You should have something attached to the HC05 serial port. What you can implement is a sort of identification command (like they always do for AT modems). For instance, when you connect you send "?" (or "ATI" like in modems) and it returns you "ShahiM's Bluetooth companion v1.05" or whatever string you prefer. This way you just have to ask him this. In the same way you can ask for a UUID (note that unique implies flashing a different value on each prototype or using hardware UUID memories)

And, by the way, there's no such thing as a stupid question

Your options are:

As you guessed, you could set the name with AT+NAME=, and only use the names matching some pattern. It would work if you're only user so you just want to ignore other BT devices, but is problematic if you're having multiple independent users (each with its different set of *HC05*s) who might be in range (you could set different pattern for each user, though).
build a database of addresses (read-only with AT+ADDR?), and only access those devices that are belonging to that user. It would avoid problem above with multiple users, but would require some logistics on your part (for example, when you sell user the app and HC05s, in the registration process you'll need to assign exactly which HC05 address that user my access. Or you might want to allow user to pick which devices are his, by having him specify specify PIN for pairing set with AT+PSWD=)
third way is to use custom Inquire Access Code instead of GIAC so only that set of devices is scanned. HC05 allows setting it with AT+IAC=. However, as it is more complex and nonstandard that (2), and you'd probably still need to registration to differentiate which user is allowed which IAC, I'd recommend you do (2) instead.

As frarugi87 recommended in the comments, you need to change the device's name. Changing the device name will allow you to identify it by a custom name that you come up with. To do this you need to use something called AT Commands. Here is a guide that contains many of the system parameters that you can check and change via AT Commands: http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/?ALLSTEPS
Here is a brief summary about how to change the device name, quoted from the above Instructable:
First switch the device into command mode

For the HC-05 module to switch to AT command mode, the HC-05 pin 34
  (often referred to as the Key pin) needs to pulled HIGH but in a
  certain order of events explained below. When the HC-05 enters the AT
  command mode, it will communicate at 38400 baud rate. Follow these
  steps in the stated order to switch to the HC-05 to AT command mode.

Wire the HC-05 and Arduino Uno per instructions.
BEFORE YOU CONNECT THE ARDUINO TO THE USB remove the VCC (power) red wire from the HC-05 so it's not getting any power from the
  Arduino. All other wires are still connected.
Now connect the Arduino Uno to the USB cable extended from your PC.
Make sure the HC-05 module is NOT PAIRED with any other Bluetooth device.
Re-connect the Arduino Uno 5V wire to the HC-05's VCC (5V power) pin.
The HC-05 LED will blink on and off at about 2 second intervals. Now the HC-05 is in AT command mode ready to accept commands to change
  configuration and settings.
To test if everything is wired correctly,  open the Serial Monitor from the 8. Arduino IDE and type "AT" and click SEND. You should see
  an "OK" If you don't see an "OK" check your wiring.

Next run this program on your Arduino
/*

AUTHOR: Hazim Bitar (techbitar)
DATE: Aug 29, 2013
LICENSE: Public domain (use at your own risk)
CONTACT: techbitar at gmail dot com (techbitar.com)

*/

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

Finally (the quotes aren't part of the command)

To change device name from the default HC-05 to let's say MYBLUE
  enter: "AT+NAME=MYBLUE"

This answer has been copied from a site. It shouldn't be allowed to collect this bounty.

I disagree. I know about bluetooth chips from past experiences, but I have never worked with the HC-05 so I had to look up how to put it in command mode. Then I summarized the article as it directly relates to the question. I think this should qualify for the bounty as I answered the question.

Joel has given attribution, and he would be told off for posting a link-only answer, so I think this is OK. If another person posts an answer which is accepted by the OP then that answer would collect the bounty.

Yes. I know changing the Device name is possible. My question was whether if there are any other methods.

Why do you need other methods? Are there any limitations, or application specifics that prevent you from changing the name? This will help give me more context for the answer.


text:
Arduino read PWM duty cycle value with input (analog / digital)
I am working on comparing autopilots like Ardupilot, CC3D, KK2.1.5. The comparision is about system reactions/behaviors that it gives during flight. For this purpose, I need to read the PWM duty cycle (like osilascopes - the PWM frequency can be vary from 50 to 430 Hz) values from autopilot card. There are 4 command input PWMs and 4 esc control PWMs for a typical quadrotor. I have to read 8 duty cycle values with digital/analog input pins. How do I measure duty cycle of 8 PWM signals?  Also, is digital or analogue measurement precise and faster?
Note about attachInterrupt command: According to arduino.cc AtMega328 series have 2 interrupts, Arduino ATmega 2560 series have 7 interrupts.

The code shown in my answer to question 18183, “Read RC receiver channels using Interrupt instead of PulseIn”. That answer has code to read four channels of RC PWM.  It can easily be adapted to work with eight channels.  It has an ISR that runs when selected pins change.  It sorts out which channel(s) changed, and stores the value of micros() at each change.
Also see my answer to question 19106, “Can external interrupts be OR'd together on the '328 (Uno)?”  That answer includes a sketch for generating appropriate ISR code.  My answer to question 32572, “How to detect the direction of a rotary encoder?”, shows another instance.
Digital input, as used in the code mentioned above, takes under  a microsecond ten microseconds in the ISR.  As noted in dannyf's comment, unrolling the for loop and (where possible) using constants instead of variables can reduce the in-ISR time to 3.4 μs.  Note, ISR entry and exit still add several microseconds.
10-bit analog input, on the other hand, will take around 104 microseconds per reading, a time comparable to some of the pulse widths you'll be measuring.  So it isn't fast enough.  If degraded ADC accuracy is acceptable, decreasing the ADC-clock scale factor as explained in a webpage at microsmart.co.za can get AD conversion time down to 20 μs.  This is around three times as long as digital input takes, so rather slow.

takes under a microsecond in the ISR, I find that unlikely. Obviously, I'm not sure which code pieces you were talking about - as they are three of them. but a causal look on them would suggest that it will take more than 16 ticks to execute the body of the ISR - not counting the overhead. As a matter of fact, a little birdie of mine said that it would take close to 8us to execute them on an Uno, :)

@dannyf, I was looking at one of the simpler ISRs (single encoder counting) when I wrote that, so will need to edit answer with correct time.  Sorry!

not a problem. two suggestions: 1) unroll the while loop; 2) use constants rather than variables. and I would also make rcOld a static inside the ISR so the code is more modular. with that, I got the execution time down to 3.4us.

Can you share your code instead of links. Also, AtMega328 series have 2 interrupts, Arduino ATmega 2560 series have 7 interrupts. So how can I measure 8 simultaneus PWM signals? https://www.arduino.cc/en/Reference/attachInterrupt

@acs, ATmega328's have 26 different interrupt vectors.  The vectors used in the referenced code are for pin change interrupts, or PCINTs, which use 3 of those vectors.   PCINTs are available on 22 of the  ATmega328-based-Nano pins, and a similar number on Uno's.  Please refer to the code shown in the previous questions -- at the moment I have work deadlines to meet.

@jwpat7 This link says there are only 3 interrupt vector ==> http://playground.arduino.cc/Main/PinChangeInterrupt  So, how did you do this possible? I couldn't find any solution. Please share your code.

@acs, Are you unable to follow the links and look at other questions on Arduino stackexchange?  In particular, see my answer to question 18183, linked in first line of answer above.  That code handles 4 RC inputs and can be adapted for as many as there are pins for.  ¶  Note, each of the 3 PCI vectors has 8 pins assigned to it.   ISRs can read ports and figure out which bits changed.  ¶   I have some 8-RC-inputs code (adaptation of that shown in answer to 18183) that I can post after some more  work deadlines; a couple of days from now.

if done in analog, run the pwm through a lpf and perform an adc on the output;
if done in digital, use a timer's capture function, or use external interrupt / pin change interrupt to capture the timing off a time base.


text:
Why adding a LED between Pin 3 and Ground causes LCD display not to show text?
For a project of mine I am programming an Arduino UNO to show information I get from some sensors on an LCD display.
As a first step I setup Arduino to show "Hello, world!" on the LCD, which worked.

For "decorative" reasons I wanted to add some LEDs between the resistors that I placed in series between PIN 3 (V0) of the LCD and ground (about 1.5K Ohm total resistance).
I first of all added one LED between the last resistor and ground. To my surprise this causes the LCD display not to show "Hello, world!" any more.
As you can see the current is flowing (the LED is lit), but I can't understand why the LCD does not show the text.

Can you help me understand what's going on? I know very little of electronics and I am learning it by doing, so I would appreciate an answer that is good for a beginner!

In a typical 1602 LCD pinout, pin 3 or V0 is the contrast setting for the display.  It usually is set to a voltage near ground, often by using a 10K pot with ends connected to Vdd and Vss with wiper to V0.
By putting an LED in series with your resistors (that apparently go to ground) you've either disconnected V0 from ground or have raised its voltage by the LED voltage.  This reduces contrast to the point that characters aren't visible even though they are on the display.
The LED backlight remains on and at the same brightness as before because it is driven via pins 15 and 16, independent of all other display settings.
Edit 1: I haven't duplicated your circuit to take measurements, so at the moment don't know for sure; but (in resistors-only case) V0 from pin 3 on the 1602 LCD board apparently sources some small current through your 1500 Ω to ground.  When you add an LED it can disconnect V0 from ground or can raise its voltage by the LED voltage, as follows:  firstly, if the LED cathode faces V0 and V0 is positive, no current will flow through the diode, thus disconnecting V0.  Secondly, if the LED anode faces V0 and V0 is positive, current will flow through the LED.  If the LED lights at all, most of its Vf characteristic voltage (typically between 3 and 4 volts for a green LED) will appear across it.  Thus, V0 sits at close to Vf plus whatever drops across the resistors.
*The same as for other diodes, LED forward current increases exponentially with voltage (Ref: wikipedia on LED physics) hence voltage change is tiny over large changes in current when an LED is emitting light.  In other words, if the LED is lighting up, its voltage will be close (ie within a few dozen millivolts) to its characteristic band gap voltage.  See petervis.com's led-resistor-calculator for a "Chart by Colour" that shows characteristic Vf forward voltages.

@jwat7 first of all thanks for the answer but there are still some tgings I don't understand.. How could pitting the led in series disconnect V0 from the ground? And how would adding it could possibly raise the voltage? Thanks again!

@lucacerone See edit 1

Can you help me understand what's going on?

that pin controls the contrast and it needs to be 3.5 - 4.x volt (typical) below Vcc. an led in conduction would drop 2 - 3v, depending on the led, making that pin's potential much closer to Vcc -> minimum contrast so you cannot see the text being displayed.

thanks for your answer! In order for the led to cause a drop in voltage shouldn't it's resistance be quite high? I can add a 1k ohm resistor in series and still get enough contrast to read the text. Or are there other ways by which the led can cause the voltage drop?


text:
What does an arduino sketch translate to before compilation?
I've been experimenting with Arduino on both esp8266 and AVR chips. The structure of the .ino file usually looks like this:
#include "Arduino.h"
#include "ESP8266WiFi.h"
##Some includes

void setup()
{
...
##Will be only run once at the begining.
}

void loop()
{
##Runs this code in a constant loop
}

My assumption is that somewhere behind simplification, before the compilation takes place, there is a full blown source file. It includes the platform specific initialization and contains the calls to setup() and loop(). When I say full blown source file I mean something that can be passed to the compiler and will compile given that the dependencies are met.
My questions are:

Is this assumption correct?
If so, can someone share an example on how does the full blown source file look like, and where did you get it from?

https://www.arduino.cc/en/Hacking/BuildProcess

The Arduino core libraries (which are nothing more than a bunch of C/C++ files - there is no such thing as the "Arduino" programming language), are compiled along with your source code. These files include all of the initialisation routines and function definitions for things like digitalWrite and so forth.
There is a main.cpp file that gets compiled which is pretty much nothing more than:
#include "Arduino.h"

int main(void) {
    //Initialise timers and things (internal)
    init();
    //Your initialisation stuff (setup)
    setup();
    //Loop forever
    for (;;) {
        //Calling your loop function
        loop();
    }
}

In terms of what your .ino file becomes, it is basically just copied to a temporary build directory and renamed to .cpp. There are some minor changes made, which is basically to just copy all of the function declarations and place them at the top of the file.
This process is actually why if you use your own header file which has some typedef in it which you then use in a function call, the code will break because the declarations get added above the #include statements meaning the custom type is used before it is defined.
If you go to the preferences you can tell it to enable verbosity during compilation. This will actually show you exactly what is being compiled. It will also give you the path to the temporary build directory in which you will find the .cpp file with the same name as your .ino file.

There are some minor changes made, which is basically to just copy all of the function declarations and place them at the top of the file.  So the .ino file acts somewhat of a library. Makes sense. Will try to get to the main.cpp and expand your answer with the example after which I'll accept it.

Seems a little redundant to use "adruino" language, which then becomes C anyway.

@Serg despite what their website says, and the grand arguments about it, there is no such thing as the "Arduino" programming language, all it is is C++ with a little bit of badly conceived pre-processing.

@TomCarpenter I know, and that's exactly my point - why go to trouble of reinventing the wheel, when they could have just let people work in C/C++ directly ?

C++ (the actual language/compiler that is used) is a multiple-compilation-unit language. There is no single source file, but rather a bundle of compiled source files, that are linked together to create the executable (or downloadable image).
In you case the user sketch provides the setup() and loop() functions, which are called from another source file, which is provided by the Arduino IDE.


text:
Slowly increase speed using PWM arduino
I'm trying to control the speed of a DC motor using PWM. Here is my code so far:
int motor = 9;
int fadeValue = 5;

void setup() {
  pinMode(motor, OUTPUT);
}

void loop() {
  for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
    analogWrite(motor, fadeValue);
    delay(100);
  if (fadeValue==245) {
    fadeValue=255;
    break;
  }
}

I want the motor to slowly increase it speed then stay high. However, the loop keep repeating.
Thanks in advance guys.

Your code is very creative. We're missing the part where loop() is called...

I believe the Arduino compiler abstracts away the main() function. The loop() function is automatically called continuously. Also, this question probably belongs in the Arduino SE.

Here's the Arduino AVR Boards loop() call: https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/cores/arduino/main.cpp#L46

If you dont want the code to repeat at the maximum, just add a condition to the loop. Your solution could look like this:
int fadeValue = 5;

void loop()
{
    if (fadeValue < 255)
    {
        if (fadeValue >= 245)
        {
            fadeValue = 255;
        }
        else
        {
            fadeValue++;
        }
        analogWrite(motor, fadeValue);
        delay(100);
    }

    //Other code here
}

By setting FadeValue to another value, the fade will start again from the new value until the maximum.

Thanks, ill try this out first and come back with the result

Could you also change the order the loop is in? So the code would look like this instead:
void loop() {
  if (fadeValue == 245) {
    fadeValue=255;
    analogWrite(motor, fadeValue);  // motor will stay at highest value
    }
  else {
      for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
        analogWrite(motor, fadeValue);
        delay(100);
        }
  }
}

So now, the loop will run until fadeValue == 245, at which point the loop will not advance to the for loop because the "if" in the if/else statement is satisfied. I'm not actually sure if this will work, but it's an idea.

So now, the loop will run until fadeValue == 245 - no, it will run until fadeValue is greater than 245 which means the test for it being equal to 245 at the start of loop won't be met.

However, the loop keep repeating.

That's the whole point of loop(). If you want some code to run only once after the program starts put it in setup():
int motor = 9;
int fadeValue = 5;

void setup() {
  pinMode(motor, OUTPUT);

  for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
    analogWrite(motor, fadeValue);
    delay(100);
    if (fadeValue == 245)
    {
      fadeValue = 255;
      break;
    }
  }
}

void loop() {
}

Why does it eat my code indentation after I submit the answer? Annoying, I haven't experienced that on other SE sites.

but i will add a button to it, For example if the button is press the motor pwm start from 0 to 255. then stay 255 till i stop it.
If i put it in void setup() it wont be able to do that.

@zuzu -- you should put all the details of what you need in the question to avoid unnecessary answers...

it can be put in the loop(): putting it in the setup(), if the speed-up period is long, isn't practical or feasible in some applications.
you can use a loop counter or time counter to slow down the ramp-up without tying down the mcu, like this:
  time_now = time(); //take a reading of current time. or millies()
  if (time_now < TIME_RAMPUP) { //still need to ramp it up
    if (time_now > time_prev) { //need to increment motor speed
      time_prev+=TIME_INC;
      motor_dc+=PWM_STEP;  // you may wish to bound the dc here
      analogWrite(MOTOR_PIN, motor_dc); //increase dc
    }
  }

If you want void loop() to only run once and don't want to put your code into setup() for some odd reason, just as an infinite while loop at the end with a delay inside like this:
void loop()
{
  for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10)
{
    analogWrite(motor, fadeValue);
    delay(100);
  if (fadeValue==245)
{
    fadeValue=255;
    break;
  }

While(1)
    Delay(1000);

}


text:
Delay between multiple analogReads
I'm trying to read 4 analog inputs (1kHz speed). I changed the prescaler to 16 for my Arduino Leonardo according to this link. I then tried to read the analog pins and I used the following code to display the time and the readings:

#define FASTADC 1
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
double t = 0;
void setup() {
  int start;
  int i;
  #if FASTADC
  // set prescale to 16
  sbi(ADCSRA, ADPS2);
  cbi(ADCSRA, ADPS1);
  cbi(ADCSRA, ADPS0);
  #endif

  Serial.begin(9600);
  Serial.print("ADCTEST: ");
  start = millis();
  for (i = 0 ; i < 1000 ; i++)
    analogRead(0);
  Serial.print(millis() - start);
  Serial.println(" msec (1000 calls)");
}

// the loop routine runs over and over again forever:
void loop() {
  // print out the value you read:
  t = millis() / 1000;
  Serial.print(t);
  Serial.print('\t');
  Serial.print(analogRead(A0)); delay(1);
  Serial.print('\t');
  Serial.print(analogRead(A1)); delay(1);
  Serial.print('\t');
  Serial.print(analogRead(A2)); delay(1);
  Serial.print('\t');
  Serial.println(analogRead(A3)); delay(1);
}

I connected 2V from the DC supply to all the 4 channels and the readings were similar. I used the output from the serial monitor and pasted the readings for 1 sec in Excel to see the frequency. With a 9600 baud rate and no delay between the readings I got 200 Hz (for the 4 analog inputs).
Why is that happening? And is there a relationship between the sampling frequency and the baud rate? Is my way of finding the frequency correct? If not what's the right way?
Finally, I'll be plotting the readings in Matlab, so I guess this will affect the sampling frequency. How can I control it so that I'm sampling with 1kHz rate for all the channels?
Here is the screenshot of the readings from the 4 channels (2V input).

Summarizing everything, I need to know the following:

The effect of adding a delay between every two readings on the accuracy of the readings and the sampling frequency.
How to find the best sampling frequency for every input and how to control it?
Will using Matlab to plot the data affect the sampling frequency?

Thanks.
EDIT: I accepted the answer below, if anyone has the same problem , please make sure that you change the prescaler as I mentioned above for the best results.

Taking a reading on a floating pin is meaningless. You can get anything. Please, connect something to the pins before doing the experiment.

At first I thought that the main problem was not that you too slow at sampling, but that you were too slow at transmitting the data. As Edgar already stated, at 9600 b/s you need 22.88ms to send a line, so the maximum frequency is less than 50Hz.
However as you experienced, the speed you are getting is 200Hz. This is because that calculation is right in the case of a real serial interface. Arduino Leonardo, on the other hand, emulates the serial interface. But.. There is no such thing as baud rate. If you look at the CDC emulation source code you will see that the baud rate you pass to the begin function is ignored.
So... Why is it still slow? Because you are using the delay function! You are waiting for 1ms every time you perform an acquisition, and then you still have to perform all the sending. This has two errors embedded: 1) using the delay function breaks the timing - better use a timer - and 2) you are too slow.
Now, if you want a 1kHz sampling (or any delay multiple of 1ms) you already have a timer running (so you can just use that):
#define INTERVAL_LENGTH_US 1000UL

unsigned long previousMicros;

void loop()
{
    unsigned long currentMicros = micros();

    if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
    {
        previousMicros += INTERVAL_LENGTH_US;

        int val_a0 = analogRead(A0);
        int val_a1 = analogRead(A1);
        int val_a2 = analogRead(A2);
        int val_a3 = analogRead(A3);

        Serial.print(((double)currentMicros) / 1000000UL, 1); // 1 is the number of decimals to print
        Serial.print('\t');
        Serial.print(val_a0);
        Serial.print('\t');
        Serial.print(val_a1);

        Serial.print('\t');
        Serial.print(val_a2);
        Serial.print('\t');
        Serial.println(val_a3);
    }
}

NOTE: The millis() function is replaced by micros() according to Edgar's and Nick's comments.
Change just the define to change the sample time. Now its set to 1000us (i.e. 1ms, so 1kHz), but don't go much higher otherwise you will have to check accurately the sampling time and the transfer speed. The t variable is not needed anymore.
Just a side note: this will also fix the bug in your code that prevents the program to display the current timing (instead of printing 2.5 it prints 2.0).
If you need a faster sample rate you should use another timer to get the correct timing, but again avoid delays. Not needed anymore

Note that millis() sometimes skips a millisecond, e.g. it jumps from 41 straight to 43. You can use micros() instead of millis() to avoid the problem: it gives a 4 µs resolution.

@EdgarBonet this sounds new to me... What are the cases when it skips (apart from when your loop code actually is longer than 1ms)?

On the 16 KHz AVRs, the millis counter is updated every 1024 µs: the millisecond count is incremented by one and the fractional count is incremented by 3 125ths of a millisecond. Whenever this fraction reaches a full millisecond, the millisecond count is incremented by two instead of one. This happens roughly once every 1000/24 ≈ 41.67 updates.

@frarugi87 I tried your code and it's working! I needed a way to fix my sampling rate and this does it. As you said, the baud rate doesn't affect anything. I tried 9600 and 250000 and both gave me 1kHz. Recieving the readings in Matlab instead of the serial monitor won't affect the frequency right?

@frarugi87 Edgar Bonet is right, I cover this issue here. As Edgar said, because of the timer prescaler, the millis "tick" is actually slightly slow. The code adjusts for that every 41/42 updates.

@EdgarBonet I make a (quick) search on google and couldn't find this behavior, so I tested it and... Well, 42 can be the Ultimate Answer to Life, The Universe and Everything, but not for millis... Thank you for pointing this out: I updated the answer with the code I think fixes this (so micros() / prescaler)

@NickGammon I read a lot of wonderful replies on SO and here by you, but I didn't know you had a forum where you put a lot of things. Thank you for your link: I'll read your website

@Isra please update the code with the one in the answer, since it fixes Edgar's issue. This one is a bit more flexible than the previous one and updates exactly (well, more exactly than millis) every ms. As for matlab, the data source is the same, so the speed is the same, provided that matlab is fast enough to read all the data

thank you @frarugi87 for pointing that out, I fixed it. But when I read the serial data in matlab, it gives me this error "Warning: Unsuccessful read: A timeout occurred before the Terminator was reached.. " Do you have an idea on why is that happening? I'm using fscanf(s, '%d')*(5.0 / 1023.0)); to read the values. One last point, if the analog readings are 10 bits wide, how is that transmitted ? I know serial communication's data width is only 8 bits (I set the baud rate to 250000 on both ends just in case)

While replacing millis() with micros(), you introduced an erroneous division by INTERVAL_LENGTH_US. I took the liberty to edit your code to restore its previous logic, which was good. Note that the test if (((currentMicros - previousMicros) / INTERVAL_LENGTH_US) > 0) is not technically wrong, and the compiler would optimize it into if (currentMicros - previousMicros >= INTERVAL_LENGTH_US) anyway. But I think it's clearer without the division. @Isra: you may try this new version.

@EdgarBonet I already noticed that, and fixed it as you fixed before writing the comments, but maybe I made a mess with the back button in the browser and the old version remained online. Thank you for fixing it...

@EdgarBonet Thanks very much, I tried it but I still get the same error: "Warning: Unsuccessful read: The input buffer was filled before the Terminator was reached.. " I've tried reading the pins with the regular rate and I was able to read it in matlab. This error shows up only when I set the rate to 1kHz.

@Isra try to use a step by step approach: first open and read only the strings you receive (with fscanf(s)), then read the integer value and finally convert and use it. See when you block and try to find a solution (I'm not very much into  matlab's serial port interface, so I don't know how to debug it properly). As for the 10 bits, well you are printing to serial, so the value you receive (for instance 1001) is transferred in ascii coding "1001", so four bytes ('1', which is 49, '0', which is 48, then '0' and '0'). If the error is the speed try lowering it to 100Hz (set the define to 10000)

@frarugi87 I did what you suggested, it turned out that I have to print the readings each in a single line (from Arduino), Matlab couldn't see the terminator (line end). Another issue, when reading the time in Matlab, you have to use fscanf(s,%f) instead of fscanf(s,%d) because it's a double number. Thank you all for your MASSIVE support and I hope this helps others as well!

Two ways to sample at or near a given frequency:

Select the right ADC clock prescaler. This has some limitations and may not get you too the precise sampling frequency.
Use a timer to trigger the sampling. Can be done in either. Hardware or software. It is the most flexible way here, especially if coupled with the ADC isr.

I tried your program on my Arduino Uno with similar results : it prints
about 44 lines per second. Then I did the math:
Each line consists of 22 characters, including the CR and LF at the end.
Each character is transmitted as 10 bits (8 data bits, one start bit and
one stop bit). At 9600 bits/second, each bit takes 0.104 ms to be
transmitted. All this amounts to 22.88 ms per line (22 × 10 × 0.104), or
about 43.7 printed lines per second, on average.
Now, since you are using a Leonardo, things could be a little different,
as the Leonardo does not use a real serial port, but a virtual one. You
may still try to increase the baud rate to see if it makes any
difference.

I was absolutely sure that this was the correct interpretation, but.. Well, the Leonardo (and all the arduino boards that emulate the serial port) ignores the baud rate you set. So the transfer speed is not the issue in THIS particular case (see my answer)

When a CDC/virtual comm port is involved, the setting of baud rate is done in the CDC device driver, on the host side. That would be windows or Linux or .... Or it wouldn't hand shake with your host terminally program.

@dannyf I never used a leonardo or micro, so I never used the CDC emulation. But... Is it really set on the host? I made a quick research on internet and I found this thread about microchip CDC. They say that there is no such thing as baud rate, since the data is transferred in blocks whenever there is the time, so there isn't a "baud rate"; you can set any value and it gets ignored on both the host and arduino... Is this wrong?

@Edgar I tried frarugi87's method and it worked with several baud rates! I never knew that Leonardo uses a virtual serial communication. I'd like to try this on an Arduino pro Micro (also Atmega32u4) and Arduino DUE (because it has a 12 bits ADC). I think with the pro micro it's going to be the same, but will it be the case with the DUE? unfortunately I don't have the two boards yet to test them myself.

@Isra: The Pro Micro should indeed behave like the Leonardo. The Due, however, seems to have an extra ATmega16U2 as an USB-to-serial chip. Thus I would expect it to behave like the Uno (i.e. the baudrate is relevant).

A few recommendations to get good performance out of the Arduino boards.

Maximize your analogResolution if the default is not already the max (as in the case of the Due.)
If possible, use a simple oscillator instead of a constant Voltage source.  If you can create a sine or triangle wave with its peaks within the Arduino's input voltage range, you can plot something more interesting than a straight line.
There is no need to do any analogReads in setup(), and you DON'T want to do anything with the Serial object in setup() except configure it.  (There is an under-the-hood reason for that.)
To get good sample rates from the Arduino boards, don't convert to text until MUCH later in the data flow.  TO try this SIGNIFICANT speed optimization, declare an array of 4 elements of type unsigned int, another array of 12 elements of type unsigned char, and an unsigned long to hold the time.
In loop(), start by assigning micros() to the unsigned long
Then call the four analogReads in an uninterrupted sequence, assigning them to the four elements of the unsigned int array.
Then copy the four bytes from the unsigned long and the eight bytes from the four unsigned ints into the 12 elements of the unsigned char array.  You will need to use the C++ shift right operator ">> 4" and the "(unsigned char)" type conversion to do this part.
Then, still in loop(), call Serial.write(byteArray, 12) once to send the time and digital representations all at once (in the byte order you specified) through the serial connection.
Place delayMicroseconds at the very end of the loop to get a higher resolution delay between loop iterations.
On the other side of the serial connection (the workstation or laptop) use dd or some other low level transfer program (instead of a terminal emulator) to copy from the binary 12-byte sample vectors from the serial device that your workstation or laptop uses to access the serial connection to a binary file.

The above eliminates several bottlenecks typical of the newbie example programs.  The issue remaining is that, to optimize speed, you never converted the raw binary data vectors to a tab-delimited text file that MATLAB or GnuPlot can read with ease.
A simple C, Java, or Python program can then read the 12 byte vectors and convert the byte groups of 4, 2, 2, 2, and 2 back into the 32 bit time stamp and the four 16 bit unsigned channel values in a loop.  The byte order is what you chose in your Arduino sketch.  You will need to use the left shift operator and bitwise and and or operations to reconstruct the time stamp and four channel values.  At the end of this loop, you can write these values as a single tab-delimited line coresponding to the current binary input vector.  Iterate through all the vectors to get a complete tab-delimited data file.
You can experiment with different delayMicrosecond values to get different sample rates, and you can calculate our baud rate to stay ahead of the sampling so that the program could theoretically run indefinitely without backing up the Serial buffer on the Arduino side.  Each Arduino analogRead and Serial object has its own maximum speed, which you can find by experimentation.

You wrote “you DON'T want to do anything with the Serial object in setup() except configure it. (There is an under-the-hood reason for that.)”. Could you elaborate? 2) You cannot get good control of the sampling rate with delayMicroseconds(), because the loop time is the delay plus the time needed to execute the code. Using micros(), like in @frarugi87's answer, is the standard method and it works well. Only a timer-triggered analog read will give you better accuracy (less jitter).


text:
Confusion with storage of declared variables and volatile
I read that volatile is used when we want to store variables in SRAM.
But aren't all the variables in a code are stored in SRAM anyway?
And what makes it an advantage sometimes for variables(like volatile) to be stored in SRAM?

That's just plain incorrect.
The volatile keyword tells the compiler that the value of that variable may change at any time, and that therefore it must re-read the value every time you use it in your code.
If you don't use volatile, the compiler may choose to make an optimisation.
Consider this code:
int b = 7;
a = b + b;

The compiler can see that 'b' is always 7 -- it is assigned the value 7 and nobody ever changes it.  The compiler may choose to optimise this to the equivalent of
a = 14;

But if you do this:
volatile int b = 7;
a = b + b;

then the compiler MUST read b twice from memory.
Why would you want to do that?  Perhaps you have an interrupt which might change the value of b.  Perhaps your interrupt changes the value of 'b' every time you press a button.  You need the code to really check the value of b every time it calculates a, and not rely on it always being 7.
Here is a fuller explanation.

Can you a bit expound on why volatile is better to use with interrupts?

I've tried and added a bit more information, but I'm not quite sure what more you'd like to know. Is there a particular thing you don't understand? (I'm aware that it's often hard to state clearly what one doesn't understand.)

Technically, variables can be stored anywhere, in SRAM, eeprom or enev flash.
However, without doing anything special, variables are stored in SRAM.
Thee votike attribute is just that, it tells the compiler that the variable could change its value and the compiler shouldn't assume that values obtained from prior access is valid now. This forces the compiler to re-read the variable on demand.

"Thee votike" ?

Local variables are most often stored in CPU registers, although in some cases they can end up in RAM.


text:
FreeRTOS Implementation on Arduino
I am trying to make an RGB LED with Fan Controller for PCs. It is an Open Sourced project. But I want to implement RTOS using this implementation of it as a function in it, namely rollColor(), takes a lot of cycles.
The data the Arduino uses comes from the Serial. The Serial data has to wait until the function rollColor() completes. This function also has a delay and total runtime of this function is approximately 20 Seconds.
This is the original code, in which RTOS is not implemented: nonRTOS
Now I don't want to give a consecutive 20 seconds of execution time to a single function, but time slices would be good.
Now this falls under (RT)OS category and I would like to utilize this library but I seem to be unable to do that as there is not much documentation to begin with. The code I have come up with is this:
#include <Arduino_FreeRTOS.h>
#include <LCD.h>
#include <LiquidCrystal_SR.h>

#define FAN1 3
#define FAN2 5

#define LEDR 6
#define LEDG 9
#define LEDB 10

#define LCD_DT 14
#define LCD_CK 15
#define LCD_EN 16

#define E_FAN1 0
#define E_FAN1 1

#define SAMPLE 100

#define E_RGB_START 2
#define E_RGB_END 502

LiquidCrystal_SR lcd(LCD_DT, LCD_CK, LCD_EN);

int led[2][6];
int led_type = 0;
int led_bright = 0;
int fan[2] = {50, 50};
int load[3];
int temp[2];
int gradient[SAMPLE][3];

bool fchange = false;
bool lchange = false;

void TaskPrintLCD( void *pvParameters );
void TaskRGBCycle( void *pvParameters );
void TaskFanSpeed( void *pvParameters );

void setup() {
  Serial.begin(57600);
  xTaskCreate(
    TaskPrintLCD
    ,  (const portCHAR *)"Print_To_LCD"  // A name just for humans
    ,  128  // This stack size can be checked & adjusted by reading the Stack Highwater
    ,  NULL
    ,  2  // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
    ,  NULL );
  xTaskCreate(
    TaskRGBCycle
    ,  (const portCHAR *)"Cycle_RGB_Colors"  // A name just for humans
    ,  128  // This stack size can be checked & adjusted by reading the Stack Highwater
    ,  NULL
    ,  3  // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
    ,  NULL );
  xTaskCreate(
    TaskFanSpeed
    ,  (const portCHAR *)"Set_Fan_Speed"  // A name just for humans
    ,  128  // This stack size can be checked & adjusted by reading the Stack Highwater
    ,  NULL
    ,  1  // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
    ,  NULL );
}

void loop() {

}

void TaskPrintLCD(void *pvParameters) {
  (void) pvParameters;
  Serial.println("LCD Settings...");
  lcd.begin(20, 4);
  for (;;) {
    printCPUUsage(load[0]);
    printGPUUsage(load[1]);
    printRAMUsage(load[2]);
    printTemps(temp[0], temp[1]);
  }
}

void TaskFanSpeed(void *pvParameters) {
  Serial.println("System Started...");
  Serial.println("Setting Pins...");
  pinMode(FAN1, OUTPUT);
  pinMode(FAN2, OUTPUT);
  (void) pvParameters;
  for (;;) {
    if (fchange) {
      Serial.println("SETTING FAN SPEED");
      int speed1 = ((fan[0] * 256) / 100 ) - 1;
      int speed2 = ((fan[1] * 256) / 100 ) - 1;
      fchange = false;
    }
  }
}

void TaskRGBCycle(void *pvParameters) {
  (void) pvParameters;
  pinMode(LEDR, OUTPUT);
  pinMode(LEDG, OUTPUT);
  pinMode(LEDB, OUTPUT);
  for (;;) {
    if (led_type == 1) {
      //ROLLCOLOR() FUNCTION START
      Serial.println("ROLLING GRADIENT START...");
      for (int i = 0; i < SAMPLE; i++) {
        analogWrite(LEDR, gradient[i][0]);
        analogWrite(LEDG, gradient[i][1]);
        analogWrite(LEDB, gradient[i][2]);
        vTaskDelay(100 / portTICK_PERIOD_MS);
      }
      for (int i = SAMPLE - 1; i >= 0; i--) {
        analogWrite(LEDR, gradient[i][0]);
        analogWrite(LEDG, gradient[i][1]);
        analogWrite(LEDB, gradient[i][2]);
        vTaskDelay(100 / portTICK_PERIOD_MS);
      }
      //ROLL COLOR FUNCTION END
      Serial.println("ROLLING GRADIENT END...");
    } else {
      analogWrite(LEDR, led_bright);
    }
  }
}

void serialEvent() {
  Serial.readStringUntil('*');
  while (String main = Serial.readStringUntil('>')) {
    Serial.println("IN WHILE");
    Serial.println(main);
    if (main == "") {
      break;
    }
    String data;
    if (main == "leds") {
      lchange = true;
      int type = Serial.readStringUntil(':').toInt();
      led_type = type;
      if (type == 1) {
        Serial.println("LED TYPE: " + led_type);
        for (int i = 0; i < 6; i++) {
          data = Serial.readStringUntil(',');
          Serial.println(data);
          if (i < 3) {
            led[0][i] = data.toInt();
          } else {
            led[1][i - 3] = data.toInt();
          }
          data = "";
        }
        generateGradient();
      } else {
        led_bright = Serial.readStringUntil(',').toInt();
      }
      Serial.readStringUntil(';');
    } else if (main == "fans") {
      fchange = true;
      for (int i = 0; i < 2; i++) {
        data = Serial.readStringUntil(',');
        fan[i] = data.toInt();
        data = "";
      }
      Serial.readStringUntil(';');
    } else if (main == "stat") {
      for (int i = 0; i < 2; i++) {
        data = Serial.readStringUntil(':');
        if (data == "load") {
          for (int j = 0; j < 3; j++) {
            data = Serial.readStringUntil(',');
            load[j] = data.toInt();
            data = "";
          }
          Serial.readStringUntil(';');
        } else if (data == "temp") {
          for (int j = 0; j < 2; j++) {
            data = Serial.readStringUntil(',');
            temp[j] = data.toInt();
            data = "";
          }
          Serial.readStringUntil(';');
        }
      }
    }
  }
}

void printCPUUsage(int usage) {
  int loc;
  int i;
  lcd.setCursor(0, 0);
  lcd.print("CPU% ");
  for (i = 1; i <= ceil(usage / 10); i++) {
    lcd.write(255);
  }
  for (i; i <= 10; i++) {
    lcd.print(" ");
  }
  lcd.print(" ");
  if (usage > 99) {
    lcd.print(usage);
  } else {
    lcd.print(" ");
    lcd.print(usage);
  }
  lcd.print("%");
}

void printGPUUsage(int usage) {
  int loc;
  int i;
  lcd.setCursor(0, 1);
  lcd.print("GPU% ");
  for (i = 1; i <= ceil(usage / 10); i++) {
    lcd.write(255);
  }
  for (i; i <= 10; i++) {
    lcd.print(" ");
  }
  lcd.print(" ");
  if (usage > 99) {
    lcd.print(usage);
  } else {
    lcd.print(" ");
    lcd.print(usage);
  }
  lcd.print("%");
}

void printRAMUsage(int usage) {
  int loc;
  int i;
  lcd.setCursor(0, 2);
  lcd.print("RAM% ");
  for (i = 1; i <= ceil(usage / 10); i++) {
    lcd.write(255);
  }
  for (i; i <= 10; i++) {
    lcd.print(" ");
  }
  lcd.print(" ");
  if (usage > 99) {
    lcd.print(usage);
  } else {
    lcd.print(" ");
    lcd.print(usage);
  }
  lcd.print("%");
}

void printTemps(int cputemp, int gputemp) {
  lcd.setCursor(0, 3);
  lcd.print("TEMP ");
  lcd.print("CPU ");
  if (cputemp < 100) {
    lcd.print(" ");
  }
  lcd.print(cputemp);
  lcd.print(" GPU ");
  if (gputemp < 100) {
    lcd.print(" ");
  }
  lcd.print(gputemp);
}

void generateGradient() {
  Serial.println("GENERATING GRADIENT...");
  float m[3];
  int r, g, b;
  m[0] = (led[1][0] - led[0][0]) / SAMPLE;
  m[1] = (led[1][1] - led[0][1]) / SAMPLE;
  m[2] = (led[1][2] - led[0][2]) / SAMPLE;
  for (int i = 0; i < SAMPLE; i++) {
    r = ceil(m[0] * i) + led[0][0];
    g = ceil(m[1] * i) + led[0][1];
    b = ceil(m[2] * i) + led[0][2];
    gradient[i][0] = r;
    gradient[i][1] = g;
    gradient[i][2] = b;
  }
  lchange = false;
  Serial.println("GRADIENT GENERATED...");
}

To me this code seems complete, but there is nothing from Arduino end, no LCD print nothing. I may be doing something wrong, but I don't know what, so please advice.
If you have any other better alternative please advise that too.
PS: I wrote this in two sittings so there might be something amiss so please feel free to edit or ask any questions for clarification.

Your printXXXusage functions could all be rolled into one function with an extra parameter in, this would mean you would only have to fix errors (if there are any) once.  As to your problem it sounds like you should use interrupts and I don't know if you can do it with RTOS.

@Matt yeah... I can.. but i will do that once this time division is done. BTW there are 3 timers and all of them are being used for the PWM Signals so what interrupt can I use for time division or slices?

@Matt BTW forgot to mention, there are no errors in the nonRTOS code, only this implementation which I am not sure if I am implementing correctly.


text:
Where is Arduino.h on a Mac? Can I download a copy if missing?
I have installed the IDE on a Mac. It works great. I want to use Eclipse as an editor only. Some files I have include "Arduino.h". Where is this file? I cannot find it.
If it is built in to the tools can I download a copy of this file(s)?

On a Mac the Arduino.h file is within the Arduino application itself. It's not that easy to get to without resorting to the command line.
You also need far more than just Arduino.h - you need the entirety of the Arduino AVR core, which is a collection of .h, .c and .cpp files. They are all together in the application.
You would probably be best off getting them from the github repository (https://github.com/arduino/Arduino) - the files you need are all under hardware/arduino/avr
On your Mac you may find them as /Applications/Arduino.app/Contents/Resources/hardware/arduino/avr or somewhere similar (not entirely sure where it puts it within the app).

I found them in Contents/Java/Hardware/arduino/avr/cores/arduino. I was able browse them in finder as I think I have MAC dev tools installed.

I copied all the files with Android.h. As suggested I then needed the tools file too. stdlib.h etc. I rummaged around and found these too. I want them for syntax checking only so not 100% bothered if they are the correct ones. I'm building for AVR platforms.

I've don't have a Mac, so I can't test this, but on the Arduino Forum they say find the file Wiring.h and create an empty file called Arduino.h in the same folder.
I don't know if that's the right approach, but it should get you to the next error, which may well be some system constant is not defined. If it does work you could go to github for the IDE (don't know exactly where that is) and download Arduino.h from there and stick it alongside Wiring.h.

Generally, if you need to find a file you can open a terminal and type
locate myfile.dat

This looks in a database (rather than searching the disk), which you may need to update by typing
sudo updatedb                       // on linux
sudo /usr/libexec/locate.updatedb   // on Mac

There simply is no "Arduino.h" file. Basically there are multiple platforms (the most common in Arduino world is the Arduino AVR platform). Each platform can contain multiple cores (but mostly only contains 1) and each core contains a "Arduino.h" file.
So to find the Arduino.h file you need to identify the board. The board gives you the platform and the core. Based on those the Arduino.h file is in the folder [platform installation folder]/cores/[core].
The [platform installation folder] is dependent on how the platform was installed on your system. For instance arduino avr comes with the Arduino IDE and as such it is installed in the app like majenko explained.
If it is installed by the boards manager on Linux, the Arduino IDE uses ~/.arduino15/packages/[provider]/hardware/[architecture]/[version] and if I'm not mistaken the same location is used on Mac.
You can also point to a folder location where additional hardware is installed.
A word on Eclipse and Arduino. There are quite a few options to run compile Arduino sketches in Eclipse. Depending on the tool it goes from easy to pretty complex.
I personally advise to use Sloeber from sloeber.io as I am the developer.


text:
How to increase sensitivity of Capacitive Touch Switch?
I am working with Capacitive Touch Sense technology.In that I am using TTP224 Touch detector IC. I am getting good sensitivity when I am using Touch pad without putting any non electric material over it and able to switch ON/OFF connected led.But when I put any non electric material like Acrylic Sheet of 2mm thickness I am not able to get any signal through pad or not able to ON/OFF connected led.
So, How can I increase sensitivity of Touch pad?
I have bought TTP224 module from here.
And what can be the alternatives for TTP224???

Try a different material. Also try to minimize any gap between the pad and the acrylic. Otherwise exchange the capacitors on the board.

@Gerben...Thanks. There is no gap between pad and acrylic. And yes I am trying with different capacitor values.

According to the datasheet (if you can name it that):

The capacitance Cs0~Cs3 can be used to adjust the sensitivity. The value of Cs0~Cs3 use smaller, then the sensitivity will be better. The sensitivity adjustment must according to the practical application on PCB. The range of Cs0~Cs3 value are 0~50pF.

So, reduce the capacitances Cs0 to Cs3 and you will get better sensitivity.

Sometimes things just ****. In my case, where 0.5 mm more of gap make the TTP223 unable to work, because I designed such a small pad. My solution? Remove the paint in the PCB, put a lot of solder in to make the pad taller. Work like a charm.

remove all c3 to c10 capacitors of 22pf. This will increase sensitivity and will sense through 5 mm sheet also .

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


text:
At what frequency/rate does the digitalRead function read an input?
Consider the following code:
void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

The line buttonState = digitalRead(buttonPin); checks the input voltage.
But how is that checked internally?
I mean at what rate the input is checked?

The check is performed in one single cycle, but the whole routine takes WAY longer. It's not clear what you are asking. For info: http://jeelabs.org/2010/01/06/pin-io-performance/ Summary: "digitalRead() takes 3712 ns, direct port read takes 151 ns, a ratio of 25:1

So it is roughly 0.3MHz right? That could be the answer to my question?

As I said it's not clear what you ask: your input is checked once every loop, meaning that you need the time for one digitalRead, one IF, one digitalWrite, one JUMP to the beginning othe next loop. DigitalRead COULD work at 0.3 MHz if you call it continuously, but you are doing more stuff.

Add a delay at the end of the loop and measure micros() once at the beginning of the loop, once at the end before the delay, and send via Serial.println(microsAfter-microsBefore).

I did some benchmarking on the cost of Arduino - in that case for digital write. I can easily do so for digital read as well. When I get time, I will provide more definitive answers. It is sufficient to say now that the cost in performance is quite substantial in avrs and considerably less on stm32.

When I get time, I will provide more definitive answers.

I did follow through with this, and the result is here, towards the end of the page: https://dannyelectronics.wordpress.com/2016/05/01/the-price-of-avr-arduino/
the short answer is: digitalRead() takes 4.9us to execute on a 16MIPS Arduino Uno, or 79 ticks (=instructions).
the fastest you can read digitalRead() is then 200KHz (= 1/4.9us).
Hope it helps.

It read a port just like it reads memory (to which it's mapped.) So speed is how fast an instruction can read memory.  EEPROM is a different animal.
Might get it a little faster by replacing
buttonState = digitalRead(buttonPin);
    with
buttonState = PORTB & _BV(buttonPin);
Assuming it's PORTB that you are using. This will alleviate at least one function call, I would think, and will generate a single instruction to read the port into the variable. It may require an instruction to load the variable address, but that's up to the compiler.  The replacement may be more trouble porting to other micros.  Normally you don't see a variable as a parameter although legal, usually a constant in a #define.
_BV(INPUT_PIN_X) is a macro (BV is for 'bit value') that expands to
(1 << INPUT_PIN_X)
dannyf times seem quick to me, but it sounds like he's done the testing. Is he taking into account the complete function call as part of the time?  I run at 1Mhz normally, so it's more difficult to relate.
Take Majenko advice and start reading the generated assembler :)
Best of luck.

For pins above 7, won't, for example _BV(13) give you masks like B1000000000000 and not work sensibly with PORTA or PORTB? Wouldn't buttonState = *portInputRegister(digitalPinToPort(buttonPin)) & digitalPinToBitMask(buttonPin); be more robust?

Ack -- digitalRead(buttonPin) gives a 1 or 0, while PORTB & _BV(buttonPin) could give you 0,1,2,4,8,16,32,64,128 depending on the state of the pin and which pin on the port you are looking at.

That depends on the frequency your Arduino runs at.
It's basically once per iteration of the loop, and that depends on everything that is happening in the loop.
You can examine the assembly language output of the compiler (disassemble the .elf file using avr-objdump -h -S <elf file>) and count the number of clock cycles per iteration (the datasheet has the number of clock cycles per instruction). However that is tedious.
If you want to read the input at a specific frequency then you should do it using a timer interrupt.

Can you give a rough number for a short code like in my example?

No, I can't. Not just like that. You could toggle an IO pin each iteration of your loop and read the frequency using an oscilloscope, then double it. That is how fast the loop is running at that moment in time.

It is based on the frequency of the arduino and the 'amount' of operations in loop() and serial_event() methods, is it not? More operations in the loop,  lower the read frequency.


text:
Arduino Uno, BLE Bluetooth Shield and Braccio Arm Shield
I'm running the Uno board and want to connect the BLE Bluetooth shield (http://redbearlab.com/bleshield/) to control the Braccio Arm I have.
When I sit the Braccio Arm Shield on the Uno everything works - I can control the Arm.
When I sit the Bluetooth Shield on the Uno, everything works I can find the device and connect to it using the IOS App.
When I sit all 3 together, I can still control the arm but can no longer find the Bluetooth device.
Any ideas as to why this is?

Be aware that the BLE Shield is using  a SPI interface therefore on Arduino Uno the SPI bus uses pins 10 (SS), 11 (MOSI), 12 (MISO), and 13 (SCK) and the Nordic’s ACI requires two hand-shake signals, RDYN and REQN, two additional pins will be used (pins 8 & 9 in the default settings), from BLEshield
Therefore the BLE shield uses 6 pins e the Braccio uses almost all Arduino Uno pins.
Conclusion, you probably can't have both shields together as the Arduino Uno hasn't enough pins.
You can try an Arduino MEGA and adapt the shields connections wiring them together using different pins for the Braccio interface for example

This really helped, I managed to get a Bluetooth module and find the pins that were not in use.


text:
Strange characters after typing an AT command in serial monitor
I'm trying to test AT commands (I am working with an  Arduino Uno and a GSM/GPRS SIM900  shield; my system is ubuntu 14.10) . Yesterday when I was testing , all  ran well.. For example after typing AT+SAPBR=3,1,"APN","ooredoo" in the serial monitor it  showed me OK.. but But now it  shows me strange  characters.
This is my code
    #include <SoftwareSerial.h>
    SoftwareSerial GPRS(2,3);

void setup() {
  // put your setup code here, to run once:
 GPRS.begin(9600);
  Serial.begin(9600);
 Serial.write("start");

}

void loop() {

  // put your main code here, to run repeatedly:
     while(GPRS.available())
     Serial.write(GPRS.read());

  while(Serial.available())
    GPRS.write(Serial.read());

}

And this it is the result of AT+SAPBR=3,1,"APN","ooredoo" typed in the serial monitor

Thank you for helping me

Did you select the right baud rate? I get these strange characters when I have set it wrong.

i didn't change anything...it worked like this yesterday,but now i have this strange characters...what can be the problem?

You haven't changed any settings, but have you knocked a wire.  It could be a loose connection or a bad ground connection.

bad connection? i don't know..but the shield work normaly..the red led is on, the station led is also on and the net led blind every 3 seconds

for those who have this issue, i resolve this by changing the speed baud of my GPRS Shield :
GPRS.begin(2400);
Serial.begin(9600);

and if you want to test AT command directly on the serial monitor you must use 2400 anywhere
GPRS.begin(2400);
    Serial.begin(2400);

and don't forget to change also  the speed on the serial monitor to 2400
I hope this will help someone


text:
Teensy lc linker script question
I am under the impression that the origin of RAM on a Cortex M is 0x20000000.  However, in the linker file for it, the ORIGIN of RAM is set to 0x1FFFF800.  Is that an error, or is there a reason for the discrepancy?

The Cortex M does not "have RAM at 0x2000000". The Cortex M is just a CPU. It is down to the chip manufacturer where they choose to place RAM in the memory map.
In the case of the MKL26Z64VFT4 used on the Teensy LC:

The on-chip SRAM is a single contiguous block split into two ranges: 1/4 is allocated to SRAM_L, and 3/4 is allocated to SRAM_U. Regardless of the block size, the SRAM is implemented such that:

SRAM_L is anchored to 0x1FFF_FFFF and occupies the space before this ending address.
SRAM_U is anchored to 0x2000_0000 and occupies the space after this beginning address.

Valid address ranges for SRAM_L and SRAM_U are then defined as:

SRAM_L = [0x2000_0000–(SRAM_size/4)] to 0x1FFF_FFFF
SRAM_U = 0x2000_0000 to [0x2000_0000+(SRAM_size*(3/4))-1]

Since there is 8kB of SRAM, 2kB is below 0x2000000 and 6kB is above 0x20000000. 2kB is 0x800. 0x2000000 - 0x800 = 0x1FFFF800.

Thanks for that, good to know.  One question, though: why does "the cortex memory map" exist, if the chip manufacturers are free to modify it?

For the M0 there is a "default" memory map, which is only a suggestion. It's up to the manufacturer what they do.


text:
Mains-Frequency Clock Library
I have an arduino thing, and the hardware I plan to connect to it (a triac zero-crossing based dimmer) provides a synchronization signal from the mains power phase it connects to.
Main power does of course vary some from the nominal 60Hz, however the exact frequency gets adjusted over the course of the day to ensure there are almost exactly 5184000 cycles per day and pretty much exactly 36288000 cycles per week, and is used by mains-powered wall clocks to keep time.
Since my application will need to keep accurate time-of-day across weeks or months without adjustment, it would be advantageous to be able to use this time source.
I can of course write my own code to increment a counter every time the arduino receives a pulse, but if a library that can handle this already exists, I would prefer to use that, in particular since then I won't have to write code to track days and months, handle DST, or any of that stuff.
What libraries exist (if any) to handle timekeeping based on a fixed-pulse-rate input source?

I don't think these exist, but you could use a general library to covert a seconds counter to time an date. Then use a different library for counting the crossings. Though this is so basic, that you can problem write it with just a few lines of code. Where do you live, because not every country tries to make the average frequency 60/50 Hz.

You could use the Arduino Time library. You will have to write your own time provider function based on pulse counting, but then you benefit from all the time-handling routines of the library.

@Gerben I'm in the USA, in a region that does regulate the mains power frequency.

@EdgarBonet That is probably what I will do, there just doesn't seem like a 'natural' way to integrate the pulse counting as a time provider except by keeping a separate redundant count of the time.

Counting the pulses is child's play and doesn't need a library (hint: use an interrupt input and increment a counter). From that count you can use TimeLib.h to convert seconds since 01/01/1970 to an actual time.  Or just do simple division to convert seconds (count/50) into minutes, hours, whatever division you want.


text:
What is the best board for setting up an SSH protocol to an Arduino?
I currently have a project using an Arduino R3, set up across the room from my computer. This has become quite annoying, as every time I want to push something to the Arduino I have to get up and move either the computer or the Arduino to another location, plug it in, and hope my code works the first time, lest I have to repeat the test over and over again. I am trying to set up an SSH server between my Raspberry Pi 2 and computer so I can just push new sketches over SSH, however, I use my Pi 2 for other projects occasionally and want to purchase a second board specifically for this purpose. Is there a good, cheap, board with wifi built in (besides the Pi 3) that I could use for this? Any suggestions?

How is SSH helping achieve your goals?

https://hackaday.io/project/9931-wireless-arduino-uploading-using-esp8266

@Gerben I don't see any reference to SSH on that page.

@NickGammon simply that I could create sketches on my computer and upload them with an ssh connection to whatever board is hooked up to the arduino, rather than unplugging either device and walking across the room every time I want to upload

SSH is a secure (encrypted) shell. Why do you need to encrypt an upload from one part of your room to the other?

@NickGammon I don't, it just seemed like the easiest way to link the two terminals, and I have a friend who did it and said it works fine for him.

Sounds like you want an Arduino Yun instead of an Uno.  Or a Dragino Yun Shield that turns your Uno into a Yun.

Yeah I confirm. I did some work recently and the Arduino Yùn Shield could do the job. You can push sketches via Wifi and run ssh commands. I add performance problem, but otherwise it works like a charm.
https://www.arduino.cc/en/Guide/ArduinoYunShield

If you get it working on the Pi2, could you just drop in a Pi Zero ($5) and a cheap USB network adapter ($2)?
Note that your question title asks for "best", but you don't define your criteria.  Reading between the lines I suspect "cheapest and adequate" is what you mean.

You could swap out the Arduino for a ESP012, not sure it meets your I/O needs. The new ESPs support over wifi firmware uploads.


text:
Wiring a potentiometer to control a 9V battery powering 2 LEDs in series
I am trying to build an array of LEDs where their brightness is controlled by a potentiometer.  The LCD will display the percentage of brightness based on the potentiometer.  I am able to successfully control the brightness of a circuit with only one LED.  However, I am having trouble with 2 two LEDs in series (which are in parallel with other sets of 2 LEDs in series).  And I believe the problem is that the Arduino is only supplying enough voltage to power one LED (maybe < 5V).  How can I properly wire a 9V battery to this circuit in which the potentiometer can control the amount voltage coming from this battery?  Are Arduinos only capable of controlling <5V with a potentiometer?
Here is my code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int potPin = A0;
int ledPin = 6;
int potValue = 0;

void setup() {
  pinMode(potPin, INPUT);
  pinMode(ledPin, OUTPUT);
  lcd.begin(16, 2);
  lcd.print("Potentiometer");
}

void loop() {
  potValue = (analogRead(potPin)/10.02);
  analogWrite(ledPin, potValue);
  lcd.setCursor(0,1);
  lcd.print(potValue);
  lcd.print("%");
  delay(100);
  lcd.print(" ");
  delay(1);
}

And here is a picture of my circuit setup:

Yes, Arduino is a 5V microcontroller, meaning it can directly control 5V circuits only. You might incur in problems also trying to deal with 3.3V circuits, even if Arduino is pretty friendly to 3.3V counterparts.
That does not mean though you cannot control higher voltage circuits, just not directly. Actually if anything above 6V is connected to an Arduino PIN you will blow that pin and potentially others which are logically connected within the MCU, so be aware.
To control higher voltage circuits you have multiple options, in your case you are probably interested into using a BJT transistor, an 2N2222 might do.

simulate this circuit – Schematic created using CircuitLab
Please note the values of R1 and R2 must be adjusted to the LEDs you are using depending on their Vf (forward voltage drop) and the maximum current you want to provide.


text:
Do I need to use the PWM pins in order to control brushless motors Arduino Uno?
I am building a quadcopter with this schematic:

It works very good but i have the pins on 3,5,6,9 = PWM pins. Is it possible to use "regular" pins instead? I will add more modules later on so i will most likely run out of PWM pins.
I could of course try it right now but i want to ask first so i could potentially avoid to destroy any items!

No, you need to use PWM in order to control the ESCs which, in turn, control the motors. If you need more PWMs you might add daugtherboard based on other ICs which might provide additional PWM outputs via I2C or serial interface.
In some non critical conditions (ESCs are critical for a quadcopter) you can simulate PWM by switching a plain digital pin HIGH and LOW very quickly, but that is not as reliable as using hardware PWM.

Damn it! I am missing 1 PWM then. I use this BLE device: https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/hooking-everything-up and if you check the schematic they require 3 PWM pins which means that there are only 3 left for my 4 motors. do you think i could change a PWM to a regular pin from that BLE device instead?

Ok i read it a bit more carefully now. Seems like i can change both REQ (pin 10) and RST (pin 9)  after i upload code if i am not mistaken

That's correct: they use pin 10 and pin 9 as plain digital, no PWM is required so by re-mapping those pins you can retain the PWM functionalities of pin 9 and 10 to your goals