text:
How do I go about pausing/stopping the timer1 task setup in this library, so I can use timer1 for something else in my code
So I want to use this library, that uses timer1 to fetch samples from analog input on pin A0.
It works great, and so after proper detection I'd like to perform all kinds of different tasks. But for those I need timer1 again and I think this library keeps it's timer1 routine continuously running. (Am I right?)
(EDIT: clarification) I think therefore a different library using timer1 won't work as expected. That's why after the first library's task is done, I'd like to free up timer1 for the second library.)
/*
  Original text created by Jacob Rosenthal:

  The Goertzel algorithm is long standing so see
  http://en.wikipedia.org/wiki/Goertzel_algorithm for a full description.
  It is often used in DTMF tone detection as an alternative to the Fast
  Fourier Transform because it is quick with low overheard because it
  is only searching for a single frequency rather than showing the
  occurrence of all frequencies.

  This work is entirely based on the Kevin Banks code found at
  http://www.embedded.com/design/configurable-systems/4024443/The-Goertzel-Algorithm
  so full credit to him for his generic implementation and breakdown. I've
  simply massaged it into an Arduino library. I recommend reading his article
  for a full description of whats going on behind the scenes.

  Created by Jacob Rosenthal, June 20, 2012.
  Released into the public domain.

  Modifications 6v6gt 09.09.2019
  1. Restructure instance variables to permit multiple instances of class.
  2. Make sample array static to share it between instances
  3. Pass in sample array as pointer so it can be reused outside class.
  4. Drive ADC by timer1 instead of polling ADC in loop()
      and reduce resolution to 8 bits.
  5. Separate coeeficient calculation from constructor because it
       now relies on data unknown at invocation (sample rate)
  5. Some consolidation of methods.
  6. Software "as is". No claims made about its suitability for any use.
       Use at your own risk. Special care required if you use other
       analog inputs or an AVR chip other than ATmega328P (Uno etc.).
*/

#include "Arduino.h"
#include "Goertzel.h"

// set by Goertzel::init()
uint8_t * Goertzel::testData;             // static declaration in .h
uint16_t Goertzel::N ;                    // ditto
uint16_t Goertzel::SAMPLING_FREQUENCY ;   // ditto

volatile bool Goertzel::testDataReady = false ; // static declaration in .h

//ADC interrupt service routine
ISR(ADC_vect) {
  // load sample buffer on sample conversion.
  static uint16_t sampleIndex = 0 ;
  if ( ! Goertzel::testDataReady   ) {
    if ( sampleIndex < Goertzel::N  ) {
      *(Goertzel::testData + sampleIndex++ )  = ADCH ; // 8 bits. Direct adressing into byte buffer
    }
    else  {
      Goertzel::testDataReady = true ;    // make buffer available to consumer
      sampleIndex = 0 ;
    }
  }
  TIFR1 = _BV(ICF1); // reset interrupt flag
}

// constructor
Goertzel::Goertzel(float TARGET_FREQUENCY  )
{
  _TARGET_FREQUENCY = TARGET_FREQUENCY; //should be integer of SAMPLING_RATE/N
}

//static method
void Goertzel::init( uint8_t *sampleArray , uint16_t sampleArraySize, uint16_t sampleFrequency ) {
  // set up sample array, number of samples and sample frequency.

  // load class static variables
  testData = sampleArray ;
  N = sampleArraySize ;
  SAMPLING_FREQUENCY = sampleFrequency ;

  // initialise ADC and Timer1. Timer1 triggers ADC at frequency SAMPLING_FREQUENCY.
  // ISR(ADC_vect) called when conversion complete.
  cli() ;

  // Setup Timer1 for chosen sampling frequency.
  TCCR1A = 0;
  TCCR1B = _BV(CS10)  |    // Bit 2:0 – CS12:0: Clock Select =  no prescaler
           _BV(WGM13) |    // WGM 12 = CTC ICR1 Immediate MAX
           _BV(WGM12);     // WGM 12 ditto
  ICR1 = ( (F_CPU ) / SAMPLING_FREQUENCY ) - 1;

  // Setup ADC for triggering by timer1; 8bit resolution; Analog Port PC0 (pin A0) ADMUX
  ADMUX =  _BV(REFS0) ;    // Fixed AVcc reference voltage for ATMega328P
  ADMUX |= _BV(ADLAR) ;    // left adjust conversion result in ADCH (8bit)
  DIDR0 |= _BV(ADC0D);     // DIDR0  Digital Input Disable Register 0
  ADCSRB = _BV(ADTS2) |    // Bit 2:0  ADTS[2:0]: ADC Auto Trigger Source
           _BV(ADTS1) |    // Timer/Counter1 Capture Event
           _BV(ADTS0);     // ditto

  ADCSRA = _BV(ADEN) |      // Bit 7   ADEN: ADC Enable
           _BV(ADSC) |      // Bit 6   ADSC: ADC Start Conversion
           _BV(ADATE) |     // Bit 5   ADATE: ADC Auto Trigger Enable
           _BV(ADIE) |      //
           _BV(ADPS0) |     // Bits 2:0  ADPS[2:0]: ADC Prescaler Select Bits  (div 8 )
           _BV(ADPS1);      // ditto
  sei() ;

}

// instance method
void Goertzel::getCoefficient( void ) {
  // previously in constructor. Now SAMPLING_FREQUENCY unknown at invocation time.
  float omega = (2.0 * PI * _TARGET_FREQUENCY) / SAMPLING_FREQUENCY;
  coeff = 2.0 * cos(omega);
}

// instance method
float Goertzel::detect()
{
  Q2 = 0;
  Q1 = 0;
  for ( uint16_t index = 0; index < N; index++)
  {
    // byte sample is ( *( testData + index ) );
    float Q0;
    Q0 = coeff * Q1 - Q2 + (float) ( *( testData + index ) - 128 ) ; //  128 for 8bit; 512 for 10bit resolution.
    Q2 = Q1;
    Q1 = Q0;
  }

  /* standard Goertzel processing. */
  float magnitude = sqrt(Q1 * Q1 + Q2 * Q2 - coeff * Q1 * Q2);
  return magnitude  ;
}

I'm new to using timers on Arduino, but I want to understand and learn more about it. So I'm reading up on it. Seeing that it's not the easiest subject to wrap my head around I'd like to ask for some directions.
On this splendid page I gathered some examples of stopping / disabling timer1.
  TCCR1B = 0;
  TIMSK1 = 0;    // disable Timer1 Interrupt

Nick Gammons Timer info page
However I don't completely recognise the usage of the library's timer names, registers, variables yet. And so I'm unsure what part of the code is doing what exactly, ie where, how and when the timer starts. And therefore I'm equally unsure how to go about stopping it when the task is done, and to start it again when a new detection is needed. It seems there is TCCR1A, TCCR1B, cli() and sei() that have something to do with it and ISR(ADC_vect). One of you probably knows ;)
EDIT: Reading the suggested ATmega328p datasheet I found out a little bit more about the following abbreviations:
cli // disable interrupts during timed sequence __disable_interrupt();
sei // Set global Interrupt Enable __enable_interrupt();
TCNT1 // Timer/Counter (setting 0 will reset)
TIFR1 // Timer Interrupt Flag Register
TCCR1A // Timer/Counter Control Register 1a (setting 0 will reset)
TCCR1B // Timer/Counter Control Register 1b (setting 0 will reset)
TIMSK1 // Timer Interrupt Mask Register
ICR1 // Input Capture Register
ICF1 // Input Capture Flag
ICP1 // Input Capture Pin
WGM // Waveform Generation Mode
CS // Clock Select Bits (prescaler??)
F_CPU // The CPU speed (What is the default value? 8000000??? 1000000??? 16000000???)
DIDR1/DIDR0 // Digital Input Disable Registers (if left enabled they will use excessive power when Analog input is floating or close to VCC/2)
ADMUX // ADC Multiplexer Selection Register
REFS1 & REFS0 // Voltage Reference Selection
ADLAR // ADC Left Adjust Result
MUX
ADEN // ADC Enable
ADSC // ADC Start Conversion
ADATE // ADC Auto Trigger Enable
ADTS // ADC Trigger Source Select
ADCSRB //
ADIE // ADC Conversion Complete Interrupt Enable
ADPS0 & ADPS0 // ADC Prescaler Select Bits

But hasn't really lightened things up entirely for me. What is _BV? for example.
EDIT: I think I'm starting to make sense of it more. Am I right here(??):
ADMUX = (0b00 << REFS0) | (1 << ADLAR) | (0b00000 << MUX0);
Is the same as:
ADMUX = (0b00 << REFS0); // 0 shift has no effect so can be omitted
ADMUX |= (1 << ADLAR);
ADMUX |= (0b00000 << MUX0); // 0 shift has no effect so can be omitted
Is de same as:
ADMUX = (1 << REFS0); // can be omitted
ADMUX |= (1 << ADLAR);
ADMUX |= (1 << MUX0); // can be omitted
is the same as:
ADMUX = _BV(REFS0); // can be omitted
ADMUX |= _BV(ADLAR);
ADMUX |= _BV(MUX0); // can be omitted
Is the same as:
ADMUX = (1 << ADLAR);
Is the same as:
ADMUX = _BV(ADLAR);

Understanding it all would be great, but may be unnecessary.
If only I'd know how I can stop and free Timer1 usage for other purposes. Starting it all up again would be easier I guess ;)

Did you try looking at the datasheet of the Atmega328p (which is the microcontroller on the Uno/Nano)? The register names (like TCCR1A) are from there. It also describes the function of each bit in each register.

Doing that now.

Re “What is _BV?”: As stated in the documentation:, #define _BV(bit) (1 << (bit))

What is the difference between:
TIFR1 = _BV(ICF1); And
TIFR1 |= bit (OCF1A);
In code comments they both are said to clear the Input Capture Flag or the Interrupt Flag register...

Re _BV() vs bit(): _BV() comes from the avr-libc, whereas bit() is from the Arduino core. Otherwise they are basically the same, except that bit() returns an unsigned long.

Look, guys, comments under a question are for clarifying the question. Not for answering it. See that big "answer" box? That's where answers go. :)

Mine was in the answer field first, bit got moved. Meanwhile, putting it this way, your answer should perhaps have been a comment?

Time hasn't been on my side lately. But here is the code I've come up with so far. Needs testing still to see if it solves all my problems but in regards to my original question this seems to hold the answer I was looking for. Later on I might add some more info/links to register settings, hex/binary/ascii tables, bitwise operations and what they all do. But the manual is your friend pretty much.
Alright then. First of all this print function comes in handy:
// Handy while experimenting with all different bitwise operations and settings
void printRegSettings() {
  const String regNames[8] = {"TCCR1A", "TCCR1B", "ICR1", "ADMUX", "DIDR0", "ADCSRA", "ADCSRB", "TIFR1"}; //other: "TCNT1", "OCR1A", "OCR1B", "TIMSK1"
  uint8_t regVars[8] = {TCCR1A, TCCR1B, ICR1, ADMUX, DIDR0, ADCSRA, ADCSRB, TIFR1}; //other: TCNT1, OCR1A, OCR1B, TIMSK1

    for (uint8_t index = 0; index < sizeof(regVars)/sizeof(regVars[0]); index++) {
      Serial.print(regNames[index]+" = 0b");
      for (uint8_t i = 8; i > 0; i--) {
        Serial.print(bitRead(regVars[index], i-1));
      }
    Serial.write('\n');
    }
}

Next put all library register settings in function, notice the boolean in the end, for emptying the ISR (later described):
void dtmfTimerSetup () {

  TCCR1A = 0;
  TCCR1B = _BV(CS10) | // Bit 2:0 – CS12:0: Clock Select = no prescaler
           _BV(WGM13) | // WGM 12 = CTC ICR1 Immediate MAX
           _BV(WGM12); // WGM 12 ditto
  ICR1 = ( (F_CPU ) / 9600 ) - 1;

  ADMUX = _BV(REFS0) ; // Fixed AVcc reference voltage for ATMega328P
  ADMUX |= _BV(ADLAR) ; // left adjust conversion result in ADCH (8bit)
  DIDR0 |= _BV(ADC0D); // DIDR0 Digital Input Disable Register 0
  ADCSRB = _BV(ADTS2) | // Bit 2:0 ADTS[2:0]: ADC Auto Trigger Source
           _BV(ADTS1) | // Timer/Counter1 Capture Event
           _BV(ADTS0); // ditto
  ADCSRA = _BV(ADEN) | // Bit 7 ADEN: ADC Enable
           _BV(ADSC) | // Bit 6 ADSC: ADC Start Conversion
           _BV(ADATE) | // Bit 5 ADATE: ADC Auto Trigger Enable
           //_BV(ADIE) | //
           _BV(ADPS0) | // Bits 2:0 ADPS[2:0]: ADC Prescaler Select Bits (div 8 )
           _BV(ADPS1); // ditto

  Goertzel::dtmfListenerISR = true;
}

Next add a function to clear all these settings. Initial values of registers is 0 as far as I checked. So setting them zero does the job. Again notice the boolean false this time.
void clearTimerSettings() {
  //Empty Goertzel dtmf interrupt ISR routine
  Goertzel::dtmfListenerISR = false;

  //reset all altered registers to initial value 0
  Serial.println(F("***CLEARING ALL BIT SETTINGS***"));
  TCCR1A = TCCR1B = ICR1 = ADMUX = DIDR0 = ADCSRA = ADCSRB = TIFR1 = 0;

// pauze but don't erase current interrupt settings:
// bitClear(ADCSRA, ADIE); //risk interference when different timer adc library sets bit again
}

In Goertzel.h Add this static bool declaration to class Goertzel public:
static volatile bool Goertzel::dtmfListenerISR;

Add boolean declaration to Goertzel.cpp and add 'if statement' inside ISR(ADC_vect) to only execute interrupt if dtmfListenerISR is true.
volatile bool Goertzel::dtmfListenerISR;

//ADC interrupt service routine

ISR(ADC_vect) {
  //if dtmfListenerISR is false, this code is skipped, freeing timer1 for other purposes
  if (Goertzel::dtmfListenerISR) {

    // load sample buffer on sample conversion.
    static uint16_t sampleIndex = 0 ;
    if ( ! Goertzel::testDataReady  ) {
      if ( sampleIndex < Goertzel::N  ) {
        *(Goertzel::testData + sampleIndex++ )  = ADCH ; // 8 bits. Direct adressing into byte buffer
      }
      else  {
        Goertzel::testDataReady = true ;    // make buffer available to consumer
        sampleIndex = 0 ;
      }
    }
    TIFR1 = _BV(ICF1); // reset interrupt flag
  }
}

Finally use these functions like this in your sketch. The setup can be done in setup but the clearing should take place in your void loop of course, once the library and timer interrupt have finished their job and you want another library / timer routine to take over. Just for testing I put them all inside a setup and a simple sketch now.
void setup() {
  Serial.begin(115200);
  //setup/initialize timer interrupt routine:
  dtmfTimerSetup();
  //FOR TESTING: check and print current settings:
  printRegSettings();
  //clear timer interrupt routine;
  clearTimerSettings();
  printRegSettings(); //only for testing purposes

}

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

Ofcourse for the other libraries using timer1 you should do the same: setup functions with register settings / cleanup and declare/set boolean for ISR part. There might be some overkill here, but so far I didn't find a more elegant way of achieving all this.

I am answering here only a tiny part of the question:

ADMUX = (0b00 << REFS0); // 0 shift has no effect so can be omitted
ADMUX |= (1 << ADLAR);
ADMUX |= (0b00000 << MUX0); // 0 shift has no effect so can be omitted

Is de same as:
ADMUX = (1 << REFS0); // can be omitted
ADMUX |= (1 << ADLAR);
ADMUX |= (1 << MUX0); // can be omitted

No, it is not the same.
Starting from the first line: (0b00 << REFS0) means “zero
left-shifted by REFS0 (i.e. six) bits”. It is not a zero shift, as
stated in the comment: it is a 6-bit shift. The resulting value is zero,
because the number being shifted is zero to start with, and because
vacated bits are zero-filled during a left-shift.
In contrast, (1 << REFS0) means “one left-shifted by REFS0 bits”.
The resulting value is:
2REFS0 = 26 = 0b01000000 = 64
In the first code snippet, ADMUX ends up with only the ADLAR bit being
set. In the second snippet, all three bits (REFS0, ADLAR and MUX0) are
set.
Edit: explaining the notion that “vacated bits are zero-filled
during a left-shift”. Let's assume x = 0bABCDEFGH is a byte, where A…H
are the individual bits (“0b” is a prefix meaning “what follows is in
binary”). Left-shifting this byte gives the following:
x << 0 = 0bABCDEFGH
x << 1 = 0bBCDEFGH0
x << 2 = 0bCDEFGH00
x << 3 = 0bDEFGH000
...

By “vacated bits are zero-filled” I mean that the bits that are beyond
the last original bit (beyond H) are replaced by zeros. Note that a zero
shift “has no effect” in the sense that x<<0 is the same as x. Note
also that shifting the value zero by any amount always yields zero.
In this particular code, the value being written to ADMUX can be
computed as follows:
1 << REFS0 = 1 << 6 = 0b00000001 << 6 = 0b01000000
1 << ADLAR = 1 << 5 = 0b00000001 << 5 = 0b00100000
1 << MUX0  = 1 << 0 = 0b00000001 << 0 = 0b00000001
──────────────────────────────────────────────────
(1<<REFS0) | (1<<ADLAR) | (1<<MUX0)   = 0b01100001

Thanks for taking the time to look at this. I have some more reading to do I suppose. And see if I can find back the source of that comment.

could you elaborate on this: "vacated bits are zero-filled during a left-shift". I'm confused because I thought a shift operation only affects the shifted bit, but now I'm reading the whole row of bits might be shifted left (or right). Then there's also the difference between the logical OR or AND. In case of a zero shift with an OR, does it have an effect at all? And a 1 shift with an OR? Does it have an effect on vacated bits?

@Gaai: What do you mean by “zero shift”? Shifting some number by zero bits or shifting the number zero by some number of bits? What do you mean by “have an effect”? Every expression has the effect or returning some value. Re OR vs AND: please look up the truth tables of these operators yourself. For the rest, see amended answer.

With having an effect I meant: actually setting/changing/writing to the bit. Instead of just reading, which is an effect aswell, as you noted, of course.

I found this line of code with the comment on a forum. I didn't use it right. But I was struggling to understand why I didn't see a bit setting for A0 as the input pin. While when other pins where used (elsewhere by people) they set these with (MUX0, MUX1, MUX2 or other ways even as it seems there are always more ways to do the same in bit settings). Anyway, I tought this might be because A0 was set by some zero setting elsewhere (called a zero shift), which meant it could be left out... I know better now how this is done, thanks to you and some further reading. It's a confusing journey ;)

so I tried ADMUX = _BV(0); //setting 0b00000001
and then ADMUX = _BV(7); //expecting the above to shift left to get 11000000. But bitRead gives me: 01000000. Setting ADMUX to 11111111 first and then doing a _BV(7), still gives me 01000000.

@Gaai: I do not understand your comment.

ADMUX = 0b00000001 followed by: ADMUX = _BV(7); Yields: 0b01000000. While if it was shifted left, I would expect 0b11000000. Reading your explanation.

I'm not sure why you need to stop the timer in the first place. Timers are just things that count "ticks" which can be programmed to arrive at various speeds (usually some division of the processor speed).
Imagine you have a clock in your kitchen. And imagine you are baking a cake. You observe the time that you put the cake into the oven. Then you note at what time the cake will be done. Meanwhile that same clock can be used to time boiling an egg. You don't need to stop or "reset" the clock to achieve this.
Just let the clock run and do its thing, and meanwhile make a note of what time needs to arrive for things to be "done".
Meanwhile, the Uno (and Nano) have other timers. You can use those. It's like owning three clocks, that can run at different speeds — or perhaps more accurately — different levels of precision.

That's because I'd like to use another (more complex) library not written by me, that uses timer1. And it seems their usage collide. Because they both want to use their favourite kitchen clock I guess ;) And I'm not yet the coding diplomat needed to convince them otherwise.

in short: I didn't want to stop the timer (as in clock) but rather the task (interrupt / isr) associated with it. I could've worded my question better perhaps, but I couldn't before because I didn't know the right words. It seems people use 'setup a timer' when they actually mean: 'setup an ISR interrupt routine' or whatever.


text:
Arduino IDE c++ 11 raw string literal have issues with // in http://, complier thinks // is comment
char webpage[] PROGMEM = R"=====(
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js"></script>
  </head>
  <body>
  </body>
</html>
)=====";

I found a problem when using the raw string literal in Arduino IDE.
My code cannot compile if i have http:// link inside the string.
I found that it should be related to how Arduino IDE thought the string after // are comments and during compile time those string are ignored and my codes break.
It looks like the arduino ide's compiler removes all //comment in the code first, before it try to compile the raw string literal and then cause the issue.
As a test I try to debug it by changing my code to https:/-/ the program can be compile as now there is no // in the raw string literal
Is there any workaround?

char webpage[] PROGMEM = R"=="==(
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js"></script>
  </head>
  <body>
  </body>
</html>
)=="==";

inspired by answer provided by @jsotola  if i used the syntax like this R"=="==()=="==" the link will become inside the quote. and hence the ide's complier regards it as a string and won't think // is comment and now the code can complie and the link works.

Escape the two quote marks inside the string using a backslash (literal quotes).
Without the escape characters, the URL is "outside" of a string because the quote marks are string delimiters.
char webpage[] PROGMEM = R"=====(
<html>
  <head>
    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js\"></script>
  </head>
  <body>
  </body>
</html>
)=====";

thanks. interesting.
after escaping the " it can complie but the link doesn't work anymore
because in the html
the src link cannot point to the link location anymore, as it got the extra \ escape character before "

Escaping characters are not left into the end result, you have some other issue, for example you can't link to external content when serving directly from an ESP8266/ESP32 because it doesn't have internet connection that could enable your device to download the resources.

This is just a simplified snippet of the code. My original program will serve a javascript page. I will post my full code later.

For c11 raw string literal, the end result will contain the escape characters. Meaning " in the raw string literal will be still display as "

The C & C++ compilers don't look for language syntax inside quoted strings (except for character-escapes such as '\n'). That is the point of quoting the string.
This program just compiled Ok for me:
const char webpage[] PROGMEM = R"=====(
<html>
  <head>
    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js\"></script>
  </head>
  <body>
  </body>
</html>
)=====";

void setup() {
}

void loop() {
}

'//' within the string did not cause any problem. Your example did get an error message that the variable 'webpage' had to be const to put it in Flash memory so I added the 'const' keyword, but that is the only change I made.
If you do that, and your compiler is still complaining, there is some other issue than the '//'.

source: Stack Exchange

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

sort: votes


text:
Where is the documentation for writing an Arduino core?
I'm interested in writing an "Arduino core" (i. e. porting Arduino to a new MCU and new board(s)).  I'm having trouble finding much documentation on how to do so.  Am I missing something?
This page says "anyone may develop a core for their own boards following the rules and requirements we have issued."  So, where are those "rules and requirements?"
I found something called the "Platform Specification", which sounded promising, but it only documents the config files; it does not say anything about the code that needs to be written to support a new platform.
I found ArduinoCore-API, which says it is the "hardware independent layer of Arduino core."  But it doesn't mention anything about how to write the hardware-dependent part of the core.
I'd be grateful if anyone could point me to the Arduino core documentation.  It's not turning up in my web searches.  Thanks!
Clarifications:

Yes, I can look at existing cores as examples, but I'd rather have the documentation, as well.  Especially since existing cores may be of varying quality, or may not be up to the latest standard.  Documentation is always a good thing.
The reason I want to write a core is because... I want to use an MCU which is not currently supported!  (Specifically, I want to add support for the GD32F350, but really that shouldn't be relevant to answering "Where is the documentation?")

the specification you linked is all what you need. see existing cores as examples. why do you want to create a core?

The specification doesn't say anything about the code I need to write.  Where does it specify that?

I understand. The Arduino API is described here https://www.arduino.cc/reference/en/. some parts are implemented in Arduino API repository. some depend on the hardware and must be implemented.

99% of writing a core is understanding, and coding for, the chip that you are working with. The specification cannot tell you that, since it completely depends on the chip architecture. You basically have two options: 1. use the pre-defined API layer and fill it out with your code behind it to make the functions work, or 2. write your own code that implements the API functions. The documentation is the list of API functions. It cannot tell you how to write those functions.

some new Arduino cores for ARM MCUs are made on top of ARM mbed OS and use the mbed support for the MCU

There are two major parts to writing an Arduino core: the hardware independent portions and the hardware dependent.
The hardware independent portions are pretty much done for you in the ArduinoCore-API. However I wouldn't just use that verbatim but use it as a starting point and adapt it to your needs. This is because it actually has a couple of unresolved issues and not everything may 100% fit your needs. We don't use it for the chipKIT core because:

It has an unresolved issue around the naming of the String.h file which conflicts with the libc's string.h on case insensitive filesystems
Our USB stack is vastly different to how the Arduino "Pluggable USB" works
We have extra facilities in a number of standard objects to make use of more efficient use of more advanced hardware

Once you have the hardware independent portion sorted you need to write, from scratch, the hardware dependent portion.  The basic list of functions you need to implement are listed in the Arduino reference. How you write them cannot be documented, since that depends on the hardware. And you may well need to (or want to) write considerably more functions that just those. For example on chipKIT as well as the standard analogWrite() function we also have functions to change the PWM frequency and resolution - things that aren't part of the "standard", but are incredibly useful.
A good starting point is to examine the Arduino.h file of an existing core (the AVR core is a good baseline) which will list most of the functions and their parameter/return types. That gives you what the functions expect to receive and what they should emit, but how those functions are written is completely down to you.
And then of course you have to implement the boards variants etc to make the whole things work...
Also, be warned that writing (and maintaining) a core is a long and involved process and will consume the rest of your life.

Thanks!  I guess it's a lot more obvious than I thought, in that you're directly implementing the API, rather than implementing some sort of "backend" functions that are called by the API.  Still, some sort of "10,000 foot overview" doc would have been helpful.  I'm not as worried about the "how", because I plan to just call into the chip vendor's firmware library.

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


text:
Python - Arduino communication not reliable
I'm trying to establish basic communication between python and my arduino due. I have managed to get a message sent to the arduino and sent back, but the code that achieves this task does not give consistent results. I'm running python 3.5 with pyserial 3.3.
My Arduino Code:
String incoming;

void setup() {
        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incoming = Serial.readStringUntil('\n');

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incoming);
        }
}

My Python Code
import serial

arduinoSerialData = serial.Serial("COM5",9600,timeout=1)

print("Initial in waiting:")
print(arduinoSerialData.in_waiting)
print("Initial out waiting:")
print(arduinoSerialData.out_waiting)

while (arduinoSerialData.in_waiting>0):
    garbage = arduinoSerialData.readline()
    print(garbage)

nummessages =0

while (nummessages<5):
    if (arduinoSerialData.in_waiting>0):
        myData = arduinoSerialData.readline()
        myData = myData.decode('utf-8')
        myData = myData.strip()
        print("The Arduino says:")
        print(myData)
        nummessages=nummessages+1
    elif(arduinoSerialData.out_waiting>0):
        pass
    else:
        arduinoSerialData.write(b'Hello Arduino!\n')

while (arduinoSerialData.in_waiting>0):
    garbage = arduinoSerialData.readline()
    print(garbage)

print("In Waiting: ")
print(arduinoSerialData.in_waiting)
print("Out Waiting: ")
print(arduinoSerialData.out_waiting)
arduinoSerialData.close()

These print statements are largely my failed attempt to diagnose the problem. The "garbage" loops were my attempt to make sure conditions were as identical as possible when the python code starts up. If I start the arduino program running and then call this python program from my command line I get inconsistent results. Sometimes my first call to the python "works" and then others won't, sometime it works several times in a row, and that first line out output where it says "The Arduino Says: I" will have a varying amounts of the "I Received: Hello Arduino" message the arduino was supposed to send. Any Ideas what could be causing this lack of consistency? If I try starting the python code first, the arduino can't even start up.

Why are you trying to utf-8 decode the data?  Life will probably be simplest if you throw away or substitute anything that isn't an ASCII character and then print what you have.

I mostly just tried that because similar examples used that as a translation tool. If I comment out the decode() and strip() lines then the program seems to always function, except that the first line is erratic. The number of characters varies, and it sometimes has \xff at the end. I'm assuming these cases are the ones that broke the decoder in the original question. I can look for a different way to go from b'text\r\n' to 'text' to try deal with this. I'll try to add a picture in the main question for clarity.

Please don't use pictures.

Likely this should be a Stackoverflow question (or search for existing answers) on how to pull the printable characters out of a buffer containing (mostly but not entirely) legacy ASCII.

In case other people run into similar issues, I'll lay out what I've found today.
-The inconsistent output was due to the fact that when you open a serial connection with python, it resets the Arduino and so python can send signals without the arduino having finished its setup() function. If I put in a 1 second delay on the python side, inconsistency stops and I no longer run into byte errors at all. I'm looking into alternative means of preventing this reset since the time delay is a deal-breaker for me.
UPDATE:
Replacing
arduinoSerialData("COM5",9600,timeout=1)

with
arduinoSerialData = serial.Serial()
arduinoSerialData.port = "COM5"
arduinoSerialData.baudrate = 9600
arduinoSerialData.timeout = 1
arduinoSerialData.setDTR(False)
#arduinoSerialData.setRTS(False)
arduinoSerialData.open()

seems to bypass the reset. I included both the setDTR and SetRTS functions here because although setDTR works for DUE, it seems some other Arduino boards need setRTS instead.
-The decode() function has a keyword argument called errors, which can be set to "ignore" if you want the code to just ignore things that can't be interpreted in your desired format. With just this keyword setup, I never got errors but output was inconsistent due to reset.

Sounds like the ignore errors option basically gives you the noise filter.  Good call on the reset thing - was just thinking about that in context of another question.

This sis not fix the same issue I had with Duo. The delay did help though.

Problem:
Arduino being a microcontroller ( not a microprocessor ), is not efficient enough. If noticed carefully, messages sent to the Serial monitor gets overlapped if the time interval between 2 messages is less than half a second !! Also, there is an equal possibility of overlapping of data from Arduino resulting in garbage data !!

Solution:
To overcome these, python modules named Arduino_Master and Arduino_Master_Delta are available.
These modules also help you to visualize data in the form of graphs as well as filter data and remove garbage values.
Arduino_Master is used for approximation and easier interface
whereas
Arduino_Master_Delta is used for accurate data representation!

Links:
Links to their documentation is given below :
Arduino_Master
Arduino_Master_Delta

Examples:
The code for all these can be found in Arduino_Master_Delta 's documentation.

I have never noticed an issue of attempting to send distinct messages too quickly causing issues with Python. I was not utilizing the Serial Monitor. The problem I was encountering was definitely caused by the Arduino resetting the program when a Serial connection was opened by Python, as detailed in my self-answer.

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


text:
(ESP8266) Check if a SSID is in range
I need to check if a given SSID is in range. Would be good if it didn't disconnect from the current wifi network that it's connected to, but it doesnt matter, i just need to see if a SSID is in range, whether it does disconnect or not.
It should be something like this:
if(WiFi.SSID(checkforthisSSID)) {
  //do something
}

Thanks.

Not so tough it is possible just try the bellow code :)
void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  CheckPossibility();
  }

 CheckPossibility(){
 int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      if(WiFi.SSID(i) == "REPLACE THIS WITH YOUR SSID"){ //enter the ssid which you want to search
      Serial.println("The network you are looking for is available");
      }
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
 // delay(5000);
}

Try to connect to an AP, Use scan networks example, then look if the SSID in in the response.
Did not try, the scan networks example has an "WiFi.disconnect()" before the scan() function.

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


text:
FPC1020 + WeMos D1 Mini
I have a FPC1020am that work perfectly with arduino and a ESP8266 D1 Mini V2 NodeMcu 4MB Lua that can connect to server.
How can I connect the FPC1020 direcetly to ESP8266 D1 Mini to scan finger and send matched id to server?
here is my code and error:
#include <NewSoftSerial.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <FPC1020.h>

extern unsigned char l_ucFPID;
extern unsigned char rBuf[192];  //Receive return data
#define sw_serial_rx_pin 2 //  Connect this pin to TX on the FPC1020
#define sw_serial_tx_pin 3 //  Connect this pin to RX on the FPC1020

const char* ssid = "-------";
const char* password = "-------";

const char* host = "-------";
String url = "-------?id=";

NewSoftSerial swSerial(sw_serial_rx_pin, sw_serial_tx_pin); // Fingerprint serial (RX, TX)
FPC1020 Finger(&swSerial);

void setup() {
  Serial.begin(115200);
  Serial.print("connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  pinMode(4, INPUT);
}

void loop() {
  Serial.println("Please put your finger on the Sensor.");
  while(Serial.available()<=0);

  if( Finger.Search()){
    Serial.print("Success, your User ID is: ");
    url = "-------?id=" + l_ucFPID;
    Serial.println( l_ucFPID, DEC);

    WiFiClient client;
    if (!client.connect(host, 80)) {
      Serial.println("connection failed");
      return;
    }

    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" +
                 "User-Agent: BuildFailureDetectorESP8266\r\n" +
                 "Connection: close\r\n\r\n");

    String line = "";
    while (client.connected()) {
      line = client.readString();
    }

    Serial.println(line);

  }
  else {
    Serial.println("Failed, please try again.");
  }
}

And the error is:
C:\Program Files (x86)\Arduino\libraries\NewSoftSerial\NewSoftSerial.cpp:41:27: fatal error: avr/interrupt.h: No such file or directory

 #include <avr/interrupt.h>
                           ^
compilation terminated.

exit status 1
Error compiling for board WeMos D1 R2 & mini.

We are not a free code writing service.

it's a serial device, hook it into the MCU's UART line, or use SoftwareSerail...

@dandavis the softwareSerial doesnt work on WeMos D1 Mini.. is there any other component that do this on WeMos D1 Mini?

i don't know where you got that idea, but i use SS all the time on d1minis...

@dandavis when i want to compile my code, I got this error: fatal error: SoftwareSerial.h: No such file or directory

@dandavis complete error:  fatal error: SoftwareSerial.h: No such file or directory
#include <SoftwareSerial.h>
                        ^

compilation terminated.
exit status 1
Error compiling for board WeMos D1 R2 & mini.

@mimskydo - That is user error, you haven't downloaded the Software Serial Library or you haven't placed it in the correct location.  Try reading the readme or IDE help on how to download 3rd party libraries.  This is why I said you should have included the error message when you asked this question on your other post, the problem would have been solved by now.

@CodeGorilla I update the question by adding code and error. Would u please take a look at it? I totally confused about it.. also I use "NewSoftSerial" instead of "SoftwareSerial" because of arduino website recomenation. tnx

NewSoftSerial is now in the Arduino core as SoftwareSerial. I doubt the old NewSoftSerial supports the ESP8266.

@mimskydo- avr = Arduino, so when you see avr in a path then it means it wants something just for the Arduino, not for the ESP.  You now need to find a version of software serial that works with the ESP.  OR you could add a hardware serial port http://www.nxp.com/products/signal-chain/bridges/single-uart-with-i2c-bus-spi-interface-64-bytes-of-transmit-and-receive-fifos-irda-sir-built-in-support:SC16IS740_750_760 ??

I have never tried this, but a D1 Mini has 2.5 serial ports.

The Tx and Rx pins are Serial0.
Digital pin 4 is TX1 - There appears to be no RX pin.
D7 and D8 are Rx2 and Tx2.

So rather than using SoftwareSerial or NewSoftwareSerial try using Serial2.  It might work.


text:
Is there a way to strip a library from all unused parts and defines, automatically?
Say you want to investigate part of the code you use from a rather large library, but it's buried between all kinds of #defines and classes etc, that you're never gonna use in your code.
Is there a tool for stripping those unused/unnecessary parts away (like the (pre-)compiler), without converting it to machine language? That would make it much easier to see what happens in the code, and what code does what. Would be a great learning tool imho.

Not quite an answer to your question but... the command avr-nm can tell you how much flash is being used by each function or method.

Good to know! I'll check the memory list from my code. Does it show unused functions that don't take any space once compiled? Saw a grep reference in there too, nostalgia hits... Man, I was pretty handy with grep and sed once. Could've probably stripped the defines that way.

avr-nm works on the compiler output: it cannot see the stuff that was removed or optimized away by the compiler. Inlined functions won't be shown either, as they become part of the functions that embed them (typically setup() and loop() get inlined into main()). You may get more relevant output if you tweak the compiler options to remove link-time optimization (-flto), as this tends to make the compiler very aggressive at inlining.

you are locking for the -E parameter of the compiler which produces C++ source code after preprocessor?

@Juraj Maybe. That sounds more like it.

Are you looking for a tool that "organizes" all sources for you to quickly navigate through it? Then of course the Arduino IDE is not the right one. You might want to try other IDEs, perhaps augmented with Arduino specific plugins, or specifically designed tools. And of course you need all the source files of the library in question, which is not the usual case.

I'll try Visual Studio Code see what I can find. Got it already for websites and javascript and there is quite a lot of options there.

Yes! I found a cool tool to strip the #ifdef and #define stuff: Coan the C preprocessor chainsaw. Off to investigate ;)

The compiler is called in optimization mode (it is even possible to specify how aggressive it will optimize). It will remove all variables and functions, that are not used in your code. Also it can replace variables that never change with literals to make the code smaller. That's already what is happening and you don't need to worry about that.
About the #defines: Everything with a # at the start is interpreted by the preprocessor. That means, that these things are done even before the compiler gets to see the code. Lets say you define a pin number via #define pin 6, then the preprocessor will replace any mentioning of pin with 6 in the code, before it hands the result over to the compiler. The compiler will never see any defines.
I'm not able to tell you, how the compiler optimizes the code. That's probably very complex. Though the avr-gcc compiler is opensource, so if you really want to learn what it does, you can always analyze its source code.

I thought if a compiler can be smart enough to strip all unused variables and functions away and convert what's left in machine language

While I don't know much about how the optimization works, I don't think that it happens in that order. I find it very unlikely, that the compiler would optimize the C++ code. Though it might do that at the assembler level (since avr-gcc first converts the C++ code to assembler and then compiles to machine code). Searching in the assembler code equivalent of the C++ code isn't a real option either.
You are probably stuck with a full text search function of a program of your choice. Most OSs will also provide that function out of the box. I know, that you can search all files of a directory for a term from the Windows explorer. On systems like Ubuntu/Debian/CentOS and similar you can use the grep command in recursive mode to search for a term. On Mac you can probably also use grep.

Re “post processor”: you mean “preprocessor”.

@EdgarBonet Oh, thanks. Definitely had preprocessor in my head when writing this XD

Thanks for taking the time to answer. I knew the compiler takes care of all that but I'd like to be able to 'quickly' look at a specific code blok (still c++, not compiler code) without it being scattered all around in a library of other functions and methods. I thought if a compiler can be smart enough to strip all unused variables and functions away and convert what's left in machine language, maybe there also is a tool that only strips but doesn't convert. It would be easier to learn how certain parts work that way. Bit of wishful thinking maybe ;)

Ah, ok. Now I understand better. I added to my answer, though my answer to that part is basically just no

I clarified my original question, thanks.

The -E command for gcc generates preprocessed C and CPP source.
I didn't find a way to integrate it into the Arduino build process. Only thing I could do was edit platform.txt and change the compile command so it generates the preprocessed cpp of a compilation unit instated of .o files. Then linking failed of course.
The produced cpp was I think less readable than the original because it contained many generated comments and original line number instructions.
the changed cpp recipe in platform txt:
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} -E {includes} "{source_file}" -o "{object_file}.cpp"

I added the -E flag and .cpp file extension for the -o option value
You can see the result in the temporary build folder. You can get the location of that folder from the IDE console when you build the sketch with Verify. (you may need to turn on the verbose compile in Preferences).

Thanks, I will need to have a good look at all that to see if I can figure it out. Haven't done it before. Is this all command line? Got a Mac nowadays (pfff, still getting used to it) havent touched a terminal yet.

no command line. it is a command used by the IDE to build the sketch for upload. you have to change it in platform.txt and it will generate the preprocessed cpp instead of creating the hex for upload

Cool. Gonna check it out soon.

The compiler doesn't quite work like that. It compiles each individual .cpp file into an object file (the .ino file becomes a .cpp file after a bit of pre-processing). I have an answer about the exact process the compiler uses there.
The libraries are also collections of .cpp files which also get turned into object files.
Optimization of unused variables would occur at that point. In other words, the compiler can optimize one compilation unit (one source file) because it can see what parts are used and what are not.
Then the linking phase commences which joins all the object files together, looking for places where a function in a library is called. So for example if you call Serial.begin() somewhere, then the linker will try to find an object file which implements that.
The linker is smart enough to not include code that is not required, so for example, if you never called Serial.begin () then it would not copy in that part of the Serial library.
In the process of doing that it resolves "jumps" and subroutine calls, so that your calls to library functions end up pointing to the place in the program memory where it has put them.
Because this is done at a late stage (after the source has been compiled) you don't really ever have a copy of the source "as linked".
However what you can do is disassemble the object file which gives you the machine code that has actually made it to the final executable. Done properly it will also include the lines of source (C++) code that generated each batch of assembler lines.
If you turn on "verbose compiling" you should see near the end of the compilation output an "ELF" file, and you can then send that to avr-objdump to turn it back into assembler:
avr-objdump -S xxx.elf

It's not great, if you aren't used to assembler, but it gives you a clue as to what made it into the executable file, and where. For a single line of C++ code you might see something like this:
    reg = portModeRegister(port);
 310:   90 e0           ldi r25, 0x00   ; 0
 312:   88 0f           add r24, r24
 314:   99 1f           adc r25, r25
 316:   fc 01           movw    r30, r24
 318:   e8 59           subi    r30, 0x98   ; 152
 31a:   ff 4f           sbci    r31, 0xFF   ; 255
 31c:   a5 91           lpm r26, Z+
 31e:   b4 91           lpm r27, Z+


text:
Why does Serial.print(1) cost 228 bytes more program memory compared to Serial.print((char)(48+1))?
Just discovered this. When I cast an int to a char inside a Serial.print statement it costs way less program memory. I'm not sure why. Could someone explain this to me?
In the following example the difference is 228 bytes!
Serial.print(1); // 1676 bytes program storage space. 184 bytes of dynamic memory.

Serial.print((char) (48 + 1)); // 1448 bytes program storage space. 184 bytes of dynamic memory.

EDIT: Adding from different comments:
Serial.print('1'); // Sketch uses 1448 bytes program memory, 184 bytes dynamic memory

Serial.write(48 + 1); // Sketch uses 1448 bytes program memory, 184 bytes dynamic memory

EDIT: For an int > 9, adding quotes in following example saves 218 bytes program memory but adds 4 bytes to dynamic memory usage.
Serial.print(123); // 1676/184 bytes
Serial.print("123"); // 1458/188 bytes
Serial.print(String(123)); // 2772/194 bytes

EDIT2: Max digits in Arduino-uno int is 5(?). You save 80 bytes by converting it to a char array, in comparison to just printing the integer:
Serial.print(12345); // 1676/184 bytes

char digits[5];
int number = 12345;
for (int i = 4; i >= 0; i--) {
  digits[i] = (number %10) + 48;
  number /= 10;
}
Serial.print(digits); // 1596/184 bytes

To test for yourself, uncommenting one or the other:
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.print(1); // uses 1676/184 bytes
  //. Serial.print((char) (48 + 1)); // uses 1448/184 bytes
  //  Serial.print('1'); // uses 1448/184 bytes
  //  Serial.write(48 + 1); // 1448/184 bytes
  //  Serial.print(123); // 1676/184 bytes
  //  Serial.print("123"); // 1458/188 bytes
  //  Serial.print(String(123)); // 2772/194 bytes
  //  Serial.print(12345); // 1676/184 bytes | 1676/184
  //  Serial.print("12345"); // 1458/188 bytes | 1460/190
  //  char buff[5];
  //  itoa(12345, buff, 10);
  //  Serial.print(buff); // 1604/184 bytes
  char digits[5];
  int number = 12345;
  for (int i = 4; i >= 0; i--) {
    digits[i] = (number %10) + 48;
    number /= 10;
  }
  Serial.print(digits); // 1596/184 bytes
}
void loop() {
  // put your main code here, to run repeatedly:

}

EDIT: Second question: Shouldn't this be optimised somehow? Or should I always take care of this myself? And why/how? ;)
*the chars 0-9 have a decimal value of 48-57 in the Ascii table, hence (char)(48 + 0-9) prints 0-9

short answer: it is not the same print function. you could try .print('1') and .print((char) 1) too

@Juraj You are right, I tested always printing an integer in combination with above examples. And the the memory usage evens out at some point. I guess the compiler optimises the int print function out if you only ever print chars/strings. And vice versa. Which it would when they invoke different functions.

The difference is simply this:

Print this character

and

Interpret this integer as a sequence of digits, work out the ASCII characters that represent each digit in turn, and print them.

As you can see even just writing out what the second one does takes more words. Printing an integer is a lot more work than just printing one character.  Think about what it takes to print the value 2034578 and how you would do that given that you can only output individual numbers 0-9 and the data isn't stored as the numbers 0-9 but a series of just 0 and 1...
It takes work. Lots of work.

So why not cast it to a char in the background then. As that takes less work, lots of less work ;)

@Gaai, because that is not what the int overload of .print() does in the general case. You cannot print .print(123); correctly with a single cast and addition. You're invoking the machinery that allows for correct printing of 123 even if you only ask for 1, and so you pay for that. The answer is correct.

print is a convinience function for easily printing different types as ASCII text. If all you want is to print a single character, then you shouldn't use print, but write. You yourself have to chosse the correct tool for your work

@chrisl Ah yes. This makes sense. That should be added to the answer! Serial.write(1) costs the same as the single char print.

@Majenko perhaps you can include the Serial.write option for single characters/digits in your answers? No memory difference then.

@Gaai The first bullet point "print this character" is the single character that you are opn about.

@Gaai Regarding Serial.write(1) <- .write() will get you out of the "danger" of accidentally calling the overload of print() that prints multi-digit numbers and perhaps express intention better, but that's all it does. It does not send 1 as a digit. So the .write(1) in your above comment sends a control character, not a digit. In other words you still need your + 48, you just don't need the cast  (char) with .write() the way you did print().

Well, my question was regarding a single digit int. Which is a single character as well as an int. But still print treats it like any int. Using more memory then it could have, treating it like a char.

@timemage you are right of course!

I added Serial.print(123) vs Serial.print("123") memory usage for completeness sake, just now.

Writing my own conversion still saves 80 bytes. Probably there is even more to gain if you do it smarter. Weird if you ask me.


text:
Anyone had Digispark Attiny85 not SEEN by some USB controllers but seen via HUB or DOCK on same device?
I have purchased a couple of different types of DigiSpark Attiny85 clones (couldn't find originals available) and they have worked great except some devices (so far, just laptops) don't see the device AT ALL.
It's not that they don't recognise it and so is a driver issue - there is nothing to apply the driver to, no indication that the thing is even plugged in other than the light comes on (so I know it has power).
More frustratingly, if I plug the Digisparks in to any problematic device via a docking station, USB hub, etc. everything works as expected (confirming the drivers are ok) and I can write scripts to the digispark.
I've tried updating the Nucleous bootloader but the problem persists.  I get this problem on three modern laptops (HP & 2 Dells) but my older Lenovo laptops have no problems.  Not sure if here is an issue with modern USB controllers?
UPDATE: Everything points towards it just being an issue with Digispark's and some USB 3.0 controllers.  The clock is correctly set at 16.5Mhz so not sure what else to do other than write these-off as a reliable device.
Anyone had any experience of this or have any suggestions?
Thanks!

It might be the bit-banging implementation of the USB protocol via the built-in oscillator, I don't know, it's just a thought. Modern USB controllers might be picky on timing. Perhaps you can check and adjust the frequency of this oscillator. I have one of these "fake" clones (rev.3) and it works on a new and an old ThinkPad.

@thebusybee, thanks for comment - from what I've read, there seems to be issues with timing specifically with some USB 3.0 controllers which is inline with what you've said and my observations (http://digistump.com/board/index.php?topic=1622.0).
I'm not familiar with adjusting the frequency and haven't seen anything on this subject in the various posts about this issue so I suspect it might just be an inherent issue that isn't going away.  I've tried updating micronucleous to the latest version too but no luck.

Not sure why I was down-voted but I've read the criteria and don't feel like it was warranted.  Does anyone have any suggestions so I can avoid it in the future.  Personally, I'll never down-vote with commenting why I've done so.

Well, I did not downvote, because you did some research and made your issue clear. Oh, BTW, you surely mean "without commenting why", don't you? -- Perhaps someone with a logic analyzer and some USB decoder and a similar setup can shed some light on the problem. Many years ago I needed 2 weeks to find protective diodes with too large capacitance this way. -- Or, if you happen to use Linux, you could try to track the system's messages while plugging in. Or you use Wireshark and its USB driver to check at a very low level. -- Anyway, I cannot help further right now, sorry.

@thebusybee, yep you're right - I missed the "out" out If you know what I mean!).  Really appreciate the help - I'm going to give up on these boards as they are just too hit and miss!

It appears the problem is down to issues around Attiny85 timing with USB 3.0 chipsets and so isn't something that can be solved.

The four USB traces on the digistump board are NOT to perfect specification and don't work with 4/5 conductor USB3 ports.  Use a dremel or band saw and cut about 2/3 of the end off the digistump Printed Circuit Board USB plug. Leave enough of the original four traces to solder to.  Cut off the plug end from an older USB cord. After carefully cutting away and cleaning off the plastic and old wires on the actual USB plug, it fits perfectly to line up to the old (now shorter) traces on the digistump. Be sure trace sides are the same direction on old and new plug and solder all four connections.  Add some superglue and/or silicone for strength and it should work every time with any USB port.
WZ


text:
Description about arduino relay
I have this relay module. I don't understand what is a role of the jumper on it (for now it's shorting the jd-vcc (what??) and vcc pins).

The jd-vcc pin can be used to power the relay coils using a separate 5V power supply. Why would you want to do that? Each relay coil draws about 73mA @ 5VDC when energized. Theres a circuit schematic on this website: http://howtomechatronics.com/tutorials/arduino/control-high-voltage-devices-arduino-relay-tutorial/

Hello! Thanks a lot. In this diagram (http://howtomechatronics.com/wp-content/uploads/2015/09/Arduino-Relay-Module-Circuit-Diagram.png) I don't understand why it's not needed to connect in addition GND from arduino to relay, to make the same ground in the system... Can you explain it please?

@Michael  In the tutorial, he's supplying 5V to the VCC pin and grounding the In1 pin using an Arduino digital pin. Have a look at the circuit schematic on the tutorial page and follow the "path" the current is taking. Current flows from VCC, through resistor R1, through the LED inside the optocoupler and finally through a diode DS1 to pin In1 on the relay board. When the Arduino digital pin is commanded LOW, it provides the ground for the optocoupler LED, turning it on. The digital pin is only suppling a ground for an LED.

@Michael  When the digital pin is made HIGH, there is 5V at pin In1. Diode DS1 is reverse biased so current can't flow from In1 through the circuit and current can't flow from VCC through the LED because it needs a ground to complete the circuit. If you wanted to power the relay board using an Arduino, then you would leave the jumper in place and connect both the 5V and ground connections. In1 would still be connected to a digital pin and work the same way. Keep in mind that each relay draws 73mA of current when energized.

@Michael: both GND pins on the relay module are already connected, check the continuity. that said, the illustration is missing the AVR power connection, and that indeed could be isolated, in which case it's wrong, and you'd need to common all the GNDs


text:
Wake up Arduino Uno by RTC
I intend to make the device runs about couple hours a day(let say 2hrs) -> go to deep sleep -> wake up in next 7 days -> repeat the process.
I got the code from one of member here (DotPi) which I can able to make the device wake up every 10 seconds and then back to sleep. When it wakes up, the LED is flashing.
My question is how to make the LED flashes for certain amount of time. For example from 7pm to 8 pm. After that the device should go to sleep again and wait for the next alarm triggered.
I was trying to use the while loop for that but the LED always flash and never go back to sleep :(

You are setting the alarm every iteration of your loop. You want to put that in your setup() function.

even I put the "rtc.setAlarm" function in main loop, the device still repeat every 10 second as I expect. My problem is I want to flash the LED for certain amount of time (as the while loop) but the LED is always flashing and never get out of that while loop even the current minute is greater than 30.

Also asked at: http://forum.arduino.cc/index.php?topic=492180

In your while loop, you never check the time again, so when the while loops hits, you will never leave it. You need to request the time again. Something like:
while ( now.minute()>0 && now.minute() < 30)
{
   digitalWrite(ledPin, HIGH);
   delay(100);
   digitalWrite(ledPin, LOW);
   delay(1000);
   now = rtc.now(); // check time again
}

cool, I got what u mean. Silly me :D


text:
Boat project - object detection
My project is to control a dual motor model boat via bluetooth hand-held device. I am using an Adafruit feather 32u4 bluefruit LE and Adafruit DC Motor + Stepper FeatherWing Add-on. I am using the Apple IOS Adafruit Bluefreuit BLE app as the controller. I have this part of the design nearly done.  I plan to use this in a swimming pool.
How can I have the boat automatically avoid the sides of the pool or any other obstruction?  Also how can I have the boat steer toward a buoy in the water?
I would like to have any solutions as low-cost.
Thanks in advance

I'm voting to close this question as off-topic because it is about a challenging and open-ended robotics sensing problem which must be solved before the practical details of the limited aspects that an Arduino could help with can be considered.

You might be able to accomplish something with underwater sonar transducers on the sides of the boat detecting the walls at one frequency, and also differentialy listening for a sonar beacon on the buoy at another, but this is far beyond the scope of the Arduino site - both in understanding the sonar issues, and in the drive/transducer electronics for underwater use.  Similarly, an optical solution will require a far more sophisticated computation platform - the actual spinning the motors that that the Arduino could handle is relatively trivial in comparison.

Chris, I take your point about being open-ended, but I was unaware that open-ended questions were off-limits.  Sorry.  I was only asking for some ideas some of which you included in your response.  I thank you for that.

Open-ended questions don't really fit the Stack Exchange model in general, but the main point is that this isn't ready for the Arduino site yet - you have a robotics problem, then an electronics one, and only possibly at the end an Arduino one.   It does occur though that your needs are likely short range enough that you may not need efficient underwater transducers, but merely audio parts that can tolerate being wet and be operated in bistatic mode - neither of which is true of the HC-SR04 type modules familiar to Arduino folks.

Thanks for all your feedback Chris.  This was my first post and I now have more of an understanding of the types of questions that this site is designed for.  Future posts will keep that in mind.  I love the site... a great resource for people who enjoy arduino projects like myself.

@Will, please take another look at the tour at https://arduino.stackexchange.com/Tour and you can see that the whole idea is to set a goal, make an attempt to make it work, then when you need help, post your efforts (including code) as you form a specific question that will generate useful answers.  This is a database where people with similar problems can find answers.  Their queries are usually pretty specific.  I can't vote to close a first post on the first day, but I highly suggest that you edit this question to make it conform to the way people will use this in the future.

@SDsolar - while that is correct, a question like this probably can't be edited to fit the Arduino site at this point, because the information being sought right now is precisely that which would narrow the broadness and off-topicness that keeps it from being a fit.


text:
Arduino NRF24L01+ arduino to netmf transmit issue
I want to communicate between Arduino Mini Pro (china import) and a stm32f4 running netmf runtime. At the moment I'm able to communicate between SPI1 and SPI2 on the stm32 board.
After that I switched on the Arduino. I'm using the RF24 library and modified the GettingStarted sample to simply open pipes and send the same byte array again and again to the stm32.
It works for the first transmit but after that I did not receive any interrupts on the receiver side.
Both NRF24L01+ are power supplied by a breadboard power supply module which supplies 500ma (max USB bus). The Arduino is connected and power supplied by a CP2102 USB/Serial adapter.
NETMF Address: 0F0F0F0F0F
Arduino Address: 0F0F0F0F0E
As arduino uses little endian, I reverse the bytes on stm32 side before writing the address into the pipe. But I'm already unsure if I need that step (adding the Arduino address on netmf side).
Here's my Arduino code:
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"

RF24 radio(9,10);

const int payload_size = 4;
const char payload[] = "PING";

void setup(void)
{

    Serial.begin(57600);
    printf_begin();
    radio.begin();
    radio.enableDynamicPayloads();
    radio.setChannel(77);
    radio.setAutoAck(true);
    radio.setRetries(15,15);
    radio.setDataRate(RF24_2MBPS);
    radio.openWritingPipe((uint64_t)0x0F0F0F0F0FLL);
    radio.openReadingPipe(1,(uint64_t)0x0F0F0F0F0ELL);
    radio.stopListening();
    radio.printDetails();
}

void loop(void)
{
    unsigned long time = millis();
    bool ok = radio.write( payload, payload_size );

    if (ok)
        printf("SUCCESS %lu...\n",time);
    else
        printf("fail %lu...\n",time);

    // Try again 1s later
    delay(1000);

}

Here's my NETmf code
NRF24L01Plus _module = new NRF24L01Plus();

public override void Init()
{
    _module.Initialize(SPI_Devices.SPI2, Pins.GPIO_PIN_D_8, Pins.GPIO_PIN_D_10, Pins.GPIO_PIN_B_12);
    _module.Configure(new byte[] { 0x0F, 0x0F, 0x0F, 0x0F, 0x0F }, 77, NRFDataRate.DR2Mbps);

    // both handlers are never executed
    _module.OnDataReceived += this.OnReceive;
    _module.OnInterrupt += _module2_OnInterrupt;

    _module.Enable();

}

Need to see your code. From my experience with RF24 library GettingStarted example, is its not asynchronous. Meaning, one must be listening and the other should be sending.

I've added the code sample

I am not familiar with the NRF24L01Plus library or NETmf. Does NETmf support c? I think the RF24 Library needs to be on both devices. I am not 100% sure.

I have a couple of projects that use the NRF24L01+ and the RF24 Library.
As I mentioned in my comment, the examples provided is not asynchronous. I am not sure if the library supports asynchronous operations. Nevertheless, in your example, one radio should be in transmit mode and the other receive. If you look at the examples, the author uses modes (role_ping_out and role_ping_back). Basicly, the author wrote the code so you can both send and receive. But you can't do send and receive at the same time.
If you look at the example cope in the library, you can see where you need to stop receiving and start sending:
radio.stopListening();

// Send the final one back.
printf("Sent response.\n\r");
radio.write( &got_time, sizeof(unsigned long) );

// Now, resume listening so we catch the next packets.
radio.startListening();

And on the other radio stop sending and start receiving:
radio.startListening();

// Wait here until we get a response, or timeout (250ms)
unsigned long started_waiting_at = __millis();
bool timeout = false;
while ( ! radio.available() && ! timeout ) {
__msleep(30); //add a small delay to let radio.available to check payload
  if (__millis() - started_waiting_at > 200 )
    timeout = true;
}

// Describe the results
if ( timeout )
{
  printf("Failed, response timed out.\n\r");
}
else
{
  // Grab the response, compare, and send to debugging spew
  unsigned long got_time;
  radio.read( &got_time, sizeof(unsigned long) );

  // Spew it
  printf("Got response %lu, round-trip delay: %lu\n\r",got_time,__millis()-got_time);
}

If this is a bit confusing, I would suggest you load the Getting Started example on both your radios. Once you get that working, you can get a better idea on how it works.
Good Luck

Thanks for your answer. As I mentioned, the first transmit works. On STM32 side (NET Micro Framework) the interrupthandler gets raised and I receive the data I sent from Arduino. But after the first receive the interrupthandler never gets called again.

Hard to tell because you only posted half your code. Where the code on the receiver side?

I've added the netmf code

Keep in mind that in most cases you just need to send back Ack for feedback. The library automatically does that, so don't build your own Ack protocol.


text:
Arduino Mega2560 Hardware ID
Do all Arduino Mega2560's have the same VID/PID identification numbers when seen by a PC as a device? I am planning on designing I specific driver to work with the 2560 and wondering if I will be able to use the same driver for multiple Arduino. Can anyone confirm this? Thanks!

VIP/PID is realized by Atmega16u2 driver which implements USB device driver. Probably all revisions of *Arduino Atmega2560*s has implicitely the same VID/PID. Each piece has unique serial number. But you can upload own firmware into 16u2 to modify USB as you wish (ideally using LUFA library). It's clean solution for production hardware because you cannot use Arduino VID because of USB rules.


text:
Hiduino as a Serial-USB midi coverter
I have an Arduino Mega2560 configured to Hiduino, which makes the Arduino a driverless class-compliant MIDI interface.
I am currently converting RS232 serial I/O data to midi data using the 'hairless midi-serial' software running in the background. I am hoping that I can utilize this Hiduino interfacing to send and receive this data in the same fashion, just through the Arduino instead.
I am lead to believe this would require the MIDI library to be used to program the 2560 to understand the serial bytes coming from the controller and converting to the appropriate midi bytes into my program, and vice versa.  I am just getting into programming. Could someone could give an example of how a program could be written to send and receive this data through the Arduino?

I've jumped in quite deep these last few weeks, I am sending serial data out to the computer, and back from the computer to my controller successfully. There is a bug however, that i can only confirm occurs with Pro Tools. Once Pro Tools is open, i cannot connect Hiduino i/o to any other application besides Pro Tools without a memory error occuring.


text:
Arduino Uno with ESP8266-01. Is that any alternative way to connect Arduino Uno to Wifi
I have bought an ESP8266-01 Wifi module last month, and I am trying to connect Arduino Uno to network so that I could connect to the MQTT broker. However, I failed to upload the sketch/communicate with ESP8266 module due to the error:
espcomm_open failed
espcomm_upload_mem failed
espcomm_upload_mem failed

I think the problem is wiring problem or power supply is unstable because the ESP8266 is required 3.3V to communicate. This is how I connect ESP8266 Wifi module to Arduino Uno, and I just simply connect Arduino Uno to USB port on my laptop:

I've been searching solutions on Internet and watching tutorials but ending up with getting the same error. In addition, I am not using any resistor, capacitor when I do the connection between ESP8266 & Arduino Uno.
These are my confusions as below:

What is the best/easiest way to connect Arduino Uno to Wifi?
How can I avoid power supply issues? Maybe a Serial Adapter Wireless development board or module?
What do I need to connect Arduino Uno to Wifi?
Is it possible to connect Arduino Uno to MQTT broker without using network? I found this Ardulink but I don't know how to deal with it
Can external wifi shield solve my problem instead of using ESP8266-01?

Thank in advance

Are you trying to program the ESP8266 or program the Uno?

@Majenko I'm trying to program ESP8266, I have selected the Generic ESP8266 Board and correct COM port before I upload the sketch.

By the way, is it possible to program Uno & ESP8266 at the same time? I mean I have code for recording student attendance and it is uploaded to Uno, and I would like to publish attendance record which is stored inside EEPROM through MQTT broker to database by using ESP8266

why do you open new question same as the previous?

your question is too broad. solve one thing at a time. if you have a sketch in Uno, did you consider to use the esp0-01 with AT firmware with WiFiEsp library? without uploading your code to esp-01.

try swapping rx and tx: tx-rx, rx-tx. you also need rst-gnd on the uno.

The Arduino board does not have enough current available to power the ESP8266. You should have a 3.3 volt supply that is capable of at least 500mA. The average current consumption is typically 80mA but the peak currents can go to 600mA during a start up calibration.
You also need to use a proper level converter to connect the RX and TX of each board. The ESP8266 is NOT 5 volt tolerant.
The ESP8266 can be programmed under the Arduino framework. This is how most people use it. (rather than using the AT command set the board comes with. This is what I suggest, but is not a requirement. If you do go that way I suggest you get a NodeMCU or a Wemos type board to learn with. Just working with the ESP8266 alone. They are cheap, they have a USB to serial converter, and they have a proper regulator for Vcc.
The ESP modules are not simple to power. You have to use a good regulator and have it electrically close to the board. No 20cm jumper wires.
Continuing on with your electrical connections. Reset is not connected to ground. It should be pulled up to 3.3 volts with a resistor, typically 10K.
And external WiFi shield is a simpler option. I prefer the ESP8266 since it has a fast processor, 80 or 160Mhz. Lots of ram and up to 1MB of program space. It is my go-to board. It is a little light on IO but that is easy to add. It is cheap, and there is a huge user base for it.

I am not really familiar with these electrical connection stuffs, is that any simple way for the beginners like me? To avoid these kind of problems like power supply issues.

By the way, thank for the reply. It's really informative

The simplest way to work with the ESP8266 is to start with a development board. The ESP-01 has too few pins and less flash memory than modules like the ESP-12F, or the boards I listed. It is OK if you need to do an interface with RX/TX as you had planned. But like I said, it needs to be 3.3V. If the 3.3 volt power/signal level is acceptable for the application I would consider doing it all with the ESP. I did a data logger for work with the ESP. SD card, a current measuring chip, LCD, 3 button input, and no WiFi, as I didn't need it. Lots of power for cheap. Check out https://www.esp8266.com/

The website I listed above is a great place to get help and answers. Some of the websites, blogs, that show how someone did something is pretty hit and miss. Some good information, and some bad. And if you don't already know the right answers then you often don't know if it is good or not. The ESP8266 with the Arduino framework has been around for a few years and it is much easier to start with it now compared to 2015 when things were starting to get developed with it. This is a good introduction https://arduino-esp8266.readthedocs.io/en/latest/ It all is pretty overwhelming at first.


text:
Linked List based question
I am making a Smart Cart using RFID. The user will
have a RFID card. As soon as he swipes the card on
the RFID Reader it will identify the user and will create
a linked list for that particular user. The linked list will
contain the unique Rfid based Ids of the items purchased by the user. In my code
the problem is that after the detection of the user it is
not creating any linked list for the items/it is not detecting the items bought by the user. Both the user and items are identified by their unique ids (ie RFID tags).It is detecting the user but once the user is being detected it is not mapping the items bought with that user.
the code for the same is :
int count = 0; // count = 0
int i;
char input[12];                                   // character array of size 12
boolean flag = 0;
// flag =0

boolean comparetag(char x[12], char bb[12]) {
  boolean ff = false;
  int fg = 0;
  for (int cc = 0; cc < 12; cc++) {
    if (x[cc] == bb[cc]) {
      fg++;
    }
  }
  if (fg == 12) {
    ff = true;
  }
  return ff;
}

struct Node {
  char x[12];
  struct Node *next;
};

struct Node* X;
struct Node* point;

void printList(struct Node *n) {
  while (n != NULL) {
    Serial.print(n->x);
    n = n->next;
  }
}

struct Node* Shopping(char[]) {

  Serial.print(input);
  // Print RFID tag number
  Serial.print("Welcome User");
  Serial.println();

  Serial.print("Start Shopping ");

  struct Node* head = NULL;
  head = (struct Node*) malloc(sizeof(struct Node));

  return head;

}

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

void loop() {

  if (flag == 0) {
    if (Serial.available()) {
      count = 0;
      while (Serial.available() && count < 12) // Read 12 characters and store them in input array
      {
        input[count] = Serial.read();
        count++;
        delay(5);
      }

      if (comparetag(input, "1B006AFA9F14")) {
        flag = 1;

        point, X = Shopping(input);
      } else {
        Serial.println("not Registered User");
      }
    }
  } else {
    int c = 0;
    if (Serial.available()) {
      while (Serial.available() && c < 12) // Read 12 characters and store them in input array
      {
        Serial.print("Taking Input");
        X->x[c] = Serial.read();
        c++;
        delay(5);
      }
      struct Node* second = NULL;
      second = (struct Node*) malloc(sizeof(struct Node));
      second = NULL;

      X->next = second;
      X = second;

    }
  }
  printList(point);
}

your question is not related to RFID as the title suggest .... your question is about linked lists .... please update your question title

I don't see any code for making new nodes or linking them into a list. A linked-list needs a root (a known variable that points to the first member of the list); a way to make or acquire new nodes and link them onto the list as the number of items grows; and a way to unlink a node and "discard" it - return its memory - once it is no longer useful.
I'll offer a couple of suggestions for linked-lists, especially in processors like the Uno with limited memory:

Don't be tempted to use malloc() and free() or new and delete for a system that must run continuously. Allocating and deallocating small pieces of memory, especially when interspersed with other allocation & deallocations, will lead to fragmentation of the heap (that portion of memory used for allocating memory at run-time). The result is that the heap will end up with lots of separate pieces of memory that are free but too small for other allocation requests, so the heap has to acquire more memory to satisfy the larger allocations. It does this by reducing the stack space! Eventually the stack will grow into the heap space, and the program will fail.My solution is to define a global array of node structs; enough of them for the program's greatest conceivable need, plus a few more for safety; link them into a list of free nodes; and give new nodes to the application by deallocating one from the free list. A You need link() and unlink() functions for a linked-list anyway, so it takes very little more code to do this.
Because we're talking about memory limited processors, If I don't need more than 255 nodes, I link with array indices instead of pointers, saving one byte per node. This costs a little bit more code to index into an array than to de-reference a pointer but compilers have gotten pretty smart about minimizing even that overhead.


text:
Can't fetch data from server using arduino and esp8266
I am trying to fetch some data from my website using esp8266 and Arduino, with the help of WiFiEsp library, I have got data from the website but don't know how to save that data in an array or variable and use it, now I can only see received data on the serial monitor.
 #include "WiFiEsp.h"

#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif

char ssid[] = "moto g";            // your network SSID (name)
char pass[] = "hvats555";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "himalayavats.com";

unsigned long lastConnectionTime = 0;
const unsigned long postingInterval = 10000L;

WiFiEspClient client;

void setup()
{
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");

  printWifiStatus();
}

void loop()
{
  // if there's incoming data from the net connection send it out the serial
port
  // this is for debugging purposes only
  while (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if 10 seconds have passed since your last connection,
  // then connect again and send data
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server
void httpRequest()
{
  Serial.println();

  // close any connection before send a new request
  // this will free the socket on the WiFi shield
   client.stop();

  // if there's a successful connection
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");

    // send the HTTP PUT request
    client.println(F("GET /to_fetch/system_info.json HTTP/1.1"));
    client.println(F("Host: himalayavats.com"));
    client.println("Connection: close");
    client.println();

    // note the time that the connection was made
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection
    Serial.println("Connection failed");
  }
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

 // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

Response from arduino(in serial monitor):-
[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 1.3.0
Attempting to connect to WPA SSID: moto g
[WiFiEsp] Connected to moto g
You're connected to the network
SSID: moto g
IP Address: 192.168.43.61
Signal strength (RSSI):-372 dBm

[WiFiEsp] Connecting to himalayavats.com
Connecting...
HTTP/1.1 200 OK
Date: Fri, 05 Jan 2018 10:19:46 GMT
Server: Apache
ETag: "12c077d-12-55dc4cfa4fffd"
Accept-Ranges: bytes
Content-Length: 18
Vary: User-Agent
Connection: close
Content-Type: application/json

{"power" : "high"}      // <-- i wanna fetch this

NOTE:- Whenever I try to add anything in loop function for example:-
int i = 0;
while(client.avilable()){
    c = client.read();
    serverResponse[i] = c; // trying to save output in an array
    i++;
}

The module doesn't even fetch data from the server it keeps restarting itself.
Output from arduino after adding above code in loop funtion:-
[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 1.3.0
Attempting to connect to WPA SSID: moto g
[WiFiEsp] Connected to moto g
You're connected to the network

[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 1.3.0
Attempting to connect to WPA SSID: moto g
[WiFiEsp] Connected to moto g
You're connected to the network

[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 1.3.0
Attempting to connect to WPA SSID: moto g
[WiFiEsp] Connected to moto g
You're connected to the network

This repeating again and again

data and http header are separated by an empty line. then see ArduinoJson library

@Juraj can you please explain data and header saperately by an empty line, is it good? Arduino output is exactly like this.

what you printed is a HTTP response. starting with HTTP/1.1 status line, then there are the HTTP headers. and then the empty line separates the header from body. in the body are your data. try using ArduinoHttpClient library over WiFiEspClient, if you do not want to parse the response self.

When Arduinos unexpectedly restarts it is usually because you have drawn too much power or have caused a segmentation error or BSOD in Windows terms.  You aren't drawing to much power, so I suspect you are accessing elements of the array outside those that you should be.
Check that i never exceeds the maximum size of serverResponse, because:
char serverResonse[10]
for int i - 0; i < 50; i++)
  serverResponse[i] = 42;  // This will crash on the 11th loop.

I can't say if the above code will cause a restart, but that's dependent on what was using the 11th byte of the array before it got stomped on.


text:
A clarification needed about the HC-05
I have just got a new pair of HC-05 Bluetooth modules. I am working on a simple project. I'm trying to move two servo motors using two potentiometers. I followed a simple tutorial to move one servo, and it worked successfully.
How to make the same thing with 2 potentiometers and two servos?
UPDATE:
I have successfully managed to write down something that get to read values from two potentiometers, but I'am still facing problems with the slave part.
Can't figure out the problem.
(Master)
//Master
int potValuePins[] = { A0, A1 };
void setup() {
  Serial.begin(9600); // Default communication rate of the Bluetooth module
   for (auto pin : potValuePins) {
     pinMode(pin, INPUT);
   }
}

void loop() {
 for (auto pin : potValuePins) {
   Serial.write(pin); // Send the pin number
   Serial.write(analogRead(pin)); // Send the pin value with a trailing
 newline as a delimiter
   int value=analogRead(pin);
   Serial.print(" Pin is: ");
   Serial.print(pin);
   Serial.print("\t");
   Serial.print("Value is: ");
   Serial.println(value);
   }
 }

(Slave)
//Slave
#include <Servo.h>
Servo myServo1;
Servo myServo2;

void setup() {
Serial.begin(9600);
myServo1.attach(9);
myServo2.attach(10);
}

void loop() {
if (Serial.available()) {
 char input[3];
 Serial.readBytes(input, 2);
 int pin = input[0];
 int angle = input[1];
 Serial.print("the pin:");
 Serial.print(pin);
 Serial.print("\t");
 Serial.print("the angle:");
 Serial.println( angle);

 switch (pin) {
  case A0:
    myServo1.write(angle);
    break;
  case A1:
    myServo2.write(angle);
    break;
  default:
    Serial.println("Unknown value");
    break;
   }
  }
 }

Looking at the example you linked to, the "communication" between the two ends is just writing a (byte) value between 0 and 255, and reading that on the other end.
One simple (out of many possibilities) to extend this to handle a set of two is just to send 2 bytes in sequence, with the first byte being an identifier of which servo you are denoting.
Where the example master code shows:
// Reading the potentiometer
potValue = analogRead(A0);
int potValueMapped = map(potValue, 0, 1023, 0, 255);
Serial.write(potValueMapped); // Sends potValue to servo motor

You instead write:
// Reading the potentiometer 1
pot1Value = analogRead(A1);
int pot1ValueMapped = map(pot1Value, 0, 1023, 0, 255);
Serial.write(1);
Serial.write(pot1ValueMapped); // Sends pot1Value to servo motor

// Reading the potentiometer 2
pot2Value = analogRead(A0);
int pot2ValueMapped = map(pot2Value, 0, 1023, 0, 255);
Serial.write(2);
Serial.write(pot2ValueMapped); // Sends pot2Value to servo motor

And on the slave side, where the example has:
if (Serial.available() > 0) { // Checks whether data is comming from the serial port
  state = Serial.read(); // Reads the data from the serial port
}
// Controlling the servo motor
myServo.write(state);

You have to separate out the two possible choices:
if (Serial.available() > 0) {
  servo_num = Serial.read();
}
if (Serial.available() > 0) {
  state = Serial.read();
}

switch (servo_num) {
  case 1:
    myServo1.write(state);
    break;
  case 2:
    myServo2.write(state);
    break;
}

Note that you'll also have to declare the servo_num variable, and instantiate two of the Servo objects. The code above is just a guide.
The simple expansion above is not robust, as it's possible that the 2nd byte is not received by the time the 2nd Serial.read() is called, and then that byte would be caught next time around the loop() by the first Serial.read() call and you'd be out of sync. But hopefully, this shows the general concept of how to start developing a protocol that is more complex than just single values.
Edit: What's probably happening is the system is getting out of sync. As I noted, it's not a robust protocol, but I think you may now understand the idea.
You can re-map the servo values to go from 2-255, rather than 0-255, and set the servo_num to either 0 or 1. In the slave, if you get a number <2, then it's a servo selector, otherwise it's a servo value. but then you lose the ability to set the servo to 0 or 1.
Also, you may want to space out the master sending the values, as you are likely sending data faster than the servo could respond. You could put a delay(100) or something in the loop() function, or change your code to use a millis()-based state machine (see the "BlinkWithoutDelay" Arduino example).

I have set the " pot2Value = analogRead(A0); " to A1, the pin in which I have inserted my second potentiometer.
I have done what you told me too, the servos are not moving the way they are suppose to.
both of them are moving at the same time and not following the potentiometers.
moving constantly.

I left the rest of the coding as an exercise to the reader :-)  How did you instantiate both Servo objects?

Servo myServo1;
Servo myServo2;
and I attached each one of them to the pin I'am using .

Edit/append the updated code you wrote to the question, or join the Pin 13 chat room and we can discuss it

I need to have 20 reputation in order to join the chat room, which I don t have them "yet" so I updated the post.

I added some other options. I'm trying to keep it simple and conceptual. You  could also go into a more complex protocol where you need to implement a state machine and tag the various parameters within the protocol. You'll likely want to go that route, but I hope I answered basically "how" you can do this. The HC-05 can send bytes, but you aren't limited to just one byte as the only data element. You can send series of bytes, etc.

I am still quiet new to the world of arduino and programming.
Its still a bit foggy what you have just said but I will try to look it up and understand what should be done.
Thank You.

Search for articles/examples on serial communication protocols, since that's what you want. You can move a servo already, and you can send a byte. Now you need to expand your knowledge to be able to do more! https://henryforceblog.wordpress.com/2015/03/12/designing-a-communication-protocol-using-arduinos-serial-library/

Can't be thankful enough for your help. :D


text:
How to Display data from Strings?
I am working in an interactive project in displaying texts in POV which people can click to generate different texts automatically.
I wrote a String to store the text first, but it seems cannot display it.
Then I change the code to use char* to store the text, but it still does not work.
Can anybody help to solve this problem....?
char* myStrings[] = {
  "a", "c", "d", "f",
  "b", "e", "v", "B", "C"];

The code:
loop(){

  //xbee
  // potVal = analogueRead(potPin);
  // xbee.println(potVal);
  for (int t=0; i<sizeof(myStrings)-1; i++) {
    displayChar(myStrings[i];
  }
  for (int i=0;i<7; i++)
    digitalWrite(leds[i],LOW);
  delay(10);

You intend for myStrings to be an array of strings, or an array of c-strings (char*) , or an array of individual characters? the name suggents one thing, but displayChar(myStrings[i]); seems to suggest the other.

I intend to make myStrings an array of 9 char* ... store 9 characters... once arduino receive command from processing so it can display one of the character...but now it can not access to the data in myStrings ?                                                  char* myStrings [9] = { "a", "c", "d", "f", "b", "e", "v", "B", "C"};                        Sorry for the poor explanation...Any help would be greatly appreciated.

an individual character is just a char, a c-style string of one or more characters is a char*. I'm still not certian, do you want myStrings[i] to be the i'th single character from the string "acdfbevBC", or do you want it to be the i'th of 9 unrelated strings?

yes...I want myStrings[i] to be the i'th single character from the string "acdfbevBC"... but now I got confused with the code and I don't know how to correct it... Really appreciated for your help btw!

First thing, in C++ (or C) a character in single quotes is just a single lone character, but any characters in double quotes is a string literal. for example "hello" is a const char[6] containing the characters 'w','o','r','l','d','\0'. That extra '\0' is the null terminator that makes an array of chars into a c-string.
Your code is making a variable
char* myStrings[] = { "a", "c", ... };

This is an array of char*, which means each element is a char*, which in turn means each element is a full string (in your case each has 2 characters).
You want an array of single characters, which means you either drop the * in char*, or drop the [] in myStrings[], and use either an array of single characters {'a','b',...}, or a single string literal "acdfbevBC". Any of these lines will work in your code:
const char * myStrings = "acdfbevBC";
char myStrings[] = "acdfbevBC";
char myStrings[] = { 'a', 'c', 'd', ... 'C', '\0'};

If you never plan to print myStrings as a unified string, you can leave off the '\0', the null terminator is there so functions that you pass it to know when it stops without you having to explicitly pass how long the string is.
Also, the first line is const char * because you should never overwrite a string literal. char myStrings[] is fine without const because the compiler is using the literal to initialize an array that gets its own place in memory, not making myStrings point into a separate cache of string literals.
Check out cpp reference's details here for more details on string literals.

Like the error message says, each entry is a char*. Convert it to an array of characters instead.