text:
LED Blinking Using Push button
Whenever I upload the following program I am getting error message
showing "expected initializer before interval".
Kindly Help me to solve out this probleme.
const byte button=2;
const byte LED=10;
bool blinking =false;//defines when blinking should occur
unsigned long blink Interval=250;// number of milliseconds for blink
unsigned long currentMillis;// variables to track millis()
unsigned long previousMillis;
void setup()
{
    pinMode(button,INPUT);
    pinMode(LED,OUTPUT);
}
void loop()
{
    // this code  blinks the LED
    if(blinking) {
        currentMillis =millis();// better to store in variable, for less jitter

        if((unsignedlong)(currentMillis-previousMillis) >=blinkInterval) { // enough time passed yet?
            digitalWrite(LED,!digitalRead(LED)); // shortcut to toggle the LED
            previousMillis =currentMillis;// sets the time we wait "from"
        }
    } else {
        digitalWrite(LED,LOW); // force LED off when not blinking
    }

    int reading=digitalRead(button);
    delay(50); // crude de-bouncing

    if(reading==LOW) // buttons with pull-up are pressed when LOW
    { blinking =true; }// start blinking
    else
    { blinking =false; }// stop blinking
}

It is blinkInterval, not blink Interval. You have an space in the name in the declaration:
unsigned long blinkInterval=250; // number of milliseconds for blink
// ....
if((unsigned long)(currentMillis-previousMillis) >= blinkInterval) {

@Josephazim. That's not a problem; that's your code. When button goes HIGH, you put blinking=false. You have to introduce a waiting time there, but that is a new problem.

Thanks!It worked as you suggest but now my problem is that when I keep holding the button led is blinking and when I release the button it stop.I want it to be when I hold the push button for 5 sec, then led should start blinking for 10 minute or according to the certain time.Kindly help me to solve this problem.

@Josephazim Check out my answer. It will helpful for you.

@NickGammon I think you have to check this comment section. I answered according to that problem.

The fully working sketch
const byte button=2;
const byte LED=10;
bool blinking =false;
unsigned long blinkInterval=250;
unsigned long currentMillis;
unsigned long previousMillis;
void setup()
{
    pinMode(button,INPUT);
    pinMode(LED,OUTPUT);
}
void loop()
{

    if(blinking) {
        currentMillis =millis();

        unsigned long blinkInterval=100;
        if((unsigned long)(currentMillis-previousMillis) >= blinkInterval) {
            digitalWrite(LED,!digitalRead(LED)); LED
            previousMillis =currentMillis;
        }
    } else {
        digitalWrite(LED,LOW);
    }

    int reading=digitalRead(button);
    delay(100);

    if(reading==LOW)
    { blinking =true; }
    else
    { blinking =false; }
}


text:
EEPROM - Arduino
In my recent project, I want to store values permanently. So for that, I want to use the EEPROM. I searched for it and read about it. Now, I have some questions.
Questions:

How many locations are there in the EEPROM? (For Arduino Uno & Mega)
I read that an EEPROM has a limit of 100,000 write cycles per
  single location. That means if one location is used 100,000 times then
  we can use another after that? Or overall the EEPROM has a limit of 100,000 write cycles?
So, what about reading the contents of the EEPROM? Does it have the same limit?
And what is the starting location (address) of the EEPROM? (For Arduino Uno & Mega)

EDIT:1

Suppose I store the HIGH value of LED in one location and the LOW value of LED in another one. Then now read the value from that locations. Now how many times I can read this value? So what about write cycle? It just uses for only one time maybe?

Any better option for storing data permanently?

(1) How many locations are there in EEPROM? (For ARDUINO UNO & MEGA)

Read the datasheet for the chip on the board. It tells you how many bytes or kilobytes the chip has for EEPROM. For instance the ATMega328P on the Uno has 1024 bytes (1k).

(2) As I read out EEPROM has a limit of 100,000 write cycles per single location. That means If one location is used 100,000 times then we can use another after that? Or Overall EEPROM has a limit of 100,000 write cycle?

Each cell has at least a 100,000 write limit. Or more specifically a 100,000 erase limit (since a cell must be erased before writing).

(3) So, what about reading the content from EEPROM? Has it maybe same limit?

No, no limit - the limit as I mentioned is on erasing: you don't erase when reading.

(4) And what is starting location(address) of EEPROM? (For ARDUINO UNO & MEGA)

Zero.  It's not really part of any address space, it uses special instructions and registers to get at it.

source: Stack Exchange

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

sort: votes


text:
Arduino HTTP Post request
I have a Arduino Mega with Wiznet 5100 Ethernet shield. Am trying to post some data onto localhost for started later on which will be accepted by a website.
But when I try to post the data I get some error. When I try to send the same data via postman it gets accepted . But when it goes from arduino error occurs.
The arduino Code is as follows:
client.println("POST /api/trackers/5a28eddaf57a6e2060e85601/solars/5a3bb2adf57a6e1a71ca135b/arduino_data HTTP/1.0");

client.println("Host: 192.168.6.16");

client.println("Accept: application/vnd.mirasol.v1");
Serial.println("After Accept application vnd");

client.println("User-Agent: Arduino/1.0");
Serial.println("After User Agent Arduino");

client.println("Accept: application/json");
Serial.println("After Accept application json");

client.println("Content-Length: ");
Serial.println("After content length");

client.println(postdata.length());

client.println("Content-Type: application/json");
Serial.println("After content type application json");

client.println("Connection: close");
Serial.println("After connection close");

client.println();
Serial.println("After client println");

client.println(postdata);
Serial.println("After post data");
Serial.println(postdata);

The output in the serial monitor is as follows:
    connecting...
connected
After Accept application vnd
After User Agent Arduino
After Accept application json
After content length
After content type application json
After connection close
After client println
After post data
{"current":10.50, "voltage":10.50}
H
disconnecting.

And the error shown in localhost is as follows:
2017-12-27 15:21:57 +0530: HTTP parse error, malformed request (): #<Puma::HttpParserError: Invalid HTTP format, parsing fails.>

I have the application in Ruby on Rails with Mongoid as the DB.
FYI: New to coding..

Your problem most likely stems from this bit:
client.println("Content-Length: ");
Serial.println("After content length");

client.println(postdata.length());

You have an extraneous "ln" in there causing the post data length to be on a separate line from the Content-Length:
Content-Length:
23

You should change the first println to a print. Also the order could do with changing to keep things logically grouped:
client.print("Content-Length: ");
client.println(postdata.length());

Serial.println("After content length");

Which would result in:
Content-Length: 23

Well did that and the rails server responded... But now am getting Completed 204 No Content . I want to send the data from the body instead of the URL to keep the security good in a way.

I would suggest, for debugging, duplicate all client prints to the serial so you can see precisely what is being sent to the server.

That 204 was there since I had not given any view or response for when the request would come in... Just went into the function and added a json response to it and it worked like a charm ... Kudos to u for helping ...

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


text:
Detecting the presence of a specific smartphone
I would like you to give me some clues about a projet I have: I want to make sure that my little brother's smartphone stays in a shelf overnight and during school hours in order to monitor the time he spends with it.
In order to fulfill my needs, I thought of using an Arduino to detect that the smartphone stays in proximity at certain hours.
Since this is my first Arduino project, I'm not quite sure what I could do, and what is possible to do.
Hence I've got a lot of questions:

Can I easily detect that a specific smartphone is in range?
Can I use the smartphone's NFC (RFID) to do so?
What kind of output could I possibly get from an Arduino? I would like to make statistics, so it must be stored somewhere, and I know Arduino doesn't have a lot of memory.
Is it possible to write on a USB key?
Which Arduino is best suited for my needs Should I consider buying an Arduino with Ethernet in order to send emails?

Thanks a lot!

I'd suggest looking into the apps that exist, that will let you schedule phone/app usages. Something like e.g. http://ourpact.com/ .

Can I easily detect that a specific smartphone is in proximity ?

It can be done, yes. How "easily" depends on how much money and expertise you have to throw at it.

Can I use the smartphone's NFC (RFID) to do so ?

It is possible to use that, yes - if you add the right hardware and software to the Arduino.

How long can an Arduino run on battery using a 9V battery from the market ?

A couple of hours if you're lucky. They are useless batteries.

What kind of output could I possibly get from an Arduino ? I would like to make statistics, so it must be stored somewhere, and I know Arduino has not a lot of memory.

Whatever you want. Again, it's SMOP / SMOH.

Is it possible to write on an USB key ?

Sure, if you get the right hardware for that.

Which Arduino is best suited for my needs ? Should I consider buying an Arduino with Ethernet in order so send email ?

The Arduino that provides the facilities your project requires - and that depends on how you are going to decide on how to do it. Remember: the Arduino is just the "brain" of the operation. You need to decide what "organs" the brain needs to control and in what way.
There's a million and one ways of achieving what you want. You could even do it 100% in the phone in software (there's probably an app for that...) without need of an Arduino...


text:
Supervised inputs for alarm panel
I'm using an Arduino Mega 2560 to make a fire alarm control panel. The control panel takes 50 (inputs) supervised inputs. The normal way as mentioned in the link is to use the analog inputs, which I am short of. Is there any other way to monitor supervised inputs other than using analog inputs?
Thanks in advance for your time – if I’ve missed out anything, over- or under-emphasized a specific point let me know in the comments.

I can think of a number of ways of doing this:

Multiplexing -- Employ a (large) number of analog MUX chips to expand the number of analog inputs you have available. That would get messy very quickly.
External ADC Chips -- Add more real analog inputs over SPI or I2C. For 50 inputs that would be quite a lot of extra chips.
Use Op-Amps -- Each input can be converted into a pair of digital inputs using two op-amps to compare the voltage of the input against two thresholds, which would give you an "active" and a "fault" signal. That would be 100 digital inputs needed (and 100 op-amps, which could be done with 25 quad op-amp chips).
Distributed processing -- Don't try and do it all with one device. Split your system into zones with far less inputs then get the zones to communicate with each other.

Of course, you can combine any of those - you could have analog MUX chips fanning out a number of external ADC chips inputs. You could MUX the inputs to the op-amps. You could have external ADC chips on multiple zone systems. Etc.
Personally, on a system of this size, I would certainly consider distributing the inputs across multiple processors even if they are all in the same physical control unit. However, distributing nodes across the building (it sounds like it's quite a large building for 50 inputs) would reduce the amount of cable needed to implement those inputs, and some industry standard bus snaking its way around the building connecting all the nodes up to a master unit would, if implemented correctly, be robust. CAN is a popular protocol for interconnecting control systems (it's used in modern lifts, and those are life critical... you don't want a lift to fail...) so could be a good choice for this.

The distributed processing option is scalable; just add more units. And with WiFi capabilities, no need for wiring to a central command.

@LookAlterno I'd be wary about using WiFi for a fire alarm system...

If I use the method 3, can I use encoders to reduce the number of inputs

Encoders....? Shift registers, sure. Io expanders, yes. Encoders? Makes no sense.


text:
Can I measure multiple photoresistors from one pin?
I would like to make a laser sensor to detect light coming from a 650nm diode. My current idea would be to use CdS photoresistors/LDRs. I want to measure a few (4-8?) at once, where light falling onto any one of them generates a signal - I don't care from which sensor it actually came. However, I would like to put as many sensors on as few pins as possible.
I've already somewhat figured out that putting LDRs in parallel isn't ideal, because any changes in voltage will become smaller the more I use. Instead, it would seem like a better idea to build some kind of 'switch' by putting each LDR together with a fixed resistor and a transistor. How exactly would a circuit for this look like, or are there better ways to do it?

Can you check this post. I think that what you want https://arduino.stackexchange.com/questions/4027/reading-many-analog-signals-in-arduino

So you want open collector bus and transistors will be used as comparators to pull the bus LOW if any of sensors is active?

I still think the parallel solution could still work. You just have to lower the value of the (pull-up) resistor, to get a bigger range of different values.

solar cells (PV) are much faster than CDS and unlike resistors, can be chained in series.

Depending on how much light falls on it, an LDR can see its resistance fall by several orders of magnitude. Thus, putting several LDRs in parallel could definitely work. Shining a laser on one of them will effectively short the whole parallel assembly into a very low resistance.

If response time is critical (on the order of about a quarter of a second) consider using photo diodes instead of Cadmium sulfide cells.
Also, consider using an Arduino with more ADC ports.  The number of ADC ports is usually a constraint of the processor used.  Different Arduinos use different processors.  Some may have more ADC ports.
Finally, to utilize a single ADC port for multiple unknown resistances, consider using a resistor network where all the unknown resistances and a known pull down resistance are connected to the ADC port. Then, in turn, using as many Arduino digital pins as there are unknown resistance, apply a digital high to only 1 unknown resistance. Keeping the digital pins to all the other unknown resistance in a high impedance state. That is, change them from OUTPUT to INPUT digital ports. Then take an ADC sample. Apply this same procedure for all the other unknown resistances. Consider adding a delay after changing the state of the digital pins to allow for the ADC input to acclimate to the new voltage.

simulate this circuit – Schematic created using CircuitLab

I think you can take them paralel to each other and in series with a simple resistor. The point within the series can be used as input voltage. Everytime the input voltage is higher than the reference voltage you can generate an interrupt from the comparator. This means if one of x resistors decreases its value this will affect the upper half resitance. Simply it will decrease the value too. Because of this the input voltage will increase and will be above of the reference voltage. This will produce interrupt (signal).
The Question is how accurate will it work. The resistors are nor 100% accurate because of that the circuit will not work accurate. What can accept? What is OK and what not?


text:
How to loop a specific tone?
I am building a security system, and found the following code
#define NOOT_B0  31
#define NOOT_C1  33
#define NOOT_D1  37
#define NOOT_E1  41
#define NOOT_F1  44
#define NOOT_G1  49
#define NOOT_A1  55
#define NOOT_B1  62
#define NOOT_C2  65
#define NOOT_D2  73
#define NOOT_E2  82
#define NOOT_F2  87
#define NOOT_G2  98
#define NOOT_A2  110
#define NOOT_B2  123
#define NOOT_C3  131
#define NOOT_D3  147
#define NOOT_E3  165
#define NOOT_F3  175
#define NOOT_G3  196
#define NOOT_A3  220
#define NOOT_B3  247
#define NOOT_C4  262
#define NOOT_D4  294
#define NOOT_E4  330
#define NOOT_F4  349
#define NOOT_G4  392
#define NOOT_A4  440
#define NOOT_B4  494
#define NOOT_C5  523
#define NOOT_D5  587
#define NOOT_E5  659
#define NOOT_F5  698
#define NOOT_G5  784
#define NOOT_A5  880
#define NOOT_B5  988
#define NOOT_C6  1047
#define NOOT_D6  1175
#define NOOT_E6  1319
#define NOOT_F6  1397
#define NOOT_G6  1568
#define NOOT_A6  1760
#define NOOT_B6  1976
#define NOOT_C7  2093
#define NOOT_D7  2349
#define NOOT_E7  2637
#define NOOT_F7  2794
#define NOOT_G7  3136
#define NOOT_A7  3520
#define NOOT_B7  3951
#define NOOT_C8  4186
#define NOOT_D8  4699

 int melody[] = {
// NOOT_C4, NOOT_G3, NOOT_G3, NOOT_A3, NOOT_G3, 0, NOOT_B3, NOOT_C4
NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8
};
int NOOTDurations[] = {
 4, 4, 4, 4, 4, 4, 4, 4
 };
 void setup() {
    // iterate over the NOOTs of the melody:
  for (int thisNOOT = 0; thisNOOT < 8; thisNOOT++) {

// to calculate the NOOT duration, take one second divided by the NOOT type.
//e.g. quarter NOOT = 1000 / 4, eighth NOOT = 1000/8, etc.
int NOOTDuration = 1000 / NOOTDurations[thisNOOT];
tone(8, melody[thisNOOT], NOOTDuration);

// to distinguish the NOOTs, set a minimum time between them.
// the NOOT's duration + 30% seems to work well:
int pauseBetweenNOOTs = NOOTDuration * 1.50;
delay(pauseBetweenNOOTs);
// stop the tone playing:
noTone(8);
  }
 }

void loop() {
int melody[] = {
 // NOOT_C4, NOOT_G3, NOOT_G3, NOOT_A3, NOOT_G3, 0, NOOT_B3, NOOT_C4
 NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8
  };
 int NOOTDurations[] = {
  4, 4, 4, 4, 4, 4, 4, 4
  };

  }

How can i let the specific tone loop? Right now it's not within the loop and i am struggling to make it work in the loop. Thanks in advance!

So put the parts you think you need in the loop() and see what happens. If it doesn't work, post a specific question.

#include "Arduino.h"

const byte TONE_PIN = 4;
const int ALARM_BEEP_1 = 4186;
const int ALARM_BEEP_2 = 4699;

const int ALARM_TONE_LENGTH = 200;
const int ALARM_TONE_PAUSE = 800;
const int ALARM_TONE_REPEAT = 6;

boolean alarm = false;

void setup()
{
  alarm = true;
}

void loop()
{
  if (alarm) {
    alarmSound();
  }
}

void alarmSound() {
  static unsigned long next = millis();
  static byte count = 0;
  if (millis() > next) {
    next += ALARM_TONE_LENGTH;
    count++;
    if (count == ALARM_TONE_REPEAT) {
      next += ALARM_TONE_PAUSE;
      count = 0;
    }
    tone(TONE_PIN, (count % 2) ? ALARM_BEEP_1 : ALARM_BEEP_2, ALARM_TONE_LENGTH);
  }
}


text:
Arduino uno PWM CTC mode - strange behaviour on interrupt
i have this simple code that i use for generating a square wave signal of 125 KHz on pin 9 using Timer1 in the "Clear Timer on Compare Match (CTC) Mode".
I also use Timer1 Compare Match A interrupt for toggling pin 7 of PORTD.
void setup() {
pinMode(9, OUTPUT);
pinMode(7, OUTPUT);

TCNT1 = 0;
TCCR1A = 0;
TCCR1B = 0;

OCR1A = 7;
TIMSK1 = _BV(OCIE1A);
TCCR1A = _BV(COM1A0);
TCCR1B = _BV(CS11) | _BV(WGM12);
}

void loop() {
}

ISR(TIMER1_COMPA_vect)
{
  PORTD = PORTD ^ 128;
}

It happens that

The 125KHz waveform on pin 7 is delayed by 1us with respect to the waveform of pin 9. I think that is related to the time that the microcontroller takes to "entering" the interrupt function and toggling the PORTD pin (1us are 16 clock cycle of the 16MHz master clock).
Sometimes the waveform on pin 7 (the one generated inside the interrupt service routine) has some "gaps". For example, this is the waveform acquired with my scope:Why this strange behaviour happens?

Thank you

This isn't the only ISR in the Arduino, there is at least the one counting millis. Counter 0 overflow ISR is not as short as yours, so every 1024us it'll cause some jitter (or as in your case, skipping the edge and basically inverting the phase). It'd be also several clock cycles delayed (against HW generated signal). Pushing and poping the registers into the stack are the deterministic delays, but the latency between setting the ISR flag and calling the ISR routine depends on currently executed instruction (some of them takes 2cycles, and there are also longer ones).
There is not much time to do anything else either. Your ISR might take less than 20 cycles, but you only have 64 cycles (ISR is called at 250kHz rate so it generates 125kHz signal).
So if anything else prevents your ISR to be called (another ISR, disabled interrupts), you can miss them, as there is only one interrupt flag.
If you want the same waveform on pin 7, just use a wire and let the pin mode as INPUT.
BTW: You don't have to use PORTB = PORTB ^ _BV(PB7);, the PINB = _BV(PB7) toggles PB7 without read-modify-write access.

This is a good oportunity to talk about how to keep things in sync (drifting, missing beats).

Thank you for the detailed explanation! Also setting TCCR0A and TCCR0B to zero solved the problems with the "gaps".

@Anacleto but be aware of using anything related to millis like delay. It's exactly the same problem as you can't use the delay in another ISR.


text:
WEMOS: How to install it?
I have been using an Arduino Uno for a year now, and I bought a WEMOS D1 Mini and a NodeMCU. I want to select WEMOS or NodeMCU from the Arduino Web Editor but it doesn't appear on the list:

I think I need to install a driver but it's only for the Arduino desktop editor (not for the web editor).

I don't believe you can. Only Arduino can do that sort of thing, since it's their web server.

You have to go to the website and download the driver. Also make sure you add the ESP8266 stable to ur preferences

I just read that it can't. It's a shame:
https://forum.arduino.cc/index.php?topic=441328.0


text:
Arduino Uno: Driving a small LED strip with 2N3904 NPN
I'd like to know why I cannot dim the small LED strip with my design. I can only turn them on and off. This is a problem for me as I wanted to have a fade effect. Here is my circuit:

The voltage from the power jack is 5 volts. My NPN transistor is a 2N3904 (from left to right: emitter, base, collector).
For the Arduino I am only using the fade exemple sketch:
int led = A2; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
   pinMode(led, OUTPUT);
 }

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
     fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

By the way, this is my first post so please tell me if something is wrong with it! Thank you for your help!
Have a nice day.

The voltage from the power jack is 5 volts - what do you mean by that? Are you feeding 5V into that thing at the top of the picture (into Vin?). I'm a little surprised the LEDs light up at all, since the forward voltage for a red LED is around 2V, and with 5 in series, they will be getting 1V each.

The analogWrite works only on PWM pins (in your scheme it's marked by ~). On the other pins it's possible to set only LOW/HIGH (values under 128 are translated to the LOW)
Not to mention weirdly used NPN with LEDs as negative feedback. But that's why it doesn't burned out yet. The usual way is connect the Emmiter to the ground and base is driven over current limiting resistor (about 1k).
This is how we usualy use PNP transistor (again with 1k resistor and emitter to the Vcc, not the collector). But PNP won't work with 5V logic and higher Vin than 5V as there will be current flow from 0V or 5V to the Vin.

The unusual NPN connection you show is called an emitter follower circuit.  The emitter will follow the base voltage -.7V or -1.4v for a darlington. I assume you are powering it by the USB.

@gil He has 5 LEDs in series (roughly about 9V @ 10mA) and emmiter follower with 0 or 5V in the base...


text:
How to store values from a sensor inside an empty array?
I need to store the value of the distance in the dist array, then calculate the maximun value and print the index associated with this value:
The problem is when starting the nested for inside another for, the servomotor stops working
// Includes the Servo library
#include <Servo.h>

// Array y valores para funcion valor maximo

int max=0;

int angle=0;

int distance=0;

// Defines Tirg and Echo pins of the Ultrasonic Sensor

const int trigPin = 10;

const int echoPin = 11;

// Variables for the duration and the distance

long duration;

//int distance[180];

Servo myServo1; // Creates a servo object for controlling the servo motor

void setup() {

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output

  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

  Serial.begin(9600);

  myServo1.attach(12); // Defines on which pin is the servo motor attached
  }

void loop() {

distance = calculateDistance();
  if (distance <= 15 && distance >=2)
  {

  // rotates the servo motor from 1 to 179 degrees and calculate the distance at each angle

  for(int j=90;j>=0;j--){

  myServo1.write(j);

  delay(30);}

  for(int j=0;j<=180;j++){

  myServo1.write(j);

  int i=0;

  int  dist [i] = {calculateDistance()};

      for (i=0;i=180;i++){           <--------------------------------------

       if (dist[i]>max){
      max=dist[i];
      angle=i;
      Serial.print(angle);
      delay(30);}

  }
      }

  // Repeats the previous lines from 179 to 90 degrees

for(int j=180;j>90;j--){

  myServo1.write(j);

  delay(30);

  }
}
}

// Function for calculating the distance measured by the Ultrasonic sensor
int calculateDistance(){

  digitalWrite(trigPin, LOW);

  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds

  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds

  distance= duration*0.034/2;

  return distance;

}

  int i=0;
  int  dist [i] = {
    calculateDistance()      };

I'm not sure what you are thinking here, but you obviously cannot store data into a zero-length array. You also cannot put a function call to populate an array of variable length.
You need to decide how many elements you need in the array, in advance, and allocate an array of that size.

Maybe more like this:
 int  dist [180];

  for (i=0;i<180;i++){
    dist [i] = calculateDistance ();
    if (dist[i]>max){
      max=dist[i];
      angle=i;
      Serial.print(angle);
      delay(30);
    }

  }

Also, this is wrong in your code:
for (i=0;i=180;i++){

You need to test for < 180 here. Your for loop will assign 180 to i and then check to see if it is non-zero, which will always be true.

I modified this part of the code and the problem is the same. Actually I do not know if I'm saving the data in the array with this instruction :/

It doesn't do the first for loop instruction, the servo only runs from 0 to 90 degrees and stops working.

You need to put in some debugging "prints". It's hard to tell what is happening. What value gets stored in distance, for example?

In distance variable gets stored the value of distance which was measured of the Ultrasonic Sensor.

Obviously. I meant what number are you seeing? Zero? 20? 100?


text:
Pause running program using a pushbutton
I have a program that flashes three LED in sequence indefinitely. How can O program a pushbutton to pause the program in the middle of the code?
Also, can I modify the code so that pressing the button a second time would speed up the flashing of the LED?
Each time I try to use a pushbutton to pause the program, it only pauses it once the program loops back to the beginning.
Here's my code at the moment (sorry, it's not very clean):
int ledpins[]   = {4, 5, 6};
int buttonpin   = 3;
int buttonstate = 0;

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

  for (int pin = 6; pin > 3; pin--) {
    pinMode(ledpins[pin], OUTPUT);
  }
  pinMode(buttonpin, INPUT);
}

void loop() {
  buttonstate = digitalRead(buttonpin);
  if (buttonstate == HIGH) {
    digitalWrite(ledpins, HIGH);
  }
  if (buttonstate == LOW) {
    for (int pin = 4; pin < 7; pin++) {
      digitalWrite(pin, HIGH);
      delay(200);
      digitalWrite(pin, LOW);
    }
    for (int pin = 6; pin > 3; pin--) {
      digitalWrite(pin, HIGH);
      delay(200);
      digitalWrite(pin, LOW);
    }
  }
}

Take a look at 'Blink without delay'.

please reformat you code so that it is properly indented and properly spaced

In setup(), you are accessing ledpins[6], which is out of bounds. 2) In loop(), digitalWrite(ledpins, HIGH) makes no sense, as ledpins is not an integer.

The problem in this code is that the for loops are blocking with delay for 1.2 seconds and only once that ends does the code come back around to check the button.  You should instead use the loop function itself to handle the looping and use the Blink Without Delay method of timing to handle the timing.  In that way the loop function is never blocked from running and can run thousands of times per second, never missing any presses of the buttons.  And also in this way you would be able to pause the program at any point, not just once every 1.2 seconds.

I would just use a pin interrupt and if the button is pressed the interrupt routine sets a flag (ie flag=1). Then in you loop just have a statement that says calls a function that is just a while loop which waits until flag variable is 0 again.  The interrupt function just toggles the flag variable every time the button is pushed. So first time button is pressed the program loops and the second time the button is pressed program execution leaves the routine and goes back to your loop().


text:
Cannot upload to otherwise working bootloaded ATmega328P via RS232: "programmer is not responding"
I have an ATmega328P on a breadboard with the following circuitry around it:

The ISP is a Tiny AVR Programmer. The RS232 to USB converter is this thing.
Following is the test program I use:

void setup() {
    Serial.begin(28800);
    DDRC  = 0b00000001;
    PORTC = 0b00000000;
}

void loop() {
    PORTC = 0b00000001;
    delay(300);
    PORTC = 0b00000000;
    delay(300);

    int Data;
    char Text[2] = {0};
    while (true)
    {
        Data = Serial.read();
        if (Data == -1) break;
        Text[0] = 0xFF - Data;
        Serial.write(Text);
    }
}

Almost everything is working fine:

I can upload the program via ISP by holding the shift-key while pressing the upload-button in Arduino IDE.
The LED on Pin 23 (PC0) blinks.
When I press the reset button the LED stops blinking and when I release the button it starts blinking again, so resetting the chip works.
When I open a serial monitor (at 28800 baud and not the one integrated in Arduino IDE) I can send 00, 01, 02, 03, ... and I receive FF, FE, FD, FC, ... back, so the serial communication works.
I can burn the bootloader from Arduino IDE. Every time I reset the chip the LED on pin 19 blinks three times in rapid succession and then stays off.

But I can't upload the program through the serial connection once the bootloader is burned.
Arduino IDE shows the following output:
C:\Portable Program Files\arduino-1.8.5\hardware\tools\avr/bin/avrdude -CC:\Portable Program Files\arduino-1.8.5\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM6 -b115200 -D -Uflash:w:C:\Users\Niko\AppData\Local\Temp\arduino_build_706815/BlinkTest.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Portable Program Files\arduino-1.8.5\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM6
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe0

(And of course the 9 other attempts follow.)
I am not sure what to do here. Maybe the baudrate is incorrect? The Arduino website says that Arduino bootloaders use 19200 baud. But executing the same command in a console but changing the -b115200 to -b19200 yields the same result. I also tried 9600.
I make sure to to reset the chip before trying to upload, though I can't really say whether I get the timing right.
Something I noticed is that The Arduino website says that "Burning the bootloader may take 15 seconds or more", but burning the bootloader takes less than a second for me. Seems unusually fast but I can't see any errors in the output.
I also find it very weird that the command executed when trying to upload via serial connection contains -carduino, which would imply that it's trying to use a programmer to upload the program. The bootloader should make that unnecessary.
Any ideas?

Your schematic does not seem to show a proper auto reset connection; manual reset is a bit tricky, though for some reason seems to work a lot better if you have verbose upload mode selected.  Also we don't know what bootloader speed you need - 38400 and 57600 are definite possibilities you don't seem to have tried.

Can you show your fuse settings please? If you have a spare Uno or similar you can use my board detector sketch to verify that.

As for the -carduino I think that just tells avrdude to use the STK500 protocol. See http://www.nongnu.org/avrdude/user-manual/avrdude_1.html

The bootloader should make that unnecessary. - not really. The bootloader is a programmer type. :) It has to use some protocol to upload the program.

really RS232? Atmega TX/RX is TTL, not RS232. https://www.sparkfun.com/tutorials/215

@ChrisStratton The automatic reset did the trick! Now it uploads fine with the 115200 baud Arduino IDE uses. Thank you very much! I'd upvote your comment, but I don't have the reputation for that. Feel free to add a full answer and I'll accept that. For completeness' sake: @NickGammon Fuse bytes are FD DE FF. And thanks for the explanation about -cardino. @Juraj Yep, that's what I meant. The name "RS232" seem to be used interchangeably most of the time anyways.

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


text:
Multiple Slaves(Arduino Mega 2560) response over SPI
I have problem creating Setup which have :

A SPI Master (Arduino Mega 2560)
SPI slaves (Arduino Mega 2560) ,which responds to the Masters request by sending float data (or Rather a 2D float array ,but lets just go step by step).

So,I initially started with 3 Arduinos in total (going step by step):

Arduino_1 :Master
Arduino_2 :Slave_1
Arduino_3 :Slave_2

I used ICSP pins for connection and Digital pin 53 (as mentioned in Nick Gammon's page :http://www.gammon.com.au/spi or How do you use SPI on an Arduino?   ,they are  good resources to start with SPI) and 10 for SS.
MY Master codes looks like:
#include <SPI.h>
#define SS_Slave_2 10

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

 pinMode(SS,OUTPUT);
 pinMode(SS_Slave_2,OUTPUT);
 pinMode(MOSI,OUTPUT);
 pinMode(SCK,OUTPUT);

 digitalWrite(SS, HIGH);  // ensure SS stays high for now
 digitalWrite(SS_Slave_2, HIGH);

 digitalWrite(SCK,LOW);
 digitalWrite(MOSI,LOW);

 // Put SCK, MOSI, SS pins into output mode
 // also put SCK, MOSI into LOW state, and SS into HIGH state.
 // Then put SPI hardware into Master mode and turn SPI on
 SPI.begin ();

 // Slow down the master a bit
 SPI.setClockDivider(SPI_CLOCK_DIV8);
}

byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (100);
  return a;
}

union first_union
{
 float f;
 byte b[4];
}data;

float yaw, pitch, roll, alt, temp;
float yaw_2, pitch_2, roll_2, alt_2, temp_2;

void loop (void)
{
 digitalWrite(SS_Slave_2, HIGH);
 digitalWrite(SS, LOW);

 //YAW
 transferAndWait ('Y');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 yaw = data.f;

 //PITCH
 transferAndWait ('P');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 pitch = data.f;

 //ROLL
 transferAndWait ('R');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 roll = data.f;

 //TEMP
 transferAndWait ('T');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 temp = data.f;

 //ALT
 transferAndWait ('A');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 alt = data.f;

 digitalWrite(SS, HIGH);
 digitalWrite(53, HIGH);
 digitalWrite(SS_Slave_2, HIGH);
 Serial.println("Slave_01: Start");
 Serial.print("yaw:");
 Serial.println(yaw, 4);
 Serial.print("pitch: ");
 Serial.println(pitch,4);
 Serial.print("roll:");
 Serial.println(roll,4);
 Serial.print("alt: ");
 Serial.println(alt,4);
 Serial.print("temp: ");
 Serial.println(temp,4);
 Serial.println("Slave_01: End");

 digitalWrite(SS, HIGH);
 digitalWrite(53, HIGH);
 digitalWrite(SS_Slave_2, LOW);

 //YAW
 transferAndWait ('Y');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 yaw_2 = data.f;

 //PITCH
 transferAndWait ('P');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 pitch_2 = data.f;

 //ROLL
 transferAndWait ('R');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 roll_2 = data.f;

 //TEMP
 transferAndWait ('T');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 temp_2 = data.f;

 //ALT
 transferAndWait ('A');
 data.b[0] = transferAndWait ('1');
 data.b[1] = transferAndWait ('2');
 data.b[2] = transferAndWait ('3');
 data.b[3] = transferAndWait ('Z');
 alt_2 = data.f;

 digitalWrite(SS_Slave_2, HIGH);
 digitalWrite(SS, HIGH);
 digitalWrite(53, HIGH);
 Serial.println("Slave_02: Start");
 Serial.print("yaw_2:");
 Serial.println(yaw_2, 4);
 Serial.print("pitch_2: ");
 Serial.println(pitch_2,4);
 Serial.print("roll_2:");
 Serial.println(roll_2,4);
 Serial.print("alt_2: ");
 Serial.println(alt_2,4);
 Serial.print("temp_2: ");
 Serial.println(temp_2,4);
 Serial.println("Slave_02: End");

 delay(500);
}

And Slave Code goes like:
#include <SPI.h>

volatile byte command;
//Set the default object
float ypr[3];
float alt = 0;
float temp = 0;

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

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);
  pinMode(MOSI,INPUT);
  pinMode(SCK,INPUT);
  pinMode(SS,INPUT);

  // turn on interrupts
  SPCR |= _BV(SPIE);

}

union first_union
{
    float f;
    byte b[4];
 }data;

ISR (SPI_STC_vect)
{
  byte c = SPDR;

  command = c;

  switch (command)
  {
   case 'Z':
   data.f = 0;
   SPDR = 0;
   break;
   case 'Y':
   data.f = ypr[0];
   SPDR = data.b[0];
   break;
   case 'P':
   data.f = ypr[2];
   SPDR = data.b[0];
   break;
   case 'R':
   data.f = ypr[1];
   SPDR = data.b[0];
   break;
   case 'A':
   data.f = alt;
   SPDR = data.b[0];
   break;
   case 'T':
   data.f = temp;
   SPDR = data.b[0];
   break;
   case '1':
   SPDR = data.b[1];
   break;
   case '2':
   SPDR = data.b[2];
   break;
   case '3':
   SPDR = data.b[3];
   break;
  }
}

void loop()
{
  Serial.println("loop() starts");
  ypr[0] = -1.1111;
  ypr[1] = -2.2222;
  ypr[2] = -3.3333;

  alt = -4.4444;
  temp = -5.5555;
  Serial.println("loop() ends");
}

The above codes (Master and Slave) are basically modified and adopted from Joseph Roberts' Question on https://stackoverflow.com/questions/20409799/sending-floats-from-an-arduino-to-another-arduino-over-spi-using-a-union
 , purely for learning purpose only.
(I modified it a bit and now similar codes works well for 1 SPI Master and 1 SPI slave Arduino setup).
//Note:Same Slave code uploaded to both the slaves.
OUTPUT:
Slave_01: Start
yaw:-1.1111
pitch: -3.3333
roll:-2.2222
alt: -4.4444
temp: -5.5555
Slave_01: End
Slave_02: Start
yaw:0.0000
pitch: 0.0000
roll:-2.2222
alt: 0.0000
temp: 0.0000
Slave_02: End
Slave_01: Start
yaw:-1.1111
pitch: -3.3333
roll:-2.2222
alt: -4.4444
temp: -5.5555
Slave_01: End
Slave_02: Start
yaw:0.0000
pitch: 0.0000
roll:0.0000
alt: 0.0000
temp: 0.0000
Slave_02: End
Slave_01: Start
yaw:-1.1111
pitch: -3.3333
roll:-2.2222
alt: -4.4444
temp: -5.5555
Slave_01: End
Slave_02: Start
yaw:0.0000
pitch: 0.0000
roll:0.0000
alt: ovf
temp: 0.0000
Slave_02: End
Slave_01: Start
yaw:-1.1111
pitch: -3.3333
roll:-2.2222
alt: -4.4444
temp: -5.5555
Slave_01: End
Slave_02: Start
yaw:0.0000
pitch: 0.0000
roll:0.0000
alt: 0.0000
temp: ovf
Slave_02: End

As we can see from output ,I got output from one of the slave only (Arduino_2:Slave_1) ,the other gave unreliable/garbage output .That is the problem ,I don't get it where the zeros for 2nd Slave comes from ?And how to correct it.Did I missed something ?
Even the page(http://www.gammon.com.au/spi) by Nick Gammon on SPI ,lacks details on Multiple Slave Arduino SPI connection (Although It is really a good place to start with SPI on Arduino, no offense  ).I know my Question is similar to Slaving multiple Arduinos via SPI ,but still the answer there doesn't helps much. I almost spend entire Night searching for the solution.
I even tried things like changing the SS for the Slaves ,but still only   Arduino_2 gave the correct results and Arduino_3 does not.
And yes ,Arduino_3 is not damaged (It works well in 1master_1slave setup). And all the Arduinos has common GND .
Any constructive criticisms are also welcomed.
Warm Regards
SV

Hi , this is my first  post/question to the forum ,so please bear with me If I lacked some important details(if any) in the Above Question.

why don't you get the setup to reliably transfer a single byte before you try sending an array?

Please can you show your wiring of the two slave setup?

I know this item is quite old, and I'm also trying to implement multiple Arduino SPI slaves, and looking at all documentations, my understanding is that the SS is not automatically managed in the slave Arduinos. From that, unsure about the wiring of your 1 master/2 slaves Arduinos that can alter the results as shown above, it looks to me your slave code does not manage the SS from two aspects :
1 - I don't see when you identify in your ISR reception procedure if the applicable slave is enabled ( aren't both modules processing the message all the time in this configuration, I suspect they both do  )
2 - Also about the SS event management in the slave module, pinMode(MISO, OUTPUT); should only be set when SS is low, otherwise you may have faulty signal with two slaves having MISO as outputs. My understanding is that only one slave at a time should have it as an output ( hence my question about wiring )
Hope it helps,

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


text:
Alternative of relay
I am carrying out a physics experiment using an Arduino. This experiment requires accurate time measurements of upto a millisecond. However I am using a relay to turn on/off an electromagnet and there is a maximum lag of 10ms due to the relay. I am a complete beginner. Please suggest alternative mechanisms to switch the electromagnet and save those precious milliseconds.
P.S. - the magnet is driven by 12V 2.5A DC.

Also, keep in mind that you cannot instantly power an electromagnet. You will have a time constant L/R where L is the magnet's inductance, and R the total circuit resistance (magnet windings, power supply, MOSFET...)

What type of physics experiment?

A relay is just an electromagnet, and the same circuit that can drive a relay can drive an electromagnet. You just need to make sure it can handle the power.
The simplest circuit is to use an N-channel MOSFET:

simulate this circuit – Schematic created using CircuitLab
Just make sure that the MOSFET can handle the required power dissipation and switches on fully at below 5V on the gate (a gate threshold voltage of less than 3V is ideal).

And remember to include a flyback diode https://elinux.org/RPi_GPIO_Interface_Circuits#Driving_a_relay

Good point. I forgot that.

I think you need something like a relay driver.
On this site:
http://www.learningaboutelectronics.com/Articles/Relay-driver-circuit.php
i found this picture:

In "practical electronics for inventors (fourth edition)" is a similar picture with following text on page 445:
"Here, an npn transistor is used to control a relay. When the transistor's base receives a control voltage/current, the transistor will turn on, allowing current to flow through the relay coil and causing the relay to switch states. The diode is used to eliminate voltage spikes created by the relay's coil. The relay must be chosen according to the proper voltage rating, etc."
You can replace the relay with the magnet. But you will still need a diode. When you switch off the magnet it will generate a voltage and will try to push the current (there is energy saved in the coil). This diode will help it to unload the energy. Otherwise this energy can destroy something.

Unless it's a very low power magnet (like, e.g., a relay), I wouldn't use an NPN transistor. An N-channel MOSFET, as pictured in Majenko's answer, is likely to perform better in most cases.

MOSFET are good. I looked in the book and they say that we can use power transistors for high-power amplifieers and power supplies. The range of power ratings are from 10 - 300W, frequency from 1 - 100MHz and Ic from 1 - 100A. He will need 12V times 2,5A this is above 10 and under 300W. I think 1 stands for 1Hz and he wants to switch only one time. The current is between 1 and 100A.

@user8886193 Don’t you mean a fast schottky? NPN should be replaced with an optocoupler, e.g. pc187. Please tell me more about this zener catch diode.

@user2497 In my book it is a diode (1N914). In the illustration in my answer it is a zener. This is illustration is from a website. Zener diodes work in both directions. In the forward direction it needs 0.6V to open like a simple diode. In the other direction (reverse direction) it needs the zeners breakdown voltage. In the illustration the breakdown voltage is 12V. Schottky diodes are used for example for telecomunication. They are fast and need 0.3V to open. It will work too. Optocoupler  will work. One question to you: Can we connect the grounds of two different voltage supplies?

@user8886193 Yes, you can. Call it system COMmon, and it will become clearer in your mind. I don’t understand why it uses a zener, I learned to use fast rise schottkys to foil flyback. Or for lack of schottkys, 1n40xx general purpose diodes. A zener would just pass along Vsrc-Zdrop; why is this desirable?

The zener will make the voltage stable for the relay. In this case 12V. A simple diode can not do this. In forward direction the zener and simple diodes work the same. In reverse direction zener diodes try to hold the voltage. They can open from a little bit to full to hold the voltage (current Iz flows).

@user8886193 Why isn’t the voltage 12V to begin with, if it’s a 12V relay? Use a 7812 or lm317 if Vsrc is >=1.25V higher than 12V. God, I have so many questions for you... I guess you are trying to clamp the voltage? Do you notice that Majanko drew a schottky in his answer? Regardless; an IRF3205 N-FET (TO-220 package) will carry a heavy load with little loss in heat. Let’s stop talking about this relay hooey...

Just use his answer. Keep in mind there are not one solution for a problem. Some solutions are better some not.


text:
Pass a char array to a function that uses File as parameter
I am in serious need for help here. I have a rather small function that get's the number of files from within a given directory. Now, the directory name (that is the path) is stored in a char array within my main loop.
My problem is, I have no idea how to pass this char array to my function.
This is my code (it's of course just a subset but it's the part that is obviously wrong) and you can also see the complete program at the end:
In the setup() routine I define my current working directory:
char plrCurrentFolder[9];

In the main loop I want to get the number of files of a given directory (in the final program this directory name will come from an NFC tag):
String temp = "findorie";
temp.toCharArray(plrCurrentFolder, 9);
unsigned int numberOfFiles = countFiles(plrCurrentFolder);

This is the function to return the number of files:
unsigned int countFiles(File dir){
  unsigned int counter = 0;
  while (true){
    File entry = dir.openNextFile();
    if (!entry){
      // no more files
      break;
    }
    counter++;
    entry.close();
  }
  dir.close();
  return counter;
}

To be honest I have two issues with this. First, I don't really like to create a temp String variable to create the char array here as I would rather stick with the char array in itself to safe on memory and maybe this would also aid in performance (although I'm not sure about that).
Second, The way this whole thing is structured right now, it simply doesn't work. When building, the compiler correctly complains:
exit status 1
could not convert '(char*)(& plrCurrentFolder)' from 'char*' to 'SDLib::File'

Can anyone help me out and give me a code snippet how to make this work???
Kind regards to all,
Christian
--- below you may find the complete code as of now ---
/*
 * Fairytale Main program
 *
 * This programm will read an nfc tag. It will check for a directory name and optional a filename
 * and start playing this on the music maker shield.
 *
 * Restrictions:
 * 1. All filenames mus be in the format  trackXXX.mp3  - where XXX is a numbering from 001 to 999
 * 2. All directory names must be exactly 8 chars long
 *
 */

// make sure to change this to 0 before uploading in production as it turns on lots and lots of serial messages
#define DEBUG 1
// we only show light effects, in case this is set to 1
#define LIGHTEFFECTS 0
// we only use the nfc reader if this is set to 1
#define NFCREADER 0

//
// setup SPI, MP3 and SD libraries
//
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>
// These are the pins used for the music maker shield
#define SHIELD_RESET  -1     // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)
#define CLK 13 // SPI Clock, shared with SD card
#define MISO 12 // Input data, from VS1053/SD card
#define MOSI 11 // Output data, to VS1053/SD card

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

Adafruit_VS1053_FilePlayer musicPlayer =
  // create shield-example object!
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

//
// setup NFC Adapter
//
#ifdef NFCREADER
/*
  #include <PN532_SPI.h>
  #include <PN532.h>
  #include <NfcAdapter.h>

  #define PN532_SCK (13) //changed from pin 2
  #define PN532_MISO (12) //changed from pin 5
  #define PN532_MOSI (11) //changed from pin 3
  #define PN532_SS (10) //changed from 4

  PN532_SPI pn532spi(SPI, PN532_SS);
  NfcAdapter nfc = NfcAdapter(pn532spi);
*/
#endif

// these variables are used for the light effects
int lightValue1, lightValue2, lightValue3;
const int redPin = 7;
const int greenPin = 8;
const int bluePin = 9;

// these are timing counters for the light effects
long time=0;
int periode = 20000;
int displace = 500;

// uptime counters
unsigned int runCounter = 0;
unsigned long startUpTime = 0;
const unsigned long maxUpTime = 120000; // 1800000L;  // 30 Minutes

// these are variables for the nfc card
boolean cardScanned = false;    // did we already scan the card?? using this to suppress reading in the card data while it is on the reader
char cardId[16];                // the uid of the card as read in through the nfc reader

// mp3 player variables
boolean plrIsPlaying = false;                         // is the mp3 player already playing?
char plrCurrentFile[13];                              // which track is the player playing?
char plrNextFile[13];                                 // which track is the player playing?
char plrPrevFile[13];                                 // which track is the player playing?
char plrCurrentFolder[9];                             // which directory is the player playing?
uint8_t plrCurrentPosition = 0;                       // on which position in seconds are we in the current track?
char currentTrackFileName[] = "/system/current.txt";  // a file we might use to store the last played track

// volume control variables for the analog poti
int volumePotPin = A0;        // the analog input pin that we use for the potentiometer
int sensorDrift = 7;          // difference to last received sensor value that must be exceeded to activate a change in the volume
int compareValue = 0;         // just a convenience variable to make comparison easier
int sensorValue = 0;          // read the value from the potentiometer
int lastSensorValue = 0;      // keeps the last read sensor value
uint8_t soundVolume = 0;      // the sound volume is derived via a map function from the sensor value

// other button settings
int btnLinePin = A1;         // pin on which the button line (4 buttons) is connected
int btnVal = 0;

// these are the prototypes for the nfc card reader
void getNfcCardData();

// these are the prototypes for the mp3 player controller
uint8_t getVolume(void);        // function that returns the volume setting based on the analog read
char plrNext(void);             // play next file in album
char plrPrev(void);             // play previous file in album
void plrPlayTrack(char, char);  // play a single track
void setupSound(void);          // initializes the sound system and plays the startup sound

// these are the prototypes to work on files
void printDirectory(File, int);   // print out the content of specified directory on serial console
unsigned int countFiles(File);    // return the number of files in a directory passed as a File descriptor
//unsigned int countFiles(char[]);    // return the number of files in a directory passed as a File descriptor

// these are the prototypes for the light effects
void fader(void);
void startuplight(void);
void highlight(int);
void flash(int);
void pulse(int);

void setup() {
  #ifdef DEBUG
    Serial.begin(115200);
  #endif

  plrCurrentFile[0] = 0; // we initialize the fiirst element of the array to 0 to later check if a current file was given.

  // initialise the music player
  if (! musicPlayer.begin()) { // initialise the music player
    #ifdef DEBUG
      Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
    #endif
    while (1);
  }
  #ifdef DEBUG
    Serial.println(F("Music Maker Shield VS1053 found"));
  #endif

  //musicPlayer.sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working

  if (!SD.begin(CARDCS)) {
    #ifdef DEBUG
      Serial.println(F("failed to detect the SD-Card"));
    #endif
    while (1);  // don't do anything more
  }
  #ifdef DEBUG
    Serial.println("SD found and operational");
  #endif

  // set the buttons as input
  pinMode(volumePotPin, INPUT);
  pinMode(btnLinePin, INPUT);

  // setup music maker shield and start playing startup file
  setupSound();

  #ifdef DEBUG
    // list files
    printDirectory(SD.open("/"), 0);
  #endif

/*
  // now as the last thing, start the nfc reader
  #ifdef DEBUG
    Serial.print("initializing NFC TAG reader ... ");
  #endif
  nfc.begin();
  delay(1000); // wait some time for
*/

  // check our current time, so we know when to stop
  startUpTime = millis();
  #ifdef DEBUG
    Serial.println("we are up and running and ready to play audio");
  #endif
}

//
//      LL       OOOOOO    OOOOOO   PPPPPPP
//      LL      OO    OO  OO    OO  PP    PP
//      LL      OO    OO  OO    OO  PP    PP
//      LL      OO    OO  OO    OO  PPPPPP
//      LLLLLL   OOOOOO    OOOOOO   PP
void loop() {
  #ifdef LIGHTEFFECTS
    // turn off all the lights. we only want to have fading lights, while the playr is active
    //analogWrite(redPin, 0);
    //analogWrite(greenPin, 0);
    //analogWrite(bluePin, 0);
  #endif

  // NFC Tag reader functions
  // now we only do this, when an nfc tag is present
/*
  if (nfc.tagPresent()){
    Serial.println("NFC tag Found!\n");
    NfcTag tag = nfc.read();
    Serial.print("Tag Type: ");
    Serial.println(tag.getTagType());
    Serial.print("UID: ");
    Serial.println(tag.getUidString());

    getNfcCardData();
*/

    String temp = "findorie";
    temp.toCharArray(plrCurrentFolder, 9);

    // now let's get the number of files in the album directory
    //unsigned int numberOfFiles = 0;
    unsigned int numberOfFiles = countFiles(plrCurrentFolder);
    #ifdef DEBUG
      Serial.print("Directory ");Serial.print(plrCurrentFolder);Serial.print(" contains ");Serial.print(numberOfFiles);Serial.println(" files");
    #endif

    // if we did not get the current file from the tag, we are hardcoding it to track001.mp3
    if ((plrCurrentFile[0] == 0)) {
      temp = "track001.mp3";
      temp.toCharArray(plrCurrentFile, 13);
    }

    #ifdef DEBUG
      Serial.print("currentFolder holds: ");Serial.print(plrCurrentFolder);Serial.print(" / currentFile contains: ");Serial.print(plrCurrentFile);
    #endif

    temp = "/";
    temp.concat(plrCurrentFolder);
    temp.concat("/");
    temp.concat(plrCurrentFile);
    char filename[temp.length() + 1];
    temp.toCharArray(filename, sizeof(filename));
    Serial.print(" / filename contains: ");Serial.println(filename);

    if (SD.exists(filename)) {
      Serial.print(filename);Serial.println(" exists.");

      // mp3 player functions playback
      // Start playing a file, then we can do stuff while waiting for it to finish
      if (! musicPlayer.startPlayingFile(filename)) {
        #ifdef DEBUG
          Serial.print("Could not open file ");Serial.println(filename);
        #endif
        while (1);
      }
      #ifdef DEBUG
        Serial.print(F("Start playing "));Serial.println(filename);
      #endif

      while (musicPlayer.playingMusic) {
        // file is now playing in the 'background' so now's a good time
        // to do something else like handling LEDs or buttons :)

        // play some nice light effects, if wanted
        #ifdef LIGHTEFFECTS
          //fader();
        #endif

        // volume control functions
        // read the input on analog pin 0 and check if we have a change in volume.
        sensorValue = analogRead(volumePotPin);
        if (lastSensorValue > sensorValue) {compareValue = lastSensorValue - sensorValue;} else {compareValue = sensorValue - lastSensorValue;}
        // If we have a high enough difference in the sensor reading, calculate it so we may set it on the player
        if (compareValue > sensorDrift){
          #ifdef DEBUG
            Serial.print("changing volume: ");
          #endif
          soundVolume = getVolume();
          musicPlayer.setVolume(soundVolume,soundVolume);
        }
      }
      #ifdef DEBUG
        Serial.println("Done playing ");Serial.println(filename);
      #endif
      #ifdef LIGHTEFFECTS
        //startuplight();
      #endif
    } else {
      Serial.print(filename);Serial.println(" does not exist.");
    } // end of file does not exist

  //} // end of tag found
} // end of loop

//
//        NN    NN  FFFFFF   CCCCCC
//        NNNN  NN  FF      CC
//        NN  N NN  FFFF    CC
//        NN  NNNN  FF      CC
//        NN    NN  FF       CCCCCC
//  BELOW THIS LINE THE NFC CONTROL IS DEFINED
//
void getNfcCardData(){
/*
  NfcTag tag = nfc.read();
  boolean usableContent = false;
  if (tag.hasNdefMessage()){
    NdefMessage message = tag.getNdefMessage();

    // If you have more than 1 Message then it wil cycle through them
    int recordCount = message.getRecordCount();
    for (int i = 0; i < recordCount; i++) {
      NdefRecord record = message.getRecord(i);

      int payloadLength = record.getPayloadLength();
      byte payload[payloadLength];
      record.getPayload(payload);

      String payloadAsString = ""; // Processes the message as a string vs as a HEX value
      for (int c = 0; c < payloadLength; c++) {
        payloadAsString += (char)payload[c];
      }

      String cleanString = payloadAsString;
      cleanString.remove(0,3);
      #ifdef DEBUG
        Serial.print("content element "); Serial.print(i); Serial.print(": "); Serial.println(cleanString);
      #endif

      // now populate the vars for the player
      int spacePosition = cleanString.indexOf(':');
      if (cleanString.charAt(spacePosition - 1) == 'A') {
        String contentString = cleanString.substring(3);
        #ifdef DEBUG
          Serial.print("Album info: ");Serial.println(contentString);
        #endif
      }
      if (cleanString.charAt(spacePosition - 1) == 'D') {
        usableContent = true;
        String contentString = cleanString.substring(3);
        plrCurrentFolder = contentString;
        #ifdef DEBUG
          Serial.print("Directory: ");Serial.println(contentString);
        #endif
      }
      if (cleanString.charAt(spacePosition - 1) == 'T') {
        String contentString = cleanString.substring(3);
        plrCurrentFile = contentString;
        #ifdef DEBUG
          Serial.print("Track: ");Serial.println(contentString);
        #endif
      }
      if (cleanString.charAt(spacePosition - 1) == 'P') {
        String contentString = cleanString.substring(3);
        plrCurrentPosition = contentString.toInt();
        #ifdef DEBUG
          Serial.print("Position: ");Serial.println(contentString);
        #endif
      }

      String uid = record.getId();
      if (uid != "") {
        #ifdef DEBUG
          Serial.print("  ID: ");
          Serial.println(uid);
        #endif
      }
    }
    if (!usableContent){
      #ifdef DEBUG
        Serial.println("THIS CARD DOES NOT HAVE THE NECESSARY MESSAGES FOR THE MP3 PLAYER");
      #endif
    }
  } else { // does the card have NDEF messages?
    #ifdef DEBUG
      Serial.println("THIS CARD DOES NOT HAVE MESSAGES AT ALL - NOT USABLE FOR THE MP3 PLAYER");
    #endif
  }
*/
}

//
//        MM      MM   PPPPPP   33333
//        MMMM  MMMM  PP    PP      33
//        MM  MM  MM  PP    PP    3333
//        MM      MM  PPPPPP        33
//        MM      MM  PP        33333
//  BELOW THIS LINE THE MP3 PLAYER CONTROL IS DEFINED
//
uint8_t getVolume(){
  soundVolume = map(sensorValue, 0, 1023, 0, 100); // map the sensor value to a sound volume

  #ifdef DEBUG
    Serial.print("last sensor value (if any) was ");Serial.print(lastSensorValue);Serial.print(" / new sensor value is ");Serial.print(sensorValue);Serial.print(" which is a volume of ");Serial.println(soundVolume);
  #endif
  lastSensorValue = sensorValue;
  return (soundVolume);
}

void plrPlayTrack(char dir, char file) {
  String temp = "/";
  temp.concat(dir);
  temp.concat("/");
  temp.concat(file);
  char myFile[temp.length() + 1];
  temp.toCharArray(myFile, sizeof(myFile));

  // mp3 player functions playback
  // Start playing a file, then we can do stuff while waiting for it to finish
  if (! musicPlayer.startPlayingFile(myFile)) {
    #ifdef DEBUG
      Serial.print("Could not open file ");Serial.println(myFile);
    #endif
    while (1);
  }
  #ifdef DEBUG
    Serial.print(F("Start playing "));Serial.println(myFile);
  #endif

  while (musicPlayer.playingMusic) {
    // file is now playing in the 'background' so now's a good time
    // to do something else like handling LEDs or buttons :)
    #ifdef DEBUG
      Serial.print(".");
    #endif
    #ifdef LIGHTEFFECTS
      //fader();
    #endif

  }
  #ifdef DEBUG
    Serial.println("Done playing ");Serial.println(myFile);
  #endif
}

char plrNext(void){
  char track[12] = "track003.mp3";
  #ifdef DEBUG
    Serial.println("plrNext toggled");
  #endif
  #ifdef LIGHTEFFECTS
    //pulse(bluePin);
  #endif

  return track;
}
char plrPrev(void){
  char track[12] = "track001.mp3";
  #ifdef DEBUG
    Serial.println("plrPrevious toggled");
  #endif
  #ifdef LIGHTEFFECTS
    //pulse(greenPin);
  #endif

  return track;
}

void setupSound(){
  // This option uses a pin interrupt. No timers required! But DREQ
  // must be on an interrupt pin. For Uno/Duemilanove/Diecimilla
  // that's Digital #2 or #3
  // See http://arduino.cc/en/Reference/attachInterrupt for other pins
  // *** This method is preferred
  if (! musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT)) {
    #ifdef DEBUG
      Serial.println(F("DREQ pin is not an interrupt pin"));
    #endif
    while (1);
  }

  // Start playing a file, then we can do stuff while waiting for it to finish
  if (! musicPlayer.startPlayingFile("hello.mp3")) {
    #ifdef DEBUG
      Serial.println("Could not open file hello.mp3");
    #endif
  } else {
    #ifdef DEBUG
      Serial.print("playing welcome file hello.mp3 ");
    #endif
  }

  // now we play the welcome sound
  startUpTime = millis();
  while (musicPlayer.playingMusic) {
    if (millis() - startUpTime > 500) {
      #ifdef DEBUG
        Serial.print(".");
      #endif
      startUpTime = millis();
    }
    // file is now playing in the 'background' so now's a good time
    // to do something else like handling LEDs or buttons :)
    #ifdef LIGHTEFFECTS
      //startuplight();
    #endif
  }
  #ifdef DEBUG
    Serial.println(" done");
  #endif
  getVolume();
  musicPlayer.setVolume(soundVolume,soundVolume);
}

//
//        FFFFFF  II  LL      EEEEEE
//        FF      II  LL      EE
//        FFFF    II  LL      EEEE
//        FF      II  LL      EE
//        FF      II  LLLLLL  EEEEEE
// BELOW THIS LINE THE FILE HELPER FUNCTIONS CAN BE FOUND
//
// counts the number of files in directory
//unsigned int countFiles(char dir[]){

unsigned int countFiles(File dir){
  unsigned int counter = 0;
  while (true){
    File entry = dir.openNextFile();
    if (!entry){
      // no more files
      break;
    }
    counter++;
    entry.close();
  }
  dir.close();
  return counter;
}

// store last played track
void rememberCurrentTrack(){

}

// read last played track
void getLastPlayedTrack(){

}

// File listing helper
void printDirectory(File dir, int numTabs) {
   while(true) {
     File entry =  dir.openNextFile();
     if (! entry) {
       // no more files
       //Serial.println("**nomorefiles**");
       break;
     }
     for (uint8_t i=0; i<numTabs; i++) {
       Serial.print('\t');
     }
     Serial.print(entry.name());
     if (entry.isDirectory()) {
       Serial.println("/");
       printDirectory(entry, numTabs+1);
     } else {
       // files have sizes, directories do not
       Serial.print("\t\t");
       Serial.println(entry.size(), DEC);
     }
     entry.close();
   }
}

//
//        LL      EEEEEE  DDDDDD
//        LL      EE      DD    DD
//        LL      EEEE    DD    DD
//        LL      EE      DD    DD
//        LLLLLL  EEEEEE  DDDDDD
//  BELOW THIS LINE THE LIGHT EFFECTS ARE DEFINED
//
// fading organically
void fader(){
  time = millis();
  lightValue1 = 128+127*cos(2*PI/periode*time);
  lightValue2 = 128+127*cos(2*PI/periode*(displace-time));
  lightValue3 = 128+127*cos(2*PI/periode*(2*displace-time));
  analogWrite(redPin, lightValue1);           // sets the value (range from 0 to 255)
  analogWrite(greenPin, lightValue2);        // sets the value (range from 0 to 255)
  analogWrite(bluePin, lightValue3);         // sets the value (range from 0 to 255)
}
// illuminate the 3 led with some fancy lightning during startup
void startuplight(){
  for (int i = 0; i<150; i++) {
    analogWrite(redPin, i);
    analogWrite(greenPin, i);
    analogWrite(bluePin, i);
    delay(10);
  }
  for (int i = 150; i>0; i--) {
    analogWrite(redPin, i);
    analogWrite(greenPin, i);
    analogWrite(bluePin, i);
    delay(10);
  }
  analogWrite(redPin, 0);
  analogWrite(greenPin, 0);
  analogWrite(bluePin, 0);
}
//turn on the desired pin for 5000 milliseconds
void highlight(int pin){
  time = millis();
  while (millis()<time+5000){
    analogWrite(pin, 255);
  }
  analogWrite(pin, 0);
}
//turn on the desired pin for 5000 milliseconds
void flash(int pin){
  time = millis();
  while (millis()<time+1000){
    analogWrite(pin, 255);
  }
  analogWrite(pin, 0);
}
//turn on the desired pin for 5000 milliseconds
void pulse(int pin){
  for (int i=0;i<3;i++){
    time = millis();
    while (millis()<time+2500){
      analogWrite(pin, 255);
    }
    analogWrite(pin, 0);
  }
}

You need to open the file then pass that file. Or have your function accept a char array and do the file opening itself. Either way, at some point, you will need to open the file.

Actually that function does not open a file at all. It simply counts the number of files in a directory. But you have a point nonetheless. Maybe best would be to restructure the function and find a way to count files in a directory without the need to pass a File descriptor to the function. Would you have, by any chance an idea on how to count files in a directory where the directory name is past as a char array???

As far as filesystems are concerned (in general) a directory is just another file. You just use special functions to read the contents of it. To do any operation on a directory you need to open it. Like a file.

Thank you so very much. As posted below, I was really blindfolded here. Thanks for your help

OMG. I'm so sorry for posting such a stupid question. And I'm also sorry for not seeing the obvious even after Majenko pointed me to it.
Of course I need to call the function like this:
numberOfFiles = countFiles(SD.open(plrCurrentFolder));

That way, the directory get's opened and my function can operate on it.
I see I still have to learn a lot :-)


text:
Unclear GET request mixed values
In my Uno code, I access to a page in my server and retrieve that value and make decision upon that value.
I get this kind of response,
Connected to server
on
on
off
off
on
off
[WiFiEsp] TIMEOUT: 116

Disconnecting from server.

Which should just be on or off.
This is my code for testing :
#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2,3); // RX, TX
#endif

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

char server[] = "192.168.50.1";

// Initialize the Ethernet client object
WiFiEspClient client;

int c =0;
int testLED = 12;

void setup()
{
  pinMode(testLED, OUTPUT);
  // initialize serial for debugging
  Serial.begin(9600);
  // 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);
  }

  // you're connected now, so print out the data
  Serial.println("You're connected to the network");

  printWifiStatus();

  Serial.println();
  Serial.println("Starting connection to server...");
  // if you get a connection, report back via serial
  if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    client.println("GET /simple.txt HTTP/1.1");
    client.println("Host: localhost");
    client.println("Connection: close");
    client.println();
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them
  if (client.available()) {
     c = client.read();

     switch(c){
          case '0':
                 Serial.println("off");
                 digitalWrite(testLED, LOW);
                 delay(2500);
                 break;

          case '1':
                 Serial.println("on");
                 digitalWrite(testLED, HIGH);
                 delay(2500);
                 break;
      }
        }

  // if the server's disconnected, stop the client
  if (!client.connected()) {
    Serial.println();
    Serial.println("Disconnecting from server...");
    client.stop();

    // do nothing forevermore
    while (true);
  }
}

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");
}

My simple.txt file just has 1.
Why this code outputs a gibberish value? Is it a problem with the way I retrive data?
Raspberry pi is working as my network server.
Thanks in advance.

What's with the huge delays?

@Majenko I put delay just for testing LED. It was not giving the result even without delay()

why are you using http if you connect to your raspberry?

@Juraj I connect to Raspberry-pi's web server.

When you send a GET request in HTTP you get a HTTP response back, not just the contents of the file you requested.
For instance, your request may result in a response of:
HTTP/1.1 200 OK
Date: Thu, 28 Dec 2017 11:02:21 GMT
Server: Apache/2.4.25 (Ubuntu)
Last-Modified: Wed, 05 Apr 2017 09:40:30 GMT
ETag: "2c39-54c682ee19688"
Accept-Ranges: bytes
Content-Length: 3
Vary: Accept-Encoding
Connection: close
Content-Type: text/plain

1

As you can see there's plenty of occurrences of 0 and 1 in there to trigger your LED.
You need to parse the incoming data better. Read it line by line and only start reacting to the content after the blank line that indicates the division between header and body.

Yes, I understood that. But how to parse those unwanted data from the response.

Keep a flag that says if you are in the header or not. The blank line tells you to change the flag, the flag tells you whether to interpret the data as commands. All the rest you ignore. If you want to read character by character then react to the end of line character and count the characters in a line. If the count is (not including the EOL characters) 0 then you have a blank line. You don't care what is in the header.

Can you provide me an example or a link to do these task. I just began Arduino

Discard everything up to a blank line. Then process that.

I found the answer for my question. @Majenko's answer helped me a lot.
I removed HTTP response given by the server and just changed few line in my original code. Also added # in-front of the number in my server's simple.txt file.
Also this arduino-forum post
void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them
while(client.available() > 0)
{
  char c = client.read();
  if(c == '#')
  {
     while(client.available() == 0) { } // Do nothing while we wait for the next value
     c = client.read();
     if(c == '1'){
        Serial.println("On");
        digitalWrite(testLED, HIGH);
        delay(2500);
     }
     else if(c == '0'){
        Serial.println("Off");
        digitalWrite(testLED, LOW);
        delay(2500);
     }
  }
}

  // if the server's disconnected, stop the client
  if (!client.connected()) {
    Serial.println();
    Serial.println("Disconnecting from server...");
    //client.stop();

    // do nothing forevermore
    while (true);
  }
}


text:
RF receiver for integer only, how to cast uint8_t to int?
I'm using the RadioHead library with ASK Driver to transmit/receive data with generic RF modules. It works fine, but I'm lacking some knowledge in programming the code to use the data received. Most examples I could find show how to send a string, but I only need to send and receive an integer.
I'm sending the decimal value '1' through the transmitter:
    uint8_t *data;
    uint8_t value;

    void loop() {
    value = 1;
    data = &value;
    driver.send(data, sizeof(value));
    driver.waitPacketSent();
    delay(200);
    }

And I have in the receiver:
void loop() {
  uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
  uint8_t buflen = sizeof(buf);
  int value;

  if (driver.recv(buf, &buflen)) {
    driver.printBuffer("Received:", buf, buflen); //prints 1.
    value = (int) buf; //my attempt to cast
    Serial.println(value); // the output is 2233, so this is wrong.
  }
  if (value == 1){ //example
  Serial.println("good");
  }
}

So what I think it is, I'm receiving bytes from the transmitter, which the library function 'driver.printBuffer' reinterprets as decimals and prints the value '1'. But how do I interpret (or cast) this as an integer so I can use it for other things like in the example (If condition) at the end? Any help is very much appreciated. Thanks.

buf is a pointer to the received bytes. Try value = buf[0]; instead.

that makes sense, it worked perfectly thanks!

This of course only works for small positive values that fit in an 8-bit type.  For larger values you will need to be more sophisticated.


text:
Arduino Due not executing code after power on
My Arduino Due does not execute its code when powered on after being powered off for ten seconds or longer. I have to press the reset button for the code to execute.
I've read some older threads about a firmware issue and saw people doing solder jobs on their boards to fix it.
My question is, does this issue happen with all/any Arduino Due boards? Are just some clones (like mine) affected and the original works fine?
What's the best way to fix this problem? In this state the board serves no purpose anymore and I've downgraded to the Uno for now.
EDIT: Adding picture and link to the board used.
https://www.amazon.de/gp/product/B016D5KYF6/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

you have posted inadequate information. what make of the board do you have? post a picture, maybe.

Nobody? It would help already to know if this issue is not "normal" for genuine Arduino Due boards.

It happens with UNOs as well. Have to press reset button to run any included program. Looking to fix this since the UNO has to start correctly when power is applied.

After some more research I found out that
a) the issue applies to some Due boards only, not all
b) newer boards seem to have fixed the issue
c) there's a software (firmware update) and hardware (10k resistor) solution
I went with the hardware fix shown here:
http://www.dimdim.gr/2016/03/fixing-startup-issues-with-arduino-dues/
I did not have an SMD resistor at hand, so mine looks ancient but does the job.
Hope that helps others, too.

addendum:
The problem occurs only on some DUE boards and is due to some undocumented behaviour of the ATSAM3X8E processor combined with the behaviour of some MOSFETS installed on the DUE boards. So its occurence is largely a matter of luck.
The fix is simple: you just solder a 10K resistor across the top of this mosfet:
resistor about to be soldered on

resistor designated as R99

While the picture is great, it would be good if you could describe the fix in words so that it can still be applied by someone who might find your answer after the off-site link might have borken.


text:
Serial communication between multiple devices (or Arduinos)
What I know from my search on the internet, for both SPI and I2C protocols, communication between multiple devices needs a master, which initiates the communication, and slaves, which respond to the master's request. Basically slaves can't initiate a transfer.
Is there any way to make different devices communicate on their will? I'm not sure about UART, but I think the story is the same here. But I know that it is possible to use a USB hub to connect multiple USB devices to one port on the computer. How can that be done? Can I use the same principle with Arduino?
To clarify what I want to do, consider that I have different modules (might be Arduinos) with different characteristics. I want to connect them on a bus line to a master Arduino. The module connections should be indifferent so that the user doesn't have to worry about which port should be used to connect the module. For this reason, using an Arduino Mega with more serial interfaces doesn't solve the problem, because we don't know which device is connected to which port.

1-Wire protocol (with a single pin) is also an alternative.

Other examples are CAN bus (standard shields are available) and PS/2 (two-side initiation (set of LEDs (and other modes) and key presses, respectively), but not really a bus). The former is a lot more complex, but also a lot more robust (it doesn't even require a common ground).

Almost any serial communication system can be "bent" to make a multi-master system - some easier than others.  The biggest problem you have is that of detecting and handling collisions.
However, if you can get away with a master->slave(s) system whereby one node on your bus makes requests to the slave nodes to get them to do something and respond with information then the whole system is far far simpler.
That is the normal way that I2C and SPI work, although I2C does have multi-master in its specification (though the Arduino API doesn't handle it AFAIK).
The industry standard way of making a UART able to communicate with multiple devices is through converting it to a standard bus system, such as EIA-422 or EIA-485 (AKA RS-422/RS-485). A half-duplex multi-drop EIA-485 is probably the simplest to arrange, and there are breakout boards for the Arduino that will convert UART to EIA-485.
It is possible (if you are clever) to make UARTs directly work as a multi-drop bus, but it requires a deeper understanding of UART control registers and electrical characteristics to emulate either an open-collector or tri-state TX pin on the slaves.
Of course, for all devices to operate on the same bus they must all conform to the specified operation of the bus. For instance, for EIA-485 all the slaves must have the ability to switch the transceiver into TX mode when needed, and react only to requests from the master and never send anything unsolicited. Just hooking random devices up to a bus with a transceiver is never going to work.
As far as USB goes - that is a single master (the PC) and multiple slaves (your keyboard, mouse, printer, scanner, webcam, Arduino, etc). Hubs are just a way of wiring them all together and routing the signals to the different peripherals at the right speeds.

I2C protocol has Multi-master Arbitration Support, i.e. any I2C device can be master and slave. I2C is a multimaster bus
Master start communication, but master device can change. If one device wants to communicate, acts as a master. The problem is that before sending data you must be sure the bus is not busy with other master.
More information: https://www.i2c-bus.org/multimaster/
With UART is not possible to build a bus, only point to point communication.

Another option thats possible if you can control the firmware on each node, as in your case with multiple arduino's, is to create a ring bus using UART ports with multiple peers on it where each node would be responsible for forwarding packets to the next node.
The UART rx tz lines for nodes would have to be connected in a ring like this:

NodeA Tx => NodeB Rx
NodeB Tx => NodeC Rx
NodeC Tx => NodeA Rx

This would require design of a somewhat complicated protocol and controlling firmware on each node, and you would need to think through issues like:

how many devices can be supported on the ring
message size
how much memory is available to buffer messages on each node
how many message is each node allowed to send
etc.


text:
How to connect dual brushless motors to arduino
I'm planning on making a Force Feed Back racing wheel with arduino.Saw a lot of tutorials but it uses brushed DC motors ,couldn't find how to connect dual brushless motor for force feed back.
This the motor I want to use :
http://www.dx.com/p/chrgm25bl2418-dc-brushless-motor-with-built-in-drive-24v-12v-470930#.WkurLcvhVAg

.                       .

Your link points to a battery...

Sorry about the link

http://www.dx.com/p/chrgm25bl2418-dc-brushless-motor-with-built-in-drive-24v-12v-470930#.WkurLcvhVAg

I'm voting to close this question as off-topic because it is about haptic motion systems, not Arduino.  This can't be an Arduino question until you've clearly defined what you goal is and verified that you have selected the correct mechanical and driver parts - something that at present it appears you have not, if your goal is "force feedback"

I want to know if there is any motor controller that could be used to control these motors and could be connected to arduino

It looks like you provide the correct voltage to the VCC and GND pins to power it, and connect the CW/CCW and PWM (and GND of course) to your Arduino - the first to control the direction, and the second to a PWM pin to control the speed.
You can use the FG pin to monitor the speed from the internal hall effect sensor if you want.

Thanks,is there any motor controller for this..?

You probably won't get force feedback by this approach.

It looks like the controller is built in. A bit like a servo.

So I can connect it to arduino without a motor controller like you said.?

I repeat my previous comment.


text:
Converting (char*)variable to int
I have the following code:
      uint8_t buf[1];
      uint8_t buflen = 1;
      if (driver.recv(buf, &buflen)) // Non-blocking
         {
            int i;
            // Message with a good checksum received, dump it.
            Serial.print("Message: ");
            Serial.println((char*)buf);//this prints out okay
            highPins[(char*)buf] = 1;
         }

The problem is in highPins[(char*)buf]. highPins is array, and in (char*)buf I get index number. When I display it with Serial.println, it shows the number, but here it does not. I am guessing its because (char*)buf is not a number. I have tried to convert it to int with few functions I have found online, but it was unsuccessful. Any help is appreciated :)

String(buf).toInt() is how i do it, but there might be better ways...

highPins[buf[0] - '0'] = 1; should do the trick :)

Note that Serial.println(const char[]) expects a NUL-terminated buffer. It will read your memory starting at &buf and continue until it finds a NUL byte.

I would suggest improving your code slightly as follows:
  uint8_t buf;
  uint8_t buflen = 1;
  if (driver.recv(&buf, &buflen)) // Non-blocking
     {
        int i;
        // Message with a good checksum received, dump it.
        Serial.print("Message: ");
        Serial.println(buf);//this prints out okay
        highPins[buf] = 1;
     }

The important point is that you do not need to declare buf as an array of just one element, but just declare the element itself (as uint8_t) and pass its address (&buf) to driver.recv(...).
As @Majenko suggested, you should alos check buf before using it as an index to highPins array, in order to avoid using an index bigger than teh array size.

The thing is, when I use your code, I get a strange result. I send string 33 with driver.send("33",  sizeof("33"));       , and with your code I get "53" over the serial. Any idea on what might be causing it?

You have to know what gets transferred between both devices: is that string or numbers? Your question made me think this was numbers (in binary representation, not as ASCII strings). You probably need to provide more details in your question.

The function you want is atoi.
int pinno = atoi((char *)buf);

I would suggest checking that the result is in the right range before using it.


text:
I2C libraries for ATTiny85?
I want to transmit I2C data, using a Digispark ATTiny85 board:

http://digistump.com/products/1
http://digistump.com/wiki/digispark/tutorials/connecting

I've found the following I2C libraries. Which one is more lightweight, stable, bug-free, efficient, powerful, and easy to use?

Adafruit's TinyWireM has not been updated in 2 years.
felias-fogg's SoftI2CMaster has been updated within days of this post.
lucullusTheOnly's TinyWire represents some years of improvements, "based on the TinyWireM and TinyWireS libraries". This version is recommended by BroHogan, co-creator of TinyWireM:
https://playground.arduino.cc/Code/USIi2c

Wire seems under-featured:

"the default Arduino Wire() library does not support changes in bus
  speed or feature proper clock stretching support. This makes the
  default library only marginally functional"
  https://www.maxbotix.com/articles/095.htm

What other I2C libs are available for ATTiny? In the IDE i see Digispark SoftSerial, OneWire, and VirtualWire.
How do they all compare?

Note, these other answers do not seem relevant to my question:

What's the difference between all the Software Serial Libraries? Which one is Arduino Nano compatible?
Alternatives to Wire library for I2C

try them both  ... the one with the most example code first

I want to transmit I2C data...

A little vague.
Transmit to what device? How fast is your data rate (100kHz, 400kHz)? Your only transmitting and not reading anything back? What is the idling voltage of your I2C bus (to then ask if you have chosen correct pull-up resistor values for your intended bus speed)?
You mention that the Wire library doesn't support core clock speed changes without some hacking, but don't talk about the speed you intend to run the microcontroller or how fast you intend to use the I2C. I can guess 400kHz, since you brought up speed, but that's not a great way to answer a question.
I have using the Wire library on an Arduino UNO at I2C bus rate of 100kHz and it's worked fine for my needs. I got bytes in and out.
At this point, the best suggestion I'd have is that if one of the above libraries you listed does not support a feature you'd like, fork it, and add support for your feature yourself. If you're only transmitting to one slave device, then you shouldn't need to worry about bus arbitration, like the TinyWire does. Adafruit is okay for the most part, but they seem (to me) slow to fix bugs and maintain code. But don't let the code's age get to you. I2C was created back in 1982, and you're still using it... :-P
Here's how I would approach choosing a library:

Define features you need
Look for a library which has most of those features
Add any new features you need
Possibly share your added features with the community with a Pull Request

bHogan seems to be the original developer of TinyWireM and TinyWireS.
Andreas Spiess ("The guy with the Swiss accent") used rambo's implementation of the TinyWire library for his I2C sensor, and rambo on GitHub and bHogan on arduino.cc seem to be the same person...
I've also used rambo's TinyWire library, and managed to make it work. Adafruits version of TinyWire seems to be a fork of rambo's code.


text:
Parsing serial port data
Hello I found an Arduino project that works with serial port parsing and it had very interesting parsing code. I am trying to use it in my project but I still don't understand some lines and what is going there. (I marked them with ???).
char inData[82]; //create 82 char array
byte index = 0; //index byte (0 - 255)
String string_convert; //String
int PCdata[20]; //int array

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

void loop() {
  parsing(); //loop the function
}

void parsing() {
  while (Serial.available() > 0) {
    //while there is data in serial buffer (128 bytes)
    char aChar = Serial.read(); //aChar - current symbol in buffer
    if (aChar != 'E') {
      //if aChar isnt the 'E' (End) symbol do:
      inData[index] = aChar;
      //(inData - array, index - loop № counter) write all Buffer to the array
      index++; //index + 1 - loop count
      inData[index] = '\0';
      //set the next position to '\0' or null symbol
    } else {
      //if aChar or current buffer symbol is 'E' (End) do:
      char *p = inData; //create inData address pointer
      char *str; //create pointer
      index = 0; //set counter to 0
      String value = ""; //create string
      while ((str = strtok_r(p, ";", &p)) != NULL) { //???
        string_convert = str; //???
        PCdata[index] = string_convert.toInt(); //???
        index++; //counter + 1 - loop count
      }
      index = 0; //counter to 0
    }
  }
}

Thank you for help!

It's parsing a bunch of semi-colon separated data, like "12;34;45;". In each iteration, it converts one value from character representation to its integer value.
strtok_r is the reentrant version of strtok. On Arduino you simply use strtok. Every time you have to parse a string having a list of values separated by some char, you use strtok.
Name
strtok, strtok_r - extract tokens from strings
Synopsis
#include <string.h>

char *strtok(char *str, const char *delim);

char *strtok_r(char *str, const char *delim, char **saveptr);

The strtok() function parses a string into a sequence of tokens (sub-strings). On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.
Each call to strtok() returns a pointer to a null-terminated string containing the next token. This token does not include the delimiting byte. If no more tokens are found, strtok() returns NULL.