text:
RESET and RESUME case in Arduino mega 2560 code (PUSHBUTTON AS INTERRUPT)

I am working on Arduino Mega 2560 which is controlling four steppers with BT6560 Driver, six pushbuttons and four limitswitches.
I want to code Arduino such that when I press RESET button (not talking about RESET button on Arduino), Arduino should run the code again from beginning.
And when I press RESUME button, Arduino should run the code from the moment I pressed the RESET button (like any song is resumed).
How can I be able to do this?
Below is a code I am working on:
int dirH_T1 = 3;
int steppin_T1 = 4;
int dirpin_F1 = 5;
int dirH_F1 = 6;
int steppin_F1 = 7;
int dirpin_T2 = 8;
int dirH_T2 = 9;
int steppin_T2 =10;
int dirpin_F2 = 11;
int dirH_F2 = 12;
int steppin_F2 =13;
int PB17ACW=23;
int PB17ACCW=22;
int PB17BCW=25;
int PB17BCCW=24;
int S01 = 34; // SENSOR INPUTS
int S02 = 35;
int S03 = 36;
int S04 = 37;

void setup()
{
    pinMode(dirpin_T1, OUTPUT);
    pinMode(dirH_T1, OUTPUT);
    pinMode(steppin_T1, OUTPUT);
    pinMode(dirpin_F1, OUTPUT);
    pinMode(dirH_F1 , OUTPUT);
    pinMode(steppin_F1, OUTPUT);

    pinMode(dirpin_T2, OUTPUT);
    pinMode(dirH_T2, OUTPUT);
    pinMode(steppin_T2, OUTPUT);
    pinMode(dirpin_F2, OUTPUT);
    pinMode(dirH_F2 , OUTPUT);
    pinMode(steppin_F2, OUTPUT);

    pinMode(PB17ACW,INPUT_PULLUP);
    pinMode(PB17ACCW,INPUT_PULLUP);
    pinMode(PB17BCW,INPUT_PULLUP);
    pinMode(PB17BCCW,INPUT_PULLUP);

    pinMode(S01,INPUT);
    pinMode(S02,INPUT);
    pinMode(S03,INPUT);
    pinMode(S04,INPUT);

}
void loop()
{
    if(digitalRead(PB17ACW)==LOW &&  digitalRead(PB17ACCW)==LOW) {
// STOP MOTOR WHEN NO KEY PRESSED
    }

// FOR FILAMENT 1 FORWARD FEEDER
    if(digitalRead(PB17ACW)==HIGH &&  digitalRead(PB17ACCW)==LOW) {
        digitalWrite(dirpin_T1, LOW);      // Set the direction.
        digitalWrite(dirH_T1, LOW);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to
            when to step.
            delayMicroseconds(50);
        }

        digitalWrite(dirpin_F1, LOW);      // Set the direction.
        digitalWrite(dirH_F1, LOW);
        delay(1000);

        do {
            digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the

            digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);

        } while(digitalRead(S01)==LOW);

        delay(1000);

        digitalWrite(dirpin_T1, LOW);      // Set the direction.
        digitalWrite(dirH_T1, HIGH);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to
            when to step.
            delayMicroseconds(50);

        }
    }

// FOR FILAMENT 1 BACKWARD FEEDER
    if(digitalRead(PB17ACW)==LOW &&  digitalRead(PB17ACCW)==HIGH) {
        digitalWrite(dirpin_T1, LOW);      // Set the direction.
        digitalWrite(dirH_T1, LOW);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);

        }

        digitalWrite(dirpin_F1, LOW);      // Set the direction.
        digitalWrite(dirH_F1, HIGH);
        delay(1000);

        do {
            digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);
        } while(digitalRead(S02)==LOW);

        delay(1000);
        digitalWrite(dirpin_T1, LOW);      // Set the direction.
        digitalWrite(dirH_T1, HIGH);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);
        }
    }

    // FOR FILAMENT 2 FORWARD FEEDER
    if(digitalRead(PB17BCW)==HIGH &&  digitalRead(PB17BCCW)==LOW) {
        digitalWrite(dirpin_T2, LOW);      // Set the direction.
        digitalWrite(dirH_T2, LOW);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T2, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);
        }

        digitalWrite(dirpin_F2, LOW);      // Set the direction.
        digitalWrite(dirH_F2, LOW);
        delay(1000);

        do {
            digitalWrite(steppin_F2, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_F2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);
        } while(digitalRead(S03)==LOW);

        delay(1000);

        digitalWrite(dirpin_T2, LOW);      // Set the direction.
        digitalWrite(dirH_T2, HIGH);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T2, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);

        }
    }

// FOR FILAMENT 2 BACKWARD FEEDER
    if(digitalRead(PB17BCW)==LOW &&  digitalRead(PB17BCCW)==HIGH) {
        digitalWrite(dirpin_T2, LOW);      // Set the direction.
        digitalWrite(dirH_T2, LOW);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T2, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);
        }

        digitalWrite(dirpin_F2, LOW);      // Set the direction.
        digitalWrite(dirH_F2, HIGH);
        delay(1000);

        do {
            digitalWrite(steppin_F2, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_F2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);

        } while(digitalRead(S04)==LOW);

        delay(1000);

        digitalWrite(dirpin_T2, LOW);      // Set the direction.
        digitalWrite(dirH_T2, HIGH);
        delay(1000);

        for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
            digitalWrite(steppin_T2, LOW);  // This LOW to HIGH change is what creates the
            digitalWrite(steppin_T2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
            delayMicroseconds(50);
        }
    }
}

I think you want to implement your code as a Finite State Machine where "reset" is just one of many states the machine can be in.

yes and currently i am focussing on a simple pushbutton but it has debouncing problem so if any other switch you can suggest if that would make things perfect and efficient.


text:
Correct solution for "multiple definition of" compile error
I'm in the process of trying to take this demo sketch and extract the necessary bits into a modular library that can be included in other sketches.
Here's where I'm at so far.
Here's the test sketch that I'm including it in.
However, when I try to compile it right now, I'm getting...
libraries/Adafruit_CC3000_Dynamodb/sha256.cpp.o: In function `Sha256Class::init()':
/home/me/sketchbook/libraries/Adafruit_CC3000_Dynamodb/sha256.cpp:33: multiple definition of `Sha256Class::init()'
sketch/sha256.cpp.o:sketch/sha256.cpp:33: first defined here

I've been programming for years in other languages, but I'm not all that experienced in C. I'm sure I'm doing something completely stupid, but I can't figure out what it is.
I'm also aware that this code still needs a lot of cleanup work in general. Right now I'm just trying to work toward a basic MVP that works so that I start gradually cleaning things up and making it more OOP one step at a time.

It looks to me like you have a copy of the sha256.cpp file in your sketch which is causing the problem.

@Majenko , nope, but seeing the sketch would probably be useful... I'll get that into a repo and update the Q.

The error message tells me you have. "sketch/sha256.cpp.o:sketch/sha256.cpp:33: first defined here"

But I'm not sure how to interpret that.  I only have one each of sha256.cpp and sha256.h, and I'm only including sha256.h from one place.  I added a link to the sketch I'm using to test above.

The module sha256.cpp (and I think the sha256.h too) are already present. Remove these 2 files from the sketch directory and it should compile without errors.

@ott  No, they're not.  There's only one of each and they're in the library, not the sketch.

Which of the myriad of DHT libraries are you using?

They may be left over in the build folder. Try restarting the IDE

@Majenko BAM!  Restarting the IDE was it.  I learned something new today!  If you want to make that an actual answer, I'll accept it.  RE: the DHT library... ( https://github.com/adafruit/DHT-sensor-library.git )

You have an old copy of the sha256 files lingering in the build folder. These will have been output at some point in the past and never been cleaned up since they have been deleted from the IDE.
It is probably a bug in the IDE that doesn't remove the old files.
Restarting the IDE will cure the problem and allow you to compile.

source: Stack Exchange

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

sort: votes


text:
Arduino outputs garbage values on serial monitor with ESP8266
I have connected my Arduino with an ESP8266.
When I check the ESP8266, by manually entering commands at serial monitor, I get correct results.
However, when I run this program
#include<SoftwareSerial.h>

SoftwareSerial esp8266(2,3);

void setup() {
  Serial.setTimeout(5000);
  Serial.begin(115200);
  esp8266.begin(115200);
  delay(1000);
}

void loop() {
  delay(2000);
  String command="AT";

  esp8266.println(command);
  if(esp8266.available())
  {
    while(esp8266.available())
    {
      char c=esp8266.read();
      Serial.write(c);
    }
  }
}

I get garbage values where sometimes it has an OK in between the output:

" Received: "ÁT OK " Received: "AÔ ÏË " Received: "AÔ OK " Received: "ÁT ÏË " Received: "ÁT OË " Received: "ÁÔ OK " Received: "Á¬ OK " Received: "ÁT OË "

Could someone help me?

Is your serial monitor configured for 115200? Did you check the ESP with a serial monitor at 115200? Can you post the garbage? Did you look on the wires with an oscilloscope?

Yeah frarugi87. I kept the serial monitor at 115200.

Ok @abdul rahuman, try using if(esp8266.available()) { Serial.print("Received: \""); while(esp8266.available()) { char c=esp8266.read(); Serial.write(c); } Serial.println("\""); } and post back the output of the serial monitor

@frarugi87 i got this upon your code. "
Received: "ÁT
OK
"
Received: "AÔ
ÏË
"
Received: "AÔ
OK
"
Received: "ÁT
ÏË
"
Received: "ÁT
OË
"
Received: "ÁÔ
OK
"
Received: "Á¬
OK
"
Received: "ÁT
OË
"

@frarugi87 as you could see it prints OK sometimes at but it prints some garbage combination with OK. so please help me.

How do you power your ESP8266? is it from 3.3v of arduino. I would recommend powering it separately. I had these issues and when I powered it using LM1117 regulator, it worked. Also if you are working on breadboard, you will run into similar issues due to loose connection. Try soldering the connections.

I have now flashed it with a newer firmware version. Now the problem of garbage values is reduced. I mean reduced but not completely gone. I now get the actual response in between a junk of garbage values. But it works perfectly sometimes. @Sherin Mathew

I have been facing these issues during last month. But now it is working fine after spending too many hours of trial and errors. I was trying to use ESP8266-01 along with arduino to switch on a florescent lamp. I'm able to do it now without using arduino. I use only the ESP8266-01 with nodemcu. It is working perfectly for the past few weeks. Please let us know what you are trying to do so that we can help you decide whether arduino is required in your case.

I am trying to controls relays and make an IR cloner. @Sherin Mathew

As noted by Matt, the baud rate for the ESP8266 can vary depending on the firmware version/manufacturer.  9600 and 115200 are the most common.  If you can connect using a serial terminal program (like CoolTerm) you can then test the baudrate.
It sounds like the ESP8266 is set to 115200, but in my experience (and others') SoftwareSerial isn't capable of 115200 baud rate (despite "allowing" this as a setting). Some reports suggest as high as 57600 is workable, though in my experience 9600 is best for reliability.  But you can reset this and see what the max reliable value is for you in your configuration.
How to change the baud rate on the ESP8266 will depend on the firmware version. I've had success with AT+IPR=9600. You only need to run this command once (it's a persistent setting). I'd suggest, based on your description, that this is the most likely culprit that's causing the intermittent "garbage" output you describe.

don't use this command. It killed my ESP01. I used AT+UART_DEF=9600,8,1,0,0 on my other ESP, it worked well

Using 115200 has too many instructions for the Arduino Uno to reliably decode characters and that's where the garbage is coming from.
The ESP8266 default baud is 115200, so you need to connect at the default rate and issue an AT command to reduce the baud rate to 9600.
Each time you reset, the ESP8266 goes back to the default baud rate.
Here's an example script that connects at the default baud rate and then reduces it to 9600. You'll connect the Serial Monitor at 9600. At the lower baud rate, I'm not getting any garbage characters.
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX

void setup()
{
  Serial.begin(9600);
  ESPserial.begin(115200);
  ESPserial.println("AT+IPR=9600");
  delay(1000);
  ESPserial.end();
  // Start the software serial for communication with the ESP8266
  ESPserial.begin(9600);

  Serial.println("Ready");
  ESPserial.println("AT+GMR");
}

void loop()
{
    // listen for communication from the ESP8266 and then write it to the serial monitor
    if ( ESPserial.available() )   {  Serial.write( ESPserial.read() );  }

    // listen for user input and send it to the ESP8266
    if ( Serial.available() )       {  ESPserial.write( Serial.read() );  }
}

An odd thing that happened to me is that I tried to use a baud rate of 4800 and I bricked one ESP8266 module. I don't know if that was a glitch or just a coincidence.

Great. After trying this, my esp8266 blinks blue led repeatedly stuck in a loop. Good answer. +1000.

Using AT+IPR is a very dangerous command. Many ESP8266 will get bricked after the command. The only way to do it is by flashing your ESP to a 9600 baudrate.
I just had to do this myself with a friend today after using the AT+IPR command and loads of websites tell you to never use the command.

spot on. That command did ruin my esp01. But this one AT+UART_DEF=9600,8,1,0,0 worked just fine

Finally, solved garbage symbols in serial monitor by lowering the ESP's baud rate from 115200 to 9600 with the following command:
AT+UART_DEF=9600,8,1,0,0
The root cause of the problem is speed limitations of the SoftwareSerial. On hardware Serial connection, it should work ok with speeds up to 115200.
There is my ESP AT+GMR info:
AT version:1.3.0.0(Jul 14 2016 18:54:01)
SDK version:2.0.0(5a875ba)
v1.0.0.3
Mar 13 2018 09:37:06

this worked perfectly

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

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


text:
Decoupling cap for self-powered LED matrix and LED strip
Should I add a decoupling capacitor to my RGB 16x32 LED matrix powered directly via the 5V pin?
When I display a spectrogram, the current load is fluctuating quickly in the 100-250 mA range (on average, the full range is 50-300 mA).
If yes, which capacitor should I pick for this purpose?
I have 0.01 μF, 0.1 μF ceramic and 1 μF, 2.2 μF, 4.7 μF, 10 μF, 100 μF electrolytic caps.
EDIT: I'm also interested to know about this WS2812B LED strip i've connected to the 5 V pin to another Arduino.
After reducing the brightness it has similar current consumption and fluctuation of the LED matrix.
In this tutorial they suggest to add a 1000 μF cap, but in my case the currents are much smaller.

No, there is no need. The matrix already has plenty of decoupling on it, including a large electrolytic for the incoming power and a small ceramic on each of the chips.

Possibly. The LEDs are "active" in that they have drive circuits in them. They should have decoupling with the LEDs in the strips. It can be good to provide a large reservoir capacitor for that though (the equivalent of the electrolytic on your matrix).

i've checked the led strip and indeed it has small caps near each WS2812B chip.


text:
How to use HC-SR04 sensor to make a flowmeter?
I am somewhat familiar with Arduino and am trying to use two ultrasonic HC-SR04 modules to measure the direction of water flow inside a pipe. The sensors are kept as in the image below.
The direction is determined by emitting a signal from one sensor and receiving it in the other, noting down the time and repeating with the other set(See image below). This is called an ultrasonic time of flight flowmeter.
We then use the obtained values to determine the direction by seeing which one is greater. Further details on how it works can be found here: https://www.youtube.com/watch?v=rqJ9snaqYiY

I used the below code to collect the data to determine direction for this but it doesn't seem to be working, as only the first value is displayed and the second is always 0.
long firstduration = 0;
long secondduration = 0;

void setup() {
  // put your setup code here, to run once:
pinMode(13, OUTPUT);
pinMode(12, INPUT);
pinMode(11, INPUT);
Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
digitalWrite(13,LOW);
delayMicroseconds(2);
digitalWrite(13,HIGH);
delayMicroseconds(10);
digitalWrite(13,LOW);
firstduration = pulseIn(12,HIGH);
secondduration = pulseIn(11, HIGH);
Serial.print(firstduration);
Serial.print(", ");
Serial.println(secondduration);
}

Updated code:
long firstduration;
long secondduration;

void setup() {
  // put your setup code here, to run once:
pinMode(10, OUTPUT);
pinMode(13, OUTPUT);
pinMode(12, INPUT);
pinMode(11, INPUT);
Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
digitalWrite(13,LOW);
delayMicroseconds(2);
digitalWrite(13,HIGH);
delayMicroseconds(10);
digitalWrite(13,LOW);
firstduration = pulseIn(12,HIGH);

digitalWrite(10,LOW);
delayMicroseconds(2);
digitalWrite(10,HIGH);
delayMicroseconds(10);
digitalWrite(10,LOW);
secondduration = pulseIn(11,HIGH);

Serial.print(firstduration);
Serial.print(", ");
Serial.println(secondduration);
}

What would the issue be?
I am using an Arduino Uno board.
I have ruled out wiring issues...
Thanks!

To which sensors trigger is pin 13 connected? The one with the echo pin 12 or 11?

pin 13 is used to trigger both sensors at the same time.

@chrisl I changed the code like you said in your answer but it didn't work...

The updated code has been shown above.

I don't think this will work with HC-SR04 sensors. They are not just ultrasonic transducers. They incorporate extra electronics for the sole purpose of measuring the time difference between the sended and received signal. They just don't provide the needed control on the ultrasonic transducers. To change their function to suite you you will need to fully understand their circuitry (I surely don't). Or build your own support circuitry. Additionally you need to think about how to transmit the ultrasonic wave into the fluid. It isn't enough to just tag a standard transducer to the pipe. The small transducers on the HC-SR04 sensors are made for transmitting through air, so the actual transducer is hidden behind the grill inside the capsule. I thin you need to at least bring the transducer itswlf directly to the pipe, if not directly to the water. You will need to buy fizting ultrasonic transducers.
Also you have a problem due to the workings of pulseIn().
If you want to read a HIGH pulse it will wait for the pin to go LOW, then to go HIGH again, and then counting the time until it goes LOW again. This means it blocks from the moment it is called until the pulse is finished (or the 1s timeout hits).
I will assume that you trigger the sensor which has its echo pin on pin 12, though a similar problem arises when you trigger the other sensor.
With the HC-SR04 the HIGH pulse will start at a specific time after the trigger pulse. Lets assume the pulse starts at the same time on both sensors (despite the described problems above). Directly after the trigger pulse you call pulseIn() on the sending sensor. It will block until it receives the each. Since this needs about twice as long as the other sensor to receive the signal (signal needs to go to the second sensor and then back to its source) the end of the echo pulse from the receiving sensor will be inside this time, thus putting its echo pin low again. The sending snsor receives its echo, the pulseIn() function ends. Now you call pulseIn() on the receiving sensor. But its pulse already ended, so the function waits and waits for the pulse to start and finally reaches its timeout. In this case it returns zero.
You would need to check the pins in a non-blocking way. Maybe even an Input Capture Interrupt would be fitting (depending on the requirements on the resolution).

Thanks @chrisl . So should I update the code to check first sensor one and then trigger sensor two and check it?

And I also need to change the sensors used so that the transmitter diaphragm touches the pipe itself right?

Actually you don't want to trigger both sensors as they are. When they both only receive their respective echo they will have the same value (as in both cases the sound wave needs to go one time with the flow and the second time against it). You would need to split up each sensor so that the receiver of each sensor sits on the other side of the pipe than the sender. The  you can do these two measurements (one with thw flow, one against it)

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


text:
Arduino does not connect to MQTT local broker
I have an Arduino Mega with Ethernet connected to a router by cable. Also I have a PC connected to the router (by Wifi) where also the local MQTT broker is installed (mosquitto). Althought the Arduino Ethernet connection seems ok, the MQTT connection does not: I get the return code -2
This is the full code, there are several functions but the MQTT init is the one that fails:
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h> // Librería para MQTT

byte mac[] = { 0xA8, 0x61, 0x0A, 0xAE, 0x3A, 0xC4 };
byte ip[] = { 192, 168, 1, 100 };
byte gateway[] = { 192, 168, 1, 2 };
byte subnet[] = { 255, 255, 255, 0 };

EthernetClient ethClient;
PubSubClient mqttClient(ethClient);

const char *MQTT_BROKER_ADRESS = "192.168.1.101";
const uint16_t MQTT_PORT = 1883;
const char *MQTT_CLIENT_NAME = "mqttx_7c0a0ed3";

void SuscribeMqtt()
{
    mqttClient.subscribe("hello/world");
}

void OnMqttReceived(char *topic, byte *payload, unsigned int length)
{
    Serial.print("Received on ");
    Serial.print(topic);
    Serial.print(": ");
    String content = "";
    for (size_t i = 0; i < length; i++)
    {
        content.concat((char)payload[i]);
    }
    Serial.print(content);
    Serial.println();
}

void InitMqtt()
{
    mqttClient.setServer(MQTT_BROKER_ADRESS, MQTT_PORT);
    mqttClient.setCallback(OnMqttReceived);
}

void ConnectMqtt()
{
    Serial.print("Starting MQTT connection...");
    if (mqttClient.connect(MQTT_CLIENT_NAME))
    {
        SuscribeMqtt();
        mqttClient.publish("connected","hello/world");
    }
    else
    {
        Serial.print("Failed MQTT connection, rc=");
        Serial.print(mqttClient.state());
        Serial.println(" try again in 5 seconds");
        delay(5000);
    }
}

void HandleMqtt()
{
    if (!mqttClient.connected())
    {
        ConnectMqtt();
    }
    mqttClient.loop();
}

void CheckLinkStatus() {

  auto link = Ethernet.linkStatus();

  Serial.print("Link status: ");

  switch (link) {
    case Unknown:
      Serial.println("Unknown");
      break;
    case LinkON:
      Serial.println("ON");
      break;
    case LinkOFF:
      Serial.println("OFF");
      break;
  }
  delay(1000);
}

void setup() {

  // You can use Ethernet.init(pin) to configure the CS pin
  //Ethernet.init(10);  // Most Arduino shields

  Serial.begin(9600);

  Ethernet.begin(mac, ip, gateway, subnet);
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());

  delay(1500);

  InitMqtt();

}

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

  CheckLinkStatus();

  HandleMqtt();

}

I have done ping from the PC IP (192.168.1.101) to the Arduino IP (192.168.1.100) and it is ok. What could be the issue?.

What is in the logs of the MQTT broker?

@StarCat how do I check the log file? I am not able to find it.

@StarCat maybe I can't find it because I am executing mosquitto as a service? also I am not able to modify conf file

is the port open on Firewall?

Maybe find an app you can run on a different computer or your phone to verify that you can connect into your mosquito server on the PC.

I finally found the issue! As @Juraj pointed out, there was some problem with mosquitto which was blocked by the windows 10 firewall. I am sure of this because when I executed mosquito with permissions and properly using the cmd, a windows firewall windows popped up and then I unblocked it and after that Arduino was able to connect

@timemage I have installed MQTT Explorer on the PC, it is very useful to check the traffic. Thanks!

@StarCat I was finally able to run mosquitto correctly, also I am writing now the log into a text file. In my answer I have put all the code. Thanks.

The issue was coming from mosquitto local broker, which was being blocked by windows 10 firewall. When I executed mosquitto with the correct permissions on its folder (read and write for "all users") and with correct mosquitto configuration file, the following window popped up and I clicked on to allow both private and public connections:

I also use the following batch file to load mosquitto and it works all the time:
cd "C:\Program Files\mosquitto"
del mosquitto.log
mosquitto -v -c mosquitto.conf

This is the content of my mosquitto configuration file:
listener 1883
allow_anonymous true
log_type error
log_type warning
log_type notice
log_type information
connection_messages true
log_timestamp true
log_dest file C:\Program Files\mosquitto\mosquitto.log

Now I am able to use MQTT from Arduino connected to a router.

With a bit of research you can see that return code two is:
2    Connection refused: client identifier not allowed by server.
My guess is that you forgot to add the login details in the code, or the code fails because the client ID is not a c-string. Try something like this (replace with appropriate values):
    if (client.connect(clientId.c_str(), mqttUsername, mqttPassword)){

It was a firewall isse when executing mosquitto, but thanks anyway!


text:
Custom board with ATMega32u4 having USB issues
I built a custom arduino based board (speciffically based off of Sparkfun's Pro Micro 3.3V 8Mhz and their Qduino mini boards) that uses the ATMega32u4-RC.
The board I built integrated an acceleromter (LSM6DS3) and a micro-SD card holder, and eleminated any uneeded GPIO. (This is basically a datalogger board for the LSM6DS3 accelerometer). It also inlcudes a usb-powered LIPO charging circuit, which is copied from the qduino mini.
A picture of the board I built,  with power LED indicating life.

The problem I am experiencing is that, after apparently sucessfull upload of the bootloader (I've tried the bootloader for the qduino mini, promicro 3.3v 8Mhz, even the Leonardo), my computer will not reconize the board. I've exauhsted all the information about driver installation from the sources for the boards my board is based on, and still can't make windows recognize my custom board.
Specifically, I've tried using a multitude of signed and unsigned drivers (on Windows 10 and 7), and can not get windows to pick anything other than usbfilt.sys as the driver.
Any advice would be greatly appreciated!
Edit: Added Eagle Schematic below

First thing you should check is if Windows sees a USB VID/PID for this device, and if so if they are as expected.  If not, instead of loading the bootloader with ISP load a simple program that flashes and LED or something and make sure the chip runs, then re-check all of your USB wiring.

I uploaded a blink sketch via my ISP (sparkfun's avr pocket programmer) and it worked just fine.
The device instance path under properties shows the following: USB\VID_0000&PID_0002\5&173CBDFC&0&1
I'm fairly certain thes are not what it should be showing.
Also, USB wiring should work. It's the same as the pro-micro and qduino mini and it's on a PCB, so...I'm not sure what else to check as far as that goes.

Glad to hear the ATmega runs.  The VID/PID are obviously wrong, so if you're sure you loaded a suitable bootloader it's probably time to include the schematic in your post and carefully check all the soldering.

Don't know that it is definitively causative of your problem, but seems like you may have forgotten the 1uF capacitor between UCap and Ground.

That was it! Apparently UCap is needed for the 3.3V board to talk with 5-volt USB system. Thanks A TON! That really saved my sanity there!

As Chris Stratton pointed out, I neglected to include the 1uF capacitor on UCap. This is absolutely necessary on a 3.3v board for the board to communicate with USB properly.
Thanks!


text:
16 bit SPI on Arduino Due
I'm trying to control AD7091-8 using Arduino Due.
This IC calls for 16 bit SPI R/W. I'd read that I can change the transmit and receive bits of Arduino DUE by changing a register (bits 4-7 of SPI_CSR).
I was able to change the SPI of Due from 8 to 16 bits. Confirmed this by looking at SCLK and MOSI in the scope. However, the data I want to transfer is becoming intermittent.
I want to send 0x1000. On 8 bits, using the line
SPI.transfer(10,0x10,SPI_LAST);

I really can see this being sent on MOSI.
However, when I'm on 16 bits, the line
SPI.transfer(10,0x1000,SPI_LAST);

It's either becoming 0x0000 or 0x0008. I'm losing the bit or it's becoming LSB_FIRST. Not MSB_FIRST.
Below is the actual code.
#include <SPI.h>
#include "C:\Users\Smart Surface 2\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\system\CMSIS\Device\ATMEL\sam3xa\include\component\component_spi.h"
#include "C:\Users\Smart Surface 2\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\system\CMSIS\Device\ATMEL\sam3xa\include\instance\instance_spi0.h"

#define CS 10

void setup() {

  pinMode(CONV,OUTPUT);

  Serial.begin(9600);
  SPI.begin(CS);
  SPI.setDataMode(CS, SPI_MODE0);
  SPI.setClockDivider(CS,21);

  REG_SPI0_WPMR=0x53504900;
  REG_SPI0_CR=0x1;
  SPI0->SPI_CSR[0]=0x00001580;

  SPI.setBitOrder(MSBFIRST);
  delay(1);
}

void loop() {

  SPI.transfer(CS,0x1000,SPI_LAST);

  int a = SPI.transfer(CS,0x0000, SPI_LAST);
  delay(1000);

  Serial.println(a);
}

How can I make my data reliable and the order still with MSB first?

Found the problem on the SPI library.
When I do the command SPI.transfer, the data is stored on a byte type variable. And I'm passing a 16 bit data on it.
I've changed line 84 of SPI.h to
uint16_t transfer(byte _pin, uint16_t _data, SPITransferMode _mode = SPI_LAST);

so it will return and receive 16 bit data.
Also have to change the corresponding function on SPI.cpp (line 174)
uint16_t SPIClass::transfer(byte _pin, uint16_t _data, SPITransferMode _mode)

so they will match.
I've copied and renamed the SPI library that I've changed so it won't affect other codes.


text:
Standalone 328P Arduino
I am creating a standalone Arduino using Atmega328P. The circuit is below.

However, I'm seeing
avrdude: Device signature = 0x000000 error

whenever I try to burn the Arduino Uno bootloader. I'm assuming that the chip isn't responding to the SPI lines?
I know I'm doing something wrong but I can't see it.
My connections are
SCLK --> Arduino Pin 13
MISO --> Arduino Pin 12
MOSI --> Arduino Pin 11
Reset --> Arduino Pin 10

VIN --> 5V
GND --> GND

I'm using a true Arduino UNO as the ISP. I've uploaded the ArduinoISP code into it, choose Arduino as ISP as Programmer and Arduino Uno on boards. The programming connections are just wired from Arduino UNO pins to some vias I've purposely added on the layout.
As mentioned in the comments, I'm adding an image of the layout here.

I've tried this very circuit on an atmega328P soldered in a TQFP adapter and with the other components soldered on the adapter as well (looks like a jungle of wires) and somehow I was able to burn the bootloader.
Hoping someone can point out what's wrong.

Are you trying to run the ATmega at 3.3 V on a 16 MHz crystal?

Yes. Will there be a problem on doing it @tttapa?

Check the datasheet, that voltage/frequency combination is out of spec. Either raise the voltage, or lower the frequency.

Thanks for pointing it out! Yeah, just saw it now on the datasheet.

I've just tried removing the regulator and connecting 5V with the VCC line. I'm still seeing the same error. Would there be other mistakes?

It's not possible to see on that schematic how your programming device is connected up to the board. Also PCB layout images could be useful to check for mistakes.

Do you know if the clock is running? Or can you provide a clock? 10µF between dtr and reset? and no diode from reset to vcc?

C3 should be 0.1uF for Serial downloads.  D10 from the ISP connects to Reset directly, not thru the cap.

@Majenko I've added the layout on the question. The SPI lines from Arduino UNO are tapped on the SPI lines of the atmega328P. There are vias on the left side of the vias so I can add wires. The connections are stated in the question above.

@Jot yes, I've looked at it on scope and the clock is running. I mean  i have 16 MHz oscillator on it. I'm not using FTDI when burning the bootloader. I'm using the SPI lines. So basically, the cap there is left floating.

Is there a ground pour or ground plane layer that has been omitted from that image?

It's not obvious from the schematic, but pins 3,4,21 need to be grounded.  Did you do that?

@Majenko yes, there is ground pour that is not shown. But yes, all ground pins are connected to ground.

noobiejp, I think we mentioned a lot of things and you answered our questions. So we have to look for more obscure things. Perhaps you can try the Nick Gammon sketch https://www.gammon.com.au/bootloader Perhaps you can try a programmer instead of Arduino as ISP. Perhaps your atmega32u4 is broken. Do you have another Arduino Uno that you can try to put a bootloader into? If that works, you can try to put a bootloader into a Leonardo or Micro. If that works, you can try your pcb board.

Your power supply is incorrect. You cannot connect a 317 this way

It seems that you are using a lm317 voltage regulator to power your atmega328p MCU but I think you forgot the part that lm317 needs feedback of 1.25v with voltage divider network to set its variable output voltage in the schematic you have connected adj pin of  lm317 directly to GND.
S0 check your output vtg from your regulator and another issue voltage regulator only works great when difference between regulating voltage is lower then the supply voltage.

From the schematic it appears you are using a LM317 voltage regulator from USB V_IN.  The voltage drop is too large and your issues may be due to brown out, i.e. insufficient voltage:  See this SE post.  You can solve it by using a lower dropout regulator (5 V to 3.3 V) or just use the standard USB 5 V, bypass V_IN to V_CC.

Hi! I've already tried bypassing the regulator by removing it and tying VIN to VCC. So the whole VCC line will get 5V straight from USB. However, still not burning the bootloader.


text:
Not able to find right library for MPU9250
I am using an Arduino Uno and learning to use the motion sensor. Currently I was not able to find the library which looks simple and would like to get your suggestion. I found this https://github.com/hideakitai/MPU9250 library to be simple but don't know how to use it.
For example, take this code:-
#include "MPU9250.h"

MPU9250 mpu;

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

    Wire.begin();

    delay(2000);
    mpu.setup();
}

void loop()
{
    static uint32_t prev_ms = millis();
    if ((millis() - prev_ms) > 16)
    {
        mpu.update();
        mpu.print();

        Serial.print("roll  (x-forward (north)) : ");
        Serial.println(mpu.getRoll());
        Serial.print("pitch (y-right (east))    : ");
        Serial.println(mpu.getPitch());
        Serial.print("yaw   (z-down (down))     : ");
        Serial.println(mpu.getYaw());

        prev_ms = millis();
    }
}

Some values are not defined here, like registration code and input pins. I am not used to reading the documentation code so might need help in that.

I didn't understand the docs

thanks for updating your post ..... you are asking the wrong question ..... you do not have a problem with the MPU9250 library ..... your problem is with I2C communication ..... https://www.arduino.cc/en/Reference/Wire

What is the problem here, are you getting any values? Yes, then good. Finding a simple solutions to complex problems isn't always a given. If it works, stick with it. If it doesn't work then show us the schematics? I would rely on this example since it's hiding all the logic. Until it's dis-proven.  You can build a schematic here to show us. (https://www.tinkercad.com/circuits). The code should work, but i dont see any code for wiring.

In the Arduino IDE, click on SKETCH > INCLUDE LIBRARY > MANAGE LIBRARIES.

Then, search for 9250, select the SparkFun one, and click INSTALL.

Finally, from the examples, choose the MPU9250BasicAHRS_I2C.


text:
Nodemcu is connected to 5v relay with logic converter but still not working
I am using a bi-directional 3.3-5V logic converter to control 5V relay with 3.3V D5 pin of nodemcu. link of logic  converter is here
However, I expected to control the relay but it didn't work. I don't think there is a problem with electrical connection or code since that is simple.
3.3V sides of nodemcu is connected to LV and 5V side of Relay is connected to HV.
Code:-
void setup() {
  // put your setup code here, to run once:
pinMode(D5, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
digitalWrite(D5, HIGH);
delay(2000);
digitalWrite(D5, LOW);
delay(2000);
}

My Observations:-
1) When relay is removed, multimeter shows 3.3V at the LV & HV side. (so logic converter is not working i guess)
2) When relay  is  connected, multimeter shows 2.5V on  both sides.
Everything is powered from nodemcu pins. Does  it means that i have to supply extenal power or something wrong with logic converter?[![enter image description here][2]][2]
What do you guys think?
PS  - I  soldered the pins another way around on logic converter. Does it change anything?
circuit image, nodemcu is powered by the laptop USB

Please show your actual wiring.

Are you trying to drive a pure relay, or do you have a relay module (which already includes the driver circuit). If the first, make sure, that the level converter can actually provide the needed current

The photograph you provide is not helpful. Instead, show us the schematic of your actual circuit and provide a link to the manufacturer's datasheet for the level converter and the relay.

Its the relay module that I am running. I provided  that above photo to check if I  soldered right side. Will the logic converter work if I soldered behind? will  add  the  circuit  also

can anybody draw wiring diagram for raspberry pi to relay connection?

You must supply a steady, regulated voltage to both 3.3v and 5v pins at all time (see Voltage Inputs on https://learn.sparkfun.com/tutorials/bi-directional-logic-level-converter-hookup-guide/all).
Logic level controller does NOT convert 3.3v to 5v for powering the relay, it just let you turn 3.3v signal to 5v so a relay can get activated. Relay's positive pin still needs to be supplied with a 5v from a PSU or other sources.

To make that work you'd need to connect the HV connection to the Vin of the NodeMCU (as well as to the relay board) which should be the 5 V coming form the USB port. You'd also need to connect the GND on the HV side to the GND of the NodeMCU.

Exactly. Although the GND sides are probably connected, the 5V needed for the relay and logic conversion needs to be supplied from somewhere. It will not be generated by the logic level converter.

The converter and/or the nodemcu can't provide enough current to drive the relay. So you should get a 5V psu.
For further details we need more information about the parts you use.

could be, I put arduino instead of nodemcu  since it has 5V pins and worked


text:
My Ultrasonic sensor is only showing 4cm range?
I am using an ultrasonic sensor SR04 with Arduino Uno and a sample program which I got from the library. However, my output reading is only 4 cm even when there is no object in front of it. I even used another sample program which had the same output. Is the problem in sensor or library?
#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
  delay(50);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

sorry, its ultrasonic sensor SR04

Yup, I changed the pins to 11 and 12. It works better than before but still shows the reading around the 4cm. Somethings it goes till 100cm. Its not accurate, is it normal or my sensor is defective?

I recommend, if you want reliability, that you upgrade to the HY-SRF05 sensor.  The problem with the SR04 is that when there is nothing in front of the sensor (or the target is beyond the limit) the sensor sometimes "locks up," and you have to reset it to get it working correctly again.  The SR04's are a few cents cheaper than the others; there's a reason for that.
Also, there's more than one library available for these sensors.  I recommend the NewPing library by Tim Eckel available from here:  https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home
I am not affiliated with Tim in any way, but he's got a good library.

Looks to me like your powering the SR04 with 3.3v instead of 5v.

I have connected it to 5v


text:
Arduino Uno 3: Stuck at 'uploading...' sketches
I was playing around with my Arduino Uno R3 board with Sublime Text 2 & 'Stino' as IDE
I am not sure if it is my code is the problem or if I broke something...
I pressed upload while another sketch didn't finish uploading, even the original Arduino IDE can't upload new sketches anymore!
This is my code:
// singleServo.ino

#include <Servo.h>

Servo servo;
const int button = 2;
const int led = 13;
const int buzzerPin = 10;
const int duration = 180;

int stateLED = LOW;
int previous = LOW;

void setup() {
    pinMode(led, OUTPUT);
    pinMode(button, INPUT);
    pinMode(buzzerPin, OUTPUT);
    Serial.begin(9600);
}

void loop() {
    int stateButton;

    stateButton = digitalRead(button);

    if (stateButton == LOW && previous == LOW) {
        if (stateLED == HIGH)
        {
            stateLED = LOW;
            initAction(duration);
        }
        else
        {
            stateLED = HIGH;
        }
    }

    digitalWrite(led, stateLED);
    previous = stateButton;
    servo.detach();
}

void initAction(int time_iA){
    tone(buzzerPin, 523, 200);
    delay(200);

    shiftServo(180, time_iA);

    tone(buzzerPin, 262, 200);
}

void shiftServo(int angle, int time_sS) {
    servo.attach(9);
    delay(500);
    int position;

    for(position=0; position <= angle; position += 1)
    {
        servo.write(position);
        delay(time_sS / 180);
        Serial.println(servo.read());
    }
    // for(position=angle; position >= 0; position -= 1)
    // {
    //  servo.write(position);
    //  delay(time_sS / 90);
    // }
}

I am a newbie with all things Arduino - Please help!
EDIT:
After rebooting the system (Ubuntu Linux 14.04) everything was working just fine again!But I'm going to take the serial functions out too.

Have you tried to power everything down, including the host PC, then upload using the Arduino IDE? What OS are you using?

Check task manager or top or whatever for any orphaned avrdude processes

I know this is really basic, and don't be offended, but have you pressed the buiild button and verified it builds before upload? - Also please double check that the arduino is attached to the USB port assigned in the buildtool.

You have to wait for the first and all other uploads to fail.
If you are not sure, a reboot is the most reliable solution.
Also note that if your sketch sends a lot of data over serial, a manual reset of the board may be needed.

Rebooting helped. But what exactly did I do wrong? Was it the Serial or because I stopped that Upload? Should I stop using the Sublime + Stino IDE?

the problem is normally uploading is an external script has not properly stopped, and its timeout are very high.
Normally killing the process may leave the serial port "busy" (unplua and replug USB solve that), but in arduino ide there is no "kill switch" and you have to wait (note t hat being external command is indipendant from the ide). Seems like stino does the same. About the IDE, use whatever you want, but before posting here check if arduino ide has same poblem!

I checked just that. I couldn't get any sketches uploaded from both ides

yes, that case is a "race condition" over the serial; as serial port can be used only by one program at time, until all precedent upload fail (a lot of timeout time, about 20/30sec for EVERY upload in queue) you can't upload. Also notice removing Serial from sketch does not help in that case, as it is a pc issue. Serial in sketch is problematic only when write too much, but a manual board reset is easyer to do, when you'll learn the rght timing :)

I was reading about that manual reset somewhere else but I couldn't get it at the right time^^ thanks anyway for the explanation

In that case as the upload never start from pc, it wouldn't have worked. Btw just keep pressed reset, attach usb, from arduino choose serial and luck upload, when "binary size blabla" appear unpress reset button. Try again and again xD

I've got the same problem on my Ubuntu.
Eventually, I was stuck at every uploading, even after unplugging+replugging the device.
Killing all avrdude process, remove the problem.
sudo killall avrdude

or with new IDEs:
sudo killall avrdude_bin

I had this happen to me on an UNO R3. I solved the issue by disabling Bluetooth on my laptop. It was causing a conflict on COM5.
I had ruled out the board, cable, and IDE. Finally noticed in Device Manager that COM5 had entries (one being the Arduino and the other being Bluetooth)
Hope that helps someone else that might have this issue in the future.

I had the same problem with arduino uno r3 on win10.
The solution was simple:

open the task manager (Ctrl + Shift + Esc)
stop all open COM processes
and the arduino upload worked again.


text:
Battery Monitoring System for Arduino
I need to incorporate a battery monitor using a 10 led bar graph. I am powering the arduino with a 7.4(though it reads 7.67) V  lithium polymer battery through the arduino`s power jack. The goal is to monitor that battery. How would I go about doing this? I have a LM3914 driver to use if I want but I am clueless as to what to do.

Create a voltage dividerm using two resistors, to safely measure the battery voltage. Just note that the voltage drops faster when the battery is getting low (i.e. the relation with battery voltage and remaining capacity isn't linear). Though who cares if the battery is 90% or 80%, we care more about the 20% versus 10%.

Google is your friend - https://learn.sparkfun.com/tutorials/dotbar-display-driver-hookup-guide


text:
Opening .h and .cpp files from folders other than the sketch folder
My team has a C++ program from another microcontroller that we are moving to Arduino, which is currently divided into two main folders, the sketch and libraries. We want to be able to open some of the library files in the Arduino IDE along with the sketch, something it will do automatically if they are in the same folder, but not allow otherwise. The files in question are referenced from the other libraries though, which means moving just a few of them results in compilation errors. We don't want to move them all to the sketch folder, since that defeats the purpose, but a few of my teammates are vehemently opposed to having to edit them using another IDE.
So is there a way to have these files open in the Arduino IDE with the sketch? Or do I have to tell my teammates to suck it up and use a second editor if they want to make changes?
Alternatively, a way to get the libraries able to reference files in the sketch folder would also work.

What IDE did they use for the other micro controller?

@geometrikal They were PIC32s, so we used the MPLAB X IDE, which everyone universally disliked.

I've just started moving a project over to netbeans. It was tricky at first but I think it would be much better than the Arduino IDE for a team.

I don't recommend this
A) Because the arduino editor is pretty bad for serious coding
B) Because you will need to have a header guard on all library code that doesn't have one already (even in .cpp's)
But, if you really have to, the only way I can think of is to make a symbolic link to the library file in the sketch directory. It works, but the file gets compiled twice, so you need those header guards on everything.

Yeah, I think everyone agrees on that. But I guess they hate alt+tabbing that much more. I'll look into symbolic links then; the headers all have guards already so that shouldn't be too much of an issue.


text:
NodeMCU keeps hanging after random time
I have tried almost everything but my NodeMCU keeps hanging after random intervals, it usually stops working after 2 days, but well... I will describe it's behaviour, what I mean by hanging is that the server stops responding to the assigned static ip, if I restart my modem or the node it works again, but this device is meant to be working endlessly and shouldn't stop working even if it has been connected during one week, I have tested it a lot, it has worked for 2 days, for 3 days, once it worked for 4 days without any problem, but after reconnecting it in another place, hanged again after almost 2 days. I started to think that probably the problem it's related to NodeMCU. So please I would really appreciate any helpful suggestion like assigning ip through the modem or something that can help. Thanks in advance.
The NodeMCU is connected to a usb power hub (A regular android phone wall charger), and it controls a relay.
Here is my code:
#include <ESP8266WiFi.h>

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

int ledPin = 13; // GPIO13
int ledPin2 = 12; // GPIO13
int desconectado = 5;
int conectado = 4;
WiFiServer server(80);
WiFiClient client;

int counter = 0;
int count;

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

  WiFi.mode(WIFI_STA);

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);

  pinMode(ledPin2, OUTPUT);
  digitalWrite(ledPin2, HIGH);

  pinMode(conectado, OUTPUT);
  pinMode(desconectado, OUTPUT);
  digitalWrite(desconectado, HIGH);

  connectWifi();

  Serial.print(F("Setting static ip to : "));
  Serial.println(WiFi.localIP());

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

}

void loop() {

  delay(200);

  if (WiFi.status() != WL_CONNECTED) {
    delay(100);
    digitalWrite(conectado, LOW);
    digitalWrite(desconectado, HIGH);
   connectWifi();
  }

  // Check if a client has connected
  client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  count = 0;
while(!client.available()){
delay(1);
count++;
if ( count > 1000 )
{
Serial.println("Abandoned Client");
client.stop();
return;
}
}

//Serial.println("new client");
//  int t = millis();
//  while(!client.available()){
//  delay(1);
//  if (millis()-t>130) return;
//  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  client.println("HTTP/1.1 200 OK");
  client.println("Access-Control-Allow-Origin: *");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one

  // Match the request
  if (request.indexOf("/switch") != -1)  {
    digitalWrite(ledPin, !digitalRead(ledPin));
    digitalWrite(ledPin2, !digitalRead(ledPin2));
    printSwitch();
  }else if (request.indexOf("/uno") != -1) {
    client.print("Canal 1 apagagado | Canal 2 encendido");
    digitalWrite(ledPin, HIGH);
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/dos") != -1){
    client.print("Canal 1 encendido | Canal 2 apagado");
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/tres") != -1){
    client.print("Canal 1 apagado | Canal 2 apagado");
    digitalWrite(ledPin, HIGH);
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/cuatro") != -1){
    client.print("Canal 1 encendido | Canal 2 encendido");
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/cinco") != -1){
    printIP();
  }else if (request.indexOf("/apagaruno") != -1){
    client.print("Canal 1 apagado");
    digitalWrite(ledPin, HIGH);
  }else if (request.indexOf("/apagardos") != -1){
    client.print("Canal 2 apagado");
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/prenderuno") != -1){
    client.print("Canal 1 encendido");
    digitalWrite(ledPin, LOW);
  }else if (request.indexOf("/prenderdos") != -1){
    client.print("Canal 2 encendido");
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/canaluno") != -1){

    if(digitalRead(ledPin) == HIGH) {
      client.print("Off");
  } else {
    client.print("On");
  }

  }else if (request.indexOf("/canaldos") != -1){

    if(digitalRead(ledPin2) == HIGH) {
    client.print("Off");
  } else {
    client.print("On");
  }

  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
  client.stop();

}

void printSwitch(){

  if(digitalRead(ledPin) == LOW) {
    client.print("Canal 1 Encendido");
  } else {
    client.print("Canal 1 Apagado");
  }
  Serial.println("");
  if(digitalRead(ledPin2) == LOW) {
    client.print("Canal 2 Encendido");
  } else {
    client.print("Canal 2 Apagado");
  }
}

void printIP(){
  delay(100);
  client.print(WiFi.localIP());
}

void connectWifi()
{
  Serial.print("Connecting to "+*ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
  }

  // config static IP
  IPAddress ip(192, 168, 1, 66);
  IPAddress gateway(192, 168, 1, 1);
  IPAddress subnet(255, 255, 255, 0);
  WiFi.config(ip, gateway, subnet);
  digitalWrite(conectado, HIGH);
  digitalWrite(desconectado, LOW);
  Serial.println("");
  Serial.println("Connected");
  Serial.println("");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}//end connect

Check the power source. If you're powering it via USB it is likely to malfunction over time, but if you use an external and stable power source you won't have that kind of problem.

What do you mean if I'm powering via usb, then how should I power it if I'm not using it's micro usb input? I'm using a wall power hub, like an android device charger.

I meant using a reliable external power source (which is probably what you're doing) as opposed to using your PC's USB port (as many people do, and it frequently results in that kind of problem). But even so, if you are getting it to work for 2 or 3 days straight, I would still check the power supply. To guarantee that is the problem, you can power it with a battery and see how it goes (just make sure to measure the current first and implement a sleep mode if necessary, otherwise it might run out of power too fast).

Is there the possibility of all this being a bug on the NodeMCU?


text:
Void value not ignored as it ought to be
im trying to build an rc plane using arduino nano and nrf24l01 as receiver but im having some issues in the code
it has error on the line
done = radio.read(joystick,sizeof(joystick)); which says that void value not ignored as it ought to be
the whole code is below
#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include<Servo.h>

Servo Throttle,Rudder,Elevator,LeftAileron,RightAileron ;

const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(9,10);
int joystick[5];

void setup()
{
  /*Serial.begin(9600);
  delay(1000);
  Serial.println("Starting Rx");*/ //Enable serial for debugging

  attachMotors();

  calibrateMotors();

  radio.begin();

  detachMotors();

  radio.setPALevel(RF24_PA_MAX);
  radio.setPayloadSize(10);
  radio.setDataRate(RF24_250KBPS);
  radio.setRetries(15,15);

  radio.openReadingPipe(1,pipe);
  radio.startListening();;
}

void loop()
{
  detachMotors();

  if(radio.available())
  {
    bool done=false;
    while(!done)
    {
      done=radio.read(joystick,sizeof(joystick));
    }

  attachMotors();

  int a=joystick[0];
  int b= joystick[1]; //stores values from tx
  int c=joystick[2];
  int d=joystick[3];
  int e=joystick[4];

  //Serial.println(a);
  //Serial.println(b);
  //Serial.println(c);
  //Serial.println(d);
  //Serial.println(e);
 // Serial.println(f);

  delay(20);
  Throttle.writeMicroseconds(a);   //write values to motor
  Rudder.write(b);
  Elevator.write(180-c);

  if(d== LOW)
  {
  LeftAileron.write(180); ////to activate right aileron
  RightAileron.write(180);
  delay(15);
  }

  else if(e == LOW)
  {
    LeftAileron.write(0);  //to activate left aileron
    RightAileron.write(0);
    delay(15);
  }
  else
  {
    LeftAileron.write(100);
    RightAileron.write(110); //Ailerons at neutral pos
    delay(15);
  }
    }
  else
  {
    calibrateMotors();
    delay(15);

  }
  }

void attachMotors()
{
  Throttle.attach(3);
  Rudder.attach(4);
  Elevator.attach(5);
  LeftAileron.attach(6);
  RightAileron.attach(7);
}

void calibrateMotors()
{
  Rudder.write(90);
  Elevator.write(90);
  LeftAileron.write(100);
  RightAileron.write(110); //centering servo shafts
}

void detachMotors()
{
  Throttle.detach();
  Rudder.detach();
  Elevator.detach();
  LeftAileron.detach();
  RightAileron.detach();
}

"Void value" basically means "nothing", that the function doesn't return anything you can to store. If you want to check if packets are available use the .available() and read() if you want to store that data somewhere (after you've made sure there is something in the buffer).

I think this examples could help you but this isn't the same library you seem to be using: https://github.com/nRF24/RF24/blob/master/examples/GettingStarted/GettingStarted.ino . (Disclaimer: I am one of the maintainers of the library linked here)


text:
ATmega328p hangs on USART RX interrupt
I was able to use USART without interrupt driven and it worked perfectly! However, when I tried adding interrupt on USART_RX_vect, the program does not work as expected anymore.
Below is my small program. The expected behavior of this program is everytime I press a button the LED should toggle its state, but also by default the LED will toggle its state every 500ms. Right now, the LED toggles every 500ms but
 the moment I press a button on my machine keyboard to send data to the ATmega328p, the program stops (the led freezes on its last state).
I am not using an external clock, but I wonder if that could be the problem or I am missing something in my code that I can't figure out.
I appreciate any help. Thank you.
#ifndef F_CPU
#define F_CPU 1000000UL
#endif

#define FOSC F_CPU
#define BAUD 4800
#define MYUBRR FOSC/16/BAUD-1

#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

void USART_Init(unsigned int ubrr) {
   UBRR0H = (unsigned char)(ubrr>>8);
   UBRR0L = (unsigned char)ubrr;
   UCSR0B = (1<<RXEN0) | (1<<RXCIE0);
   UCSR0C |= (1<<UCSZ00 | (1 << UCSZ01));
}

IRS(USART_RX_vect) {
    PORTC ^= (1 << PC5);
}

int main(void) {
    USART_Init(MYUBRR);
    DDRC |= (1 << PC5);
    sei();
    while(1) {
        PORTC ^= (1 << PC5);
        _delay_ms(500);
    }
    return 0;
}

Edit#1: I modified IRS handler:
Code:
IRS(USART_RX_vect) {
    while(!(UCSR0A&(1<<RXC0))){};
    unsigned char received = UDR0;
    PORTC ^= (1 << PC5);
}

Status: Program does not work.
Edit#2: Fixed typo ISR instead of IRS (pffff)
Solution: I was missing the code for consuming the RX buffer and I had a typo: IRS should be ISR. Thanks for @Edgar Bonet and @Majenko for the help!

Just replace IRS (Internal Revenue Service) with ISR (Interrupt Service Routine).

Nice catch, I didn'even think about this ... I thought the compiler would help me fix my syntax :/

@COMP: It did help me: warning: type of ‘__vector_18’ defaults to ‘int’ and warning: unused parameter ‘__vector_18’.

@COMP: And warning: return type defaults to ‘int’ for the IRS() function.

Good catch there ;) I suspect it may actually be a combined problem including not reading the RX buffer, and both needed to be fixed to see it work.

EdgarBonet you're right, I ignored my console as long as it passed the syntax analysis phase. @Majenko yes it's both answers combined that fixed my problem. Thanks!

I suspect if you were a fly you would see your LED flashing very very rapidly.
The reason is, your interrupt will constantly trigger itself over and over and over again.
Why? Because you aren't reading the incoming character from the RX buffer. And until you do the chip will keep alerting you that there is something there to read by triggering the interrupt.

I tried modifying my code, not sure if that is enough to consume the character from the buffer. (Refer to Edit#1)

It should be - if the compiler doesn't optimize it out (which it shouldn't since one half is volatile). However, I usually simplify it to: (void)URD0;

Unfortunately it did not fix my program, but it's for sure something I didn't know. Thanks!


text:
5V and Vin pins on Arduino
I am working on connecting two Arduino boards (Arduino Uno & Arduino Nano). I am trying to run a stepper motor  connected to Arduino Nano with two digital Pins on Arduino Uno to alter the direction of the stepper motor(BYJ48) connected to the arduino Nano.
While making connections I attached the pins as:
1] 5V  (UNO) -> 5V (NANO) & GND (UNO) -> GND (NANO)
2] 5V (UNO)  -> 5in (NANO) & GND (UNO) -> GND (NANO)
Both [1] & [2] worked fine initially but I kept the arduino powered and tried toggling the Vin with 5v. Nothing went wrong in the beginning but later fumes started coming out and I dont know the reason why?
Was that because I kept the power on while toggling between Vin & 5v ?
NOTE: besides the code and success in running the possible reason of fumes is much important here.

Why did you connect arduino's 5V and GND at all? What was the reason? And why did you use two arduinos to drive stepper motor?

task for me was to connect the two arduinos with just any two pins and try to communicate between two with the digital pins on ARDUINO UNO. I was trying to gather the ways how i can do that and i thought let just try with simply 5v->5v & GND -> GND like the way we do for I2C. I was just checking if that can be done or not.

Ah so, this is not the case at all... If you want to use I2C you need to use digital pins, not 5V or GND! You can read more there http://www.instructables.com/id/I2C-between-Arduinos/

GND is connected to keep the relative zero the same, but 5V is not used for sure.

thanks for the comment but i want to know how to communicate between the two arduinos of different types without using any protocols like I2C or SPI..? Can we do this..?

Yes, you can write your own protocol, but it is not an easy task and except of learning, no real reason to do that.

Note: You can try make up custom communication. But you have to use the pins you can actually control (write and read). 5V is not the case.

You can try software serial communication between the two boards. Any two digital pins of one board can be used as Rx and Tx, and make sure the roles of Rx and Tx are reversed on the other board. See the Software Serial library:
https://www.arduino.cc/en/Reference/SoftwareSerial


text:
Arduino Uno as a HID the letters duplicate
This is my current result.

I don't know how to solve this.
This is my code:
//Modifier Keys
#define LEFT_CTRL   0x01
#define LEFT_SHIFT  0x02
#define LEFT_ALT    0x04
#define LEFT_GUI    0x08
#define RIGHT_CTRL  0x10
#define RIGHT_SHIFT 0x20
#define RIGHT_ALT   0x40
#define RIGHT_GUI   0x80

//Keys
#define KEY_ENTER 0x28
#define KEY_BACKSPEACE 0x2A
#define KEY_TAB 0x2B
#define KEY_CAPSLOCK 0x39
//keyPress(RIGHT_ALT, 0x1F);

uint8_t buf[8] = { 0 }; //buffer

void setup()
{
  Serial.begin(9600);
  delay(600);
  keyPress(LEFT_GUI, 0x15); // Windows keys + R
  keyRelease();
  delay(200);
  keyString("cmd");
  delay(500);
  keyPress(0, KEY_ENTER);
  keyRelease();
  delay(500);
  keyString("ipconfig");
  delay(500);
  keyPress(0, KEY_ENTER);
  keyRelease();
}

void loop()
{
  //keyString("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 - = [] \\ ; ' , . / !@#$%^&*()_+ {}|; \" <> ?"); // <---test key
}

void keyRelease()
{
  buf[0] = 0;
  buf[2] = 0;
  Serial.write(buf, 8); // Release key
}

void keyString(String text) {
  char alpha[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
  int mean_dic[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};
  //                                                                                39    61    91    93    44    46    45    32    43
  char normal_sym[] =     { '1',  '2',  '3',  '4',  '5',  '6',  '7',  '8',  '9',  '0',  '\'',  '¡',  '[',  '+', 'ñ',  ',',  '.',  '-',  ' ',  '+'};
  int mean_normal_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,  0x2D, 0x2E, 0x2F, 0x30, 0x33 ,0x36, 0x37, 0x38, 0x2C, 0x57};

  char shift_sym[] =     { '!',  '"',  '#',  '$',  '%',  '&',  '/',  '(',  ')',  '=',  '?',  '¿',  '°',  '*',  'Ñ', '{',   ';',  ':',  '_'};
  int mean_shift_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2D, 0x2E, 0x2F, 0x30, 0x33, 0x34, 0x36, 0x37, 0x38};

/*  English Dic
  char alpha[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
  int mean_dic[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};

  char normal_sym[] =     {  '1', '2',  '3',  '4', ' 5',  '6',  '7',  '8',  '9',  '0',  '-',  '=',  '[',  ']',  '\\', ';'  '\'',  ',',  '.',  '/',  ' '};
  int mean_normal_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x33, 0x34, 0x36, 0x37, 0x38, 0x2C};

  char shift_sym[] = {'!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '{', '}', '|', ':', '\"', '<', '>', '?'};
  int mean_shift_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x33, 0x34, 0x36, 0x37, 0x38};
*/
  char temp_char;

  for(int i = 0;i<text.length();i++)  //Recorre lo que vos le mandaste
  {
    temp_char = text.charAt(i); //Agarra el primer caracter que se le envia por parametro
    if(((int)temp_char >= 97 && (int)temp_char <= 122) || ((int)temp_char >= 65 && (int)temp_char <= 90)) //Si el caratecer es una letra mayuscula o minuscula ---
    {
      for(int j = 0;j<sizeof(mean_dic) - 1;j++) //Recorre esta lista
      {
        if(temp_char == alpha[j]) //Si el caracter es igual al de la lista entonces...
        {
          keyPress(0, mean_dic[j]); //Presionalo
          keyRelease();
          break;
        }
        else if(temp_char == toupper(alpha[j])) //Si el caracter es igual al de la lista (En MaYuscula)
        {
          keyPress(RIGHT_SHIFT, mean_dic[j]); //Presionalo
          keyRelease();
          break;
        }
      }
    }

    else if(((int)temp_char >= 48 && (int)temp_char <= 57) || ((int)temp_char >= 43 && (int)temp_char <= 46 || (int)temp_char == 32  || (int)temp_char == 39 || (int)temp_char == 173 || (int)temp_char == 164 || (int)temp_char == 91 || (int)temp_char == 93)) //Si el caratecer es una letra mayuscula o minuscula...
    {
      //check = false; //Flag para distinguir nros de caractes especiales
      for(int j = 0;j<sizeof(mean_normal_sym)-1;j++)  //Recorro los nros
      {
        if(temp_char == normal_sym[j]) //Si en una de esas coincide
        {
          keyPress(0, mean_normal_sym[j]);
          keyRelease();
          break;
        }

      }
    }

    else
    {
        for(int i = 0;i<sizeof(mean_shift_sym)-1;i++)//Di lo tuyo Bart...
        {
          if(temp_char == shift_sym[i])
          {
            keyPress(LEFT_SHIFT, mean_shift_sym[i]);
            keyRelease();
            break;
          }
        }
      }
  }
}

void keyPress(int mod, int key)
{
  buf[0] = mod;
  buf[2] = key;
  Serial.write(buf, 8);
}

Why does the CMD command work and yet the ipconfig command has a problem?

I cannot see what makes an Arduino UNO with this code a HID device. Can someone enlighten me? I just see a bunch of serial prints.

i suspect that the OP is not using an Arduino UNO

You might want to consider using the function isAlpha() If its on an Arduino.
Also if (tempChar == 'A') will work and make the code more readable.
I suspect the problem you have is caused by keyPress() and keyRelease().  You are setting 4 bytes of buffer and then writing 8 bytes to the serial interface.  What is the value in buffer[4]?  I think its a lucky coincidence that its duplicating characters rather than crashing.

i dont realy get what you are saying so please can you explain more

Why are you writing 8 characters from buf after only setting two bytes to something, in keyPress?

@Matt - the default for global variables is to be set to zero, but still ...

@NickGammon I've been stung to many times by that to trust it any more. :)

@KarimNagdi - Nick is right, you are putting 2 int variables mod and key into buf.  This means you are writing 4 bytes into buf (each int is 2 bytes ?) and then you are writing all 8 bytes of buf out with your call to Serial.write(buf,8).  As Nick said above buf[4] should be zero.
So either you are calling keyPress() twice or because you are not supplying enough data Serial.write() is repeating the buffer.  These are guesses, they might be way off the mark, but its worth looking at.

authors: максим гурко


text:
Advance arduino programming?
I have worked with basic arduino IDE for making robots and sensor based projects.Now I want to learn some advance arduino programming and try some complex Arduino projects.Can anyone help me with the links or related information..?

get an ESP8266 to run some of your AVT sketches; the conversion will teach you a lot about the ardunio platform, and MCUs in general.

Here are 4 suggestions:

Especially for point 2 there are plenty of resources that are easy to find. Once you learn "Blink" sketch,you will realize there is a lot out there.

Don't use Arduino IDE

It lacks a lot of features which any serious programming IDE offers today. Visual Micro for Visual Studio and PlatformIO are two examples. More alternatives mentioned in the comments. These IDE which give you advance features like syntax highlighting, autocompletion, multifile projects, etc..

Start learning C/C++

Arduino programming is derived from C++ with some nice libraries to make it easier, specially on Embedded Systems. Instead of looking up and setting registers to change pin state Arduino libraries will make it easier for you.I have worked with complex projects on arduino and arduino libraries made it very easy to go. There is a lot more to learn in arduino.

Start learning electronics

Your advanced projects surely comes with advanced electronics. This is a whole other place where things might go beyond our understanding. I have spent hours and days debugging my codes. It will also help you find your way through the jungle of all the current "maker toys". There are different platforms, variety of boards and chips,people often spend a lot of time figuring out which one is suitable for our project.

Have a look at Arduino's "successors": ESP8266, ESP32

These Chinese chips are like Arduino on crack. They have onboard WiFi and higher clock frequencies (but are also a lot more capricious and don't have as much documentation as Arduino). Best part: You can program them just as easily as your Arduino Or you can try barebone programming (javascript)later. The newest one, the ESP32 is a dual-core chip with 240 MHz, WiFi and Bluetooth. Cost is around USD 2. It is available on Aliexpress.
There are also a lot of other chips/boards out there that I have not mentioned here. Above is AFAIK the most common.

1b.  Don't use Visual Micro and Visual Studio, the overhead isn't worth the benefits IMO.  Use Notepad++ as an external editor for the Arduino IDE.  It has all the features of Visual Studio 2017 + it has macros!  (Otherwise Grtschnk is spot on!)

Try eclipse then. There's already a good plugin for that to support Arduino.

I don't see how netbeans was any better.  They're just about equivalent to me.  I haven't had any issues with eclipse. I use it for Java, python, c++, Arduino, and I'm sure something else I'm not thinking of this early in the morning.  Either way, it was just a suggestion. You don't have to take it.


text:
Connect a sensor to Arduino without knowing much info about the sensor
I am planning to buy a formaldehyde sensor and I would like to connect it to an Arduino Uno board (and later to a Raspberry). As far as I know, the sensor comes in a small box/bag without any other external components (e.g. amplifiers etc.). So I will end up having in my hand a sensor with two copper terminals for connection (see image below):

Is it possible to connect this to an Arduino board without having a connection scheme? If yes, where do I connect the two terminals of this sensor to the 5V, GND and the A## ports? Also, how to translate the voltage coming from the sensor to ppm (parts per million) only by having general specifications from the manufacturer and not some kind of table of conversion? Also, would I need an external component for this? If yes, which component?
I know that this question sounds very stupid, but so far I've used sensors that come with a code on Seeed Grove with a clear description and I assumed that the code is there because there is a link between the producer of a certain sensor and Groove. Thank you!
FYI: The producer writes some things about the sensor but that doesn't help me a lot:

This sensor is of the two-electrode electrochemical type, operating by the
  diffusion principle and as such requires no external sampling hardware. In
  the presence of formaldehyde gas a small direct current is produced; the
  sensor requires no power supply of its own but this current requires
  amplification to make it readable using external data collection
  equipment.

Step one: read the datasheet. Step two: implement the circuit described therein.

buy the sensor kit

I would gladly buy the kit, but I'm afraid I would end up with the same problem. How would I connect the kit to an Arduino board? As for implementing the circuit, well, I don't have the right knowledge. You are referring to the one with resistors and capacitors, right? (I can only read some of the symbols in the circuit schemes)

You have linked to the datasheet of the sensor.
In the datasheet, look at the "Application Circuit" section. You must build this circuit. The sensor produces a very small electric current, and the application circuit is high-gain amplifier to translate that very small electric current to a varying voltage you can sample with the Arduino ADC.
Note on the circuit, the wire labled "To ADC" -- that is the part which you connect to your arduino.
As for calibration, the datasheet itself notes that the process is non-trivial, or that they can perform a calibration, for an additional fee, at the time you order a batch of sensors. Presumably their calibration will include the precise resistor values used to set the gain of the amplifier, and also an equation to associate PPM values to the analog voltage provided at the "To ADC" wire.
As for reading the circuit diagram (schematic), you may already know resistors and capacitors. For the other items, search online for the part numbers given, to find out what they are.
The datasheet also notes that the application circuit is available pre-built from the sensor manufacturer. You may want to contact them to determine how to purchase one for yourself.
Most electronics products have a datasheet that explains all you typically need to know about the device, such as it's operating parameter minima and maxima, typical values, typical outputs, etc. This sensor is no different, except that the calibration procedure is not described in great detail due to the complexity.

Thank you for the nice answer. Do you know if the Kit they offer on the website is composed of that extra circuit from the datasheet or it is a different circuit? Otherwise, I will ask them to send the sensor together with that particular circuit. Thank you for clarifying this.

Read their website. In the Accessories section is the interface circuit board. I do find it hard to believe that a Q&A website is need to read information that is freely available and linked to already!?

It's not only about reading it. It's also about understanding. I'm a noob in electronics and that's why I am dealing with this. The interface circuit board doesn't have a scheme that would make me understand that it is the one in the specs. That's why I need help. Thanks to you it is now clear how to connect that circuit to an Arduino. If that accessory is the circuit that I would have to build, then I will just get it.


text:
Serial Monitor "button" implementation
I have a small project and I have some problems while working on that. The idea of the project is as below:
I have an LED which is operated by two "buttons". The buttons takes two values (1 or0) which I have to send from serial monitor.
One button is for LDR sensor, which lights up the LED when its value is below 300 (in my code). The other button turns it off (Value 0). The buttons are working together, so I have to consider both of them in my statements. The problem is that I cannot play with the serial monitor it's just looping continuously and I cant type anything as input.
Can anyone help me with this to find a solution to be able to input values for both buttons?
Here is the code:
const int analogInPin = A0; //LDR PIN
const int digitalOutPin = 13; // LED PIN
int outputValue;

int sensorValue = 0; //

char Buton1; //LDR button
char Buton2; //Blutooth button

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

void loop()
{
  while (Serial.available())
  {
    Serial.println("Button1 value: ");
    Buton1 = Serial.read();
    if (Buton1 == '1')
    {
      Buton2 = Serial.read();
      Serial.println("Button2 value: ");
      if (Buton1 == '1' and Buton2 == '0')
      {
        sensorValue = analogRead(analogInPin);
        outputValue = map(sensorValue, 0, 1023, 0, 255);
        Serial.print ("Sensor: ");
        Serial.println(sensorValue);
        if (sensorValue < 300);
        {
          digitalWrite(digitalOutPin, 255);
        }
      }
      else if (Buton1 == '1' and Buton2 == '1')
      {
        digitalWrite(digitalOutPin, 255);
        Serial.print("Both buttons are ON ! !");
      }
    }
    else if (Buton1 == '0')
    {
      Serial.println("Button2 value: ");
      Buton2 = Serial.read();
    }
    if (Buton1 == '0' and Buton2 == '1')
    {
      digitalWrite(digitalOutPin, 255);
    }
    else if (Buton1 == '0' and Buton2 == '0')
    {
      Serial.println("Both buttons are inactive ! Please reset");
      break;
    }
  }
}

How are you supposed to know which 1 and 0 come from which button?

The first problem is that your code does not wait for anything to be typed, so it loops very rapidly. Serial.read() returns -1 when there is nothing in the buffer, so I imagine your codes is printing something like:
Button1 value:
Button1 value:
Button1 value:
Button1 value:

Try inserting
while( !Serial.available() )
   ;

before your serial.read() calls. This will force it to wait until you type something before it continues.

A simple approach would be to use bit 0 of serial data to control "button 1", and bit 1 of serial data to control "button 2".  As follows:
char sd = Serial.read();
byte button1 = sd & 1;
byte button2 = sd & 2; // Or (sd & 2)>>1 if you prefer

With the above code, button 1 is true for odd-digit inputs, and button 2 is true when (sd & 2)>>1 is odd.  For example, input 0 to turn off both buttons, 1 to turn on only button 1, 2 for only button 2, and 3 to turn on both.
You might also wish to button1 or button2 only when the input character represents a digit.  For this, you can say:
char sd = Serial.read();
byte button1, button2;
... ;
if ('0' <= sd && sd <= '9') {
    button1 = sd & 1;
    button2 = (sd & 2)>>1;
}

See if this helps:
const int analogInPin = A0; //LDR PIN
const int digitalOutPin = 13; // LED PIN
int outputValue;

int sensorValue = 0; //

byte Buton1; //LDR button
byte Buton2; //Blutooth button

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

void loop() {
  while (Serial.available() > 0) {
    char inChar = Serial.read();
    if (inChar == 'l' || inChar == 'L')
    {
      Buton1 = Serial.parseInt();
      Buton1 = constrain(Buton1,0,1);
    }
    else if (inChar == 'b' || inChar == 'B')
    {
      Buton2 = Serial.parseInt();
      Buton2 = constrain(Buton2,0,1);
    }
    else
    {
      Serial.println("invalid input");
      while (Serial.available() > 0)
        Serial.read();
    }
    Serial.print("Buton1 = ");
    Serial.println(Buton1);
    Serial.print("Buton2 = ");
    Serial.println(Buton2);
    Serial.println();
  }
}

as it has been pointed before you the read function returns a -1 when there are no information to access, what you can do is
while( !Serial.available() )
{
  //do nothing
}
Buton1=Serial.read();
Serial.clear();   //for having the buffer clear for the next button

Each button has a 1 state and a 0 state. The combination will always be something like this:
if (button1 == '1' and button2 == '1')
do something
if (button1 == '1' and button2 == '0')
do something
if (button1 == '0' and button2 == '1')
do something
if (button1 == '0' and button2 == '0')
do something

How does this solve the problem in the question? The problem was "it is just looping forever".


text:
ATtiny85: Power consumption vs clock speed
Short and simple: What is the power consumption for an ATtiny85 running at 1 MHz and 8 MHz using the internal clock? Not using any sleep modes.
I have googled a lot and can't find any info on this. I ask because I want to know if it is worth using 1 MHz to increase battery life.

The datasheet is the 1st place to look for things like this

I actually did look in the datasheet. But is very long (234 pages) so I searched for strings like "power consumption" etc without luck. If I had just searched for "current" instead I would have found it!

The datasheet shows that current decreases at lower frequencies. Around 1 mA at 1 MHz running at 5 V. More like 5 mA at 8 MHz running at 5 V.

You can save quite a bit by using lower voltages as well, as you can see. For really big savings use a sleep mode. Read about Power saving techniques for microprocessors.

(Edited to add)
To amplify on my remarks, you should be able to get 200 nA consumption at 3.5 V in sleep mode with no watchdog timer. That will still respond to interrupts, such as closing a switch.

If you need to do things periodically you can enable the watchdog, and then get around 5 µA consumption at 3.5 V.

This is so much less current than the 1 mA mentioned above, that it is well worth exploring running in power-down mode, where possible.

Wow. This answer is brilliant and a perfect example why I love Stackexchange so much. Thanks a million!

Nice answer. I would just add that, when using sleep modes, the relevant metric for active mode consumption is not the current (consumed charge per unit time) but the consumed charge per clock cycle. Thus, it seems that running at 8 MHz is more efficient (5 mA / 8 MHz = 0.625 nC/cycle) than running at 1 MHz (1 mA / 1 MHz = 1 nC/cycle).

@EdgarBonet: Is that because it takes less time to run the program when it wakes up at 8Mhz compared to 1Mhz? So it can again go to sleep as soon as possible.

@Nick Gammon: When dealing with low power comsumption, what would be the best option to run the Attiny from 12V? A 7805 is rather inefficient I believe.

@marlar: Exactly! You have some job to do when you wake up, which takes a fixed number of cycles irrespective of clock frequency. Then you care about the consumption per cycle, not per second.

but the consumed charge per clock cycle - absolutely. Which is why I mention on my page about power, that if you operate at a lower clock speed you might be using less power, but you are using it for longer.

what would be the best option to run the Attiny from 12V - if you really must have 12 V as a supply, you may well find a buck-mode switching power supply more efficient.

@NickGammon: Thanks. 12V is used by the stuff that Attiny controls, that's why.

@marlar, if the thing that the Attiny controls uses 12v, then you should first and foremost look at the power consumption of this device - it's no good saving 2 or 4 mA, if you are running something that draws 2 amps.

@AMADANONInc.: you are of course right. But the controlled components are dormant most of the time and use no power except when attiny think it's time to call to action. Apart from that, there is certainly also a learning element here. I really want to investigate low-power mode.


text:
Are all Arduino shields compatible with all Arduino boards?
Are all Arduino shields compatible with all Arduino boards? Like is the Wi-Fi one compatible with the Arduino Nano & Micro as well as the Uno, etc., or do I need to be careful when buying shields that they'll be compatible with my board? Also, the shields just plug into the boards, don't they?

When you want to choose a shield for your board you should check:
1- Pin-out, this one is the least concerning one , Most arduino boards are Shield pin-out compatible and you can verify it visually, for others, normally there are some converter boards (e.g for NANO), and in the worst case, building a converter board or wiring the shield to board is trivial in most situations.
2- Shield operating voltage should match your board's, most shields operate at 5V, 3.3V or both. Normally AVR-based boards (e.g. UNO, Mega, ...) operate at 5V and ARM based ones (e.g. Due, ...) operate at 3.3V, So we should choose the shield accordingly (just keep in mind that most shield are designed with Arduino UNO in mind so it's more likely that your shields operate at 5V).
3- Library, Lots of Libraries for Arduino shields bypass Arduino library abstraction (mostly for performance reasons) and use hardware specific features (e.g directly write on specific ports), here is source of some incompatibilities between your board and the shield, for example there are handful of TFT LCD shields in the market which their library only supports UNO boards, in these cases you should either port it to your board's (based on micro-controller model and it's architecture, sometimes its as easy as changing some pin/port definitions and sometimes as hard as writing the library from scratch).

For the most part, all the shields are compatible with all the boards that have a matching shield footprint. For example, the Uno, Leonardo, and the front half of the mega all have their header pins laid out in the standard arduino shield shape. If your board has this shield footprint, then all you have to do is plug the shield in on top and upload the right code to make it work.
The nano and micro have a different size and shape than a standard arduino, and so shields will not have a handy way of attaching to them. Since they do have standard arduino chips on them, they are technically compatible, but you would have to make your own wiring to attach them.

Can you point me to documentation that shows what I need to look for so I'll be able to work out whether shields and boards are compatible please?

All you have to do is look at a picture. If the pins on the board are shield shaped (like this: http://www.themaximitecomputer.com/max/Programs/Hardware/Dontronics/Arduino%20Reference/Arduino-Dimensions.jpg ) Then any arduino shield should work.


text:
220v lightbulb gradual dimmer
I am trying to turn my incandescent bulb gradually,say its brightness should  go from zero to 100% in 10 mins. In doing so I found the following code and it works well but it's not as gradual as I want so  I hope to achieve my goal by modifying it. I thought I could change the delay in void loop() and that's it! but doing so makes no significant result.
volatile int i=0;               // Variable to use as a counter volatile as it is in an interrupt
volatile boolean zero_cross=0;  // Boolean to store a "switch" to tell us if we have crossed zero
int AC_pin = 9;                // Output to Opto Triac
int dim_level = 0;                    // Dimming level (0-128)  0 = on, 128 = 0ff
int inc=1;                      // counting up or down, 1=up, -1=down

int freqStep =75;    // This is the delay-per-brightness step in microseconds.
                      // For 60 Hz it should be 65
// It is calculated based on the frequency of your voltage supply (50Hz or 60Hz)
// and the number of brightness steps you want.
//
// Realize that there are 2 zerocrossing per cycle. This means
// zero crossing happens at 120Hz for a 60Hz supply or 100Hz for a 50Hz supply.

// To calculate freqStep divide the length of one full half-wave of the power
// cycle (in microseconds) by the number of brightness steps.
//
// (120 Hz=8333uS) / 128 brightness steps = 65 uS / brightness step
// (100Hz=10000uS) / 128 steps = 75uS/step

void setup() {                                      // Begin setup
  pinMode(AC_pin, OUTPUT);                          // Set the Triac pin as output
  attachInterrupt(0, zero_cross_detect, RISING);    // Attach an Interupt to Pin 2 (interupt 0) for Zero Cross Detection
  Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
  Timer1.attachInterrupt(dim_check, freqStep);
  // Use the TimerOne Library to attach an interrupt
  // to the function we use to check to see if it is
  // the right time to fire the triac.  This function
  // will now run every freqStep in microseconds.
}

void zero_cross_detect() {
  zero_cross = true;               // set the boolean to true to tell our dimming function that a zero cross has occured
  i=0;
  digitalWrite(AC_pin, LOW);       // turn off TRIAC (and AC)
}

// Turn on the TRIAC at the appropriate time
void dim_check() {
  if(zero_cross == true) {
    if(i>=dim_level) {
      digitalWrite(AC_pin, HIGH); // turn on light
      i=0;  // reset time step counter
      zero_cross = false; //reset zero cross detection
    }
    else {
      i++; // increment time step counter
    }
  }
}

void loop() {
  dim_level+=inc;
  if((dim_level>=128) || (dim_level<=0))
    inc*=-1;
  delay(600);
}

Edit 1: Working on  the first sketch suggested by Juraj, I put a light bulb as its load and because the period was initialized by FADE_MIN I expect the light should instantly glow in full brightness first and then gradually lose its brightness and so on, but it's not what happens and instead it takes some time to achieve its full brightness.

try my sketch https://arduino.stackexchange.com/questions/63631/fan-regulator-control-from-arduino/63674#63674

Right! I've just run it on Proteus , but it's not that clear to me. what is "FADE_MAX/MIN" for example? arbitrary chosen? what is happening in the void loop? and how to obtain the gradual fading in say 10 mins?

What delays did you try?  The vold loop(){...} code  makes 128 steps * 600ms = 76.8 sec, which is not close to the desired 10*60=600sec.  You probably want a delay(10*60 * 1000 / 128) (that's 4687ms per step) to make it 10 minutes one-way.   Also, how do you get 10000uS / 128 steps = 75uS/step?  I get 10000/128 = 78.

... and thirdly, the n/128 steps on an incandescent lamp probably don't map linearly to perceived brightness for a couple reasons: The power per unit time under the sine curve isn't uniform, and secondly the perceived brightness per incremental watt will change with temperature and wattage.  You might add an array mapping equal-sized perceptual steps to microseconds, using Juraj's 3rd example..

addressing Edit 1: try lower FADE_MIN value

I tried different amounts for delay and FADE_MIN and it still gradually goes high.


text:
I bought ATmega328p with bootloader and I can't erase it
I bought an online deal which had 10x ATmega328p with bootloader installed. I thought I can erase the bootloader once I got the order (I want to write custom task without a bootloader) but my programmer does not seem to find the ATmega328p. I know it is the problem of the microcontroller because I have another ATmega328p which works fine and I can upload code to it. Is there a flag or switch I am missing when trying to overwrite the bootloader on the microcontroller?
Here are the components I am using:

ATmega328p with bootloader
SparkFun Pocket AVR Programmer (usbtiny)

Here are the commands I am using:

To compile: avr-gcc -std=c11 -mmcu=atmega328 -O -o main.o main.c
To generate hex: avr-objcopy -O ihex main.o main.hex
To upload: sudo avrdude -c usbtiny -p m328p -U flash:w:main.hex

Here is the output of the avrdude command:
avrdude: Using SCK period of 10 usec
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Anyone encountered similar situation before? How did youu managed to fix it? I appreciate any help :)
Thank you
Edit #1 I tried setting the -B flag to various values but nothing seems to solve the problem.
Edit #2 Here is the circuit I am using while programming the ATmega328p

2x Capacitors 22pf
1x Crystal oscillator 16Mhz
1x Resistor 10K ohm
1x ATmega328p
1x SparkFun Pocket AVR Programmer

Maybe you need to provide a specific clock input to the chip...

Thanks @Majenko for your comment, I should have mentioned that I tried using the -B flag with low, medium and high values but nothing did work

This is almost certainly not a bootloader problem but either a programmer, wiring, power, clock, or fuses one.  Or you could have switching power supply chips re-printed to look like ATmega328p's (though those were QFP, and I suspect yours are DIP).

Your post should include a schematic diagram of how your powered and clocked these.  Would also be good to include a photo of the chips themselves.  Have you tried this process/programmer with any chips from a reputable source yet?

@ChrisStratton thanks for your suggestions, I added an image showing the circuit I am using.

Your connections to the ATmega328p are incomplete.
You are missing the connection of ground to pin 22, and you must supply power to AVCC on pin 20.
You should also place the capacitors much closer to the crystal with a very direct route to ground, and try to place the crystal itself closer to the chip.
Additionally you should use supply bypass capacitors.
Please see the minimum wiring at Arduino on a Breadboard, however this document itself is erroneous as it neglects to show the high frequency 0.1 uF bypass capacitors you should have directly across each pair of power pins.
That's not to say that there may not be additional issues as well - but you need to fix the circuit problems first.

Thank you Chris for your answer, I will try your suggestions and will post an update

I adjusted my circuit as you mentioned and it worked! Thank you Chris +1


text:
ESP32 wifi module
I want to connect my arduino uno rev3 to wifi. The best option I found was esp8266. After searching about it I found that it is succeeded by esp32. But I am not able to find much information about it. So I just wanted to ask if esp32 module exists as a addon to arduino or is it a board on its own. It will be really helpful if somebody can send the link from where I can buy this module(and not the board) and how to connect it to arduino.

Its called an ESP32 not an EP32 that might help your searches.

it is a "board" on it's own, that some people use the integrated UART with, to make it talk to AVRs using factory AT firmware, but it can run it's own sketch. it will work fine for you and if running stand-alone, is actually a better option then the venerable 8266 in terms of un-interupted CPU, HTTPS, more RAM, etc.

ESP32 is not a replacement for the ESP8266.  There is quite a bit of info out there, but mostly in Chinese.  If you were to use an ESP32 to provide WIFI its like using a Formula 1 car as a mobility scooter (Rascal in American?) It will do the job, but its really not suitable.
You can buy ESP32 on eBay or AliExpress, but really you shouldn't for this task.  Stick with an ESP8266.
BTW People will mark this as off topic, because it isn't strictly Arduino related.

So you are saying that esp32 is a fullblown board and not just available as a module like esp8266 module?

ESP32's seem to be available in similar module packaging as ESP8266's.  It's not that one couldn't work, it's that it's not necessary and being newer means less support and more issues you can run into, fewer tutorials you can be confident will work unchanged, etc.