body:
I tried to edit the Fade sketch such that the max intensity the PWM reaches is controlled by a potentiometer. I used analogRead() on the potentiometer and converted the 10bit value to 8bit equivalent(by dividing by 4 and rounding) to feed into analogWrite. I am new to arduino and I dont know a more elegant way to do this, sorry!

It worked generally but **sometimes** while turning the potentiometer, the **LED would be stuck at a fixed level of brightness**. I have to reset the Arduino or turn the pot to the extremes to remove this "loop". I set up serial monitor to look at the values of brightness. It does not always happen at the same position of the potentiometer.

I deduce that it is a mathematical error causing this loop, likely due to my poor use of the if() function. Can anyone offer me a reason for this?

*I tested with both the Uno and Nano, as well as TinkerCad simulator with similar results.

[![Basically like this but with positive lead on pin 11 instead of 13][1]][1]
[![Brightness stuck at specific values][2]][2]

-----------------------------Fade sketch edited by me----------------------

    /*
     Fade, edited with maximum intensity controlled by potentiometer reading
     */

    int led = 11;           // 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
    int potPin = A0;    // set the pin that reads the potentiometer voltage
    int potValue = 0;   // declare and initialize potValue
    int potValueConverted = 0; // 10bit potValue converted to 8bit equivalent

    // the setup routine runs once when you press reset:
    void setup() {
      // declare pin 9 to be an output:
      pinMode(led, OUTPUT);
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      //read the voltage at the pot
      potValue = analogRead(potPin);

      //convert 10bit input into 8bit output by dividing by 4, rounding to avoid need for float variable
      potValueConverted = round(potValue/4);

      // set the brightness of pin 11:
      analogWrite(led, brightness);

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

    Serial.println(brightness);

      // reverse the direction of the fading at the ends of the fade:
      if (brightness <= 0 || brightness >= potValueConverted) {
        fadeAmount = -fadeAmount;
      }

      // wait for 30 milliseconds to see the dimming effect
      delay(30);
    }

----------------------------------------------------------------------------

  [1]: https://i.stack.imgur.com/IovL8.jpg
  [2]: https://i.stack.imgur.com/5YXPZ.png

title: Fade sketch stuck in mathematical loop

Answers: 2

body:
> the LED would be stuck at a fixed level of brightness.

that's by design: think about what happens when potValueConverted is very small.

edit:

to change the brighness, I would do this:

      brightness += fading; //change brightness;
      if ((brightness < BRIGHTNESS_MIN) || (brightness > BRIGHTNESS_MAX)) {fading = -fading; brightness += fading;} //bound brightness to _MIN and _MAX

body:
It seems like the problem occurs when brightness is a lot higher than potValueConverted.

For example, lets say our brightness=100, potValueConverted=50, this triggers the latter "if" condition, i.e.
> brightness >= potValueConverted

and at the next iteration, brightness = 105 (or 95), both of which will satisfy the condition for fadeAmount to flip its polarity, thus resulting in the brightness value oscillating between 105 and 100 (or 100 and 95).
This results in the LED getting stuck at the same level of brightness.

a quick hack fixes this problem (as far as I can tell)

     if (brightness <= 0 ) {
        fadeAmount = 5;
      }
     if (brightness >= potValueConverted +5 ) {
        fadeAmount = -5;
      }

**note the +5 for the second if statement is to ensure that the brightness value does not become negative.


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

  [1]: https://i.stack.imgur.com/7IXYd.jpg

Beginner here: Would the circuit in the picture work or do input pins not absorb the energy as ground does? I know setting the pin as an input makes the direct 5V connection safe but maybe I'm mistaken. I'm trying to understand the nature of how these connections are made. Thank you in advance!

title: Can you use an input pin instead of ground in Arduino circuitry?

Answers: 2

body:
If you remove the ground wire, digital pin 2 will be left "floating" until the button is pressed, and this is not a good thing to do:

https://electronics.stackexchange.com/questions/83133/arduino-digitalread-reading-wrong

There is a way to eliminate the pull-down resistor and simplify the wiring by using pinMode(BUTTON_PIN, INPUT_PULLUP); in setup(). You would connect one "leg" of the N.O. momentary push button switch to ground and the other "leg" to Pin 2. You will still need to "debounce" the switch, and for that I recommend a library.

There is a link to a good library here: https://playground.arduino.cc/Code/Bounce.

The example sketch called bounce.ino is a good place to start.

body:
An input pin can only sense the voltage that is applied to it - whether it is above or below a pair of thresholds.

In your existing circuit when the button is not pressed the voltage sensed by the pin is 0V because it is connected to 0V (also known as Ground) through the resistor. When you press the button the input pin is connected directly to +5V, so the pin senses 5V.

If you remove the resistor or the connection to ground the pin can still sense 5V on it when the button connects it to 5V, but when you release the button the input pin then isn't connected to anything at all. It's not connected to 0V, so it can't sense what voltage is there - there simply isn't any voltage connected to it (no voltage isn't the same as 0V).

In this case the pin is said to be "floating". It's neither HIGH (5V) nor LOW (0V), it's just dangling around not knowing what it's doing.

If you want to get more technical and look at the mechanics of it, it's helpful to know that the gate of a MOSFET (which is what the input pin actually is) looks to all intents and purposes like a small capacitor.  When you connect the input pin to +5V the capacitor is charged up (current flows into it from 5V to charge it). When you connect the input pin to 0V it discharges (current flows out of the capacitor down to 0V). When charged you have a HIGH and when discharged you have a LOW.

However when a charged capacitor has no connection it (for a certain amount of time, due to *self discharge*) keeps hold of its charge. So if you charge it with +5V and then disconnect it you will still get +5V on the capacitor. That is until it discharges through internal leakage currents.

Those leakage currents though are so small and the capacitor is so sensitive that the input pin acts like a radio antenna. It picks up *noise* from the surrounding area (electromagnetic waves) which can charge and discharge the capacitor pretty much at random. So at times you may see the input as HIGH and at other times as LOW, purely depending on chance. And the longer your wires the more noise it will pick up.

The worst source of noise is the 50/60Hz mains hum that is all around you. You can see this in reality if you graph the voltage on a disconnected ADC pin and bring your hand close to it - you act like a capacitively coupled antenna and you can see the mains waveform on your graph.

It's the same on a digital input pin, except that it converts it to a square wave as it passes the thresholds (you might like to look at *schmitt triggers* for more detail about how it does that).

So adding the pull down (or pull up if you prefer) resistor is critical to making the input pin see what you want it to see, and not just random noise.

Since the input is like a capacitor selecting the right value of resistor can be quite important in some situations. For a simple button like this there's nothing to worry about, but for something like a rotary encoder where the input signal may change more rapidly the resistor value does become more of a concern.  Have too high a value and the gate will take too long to discharge (or charge if it's a pull up resistor). Too low and too much current could be wasted through the resistor when the button (or encoder) is active (potentially damaging the button if it's a low current sensitive device).


body:
Currently, I have an Arduino Uno set up, with a HC-SRO4 ultrasonic sensor printing distances of objects in front of it on a scale from 1-15 to the serial monitor. I want to attach the HC-05 bluetooth module and do the following:
First, it will read the values from the serial monitor. Then, I would like the HC-05 module to take these numbers and continuously send it to my Android app, which will then process what to do with the numbers.

I understand the Android part may be out of scope of this forum, but please try to help me with taking data from the serial monitor and have it transmit the data.

Here is the code I have for the ultrasonic sensor:

    const int trigPin = 9;
    const int echoPin = 10;
    // defines variables
    long duration;
    int distance;
    void setup() {
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
      Serial.begin(9600); // Starts the serial communication
    }
    void loop() {
      // Clears the trigPin
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      // Sets the trigPin on HIGH state for 10 micro seconds
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      // Reads the echoPin, returns the sound wave travel time in microseconds
      duration = pulseIn(echoPin, HIGH);
      // Calculating the distance
      distance = duration * 0.034 / 2;
      // Prints the distance on the Serial Monitor
      Serial.print("Distance: ");
      Serial.println(distance);
    }

title: How do I make the HC-05 bluetooth module take data from the HC-SRO4, and then send it to my Android app?

Answers: 2

body:
> First, it will read the values from the serial monitor. Then, I would like the HC-05 module to take these numbers and continuously send it to my Android app, which will then process what to do with the numbers.

No. What you do is you connect your Bluetooth module to two digital pins, which you'll use, along with the `SoftwareSerial` library, just the way you are using currently the `Serial` object. Look at the `SoftwareSerial` examples in the IDE.

Before you use the HC-05 module, and transmit data, you'll have to make sure it is set up properly (baud rate, name, PIN code, etc). Plenty of code and tutorials on Google about that.

body: Use software serial library and connect your HC-05 TX RX pins accordingly, to transmit/recieve the ultrasonic data using bluetooth. From playstore you will get bluetooth terminal software. Install it in your smart phone. Now connect your phone's bluetooth to HC-05 using that software. Now you can see in that app, all data you are receiving via bluetooth. you can also transmit data using that app. If you want to develop your own app, maybe you can check out MIT app inventor. Simple and fast.


body:
I'm as new as you can be at Arduino programming and specific electronics, so I don't even know if I'm asking the correct question.

I've ordered an Arduino a breadboard and some PCBs and now I'm looking for a few parts that I should buy in order to get some basic projects done.

I'd like to start with a garden automation project, a fairly simple one.
Humidity sensors, temperature sensors and a water pump.

Can I connect all (4) of the humidity sensors to a single local circuit and then connect that to the board so I can limit the number of input pins used? I'd still need to get independent readings from the sensors. Or would I need to use another board incorporating RF/Wireless/Bluetooth modules to receive the information and then send it to the board for further processing?

I'm sorry if what I just said makes no sense and I thank you for your time.
All I have is low-mid level electronic related experience. Battery checkers, Power supplies, basic light sensors, PCB making ETC.

title: Can you connect more sensors of the same type to a single board while not using up more pins than if you were to use a single sensor?

Answers: 3

body:
If the connection is a digital sense pin then you can use a parallel-in serial-out IC to read them all simultaneously and then shift it in. Takes up 3 pins on the arduino a latch a clock and a data pin.

If the connection is SPI then you can connect the clocks and MISO pins together and then need a slave select for each. you can control many of them with a serial in parallel out IC or a decoder.

If the connection is with the I2C protocol and each device has a different address then you can simply connect them all in parallel.

If the sensor has an analog output then you can use an analog to digital converter (ADC) which can have multiple inputs and often have a serial interface.

body:
If you do not need them to run simultaneously, you can use a multiplexer such as this one from Sparkfun:

https://www.sparkfun.com/products/9056

body:
It all depends on the interface between the Arduino and the sensor.

For example the DS18B20 uses the 1-Wire bus. That requires one digital pin and a number of DS18B20 can be connected to the same 1-Wire bus. Every DS18B20 has an unique identifier that makes that possible.

Humidity sensors like DHT11 or DHT22 require a pin for each sensors. They are not accurate anyway.

Sensors like the BME280 use the I2C bus. The I2C bus allows that many sensors can be connected. Each I2C sensor has an I2C address. Sometimes a sensor can have just one I2C address and therefor only one of such a sensor can be connected to the I2C bus. But sometimes a trick is possible to have more.

This list goes on and on and on. A lot is possible without extra hardware.

Because you are going to use sensors and many sensors are 3.3V, did you buy a 3.3V Arduino board ?


body:
I have been working with Arduino for almost a year, because I found it easy for beginners in electronics. But now, I have a major problem, I'm trying to get rid of my delay() function because I want my Arduino Nano to handle to tasks at once:

1-Read MIDI data and transfert it into a pwm signal, as well as monitoring the on and off of the signal (which are bytes). This part works correctly, but i'm not using the mirco(), i'm using a library called Timer1.

2-Generate a PWM signal of 20% dutycycle with a frequency ranging from 1 to 103 Hz using a potentiometer to adjust the frequency.

So, what happens is that the signal I measure on my oscilloscope is a PWM at 50% duty cycle and with frequencies that don't match my calculations at all. Also, It doesn't change smoothly, the frequency goes from 159Hz to let's say 180Hz only at one particular point on the potentiometer, just like if all the rest of it was useless. I decided to monitor all my values with Serial and everything was good, the values were OK and nothing was wrong. Then I decided to change all my variables to floats so I could maybe get more precision... Didn't work as well. So now I'm kind of desesperate.

    //MANUAL MODE TEST WITH MICROS()
    //VARIABLES ASSIGNEMENT
    unsigned long current=0.0;
    unsigned long previous=0.0;

    float TimeOn = 0.0;
    float TimeOff = 0.0;
    float manuelF = 0.0;
    float sensor = 0.0;

    int pin = 11;

    byte state = LOW;

    //SETUP AND PIN ASSIGNEMENT
    void setup() {
      pinMode(9, OUTPUT);//MUSIC SIGNAL OUTPUT
      pinMode(11, OUTPUT);//MANUAL SIGNAL OUTPUT
      pinMode(A5, INPUT);//POTENTIOMETER MANUAL
      pinMode(A6, INPUT);//POTENTIOMETER MUSIC
      Serial.begin(9600);
    }

    void loop() {

      sensor = analogRead(A5);
      manuelF=((sensor+10.0)/10.0); //Capture la fréquence sur A5
      TimeOn=1000000.0*(0.2*(1.0/manuelF));
      TimeOff=1000000.0*(0.8*(1.0/manuelF));
      current = micros();

      Serial.println(TimeOn);

      //Serial.print("A5 read:");
      //Serial.println(analogRead(A5),8);
      //Serial.println("-----------");
      //Serial.print("Fréquence: ");
      //Serial.println(manuelF,8);
      //Serial.print("timeon:");
      //Serial.println(TimeOn,8);
      //Serial.print("timeoff:");
      //Serial.println(TimeOff,8);

      if ((state == LOW)&&(current - previous >= TimeOff)){
          state = HIGH;
          digitalWrite(pin,state);
          previous = current;
        }
      else{
        if (current - previous >= TimeOn){
          state = LOW;
          digitalWrite(pin,state);
          previous =current;
        }

      }
     }

As you can see I'm still monitoring the TimeOn variable. Well, It shows exactly (to 4 micro seconds precise) the time that it is supposed to be ON.

My output at that moment is a 50% duty cycle with a frequency of 53Hz when I pass the 7k on the potentiometer (it is a 10k). Before that, it doesn't even outputs a signal.

What is going on?

EDIT#1:
I have done the modifications that @Edgar Bonet suggested me. It partially worked. What i'm left with now is a PWM that can go from 1Hz to 5Hz almost smoothly with the duty cycle at 20% for 1Hz and going up to 22% at 5Hz. After that I only get very discrete frequencies: 7.99Hz, 9.55Hz, 10.66Hz, 11.99Hz, 13.70Hz, 19.18Hz, 21.32Hz, 26.65Hz, 35.54Hz and then it takes almost half a turn before it changes to 53.3Hz until the end. The duty cycle at 35Hz is 33.3% and it reaches 50% at 53.3Hz... What logic is that....

title: Cannot create a PWM with 20% duty cycle using micro() timer

Answers: 2

body:
You wrote:

<!-- language-all: lang-c++ -->

    if ((state == LOW)&&(current - previous >= TimeOff)){
        state = HIGH;
        digitalWrite(pin,state);
        previous = current;
      }
    else{
      if (current - previous >= TimeOn){
        state = LOW;
        digitalWrite(pin,state);
        previous =current;
      }

While you probably mean:

    if (state == LOW && current - previous >= TimeOff) {
        state = HIGH;
        digitalWrite(pin, state);
        previous = current;
    }
    else if (state == HIGH && current - previous >= TimeOn) {
        state = LOW;
        digitalWrite(pin, state);
        previous =current;
    }

body:
I have found the problem. Part of it was the code, thank you @Edgar Bonet. The other part was the pin I was using to generate the PWM signal. Throughout my reasearch, I found that on the arduino nano, the timer pins are the same than those on the arduino Uno. Thus:

Timer0 :pins 5-6

Timer1 :pins 9-10

Timer2 :pins 3-11

Since I was using the function micros() which uses the timer0, I had to send the signal to the right pin. I cannot describe why it did send a certain PWM to discrete frequencies, but the important is that it now works.

In parallel, because the other part of my program is using timer1, the two data transmission won't interfere with each other!

Time inversted in researches: 4hours

Hope this helps someone! Thanks.


body:
I have a standard 16x2 LCD screen and I have it hooked up to my Arduino UNO via a I2C backpack (4-bit mode).

Since I want to learn about the lcd at a lower level I’ve decided not to use the LCD library and instead use the Wire library.

I have writing to the LCD working fine so now I want to understand how to read from it. I thought trying to read the busy flag was a good start.  (I currently delay() after to the LCD which seems to be the most popular solution).

According to the LCD documentation it requires that the RS bit be set to 0 and RW bit to 1. I have a attached the code below.  For some reason it always reads 0x2.

I also read the busy flag right after writing to the screen and it always screws up every other letter.  E.g. if I write 'k' twice to the screen, the first 'k' shows up fine, but the second time it becomes a 'f'.  I am suspecting writing to the LCD before reading is screwing up the data processing.  If I don't attempt to read the flag, all the characters show up correctly.

Here is the code.  Any help would be appreciated.  Thank you!

    #define ENABLE (1 << 2)
    #define BACKLIGHT (1 << 3)

    #define READ (1 << 1)

    byte readReq = BACKLIGHT | ENABLE | READ;
    Wire.beginTransmission(0x3F);
    Wire.write(readReq);
    Wire.write(readReq & ~ENABLE);// write 1st nibble
    Wire.write(readReq);
    Wire.write(readReq & ~ENABLE); //write 2nd nibble

    Wire.endTransmission();

    Wire.requestFrom(0x3F, 2);

    while (Wire.available() < 2) {}

    byte firstNibble = Wire.read(); //always reads 0x2
    byte secondNibble = Wire.read(); //always reads 0x2
    Serial.println(firstNibble, HEX);
    Serial.println(secondNibble, HEX);

title: How to read the busy flag on LCD?

Answers: 0


body:
This is my first project other than some of the starter projects. I am trying to flash the firmware onto an ESP8266 wifi module using and arduino uno. It would be nice to know if anything is wrong/redundant in the picture below (I was looking at a few different diagrams to try and figure out what was right). I have found some tutorials saying that TX should go to RX instead of TX to TX so that is what I am doing. I am trying to use the level shifter to go from 5v to 3.3v because I wasn't sure if I had enough current going to the ESP8266 when just directly hooked up to 3.3v on arduino (I read in a few places that the arduino doesn't have a strong enough current to operate the wifi module). I found some tutorials which use a voltage regulator, I tried doing that but had the same results I am getting now. I have also read that you don't need a level shifter or voltage regulator but it might harm the components so I haven't tried that way yet.

I am the point where I plug it into my computer via USB, open the Arduino IDE > Tools > Serial Monitor.

I type the command 'AT' and there is no response - I tried every baud setting. Sometimes it randomly outputs a question mark or two.

Other things of note: When I plug it in, the ESP8266 blue light flashes once. When I was modding the header pins of the ESP8266 I kind of fumbled it a lot - could that have broken some aspect of the chip? Also while modding the header pins, I pushed them all in to make them longer and bent them on the other side, so it would work with the breadboard - I'm wondering if the soldering connections need to be stronger (you can kind of see in the picture).

[![enter image description here][2]][2]

This is the schematic for what I was trying to achieve basically, while also using the level shifter:

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

Any advice with regards to anything you see here would be great, I am new to the world of circuits.

Note: there is a ground wire that is not in the frame of the picture connecting one side of the breadboard to the other, that part of this is one thing I was wondering about.

  [1]: https://i.stack.imgur.com/Dbeyn.jpg
  [2]: https://i.stack.imgur.com/bOvxB.jpg

title: Trying to flash ESP8266 with Arduino UNO

Answers: 3

body:
You do not need the level shifter. The input pins of the ESP8266 contain over-voltage (though not over-current) protection. All you need to do is limit the current that can flow through the over-voltage protection circuit, and all that needs is a series resistor in the region of 100Ω or so.

And the Arduino already has that protection between the ATMega16U2 and the TX/RX pins anyway in the form of 100Ω resistors that it uses to prevent short circuits between the two MCUs on the board, so you don't need to add it in this instance (you do if you want to communicate between the ATMega328P and the ESP8266, but only between the Arduino's TX and the ESP8266's RX pins).

When it comes to actively running the ESP8266 it can be beneficial to power it from a more powerful 3.3V regulator than the 150mA one on the Arduino since when transmitting the ESP8266 wants more than that, but for simple flashing of it the Arduino's 150mA regulator should do the job fine.

One thing to note though: I don't like the look of the soldering on your ESP8266 pins. I would be inclined to re-solder those joints. Add a bit of flux to help the solder flow properly.

body:
What I have done was connecting ESP8266 and UNO as the schematic described.

But instead of using the default program in ESP8266, I programmed ESP8266 via UNO using the ESP8266 Library on Arduino IDE

If your way still did not work you can maybe try this method.

body:
I think I may be able to help clarify things a bit here:

You are not trying to "flash" the ESP01 (the kind you have) board, but you are trying to talk to the AT command firmware it came installed with.

Also, there's a sort of pingback sketch (I forget the name and can't find it, but it basically uses a SoftwareSerial and copies characters from one to the other and vice versa) that is used to configure the ESP01 that's *normally* used, but you don't seem to be using it here (it may not be worth the effort, either, since it's tricky to get working sometimes).

In this case, it seems that you are trying to do one of two things:

If you are trying to talk to the ESP01 module **from the computer** connect the TX to the TX pin and the RX to the RX pin. This is because the Arduino board's serial adapter is *already* connected in the mirrored direction, and you are using that to talk to the ESP01. Do note that you should, **before** connecting the ESP01, upload the Blink sketch or similar to the Arduino so that it's not trying to use the Serial connection too.
See http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/ for more information on that use case.

On the other hand, if you are trying to talk to the device from the Arduino itself (as in, the Arduino has a program that needs WiFi access), you'd want to connect it RX to TX and TX to RX. Of course, when doing this, the Arduino should already have its program uploaded since the ESP01 would cause issues uploading firmware via Serial afterward (they both talk at once).

Lastly, these things are REALLY finicky, so make sure you set the baud rate and use NLCR end-of-line signaling.


body:
In the past few months I have successfully logged the data from the power and gas meter in my house to a remote web server.

Now I try to add the ability to enable and disable my doorbell over the internet.

Although it seems to work, I experience 2 problems.

**Problems**

 - Arduino freezes after a few hours

 - When the meter reading is transmitted, the doorbell can not be
   switched.

**Questions**
> *Is there a way to give priority to control the doorbell?*

and ..

> *is there a way to find out why the Arduino freezes after a while?*

**Setup:**

 - Arduino Mega 2560 board
 - Ethernet shield
 - LCD display
 - Relay
 - light sensor(for backlight control)
 - serial connection to smart power/gas meter

    //V1.1: Cleaned up messy code
    #include <LiquidCrystal_I2C.h>
    #include <Wire.h>  // Comes with Arduino IDE
    LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
    #include <AltSoftSerial.h>
    #include <SPI.h>
    #include <Ethernet.h>

    //setup ethernet server
    byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; //assign arduino mac address
    byte ip[] = { 192, 168,  178, 95}; // ip in lan assigned to arduino
    byte gateway[] = { 192,  168, 178,  1}; // internet access via router
    byte subnet[] = {  255,  255,  255,  0}; //subnet mask
    EthernetServer server(84); //server port arduino server will use
    char thingSpeakAddress[] = "";
    IPAddress myDns(8, 8, 8, 8);
    EthernetClient client;
    String writeAPIKey = "XXXMX2WYYR0EVZZZ";
    String tsData = "hello"; //dummy data
    String readString; //used by server to capture POST request
    const int updateThingSpeakInterval = 20 * 1000; // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
    // Variable Setup
    long lastConnectionTime = 0;
    boolean lastConnected = false;
    int failedCounter = 0;
    unsigned long int updateCounter = 0; //set refresh counter to 0
    //////////////////////
    //slimme meter////////
    /////////////////////
    char c;
    AltSoftSerial altSerial;
    const int requestPin = 48; //data pin connected to smartmeter
    char input; // incoming serial data (byte)
    bool readnextLine = false;
    #define BUFSIZE 75
    char buffer[BUFSIZE]; //Buffer for serial data to find \n .
    int bufpos = 0;
    long mEVLT = 0; //Meter reading Electrics - consumption low tariff
    long mEVHT = 0; //Meter reading Electrics - consumption low tariff
    long mEAV = 0; //Meter reading Electrics - Actual consumption
    long mG = 0; //Meter reading Gas
    //unsigned long lastConnectionTime = 0;             // last time you connected to the server, in milliseconds
    const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
    // the "L" is needed to use long type numbers

    //const unsigned long postingInterval = 10 L * 1000 L; // delay between updates, in milliseconds, the "L" is needed to use long type numbers
    /////////////////////////////////////////
    //photcel////////controls lcd backlight//
    ////////////////////////////////////////
    int photocellPin = 5; // the cell and 10K pulldown are connected to a0
    int photocellReading; // the analog reading from the analog resistor divider
    //boolean doorbell = true;

    int creset = 43; //Telling arduino that you are connecting pin 43 with reset

    //////////
    //setup///
    //////////
    void setup() {
      Wire.begin();
      digitalWrite(22, LOW);
      digitalWrite(creset, HIGH);
      pinMode(creset, OUTPUT);
      pinMode(22, OUTPUT); //pin selected to control
      pinMode(6, OUTPUT); //pin selected to control
      pinMode(7, OUTPUT); //pin selected to control
      pinMode(8, OUTPUT); //pin selected to control
      //pinMode(5, OUTPUT); //pin 5 selected to control
      Ethernet.begin(mac, ip, myDns, gateway, subnet);
      server.begin();
      Serial.begin(9600);
      altSerial.begin(9600);
      Serial.println(F("Smarthome controller")); // keep track of what is loaded
      Serial.println(F("Send a g in serial monitor to test client")); // what to do to test client
      lcd.begin(20, 4); // initialize the lcd for 16 chars 2 lines, turn on backlight
      // sensorValue = analogRead(sensorPin);
      lcd.backlight(); // finish with backlight on
      //-------- Write characters on the display ------------------
      // NOTE: Cursor Position: Lines and Characters start at 0
      lcd.setCursor(0, 0); //Start at character 4 on line 0
      lcd.print("Smarthome controller");
      delay(1000);
      lcd.setCursor(0, 1);
      lcd.print("powerd by arduino");
      delay(1000);
      lcd.print("                  ");
      lcd.setCursor(0, 2);
      lcd.print("");
      lcd.setCursor(0, 3);
      delay(1000);
      lcd.print("Slimmemeter:     ");
      //lcd.backlight(); // turn on backlight.
      lcd.setCursor(0, 2);
      lcd.print("Doorbell: onn      ");
    }
    void loop() {
      if (updateCounter > 400) {
        digitalWrite(creset, LOW);  // Reset arduino
      }
      // Update ThingSpeak
      if (!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval)) {
        decodeTelegram();
      }
      // Check if Arduino Ethernet needs to be restarted
      if (failedCounter > 3) {
        startEthernet();
      }
      lastConnected = client.connected();
      EthernetClient client = server.available();
      if (client) {
        while (client.connected()) {
          if (client.available()) {
            char cl = client.read();
            //read char by char HTTP request
            if (readString.length() < 100) {
              //store characters to string
              readString += cl;
              //Serial.print(c);
            }
            //if HTTP request has ended
            if (cl == '\n') {
              ///////////////
              Serial.print(readString); //print to serial monitor for debuging
              //now output HTML data header
              if (readString.indexOf('?') >= 0) { //don't send new page
                client.println("HTTP/1.1 204 Zoomkat");
                client.println();
                client.println();
              } else {
                client.println(F("HTTP/1.1 200 OK")); //send new page on browser request
                client.println(F("Content-Type: text/html"));
                client.println();
                client.println(F(""));
                client.println(F(""));
                client.println(F("<TITLE>Smarthome</TITLE>"));
                client.println(F(""));
                client.println(F(""));
                client.println(F("
Smarthome control page
"));
                // DIY buttons
                client.println(F("Deurbel"));
                client.println(F("ON"));
                client.println(F("OFF

"));

                client.println(F("Pins"));
                client.println(F(" ALL ON"));
                client.println(F(" ALL OFF"));
                client.println(F(""));
                client.println(F(""));
                client.println(F(""));
                client.println(F(""));
              }
              delay(1);
              //stopping client
              client.stop();
              if (readString.indexOf("**secretcode**") > 0) //checks for secretkey
              {
                ///////////////////// control arduino pin
                if (readString.indexOf("on2") > 0) //checks for 2
                {
                  digitalWrite(22, LOW); // set pin 5 high
                  //Serial.println(F("Led 5 On"));
                  //Serial.println();
                  lcd.setCursor(0, 2);
                  lcd.print("Doorbell: on      ");
                  //doorbell = true;
                }
                if (readString.indexOf("off3") > 0) //checks for 3
                {
                  digitalWrite(22, HIGH); // set pin 5 low
                  //Serial.println(F("Led 5 Off"));
                  //Serial.println();
                  lcd.setCursor(0, 2);
                  lcd.print("Doorbell: off      ");
                  //doorbell = false;
                }

                //clearing string for next read
                readString = "";
              }
            }
          }
        }
      }

      //lcd.setCursor(0, 0); //Start at character 4 on line 0
      //lcd.print("SMARTHOME CONTROLLER;.");
      //String analogValue = String(analogRead(A5), DEC);
      photocellReading = analogRead(photocellPin);

      //lcd.setCursor(0, 1);
      //lcd.print(photocellReading);
      if (photocellReading < 800) {
        lcd.backlight(); // turn on backlight.
      } else {
        lcd.noBacklight(); // turn on backlight.
      }

    }

    ////////////////////////////////////////////////////////////////////////////
    //////////////////////////FUNCTIONS/////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////
    void updateThingSpeak(String tsData)
    //void sendGET() //client function to send and receive GET data from external server.
    {
      //lcd.setCursor(0, 2);
      // lcd.print("                   ");
      lcd.setCursor(13, 3);
      lcd.print("verstur");
      // delay(1000);
      if (client.connect(thingSpeakAddress, 80)) {
        client.print("GET /smarthome/log.php?stroomLaag=");
        client.print(mEVLT);
        client.print("&stroomHoog=");
        client.print(mEVHT);
        client.print("&stroomVerbruik=");
        client.print(mEAV);
        client.print("&gasStand=");
        client.print(mG);
        client.println(" HTTP/1.1");
        client.println("Host: .nl");
        client.println("User-Agent: arduino-ethernet");
        client.println("Connection: close");
        client.println();
        lastConnectionTime = millis();
        updateCounter++;
        Serial.print("Connecting to log server...");
        Serial.println(updateCounter);
        //x=x+1; //page upload counter
        // lcd.setCursor(0,3);
        // lcd.print("Data send           ");
        //delay(1000);
        lcd.setCursor(13, 3);
        //lcd.print("                    ");
        lcd.print("ok        ");
        lcd.setCursor(16, 3);
        lcd.print(updateCounter);
        if (client.connected()) {
          Serial.println("Connecting to suscesfull...");
          //Serial.println();
          failedCounter = 0;
        } else {
          failedCounter++;
          Serial.println("Connection to failed (" + String(failedCounter, DEC) + ")");
          Serial.println("connection failed");
          Serial.println();
          lcd.setCursor(13, 3);
          lcd.print("fout");
          lcd.setCursor(16, 3);
          lcd.print(String(failedCounter, DEC));
        }
      } else {
        failedCounter++;
        Serial.println("Connection to ThingSpeak Failed (" + String(failedCounter, DEC) + ")");
        Serial.println();
        lastConnectionTime = millis();
      }
      while (client.connected() && !client.available()) delay(1); //waits for data
      while (client.connected() || client.available()) { //connected or data available
        char cl = client.read(); //gets byte from ethernet buffer
        //readString += c; //places captured byte in readString
        //Serial.print(c); //print raw data
      }
      client.stop(); //stop client
      readString = ""; //clear readString variable
    }

    ////////////////////////////////////////////////////

    void startEthernet() {
      client.stop();
      Serial.println("Connecting Arduino to network...");
      Serial.println();
      delay(1000);
      // Connect to network amd obtain an IP address using DHCP
      if (Ethernet.begin(mac) == 0) {
        Serial.println("DHCP Failed, reset Arduino to try again");
        Serial.println();
      } else {
        Ethernet.begin(mac, ip, gateway, gateway, subnet);
        server.begin();
        Serial.println("Arduino connected to network using DHCP");
        Serial.println();
      }
      delay(1000);
    }

    ////////////////////////////////////////////////////

    void decodeTelegram() {
      long tl = 0;
      long tld = 0;
      if (altSerial.available()) {
        //input = altSerial.read();
        c = altSerial.read();
        // --- 7 bits instelling ---
        c &= ~(1 << 7);
        char inChar = (char) c;
        //Serial.print(c);
        input = c;
        //Serial.println(input);
        //char inChar = (char)input;
        // Fill buffer up to and including a new line (\n)
        buffer[bufpos] = input & 127;
        bufpos++;
        if (input == '\n') { // We received a new line (data up to \n)
          if (sscanf(buffer, "1-0:1.8.1(%ld.%ld", & tl, & tld) == 2) {
            tl *= 1000;
            tl += tld;
            mEVLT = tl;
          }
          // 1-0:1.8.2 = Elektra verbruik hoog tarief (DSMR v4.0)
          if (sscanf(buffer, "1-0:1.8.2(%ld.%ld", & tl, & tld) == 2) {
            tl *= 1000;
            tl += tld;
            mEVHT = tl;
          }
          // 1-0:1.7.0 = Electricity consumption actual usage (DSMR v4.0)
          if (sscanf(buffer, "1-0:1.7.0(%ld.%ld", & tl, & tld) == 2) {
            mEAV = tl + tld;
          }
          // 0-1:24.2.1 = Gas (DSMR v4.0) on Kaifa MA105 meter
          //if (strncmp(buffer, "0-1:24.2.0", strlen("0-1:24.2.1")) == 0) {
          if (sscanf(strrchr(buffer, '(') + 1, "%d.%d", & tl, & tld) == 2) {
            mG = (tl * 1000) + tld;
          }
          //}
          // Empty buffer again (whole array)
          for (int i = 0; i < 75; i++) {
            buffer[i] = 0;
          }
          bufpos = 0;
        }
        if (input == '!') { //uitroepteken geeft einde van telegram aan, dus we gaan data versturen
          // if (millis() - lastConnectionTime > postingInterval) {
          // httpRequest();
          updateThingSpeak("field1=0");
          // httpRequest();
          mEVLT = 0;
          mEVHT = 0;
          mEAV = 0;
          mG = 0;
          client.stop();
          //}
        } //Einde vraagteken detectie
        //Serial.print(c);
      } //Einde 'if AltSerial.available'
    } //Einde 'decodeTelegram()' functie

title: Stability issue with webserver and smartmeter logging

Answers: 2

body:
Please see some comments that can help you.

Why do you use a software serial port?
This ATmega has 4 real serial ports!

`delay()` is dangerous in the main loop runtime. Try to use it only in setup.

Every time you call a task, be sure you will not stay there forever.
Get out of the task, if something seems to be too long time. Use `millis()` stamp time differences to measure time spent.
Print it if necessary on debug compiler option.
Printing on failure case do not spend MCU time if there are no errors.

body:
<!-- language-all: cpp -->

    buffer[bufpos] = input & 127;
    bufpos++;

Never use a buffer without a length protection.
Flag if max buffer is reached, force to never write after last position.

Like this:

    if ( bufpos > MaxBuff )
    {
        Serial.print("errornumber");
        bufpos = MaxBuff;
        //And force \n to finish errored message
    }


body:
Because I'm still figuring out 'Arduino C' I leave all warnings on.

Recently I got this one:

`narrowing conversion of '(int)(((unsigned char)bx_0) | ((unsigned char)bx_1))' from 'int' to 'const byte...` etc.

...referring to this line:

    const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

...pointing to the `or` symbol.

The code in question (much simplified to recreate this):

    const int latch[2] = {2, 4};

    const byte bx_0 = 1 << latch[0];
    const byte bx_1 = 1 << latch[1];

    const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

(This happens whether I use `byte`, `uint8_t`, or `unsigned char` everywhere.)

Without the `or` operator, no warning. If `bx_0` and `bx_1` are simple bytes, not shifted into existence, no warning. If I do this:

    const byte pinMask[3] = {bx_0, bx_1, (byte)(bx_0 | bx_1)};

...again, no warning.

However, I get no complaints about this:

    const byte notMask = !(bx_1 | bx_0);

...so a further condition is that the problem `or` has to be in an initializer list. Yikes.

I don't get it. There's no way an `or` of two bytes can force widening, so where did the `(int)` cast come from? It apparently has something to do with the `1 << latch[0]` code, but the result of that is still a byte, by definition.

I have a solution -- the `(byte)` cast -- but in the real code it's ugly and feels unnecessary. Everything is already just bytes.

title: What is causing this 'narrowing conversion' warning?

Answers: 1

body:
That warning message arises when a compiler complies with [C/C++ specifications](http://www.iso-9899.info/wiki/The_Standard).

According to ISO/IEC 9899:2011 part 6.5.12.2 (“Bitwise inclusive OR operator”),
>Each of the operands shall have integer type

Thus, in the evaluation of `bx_0 | bx_1` within the statement `const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};`, the operands `bx_0` and `bx_1` are converted to `int` type before being OR'd together.  This produces an `int` result, which then must be narrowed to `byte` before it can be stored in the  `byte` array.

Knowing that the `(byte)` cast is necessary because of C/C++ specifications should convert your view of the cast from “ugly” and “unnecessary” to “necessary” and either “ok” or “oh well”.  :)


body:
I've been working to a project that uses arduino for RFID but when connected to ethernet shield, the RFID seems to not read any card tapped to sensor but the LCD seems to do fine. Here's the code I use from this page: http://www.instructables.com/id/RFID-CARD-READER-WITH-ARDUINORFID-RC522-and-LCD-16/

    #include <EEPROM.h> //Library To read and write PICC's UIDs from/to EEPROM
    #include <SPI.h> //Library  RC522 Module uses SPI protocol
    #include <MFRC522.h> //Library  RC522 Module
    #include <LiquidCrystal.h> //Library  for LCD Display
    #include <Ethernet.h>

    EthernetServer server(80);
    boolean match = false; // initialize card match to false
    boolean programMode = false; // initialize programming mode to false
    int successRead; // Variable integer to keep if we have Successful Read from Reader
    byte storedCard[4]; // Stores an ID read from EEPROM
    byte readCard[4]; // Stores scanned ID read from RFID Module
    byte masterCard[4]; // Stores master card's ID read from EEPROM
    #define SS_PIN 10
    #define RST_PIN 9
    MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2); //Initializing LCD PINS as (RS, EN, D4, D5, D6, D7)

    void setup() {
      Serial.begin(9600); // Initialize serial communications with PC
      lcd.begin(16, 2); //Initializing LCD 16x2
      pinMode(8, OUTPUT); //LED and Buzzer PIN OUT
      SPI.begin(); // MFRC522 Hardware uses SPI protocol
      mfrc522.PCD_Init(); // Initialize MFRC522 Hardware
      mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
      if (EEPROM.read(1) != 1) {
        // Look EEPROM if Master Card defined, EEPROM address 1 holds if defined
        Serial.println("No Admin Card Defined");
        //When no Master Card in Your EEROM (Serial Display)
        Serial.println("Scan A card to Define as Admin Card");
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.println("SET ADMIN CARD   ");
        //When no Master Card in Your EEROM (LCD Display)
        lcd.setCursor(0, 1);
        lcd.println("SCAN A CARD.....");
        //Scan any RFID CARD to set Your Master Card in Your EEROM (LCD Display)
        delay(1500);
        do {
          successRead = getID();
          // sets successRead to 1 when we get read from reader otherwise 0
        }
        while (!successRead);
        //the program will not go further while you not get a successful read
        for (int j = 0; j < 4; j++) {
          // Loop 4 times
          EEPROM.write(2 + j, readCard[j]);
          // Write scanned PICC's UID to EEPROM, start from address 3
        }
        EEPROM.write(1, 1); //Write to EEPROM we defined Master Card.
        Serial.println("Admin Card Defined");
      }
      Serial.println("Administrator Card's UID");
      for (int i = 0; i < 4; i++) { // Read Master Card's UID from EEPROM
        masterCard[i] = EEPROM.read(2 + i); // Write it to masterCard
        Serial.print(masterCard[i], HEX); //Master Card only view in serial
        Serial.println("Waiting PICCs to bo scanned :)");
      }
     //WAITING TO SCAN THE RFID CARDS:
      Serial.println("");
      Serial.println("Waiting cards to bo scanned :)");
      lcd.clear();
      lcd.setCursor(4, 0);
      lcd.println("WAITING     ");
      lcd.setCursor(3, 1);
      lcd.println("FOR CARD...  ");
      delay(1500);
    }

    int getID() {
     // Getting ready for Reading PICCs
      if (! mfrc522.PICC_IsNewCardPresent()) {
        //If a new PICC placed to RFID reader continue
        return 0;
      }
      if (! mfrc522.PICC_ReadCardSerial()) {
        //Since a PICC placed get Serial and continue
        return 0;
      }
     // There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC
     // I think we should assume every PICC as they have 4 byte UID
     // Until we support 7 byte PICCs
      Serial.println("Scanning card's UID....");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("SCANNING");
      lcd.setCursor(0, 1);
      lcd.print("Card's UID.....");
      delay(2000);
      for (int i = 0; i < 4; i++) {
        readCard[i] = mfrc522.uid.uidByte[i];
        Serial.print(readCard[i], HEX);
      }
      Serial.println("");
      mfrc522.PICC_HaltA(); // Stop reading
      return 1;
    }
    boolean isMaster(byte test[]) {
      if (checkTwo(test, masterCard))
        return true;
      else
        return false;
    }

    boolean checkTwo (byte a[], byte b[]) {
      if (a[0] != NULL)
        // Make sure there is something in the array first
        match = true;
        // Assume they match at first
      for (int k = 0; k < 4; k++) {
        // Loop 4 times
        if (a[k] != b[k])
          // IF a != b then set match = false, one fails, all fail
          match = false;
      }
      if (match) {
        // Check to see if if match is still true
        return true;
      } else  {
        return false;
      }
    }
    boolean findID(byte find[]) {
      int count = EEPROM.read(0);
      // Read the first Byte of EEPROM that
      for (int i = 1; i <= count; i++) {
        // Loop once for each EEPROM entry
        readID(i);
        // Read an ID from EEPROM, it is stored in storedCard[4]
        if (checkTwo(find, storedCard)) {
          // Check to see if the storedCard read from EEPROM
          return true;
          break; // Stop looking we found it
        } else {
          // If not, return false
        }
      }
      return false;
    }
    void readID(int number) {
      int start = (number * 4) + 2;
      // Figure out starting position
      for (int i = 0; i < 4; i++) {
        // Loop 4 times to get the 4 Bytes
        storedCard[i] = EEPROM.read(start + i);
        // Assign values read from EEPROM to array
      }
    }
    void deleteID(byte a[]) {
      if (!findID(a)) {
        // Before we delete from the EEPROM, check to see if we have this card!
        failedWrite(); // If not
      } else {
        int num = EEPROM.read(0);
        // Get the numer of used spaces, position 0 stores the number of ID cards
        int slot;
        // Figure out the slot number of the card
        int start;
        // = (num * 4) + 6; // Figure out where the next slot starts
        int looping;
        // The number of times the loop repeats
        int j;
        int count = EEPROM.read(0);
        // Read the first Byte of EEPROM that stores number of cards
        slot = findIDSLOT(a);
        //Figure out the slot number of the card to delete
        start = (slot * 4) + 2;
        looping = ((num - slot) * 4);
        num--; // Decrement the counter by one
        EEPROM.write(0, num); // Write the new count to the counter
        for (j = 0; j < looping; j++) {
          // Loop the card shift times
          EEPROM.write(start + j, EEPROM.read(start + 4 + j));
          // Shift the array values to 4 places earlier in the EEPROM
        }
        for (int k = 0; k < 4; k++) {
          //Shifting loop
          EEPROM.write(start + j + k, 0);
        }
        successDelete();
      }
    }
    //For Failed to add the card:
    void failedWrite() {
      Serial.println("something wrong with Card");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("SOMETHING WRONG");
      lcd.setCursor(0, 1);
      lcd.print("WITH CARD");
      delay(2000);
    }

    //For Sucessfully Deleted:
    void successDelete() {
      Serial.println("Succesfully removed");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("SUCCESFULLY");
      lcd.setCursor(0, 1);
      lcd.print("REMOVED CARD");
      delay(2000);
    }

    int findIDSLOT(byte find[]) {
      int count = EEPROM.read(0);
      // Read the first Byte of EEPROM that
      for (int i = 1; i <= count; i++) {
        // Loop once for each EEPROM entry
        readID(i);
        // Read an ID from EEPROM, it is stored in storedCard[4]
        if (checkTwo(find, storedCard)) {
          // Check to see if the storedCard read from EEPROM
          // is the same as the find[] ID card passed
          return i;
          // The slot number of the card
          break;
          // Stop looking we found it
        }
      }
    }
    //For Sucessfully Added:
    void successWrite() {
      Serial.println("Succesfully added");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("SUCCESFULLY");
      lcd.setCursor(0, 1);
      lcd.print("ADDED");
      delay(2000);
    }

    //For Adding card to EEPROM:
    void writeID(byte a[]) {
      if (!findID(a)) {
        // Before we write to the EEPROM, check to see if we have seen this card before!
        int num = EEPROM.read(0);
        // Get the numer of used spaces, position 0 stores the number of ID cards
        int start = (num * 4) + 6;
        // Figure out where the next slot starts
        num++;
        // Increment the counter by one
        EEPROM.write(0, num);
        // Write the new count to the counter
        for (int j = 0; j < 4; j++) {
          // Loop 4 times
          EEPROM.write(start + j, a[j]);
          // Write the array values to EEPROM in the right position
        }
        successWrite();
      } else {
        failedWrite();
      }
    }
    void loop() {
      lcd.clear();
      lcd.setCursor(4, 0);
      lcd.print("TAP YOUR");
      lcd.setCursor(4, 1);
      lcd.print("CARD HERE");
      do {
        successRead = getID(); // sets successRead to 1 when we get read from     reader otherwise 0
        if (programMode) {
          // Program Mode cycles through RGB waiting to read a new card
        } else {
        }
      }
      while (!successRead);
      //the program will not go further while you not get a successful read
      if (programMode) {
        if (isMaster(readCard)) {
          //If master card scanned again exit program mode
          Serial.println("This is ADMIN Card");
          Serial.println("Exiting ADMIN Mode");
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("EXITING FROM");
          lcd.setCursor(0, 1);
          lcd.print("ADMINISTRATOR MODE");
          delay(2000);
          programMode = false;
          return;
        } else {
          if (findID(readCard)) {
            //If scanned card is known delete it
            Serial.println("I know this CARD, so removing");
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("AVAILABLE!");
            lcd.setCursor(0, 1);
            lcd.print("SO DELETING.....");
            delay(5000);
            deleteID(readCard);
            Serial.println("-----------------------------");
          } else {
            // If scanned card is not known add it
            Serial.println("Adding this card...");
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("Card no:");
            lcd.setCursor(0, 1);
            lcd.print(readCard[0], HEX);
            lcd.print(readCard[1], HEX);
            lcd.print(readCard[2], HEX);
            lcd.print(readCard[3], HEX);
            lcd.print(readCard[4], HEX);
            delay(4000);
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("NOT AVAILABLE");
            lcd.setCursor(0, 1);
            lcd.print("SO ADDING...");
            delay(5000);
            writeID(readCard);
            Serial.println("-----------------------------");
          }
        }
      } else {
        if (isMaster(readCard)) {
          // If scanned card's ID matches Master Card's ID enter program mode
          programMode = true;
          Serial.println("Welcome to Administrator Mode");
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("WELCOME TO");
          lcd.setCursor(0, 1);
          lcd.print("ADMIN MODE");
          delay(3000);
          int count = EEPROM.read(0);
          // Read the first Byte of EEPROM that
          Serial.print("I have ");
          // stores the number of ID's in EEPROM
          Serial.print(count);
          Serial.print(" record(s) on EEPROM");
          Serial.println("");
          Serial.println("Scan a card to ADD or REMOVE");
          Serial.println("-----------------------------");
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("SCAN CARD TO");
          lcd.setCursor(0, 1);
          lcd.print("ADD OR REMOVE...");
          delay(2500);
        } else {
          if (findID(readCard)) {
            // If not, see if the card is in the EEPROM
            Serial.println("Acces Granted");
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("ACCESS GRANTED");
            lcd.setCursor(0, 1);
            lcd.print("YOU MAY ENTER NOW");
            digitalWrite(8, HIGH);
            delay(1500);
            digitalWrite(8, LOW);
            lcd.clear();
          } else {
            // If not, show that the ID was not valid
            Serial.println("Access Denied");
            for (int abcd = 0; abcd < 3; abcd++) {
              lcd.clear();
              lcd.setCursor(0, 0);
              lcd.print("     SORRY");
              lcd.setCursor(0, 1);
              lcd.print("  ACCESS DENIED");
              digitalWrite(8, HIGH);
              delay(1000);
              digitalWrite(8, LOW);
              lcd.clear();
              lcd.print("   YOU'RE NOT  ");
              lcd.setCursor(0, 1);
              lcd.print("   AUTHORIZED   ");
              delay(1000);
            }
            lcd.clear();
          }
        }
      }
    }

Any help would be appreciated!

title: Arduino UNO + Ethernet Shield + LCD + RFID but RFID doesn't work

Answers: 2

body: It may not be possible to use every optional Arduino feature with every other optional Arduino feature. Some features use the same Arduino resources.  If there is actually a hardware contention problem, you need to dive deep into the software drivers and hardware to figure out if there is a possible work around.  But this is hardly the type of effort new developers would take on.  It might be easier for a new developer to use 2 different Arduino's to host the features desired and set up a communication link between them.

body:
I recently made a similar project with a RFID reader and an SD card shield, and I had the same problem.

The explanation why it doesn't work is that some shields that use SPI communication don't really care about your slave select pin being pulled low, and interfere when Arduino is talking to another SPI device via the MISO pin.

 The only way I got it to work is by using a tri-state buffer on the MISO pins of my SPI devices. You can find plenty of info about it on the internet, as well as how to use them in your project.

The idea is simple, it works kind of like a transistor. When you pull the enable pin of the buffer to ground using SS pin, you allow the MISO pin of that device to be connected to the corresponding Arduino input. Otherwise, the MISO pin will be on a state of high impedance and would not interfere on the communication anymore.

Good luck with your project.


body:
I downloaded `arduino-1.8.4-linux32.tar.xz` and ran `install.sh` as outlined (the very sketchy instructions) in https://www.arduino.cc/en/Guide/Linux

This seemed to work OK, so I removed 354M of what I thought was the installer, only to discover that I had deleted arduino.

The so-called `install.sh` on closer inspection seemed only to create links into the uncompressed download in my home directory.

The whole process seems very un-Linux like; I had assumed that it would be installed in `/usr/share/` like most Linux programs.

I realise I could extract into `/usr/share/` and set permissions for other users, but surely there must be others who have wanted to do the same. The macOS version seems to have a proper installer; does one exist for Linux?

title: Installing Arduino IDE on Linux

Answers: 3

body:
The problem here is that there are multiple flavours of linux each with their own installation and package management systems - Aptitude, Yum, EMerge, etc.

It is not easy for Arduino to keep up with creating packages for each and every system, so instead they create a single tarball that can be used on any of the systems.

At one point Arduino (or someone, anyway) used to create Debian packages for the IDE and upload them to the main Debian repository - however this has not been done for many years now and the packages in the Debian repositories are very much out of date (1.0.5 IIRC).

If you, as a system manager, choose to deploy the IDE system wide then it is your task to decide how best to do that.

One option is to just copy the contents of the archive to `/usr/share/arduino` and then run `./install.sh` from within that directory.

body:
I ran the following to Install the latest Arduino IDE on my Raspberry Pi3.
This should work all Pi models. [This release enables you to run the Arduino Software (IDE) on many of the mini PC boards based on ARM6+ processors currently on the market, including Raspberry Pi](https://blog.arduino.cc/2016/05/17/discover-the-latest-arduino-build-for-arm-linux/)

    # Installing Arduino IDE
    cd /usr/share/
    sudo tar xf /home/pi/arduino-1.8.9-linuxarm.tar.xz
    sudo chown root:root -R /usr/share/arduino-1.8.9/

    # Adding desktop shortcut, menu item and file associations for Arduino IDE
    # Each user needs to repeate this
    cd
    /usr/share/arduino-1.8.9/install.sh

There is a similar instruction in [MagPi61](https://www.raspberrypi.org/magpi/issues/61/) except they suggest installation in `/opt`

body:
I wrote an installation instruction for the Arduino 2.0.x IDE over at [AskUbuntu](https://askubuntu.com/q/1461941/51957).

I chose to install the files in the `/opt` directory, but opinions differ on that topic. The instruction also elaborates on adding desktop links and an icon for Ubuntu flavors.


body:
I have been using two nRF24L01 to communicate with each other using a simple Arduino Uno Board. It worked for 5 days and now all of a sudden it is now working. I tried to change the modules and the Arduino boards too, but even if trying a simple example the communication between them is not happening.

I googled everything and tried every option, it is not working.

I used `printDetails()` to check the config of the modules. It shows everything is ok but I am not able to understand if the transmitter or the receiver is the problem. Please guide me to solve this problem. Also how to make sure if both are working (any debugging technique)?

I have been trying it for 9 days now, and I badly want it to work.

The code I am using is very simple code. It doesn't have any errors.

Receiver code:

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    RF24 radio(7, 8); // CNS, CE
    String response;
    boolean done = false;

    void setup() {
      delay(500);
      Serial.begin(9600);
      radio.begin();
      radio.setPALevel(RF24_PA_MIN);
      radio.openReadingPipe(0,0xF0F0F0F0AA);
      radio.startListening();
    }

    void loop() {
      if (radio.available()) {
        radio.read(&response, sizeof(response));
        done = true;
      }
      if (done) {
        Serial.println(response);
      }
      done = false;
      delay(1000);
    }

Sender code:

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    RF24 radio(7, 8); // CNS, CE
    String request;

    void setup() {
      delay(500);
      Serial.begin(9600);
      radio.begin();
      radio.openWritingPipe(0xF0F0F0F0AA);
      radio.setPALevel(RF24_PA_MIN);
      radio.stopListening();
    }

    void loop() {
      while (Serial.available() > 0) {
        request = Serial.readString();
        Serial.println(request);
        radio.write(&request, sizeof(request));
        delay(1000);
      }
    }

title: nRF24L01 not communicating

Answers: 2

body:
Hello,

You need to set a channel to both NRF:

    void setup() {
       delay(500);
       Serial.begin(9600);
       radio.begin();
       radio.setChannel(0x55); //set the channel
       radio.openWritingPipe(0xF0F0F0F0AA);
       radio.setPALevel(RF24_PA_MIN);
       radio.stopListening();
       radio.powerUp(); //Power up the radio
    }

Change this.

    void loop() {
        if (radio.available()) {
            radio.read(&response, sizeof(response));
            done = true;
        }
        if (done) {
            Serial.println(response);
            done = false;
        }
        //done = false;
        delay(1000);
    }

body: Maybe you should check your power supply. If it worked for 5 days, then it should be ok with your boards and module. If it don't work anymore it could be broken board, broken module or power supply.


body:
I bought an Arduino Mini and also an Arduino USB 2 Serial Converter.
While trying to program the Arduino Mini, I get this error:

    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00

After doing some research I tried many things like changing the settings, serial port, made sure I'm using the right Arduino etcetera.

Some points to consider:

 - I tried burning the bootloader using my Arduino Uno.
 - Uploading sketches to the Arduino Mini using my Arduino Uno works (so problem is not directly with the Mini).
 - I *am* pressing the Reset button before uploading. I also tried hooking a capacitor and the Reset wire directly. No change.

The wiring (I also tried connecting TX of Mini to RX of serial converter, and vice versa):

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

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

title: Can't upload to Arduino Mini via Arduino USB 2 Serial Converter

Answers: 1

body: The Arduino USB 2 Serial converter was defect (even though brand new). I bought a cheaper (7 Euro) FTDI to USB and I can now upload.


body:
I have an Arduino Uno device that uses the following modules:

 - 16 PIN LED w/ Backlight
 - RFID - RC522 (RFID Reader)
 - HR911105A (LAN Module - HanRun)

These three modules use every digital pin available in the Uno (2-13) and
it works correctly. The problem is that I want to add a relay to this board. I am new to Arduino so I use tutorials and right now I do not fully understand how this works. So I have connected the `IN` pin of the relay to Uno pin 8 and the `NO` pin of the relay to Uno pin 13.

The problem is that when I don't use other modules the relay works correctly (using this code).

    int relay_pin = 8;
    int led_pin = 13;

    void setup() {
      pinMode(relay_pin,OUTPUT);
      pinMode(led_pin,OUTPUT);
      digitalWrite(led_pin,HIGH);
    }

    void loop() {
      digitalWrite(relay_pin,HIGH);
      delay(5000);
      digitalWrite(relay_pin,LOW);
      delay(5000);
    }

The remaining ports are 1 and 0, which I assume are TX/RX, and can't be used for relay (am I wrong?).

So obviously I should not be using those pins but I wonder which pins I am allowed to use simultaneously when using two or three modules at the same time.

Does it depend on the modules or are there some instructions?

title: Arduino Uno - Multiple modules for HDMI switch device

Answers: 1

body:
The relay wiring diagram you are following is just plain bizarre and the strangest one I have ever seen.

Ignore it. It is completely incorrect.

You only need one pin to control a relay, so disconnect it from pin 13.

The switched side can connect to anywhere where you would normally use a switch - such as to switch power to an LED *connected between +5V and GND with a suitable current limiting resistor*.

You can use any available pin to control the relay, and that includes pins 0 or 1 *if you aren't using serial communication*.  Note that with the relay connected to one of those pins it will most likely activate and buzz while you upload a sketch - best to disconnect it at that point and reconnect it afterwards.

----

Devices like relays and LEDs need their own dedicated pin. They can't be shared with other functions or each other.

The only devices that can share pins are devices which connect to a *bus*, such as SPI or I2C.


body:
I have Simcom **SIM900a** GSM *(SIM900a Mini DEV Board v3.9.2)* and I am interfacing it with **Arduino UNO**.
I have no idea how to connect SIM900a to Arduino UNO.

What I did now is:
[![SIM900a; My reference image][1]][1]

I connect the following Pin from above image to:

**5** to: `GND (Digital GND near Pin 13)`

**6** to: `5V of Arduino`

**2** to: `GND of Arduino near 5V`

**3** to: `Digital Pin 0 of Arduino (RX)`

**4** to: `Digital Pin 1 of Arduino (TX)`

**1** to: (No idea)

From Picture option **7**, **8**, **9** are not connected to anything.

Can you please guide me am I doing right?

I am getting hard time to find out what is `TX` and `RX` in my SIM900a module as it is not written there.

My SIM900a looks like [**this**][2], [**this**][3]*(Schematics given)* and [this][4].

When I upload the sketch:

**File > Examples > GSM > TestModem:**

to Arduino, I got this output from **Serial Monitor**:

> Starting modem test...ERROR, no modem answer.
>
> Checking IMEI...Modem's IMEI: 0
>
> Reseting Modem... Modem is functioning properly: IMEI: 0

**PS:**

I saw this schematic [here][5] which is way different than what I am doing.

**PSS:**

Hints, am I supposed to provide external power supply of `5 V` `2 A` OR do I need some kind of converters `(TTL to RS232 converter)` ?

  [1]: https://i.stack.imgur.com/vYUn8.png
  [2]: http://www.arduinopak.com/Prd_Detail.aspx?Prd_ID=19993
  [3]: http://upsats.com/Content/Product/img/Product/Large/SIM900V4-G36-37C.jpg
  [4]: http://www.electrodragon.com/product/sim900a-mini-dev-board/
  [5]: http://www.instructables.com/id/Using-a-SIM900A-GSMGPRS-module-in-Australia/

title: SIM900a Mini Modem, IMEI 0, help with TX RX pins

Answers: 2

body:
Your wiring is correct:

    6 - VDC (+5V)
    5 - GND
    4 - RX (connect to Arduino TX - pin 1 for UNO)
    3 - TX (connect to Arduino RX - pin 0 for UNO)

5VDC/2A power supply is must, otherwise module will be resetting when wireless radio is turned on. When using separate power supply, don't forget to connect Arduino GND and module GND.

The RX/TX on the module are depicted as 5VR/5VT (and 3VR/3VT for 3.3V pins).

The better way to get started / debug would be to use USB-to-serial converter: set the baudrate as 115200, connect and type AT and enter. Shall respond with AT (echo) and OK.

PS: The red wire (6) shall be on the left and black (5) on the right side, according to the board connector.

body:
Finally I found solution to this problem:

My Pins connections were wrong, it should not be: `0` and `1` it should be `2` & `3`:

    2 - RX Arduino
    3 - TX Arduino

also `SoftwareSerial.h` is not working with `SIM900A`

**Pins:**

All connections should be like this:

    SIM900A - Arduino
    =================
    VCC     - VDC (+5V)
    GND     - GND
    5VR     - Connect to Arduino TX (Pin 3)
    5VT     - Connect to Arduino RX (Pin 2)

As discussed [here](https://arduino.stackexchange.com/a/35717/26037).

**Very important:**

Any program with header/library: `#include <SoftwareSerial.h>` is not working but `#include <GSM.h>` is working fine. As `SoftwareSerial.h` only work with `GSM Shield` and `SIM900A` isn't a shield.

**Program/Sketch to Upload:**

    /*
    SMS sender

    created 25 Feb 2012
    Originally written by Tom Igoe
    But this is modified version
    */

    // Include the GSM library
    #include <GSM.h>

    #define PINNUMBER ""

    // initialize the library instance
    GSM gsmAccess;
    GSM_SMS sms;

    void setup(){
    // initialize serial communications and wait for port to open:
    Serial.begin(9600);
    while (!Serial){
    ; // wait for serial port to connect. Needed for Leonardo only
    }
    Serial.println("SMS Messages Sender");
    // connection state
    boolean notConnected = true;

    // Start SIM900A GSM

    while (notConnected){
        Serial.println("Status 1: Please wait a while, If it taking lot of time, \nmeans you have wrong pin connections.");
        // If your SIM has PIN, pass it as a parameter of begin() in quotes
        if (gsmAccess.begin(PINNUMBER) == GSM_READY){
        Serial.println("Status 2: GSM is ready.");
        notConnected = false;
    }else{
        Serial.println("Status 3: Not connected");
        delay(1000);
      }
    }
        Serial.println("Status 4: GSM initialized. " );

        // calling function to send message
        sendMessage();
    }

    void loop(){
        // empty loop
    }

    // method to send message to specific number just once.
    void sendMessage(){
        Serial.print("Message is sending...: ");
        // send the message
        sms.beginSMS("03XXXXXXX "); // Replace XXXXXXX with your mobile number.
        sms.print("This is just some message"); // Message content, replace with your's.
        sms.endSMS();
        Serial.println("COMPLETE!\n");
        Serial.println("Message Sent...!\n");
    }

**Bam**, It is working, and it successfully can send message.

**Things to remember:**

 1. As everywhere being said you need to supply external power supply to SIM900A   it requires `5 Volts` and `2 Amphs`.

 2. Connect `GND` of SIM900A to Arduino `GND`.

 3. Connect `VCC+` *(above photo connection 2)* to `5V` pin of Arduino.

**One Problem:**
When I upload sketch of:

> Example > GSM > TestModem:

to Arduino, I got this output from **Serial Monitor**:

> Starting modem test...ERROR, no modem answer.
>
> Checking IMEI...Modem's IMEI: 0
>
> Reseting Modem... Modem is functioning properly: IMEI: 0

I cannot get IMEI from SIM900A but I can send message.


body:
I am using Arduino Micro. Is there any way to use PWM on pin 4 instead of Pin3 ?

I tried to change pins_Arduino.h but didnt worked.

    //#define digitalPinHasPWM(p)         ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 13)

    #define digitalPinHasPWM(p)         ((p) == 4 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 13)

and

    const uint8_t PROGMEM digital_pin_to_timer_PGM[] = {
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     ////////////////////////modified///////////////
     //TIMER0B,  /* 3 */
     //NOT_ON_TIMER,
     NOT_ON_TIMER,
     TIMER0B,  /* 4 */
     ////////////////////////////////////////////////////
     TIMER3A,  /* 5 */
     TIMER4D,  /* 6 */
     NOT_ON_TIMER,

     NOT_ON_TIMER,
     TIMER1A,  /* 9 */
     TIMER1B,  /* 10 */
     TIMER0A,  /* 11 */

     NOT_ON_TIMER,
     TIMER4A,  /* 13 */

     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,

     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
    };

title: PWM on Pin 4 - arduino Micro

Answers: 1

body: You cannot. There is no PWM on that pin. PWM is generated by hardware. The hardware simply does not exist.


body:
I want to drive a servo via a HCO6 and HC05 link as a stand alone, using no android or PC.
The question is how to send a 1.5 ms signal (generated with a pulse command on a Nano) from one HC to another HC (to which my servo will be connected) ?
I do not need to care about passwords in my linking. No text to be sent, just the 1ms to 2 ms signal, at a refresh rate of 50 Hz.
I will use the HC with a OOK modulation (on - off on the data pin)?
How to achieve this ?
Thanks !

title: Connecting a servo via HC05 and HC06

Answers: 1

body:
You cannot. You will need an Arduino at the servo end to generate the PWM signal from serial instructions sent over Bluetooth.

Since PWM is (typically) 8-bit and serial is (typically) 8-bit you could simply have each byte as a 1:1 mapping to a PWM value.

One the transmit end:

    bluetoothSerial.write(pwmValue);

On the receive end:

    if (bluetoothSerial.available()) {
        analogWrite(9, bluetoothSerial.read());
    }


body:
Hello Good Day to Everyone.
I have a project where I need to send DHT11 sensor data to a Firebase database using both Arduino UNO and Esp8266 esp-01 wifi module. Both of them must work together to send the data.

[![Connection][1]][1]

  [1]: https://i.stack.imgur.com/naxqL.jpg

Arduino Code:

    #include <dht.h>

    dht DHT;

    #define DHT11_PIN 7

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

    }

    void loop() {
     // put your main code here, to run repeatedly:
    int chk = DHT.read11(DHT11_PIN);
    Serial.print("Temperature = ");
    Serial.println(DHT.temperature);
    Serial.print("Humidity = ");
    Serial.println(DHT.humidity);
    delay(1000);

    }

My arduino code is working fine. Now comes the part where I need to program the ESP8266 which I am really confused how to pass the data to the wifi module and send it to firebase. I tried to code some and this is my

ESP8266 Code:

    #include <ESP8266WiFi.h>
    #include <FirebaseArduino.h>
    #include <DHT.h>

    #define FIREBASE_HOST "test.firebaseio.com"
    #define FIREBASE_AUTH "authcode"

    #define WIFI_SSID "mywifi"
    #define WIFI_PASSWORD "12345"

    #define DHTTYPE DHT11
    #define DHTPIN  7

    DHT dht(DHTPIN, DHTTYPE);
    float temp_f;
    unsigned long previousMillis = 0;
    const long interval = 2300;

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

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print("connecting");
    while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
    }
     Serial.println();
     Serial.print("connected: ");
     Serial.println(WiFi.localIP());

    Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

     }

    void loop() {
    delay(2000);
    float h = dht.readHumidity();
    float t = dht.readTemperature();
    delay(50);
    Firebase.setFloat("temp",t);
    Firebase.setFloat("hum",h);
    delay(1000);
    }

I don't want my esp8266 to go stand alone. I wanted the data to come from the arduino but somehow I don't know how to receive the data from the arduino in the esp8266.

I hope someone can enlighten me..
thank you

title: DHT11 data in Arduino UNO to Firebase through ESP8266

Answers: 1

body:
First of all, FirebaseArduino.h library is for ESP8266 itself and not for Arduino UNO.
The code you have written will not work as you are giving instructions like `Firebase.setFloat("temp",t);` to UNO. It will not compile.
What you should do is set ESP8266-01 as your primary board and let the UNO transmit the data by software serial.
ESP8266-01 will capture that data and transmit it over the Internet.
YOU CAN'T USE FirebaseArduino.h FOR ARDUINO UNO! It is for the ESP8266.
All YouTube videos will show you how to code for NodeMCU esp8266-12E. Do that for ESP-01 and communicate with Arduino for data (converting data calculated to string will help to reduce problems). Get data in form of string from UNO and transmit it using ESP-01!

If you want I can share all video list that I found useful!


body:
[![  these is my shield     ][1]][1]

  [1]: https://i.stack.imgur.com/Tjy8F.jpg

The logical communication(rx & tx) between the shield and Arduino Uno doesn't  work. Arduino (rx & tx) supply  is 0 & 5 V but this is 0 & 2.8 V. What am I to do?

title: Problem with Arduino Uno and SIM900 shield logical communication (rx & tx)

Answers: 1

body:
Use a [logic level converter][1].

A logic level converter is a small device that converts between different logic levels, for example between 5V and 3.3V.

I am not affiliated with Sparkfun, I just think they are the most informative source.

  [1]: https://learn.sparkfun.com/tutorials/using-the-logic-level-converter


body:
First Post.

I'm using a NodeMCU esp8266 connected to a digital vibration sensor. My project is to detect when a pager vibrates to then trigger through the maker channel of ifttt an outcome.

I'm following this project as my base, hoping to adapt it ever so slightly, but the more I adapt the code the less it seems to work. https://blog.erindachtler.me/tutorial-a-wifi-enabled-washing-machine/
<!-- language-all: lang-cpp -->

    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>

    #define WIFI_SSID "wifissid"
    #define WIFI_KEY "wifikey"

    #define NOTIFY_URL
    "https://maker.ifttt.com/trigger/myproject/with/key/mykey"

    int vibration = 16; //vibration sensor
    int LedPin =4; //built in led
    int numberofshouts = 0;
    int vibrationstate = 0;
    int lastvibrationstate = 0;

    void setup() {
    pinMode(vibration, INPUT);
    pinMode(LedPin, OUTPUT);
    Serial.begin(9600);

    // Connect to WiFi network
    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(WIFI_SSID);

    WiFi.begin(WIFI_SSID, WIFI_KEY);

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

    // Start the server
    Serial.println("Server started");

    // Print the IP address
    Serial.println(WiFi.localIP());

    }

    void loop() {
    // put your main code here, to run repeatedly:
    int vibrationvalue = digitalRead(vibration);

    if (vibrationvalue == HIGH)  {
      Serial.print("Vibration");
      sendDoneNotification();
    }

    else {
    digitalWrite(LedPin, LOW);
    }

    }

    void sendDoneNotification() {
    WiFi.begin(WIFI_SSID, WIFI_KEY);

    while((WiFi.status() != WL_CONNECTED)) {
    delay(100);
    }

    HTTPClient http;
    http.begin(NOTIFY_URL);
    int httpCode = http.GET();
    if(httpCode > 0) {
    // HTTP header has been send and Server response header has been handled
    Serial.printf("[HTTP] GET... code: %d\n", httpCode);

    // file found at server
    if(httpCode == HTTP_CODE_OK) {
      String payload = http.getString();
      Serial.println(payload);
    }
    } else {
      Serial.printf("[HTTP] GET... failed, error: %s\n",
    http.errorToString(httpCode).c_str());
    }
    http.end();

     WiFi.disconnect();
     }

What happens is my serial just reports

[HTTP] GET... failed, error: connection refused

I don't quite get the post commands.
I basically want it to read the vibration sensor and while it's reporting no movement do nothing, but after it detects vibration for a couple of seconds it then sends the post command to the maker url that will trigger my ifttt command, thus notifying me on my phone etc.

I have created and run a serial print program to test the sensor and adjust the sensitivity so I know the sensor is working.
My NodeMCU doesn't have a D1 pin so i have it connected to D0, not sure if this is correct or not.

Any tips or advice if there is an easier way of doing this.

Many thanks and have a nice day.

Adrian.

title: Digital Vibration sensor on NodeMCU ESP8266

Answers: 0


body: I have a (HCSR04) ultrasonic distance module connected to arduino , i have connected all the four pins of the module properly and its working fine , then when i pull off the wire which is connected to ground in arduino , the module works totally fine . How the module works without connecting its ground pin to arduino ground ?

title: Ultrasonic distance module works without connecting to gnd

Answers: 1

body:
It's not uncommon for part to "sort of" work when one of the supply rails is missing and an input signal of the some polarity somewhat substitutes for it, often through built-in ESD protection diodes.  In this case, the trigger input when idle is low, and there's probably some capacitance on the board that could hold it through the brief trigger pulse.

It's a bad idea to rely on this though, both as it typically means stressing parts by operating them outside of specified limits, and can also produce not-quite reliable behavior.

For example, I once wired an SPI flash chip on a small carrier stuck underneath an MCU eval board, in order to test some software for a board I was designing.  It worked great.  Or I should say, it did right up until I tried to write to it, which would always fail.  Eventually I discovered that I'd forgotten the ground connection when wiring it up.  It was able to return enough current through the I/Os to perform read operations, but not to support a write.


body:
I am using nRF24L01 with Arduino Nano and Mini. I feel they are very useful when we want to connect multiple Arduinos together.

In market we can buy Arduino with WiFi and Bluetooth, why don't they make Arduino model with nRF24L01? Is there any specific valid reason?

Or am I wrong in using nRF24L01 and there is a better cost and power efficient way to connect multiple Arduinos together wirelessly?

title: Arduino with nRF24L01

Answers: 2

body:
nRF24L01 is a proprietary system, unlike WiFi and Bluetooth. There is only one (official) maker of nRF devices (Nordic Semiconductor).

Yes, they are very nice modules, but why would you spend the time and money developing a generic microcontroller board that has such limited scope as to only be able to communicate with the same board or one with one specific module attached?  You wouldn't - it doesn't make financial sense - especially when it's easy for an end user to add the module to any other board instead.

Bluetooth and WiFi make more financial sense because there is a huge range of devices that they can communicate with which means they can be used for a far greater range of projects thus increasing demand for them.

body:
NordicRF (the company behind nRF24L01) has released two series of SoC devices that are compatible with nRF24: [NRF51][1] and [NRF52][2]. Thanks to the effort by Sandeep Mistry and other contributors, they can be programmed using the Arduino IDE and libraries. Instructions are available here: [https://github.com/sandeepmistry/arduino-nRF5][3]

I have tested NRF51822, which is the cheapest variant (costing slightly more than Arduino Pro Mini + NRF24L01+ but in a single small and power-efficient package) and it works great.

The BBC Micro:bit is based on NRF51. More information is available at https://forum.mysensors.org/topic/9722/bbc-micro-bit-and-mysensors-a-great-match

Compared to the Atmega328-based Arduino Pro Mini, NRF51822 has 8x larger flash and 8x larger RAM. It also has Bluetooth 5 and BLE support and a 32-bit ARM Cortex M0 CPU.

There is also this alternative: https://www.ebid.net/eu/for-sale/arduino-ide-compatible-controller-with-the-nordic-nrf24l01-radio-transceiver-156695123.htm

Specifications:

 - Dimensions 59mm x 18mm
 - The Nordic nRF24L01+ 2.4 GHz Radio transceiver on board
 - Supply voltage up to 6.5 Volts
 - The Digital and Analog pins are 5 volts
 - ATMega328P frequency is 8 Mhz
 - 4 battery connector pins
 - FTDI header for programming
[![enter image description here][4]][4]

Full disclosure: I am member of the MySensors core team. A MySensors user (not affiliated with the core team) created and is selling this board.

  [1]: https://www.nordicsemi.com/Products/nRF51-Series-SoC
  [2]: https://www.nordicsemi.com/Products/nRF52-Series-SoC
  [3]: https://github.com/sandeepmistry/arduino-nRF5
  [4]: https://i.stack.imgur.com/EZXO1.jpg


body:
I tried to download the ATmega16 board in my Arduino. I have set below URL under File->Preference->Additional board manager URL

`https://mcudude.github.io/MightyCore/package_MCUdude_MightyCore_index.json`

I am getting below attach images. How can we resolve this error and install atmega16 board manager?

I am using Arduino version 1.6.9. I don't have any issue in opening MightyCare and Arudino URL from my chrome browser.

[![Error_in_BoardManager][1]][1]

  [1]: https://i.stack.imgur.com/0w920.jpg

title: Set board manager as ATmega16

Answers: 1

body:
Thanks for everyone help here.

I have resolved by few steps.

1) File -> preference -> Board manager URL as like below. Basically URL are seperated by commas.
`http://arduino.esp8266.com/stable/package_esp8266com_index.json,https://mcudude.github.io/MightyCore/package_MCUdude_MightyCore_index.json`

2) Deleted the tmp file (package_index.json.tmp) which is in the path `C:\Users\SIMBU\AppData\Local\Arduino15\`

This helped me to resolve the issue.


body:
I stumbled upon an AT command for the ESP8266 that I really need. The following command is "AT+CWLAP", but I have no idea how to use it. I can't seem to find any resource on how to implement it.

I need the SSID, RSSI, and MAC addresses of the AP and pretty much use those data internally. For example (not necessarily doing this but you get the point), depending on the signal strength, choose the best option and print the SSID of the AP.

Is it even possible?

title: How to use and retrieve data file from AT command in Arduino D1 Mini Wemos (With esp8266)

Answers: 1

body:
The command is documented in the [ESP8266 AT Command Reference][1], with a non-PDF option at [https://room-15.github.io/blog/2015/03/26/esp8266-at-command-reference/#AT+CWLAP][2]

The response from the `AT+CWLAP` is a series of lines listing available access points, and for each, you are given their encryption method, SSID, RSSI, MAC, and the channel (or frequency offset and a calibration value).

It would be up to the you to parse the resulting strings to obtain the APs, sort by signal strength, and decide what to do with that information.

**EDIT:**

Because you are using the Arduino environment/core to write code for the ESP8266, you won't be able to use the AT command set. The AT Commands are available when the ESP8266 has the EspressIF firmware loaded to it, and thus the ESP8266 module is intended to be a peripheral device to some other controller; contrast with your use, where the ESP8266 is the **only** controller, with the WiFi ability baked in.

In this case, you will need to examine the features of the [Arduino ESP8266 core][3], especially the [ESP8266WiFi library][4], which gives an [example sketch for scanning the available WiFi networks][5].

  [1]: https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf
  [2]: https://room-15.github.io/blog/2015/03/26/esp8266-at-command-reference/#AT+CWLAP
  [3]: https://github.com/esp8266/Arduino/tree/master/libraries
  [4]: https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFi
  [5]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino


body:
I wrote an Arduino program that requires two ports for serial communication. I intended to use both hardware serial and software serial, but the problem is receiving data from receiving buffer of the software serial: it always returns zero byte from `myserial.available()`.

For clarity I used the software serial example in Arduino IDE ver. 1.8.4.
I tried to change the baud rate but still the problem persists. I read somewhere that they made some code changes in the SoftwareSerial library's .cpp and .h files. I tried to find the site without success. And my PC where I installed those libraries was stolen. Before that it was working properly.

The mistake I made is that I just copied the code and pasted in the library without concentrating on it. Here is the example of program with two serial ports.

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2, 3); // RX, TX

    void setup() {
      Serial.begin(57600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }
      Serial.println("Goodnight moon!");
      // set the data rate for the SoftwareSerial port
      mySerial.begin(4800);
      mySerial.println("Hello, world?");
    }

    void loop() {
      if (mySerial.available())
        Serial.write(mySerial.read());
      if (Serial.available())
        mySerial.write(Serial.read());
    }

title: myserial.available() returns zero byte

Answers: 2

body:
The SoftwareSerial example code
https://www.arduino.cc/en/Reference/SoftwareSerialAvailable
shows that the pins used as tx and rx for SoftwareSerial need to be defined using pinMode() as digital input and output.

>Example

    // include the SoftwareSerial library so you can use its functions:
    #include <SoftwareSerial.h>

    #define rxPin 10
    #define txPin 11

    // set up a new serial port
    SoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);

    void setup()  {
      // define pin modes for tx, rx:
      pinMode(rxPin, INPUT);
      pinMode(txPin, OUTPUT);
      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
    }

    void loop() {
      if (mySerial.available()>0){
        mySerial.read();
      }
    }

body:
Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).
Not all pins on the Leonardo and Micro support change interrupts, so only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).


body:
I would like to calculate the amount of voltage from my A0 pin. I am using a 9v battery to power my load in my circuit. The formula to calculate voltage from the A0 pin is:

        sens = analogRead(A0);
        vol = sens * ( 5.0 / 1023.0);
If my power source is 9v, should i replace the 5.0 to 9.0?

title: How to calculate voltage from A0 pin

Answers: 1

body:
The analog input pins are 0V-5V strictly. If you need to measure a 9V input, you need to scale the voltage to test so that it is within a 0V-5V range. Often this is done with a voltage divider circuit.

In the example below, the 9V test voltage is divided in half, so the scale is 0V-4.5V, which is within range of the input pin.

Then your algorithm is

    vol = sens * (2.0) * ( 5.0 / 1024.0);

<!-- 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/mTaiH.png)

<!-- End schematic -->


body:
I'm newbie in arduino due. I need to reduce the default PWM frequency of arduino Due. Anyone have any tutorial to do this? (Frequencys like 25hz, 50Hz for example)

I read in some posts, if i change the PWM frequency, i make changes in internal timers of arduino and i loss functions like delay(), millis(), etc.

Exits any form to not lose these functions?

Thanks a lot!

title: Reduce PWM Frequency Arduino DUE

Answers: 1

body:
The [Palatis Softpwm library][1] can generate PWM on any digital pin with (almost) any frequency. Example for 25Hz:

    #include <SoftPWM.h>
    SOFTPWM_DEFINE_CHANNEL(0, DDRB, PORTB, PORTB2);  //Arduino pin 10
    void setup() {
      // begin with 25Hz pwm frequency
      Palatis::SoftPWM.begin(25);
      Palatis::SoftPWM.set(0, value); // value is 0 to 255 just like normal Arduino analogWrite
    }

  [1]: https://github.com/Palatis/arduino-softpwm


body:
I cannot upload my sketch to my arduino DUE.

I get this error:

    Send auto-baud
    No device found on COM8
    Set binary mode
    An error occurred while uploading the sketch

The IDE recognizes thought that port 8 is the DUE programming port. Also i get a response when i press "Get Board Info".

After searching online, i found out it has to do with my baud rate.
So i use the "mode" command in windows and the baud rate is 115200.

So i use this command:

    mode com8:1200,n,8,1

When i retype mode, then indeed, COM8 is at 1200 baud.
Then i try to reupload and it fails yet again!

So i retype "mode" and COM8 is back to 115200.

So i think the IDE resets the baud rate to that value.

Any clue on what to do?

title: Cannot upload to Due

Answers: 0


body:
I'm using an Arduino Uno. Currently I am using an ESP8266 WIFI module to connect to the Wifi. But is it possible to use my laptop or Android mobile as a WiFi Shield/Module? I want to connect with cloud server using the connection.

Thanks in advance.

title: Can I use my PC or Android mobile as WiFi Shield/Module for Arduino UNO?

Answers: 1

body:
This problem can be broken into several components:

### Communications channel between the Arduino Uno and the laptop or Android mobile

There are several options. The most common and probably easiest is to do serial communication over USB. The Uno has a USB-serial chip that creates a virtual COM port (VCP) on a computer when you connect the Uno to it via the USB receptacle on the board. This VCP is commonly used to upload sketches to the Uno and also to communicate with the Arduino IDE's Serial Monitor.

Another option for communications between your Uno and the laptop or Android mobile is Bluetooth. You can buy a Bluetooth module for your Uno that will allow this. This may be preferable if you need wireless communication.

### Application on the Laptop or Android mobile that interprets communication with the Uno

Now you can communicate between the two devices but you need a program running on the Laptop or Android mobile to actually do something with the communication. This application will receive commands from the Uno, and make the desired interactions with the "cloud server", and perhaps respond to the Uno. You will need to have some sort of a command protocol. The details of this will be dependent on which type of communications channel you chose. There are many ways you can accomplish this and the best option will also depend on whether you will be writing this application yourself or trying to find an existing application that suits your needs.

### Arduino Uno firmware

This is a sketch you will write and upload to your Uno that sends commands to the laptop or Android mobile via your chosen communications channel and handles any responses.


body:
I want to learn pcb design in Eagle/Fritzing. So i was thinking of using existing amazing Arduino mini/nano in eagle and create a custom pcb which has all arduino capability and plus some components like 7 segment/Bluetooth radio etc.

Can we do that? Is is allowed or arduino design is not open to be modified?

title: Can we use Arduino mini in eagle to create new custom modal

Answers: 2

body:
Arduino is open-source hardware. The Arduino website has [schematics][1] and [board layout files][2].

  [1]: https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf
  [2]: https://www.arduino.cc/en/uploads/Main/arduino-pro-mini-reference-design.zip

body:
From https://www.arduino.cc/en/Main/FAQ#toc8:
>I want to design my own board, what should I do?
>
>The reference designs for the Arduino boards are available from their specific product pages. They're licensed under a Creative Commons Attribution Share-Alike license, so you are free to use and adapt them for your own needs without asking permission or paying a fee.

You can find the board design files on the **Documentation** tab of each product page.

Arduino Mini product page:
https://store.arduino.cc/arduino-mini-05

Arduino Nano product page:
https://store.arduino.cc/arduino-nano