body:
So I'm trying to use my UNO as an HID device. I followed [this][1] tutorial, flashed the firmware and got the UNO to be detected as an HID device.

[1]:http://www.instructables.com/id/Make-arduino-uno-work-like-leonardo/
However, I am still getting the error
>'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?

Here's the code -

    /*
    Copyright (c) 2014 NicoHood
     See the readme for credit to other people.

     Keyboard example
     Press a button to write some text to your pc.
     See official documentation for more infos
     */

    // include HID library
    #include <HID.h>

    const int pinLed = 13;
    const int pinButton = 8;

    void setup() {
      pinMode(pinLed, OUTPUT);
      pinMode(pinButton, INPUT_PULLUP);

      // Starts Serial at baud 115200 otherwise HID wont work on Uno/Mega.
      // This is not needed for Leonado/(Pro)Micro but make sure to activate desired USB functions in HID.h
      Serial.begin(115200);

      // Sends a clean report to the host. This is important because
      // the 16u2 of the Uno/Mega is not turned off while programming
      // so you want to start with a clean report to avoid strange bugs after reset.
      Keyboard.begin();
    }

    void loop() {
      if (!digitalRead(pinButton)) {
        digitalWrite(pinLed, HIGH);

        // Same use as the official library, pretty much self explaining
        Keyboard.println("This message was sent with my Arduino.");
        Serial.println("Serial port is still working and not glitching out");

        // simple debounce
        delay(300);
        digitalWrite(pinLed, LOW);
      }
    }

    /*
    Definitions:

     KEY_LEFT_CTRL
     KEY_LEFT_SHIFT
     KEY_LEFT_ALT
     KEY_LEFT_GUI
     KEY_RIGHT_CTRL
     KEY_RIGHT_SHIFT
     KEY_RIGHT_ALT
     KEY_RIGHT_GUI

     KEY_UP_ARROW
     KEY_DOWN_ARROW
     KEY_LEFT_ARROW
     KEY_RIGHT_ARROW
     KEY_BACKSPACE
     KEY_TAB
     KEY_RETURN
     KEY_ESC
     KEY_INSERT
     KEY_DELETE
     KEY_PAGE_UP
     KEY_PAGE_DOWN
     KEY_HOME
     KEY_END
     KEY_CAPS_LOCK
     KEY_F1
     KEY_F2
     KEY_F3
     KEY_F4
     KEY_F5
     KEY_F6
     KEY_F7
     KEY_F8
     KEY_F9
     KEY_F10
     KEY_F11
     KEY_F12

     KEY_PRINT
     KEY_SCROLL_LOCK
     KEY_PAUSE
     */

Can anyone point out what I'm doing wrong here?

title: Unable to use Keyboard library with Arduino UNO even after changing the firmware

Answers: 2

body: If I open the rar library file, than I see a file called Keyboard.h. I'm sure you need to include Keyboard.h, than the class Keyboard is known and you can use it in your sketch.

body:
Okay, so the problem was that the added HID library was conflicting with the core Keyboard/Mouse library. I replaced the core library with the new one and it worked without any problems.

Well one problem actually, it would ask for a platform.h. To solve this download the Arduino v1.5.7 BETA zip and find the platform.h file in it and paste it in your current Arduino directory.


body:
I am working on a project where I connect a GPS module and GPRS SIM900 shield. The location will be sent when it recives a certain character.

Now my question is, can the Arduino receive from GPRS and GPS module data at the same time? The GPS is not given coordinates, however it works properly without receiving a message from the GPRS.

I am using softwareserial  for both. Should/can I use hardware serial and softwareserial?

title: Make Arduino send and receive at the same time

Answers: 3

body:
Probably you don't need to use both GPS and GPRS in same time. Just check for a certain character from GPRS in the loop and when it comes check the GPS data.

Why not connect GPS module to hardware serial?

body:
> I am using `SoftwareSerial` for both.

As others have said, you cannot listen to 2 `SoftwareSerial` ports at the same time.

>   Should/can I use `HardwareSerial` and `SoftwareSerial`?
>
>  ... can the Arduino receive from GPRS and GPS module data at the same time?

Yes, but...

[This answer](https://arduino.stackexchange.com/questions/34126#34130) provides full details on choosing "good" combinations of hardware and software serial ports.  To summarize:

*  Use the `HardwareSerial` port (i.e., `Serial`) for one of the devices.  You can still use it for debug prints, as long as the device has some kind of command "format".  For example, if commands start with "AT", just make sure that none of your debug prints start with "AT".  It is the absolute best choice.  You would have to disconnect RX pin 0 from the device in order to upload new sketches over USB.

*  Use `AltSoftSerial` for the other device.  It is the most efficient software serial port, and it can be used at the same time as `Serial`.  It only works on two specific pins.

*  `NeoSWSerial` is the next best choice, at limited baud rates.  It can be used with the above choices, but transmitting on `NeoSWSerial` prevents them from receiving.

*  `SoftwareSerial` is the worst choice.  Receiving **or** transmitting on `SoftwareSerial` prevents all of the above from receiving anything.  It disables interrupts for long periods of time.

body: you can connect gps to hardware serial port rx and gsm to software serial.  in similar way,  I solve the problem


body: I'm working on an Arduino project that sends and receives text to/from a C# application via ENC28J60 in a LAN network. Whenever C# sends a request to Arduino (In text), Arduino responds to it by sending also a text. What is the best way to do this? I'm newbie in network programming (Or whatever it's called). Thanls in advance :)

title: Send and receive text between Arduino Mega 2560 and C# via ENC28J60

Answers: 1

body:
You can use TCP or UDP protocols.

https://www.arduino.cc/en/Tutorial/UDPSendReceiveString

https://www.arduino.cc/en/Tutorial/DhcpChatServer

You can use free UDP, TCP port listener sofwares for Windows, Linux etc.. for testing your setup.

For C# development:

https://stackoverflow.com/questions/20038943/simple-udp-example-to-send-and-receive-data-from-same-socket

and

https://stackoverflow.com/questions/10182751/server-client-send-receive-simple-text


body:
so I am new to arduino and coding in general, I am trying to use the arduino to remotely survey plants, I am using this guide: https://create.arduino.cc/projecthub/arduino/plant-communicator-7ea06f. The entire code is:

    #include <WiFi101.h>
    #include<WiFiSSLClient.h>
    const char* ssid = SKY1C9D0;    //  your network SSID (name)
    const char* password = SYDTSTQR;  // your network password
    String httpsRequest = https://hooks.zapier.com/hooks/catch/2821422/84ehn1/;
    // your Zapier URL
       const char* host = "hooks.zapier.com";
    WiFiSSLClient client;
    void setup() {
      Serial.begin(9600);
      while (!Serial);
      delay(2000);
      Serial.print("Connecting Wifi: ");
      Serial.println(ssid);
      while (WiFi.begin(ssid, password) != WL_CONNECTED) {
        Serial.print(".");
        delay(500);
      }
      Serial.println("");
      Serial.println("WiFi connected");
    }
    void loop() {
      float temperature = 22;
      int moisture = 150;
      int light = 40;
      String warning = "This is a warning message";
      warning.replace(" ", " ");
      send_email(temperature, moistue, light, warning );
      delay(20000)
    }
    void send_email(float temperature, int moisture, int light, String warning)     {
      // convert values to String
      String _temperature = String(temperature);
      String _moisture = String(moisture);
      String _light = String(light);
      String _warning = warning;
      if (client.connect(host, 443)) {
        client.println("POST " + httpsRequest + "temperature=" + _temperature +                 "&moisture=" + _moisture + "&light=" + _light + "&warning=" + _warning + "     HTTP/1.1");
        client.println("Host: " + String(host));
        client.println("Connection: close");
        client.println();
        delay(1000);
        while (client.available()) { // Print on the console the answer of the server
          char c = client.read();
          Serial.write(c);
        }
        client.stop();  // Disconnect from the server
      }
      else {
        Serial.println("Failed to connect to client");
     }
    }

The error is specifically highlighted here:
    `const char* ssid = SECRET_SSID;    //  your network SSID (name)`. The error is that the ssid has not been declared.
I am unsure of what to do to fix this and any other possible errors that have gone unnoticed. I would highly appreciate any help or guidance.
Thank you

title: SSID was not declared in this scope

Answers: 2

body:
You need quotes around literal string values.

    const char* ssid = "SKY1C9D0" ; // your network SSID (name)
    const char* password = "SYDTSTQR" ;

body:
A problem in the include file on the line previous could cause the following line to be misinterpreted. To test that try moving the ssid after the password and see if the error changes. Obviously make sure all strings are properly quoted.

    #include <WiFi101.h>
    #include <WiFiSSLClient.h>

    const char* password = "SYDTSTQR";  // your network password
    const char* ssid = "SKY1C9D0";    //  your network SSID (name)
    String httpsRequest = "https://hooks.zapier.com/hooks/catch/2821422/84ehn1/";


body:
I recently purchased several of the DFRobot ledkeypad shields: https://www.dfrobot.com/product-1407.html

I have Arduino Leonardo (which also had some problems in the beginning, being recognized as modems).
My OS is Linux Mint, and I'm using the last Arduino IDE.

The library I use is the one recommended on the website of the vendor, LedKeypad.h, and works fine with the other shields of the same model from the same batch.

Some shields worked fine but I am now having trouble with one of them, which seems unresponsive. I can load for instance the blink program in the arduino, and it works, but the shield does not work. When it is plugged in, the fours dots are slightly red, and I cannot turn them off.

I tried displaying something on the serial monitor when the buttons are pushed, and only one of the 5 buttons works (the KEY_DOWN one).

Is there anything I can attempt to fix the problem ? Or should I just give up on this shield ?

title: ledkeypad shield not responsive

Answers: 1

body:
> ... and works fine with the other shields of the same model from the same batch.

So had you considered that the shield might be faulty? Have you contacted the manufacturer or vendor for support?


body:
I have created a small circuit with a 220 Ohm resistor and a LED connected to PIN9 for power.

I want to measure the Voltage of the current flowing through the circuit. In order to do that I connected a bridge from between the resistor and the LED to the A3 PIN and used this code:

    int ledPin=9;
    int inPin=A3;
    long int in=0;
    float V_in=0;
    int val;

    void setup() {
      analogReference(DEFAULT);
      pinMode(ledPin, OUTPUT);
      pinMode(inPin, INPUT);
      Serial.begin(9600);
      }

      void loop() {
        if (Serial.available() > 0) {
          val = Serial.parseInt();

          if (val>=0 && val<=155) {
            analogWrite(ledPin, val);
            //Serial.println(val);

            for (int i=0; i<10; i++) {
              val+=5;
              analogWrite(ledPin, val);
              //Serial.println(val);

              delay(1000);
              in = analogRead(inPin);
              V_in=float(5.0)*(float(in)/float(1023));
              Serial.println(V_in);
              delay(1000);
              }

            }
            else {
              Serial.println("Dio è morto.");
              }
          }
        }

**The problem is that when I run it, with an Input of 55, I get what seams to be a random arrangement of 0s and 2.56s. While I expect a increasing sequence of numbers between 0 and 2.5.**

**What am I doing wrong?**

I measured the Voltage on the A3 Pin using a voltimeter, and it increases every step by 0.2, exactly as expected.

This is an output example:

[![example][1]][1]

  [1]: https://i.stack.imgur.com/R4aga.png

title: Arduino UNO - analogRead() returning mixed results

Answers: 1

body:
The `analogWrite` function, despite its name, outputs PWM (pulse width modulation) which is either fully on or fully off, with varying duty cycles. If you run that through a RC network (eg. 4.7k in series and 10 µF to ground), it will smooth out the pulses and you will actually get a varying voltage.

So in your case you are measuring on or off depending on the timing. However since you are measuring between the resistor and the LED, you won't get 5V because of the voltage drop over the resistor. An LED, depending on the colour, might have a voltage drop of around 2.2V, and thus you might expect 2.8V at that junction. This is approximately what you got.

---

> I want to measure the Voltage of the current ...

This doesn't make any sense electrically. You are either measuring the voltage (in volts) or the current (in amps). You don't measure the "voltage of the current". I suppose you mean "the voltage at that point".

---

### Reference

Arduino functions reference:

[Reference > Language > Functions > Analog io > Analogwrite ](https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/)


body:
I am new to Arduino and I am currently working with an Arduino Uno and SD card module - SD/MMC for database storage using the Arduino database library from <https://github.com/jwhiddon/EDB>.

My question is, is the `char str[]` type the equivalent of `VARCHAR`?

Here is my arbitrary record definition for my table:

    struct LogEvent {
      int logId;
      int unumber;
      char username[10];
      char fname[15];
      char lname[15];
      char role[6];
      char boxid[10];
      char userStatus[2];
    } logEvent;

title: Arduino extended database library data type. Is char str[] in Arduino the equivalent of VARCHAR in SQL?

Answers: 2

body: If you're referring to the SQL type `VARCHAR`, then, vaguely. `char username[10];` for instance will define a char array of 10 bytes. A `char` being the equivalent of a byte. That's about it for the type. This is C++, so you're pretty close to the iron, and a char array is about as basic as it gets. No collation, no encoding (remember that a character is not always a single byte!), no indexing. Just a bunch of bytes put together.

body:
If you mean, are these equivalent:

    foo VARCHAR(100);

and:

    char foo [100];

No, they are not equivalent, really. In the case of SQL you can put 100 characters into foo. In the case of C++ you would (generally speaking) put up to 99 characters into foo, with the final character being 0x00 which indicates the length of the string.

You could conceivably put 100 characters into `foo` but then you would have to store the size of `foo` in another variable.


body:
I bought a new ENC28J60 module and I tried to communicate with the PC through Arduino Uno board.

When I tried to ping the address that I gave in the program it's not getting the ping. Give me some solution.

I used the web server example that is in the example section of Arduino. I even turned off my firewall setting.

The code that I used is:

    /*
      Web Server

     A simple web server that shows the value of the analog input pins.
     using an Arduino Wiznet Ethernet shield.

     Circuit:
     * Ethernet shield attached to pins 10, 11, 12, 13
     * Analog inputs attached to pins A0 through A5 (optional)

     created 18 Dec 2009
     by David A. Mellis
     modified 9 Apr 2012
     by Tom Igoe
     modified 02 Sept 2015
     by Arturo Guadalupi

     */

    #include <SPI.h>
    #include <Ethernet.h>

    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };
    IPAddress ip(192, 168, 1, 20);

    // Initialize the Ethernet server library
    // with the IP address and port you want to use
    // (port 80 is default for HTTP):
    EthernetServer server(80);

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      // listen for incoming clients
      EthernetClient client = server.available();
      if (client) {
        Serial.println("new client");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            Serial.write(c);
            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n' && currentLineIsBlank) {
              // send a standard http response header
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println("Connection: close");  // the connection will be closed after completion of the response
              client.println("Refresh: 5");  // refresh the page automatically every 5 sec
              client.println();
              client.println("<!DOCTYPE HTML>");
              client.println("");
              // output the value of each analog input pin
              for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
                int sensorReading = analogRead(analogChannel);
                client.print("analog input ");
                client.print(analogChannel);
                client.print(" is ");
                client.print(sensorReading);
                client.println("
");
              }
              client.println("");
              break;
            }
            if (c == '\n') {
              // you're starting a new line
              currentLineIsBlank = true;
            } else if (c != '\r') {
              // you've gotten a character on the current line
              currentLineIsBlank = false;
            }
          }
        }
        // give the web browser time to receive the data
        delay(1);
        // close the connection:
        client.stop();
        Serial.println("client disconnected");
      }
    }

title: ENC28J60 is not getting ping

Answers: 1

body:
You have an ENC28J60 based module. Your code is for the Wiznet-based module. The two are not interchangeable.

See this: http://nathanhein.com/2013/02/getting-arduino-online-with-an-enc28j60/

Good luck.


body:
I used the code from this [project...](https://digibird1.wordpress.com/arduino-as-a-5m-sample-osciloscope/comment-page-1/#comment-354) to build an oscilloscope-like project. It worked fine with Uno and Nano.

Later I tried to do the same with a Mega, but I don't know what's wrong. It's not working! Maybe due to some pin or port number mismatch (I think so...). Because it has some low level code like:

    ------------------------------------------------------
    // set up 8 MHz timer on pin 9
    pinMode (9, OUTPUT);
    // set up Timer 1
    TCCR1A = _BV (COM1A0);  // toggle OC1A on Compare Match
    TCCR1B = _BV(WGM12) | _BV(CS10);   // CTC, no prescaling
    OCR1A =  0;       // output every cycle
    ---------------------------------------------------------

And like:

    Data.Values[i]=PINC;

I have very little knowledge about these registers.

Please help me port this code to Mega and make it work...

title: Code that worked in Uno/Nano is not working in Mega - help me port the code to Mega

Answers: 1

body:
There is some concept you would have to learn before you can go from Arduino Uno to Mega.
Because your [project][1] is designed to operate on Arduino Uno R3, the registers operations like below are specific to the microcontroller in Arduino Uno - in this case ATmega328P-PU - datasheet [here][2]
`TCCR1A = _BV (COM1A0);  // toggle OC1A on Compare Match
 TCCR1B = _BV(WGM12) | _BV(CS10);   // CTC, no prescaling
 OCR1A =  0;`
You can find description of registers in mentioned datasheet in chapter 19. TC0 - 8-bit Timer/Counter0 with PWM
Now, you grab another datasheet - one which describes ATmega2560 (yes, this is microcontroller which is sitting in Arduino Mega), find corresponding pin (like OC1 in Uno - check the drawing below):
[![Arduino Uno R3][3]][3]
and find proper pin and corresponding register from ATmega2560 [datasheet][4].
Take a look at the schematic picture first, select one of OCx pins and configure what is needed.
Pins from Aruino Mega with OCR functionality:
[![Arduino Mega][5]][5]
and
[![Ard Mega][6]][6]
You need to learn what registers are, and what they can do. Can be a little demanding task, but believe me - this will give you supernatural powers in microcontrollers world ;)

  [1]: https://digibird1.wordpress.com/arduino-as-a-5m-sample-osciloscope/comment-page-1/#comment-354
  [2]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf
  [3]: https://i.stack.imgur.com/aOH4g.png
  [4]: http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf
  [5]: https://i.stack.imgur.com/Y84uE.png
  [6]: https://i.stack.imgur.com/KsafT.png


body:
I am connecting an ESP8266 to my home network (WiFi). After successful connection, an IP is assigned to it. I am sending commands to the ESP8266 from an Android app.

What can I do to find the ESP8266 on any network where my Android app is also connected? I ask this because whenever I change the network, a new IP is assigned to the ESP8266 and I have to manually change the IP in the Android app.

I just need to find the ESP8266 on the network, get its IP address and send commands to it.

Thanks in advance.

title: Finding ESP8266 in a network

Answers: 2

body:
Some solutions that have worked for me:

1. **Reserved IP** - use the router's DHCP reservation to give the same ESP the same IP each time.

2. **Static IP** - Set the ESP to use the same IP each time, bypassing the DHCP feature altogether. This also boots the ESP slightly faster. `WiFi.config(ip, gateway, subnet);`

3. **Dump the IP** address to Serial on boot, so that you can at least see what's assigned: `Serial.println(WiFi.localIP());`

4. Give the **STA a unique name** that you can find in the router's DCHP clients page: `WiFi.hostname("look_here");`

5. use **mDNS** to assign a domain-like local URL to the device: `MDNS.begin("esp8266");// default to "http://esp8266.local/"`

body:
The best way to do this if you are doing it for product is using SSDP protocol.
It's Simple service discovery protocol which allows you to search for device in a network. It's implemented in many smart devices now a days with dlna or upnp.

Implement a SSDP server on esp8266 and
Implement a SSDP client on Android device.

You can find many devices with this approach, using simple filter to result with your specific information you want from SSDP packet can allow you to only get desired devices from network.

All the documentation about SSDP is given on Arduino esp8266 GitHub page.

You can broadcast your IP in your SSDP packet and then use it in your app, But still your most imp problem of dynamic IP remains unsolved as your IP will always be changing and using IP for accessing a hardware like home automation is not proper way.

You can either use.
1) Static IP for this if you want offline access or
2) Use cloud based solutions, such as mqtt to access device anywhere without the worries of NAT, IP or anything.

But second option is more of commercial kind, you need multiple resources to implement it.


body:
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
    }

title: LED Blinking Using Push button

Answers: 2

body:
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) {

body:
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; }
    }


body:
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:

>1. How many locations are there in the EEPROM? (For Arduino Uno & Mega)
>
>2. 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?
>
>3. So, what about reading the contents of the EEPROM? Does it have the same limit?
>
>4. And what is the starting location (address) of the EEPROM? (For Arduino Uno & Mega)

EDIT:1

> 5. 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?

title: EEPROM - Arduino

Answers: 1

body:
> (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.


body:
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..

title: Arduino HTTP Post request

Answers: 1

body:
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


body:
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!

title: Detecting the presence of a specific smartphone

Answers: 1

body:
> 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...


body:
I'm using an Arduino Mega 2560 to make a fire alarm control panel. The control panel takes 50 (inputs) [supervised inputs][1]. 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.

  [1]: https://resources.altium.com/pcb-design-blog/how-to-implement-supervised-inputs-in-your-pcb-circuit-design

title: Supervised inputs for alarm panel

Answers: 1

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

1. **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.
2. **External ADC Chips** -- Add more real analog inputs over SPI or I2C. For 50 inputs that would be quite a lot of extra chips.
3. **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](http://tinyurl.com/y8oxpzk8), 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).
4. **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.


body:
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?

title: Can I measure multiple photoresistors from one pin?

Answers: 2

body:
If response time is critical (on the order of about a quarter of a second) consider using [photo diodes][1] instead of [Cadmium sulfide cells][2].

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.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/ZhGHP.png)

<!-- End schematic -->

  [1]: https://en.wikipedia.org/wiki/Photodiode
  [2]: https://en.wikipedia.org/wiki/Photoresistor

body:
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?


body:
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!

title: How to loop a specific tone?

Answers: 1

body:
    #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);
      }
    }


body:
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:[![enter image description here][1]][1]Why this strange behaviour happens?

  [1]: https://i.stack.imgur.com/YEc5v.png
Thank you

title: Arduino uno PWM CTC mode - strange behaviour on interrupt

Answers: 1

body:
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.


body:
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:

[![Arduino Editor Board List][1]][1]

  [1]: https://i.stack.imgur.com/gUTcq.png

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

title: WEMOS: How to install it?

Answers: 1

body:
I just read that it can't. It's a shame:

[https://forum.arduino.cc/index.php?topic=441328.0][1]

  [1]: https://forum.arduino.cc/index.php?topic=441328.0


body:
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:

[![Circuit using fritzing][1]][1]

  [1]: https://i.stack.imgur.com/KragO.png

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.

title: Arduino Uno: Driving a small LED strip with 2N3904 NPN

Answers: 1

body:
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`.


body:
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;

    }

title: How to store values from a sensor inside an empty array?

Answers: 1

body:
      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.


body:
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);
        }
      }
    }

title: Pause running program using a pushbutton

Answers: 2

body: 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().

body: 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.


body:
I have an ATmega328P on a breadboard with the following circuitry around it:
[![Breadboard Circuitry][1]][1]
The ISP is a [Tiny AVR Programmer][2]. The RS232 to USB converter is [this thing][3].

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][4] 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][4] 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?

  [1]: https://i.stack.imgur.com/ANtXs.png
  [2]: https://github.com/sparkfun/Tiny-AVR-Programmer
  [3]: https://www.conrad.at/de/schnittstellenwandler-197257-usb-rs-232-passend-fuer-serie-c-control-197257.html
  [4]: https://www.arduino.cc/en/Hacking/Bootloader

title: Cannot upload to otherwise working bootloaded ATmega328P via RS232: "programmer is not responding"

Answers: 0


body:
I have problem creating Setup which have :

1. A SPI Master (Arduino Mega 2560)

2. 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 https://arduino.stackexchange.com/questions/16348/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 https://arduino.stackexchange.com/questions/9616/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

title: Multiple Slaves(Arduino Mega 2560) response over SPI

Answers: 1

body:
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,


body:
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.

title: Alternative of relay

Answers: 2

body:
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:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/su86b.png)

<!-- End schematic -->

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).

body:
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:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/dpPz9.png

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.


body:
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);
      }
    }

title: Pass a char array to a function that uses File as parameter

Answers: 1

body:
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 :-)


body:
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.

title: Unclear GET request mixed values

Answers: 2

body:
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.

body:
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][1]

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

  [1]: http://forum.arduino.cc/index.php?topic=49357.0


body:
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.

title: RF receiver for integer only, how to cast uint8_t to int?

Answers: 1

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