text:
Arduino connection with the server failed
I am trying to connect arduino uno and ethernet shield and try to send some data to an asp.net web api application. When i upload the sketch, i get in the serial monitor connection failed.
I don't understand what's going wrong ?
Below is the code i am using
#include "cactus_io_DHT22.h"
#include <SPI.h>
#include <Ethernet.h>
#include <Client.h>

#define DHT22_PIN 2

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xDD };

IPAddress ip(192,168,0,177);
IPAddress server(192,168,0,11);
EthernetClient client;

DHT22 dht(DHT22_PIN);
float heatindex1 =0.00;
float heatindex2 = 0.00;

void setup() {
  Ethernet.begin(mac,ip);
    delay(1000);  Serial.begin(9600);

    Serial.println("connecting...");
    if (client.connect(server, 80)) {
      Serial.println("connected :D ");
    }
  Serial.print("Arduino server IP address: ");
  Serial.println(Ethernet.localIP());
  Serial.println("DHT22 Humidity - Temperature Sensor");
  Serial.println("RH\t\tTemp (C)\tTemp (F)\tHeat Index (C)\t Heat Index
 (F)\t Max(C)\t\t Min(C)");

  dht.begin();
  dht.readHumidity();
  dht.readTemperature();

}

float max1=dht.temperature_C;
 float min1=100;

void loop() {
  dht.readHumidity();
  dht.readTemperature();
  heatindex1=dht.computeHeatIndex_C();
  heatindex2=dht.computeHeatIndex_F();

  if(dht.temperature_C>max1)
  {max1=dht.temperature_C;}
  if(dht.temperature_C<min1)
  {min1=dht.temperature_C;}

  // Check if any reads failed and exit early (to try again).
  if (isnan(dht.humidity) || isnan(dht.temperature_C)) {
    Serial.println("DHT sensor read failure!");
    return;
  }
  if (client) {

   // When a client sends a request to a webserver, that request ends with a blank line
    boolean currentLineIsBlank = true;

    Serial.println("OK"); }

  if (client.connect(server, 80)) {
    client.print("GET /api/todo?humidity=");
    client.print(dht.humidity);
    client.print("&temperature1=");
    client.print(dht.temperature_C);
    client.print("&temperature2=");
    client.print(dht.temperature_F);
    client.print("&heatindex1=");
    client.print(heatindex1);
    client.print("&heatindex2=");
    client.print(heatindex2);
    client.print("&max1=");
    client.print(max1);
    client.print("&min1=");
    client.print(min1);// And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.println(" HTTP/1.1"); // Part of the GET request
    client.println("Host: 192.168.0.11"); // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie.Host: "www.yourwebpage.com")
    client.println("Connection: close"); // Part of the GET request telling the server that we are over transmitting the message
    client.println(); // Empty line
    client.println(); // Empty line
    client.stop();    // Closing connection to server

  }

  else {
    //If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }

   Serial.print(dht.humidity); Serial.print(" %\t\t");
  Serial.print(dht.temperature_C); Serial.print(" *C\t");
  Serial.print(dht.temperature_F); Serial.print(" *F\t");
  Serial.print(dht.computeHeatIndex_C()); Serial.print(" *C\t ");
  Serial.print(dht.computeHeatIndex_F()); Serial.print(" *F\t ");
  Serial.print(max1); Serial.print(" *C\t ");
  Serial.print(min1); Serial.println(" *C\t");

  delay(5000);
}

I don't know of this library, but you're using the connection code twice, once in the setup() and later again in the loop().
You're already checking whether the client exists:
if (client) {

Why are you asking a few lines down again to connect?
if (client.connect(server, 80)) {

My guess is, that this if()-Clause is not necessary. Or the connection in the setup() should be removed.
If this isn't the source of the error, first test whether the server on 192.168.0.11 is running and that you can connect (from a different device) to the port 80.


text:
Arduino IDE with ATtiny85 error "multiple definition of `__vector_5"
I am having a problem compiling the code for my ATtiny85 circuit.
I am using the timer/counter0 in normal mode so that when it overflows it triggers the TIMER0_OVF_vect ISR. When I have that ISR in my code, it wont compile and gives this error:
wiring.c.o (symbol from plugin): In function `__vector_5':
(.text+0x0): multiple definition of `__vector_5'
sketch\Glove_heater_v1.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board ATtiny25/45/85.

Maybe I just need to use a different name for the ISR?
My Code:

//Red LED on PB0
//Blue LED on PB1
//Pushbutton PB2
//Battery voltage divider PB3
//Mosfet control PB4

#include <avr/io.h>
#include <stdint.h>
#include <avr/interrupt.h>

volatile uint8_t checkVoltage = 0;

void setup() {

   DDRB = 0b0010011; //set PB0,PB1,PB4 as output, PB2,PB3 as input
   PORTB = 0b00000011; //set PB0,PB1 HIGH so LEDs are off, other pins LOW

   //Setup TC0 for overflow interrupt trigger
   TCCR0B |= 0b00000101; //clk/1024 prescaler
   TIMSK |= 0b00000010;  //set TOIE0 enable overflow interrupt
   sei();
}

void loop() { //do nothing in this test code

}

ISR(TIMER0_OVF_vect){ //Timer/counter0 interrupt check voltage
   checkVoltage = 1;
}

Any ideas are appreciated!

Arduino uses it for counting millis

The error message was:

wiring.c.o [...]: multiple definition of `__vector_5'
  Glove_heater_v1.ino.cpp.o [...]: first defined here

__vector_5 is TIMER0_OVF_vect. So you have one definition of this
ISR in your sketch, and another one in wiring.c. This wiring.c is part
of the Arduino core. As KIIV puts it in a comment, it uses
TIMER0_OVF_vect for timekeeping (millis(), micros() and
delay()).
You have two options for solving this:

you can use the other timer (Timer 1) in your sketch, and leave Timer
0 for the Arduino core
since you are not using the Arduino core anyway, you can get rid of it
by simply defining main() in your sketch instead of setup() and
loop().

Ah I see, thank you very much for the explanation. The final code uses both timers so, I will avoid using the Arduino core in this case.

source: Stack Exchange

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

sort: votes


text:
Arduino GPIB control
I want to control a scientific instrument with an Arduino through GPIB. I have a USB-GPIB adapter, so I would want to do it through the USB. There are tutorials on the Internet on how to connect Arduino to a GPIB instrument through pins, but I did not fid any explanation of how to do it though USB. Is there a software package I can use?

an arduino can interface to something simple like a USB keyboard or mouse ... it may have problems with interfacing GPIB through the USB ... you would be better off using something like a Raspberry Pi ... it uses Linux as an operating system ... it has the necessary hardware to make use of the USB-GPIB adapter .... the necessary software may also be available .... google linux gpib instrument to see if there is any scientific software that you could use

Is there a reason, why you want to use the USB-GPIB adapter? When there are tutorials on how to directly interface GPIB, why do you want to involve the USB interface? USB is a rather complex interface and the possible capabilities of Arduinos (depending on which version you use) regarding USB are limited.

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


text:
How to prevent counter increment when holding the button
I am a newbie and also a noobie. Kindly assist this poor boy over here.
I am looking for a way to increment a variable by one each time a button is pressed. Current approach is the following :
void buttonLoop() {
  int win = 0;
  while (win ==0) {
  display.setCursor(0, 0);
  //getButtons() function can be used to test if any button is pressed, or used like:
  //getButtons(TSButtonUpperLeft) to test a particular button, or even like:
  //getButtons(TSButtonUpperLeft|TSButtonUpperRight) to test multiple buttons
  //results are flipped as you would expect when setFlip(true)
  if (display.getButtons(TSButtonUpperLeft)) {
    display.println("Pressed!");
    score++;
    updateScore();
  } else {
    display.println("          ");
  }
  display.setCursor(0, 54);
  if (display.getButtons(TSButtonLowerLeft)) {
    display.println("Pressed!");
    score++;
    updateScore();
  } else {
    display.println("          ");
  }
  display.setCursor(95 - display.getPrintWidth("Pressed!"), 0);
  if (display.getButtons(TSButtonUpperRight)) {
    display.println("Pressed!");
    score++;
    updateScore();
  } else {
    display.println("          ");
  }
  display.setCursor(95 - display.getPrintWidth("Pressed!"), 54);
  if (display.getButtons(TSButtonLowerRight)) {
    display.println("Pressed!");
    score++;
    updateScore();
  } else {
    display.println("          ");
  }
}
}

In my case, the counter will keep increasing if I do not let go of the button. How do I make it so that the counter will only increase by 1 even if i continue holding onto the button.
Thank you for all the kind souls in this society :)

Look for the Bounce2 library in the IDE library manager.

check to see if the button was released before allowing the counter to increment again

See my answer in this thread:
How to connect Big Dome Button with arduino
That thread explains how to wire up a switch and write code that increments a counter each time a button is pressed.
The bits you care about:
Connect one lead of the switch to a digital input, and the other lead to ground.
Then set your switch pin to INPUT_PULLUP mode. Now your switch will read HIGH until it's pressed, then it will read LOW.
create a variable at the top of your code called buttonState:
byte buttonState = HIGH;

Also define an unsigned long variable nextReadMillis:
unsigned long nextReadMillis = 0;

and a pressCount variable:
unsigned int pressCount = 0;

And define a debounceTime:
#define debounceTime 50

In your loop, do something like this:
void loop() {
    //Get the new millis(value)
    unsigned long newMillis = millis();

    //only look at the new button value if enough time has elapsed.
    if (newMillis >= nextReadMillis) {
       byte newButtonState = digitalRead(buttonPin);

       //Only do something if the button state has changed
       if (buttonState != newButtonState) {
          buttonState = newButtonState;
          nextReadMillis = newMillis + debounceTime;
          //If the button is now in the pressed (LOW) state, increment the count
          if (buttonState == LOW) {
              pressCount++;
          }
       }
    }
}

That's pseudo-code. It likely has syntax errors. It's not meant to be copy/pasted. Use it as a guide for your project.
The code using millis() is a version of "software debouncing." Electrical switches tend to "jitter" or "bounce" between their on and off states very rapidly when they are first pressed/released. By only checking for state changes after a brief delay, you ignore the jitter in the readings.
You can adjust the value of debounceTime up or down a little. A value of 50 is 1/20th of a second, which should make your button presses quite responsive, but still debounce the switch well. If you find your count sometimes increases by more than one for a button press, you can increase the value to 100 or even 500, although at 500 (1/2 second) the button won't respond to really rapid presses


text:
What to use instead of a USB to serial converter
The usb to serial converter i found was $4 .maybe i could use something less expensive,like jus a port.I need serious help ,the serial port was about $1

To do what? You need to elaborate a bit more, this is to fussy!

To upload a sketch.....I don't want to use up cash without knowing what I'm doing.I've lost a lot of cash on experiments.

Any USB to Serial converter works. The only culprit is DTR, if that exist on the USB Serial, then you can program the arduino without any manual interventions, if it is missing, then you have to press the reset button before the Arduino IDE starts to upload the program, this will put your arduino in to "programming mode".

Here is a example on how a programming without DTR, https://www.youtube.com/watch?v=TFARDFn8fs0

Oh by the way there isn't a cheaper way than a USB to serial converter. If you have a Arduino UNO laying around, you could use the USB to serial converter in that one, but you have to pull out the 328 chip first. Ref.: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

You can buy a CH340 adapter board with the standard "FTDI header" pinout (including DTR/CTS for auto-reset) on eBay for $1.46 with free shipping. You can get them as low as $0.67 on Aliexpress without DTR/CTS broken out.

"the serial port was about $1" What does that mean?

May I suggest RS232 connection? It is an ancient tech but it might work for you. I am adding a tutorial. Also a component from eBay, which is 0.99 US dolar.

The usb to serial converter i found was $4 .

you can find old Nokia data cable (a form of usb/ttl converter) for less than a dollar, or free if you happen to have one.
alternaively, usbasp programmers are very simple / inexpensive.
diy is possible but you need to count your time. tools need to be reliable so i tend to rule that out.

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


text:
Arduino library not working, can't find header
I have fair experience with C/C++ so I decided to have a go at writing my first simple Arduino library. I wrote the code which seems to be fine to me except that it keeps complaining about the header file not found during compilation:
/home/me/sketchbook/libraries/SegDisplay/SegDisplay.cpp:1:24: fatal error: SegDispaly.h: No such file or directory
 #include "SegDispaly.h"
                        ^
compilation terminated.

I have the library located in my sketch folder under the name "SegDisplay":
/home/me/sketchbook/libraries/
└── SegDisplay
    ├── examples
    ├── keywords.txt
    ├── README.md
    ├── SegDisplay.cpp
    └── SegDisplay.h

and here's the code:
SegDisplay.h:
#ifndef _SEVEN_SEG_H_
#define _SEVEN_SEG_H_

#include <math.h>

#if defined(ARDUINO) && (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif

class SegDisplay
{
public:
    SegDisplay (int clockPin, int latchPin, int dataPin, int digitPins[4]);
    void display (double value);

private:
    const int digitPins[4];
    const int clockPin;
    const int latchPin;
    const int dataPin;
    const byte digit[10] = //seven segment digits in bits
    {
        B00111111, //0
        B00000110, //1
        B01011011, //2
        B01001111, //3
        B01100110, //4
        B01101101, //5
        B01111101, //6
        B00000111, //7
        B01111111, //8
        B01101111  //9
    };
    int digitBuffer[4];

    void setRegisterData (byte data);
    void clearRegister();
    void clearDisplay();
    void updateDisplay();
};

#endif

SegDisplay.cpp:
#include "SegDispaly.h"

SegDisplay::SegDisplay (int a, int b, int c, int d[4]):
    clockPin (a), latchPin (b), dataPin (c), digitPins (d), digitBuffer ({0})
{
    for (int i = 0; i < 4; i++)
    {
        pinMode (digitPins[i], OUTPUT);
        digitalWrite (digitPins[i], HIGH);
    }
    pinMode (latchPin, OUTPUT);
    pinMode (clockPin, OUTPUT);
    pinMode (dataPin, OUTPUT);
}

void SegDispaly::setRegisterData (byte data)
{
    digitalWrite (latchPin, LOW);
    shiftOut (dataPin, clockPin, MSBFIRST, data);
    digitalWrite (latchPin, HIGH);
}

void SegDispaly::clearRegister()
{
    setRegisterData (B00000000);
}

void SegDispaly::clearDisplay()
{
    // deactivate transistors
    for (int n = 0; n < 4; n++) digitalWrite (digitPins[n], HIGH);
}

//writes the temperature on display
void SegDispaly::updateDisplay()
{
    byte outByte;
    // dispaly digits
    for (int i = 0; i < 4; i++)
    {
        clearDisplay();
        clearRegister();

        // enable nth cell cathode (transistor)
        digitalWrite (digitPins[i], LOW);

        // output nth digit on display
        if (i == 1)
        {
            //print the decimal point on the 2nd digit
            outByte = digit[digitBuffer[i]] | B10000000;
        }
        else outByte = digit[digitBuffer[i]];
        setRegisterData (outByte);

        //delayMicroseconds (500);
        delay (5);

        //Serial.print (outByte, BIN);
        //if (i == 3)
        //{
        //  Serial.println (".");
        //}
        //else Serial.print (", ");
    }
}

void SegDispaly::display (double value)
{
    int n = int (value * 100);
    digitBuffer[0] = n / 1000;
    digitBuffer[1] = (n % 1000) / 100;
    digitBuffer[2] = (n % 100) / 10;
    digitBuffer[3] = (n % 100) % 10;
    updateDisplay();
}

My target AVR is Arduino Uno R3, the code used to work fine in a sketch before I decided to create a library out of it. Any help would be greatly appreciated. thanks in advance.

You spelled the header filename wrong:
#include "SegDispaly.h"

should be:
#include "SegDisplay.h"

You have also made the same mistake in the class name multiple places in SegDisplay.cpp.

you know I checked the spelling of SegDisplay several times and couldn't spot it for some reason, I must be going blind. Thanks

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


text:
YL-38 output to NodeMCU v1.0 analog input
Using a YL-38 and NodeMCU v1.0 I am trying to achieve what the first link is doing, take a soil moisture reading. I've done this on an arduino, but the conversion from an arduino nano to a nodemcu is proving difficult.
To my understanding, the nodemcu A0 pin operates from 0v-3.3v but the YL-38 analog output operates from 0-4.1v. So first off, is my understanding correct?
I struggle with hardware, so looking around I found these resources:
How to set up a simple level shifter: this setup seemed pretty much like what i wanted, but the 5v input was off
This thread was verbatim what I wanted but I am terrible with circuit math, so I couldn't solve or understand the provided formulas.
Attempt 0: Initially had sensor analog out connected to a0 on nodemcu. Saturated or dry the mcu read 1023. Thought this must be because the signal out is above the A0 mapping range.
Attempt 1: I figured I'd try out the level shifter. Wired it all up as indicated. Now my readings were 760 saturated and 765 dry.
runHygrometer(index);
delay(2000); //allow hygrometer to wake up
reading = (DEBUG) ? analogRead(HYGROMETER_READ_PIN) : 1023 - analogRead(HYGROMETER_READ_PIN);

As shown, my code does no scaling, It's a direct read (DEBUG is true here). So what gives? When using an arduino the range of readings was typically from 20 dry to 180 saturated (DEBUG false, so raw 1003 dry and 843 saturated)

To my understanding, the NodeMCU A0 pin operates from 0v-3.3v

Incorrect. The ESP8266's ADC can only measure between 0V and 1V.
You need to reduce your output voltage down to that range. How you do that very much depends on the output impedance of the YL-38.
The LM393 that the YL-38 is based around looks to have a maximum output current of 16mA. That should be enough to happily drive a simple voltage divider.  A 4.7kΩ and 1kΩ divider would give you 0 to 0.877v out from a 0-5V input.

simulate this circuit – Schematic created using CircuitLab
An alternative would be to attach an external ADC running at 5V to the NodeMCU. This would give you multiple channels of analogue input with a 0-5V range. I use the MCP3208 running over SPI (I actually bit-bang it on the ESP8266 rather than using SPI, since I haven't yet got SPI to work properly with it).  Ideally, you want a proper logic level translator for the SCK and MOSI signals to boost them to 5V. It all gets a little complex, though.

It has come to light that the NodeMCU includes a voltage divider already. For some reason they chose to use massive resistors, which give far too high an impedance for any reasonable ADC input to accurately work with.  I would suggest, if you can, removing those resistors from the board and replacing them with 4.7k and 1k resistors to form your own voltage divider. Otherwise you're going to have to use a pair of op-amps in inverting mode, one with a fractional gain, and one with unity gain (the second is to "undo" the inverting of the first one) to reduce the signal to 0-3.3V.
TBH I'd be inclined to use an external ADC anyway for this.

I thought I read that A0 has a voltage divider and feeds that signal into the ESP8266 ADC? I'm referring to the 3rd to last page on NodeMCU doc listed above.
https://randomnerdtutorials.com/esp8266-adc-reading-analog-values-with-nodemcu/
"Currently, TOUT (Pin6) has a 10-bit precision and its input voltage range is 0 to 3.3V when TOUT is connected to an external circuit."

Ugh. So it does. That's nasty. You want to remove those resistors and replace them with 4.7K and 1K. The resistors used are at least 10x too big for any normal ADC input. Far too high an impedance. You can't use another voltage divider along side it, it just won't work. Either that or you'd have to use an op-amp with a sub-unity gain (actually you'd need a pair of inverting op-amps, one with a fractional gain and one with unity gain) to buffer your signal with a low impedance output. Or use an external ADC...

So i should look into using an external ADC to convert 5v to 3.3v signals? Would that be the simplest solution?

It's the route I'd probably take, yes. In fact, right in front of me I have a D1 Mini Pro with an MCP3208 attached to it to do some current and voltage measurements...

I'm really short on IO pins, so im not sure if the MCP3002 will work for me. But can i skip ADC EX and its voltage divider and use your 4.7k/1k external ADC straight to the ESP8266's tout pin (which i think is labled just ADC in the doc)?

@DougClark Sure thing. You may want to remove the existing divider though as the lower resistor will skew your readings slightly.

Let us continue this discussion in chat.


text:
Simple Calculator
I'm trying to make a basic calculator with the Serial monitor but it doesn't seem to work.
int a;
int b;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available()) {
    Serial.println("First Number: ");
    a = Serial.read();
    Serial.println("Second Number: ");
    b = Serial.read();
    Serial.println(a + b);
  }
}

Serial.read() reads in only the first byte of the data from the serial.This is not what we want, We everything that the user has entered to be treated as an Integer and then read it into the variables. You should use Serial.parseInt() for the job.
See the modified program below:
int a;
int b;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  Serial.println("Enter the First number");
  while(!Serial.available()); // wait till the user has entered something
  a = Serial.parseInt(); // treat what the user has entered as an Integer and read the whole number
  Serial.println("Enter the second number");
  while(!Serial.available());
  b = Serial.parseInt();
  Serial.println(a+b); // Print the sum
}


text:
Unable to program Arduino mega2560?
I am using arduino mega for my application .  Board works well for a week , from yesterday it  is not programming at all , it shows me some error like timeout . What could be the problem kindly  help me to solve this.
avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM20
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "\\.\COM20": The system cannot find the file specified.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
avrdude: ser_drain(): read error: The handle is invalid.

avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

avrdude done.  Thank you.

avrdude: ser_open(): can't open device "\\.\COM20": The system cannot find the file specified. -- There's a hint right there...

Com 20 is not configured with your arduino. Go to the arduino program and I think it is on the tools tab or the one next to it. There should be a port label and it says which com port to use. Then go to device manager, then ports. Then go to properties on the port that has arduino and change that to the port the arduino program said. It should work then. This topic has been solved many times.

ya its working fine now...

I am glad to hear that.

But this problem occurs very often why?.... Now also i am getting this error what could be the problem...


text:
Using Arduino Wifi Shield to Receive Signal
I am trying to use an Arduino Uno with Arduino Wifi Shield 101 to receive a signal from phone or webpage over wifi so it will "initiate" my circuit. I was able to connect the board to wifi but am unsure on how I should continue. My main goal is to be able to send it two different commands that would run different parts of code in my arduino script. I am very new to this stuff! Thanks :)

use the arduino to serve a web page that has a button

Look for the Web Server example in the arduino IDE.  That will give you a starting point to allow you to control the arduino via a web page.  This tutorial is also very in depth : https://startingelectronics.org/articles/arduino/switch-and-web-page-button-LED-control/


text:
Read amount of I/Os in code
I want to write an Arduino code, that runs on several different Boards. The code can perform digitalRead/Write operations, but the pin number will be set from the user/outside. I want to include a check, if the selected pin exists.
Is it possible, to read the amount of I/Os (digital and analog) of the Arduino the code is currently running on, to check if the users selection is in the given range? Or is it possible to check, if a certain pin number exists?

It depends on the core, but most provide the macro NUM_DIGITAL_PINS which tells you the number of digital pins the board has.  In general this doesn't equate to the actual number, but to one more than the highest number (there are boards with gaps in the pin number sequence).
So you can use:
if (pinNumber < NUM_DIGITAL_PINS) {
    digitalWrite(pinNumber, HIGH);
} else {
    Serial.println("Invalid pin number");
}

In tandem with that you also usually have NUM_ANALOG_INPUTS.

The number of the GPIO pins available depends on how the chip is wired on the Arduino Board and which microcontroller one is running on. For example, an Arduino Uno with a ATMega328p chip has 14 Digital I/O pins, whereas an Arduino Mega 2560 with a chip has 54 digital I/O pins.


text:
Multiple Loops to control on and off LEDs
I'm new here. I have tried to write a simple code to turn LED's and light them up in specific pattern and being able to switch it off while in loop. So far I've managed to either get them constantly flashing in pattern and not responding to button or when I wrote in seperate void loops each function IDE Arduino throwing me error 'expected 'while' before 'loop1'' and I'm completely stuck and not got a clue what's the problem with code. Anyone could help?
Here's a code:
const int ledPin =  2;
const int ledPin1 = 3;
const int ledPin2 = 4;
const int buttonPin = 5;

int programState = 0;

int buttonState;
long buttonMillis = 0;
const long intervalButton = 300;

long ledMillis = 300;
const long intervalLed = 500;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(buttonPin, HIGH);
}

void loop()
{
  unsigned long currentMillis = millis();
  buttonState = digitalRead(buttonPin);

 if (buttonState == LOW && programState == 0)
  do{
   programState = 1;
    }
void loop1(){
if {programState = 1 && buttonState == HIGH}
 do  {
   programState = 2;
    ledMillis = currentMillis;
    digitalWrite(ledPin, HIGH);
    delay(200);
    digitalWrite(ledPin1,HIGH);
    delay(200);
    digitalWrite(ledPin2,HIGH);
    delay(200);
    digitalWrite(ledPin2,LOW);
    delay(200);
    digitalWrite(ledPin1,LOW);
    delay(200);
    digitalWrite(ledPin,LOW);
    delay(200);
    digitalWrite(ledPin,HIGH);
    delay(200);
    digitalWrite(ledPin1,HIGH);
    delay(200);
    digitalWrite(ledPin2,HIGH);
    delay(200);
    digitalWrite(ledPin2,LOW);
    delay(200);
    digitalWrite(ledPin1,LOW);
    delay(200);
    digitalWrite(ledPin,LOW);
    delay(1500);}
 }
 void loop2(){
 if (programState = 2 && buttonState == LOW)

 do {
  programState = 2;
    digitalWrite(ledPin, HIGH);
    delay(200);
    digitalWrite(ledPin1,HIGH);
    delay(200);
    digitalWrite(ledPin2,HIGH);
    delay(200);
    digitalWrite(ledPin2,LOW);
    delay(200);
    digitalWrite(ledPin1,LOW);
    delay(200);
    digitalWrite(ledPin,LOW);
    delay(200);
    digitalWrite(ledPin,HIGH);
    delay(200);
    digitalWrite(ledPin1,HIGH);
    delay(200);
    digitalWrite(ledPin2,HIGH);
    delay(200);
    digitalWrite(ledPin2,LOW);
    delay(200);
    digitalWrite(ledPin1,LOW);
    delay(200);
    digitalWrite(ledPin,LOW);
    delay(1500);}

 else if  (programState == 2 && buttonState == HIGH)
 do
   {

    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
  }
}
yield();
}

In addition to using the do construct incorrectly, you are also using an approach that won't work.
You generally should not use a do-while statement in Arduino. That causes your code to "stick" in the body of the do-while statement while the while condition is true, which prevents the rest of your code from executing.
You also should not use the delay() function if you need to manage timing different things at the same time. (To make a more general statement, you should not use the delay() function at all. Forget it exists.) There are rare cases (like doing one-time setup of hardware in your setup() method.) where using the delay() function is appropriate, or very short intervals like timing ultrasonic pulses, but the delay() function ALWAYS causes your program to come to a complete halt until the delay interval has passed.
You should search on "Arduino blink without delay" and study the example project you find. It outlines how to use the millis() function to keep track of timing. With that approach you can time multiple things at the same time. (You'd have multiple "fire time" variables that would remember the millis() value at which you want a change to occur, and you get that value of millis(), your code would trigger the change (toggling an LED, for example) and then update that "fire time" variable.

You are using the do function wrongly:
Like this:
do{
  programState = 1;
}

It should be something like:
do
{
  programState = 1;
} while (`some condition`);

Where some condition is a condition that repeat the parts in { and } in case some condition is true.
However, besides that, it does not make sense normally to assign a variable in a while loop as only statement, since it will be 1 after the first iteration and reassigning it again does not make the value different (programState stays at 1).
Also note that in most cases the following form is used (unless you always want the body to be executed at least once):
while (`some condition`)
{
  `statements`
}

Are you sure you need the do or while statement at all? Otherwise, try to remove the do statements and see if that is closer to what you need (I cannot map the code to your requirements). I have the feeling you want to use loops to prevent a lot of code duplication, for that you need to store the ledPin, ledPin1 and ledPin2 variables in an array and loop over them.
Another way is instead of e.g. the following code:
digitalWrite(ledPin, HIGH);
delay(200);

to create a separate function:
void setPin(int pin, int value)
{
   digitalWrite(pin, value);
   delay(200);
}

and call the function by:
setPin(ledPin, HIGH);

Now you can change all occurences of 'digitalWrite(some pin, some state); delay(200)' to the single statement above.
Also, I see there is a function yield that is not implemented.

Thank You :) I will follow Your advice and see where it takes me


text:
check if a fuse is good or bad in an ac circuit using arduino
I have a fuse in a ac circuit of which i want to check if the fuse is ok or not. I'm wishing to wire up two nodes of the fuse holder and determine the fuse status. I have a plan of notify user if the fuse is ok or not.
How can I do that using arduino?

AC and what is the voltage?

Bluntly, don't do that.  The serious challenges of doing so safely are far beyond the scope of the Arduino site.  At best, there might be some existing property of the powered equipment which you could non-invasively monitor, for example, gluing a light sensor to the exterior of the enclosure over an existing power light.  Do not attempt to make any connections from an Arduino to mains circuitry.

@MatsK 220V. I'm wishing to check the fuse of an IPS.

easy: just use a hall-effect current sensor; if the fuse is ok, there will be current.


text:
Serial monitor showing extra data
I am trying to communicate NODEMCU and Arduino Uno using Serial Communication (RX,TX) using SoftwareSerial library.
Here is my code
int count;
char reqst[] = " ";

void setup() {

  Serial.begin(115200);
  Serial.println("Ready");

}

void loop() {

 while ( Serial.available() > 0 )  {

  char inChar = Serial.read();
  reqst[count] = inChar;
  count++;

     if (inChar == '\n') {

        Serial.print("String: ");
        Serial.println(reqst);
        count = 0;
        delay(1000);

     }

 }

}

here my output in serial monitor is showing ;
String: aj
779
String: am
779
I have checked that from NODEMCU i am sending correct string but in Arduino Uno
the number "779" is coming from nowhere.
So my problem is i am not be able to execute my function according to the desired string. Can anyone tell why the number is coming below the string ?.

char reqst[] = " ";

Here you created an array two chars in length. But one of those characters must be used for the null terminator so actually it can only hold a string that's a single character long. If you write past the end of the array that will cause undefined behavior. This is likely to be the cause of the strange results you encountered. You need to size reqst[] large enough to contain any string you may receive, including the null terminator. You should add code to ensure that you never write off the end of the array and that it will always end in a null terminator.
I realize it may only be a simplified minimal example, but in the code you posted there is no need to store the incoming characters. Instead you could just print them as they are received.

Also needs to add a null to the end of the string before printing it.

thanks for the help.  the reason why i am storing the receiving string is because i will be doing string comparison operations and then do further operations using that string i have received.
Do u mean to say that i should fix the char reqst[] array size .?
can you have a look at the original code . strong apology for not sharing this one.
http://textuploader.com/d0li1
here output is
writting to radio is :
am00779
writting to radio is :
aj00779
still the 00779 is coming.

@Delta_G :guys , i hope u can see the full code given in the link in the comment above.

It's reasonable to provide a minimal code example, I just thought I'd mention it in case you weren't using the string for anything. As I said: "You need to size reqst[] large enough to contain any string you may receive, including the null terminator. You should add code to ensure that you never write off the end of the array and that it will always end in a null terminator."


text:
NRF24L01 receiving even if no data sent
I am using nRF24L01 to communicate between two micro controllers. Both are Arduino Uno.
The question i have here is , even if i do not send any data from sender to receiver , the receiver device is constantly checking for the data, and the blank data is being received per second. And also no data is received by receiver which is sent by sender.
I am sharing the code for both sender and receiver.
Please suggest me what wrong i am doing.
Receiver Code :
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

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

void setup() {

 delay(500);
 Serial.begin(9600);

 radio.begin();
 radio.setPALevel(RF24_PA_MIN);
 radio.openReadingPipe(0, 0xF0F0F0F0AA);
 radio.startListening();

}

void loop() {

   if (radio.available()) {

   radio.read(&response, sizeof(response));
   done = true;

}

if (done) {
  Serial.println(response);
}

done = false;
delay(1000);

}

Sender Code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

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

void setup() {

delay(500);
Serial.begin(9600);

radio.begin();
radio.openWritingPipe(0xF0F0F0F0AA);
radio.setPALevel(RF24_PA_MIN);
radio.stopListening();

}

void loop() {

   while ( Serial.available() > 0 )  {

   request = Serial.readString();

   Serial.println(request);
   radio.write(&request, sizeof(request));

   delay(1000);

 }
}

Comments are not for extended discussion; this conversation has been moved to chat.

I've written a code for NRF24L01+ based on the datasheet.run them on your arduino and test them.CE pin is PIN7 in arduino and CSN is PIN8 in arduino.
NRF_monitorRegisters() shows all Registers of NRF.It's nice to test your NRF
maybe it helps:
for transmitter:
#include <SPI.h>

int sending = 1;
int data = 7;

void IRQ() {
  Serial.println("STATUS register from IRQ ISR :  ");
  digitalWrite(8, 0);
  SPI.transfer(0x07);
  delay(10);
  Serial.println(SPI.transfer(0xff), BIN);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x08);
  delay(10);
  Serial.println(SPI.transfer(0xff), BIN);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x07 + 0x20);
  delay(10);
  SPI.transfer(0xff);
  delay(10);
  digitalWrite(8, 1);
}

void NRF_transmitterBegin() {

  //reading
  /*digitalWrite(8, 0);
    SPI.transfer(0x00);
    delay(10);
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);*/

  pinMode(7, OUTPUT);  //CE
  pinMode(8, OUTPUT);  //CSN
  delay(100);
  digitalWrite(8, 1);
  digitalWrite(7, 0);

  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV4);
  SPI.begin();
  delay(1000);

  digitalWrite(8, 0);   //flush TX_FIFO
  SPI.transfer(0xe1);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);   //flush RX_FIFO
  SPI.transfer(0xe2);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x07 + 0x20);
  delay(10);
  SPI.transfer(0xf0);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x00 + 0x20);
  delay(10);
  SPI.transfer(0x0e);
  delay(10);
  digitalWrite(8, 1);
  delay(10);

  /*digitalWrite(8, 0);
    SPI.transfer(0x11 + 0x20);
    delay(10);
    SPI.transfer(0x3f);
    delay(10);
    digitalWrite(8, 1);*/

  //Down for DYNPL
  digitalWrite(8, 0);
  SPI.transfer(0x1c + 0x20);
  delay(10);
  SPI.transfer(0x01);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x1d + 0x20);
  delay(10);
  SPI.transfer(0x04);
  delay(10);
  digitalWrite(8, 1);
  //Up for DYNPL

  digitalWrite(8, 0);
  SPI.transfer(0x01 + 0x20);
  delay(10);
  SPI.transfer(0x3f);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x02 + 0x20);
  delay(10);
  SPI.transfer(0x03);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x03 + 0x20);
  delay(10);
  SPI.transfer(0x03);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x04 + 0x20);
  delay(10);
  SPI.transfer(0xff);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x05 + 0x20);
  delay(10);
  SPI.transfer(0x4c);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x06 + 0x20);
  delay(10);
  SPI.transfer(0x06);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x0a + 0x20);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x10 + 0x20);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  digitalWrite(8, 1);

  attachInterrupt(digitalPinToInterrupt(2), IRQ, FALLING);
  delay(10);

}

void NRF_transmit(int whatIsData , float data , float hum) {    //hum is used just for temp&humidity
  /*
     byte 0 says what is our data:  1 -> data and humidity    2 -> movement   3 -> gas

     1(float) :   byte 1 -> integer part of temp  byte 2 -> fractional part of temp   byte 3 -> integer part of humidity    byte 4 -> fractional part of humidity    byte 5 -> %battery
     2(binary) :  byte 1 -> %battery
     3(float) :   byte 1 -> integer part of gas   byte 2 -> fractional part of gas    byte 3 -> %battery

     %battery feature is in progress ...
  */

  int byte0 = 0 , byte1 = 0 , byte2 = 0 , byte3 = 0 , byte4 = 0 , byte5 = 0;
  float buf = 0;

  byte0 = whatIsData;

  switch (whatIsData) {
    case 1: {

        byte1 = data;
        buf = data - byte1;
        byte2 = buf * 10;

        byte3 = hum;
        buf = hum - byte3;
        byte4 = buf * 10;

        break;
      }
    case 2: {

        break;
      }
    case 3: {

        byte1 = data;
        buf = data - byte1;
        byte2 = buf * 10;

        break;
      }
    default: {
        break;
      }
  }

  digitalWrite(8, 0);
  SPI.transfer(0xe1);   //flush TX_FIFO empty
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0xa0);   //write on TX_FIFO
  delay(10);
  SPI.transfer(byte0);
  delay(10);
  SPI.transfer(byte1);
  delay(10);
  SPI.transfer(byte2);
  delay(10);
  SPI.transfer(byte3);
  delay(10);
  SPI.transfer(byte4);
  delay(10);
  SPI.transfer(byte5);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(7, 1);   //CE High
  delay(1);
  digitalWrite(7, 0);   //CE Low

}

void NRF_monitorRegisters() {

  for (int i = 0; i < 30; i++) {
    digitalWrite(8, 0);
    SPI.transfer(i);
    delay(10);
    Serial.print(i , HEX);
    Serial.print(" -> ");
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);
  }
  Serial.println("");

}

void setup() {

  Serial.begin(115200);

  NRF_transmitterBegin();
  NRF_monitorRegisters();

}

void loop() {

  NRF_transmit(3 , 15.1 , 0);

  delay(1000);
}

for receiver :
#include <SPI.h>

long int lastTime = 0;

void IRQ() {

  int whatIsData = 0;
  int byte1 = 0 , byte2 = 0 , byte3 = 0 , byte4 = 0 , byte5 = 0;
  float data = 0 , hum = 0 , buf = 0;

  /*Serial.println("STATUS register from IRQ ISR :  ");
    digitalWrite(8, 0);
    SPI.transfer(0x07);
    delay(10);
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);*/

  digitalWrite(8, 0);
  SPI.transfer(0x61);
  delay(10);
  whatIsData = SPI.transfer(0xff);
  delay(10);
  byte1 = SPI.transfer(0xff);
  delay(10);
  byte2 = SPI.transfer(0xff);
  delay(10);
  byte3 = SPI.transfer(0xff);
  delay(10);
  byte4 = SPI.transfer(0xff);
  delay(10);
  byte5 = SPI.transfer(0xff);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);   //flush RX_FIFO
  SPI.transfer(0xe2);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x07 + 0x20);
  delay(10);
  SPI.transfer(0xf0);
  delay(10);
  digitalWrite(8, 1);
  delay(10);

  switch (whatIsData) {
    case 1: {

        buf = byte2;
        data = byte1 + buf / 10;
        buf = byte4;
        hum = byte3 + buf / 10;

        Serial.print("Received data from DHT22 -> temp:");
        Serial.print(data);
        Serial.print("  humidity:");
        Serial.println(hum);

        break;
      }
    case 2: {

        Serial.println("Received data from PIR -> Move detected");

        break;
      }
    case 3: {

        buf = byte2;
        data = byte1 + buf / 10;

        Serial.print("Received data from gas sensor -> %gas:");
        Serial.println(data);

        break;
      }
    default: {

        Serial.println("a problem accured");

        break;
      }
  }

}

void NRF_receiverBegin() {

  //reading
  /*digitalWrite(8, 0);
    SPI.transfer(0x00);
    delay(10);
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);*/

  pinMode(7, OUTPUT);  //CE
  pinMode(8, OUTPUT);  //CSN
  delay(100);
  digitalWrite(8, 1);
  digitalWrite(7, 0);

  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV4);
  SPI.begin();
  delay(100);

  digitalWrite(8, 0);   //flush TX_FIFO
  SPI.transfer(0xe1);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);   //flush RX_FIFO
  SPI.transfer(0xe2);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x07 + 0x20);
  delay(10);
  SPI.transfer(0xf0);
  delay(10);
  digitalWrite(8, 1);
  delay(10);

  digitalWrite(8, 0);
  SPI.transfer(0x00 + 0x20);
  delay(10);
  SPI.transfer(0x0f);
  delay(10);
  digitalWrite(8, 1);
  delay(10);

  /*digitalWrite(8, 0);
    SPI.transfer(0x11 + 0x20);
    delay(10);
    SPI.transfer(0x01);
    delay(10);
    digitalWrite(8, 1);*/

  //Down for DYNPL
  digitalWrite(8, 0);
  SPI.transfer(0x1c + 0x20);
  delay(10);
  SPI.transfer(0x01);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x1d + 0x20);
  delay(10);
  SPI.transfer(0x04);
  delay(10);
  digitalWrite(8, 1);
  //Up for DYNPL

  digitalWrite(8, 0);
  SPI.transfer(0x01 + 0x20);
  delay(10);
  SPI.transfer(0x3f);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x02 + 0x20);
  delay(10);
  SPI.transfer(0x03);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x03 + 0x20);
  delay(10);
  SPI.transfer(0x03);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x04 + 0x20);
  delay(10);
  SPI.transfer(0xff);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x05 + 0x20);
  delay(10);
  SPI.transfer(0x4c);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x06 + 0x20);
  delay(10);
  SPI.transfer(0x06);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x0a + 0x20);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x10 + 0x20);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  digitalWrite(8, 1);

}

void NRF_startListening() {

  attachInterrupt(digitalPinToInterrupt(2), IRQ, FALLING);

  digitalWrite(7, 1);   //CE High
  Serial.println("Listening started");

}

void NRF_monitorRegisters() {

  for (int i = 0; i < 30; i++) {
    digitalWrite(8, 0);
    SPI.transfer(i);
    delay(10);
    Serial.print(i , HEX);
    Serial.print(" -> ");
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);
  }
  Serial.println("");

}

void setup() {

  Serial.begin(115200);

  NRF_receiverBegin();
  NRF_startListening();
  NRF_monitorRegisters();

}

void loop() {

  /*if (millis() - lastTime > 20000) {
    NRF_monitorRegisters();
    lastTime = millis();
  }*/

}

OK.if u read Datasheet u'll found that NRF communicates with MCU by SPI.
and u can control the NRF by it's registers.
in page 48 of NORDIC Datasheet u can see all commands of NRF (for example u can write on a register with 001A AAAA witch AAAAA is address of register and in next step u'll write the registers value.)
and in page 54 u can see the registers address.

You may have reversed the wire:
RF24 radio(7, 8); //  CE,CNS

This could be a valid comment towards an answer, but it needs more explanation.  Perhaps your theory is that by not properly enabling the chip, the idle state of MISO is being read and misinterpreted as the status register showing data available.  But if that is your theory, you need to actually state it, not just leave a cryptic mention of wiring.


text:
Can the atmega328 return remainder during integer division?
When I write code like this:
int a = 7
int b = 2
int c = a/b
int r = a%b

Does the chip use the remainder while calculating c or does it redo the entire calculation?

The Atmega328 does not have an intrinsic divide instruction so one has to be implemented by a sequence of other instructions. So the chip doesn't even know about a divide instruction.

Ah, so the division itself is done by a series of assembly instructions, not just one :) Then I would hope the compiler is smart enough to save the remainder :)

Why do you need to know this? To divide by 2 the compiler merely has to shift right one, and the remainder is simply the low-order bit. These are very fast things to do. The "chip" does what it is told to do.

@NickGammon I'm solving Differential equations in real time with integers to predict the behaviour of a system and I need to know if it's worth to keep track of the remainders to account for them or not, so far it's looking like it's not worth it though, but I want to explore my options to increase accuracy :)

If using optimization, the compiler is smart enough to recognize this.
Since your example is so short, it could be optimized away entirely.
To ensure that doesn't happen, the results in c and r have to be used in some way.
Also, if a and b could never change, the values of c and r would be calculated during compilation.
Therefore, I put the calculation in its own function.
From godbolt.com, using AVR-GCC 9.2.0:
#include<stdint.h>
#include<stdio.h>

uint8_t a = 0;
uint8_t b = 2;
uint8_t c = 0;
uint8_t r = 0;

void calculate() {
    c = a / b;
    r = a % b;
}

int main() {
    a = 7;
    b = 2;

    calculate();

    printf("%d %d", c, r);
}

compiles the calculate() function into
calculate():
        lds r24,a
        lds r22,b
        rcall __udivmodqi4
        sts c,r24
        sts r,r25
        ret

The results, stored in r24 and r25 respectively, are re-used from the same division operation.

By having optimizations turned off, you are asking the compiler to not be smart. And it dutifully obeys. No one would ever compile Arduino code this way. The standard Arduino optimization level is -Os, and at this level the compiler is smart enough to optimize your code to the equivalent of return 0;.

You're right. Though even when making sure the results are used (even by the same statement), and the variables a and b are not constant, it doesn't seem to remember the remainder of the first operation directly: https://godbolt.org/z/Edzq54

Your new test is flawed again. By having a and b volatile, you tell the compiler that it should not assume their values to be stable. Thus a/b and a%b are two different divisions.

Ugh, I'm crap at this. You're right, optimization does use only one division if you make sure the variables can't change and also prevent it from calculating it all during compilation.
https://godbolt.org/z/bG4cG6

Using volatile was not a bad idea: it's a convenient way to simulate side-effects, like I/O. You just have to make sure the numbers you are dividing are not themselves volatile. See for example: https://godbolt.org/z/zGefj9

The compiler is only as smart as you provide it the necessary information.

It is good to examine code on godbolt.com. But use it wisely.
Noone should ever compile without optimizations. In the example above the code is not optimized and thus would never been used as such on a board.
The example is so artificial that the compiler optimizes it away into just 2 instructions. So the code should be representative for the intended usage.
A better godbolt would be:

#include<stdint.h>
#include<stdlib.h>

void myDiv(uint8_t * c, uint8_t * r, const uint8_t a, const uint8_t b) {
    *c = a/b;
    *r = a%b;
}

So the input is not predetermined and also the resulting numbers are returned and not thrown away. Which translates with -Os to:
myDiv(unsigned char*, unsigned char*, unsigned char, unsigned char):
        mov r27,r25
        mov r26,r24
        mov r31,r23
        mov r30,r22
        mov r24,r20
        mov r22,r18
        rcall __udivmodqi4
        st X,r24
        st Z,r25
        ret

There is the div(numerator, denominator) function in stdlib.h. This function performs a division and returns both the dividend and the remainder. It is optimized for each platform and uses the best available method to get both. In Godbolt it would look like this:

#include<stdint.h>
#include<stdlib.h>

void myDiv2(uint8_t * c, uint8_t * r, const uint8_t a, const uint8_t b) {
    div_t d = div(a, b);
    *c = d.quot;
    *r = d.rem;
}

But what surprise, with -Os the resulting assembly looks exactly the same! (I leave it to the reader to try it on godbolt).
That means, the compiler is smart enough to:
a. recognise the intention when calling division and modulo an the same operands successively.
b. will use the best available method to achieve the intended calculation for you.

EDIT after Edgar Bonet's comment:
While playing around in godbolt I made a copy-paste mistake. div only applies to int values. That makes the resulting assembly code larger as there has twice the data to be shoveld around. After changing both examples to int they look almost similar. The only difference is:
The result is stored in d first and then copied to c and r.
So the division/modulo code is more efficient in that regard as the resulting values are copied directly from the registers used in the calling convention.
https://godbolt.org/z/61exz7

Very interesting, +1
Declaring an optimization in my code gets rid of almost all the code, but declaring the variables as volatile prevents that. Even when "volatile", it still does not recognize the potential savings as such, and calculated the division twice.

if you read the assembler code carefuly you will see that it is not the case.

Sorry, I was still talking about my (close to the question) code: https://godbolt.org/z/jWqdv4

I take the code in question as a sample that shows the intention and not the question to be answered. Making everything voaltile forbids optimizations by the compiler. So there is no point in doing so and having -Os. If we stick to the exact code in question then the result would be just two instructions because the input is known at compile time, it does not change and the results of the computations are discarded.

+1. In the second example, you mean *c = d.quot; *r = d.rem;.

@EdgarBonet thank you for pointing that out.


text:
How to use ADC interrupt on STM32 blue pill
I'm currently using the STM32F1xx boards from http://dan.drown.org/stm32duino/package_STM32duino_index.json
To program my blue pill but I can’t find how to write the interrupt for the ADC. I’ve set the registers to output an interrupt when it finishes but I can’t find how to write the code for the interrupt.
I’ve tried the ”ISR(ADC_vect)” function which works for arduino, but the compiler is complaining that ”ISR” is not recognized. I’ve tried to look for the documentation for the STM32duino, but the little I could find didn’t even mention the ADC or any interrupt routines. I’ve searched though the STM32duino forum without any luck. If anyone knows how to solve this or where to find information about interrupt code for the STM32 boards I would be very happy :)

A quick google gave me void ADC_IRQHandler(){ ... }. Not sure if that's correct though, as I'm not familiar with STM32s.

@Gerben It did not work :(

As you already found, the function to override is __irq_adc() defined weakly here and bound to the interrupt vector table here.
If you've defined it and it's not working, it's probably because you got rid of the attachInterrupt() call entirely, which does more than just assign an interrupt handler; it also enables the interrupt for that ADC. So:
myADC.calibrate();
myADC.setSampleRate(ADC_SMPR_1_5);
adc_enable_irq(ADC1, ADC_EOC);
myADC.setPins(&pin, 1);

extern "C" void __irq_adc() {
// handle the interrupt
// make sure to check statuses and clear flags as shown in the default handler
}

Not sure if the extern "C" will be needed, probably will be, you'll have to check and find out.

This worked, though it only worked if I used the "attachInterrupt" on the ADC, did not seem to work using registers only :/ Maybe the attachInterrupt needs to be called to bind the __irq_adc function to the interrupt vector table? Also, extern "C" was required for it to work.

@BeaconofWierd I don't understand. You're still using the attachInterrupt() instead of overidding __irq_adc() directly? What exactly is working?

I tried to just add the __irq_adc() function, but then it was not called. When I also used the attachInterrupt() the __irq_adc() function was called. I tried to enable and disable intterupts using registers to see if that was the problem, but I was still only able to use __irq_adc() if I first called attachInterrupt() somewhere in the code. I verified that I was using the correct register to turn on interrupts by turning them off after calling attachInterrupt().

@BeaconofWierd That's weird. To be clear, you did add adc_enable_irq(ADC1, ADC_EOC); to replace attachInterrupt(), as I mentioned up there? Because with that in place, I see no difference at all with the existing attachInterrupt() call in STM32ADC.cpp. Also remember that you can't test with an empty __irq_adc(), you need to at least clear the EOC flag as shown in the default handler, else your code will seem hung. Also get rid of every other register-fiddling first.

If it still doesn't work, post your entire sketch. Think I have an STM32 around somewhere...

Ah, adding the adc_enable_ird also made it work :) Probably the better way to go than calling attachInterrupt(), when using that there seemed to be an issue where I couldn't use 1.5 cycles for the sample time, so now that's fixed too:). Worked even with all my register-fiddling ^^ Thanks a lot :) Now my sampling speed is OVER 9000!!! ;D

Ah, great. Was starting to wonder if there was other shenanigans going on in their ADC library.

I couldn't find the function being called directly, but there's a good example explaining how to attach interrupts to the ADC which works well: https://github.com/rogerclarkmelbourne/Arduino_STM32/blob/master/STM32F1/libraries/STM32ADC/examples/SingleConversionInterrupt/SingleConversionInterrupt.ino
If anyone knows the actual function being called directly that would be great to add on here, but until then this example does what I need and will hopefully help others having the same problem.

If you reverse the call stack in that example you end up with ADC1->handlers[ADC_EOC] = yourfunction; , and ADC1egs->CR1 |= (1U<<(ADC_EOC +ADC_CR1_EOCIE_BIT)); to enable the IRQ. As far as I can see.

Yeah, I followed the code back to where the function in ADC1->handlers[ADC_EOC] was run, and it was inside a function called adc_irq if I remember correctly, it was even defined with the __weak keyword, so I was sure I had the right one, but for some reason that function did not work either when I wrote my own version of it :(

first you need to enable the interrupt (I don't know if the stm32 wrapper for arduino does it or not):
NVIC_EnableIRQ(ADC1_IRQn);

then you have to write ISR as gerben said:
extern "C" void ADC1_IRQHandler()
{
    //clear ADC flag
}

extern "C" because [as far as I know] the arduino projects are C++.

Sadly it does not work with the STM32duino library :(
I did however find examples of how to attach interrupts to the ADC, for anyone looking to just to that: https://github.com/rogerclarkmelbourne/Arduino_STM32/blob/master/STM32F1/libraries/STM32ADC/examples/SingleConversionInterrupt/SingleConversionInterrupt.ino
Though I want as much speed as possible for my application so I will have to dig deeper to try to find the function that's called by the ISR itself.


text:
MemoryFree library showing Irregular Behaviour..!
I simply burned the code written below but it is showing me irregular behaviour.. as in output's last paragraph, free memory increases after a runtime allocation, how it is possible? The output is attached :
#include <MemoryFree.h>
String str="rajat";
int flag=0;
void setup()
{
  // put your setup code here, to run once:

  Serial.begin(9600); Serial.println(freeMemory(), DEC);  // print how much RAM is available.
  Serial.println("Lets Start");
}

void loop()
{
    Serial.println("");
    Serial.println("Rajat0");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat1");
    str=str+"rjt";
    Serial.println(str);
    Serial.println("Rajat2");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat3");
    Serial.println("");
      delay(1000);
}

Free memory can be found in two forms:

The free space between the heap and the stack. This is usually the
main chunk of free memory.
Heap “holes”, i.e. pieces of unallocated memory within the heap. The
presence of these holes is called “heap fragmentation”.

There are various versions of the MemoryFree library. The simplest ones
only report the main chunk between the heap and the stack. The more
sophisticated ones walk the malloc()'s free list in order to also count
the heap holes. Which approach is better? I would argue that the naive
version is fine, as heap holes is something you should not count on,
because it is never guaranteed that a particular allocation will fit in
any of those holes.
You are visibly using one of the naive versions. As you grow your
string, the object calls realloc(), which in some cases copies the
string's character array and frees the original one, potentially
creating a heap hole. Eventually, small holes can coalesce into a
larger one big enough for the next allocation, and
realloc() can end up using this large hole and freeing the chunk at
the top of the heap. When this happens, the heap shrinks, and the main
chunk of free memory gets larger, which is what freeMemory() is
reporting to you.
In summary, it's normal and expected behavior. If you want something
less surprising, use a version of the library that does count the holes.
But then you may run into a more displeasing surprise: a heap–stack
collision, or an out-of-memory condition, can happen even with loads of
memory buried inside heap holes.


text:
ESP32 documentaiont for "time.h"
I am working from the example sketch in that installed with the ESP32 Dev Module into the Arduino IDE.  It includes <WiFi.h> and "time.h".  I have a number of questions about how to use the clock that is set up with configTime using NTP. I am trying to find the documentation, but I'm having difficulty identifying exactly who is providing me the "time.h" header file, and of course, there are a lot of different time.h header files out there so googling is difficult.
Where can I find the documentation for this particular header?

Example questions:

Can the time be set manually without a WiFi connection?
Can the timezone be changed without connecting to NTP again?
Can I get the time as a Unix Time Stamp?  (Yes)
Can I arrange for a function callback at a certain time? (I'm aware I can use the timer library for this but I'm hoping for something like a callback at 4:20p every Saturday)

have you checked in the library for documentation?

time.h is provided by the compiler (more specifically the C library in use in the compiler).
I believe the xtensa-esp32 compiler uses newlib as the C library. If that is the case, the documentation is here: https://sourceware.org/newlib/libc.html#Timefns

So, time.h is not where configTime(...) is defined then?

No. configTime() is part of the ESP32 core.  https://github.com/espressif/arduino-esp32/blob/master/cores/esp32/esp32-hal-time.c#L47


text:
Why doesn't pin 19 work when powering the EzSBC Esp32 board from batteries?
I recently got an ESP32-01 Breakout and Development Board from EzSBC.com.  It is advertised as a board specifically designed for use with batteries because of it's low current draw when in sleep.
As a test I loaded the basic Arduino blink sketch onto the board using pin 19 as the built in test LED.  When I power the board from the computer through the USB connection the LED blinks as expected, but when I connect a battery accross VIN -> GND nothing happens.
What am I doing wrong?

There is a subtle design choice in this board that took be hours to figure out.
According the connection schematic the blue leg of the LS3528RGB LED is connected to IO19 through a 1k resister (R2-1).  However the power leg is connected to Vusb not 3.3V like the other RGB LED.  This means that the LED connected to IO19 is only usable when the board is connected through the micro-USB port and not when connected directly to battery.
This can be useful for programmatically reading whether the board is running on battery or USB.

so the pin works? only the on-board LED is not powered?

This can be useful for programmatically reading whether the board is running on battery or USB. -- also good for saving power when on batteries.

Juraj, that is correct.  When the USB is plugged in the pin will be pulled high by a 1k resister.  When on battery, it will be an open circuit.


text:
Does RFID-RC522 supoort tk4100 chip protocol ISO18000-2C 10 digital ID card?
I have ordered a starter kit and received RFID reader is

RFID-RC522

module with one card and tag now I need more RFID card for my project and I can't find the supported card type for my project please can any one tell me supported card types and if this card supports my device this is the card type

tk4100 chip protocol ISO18000-2C 10 digital ID number

The MFRC522 on your kit is designed to communicate with ISO/IEC 14443 A/MIFARE and NTAG cards.
Search for Mifare Classic or Mifare Ultralight or NTAG213, NTAG216 ... cards.

Thank you very much


text:
freeMemory() function from memoryfree library not returning decreased value in arduino UNO
I burned the code written below, I expect that as we declare the local variable in the loop, freeMemory() function should return decreased value. But it remains constant..! please explain why..?  The output is attached :
#include <MemoryFree.h>
void setup()
{
  // put your setup code here, to run once:

  Serial.begin(9600); Serial.println(freeMemory(), DEC);  // print how much RAM is available.
  Serial.println("Lets Start");
}
void jack();
void loop()
{
    char c=0;
    c++;
    Serial.println("");
    Serial.println("Rajat0");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat1");
    int x=0;
    x++;
    Serial.println("Rajat2");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat3");
    jack();
    Serial.println("");
    delay(1000);
}
void jack()
{
    Serial.println("jack0");
    int x=0;
    x++;
    Serial.println(freeMemory(), DEC);
    Serial.println("jack1");
}

Given your recent track of similar questions that turn around how the compiler manages memory, I very strongly recommend you start to learn the basics of AVR assembly, and then read the assembly generated by the compiler. I promise this will enlightening.

Thanks @Edgar for your kind suggestion..! :) It will be a great help if you can recommend me with some strong reference.. i.e. links, books etc.

You are assuming that, just because you created a variable, it will be stored in memory. That is often not the case.
The compiler is reasonably intelligent. And there are lots of CPU registers in the AVR core. If there is a free register available for a temporary local variable like that, why would it waste time and effort putting it into memory when it can just keep it in a register?
Also, since you don't really do anything with the variable, chances are the compiler is just throwing it away.
Marking a variable volatile will remove both those problems, and you may see different results.

Suppose CPU chooses memory to store variable..Does'nt stack variable will occupy space after they are declared..? And free memory should be decreased in the jack function w.r.t available memory before calling jack function..?

The CPU doesn't choose anything. The compiler makes that decision. If it decides the variable is only used for a short time and there is a spare register it will choose to use that register instead of allocating space on the stack. Your view of the language and compiler is too naïve.

Sorry..! I am a UG fresher.. still learning.. :).. but let say compiler chose.. ! my query if it chooses memory to store variable..Does'nt stack variable will occupy space after they are declared..? And free memory should be decreased in the jack function w.r.t available memory before calling jack function..?(& Of course if those variables will be used in some conditional operations)

If the compiler chooses to allocate memory then there are two possible scenarios. Either the memory will be allocated on the stack at the point the function is entered, or it will be allocated when the variable is first used. You should look at the assembly language the compiler produces.

Function 'jack' also does not show any difference in allocation. Since jack() is called only within this one module (known, because the program only consist of one module), and only once, the compiler can replace the function-call with the actual code of the function, saving both the space and time of a call and return.
That optimization is called "inlining" (usually only useful for instructional purposes but learning appears to be the whole point of your sketch). You can suppress the inlining by prefixing both the function and its declaration with __attribute__ ((noinline)). (Note that this attribute is specific to the gcc compilers; other compilers may provide a different way to do it, or none at all):
__attribute__ ((noinline)) void jack();

...

__attribute__ ((noinline)) void jack(){
   ... etc ...
}


text:
wifi failled connection with yun and after upgrading openwrt
I recently bought an arduino yun. When trying to connect to the router following the procedure in https://www.arduino.cc/en/Guide/ArduinoYun#toc14. After the Configure & Restart, the Arduino network shut down after a few moments but it wasn´t linked to my router.
After reading a bit about it in the internet, i upgraded it following https://www.arduino.cc/en/Tutorial/YunSysupgrade. As i found that the firmware version 1.5.3 was from 2014 https://github.com/arduino/openwrt-yun/blob/master/ChangeLog, and as Reflashing the OpenWrt-Yun image on the Yún would void warranty, i proceeded by http://nootrix.com/software/upgrade-arduino-yun-openwrt/. Everything occured as detailled there.
However now, when i turn on the yún, none network appear and the WLAN LED doesn't blink.
Thanks

Find out if the Linux system is running. Maybe you mistyped your WiFi password.
Try the Following:

connect via Ethernet check your router to see if the Yun request an IP via DHCP
If unsuccessful connect via USB and install this sketch to see if you get a command prompt maybe your network settings are messed up

Still no success?

Press the WiFi reset button for at least 30 seconds to do a reset to
factory defaults.


text:
How to get the body of an HTTP request?
I want to read a binary body datas from an HTTP POST request.
The context is that I'm making a LED strip controller and I'm currently using this code :
#include <WebServer.h>
#include <Adafruit_NeoPixel.h>

Adafruit_NeoPixel strip = Adafruit_NeoPixel(LED_COUNT, STRIP_PIN, NEO_GRB | NEO_KHZ800);
WebServer server(80);

void handleSimpleWrite()
{
    int r = 0, g = 0, b = 0;
    if (server.hasArg("red"))
        r = server.arg("red").toInt();
    if (server.hasArg("green"))
        g = server.arg("green").toInt();
    if (server.hasArg("blue"))
        b = server.arg("blue").toInt();
    strip.setPixelColor(id, r, g, b);
    strip.show()
    server.send(200,"Ok");
}

It works, but it's clearly innefficient. I want to make an API endpoint that get a binary buffer with RGB states along the request body and I can't figure out how to read this body.
Any ideas ?

this may help ... https://startingelectronics.org/tutorials/arduino/ethernet-shield-web-server-tutorial/SD-card-AJAX-XML-web-server/

esp8266 has arg("plain"). esp32 doesn't have it. can't you use plain WiFiServer?

@jsotola this library seem to be for AVR based Arduino, the header is unknow for my board
@Juraj I think that arg("plain") is stay working when looking in the source code.
I will edit libraries/WebServer/src/Parsing.cpp to fit my needs.

i send a long string of hex pairs, and it works well. use websockets instead of http to get more bandwidth.

What does efficiency mean here? -- Did you do any calculations about efficiency, if you mean speed? I mean, how fast will you change the RGB values? And how fast is the network connection? And how fast is the code you show? -- I'd leave it as is, because it is a clear and simple interface, and I assume that network and CPU are much faster than needed for this simple task.

@thebusybee you are right. I said that's not efficient because to set a different color on each LED, you need to perform an HTTP request for each LED, more than 500 in my case...

How about putting all 500 LED colors in a single POST? Even as string representation this is just a few KB, transferred in milliseconds.


text:
How to power Nodemcu using 12 volt AC to DC adapter?
I am trying to make a small project using Nodemcu. My project is WiFi controlled LED, 2 LED's will blink at the same time. I have successfully uploaded the code and it works fine using USB connection. But I want to power the Nodemcu using 12 volts 1.5 amps AC to DC adapter. I have checked it in web search but I have not found an understanding circuit. please help me out guys.

You connect the + side of the adapter to VIN pin and the - side to GND.
You have to check the maximum voltage when using the VIN pin. Probably it means you 'waste' some power (but it's from a wall wart, so it should be ok). See the remark of Flyingfenix below for heating consequences.
See this link: Power Related ESP-12E Development Board Pins, fragment 'Using a Wall Wart':

Examples: Wall-Mount-AC-Adapters
The current (1.5A) should be more than enough; the adapter's current should be higher than what is needed by the NodeMCU + circuit. So this is ok.

Thankyou Michel Keijzers. I will go ahead and try the connection today. cheers..!!

Please note that the regulator used (AMS1117 3.3V or equivalent) is a linear regulator, meaning that it "wastes" everything above 3.3V as heat. Using a 12V or above supply and loading the module's outputs/using wifi means it will run very hot - possibly even damaging it. Use, if possible, a 5V wall wart - temperatures will be much lower.

@Flyingfenix Thanks for the remark, I put a forward in my answer to your comment.

NodeMCU is not an Arduino and I've seen stories about them burning up when supplied with voltage too high.

@S.Imp Thanks for that remark, I removed the +20V as I cannot find it (anymore).

@MichelKeijzers your answer is pretty helpful. You might offer a link to 3.3V wall warts or to one of the voltage regulators mentioned here

You could just use a buck converter or linear regulator outside the NodeMCU, and power it with 5V, it will save your NodeMCU's tiny SMD components, If you look on the underside of most of these boards, the given maximum is 10V and recommended 5V


text:
Arduino expected ':' before '{' token
I wanted to compile a project yesterday which always worked until now. Probably since an adjustment of the libraries (update) I have not been able to do this anymore. I ask for help.
ERRORMESSAGE:
exit status 1
expected ':' before '{' token
Line from Error
#define MSG_PRINT(...) { MSG_PRINTER.print(__VA_ARGS__); }

With all those compile errors in here, we should consider renaming from Arduino to Does-Not-Compile. - Have you even tried to google how to define function-like macros and how to use them?

what is the value of MSG_PRINT(...) after the #define directive  is evaluated?

What comes in your code just before you use MSG_PRINT?

MSG_PRINT is a macro.  It gets replaced in your code verbatim before compilation.
The error message will give you more information. Specifically it will tell you where the error is. For example:
/tmp/untitled1/untitled1.ino: In function 'void loop()':
/tmp/untitled1/untitled1.ino:1:24: error: expected ':' before '{' token
/tmp/untitled1/untitled1.ino:12:13: note: in expansion of macro 'MSG_PRINT'

Here I have defined MSG_PRINT at line 1, which is where it "says" the error is. However that's only where the macro is. The actual error is at line 12, where the error says the macro is being expanded. That's the last line in the error message.
The little bit of code I used to trigger that error is actually a switch command where I deliberately omitted the : at the end of a case statement:
    switch (v) {
        case 3 // <---- missing colon here
            MSG_PRINT("foo");
            break;
    }

If we replace MSG_PRINT as the preprocessor would we end up with:
    switch (v) {
        case 3
            { Serial.println("foo"); }
            break;
    }

(I defined MSG_PRINT to just call Serial.println...) and now we can better see the context of the error.
With the expansion now in place it is obvious that there is indeed a : missing before a {, even though that { isn't immediately visible in your code.
Learning to interpret these sometimes cryptic error messages is key to working with C and C++.


text:
IF, ELSE IF functions not working with analogRead
not sure what is going wrong in the code below, but it's a simplified code of a larger piece I'm trying to debug. I notice that the code seems to skip to the else statement even though the if statement is valid.
Potential is set to analogRead(A0)
while (potential < 1023) {
Serial.println(analogRead(A0));
if (potential < 1023) {
  if (potential > 200) {
    Serial.println("cool");
  } else {
    Serial.println("low");
    lcd.print("hello");
    delay(1000);
  }
}

Results in serial monitor show
235
low
324
low

I've also tried if (potential < 1023 && potential > 200) and if ((potential < 1023) && (potential >200)) to no avail.
Can anyone help, let me know what's going wrong or suggest a fix to this?

Did you forget to read into the variable?

Indeed, the comparison appears to be based on an old value (or maybe an initial 0), not the new value you are printing but never assigning to "potential".  You should probably do the analog read to potential and print that, rather than directly print the return value.

@ChrisStratton and Ignacio
Thanks guys, I added the variable into the while loop and it worked

If in while loop, analogRead needs to be reassigned so it is constantly read.
int potential = analogRead(A0);

void setup() {
  while (potential < 1023) {
    potential = analogRead(A0);
    ...
    }
}

Thanks guys for the help!

I'm not sure what you're trying to achieve with that while.
But this will result in none of your other code being executed until potential is above 1022, which sound rather weird. (Unless it's for some kind of safety mechanism).
The problem is that you do send the new value over serial.
But you do not assign that new value to the variable 'potential'.
Basically, you see something completely different as what is actually happening.
You should do Serial.println(potential); to be sure that you print the value of 'potential'.
And you should assign the analogRead(A0); to your variable potential.
I've also taken away the while since I think it would be misplaced. And I worked around it, so it doesn't block your complete sketch.
void loop() {
  potential = analogRead(A0));
  Serial.println(potential);

  if (potential < 1023) {
    if (potential > 200) {
      Serial.println("cool");
    } else {
      Serial.println("low");
      lcd.print("hello");
      delay(1000);
    }
  }else{
    //Code that won't run if potential < 1023
  }

  //Other code that can run "simultaniously".
}

Thanks for the answer, I'd like to explain a bit more about what I'm trying to achieve.
I want to make sure it doesn't go on to the next part of the code till the potentiometer has been turned all the way to the end (1023). So the whole chunk in my question was part of void setup actually, which also explains why I needed the while for the loop.
I set potential as a global variable, do I need to define it again in the setup scope?

Hi Paul,
I reintroduced the variable into the while loop and it worked.

@Sarahhyy Ah, okay, that other part of the code wasn't shown before ;)
Please consider accepting this as an answer, if it solved your problem.


text:
Which motors to choose?
I don't know if this is the right place to ask, but I'm an arduino newbie and I'm seeking some suggestions.
For my Robotics subject at University, I'm going to build a robot that should be able to move some objects (dragging them on the ground, not lifting them) from one place to another. I was looking around the web for the necessary components when I stumbled on a doubt: are 3-6V motors powerful enough for the wheels? Or do I need something more powerful like the 12V motors?
I'm not sure of what to choose between step motors or servo motors either, what do you suggest?
Oh and last thing, I opted for a L293D bridge driver for the motors, is this a good idea?
Thanks in advance!

Robotics Stackexchange would be better for this question.  I suggest deleting it here and adding it there.

A 12 volt DC motor is good for dragging items, but then again it depends on the items weight. Stepper is used for millimeter precision, like 3D printing. Servo is an DC motor with precision for 180 degree movement, like robot arms. If the moving object is over 1kg you should look into geared DC motors or even the stronger brushed motors, or geared brushed motors. Whats the max weight?

We still don't know yet, the professor did not give the full specifications yet. They should be simple balls of about 7/10 cm diameter, so they will be definetly under 1kg weight

You need to size your motors correctly depending on how much load they are expected to overcome. You first consideration should be how much maximum force would your robot need to exert at any given time....
For a robot just starting to drag a load (assuming the surface is flat) behind it, the robot would have to at least apply a force just greater than...
Maximum Static Frictional Force due to Robot's own weight on its wheels + Maximum Static Frictional Force due to object being dragged.
Maximum Frictional Force = Normal Force (weight) * coeff of Friction for the two surfaces
So for example, the coeff of friction between a brick (load) and ice (surface) would be lesser than between a brick (load) and asphalt (surface).
You need to do these calculations first.
If the speed limitations of your robot are inconsequential, then you only need to choose your wheel size and then determine how much torque your motor needs to be able to generate.
You do this like so.....Motor Torque needed = Force to generate / (radius of wheel * number of motors you want to install). So for instance, the torque needed per motor in a 4WD robot would be half that needed for an equivalent robot with only 2 powered wheels.
Once you have the motor torque you need, you can choose a motor and then choose a suitable power source for this motor.
Now repeat ALL the steps above this time accounting for the weight of the motors and the battery.


text:
MPU6050 acceleration values not 16-bit?
I'm looking at the little code snippet from this (many other projects also use similar code):
void loop(){
 mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

 ax = map(ax, -17000, 17000, -1500, 1500);
 ...

If my reading is correct, it's assuming the value of ax to be between -17000 and 17000. But isn't the value supposed to be 16-bit? If so, shouldn't the range be wider than -17000, 17000? Is the value capped?
Any thought appreciated.

The ADC for the accelerometer is 16 bit, yes. Also the data being sent out is in 16 bit format.
But what you are confusing is resolution and range.
The accelerometer can be programmed to have a sensitivity of 2g, 4g, 8g or 16g.  With it set to the least sensitive, that is 2g, the full range of -32768 to +32767 would equate to ±2g.
That's fine when you're measuring G-forces of up to 2g, but when all you are sensing is tilt then there is only 1g - the 1g the Earth exerts on it.
That 1g is half the 2g range, which is -16384 to +16363.  So round that up and give a little extra headroom to your calculations, and you get -17000 to +17000. It gives enough range in your calculations to give the full ±1g range "plus a little bit".

Very good point! So, suppose I'd like to detect when a rod rotating about the x axis is being accelerated too much (eg 1m/s^2), should I be using the accelerometer or gyro values? I'm guessing it might be gyro since accelerometer measures linear acceleration and I might want instantaneous angular accelerations?

Actually, isn't 2g the most rather than the least sensitive? At 2g, it could pick up more refined changes in acceleration than at 16g.

That's what I meant, yeah. Most sensitive, or least attenuated.

No, the map() function does not cap it's input or output, you would
need constrain() for that. With map() alone, there is no assumption
about the range of the values, other than the calculation not
overflowing 32-bit integers. Thus,
ax = map(ax, -17000, 17000, -1500, 1500);

simply multiplies x by the ratio 1500/17000. It is mathematically
equivalent to
ax = map(ax, 0, 34, 0, 3);

or to
ax = ax * 3L / 34;

C.f. the documentation of map().


text:
MacOS 10.15.1 Catalina CU port always busy, and TTY port not selectable
I am trying to use an FTDI breakout board to connect to my custom made Arduino compatible board. I am using a new 16 inch macbook pro with USB-c ports, so I am using a dongle, in case that could be the problem.
Every time I try and upload a sketch I get the error: "can't open device "/dev/cu.usbserial-D306P6WW": Resource busy". When I check the /dev/ folder, both "/dev/cu.usbserial-D306P6WW" and "/dev/tty.usbserial-D306P6WW" show up, however in Arduino IDE I can only choose the "/dev/cu.usbserial-D306P6WW" option. I have installed FTDI VCP drivers, CH340 drivers and all kinds of other drivers to try and fix this issue. I have restarted countless times, and I have used a multitude of commands to check for programs hogging the usb port, but there is never a program. Plugging a harddrive into the same port causes no problems, so the port can't really be the problem. I am using a "FTDI FT231XS" board from Sparkfun.

Do you have the Arduino serial monitor opened in parallel? Also, from where do you have the FTDI drivers? Have you unloaded the mac os kernel drivers before that?

I don't have the serial monitor open. I downloaded the FTDI drivers from their website, and I have not unloaded any drivers? Do I need to do that?

Hm actually I confused it with the CH340 installation process (https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver). But that shouldn't be used for such a recent Mac OS version; also you don't need it because you don't have a CH340 chipset. If you followed https://learn.sparkfun.com/ftdiDriversMac you should be good. Can you open a root terminal and edit your question to include the output of kextstat | grep FTDI? Unplug and replug the FTDI board and post the recent dmesg output starting at the unplugging of the USB device.

Thanks for your help, I tried a whole bunch of other things, and then decided I would update my Mac version. For some mystical reason this actually fixed the problem?! Thanks anyway!

Nevermind, updating my MacOS version to 10.15.3 magically fixed the problem...


text:
Error compiling for board NodeMCU 1.0
i tried compiling a program to upload sensor readings that i connected with my ESP8266 to cloud (in my case, Antares) but i keep getting this error message. Can anyone tell me where the problem is, and what do i need to do to get it fixed ?
At first i thought it was because come incompatibility with my older version of Arduino IDE, so i updated to the latest version of it, but nothing changed.
Im kinda new here, so any suggest might help. Thank you!
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"
C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp: In member function 'void AntaresESP8266HTTP::get(String, String)':
C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp:202:23: error: 'class WiFiClientSecure' has no member named 'setCACert_P'
 bool res = client.setCACert_P(caCert, caCertLen);

                   ^

C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp:222:16: error: 'class WiFiClientSecure' has no member named 'verifyCertChain'
 if (client.verifyCertChain(_serverNoHttp)) {

            ^

C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp: In member function 'String AntaresESP8266HTTP::getRaw(String, String)':
C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp:274:23: error: 'class WiFiClientSecure' has no member named 'setCACert_P'
 bool res = client.setCACert_P(caCert, caCertLen);

                   ^

C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp:294:16: error: 'class WiFiClientSecure' has no member named 'verifyCertChain'
 if (client.verifyCertChain(_serverNoHttp)) {

            ^

C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp: In member function 'void AntaresESP8266HTTP::send(String, String)':
C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp:439:23: error: 'class WiFiClientSecure' has no member named 'setCACert_P'
 bool res = client.setCACert_P(caCert, caCertLen);

                   ^

C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp:459:16: error: 'class WiFiClientSecure' has no member named 'verifyCertChain'
 if (client.verifyCertChain(_serverNoHttp)) {

            ^

C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp: In member function 'void AntaresESP8266HTTP::sendRaw(String, String, String)':
C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp:512:23: error: 'class WiFiClientSecure' has no member named 'setCACert_P'
 bool res = client.setCACert_P(caCert, caCertLen);

                   ^

C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp:532:16: error: 'class WiFiClientSecure' has no member named 'verifyCertChain'
 if (client.verifyCertChain(_serverNoHttp)) {

            ^

C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp: In member function 'void AntaresESP8266HTTP::getLatestTest(String, String)':
C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp:688:40: error: no matching function for call to 'WiFiClient::connect(String&, uint16_t&)'
 if(client.connect(_server, _portNum)) {

                                    ^

C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp:688:40: note: candidates are:
In file included from C:\Users\LENOVO\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.3.0\libraries\ESP8266WiFi\src/ESP8266WiFi.h:39:0,
             from C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.h:5,

             from C:\Users\LENOVO\Documents\Arduino\libraries\antares-esp8266-http-master\src\AntaresESP8266HTTP.cpp:1:

C:\Users\LENOVO\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.3.0\libraries\ESP8266WiFi\src/WiFiClient.h:47:15: note: virtual int WiFiClient::connect(IPAddress, uint16_t)
virtual int connect(IPAddress ip, uint16_t port);
           ^

C:\Users\LENOVO\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.3.0\libraries\ESP8266WiFi\src/WiFiClient.h:47:15: note:   no known conversion for argument 1 from 'String' to 'IPAddress'
C:\Users\LENOVO\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.3.0\libraries\ESP8266WiFi\src/WiFiClient.h:48:15: note: virtual int WiFiClient::connect(const char*, uint16_t)
virtual int connect(const char *host, uint16_t port);
           ^

C:\Users\LENOVO\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.3.0\libraries\ESP8266WiFi\src/WiFiClient.h:48:15: note:   no known conversion for argument 1 from 'String' to 'const char*'
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

please format the printout ... put these three symbols  ``` on a blank line before the printout ... same after the printout ... make sure that there is nothing else on the line

check the esp8266 core version in Boards Manager

As noted by @Jurajj, You’re working with an old ESP8266 Core version (2.3.0 is from 2016). Update it and try again (and it would be nice if you could report back here).

It turned out that the ESP8266 core version that i had installed is obsolete, so i installed the esp8266 core version 2.7.4 and the compiling works just fine. Thank you so much everyone for the help ! :D


text:
NodeMcu Communication to RS485 Device using TTL to RS485 converter

Good day everyone,
           I am facing a problem when trying to use nodemcu  (Nodemcu ESP8266 Lolin V3) to communicate with an RS485 device. I sent an enquiry frame to the device and got the response in bytes. However, the response is not meaningful as it cannot be converted to readable ASCII characters.

           I used the built in Serial for this purpose. Hence i debug the program by sending the program flow state and data received to a server as shown in the Web UI below :-

The response that i expect is the ASCII bytes:-
AFC54D48355CC030B14ED8D4B459

which is completely different than what is shown in the Web UI above.
Here is the connection and the code that i have tried so far:-

The code :-
#include<ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

int enable_pin = 5; //DE and RE pin is jumped together to Nodemcu D1 pin.

String link = "http://someserver.ngrok.io"; //the server

void setup() {
  pinMode(enable_pin,OUTPUT);
  sendActivity("baud_rate_is_set");
  Serial.begin(9600);
  delay(2000);
  digitalWrite(enable_pin,HIGH); //mcu - master : meter - slave
}

void loop() {
  int timeout = 5000;
  int delay_unit = 100;
  byte request[] = {0xb7,0xb7,0xaf,0x3f,0x30,0xb7,0xb4,0xb4,0x36,0x33,0x35,0xb1,0x21,0x8d,0x0a};
  sendActivity("send_enquiry_frame");

  //write
  Serial.write(request,sizeof(request) / sizeof(request[0]));
  digitalWrite(enable_pin,LOW);

  //delay & timeout
  sendActivity("start_waiting_5s");
  int current_delay = 0;
  while(current_delay <= timeout)
  {
    current_delay = current_delay + delay_unit;
    delay(delay_unit);
  }
  sendActivity("done_waiting_5s");

  //get the response part
  if(Serial.available())
  {
    sendActivity("serial_data_available");
    byte serial_receive_buff[200];
    Serial.readBytes(serial_receive_buff,200);
    char buff[200];
    array_to_string(serial_receive_buff,200,buff);
    sendResponse(buff);
  }
  else{
    sendActivity("serial_data_not_available");
  }
  delay(3000);

}

void sendActivity(String act)
{
  HTTPClient http;
  http.begin(link+"/api/activity/"+act);
  int code = http.GET();
}

void sendResponse(String data)
{
  HTTPClient http;
  http.begin(link+"/api/data/"+data);
  int code = http.GET();
}

void array_to_string(byte array[], unsigned int len, char buffer[])
{

    for (unsigned int i = 0; i < len; i++)
    {
        byte nib1 = (array[i] >> 4) & 0x0F;
        byte nib2 = (array[i] >> 0) & 0x0F;
        buffer[i*2+0] = nib1  < 0xA ? '0' + nib1  : 'A' + nib1  - 0xA;
        buffer[i*2+1] = nib2  < 0xA ? '0' + nib2  : 'A' + nib2  - 0xA;
    }
    buffer[len*2] = '\0';
}

Can anyone point out what i messed up ? I am stuck on this problem for few days. Thanks a lot.

I can get an ASCII string if i convert the bytes

i forgot to mention that the expected byte after some conversion should be "/EMH5@01NXT4Y". What i actually get when trying to convert the response from the rs485 interface did not yield this.