text:
Sending a string from Arduino to ESP8266 works on UNO but not on Pro Mini

I have a project where I am getting sensor data and sending it over to an ESP8266-01 to send to ThingSpeak. After some work I got it to work. So like a real smart person I decided to replace the Arduino UNO I was using (that worked) with an Arduino Pro Mini. Using the same code and connections the String isn't sent to the ESP and then not to ThingSpeak.
Here is a reduced version of the sending code that I used on the UNO and the Pro.
#include <FS.h>
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
#include <EEPROM.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>
//#include <SoftwareSerial.h>

//SoftwareSerial espSerial(A0, D1); // RX | TX
//stuff to bring in string
const byte numChars = 32;
char receivedChars[numChars];
char tempChars[numChars]; // temporary array for use when parsing
// variables to hold the parsed data
char messageFromPC[numChars] = {0};
float floatFromPC = 0;
float floatFromPC2 = 0;
boolean newData = false;
//end stuff ti bring in string
String f;
String start = "start";
//NEW STUFF START
char Password[36] = "";
char apiKey[16] = "";
WiFiClient client;
//eeprom new end
char defaultHost[100] = "";
//Thing Speak IP address (sometime the web address causes issues with ESP :/
long itt = 500;
long itt2 = 500;
const byte wifiResetPin = 13;
int interruptPinDebounce = 0;
long debouncing_time = 1000;
volatile unsigned long wifiResetLastMillis = 0;
bool shouldSaveConfig = false;

void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}

void handleWifiReset() {
  if (millis() < wifiResetLastMillis) {
    wifiResetLastMillis = millis();
  }
  if ((millis() - wifiResetLastMillis) >= debouncing_time) {
    Serial.println("Clearing WiFi data resetting");
    WiFiManager wifiManager;
    wifiManager.resetSettings();
    SPIFFS.format();
    ESP.reset();
    delay(1000);
  }
  wifiResetLastMillis = millis();
}
int addr = 0;
void setup() {
  //EEPROM.begin(512); //Initialize EEPROM
  WiFiManager wifiManager;
  Serial.begin(9600);
  //espSerial.begin(115200);
  pinMode(wifiResetPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(wifiResetPin), handleWifiReset, FALLING);
  WiFiManagerParameter customAPIKey("apiKey", "ThingSpeakWriteAPI", apiKey, 16);
  //END NEW STUFF
  //WiFiManager
  //Local initialization. Once its business is done, there is no need to keep it around
  //WiFiManager wifiManager;
  //NEW STUFF START
  //wifiManager.setSaveConfigCallback(saveConfigCallback);
  wifiManager.addParameter(&customAPIKey);
  //END NEW STUFF
  //reset saved settings
  //wifiManager.resetSettings();
  //set custom ip for portal
  //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
  //fetches ssid and pass from eeprom and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  wifiManager.autoConnect("AutoConnectAP");
  Serial.println("Connected");
  //NEW STUFF START
  strcpy(apiKey, customAPIKey.getValue());
  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["defaultHost"] = defaultHost;
    json["apiKey"] = apiKey;
    Serial.println("API");
    Serial.print(apiKey);
    String apiKey2 = String(apiKey);
    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }
    json.printTo(configFile);
    json.printTo(Serial);
    delay(1000);
    configFile.close();
    //end save
  }
  Serial.println("local ip");
  Serial.println(WiFi.localIP());
  //END NEW STUFF
  //or use this for auto generated name ESP + ChipID
  //wifiManager.autoConnect();
  //Serial.println("WriteApi");
  //Serial.println(apiKey);
  //if you get here you have connected to the WiFi
  //Serial.println("K)");
  //save the custom parameters to FS
  strcpy(apiKey, customAPIKey.getValue());
  EEPROM.begin(512); //Initialize EEPROM
  // write appropriate byte of the EEPROM.
  // these values will remain there when the board is
  // turned off.
  EEPROM.write(addr, 'A'); //Write character A
  addr++; //Increment address
  EEPROM.write(addr, 'B'); //Write character A
  addr++; //Increment address
  EEPROM.write(addr, 'C'); //Write character A
  //Write string to eeprom
  String www = apiKey;
  for (int i = 0; i < www.length(); i++) {
    //loop upto string lenght www.length() returns length of string
    EEPROM.write(0x0F + i, www[i]); //Write one by one with starting address of 0x0F
  }
  EEPROM.commit(); //Store data to EEPROM
  //Read string from eeprom
}

//callback notifying us of the need to save config
void loop() {
  //new stuff string
  recvWithStartEndMarkers();
  if (newData == true) {
    strcpy(tempChars, receivedChars);
    // this temporary copy is necessary to protect the original data
    //   because strtok() used in parseData() replaces the commas with \0
    parseData();
    showParsedData();
    newData = false;
  }
  //new stuff string end
  WiFiManager wifiManager;
  if (WiFi.status() == WL_DISCONNECTED) {
    wifiManager.autoConnect("AutoConnectAP");
  }
  delay(1000);
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("Connected");
    delay(1000);
    WiFiClient client;
    long itt = 50;
    long itt2 = 200;
    char defaultHost[100] = "api.thingspeak.com";
    EEPROM.begin(512);
    Serial.println(""); //Goto next line, as ESP sends some garbage when you reset it
    Serial.print(char(EEPROM.read(addr))); //Read from address 0x00
    addr++; //Increment address
    Serial.print(char(EEPROM.read(addr))); //Read from address 0x01
    addr++; //Increment address
    Serial.println(char(EEPROM.read(addr))); //Read from address 0x02
    //Read string from eeprom
    String www;
    //Here we dont know how many bytes to read it is better practice to use some terminating character
    //Lets do it manually www.circuits4you.com  total length is 20 characters
    for (int i = 0; i < 16; i++) {
      www = www + char(EEPROM.read(0x0F + i)); //Read one by one with starting address of 0x0F
    }
    Serial.print(www); //Print the text on serial monitor
    if (client.connect(defaultHost, 80)) { // "184.106.153.149" or api.thingspeak.com
      itt++; //Replace with a sensor reading or something useful
      String postStr = www;
      postStr += "&field1=";
      postStr += String(floatFromPC);
      postStr += "&field2=";
      postStr += String(floatFromPC2);
      postStr += "\r\n\r\n\r\n";
      client.print("POST /update HTTP/1.1\n");
      client.print("Host: api.thingspeak.com\n");
      client.print("Connection: close\n");
      client.print("X-THINGSPEAKAPIKEY: " + String (www) + "\n");
      client.print("Content-Type: application/x-www-form-urlencoded\n");
      client.print("Content-Length: ");
      client.print(postStr.length());
      client.print("\n\n\n");
      client.print(postStr);
      Serial.println("% send to Thingspeak");
    }
    client.stop();
    Serial.println("Waiting…");
  }
  delay(5000);
}

//more new stuff for string
void recvWithStartEndMarkers() {
  static boolean recvInProgress = false;
  static byte ndx = 0;
  char startMarker = '<';
  char endMarker = '>';
  char rc;
  while (Serial.available() > 0 && newData == false) {
    rc = Serial.read();
    if (recvInProgress == true) {
      if (rc != endMarker) {
        receivedChars[ndx] = rc;
        ndx++;
        if (ndx >= numChars) {
          ndx = numChars - 1;
        }
      } else {
        receivedChars[ndx] = '\0'; // terminate the string
        recvInProgress = false;
        ndx = 0;
        newData = true;
      }
    } else if (rc == startMarker) {
      recvInProgress = true;
    }
  }
}

void parseData() { // split the data into its parts
  char * strtokIndx; // this is used by strtok() as an index
  strtokIndx = strtok(tempChars, ","); // get the first part - the string
  strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC
  strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
  floatFromPC = atoi(strtokIndx); // convert this part to an integer
  strtokIndx = strtok(NULL, ",");
  floatFromPC2 = atoi(strtokIndx); // convert this part to a float
}

void showParsedData() {
  Serial.print("Message ");
  Serial.println(messageFromPC);
  Serial.print("Float ");
  Serial.println(floatFromPC);
  Serial.print("Float ");
  Serial.println(floatFromPC2);
}
//end new stuff string

Sorry for the length but... I don't know if I need to modify how I send the string or I have to turn on the TX and RX pins in the Pro Mini. I have tried connecting the RX Arduino to TX ESP and TX Arduino to RX ESP and RX to RX and TX to TX with no results. I know the pins work because I have programmed the ESP and the PRO numerous times with the TX and RX pins.
Can anyone help me with this? It is driving me crazy.

Are you using the same connections between the ESP and either Arduino? Cross-connecting RX/TX is correct. The Uno is a 5v device; the ESP is a 3.3v device. The Pro-mini could be either. Did you use level shifters or equivalent with the UNO? Does the Pro-mini both need & use them (5v Pro-mini) or not need and not use them (3.3v Pro-mini)?

So I tried some experiments.  I had an adapter module attached to the ESP so I removed it and wired directly to the ESP.  I went from the Pro's board pins both RX to TX and TX to Rx and the other way around with no upload, no flashing tx led on board I also tried from the header pins at the end of the board both T

sorry hit return here is the end of the previous comment  TX to RX and RX to TX and visa versa.  But with no better results.  I usually use level shifters but didn't for the experiment on the Arduino Uno and the Arduino Pro Mini.  Without the shifter it worked with the UNO and not the Pro Mini.  So I don't think it is the pin connections.

Something about you Pro-min is different from you Uno. (Operating voltage? Frequency? Baud-rate selection?) We don't have enough information (yet) to know what it is, but that's the direction you'll need to take.

So the ESP is running off a separate voltage regulator 3.3v.  I have tried all kinds of baud rates on both Pro and ESP.  The ESP is supposed to run at 115200 and when I try to reset it it says that the 115200 baud rate is overridden with 115200 but what ever rate I put in the code to override I have to set the serial monitor to that rate to have it read correctly.  The Pro says its normal rate is 57600 but I have tried to reset it and nothing seems to help.  I need a definitive answer.  Is the TXO on the Pro board go to the RX on the ESP and RXI to TX.  this is how I have it set up.

Here is a print out of the upload form computer to Pro Mini               Using Port                    : /dev/cu.usbserial-00000000                          Using Programmer              : arduino                                                          Overriding Baud Rate          : 57600                                                               AVR Part                      : ATmega328P

You have the Tx->Rx and Rx->Tx connections correct (called "cross-connected"). "Overriding baud rate...etc" is correct during upload. The boot-loader sets a known baud-rate for uploading, and avrdude on your PC sets the PC's baud-rate to that same value. The word "overriding" is confusing here but just means that during upload, it won't be using the last rates you left them at. ...

... Still wondering though, how your Uno and Pro-mini are different. Is each of them a 5v device? Is/was the Arduino & ESP grounds connected to each other? Is/was the ESP being powered by the Arduino's 3.3v power pin (it shouldn't be)? Is the Arduino Tx -> ESP RX connected via either a voltage divider or a level converter (it must be, but the reverse connection, ETx -> ARx, is OK without). Is Arduino using the UART on pins [1,2] or SoftwareSerial (If SS, you'll need to keep your baud rates down to 9600)? A schematic of your power & communication connections would help.

UNO and Pro are both 5v.  the UNO and the ESP both have common ground and when originally hooked up the UNO is powered by a battery source that has booster to 9v put into Vin pin.  The ESP is powered by the 9v going through a 3.3 v regulator.  On the Pro it is powered by by the 9v booster going to a 5v regulator then into 5v vcc pin to power the board the ESP is powered by going thru 3.3v regulator.  relay is turned on for a brief time to power the ESP with the 3.3v on both so as to save power.  9v going into UNO I think is regulated down to 5v.  I can't think of anything else. both are 16 htz

If I re-read your post correctly, the connection, Arduino Tx -> ESP Rx, is direct-wired. But the Arduino's 5v is too high for the ESP and may have damaged its Rx pin driver. Does Uno still work? All I can do more is repeat that you or we need schematics of the working- and non-working systems and a more detailed problem description than "... it works great on the Arduino UNO but not on the Arduino Pro Mini". Tough problems need taking a step back and applying a rigorous, complete, and step-by-step analysis. Pls upd your ques with schematics, & clear description of how they behave differently.

Each time I changed baud rate I reprogrammed ESP using RX-TX so they are working fine. I have read that over long exposure it could fry them but for short periods it is ok. One I have this figured out I will put them in. The PRO I am using is a knock off so that could be it. I have ordered a genuine one from SparkFun and will swap it out when it gets in. I am uploading two wiring diagrams

The one difference I see between your two schematics is that the Uno uses its on-board 5v regulator and your external 5v regulator seems to have no function. The Pro uses your external 5v regulator. Why the difference? Have you tried supplying the Pro's Vin/Raw input with 9v as you do the Uno? I have no idea why this should be problematic; it's just a difference I see, that I would rule-out. I'd also make the reverse experiment and compare either MCU board being supplied at its Vin from your external regulator.

I will try that. The raw input on the PRO voltage regulates to 5v so I didn’t think there should be a difference. Is there a way to program the ESP8266 using the Arduino PRO MINI like I do the UNO. that way I would know if the RX TX on PRO board is working.

You should be able to do anything with the Pro that you can with the Uno. But didn't you say you were able to do that (2nd to last sentence of your posting)?

I program the ESP with the UNO then switch it over to the Pro. I am on the road right now but will try it when I get home. Can’t see why the change in voltage input should make a difference

I tried hooking up the 9vdc to the raw and disconnecting the 5vdc to the VCC. The PRO shows it has power by the red led but the pins don’t seem to work. At least the #2 pin doesn’t come on when it is supposed to. If I disconnect the 5v and plug in the header power the #2 pin doesn’t respond like it should. I think the board is messed up. I will attempt to remover and replace it. Any suggestions on removal.

Today I installed a new Arduino Pro Mini and programmed it. The hookup now is the same as with the Arduino UNO shown above. 9v goes to raw input. When connected to the battery everything works as it should except the sensor numbers are NOT transmitted from the Pro to the ESP. I am going to try connecting TX-TX and RX-RX. but I don’t think that will work. Could it be that when I send the numbers from the Pro to the esp, the esp starts broadcasting before it receives the sensor numbers?  Should I have it run longer to see if it gets the numbers for the 2nd broadcast? Still no TX leds in Pro.

I finally got this to work by repeating the Serial.print (f); and then delay(1000); multiple times.  I changed my original post to reflect this.  Somehow this gets the string over to the ESP so it can parse it and upload it.  Now all I want to do is add a temperature sensor and maybe add an IFTTT to the whole thing so if the low end gets too low or the high end too high (of the water level I can get a notification to check out the whole system.
Thanks JRobert for the help I got the power I needed to the board.


text:
Are my stepper motors being burnt out? What is the issue here?
I am building a mini-cnc laser engraver as shown in this intructable and this youtube video.
I have built the circuit (minus the jst connector and two male pins at the top left of the board) and have attached a stepper motor from a dvd drive. It worked like a charm, but made a loud ringing noise (like tinnitus.) I proceeded to test it with laser GRBL, and it moved great, but gradually started missing steps, at first only in one direction and eventually in both. After a couple hours of being connected, it wouldn't budge at all. I switched the motor for another motor, and tested it again. This time the motor was much shorter-lived. It made 5 steps perfectly and then just shut off. You could hear the motor try to turn, but it was like it didn't have any torque at all. What could be the issue? (I also tried it on the other axis with the other motor driver, no change.)
It's also worth noting that at one point both the positive and negative (ground) cables from my power supply made contact with metal at once, throwing a spark. However, the steps were already beginning to be lost before that happened.
As per your request, I have attached the circuit layout I am attempting (it's identical to the one in the tutorial) as well as a picture of my physical circuit board. (sorry, a link was my only option as the pics were to big for upload) I know the soldering is pretty bad- I have a giant soldering iron. I don't see any shorts though.

At what voltage did you run those steppers?

@Gerben im going to be completely honest, ive never attempted anything with circuit boards or arduino before. I followed the instructables, which tells me to use a 12v power supply on the screw terminal after everything is hooked up. – Drake Ford just now    Edit    Delete

Your steppers might be 5V instead of 12V. Or his are 5Volt to, but has set the A4988 Motor Drivers to limit the current (with the small potentiometer on the board).

To progress this further I think you'd need to edit your answer to add the part number(s) of your components (preferably along with with their specifications) and along with the schematic / circuit layout you have implemented (rather than the one from the tutorial).

@AJP I have done as you suggested

You can upload images as part of your question, you know. That is far preferable to sending people off-site to some link that might go down in a year, making the question hard to follow. I also don't see the part numbers that were requested.

Sorry my suggestion of a circuit layout was only partially useful as this is what you hope you've wired up @DrakeFord but it's always good to see the actual wiring up.  And as Nick's suggested a picture of your circuit plus a picture of the intended circuit layout would be good.  There might be a simple mistake here.
And secondly again, what are the motors you are using (their part numbers) and their resistance and amperage. You'll need these to know if they'll work with your A4988 drivers: https://learn.adafruit.com/all-about-stepper-motors/matching-the-driver-to-the-stepper

@AJP I had to link my pictures of my circuit- they were too large for upload. I do not have my stepper motor part number, since they were harvested from a DVD drive. My DVD drive model number is LITE-ON SOHW-1633S

You can scale the pictures down.
There should be some part numbers on it somewhere.  Is there no writing on it?  Not a stuck on paper label.  No dot matrix printed numbers.  Nothing?  If you can't find out exactly what the motors are and are capable of I'd go back to experimenting (though you may fry your driver if the motors draw too much current).  Try measuring the voltage and current and see if it's acceptable for your A4988 drivers.  If so try reducing the speed of driving the motors.  Also try with them disconnected from any physical load... maybe they're just stalling.

@AJP the only number i see is E232171 which is printed onto the flexible pcb where the 4 solder joints are on the motor. other than that, nothing. The motors have no physial load.

You seen this @DrakeFord? https://www.eevblog.com/forum/projects/dvd-rw-(liteon)-teardown-stuff-details-(motors-laser-diodes-ir-red-visual-etc)/msg706604/?PHPSESSID=o815ofg9mgsifeduvk0akvpsa0#msg706604

@AJP yes I have. I am suspecting that I might have a bad voltage regulator on the board and that it is feeding 12V into the 5V Stepper. Maybe replace the voltage regulator?

@DrakeFord if you think the voltage regulator is at fault then isolate that first.  If it's producing 12V you'll likely be damaging other components.  If you have a DVM (Digital Volt Meter) then measure it's output and see if it's behaving as intended before just replacing it.  If you don't have a DVM, then borrow or buy one... it's an essential (and cheap) bit of kit of hobby electronics.  When debugging all these problems following this guidance is very powerful: https://stackoverflow.com/help/minimal-reproducible-example  As you reduce the size of your problem it becomes easier to solve it.

So the problem was that somehow the potentiometer had reset its own vref output. I couldn't adjust it after it did this. I replaced both drivers and it works like a charm now.

source: Stack Exchange

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

sort: votes


text:
Webpage values wont update
I've been trying to run the following esp32 LED PWM code to change the LED's brightness, and show the current PWM duty on the webpage, but the PWM values on the webpage won't change until I hit the submit button twice.
#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
WebServer ser(80);
int s=0;
String k;

String iso()
{
  k="
LED PWM<FORM action=\"/\" method=\"post\"><input type=\"text\" name=\"duty\">
 <input type=\"submit\" value=\"Submit\">Cureent Duty=";
  k=k+s;
  k=k+"
";

  return k;
}

void root()
{
  iso();
  ser.send(200, "text/html", iso());

  if (ser.hasArg("duty"))
  {
      iso();
      s=ser.arg("duty").toInt();
      ledcWrite(4, s);
      iso();
      ser.send(200, "text/html", iso());
  }
}

void setup() {
  Serial.begin(9600);
  ledcAttachPin(33, 4);
  ledcSetup(4, 5000, 8);
  WiFi.begin("ssid", "pass");
  Serial.print("\nConnecting To WiFi");
  while (WiFi.status()!=WL_CONNECTED)
  {

    Serial.printf("\n.");
  }
  Serial.print("\nConnected");

  ser.on("/", root);
  ser.begin(80);
}

void loop() {
  ser.handleClient();
}

Here's a GIF addressing the issue

upvote for visually demonstrating the issue

When the client sends you a request, you should answer only once. Your
root() function attempts to answer twice whenever the request contains
the argument “duty”. The client will not handle a duplicate response to
a single request.
Here is your root() function:
void root()
{
  iso();
  ser.send(200, "text/html", iso());  // ← first response

  if (ser.hasArg("duty"))
  {
      iso();
      s=ser.arg("duty").toInt();
      ledcWrite(4, s);
      iso();
      ser.send(200, "text/html", iso());  // ← second response
  }
}

You may notice that the first response was sent before updating the
duty cycle.
The proper way to handle the request is to first handle the request
parameters, if any, then send the response:
void root()
{
  if (ser.hasArg("duty")) {
    s = ser.arg("duty").toInt();
    ledcWrite(4, s);
  }
  ser.send(200, "text/html", iso());  // ← only sent once
}

As a side note, there is absolutely no need to build the response five
times (you have five calls to iso() within root()) when you only
need it once!

I'm such an idiot ! ;P thanks a lot.

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


text:
Nodemcu does not connect to phone wifi
All welcome.
I'm trying to connect nodemcu to the phone's wifi.
And nodemcu can't do it. But sometimes after several reboots she does it. Also if i use my old phone - nodemcu connects perfectly! Why?
My "new" phone: Fly FS504 Cirrus 2
My old phone: Fly IQ4504 Quad.
My code:
#include <ESP8266WiFi.h>

const char *ssid =  "Just my SSID";

const char *pass =  "Some password";

WiFiClient client;

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

       Serial.println("Connecting to ");
       Serial.println(ssid);

       WiFi.begin(ssid, pass);
       while (WiFi.status() != WL_CONNECTED)
          {
            // stack here (only with new phone)
            delay(500);
            Serial.print(".");
          }
      Serial.println("");
      Serial.println("WiFi connected");
}

void loop()
{

}

Does it crash? If you're on a breadboard I guess that's the reason. You could try to explicitly WiFi.disconnect() before attempting to connect, the esp8266's wifi is a bit buggy sometimes.

@SimSon, hmm.. Just add Wifi.disconnect() before WiFi.begin()?

@SimSon, thanks! It's working! I spent a lot of time for this problem. Have a nice day :)

glad to hear. So did my workaround "fix" your problem? If yes, I'd form it into an answer so you can close this question

@SimSon, yeah, do it

From my experience the esp8266's wifi is a little bit buggy sometimes. I'm not sure if it has something to do with the esp auto-connecting to known networks, but I managed to work-around this issue by explicitly WiFi.disconnect()ing from any potential network right before calling WiFi.begin().
Another thing that I noticed several times is that the esp can be easily disturbed when connected to a breadboard, in special when wifi is in use (in this case the esp might even crash). There must be some bad interferences, I guess.


text:
Showing GPS Values on I2C LCD using Arduino and ESP8266
I am working with Arduino. I'm using 2 Arduino boards along with 2 ESP8266 modules to transfer data from one Arduino to another Arduino. I want to transfer GPS values from system 1 to system 2 using Wi-Fi module ESP8266 along with Arduino UNO. I've written the main codes for server and client end. I'm not able to print anything on LCD if I'm using ESP8266 and selected 'generic ESP8266' boards.

do the examples of the LCD library work on the Arduino with the LCD?

you describe three possible areas of failure ... fail to read data from GPS ... fail to transfer data between arduinos ... fail to display data on LCD ....... which of the three is the actual failure? .... if it is one area of failure, then why are you not asking a specific question about it?


text:
Esp and blynk app
It is possible to control one relay using Blynk app and also using an atmega? To a better understanding think at a relay that will turn on a fan when you use the blynk app. but when you don;t have the phone around you, using a pushbutton, you can turn it on from there(the button will be connected to atmega)

void setup()
{
  Serial.begin(9600);
  pinMode(relCh1,OUTPUT);

  pinMode(relCh2,OUTPUT);

  pinMode(relCh3,OUTPUT);

  pinMode(relCh4,OUTPUT);
  digitalWrite(relCh1,HIGH);
  pinMode(EspReadPin, INPUT);
  digitalWrite(relCh3,HIGH);
}
void loop()
{
Serial.println(digitalRead(6));
delay(400);
  if(digitalRead(EspReadPin == 1))
  {
    digitalWrite(relCh3,LOW);
  }
  else if(digitalRead(EspReadPin == 0))
  {
    digitalWrite(relCh3,HIGH);
  }
}

Yes it is possible.
Use the Blynk example sketch to activate the pin of the esp8266. Read the pin of the esp8266 with the ATMega. Handle in ATmega sketch the esp8266 pin as a second button.

i can't understand. Can you please to explain more detailed?

can you please rewrite your question in more detail

Of course ! basically what i want is to control one relay from two different locations. One will be in the house(a panel with buttons) - where will be also this button for the relay. and will be controlled by atmega(when it will be pressed - will turn on the relay). and another "location" will be from the phone. but for this part i will use blynk and esp.

and you have the local part working and want to add the esp8266 with Blynk?

i use the pin from atmega as output. and on the breadboard is connected to relay(as signal) but on the same line(on the breadboard) i put also the pin from the esp. and the problem appears  that if i press the button - relay will turn on. but if i use the blynk app- nothing happens.

so for the moment i can control it using just atmega. if i remove the pin coming from the atmega - blynk works perfect.

so then read my answer again. the part about "read the esp8266 pin with ATmega"

so how should i do that? i mean.. the only solution i am thinking right now is to define another pin of atmega as INPUT and to read it.

is it a problem?

i am afraid it wont work.

why would it not work? this is what microcontrollers do

i've just try it and nothing. ..

it reads pin as high but only that

do you have a plain esp8266? what pin of the esp8266 did you use? (add the info to the question)

no, i have an NodeMCU and the pin used is D0 = GPIO 16

did you upload the Blynk sketch into the NodeMcu?

yes. Esp and blynk works perfect. The problem appears on the atmega side. even the relay module it goes crazy. Even if i set them in the setup function to be opend, when the sketch is uploaded, they close. and i cannot understand why.

i have tested what you told me to do on the arduino nano and i set the pin as input. if it's high, then the built in led will be on, else should be off. and works. it;s ok. but on the mega... something goes crazy.

anyway, you helped me. Thank you!

are the relays active LOW?

yes. if i set them as low - they are closed

something strange happening here.  i wrote a sketch to test one btn and if is high to turn the relay on. Ok...i uploaded the code and then if i press the button the atmega it sees that is high and execute 'digitalWrite(relay,HIGH); ' .the problem is that the relay wont close. i use dmm to measure the voltage at the relay signal pin and is 4.7V- normally it should close. but no. the led in front of the relay barely glows.

only pull-up on INPUT pin? not OUTPUT? check the pin numbers in sketch

now, if i test it using 2 conditions more - it works

i have posted the code above. so if i remove in the if statements  && and all after. it wont wok

if (b == HIGH || a == LOW) {} else {}?

i tested with your suggestion. this is what it happens. the led in front of relay(that who shows if the relay receive voltage) barely lights in both situations(if i use the app or i push the btn) BUT if i press the button and i use the app in the same time. the relay close.

it turns on and off fast?

no. if i press the button on blynk to turn it on. it wont turn on. instead the led glows (barely- like it receive the minimum voltage on the junction to let the current flows) but if i measure the voltage- there is 4.7V but the relay wont close.

Looking in the serial Monitor it looks like the relay will close only when it receive 0 but that is for LOW. and i set it to HIGH. My head hurts..don't know wtf is happening here. Very probably is that i had done something wrong.

has the button a pull-down resistor? it is better to wire the button to ground and use the internal pullup with INPUT_PULLUP mode like in DigitalInputPullup example


text:
ARDUINO UNO WIFI R3 (Dev Edition) Send simple http get request
I need send http request to my own server from arduino uno.
First of all I connected the board through web client configurator.
I tried different codes, the last one is:
    /*
    File: RestClient.ino
    This example makes an HTTP request after 10 seconds and shows the result both in
    serial monitor and in the wifi console of the Arduino Uno WiFi.
Note: works only with Arduino Uno WiFi Developer Edition.

http://www.arduino.org/learning/tutorials/boards-tutorials/restserver-and-restclient
*/

#include <Wire.h>
#include <UnoWiFiDevEd.h>

void setup() {

  const char* connector = "rest";
  const char* server = "<MY IP>";
  const char* method = "GET";
  const char* resource = "/";

  Serial.begin(9600);
  Serial.println("prima");
  Ciao.begin();
  Serial.println("dopo");

  pinMode(2, INPUT);

  //delay(1000);
  doRequest(connector, server, resource, method);
}

void loop() {

}

void doRequest(const char* conn, const char* server, const char* command, const char* method){
  Serial.println("Im doing the request");
  CiaoData data = Ciao.write(conn, server, command, method);
  if (!data.isEmpty()){
    Ciao.println( "State: " + String (data.get(1)) );
    Ciao.println( "Response: " + String (data.get(2)) );
    Serial.println( "State: " + String (data.get(1)) );
    Serial.println( "Response: " + String (data.get(2)) );
  }
  else{
    Ciao.println ("Write Error");
    Serial.println ("Write Error");
  }
}

But I get "Write Error" and the server does not recive any request

does your server run on port 80 and is it accessible over the Firewall? try to access it from some other device in the network.

I made a mistake. I put PubIP:PORT.
After your comment I exposed the server on PORT 80 and works.
So The request works only with port 80.
Thank you

If you find out that the UnoWiFiDevEd library is very limited, you can use WiFiLink firmware and library with my UnoWiFiDevEdSerial1 library


text:
Keypad code not working
I am new I took a code of keypad in arduino. Arduino code is not working in setup area but if I place the same code in loop are it works why? Kindly guide me.
Here is the code.
#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
  {'0','1','2','3'},
  {'4','5','6','7'},
  {'8','9','A','B'},
  {'C','D','E','F'}
};
byte rowPins[ROWS] = {2, 3, 4,5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8, 9}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

void setup(){
  Serial.begin(9600);
  char customKey = customKeypad.getKey();

  if (customKey){
    Serial.println(customKey);
  }
}

void loop(){

}

Please note that setup() runs just once while loop() is repeated forever (see e.g. here) that's an important difference.

but it must run once, it is not .

It is. It's just running waaaaay faster than you can press a key.

I think you need to learn the difference between "Running once right at the very start" and "Getting one keypress". The two concepts are completely different.

Ok thanks alot.

To illustrate what the are talking about, try putting an else on your if.... I.e. else { Serial.println("no key press"); } . As a bonus you will get a free game called "can I beat the no key press message?" :-)


text:
OLED DISPLAY USING SPI
My display is not responding to this code. Help please
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_MOSI 10
#define OLED_CLK 9
#define OLED_DC 12
#define OLED_CS 13
#define OLED_RESET 11
Adafruit_SSD1306 display(OLED_MOSI,OLED_CLK,OLED_DC,OLED_CS,OLED_RESET);

void setup(){
  Serial.begin(9600);
  display.begin(SSD1306_SWITCHCAPVCC);
  display.clearDisplay();

  display.setTextSize(1);
  display.setCursor(30,30);
  display.print("Hello WOrld");
  display.display();
  }

  void loop(){

    }

what does this mean? not responding

There is no code, that would respond to user actions. It just displays hello world, nothing else.

sorry what i meant was that the display is not turning on. I ran the adafruit example and the display qorks fine. So is there a problem in the code? i copied this code from a youtube video

Pin definitions in your code seem to be mixed up. If Adafruit example works fine with your setup, you should keep the pin definitions Adarfruit uses:
#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13

Also, you are using a deprecated constructor. It is recommended to use a constructor which explicitly specifies display size.


text:
Xbee S2C is resetting Arduino Uno
I have a coordinator radio hooked up to a sparkfun xbee shield, hooked up to an Uno. This is then hooked up to my computer. This coordinator talks with a number of xbee routers/end devices and sends them 6 commands to change the digital pins high or low on the corresponding xbees. The commands are always frame ID = 0, then the last (6th) command I send a 0x2 to save all the digital pins high or low at once.
The issue is that occasionally when the xbee receives all of the commands and saves them, the Uno will reset itself. (I can tell by the blinking LED on 13).
I have looked into it, and the best suggestion so far is to disable D7 on the receiving Xbee via XCTU. This unfortunately has not helped. Is there another reason that the arduino is resetting every couple of times I change the pins on the xbee? It doesn't happen every time, just once out of every 3-5 times...

Bleh, I figured it out. Not only do I have to turn D7 off, I also have to hook a jumper between 5V and RST as shown here.
https://learn.sparkfun.com/tutorials/xbee-shield-hookup-guide/all

It's OK to accept your own answer as the solution.


text:
All floats feedback a rounded down integer
So I am very confused at the results I am getting.
It seems that floats aren't working properly, and I don't understand why.
I was trying to read a temp sensor and convert the reading to celsius. However, when I tried to divide the value (an int between 145-165) by 1024, and multiply by 5 I would get back a float value of 0.00
Here's the code I was using
    void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(A0, INPUT);

}

void loop() {
  int sensorVal = analogRead(A0);
    Serial.print("Sensor Value: ");
    Serial.println(sensorVal);

  float voltage = ((sensorVal/1024) * 5);
    Serial.print("Voltage Value: ");
    Serial.println(voltage);

}

This would only return values of 0.00 for voltage, even though the sensor itself is working fine, returning varying values between 146 and 165 based on how much heat I apply.
This didn't make any sense, so I tried it with some other values, eg.
Serial.print(float (10 / 6));

and
Serial.print(float (5 / 2));

which should have returned 1.67 and 2.50 respectively, but instead returned 1.00 and 2.00
I think it might be a settings thing, where all floats round down to an int, but that seems really weird.
Any help would be great!

Hint: Try float voltage = ((sensorVal/1024.0) * 5.0);

FYI, your intermediate results are truncated, not rounded. ( 0/11 will yield 1, since the answer is ≈1.81, and it simply strips away the decimal part. By comparison, round(20.0/11.0) will give you a value of 2.0, since 1.8181 rounded rounds up to 2.)

You are doing integer arithmetic. Try adding .0 to the end of your values where you need the floating point results.
For example...

  float voltage = ((sensorVal/1024.0) * 5.0);

Remember the results of analog read is an integer. So the conversion to a float in you original code only happens when the "=" is being "executed". Another possibility is to cast it to a float straight away.

  float voltage = ((((float)sensorVal)/1024.0) * 5.0);

Or more simply

  float voltage = ((float)sensorVal)/1024.0 * 5.0;

This helped a lot. I realized that I should have also initialized my sensorVal as a float

You already got a couple of perfectly good answer. I will nevertheless
suggest a slightly different idiom:
float voltage = sensorVal * (5.0 / 1024);

or, maybe better:
const float V_REF = 5.0;  // at the top of the sketch

float voltage = sensorVal * (V_REF / 1024);

The reason this is slightly better than the other options is because
division – even integer division – is a very expensive
operation on the smaller Arduinos. By writing the conversion as in the
lines above, the ratio V_REF / 1024 becomes a compile-time constant,
which is evaluated by the compiler at build time. Then, only the much
cheaper multiplication needs to be done by the Arduino itself, at run
time. Not a big deal if you are not time constrained, but it's a
low-hanging fruit in terms of optimization.
You may write 1024.0 instead of 1024 if it feels safer. I tend to
keep the .0 for the voltage only, because 1024 is an integer, whereas
the “5” in “5 volts” is conceptually a real number (it's an
analog voltage, and not even exactly 5 V if you bother to measure
it). But this is just a personal preference at the end.

Good point on avoiding runtime division. (voted)

I must admit @edgar_bonet, I found what you said very hard to believe - after all one of the things that an optimising compilers should check for is "constant arithmetic" and "work it out for you" and just apply the result. That is, x / 1023.0 * 5.0 should be optimised as (X / 204.6) . Since I didn't believe you (sorry about that), I tried a simple program and was stunned to see that it actually executes the division of the constants in the generated assembler - unless you put that part of the expression in parenthesis.

What was also of interest was that in my first version I simply put int reading = analogRead(A0);  float result = reading / 1023.0 * 5.0; in my setup() function with nothing else. Long story short, the compiler optimised the whole block of code out of the generated assembler (because I wasn't doing anything with the result). It wasn't until I put in Serial.println(result); that the calculation was emitted by the compiler.
I was going to down vote you ('cos I thought you were wrong), but after checking and found you were right - you get an upvote from me to.

@GMc: The compiler cannot optimize x / 1023.0 * 5.0 into x * (5.0 / 1023.0) because the two expressions, although equivalent in the realm of real numbers, are not equivalent for floating point numbers. The compiler is not allowed to perform an optimization that can possibly modify the result of a computation. That is, unless you give it an option like -funsafe-math-optimizations, which is off by default.

@edgar_bonet thanks for the insights and the great addition to the answer I will definitely explore this further.

GMc explained what to do, but didn't explain in detail why your code fails to give floating point results.
Most languages evaluate expressions using order of operations. C and C++ are no exception to this.
In C/C++, while the expression is being evaluated, the compiler also decides what data types to use for each part. integer-integer expressions are evaluated using integer math. If either of the parts of an expression is a larger/floating point type, both values are "promoted" to the larger/more complex type before evaluating the expression.
in your code
float voltage = ((sensorVal/1024) * 5);

The sensorVal/1024 bit is evaluate first. Since both sensorVal and 1024 are integers, the compiler uses integer math. That yields an int result, and so any fractional part is truncated and lost.
It then evaluates result*5 (where result is the result of the first part, sensorVal/1024, which is an integer.) Both of those parts are integers, so the result of that expression is an int.
Finally, you ask the compiler to store the result into a float, voltage. The compiler then promotes the integer result of the whole expression to a float, but you've lost any floating point part of your calculations.
By rewriting your line as
float voltage = ((sensorVal/1024.0) * 5.0);

The compiler does what you want. The sensorVal/1024.0 bit is now integer-float math, so the compiler "promotes" sensorVal to a float and then does float-float math. The second part is now float-float, so the result is also floating point.
float voltage = ((sensorVal/1024.0) * 5);

Would also work in this case (where 5 is an integer constant.) That works because float_result*5 is float-integer math, and the compiler will promote 5 to a floating point value and do float-float math. to get the final result. However, it's safer to use all floating point constants so you don't accidentally do part of your calculations using integer math and truncate that part before converting to floating point.
As you say, making sensorVal a float also would be a good idea. (Again, to avoid accidentally doing integer math on part of your expression and getting wrong results in the process. In this case making sensorVal a float isn't needed, but with a different expression you might wind up with integer math for part of the calculation.)


text:
Multiple dht11 on an wemos d1 r1
I am trying to connect three separate DHT11 to my Wemos d1 r1.
I have each sensor hooked to a power pin which turns on and off, the sensor pin and a common ground.
Here is my code:

#include <DHTesp.h>
#include <ESP8266WiFi.h>

String apiKey = "xxxxxxxxxxxxxx";
const char* ssid = "xxxxxxxxxxx";
const char* password = "xxxxxxxxxxxx";
const char* server = "api.thingspeak.com";

DHTesp dht;
DHTesp dht2;
DHTesp dht3;
WiFiClient client;

void setup() {

  pinMode(D6,OUTPUT);
  pinMode(D8,OUTPUT);
  pinMode(D1,OUTPUT);

    Serial.begin(115200);
    dht.setup(D5, DHTesp::DHT11);
    dht2.setup(D7, DHTesp::DHT11);
    dht3.setup(D2, DHTesp::DHT11);
    WiFi.begin(ssid, password);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

}

void loop() {
 digitalWrite(D6,HIGH);
  delay(8000);

    float t = dht.getTemperature();
    float f = (t*1.8) + 32;

    if (isnan(t))
  {
    Serial.println("Failed to read from DHT2 sensor!");
    return;
  }
    Serial.print(", \"maintemp\": ");
    Serial.print(f);
    Serial.print("}\n");

digitalWrite(D6,LOW);
digitalWrite(D8,HIGH);
delay(8000);

    float t2 = dht2.getTemperature();
    float f2 = (t2*1.8) + 32;

    if (isnan(t2))
  {
    Serial.println("Failed to read from DHT3 sensor!");
    return;
  }
    Serial.print(", \"lowtemp\": ");
    Serial.print(f2);
    Serial.print("}\n");

digitalWrite(D6,LOW);
digitalWrite(D1,HIGH);
delay(8000);

    float t3 = dht3.getTemperature();
    float f3 = (t3*1.8) + 32;

    if (isnan(t3))
  {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
    Serial.print(", \"uptemp\": ");
    Serial.print(f3);
    Serial.print("}\n");

    digitalWrite(D1,LOW);

    delay(2000);

    if (client.connect(server, 80)) {
    String postStr = apiKey;
    postStr += "&field3=";
    postStr += String(f);
    postStr += "&field4=";
    postStr += String(f2);
    postStr += "&field5=";
    postStr += String(f3);
    postStr += "\r\n\r\n\r\n\r\n";

    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(postStr.length());
    client.print("\n\n\n\n");
    client.print(postStr);

    Serial.print("Temperature: ");
    Serial.print(f);

    Serial.println("Sending data to Thingspeak");
  }
  client.stop();

  Serial.println("Waiting 20 secs");
  // thingspeak needs at least a 15 sec delay between updates
  // 20 seconds to be safe

  delay(53700);
}

As you can see I assign a separate DHT to each sensor pin and turn on and off the power pins to each sensor.  They all have a common ground.
When I run the code the first sensor reads the temperature but the second one says "Failed to read from DHT3 sensor!".
It is not the sensor because if I swap the first and second sensor the first one always read and the second fails.  If I eliminate the second sensor the third one fails.  I have tried to power all of the sensor pins in SetUP but still the first one is the only one to work.  Is there some kind of trick I have to use here.
I am using DHTESP.h since the regular DHT.h didn't work with the Wemos Pro Mini.
Has anyone had any experience with this to give me some guidance.
Thanks

Can you add a print of getStatusString in your error? For instance if (isnan(t))   {     Serial.print("Failed to read from DHT2 sensor: status ");     Serial.println(dht2.getStatusString());     return;   }. Do this for all three sensors, then post the output; it will tell you at least what is the error it detects (timeout? checksum? ...)

Can you draw a schematic diagram? What's the total measured pullup from the data line to the +5V line?

You probably have to create an set up a new DHT object each time you turn the power on. My guess is that the sensor needs to be initialized by the Arduino before it is ready to take readings, and when you turn the power off and back on it loses its configuration.


text:
New to arduino, help wiring relay
I am new to arduino and need some help. I just baught light bars for my jeep and wiring harnesses with them, the harnesses come with buttons and I wanted to replace the button and have them controlled on my phone. The harnesses come with a relay and a fuse and a button all 12v, How would i go about using my raspberry pi or udoo x86(which has built in adruino) to basically replace the rocker switch so i can then turn things on and off without needing to have actual switches.

a simple MCU can do it. no need to have a computer for this. use Arduino Nano or Mini

Google: "Arduino relay" and look at the pretty pictures.

Or, if you don't want to mess with the harnesses electronic, you can bridge the buttons using a MOSFET, which can be directly controlled by Arduino or the Pi.

To drive a relay you'll need a transistor (a MOSFET is a good choice) and you'll need a diode across the relay coils to protect the transistor from the reverse current pulse when you remove power from the relay coils.
As Majenko says, if you Google "Arduino relay" you'll find lots of articles covering the topic. (And if you use a digital output line from your PI the exact same circuit will work.)
This MOSFET is a good option for switching high current loads with a 5V logic signal:
https://www.adafruit.com/product/355
The diode will need to be a power diode that can handle your voltage/current needs. You'll need to figure out how much current your light bar uses, and then I'd suggest a diode that can handle twice that much current (at 12V) for a margin of safety.

Re “handle twice that much current (at 12V)”: Not at 12 V. It should handle the current when forward biased, and the voltage when reverse biased.

why not MOSFET only

An inductive coil like a relay coil dumps a large surge of reverse current when you remove power from it. (sometimes called "flyback current".) That is enough to destroy a transistor, so you need a diode to protect the transistor.

how do i see how much current the lights bar uses, can i just use the volts and amps that the relay says on it? also things say i need a resistor, how do i choose that also.

http://henrysbench.capnfatz.com/henrys-bench/arduino-output-devices/tip122-arduino-relay-tutorial/ this is the circuit i think i will use with the mosfet, does each mosfet use a different ground or all the same

I meant without the relay

@Juraj, sure, you could skip the relay and drive the light bar directly without the relay. In that case it would be a straight inductive load and you wouldn't need a protection diode. To the OP, it would be simpler to get rid of the relay from your harness and control the lights directly with a MOSFET like the one I linked in my answer. You can drive that MOSFET's gate directly with a logic line from a PI or Arduino, and it will switch a large amount of current (although you'll need a heat-sink for larger current loads - see the specs.)


text:
Change css form color from esp32 if statement
I am fairly new to arduino and ESP though am very familiar with css and javascript.
I have an esp webserver that includes a button
client.print("<button style='background-color: #F30C0C; color:#000;'></button>");

but need it to change the css backbround-color when pin is reading HIGH
 if (c == '\n') {
          currentLineIsBlank = true;
          buffer = "";
        }
        else if (c == '\r') {
          if (buffer.indexOf("GET /?relay1") >= 0)
            relayPIN1read = digitalRead(relayPIN1);

          if (relayPIN1read == HIGH) {
            digitalWrite(relayPIN1, LOW);
          }
          if (relayPIN1read == LOW) {
            digitalWrite(relayPIN1, HIGH);
          }
        }
      }

Does any one know of any way to do this?

First print everything up to the colour. Then print the colour, which you change depending on the state of the pin. Then print the rest.
client.print("<button style='background-color: ");

if (digitalRead(PIN) == HIGH) {
    client.print("#0CF30C");
} else {
    client.print("#F30C0C");
}

client.print("; color:#000;'></button>");

I  did try that, but seamed to go HIGH and LOW as if it was in a 2 count loop.. but will give it another go... Thank you

@Ben You are sending a "toggle" command rather than a "set" or "reset" command. You should separate it out and use a similar system as the colour to change the command the button sends.

dont know what i was going last time.. but that worked like a charm.. thanks very much for your time :)


text:
Windows 10 does not recognize Arduino Leonardo
Using Arduino Leonardo, IDE 1.8.9, Windows 10.
For a short time, when I first got the Leonardo, Windows 10 would recognize the board; I could see it in devices, Windows 10 would make a sound when plugged in, it would show listed in the ports of the IDE, and I could upload my code to the board (confirmed with blinking light sketch). It no longer does.
The error I get in the IDE avrdude: butterfly_recv(): programmer is not responding.
I believe the main issues stems from I had selected Arduino UNO (I have a couple of those as well) in the IDE and Uploaded my sketch.
Ever since I did this, Windows 10 no longer recognizes the board when plugged in. It doesn't even show in "other devices" under device manager.
I have tried the following:

The on-board reset trick that seems to be most of what other users experience and solves their issue. All variations. Holding the reset button, uploading, releasing, etc.
Swapping cables. Confirmed with another device it was a data cable and working.
Uninstalling and reinstalling the IDE
Restarting numerous times
Burning boot loader - since Windows 10 won't recognize the device, this fails immediately can't even communicate to the board.

I have seen similar questions about this, but none of them seem to specifically cover what I am encountering.

did you try a double reset?

the bootloader can be burned only with a programmer so it is not relevant if the board shows up as a port

I believe so yes. reset.. click upload... reset again when IDE says uploading?

no reset and reset. then select port and upload

yes tried that as well. waiting for it to appear in the ports menu. never does

Sounds like you've bricked it.  Your broken sketch (wrong MCU selected) means that it's not presenting a CDC/ACM port.
Your best bet is to use a hardware programmer (eg USBASP or another Arduino) to erase the chip and reload the bootloader.

Thanks for the info. Can you point me to a tutorial for this?

@static_cast It's the same as burning any Arduino bootloader. There's millions of tutorials online about how to do it. TBH I'd buy a USBASP. They're dirt cheap from China.


text:
MEGA2560 only starts program after pressing RESET button multiple times
I am working on a program where I am controlling an MP3 player by using UART between my MEGA2560 and the MP3 player. The MEGA2560 sends serial commands to the MP3 player when external interrupts are generated on INT4 and INT5 and it all seems to work fine.
When I want to test my program I press the RESET button on the Arduino in order to start the program. However, sometimes the program only starts after pressing the RESET button multiple times. This happens often but not all the time, which is weird.
What do you think could be the reason for this?

Does keeping the RESET button pressed for at least 1 second change the behavior?

Are you using Serial inside the interrupt handlers?

What causes the signals to switch on INT4 & 5? Normally, one would have the pins connect to Gnd when a button is pressed, and the lines are held high when not pressed by a Pullup resistor, typically the internal pullup is enough. For long wires, an external pullup may be needed.

@CrossRoads
I have two sensors (one for INT4 and one for INT5). When the sensors are turned on, they send 5V on the output. I measured the output with a scope and it works.


text:
Connecting to MQTT causes DHT11 Sensor to stop working?
I have a project I am working on, based on an ESP32 from NodeMCU. I have a bunch of sensors connected to said ESP32 - they all work and the code itself "works" with a minor quirk.
The issue in question starts with a DHT11 sensor. I started from the basic "hello world" DHT11 code (you can find it easily with a DHT11 search in google). That sensor works in my code that you can see below - I copied and pasted the sample code, and except for changing variables, did not alter the sample code really at all.
The issue I have is that while the sample code will read accurately on every loop, in my code, it reads from the sensor exactly once the first time the loop runs, and then never again.
I believe I have isolated the issue to this bit of code and the corresponding function it calls (it didn't used to be a function - that was a troubleshooting step):
  if (!client.connected()) {
    reconnectMQ();
  } etc...

By moving this statement and grouping the MQTT messaging to the end, the system runs a full loop with correct readings, exactly once, but after that function is called the DHT11 begins failing to read.
Things I have tried:

 different variable names for temp and humidity (in case "t" and "h" are in use in the MQ library)
     order of operations (made the loop work once)
     changing the reconnectMQ() to a full function and not just a loop in the main loop
     changing the logic of the DHT11 sensor to at least not hang forever trying to read - this meant it got through this part, but with 0 values
     "turning off" MQ - this means that everything works, but obviously is a bit like cutting off your arm for a sprained wrist.
     ENDLESS Google and Stack searches before resorting to this post.

I hate to do this as my project is 200 lines long, but I suspect the full code is needed to see what's possibly happening.
#include <time.h>
#include <DHT.h>
#include <WiFi.h>
#include <PubSubClient.h>

//use pin 23 to read temp and humidity
//our sensor is DHT11 type
//creates an instance of DHT sensor
#define DHTPIN 23
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

//Define the analog pins inbound for the Soil Moisture sensors
const int sm1Pin = 33;
const int sm2Pin = 34;
const int sm3Pin = 35;
const int sm4Pin = 32;

const int power = 22;
const int exec = 21;
const int net = 19;

//define the pin for the light level reading
const int light = 36;

//Init MQTT payload arrays
char data0[50];
char data1[50];
char data2[50];

// declare our Wifi and MQTT connections and other constant settings for the network
const char* ssid     = "*******";            // The SSID (name) of the Wi-Fi network you want to connect to
const char* password = "*******";                          // The password of the Wi-Fi network
const char* mqtt_server = "192.168.1.195";                             // The target mqtt server
const char* input_string = "{\"Reporting\":\"GardenUnit1\", ";       // The name of this garden monitor unit
String clientId = "GP1";
int lcount = 0;

// declare our Wifi and MQTT connections
WiFiClient espClient;
PubSubClient client(espClient);

//
// Reconnects to the MQTT message-bus if the connection died, or we're
// not otherwise connected.
//
void reconnectMQ() {

  digitalWrite(net, LOW);  // turn the Blue NET LED Off

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Wifi not connected - configuring");
    setup_wifi();
  } else {
    Serial.println("Wifi Connected - connecting MQTT");
  }

  // Attempt to connect
  Serial.println("Attempting to connect to MQTT Server...");
  while (!client.connected()) {
    if (client.connect(clientId.c_str())) {
      Serial.println("connected to MQTT server");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }

  // Once connected, publish an announcement...
  String payload = String(input_string) + "\"MQTT\":\"Reconnected\"}";
  payload.toCharArray(data1, (payload.length() + 1));
  client.publish("control", data1); //the "control" topic is just for notifications - change to fit your needs

  digitalWrite(net, HIGH);  // turn the Blue NET LED on
  delay(5000);
}

void setup_wifi() {
  delay(10);
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  WiFi.begin(ssid, password);             // Connect to the wifi network

  while (WiFi.status() != WL_CONNECTED) // Wait for the Wi-Fi to connect
    delay(1000);
    Serial.print('.');

  Serial.println('\n');
  Serial.println("Connected!");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());         // Send the IP address of the ESP32 to the serial port

}

void setup() {
  Serial.begin(9600); // open serial port, set the baud rate as 9600 bps
  // These Options control the precision of the reading, and the voltage reduction capability of the ESP32
  // Attenuation number 3 is 11DB
  analogSetWidth(10);
  analogSetAttenuation((adc_attenuation_t)3);

  // Define the MQTT Server connection settings and then launch the MQTT Connection
  client.setServer(mqtt_server, 1883);

  // Set output and input pins to correct modes
  pinMode (power, OUTPUT);
  pinMode (exec, OUTPUT);
  pinMode (net, OUTPUT);

  //Turn on Green Power light
  digitalWrite (power, HIGH);

  //Connect to the wireless network
  setup_wifi();

  //This call starts the dht11 sensor instance
  dht.begin();
}

void loop() {
  //Turn on RED EXEC light - this means a sample is being taken
  digitalWrite (exec, HIGH);

  //Read DHT11 Temp and Humidity - Humidity is a % and temp is in Celcius
  float hum = dht.readHumidity();
  float temp = dht.readTemperature();
  // Check if any reads failed but insert bogus data so system continues
    if (isnan(hum) || isnan(temp)) {
        Serial.println("Failed to read from DHT sensor!");
        client.publish("garden1", "{\"Error\":\"Humidty/Temp Sensor Offline!\"}");
        hum = 0;
        temp = 0;
    } else {
        // print the result to Terminal
        Serial.print("Humidity: ");
        Serial.print(hum);
        Serial.print(" %\t");
        Serial.print("Temperature: ");
        Serial.print(temp);
        Serial.println(" *C ");
    }

  //Read value and print to serial for S1
  float s1 = analogRead(sm1Pin);
  Serial.print("Sensor 1: ");
  Serial.print(s1);
  Serial.println();
  //Read value and print to serial for S2
  float s2 = analogRead(sm2Pin);
  Serial.print("Sensor 2: ");
  Serial.print(s2);
  Serial.println();
  //Read value and print to serial for S3
  float s3 = analogRead(sm3Pin);
  Serial.print("Sensor 3: ");
  Serial.print(s3);
  Serial.println();
  //Read value and print to serial for S4
  float s4 = analogRead(sm4Pin);
  Serial.print("Sensor 4: ");
  Serial.print(s4);
  Serial.println();

  float L1 = analogRead(light);
  Serial.print("Light level: ");
  Serial.print(L1);
  Serial.println();

  if (!client.connected()) {
    reconnectMQ();
  }

  String payload = String(input_string) + "\"S1\":\"" + s1 + "\", \"S2\":\"" + s2 + "\", \"S3\":\"" + s3 + "\", \"S4\":\"" + s4 + "\"}";
  payload.toCharArray(data0, (payload.length() + 1));
  Serial.println("Publishing message 1:");
  while (!client.publish("garden1", data0)) {
    Serial.print(".");
  }
  String payload2 = String(input_string) + "\"Humidity\":\"" + hum + "\", \"Temperature\":\"" + temp + "\", \"Light\":\"" + L1 + "\"}";
  payload2.toCharArray(data2, (payload2.length() + 1));
  Serial.println("Publishing message 2:");
  while (!client.publish("garden1", data2)){
    Serial.print(".");
  }

  //Turn off RED EXEC light - this means a sample is done
  digitalWrite (exec, LOW);
  lcount = lcount + 1;
  delay(10000);
}

What happens when the code I have here runs is that I see all the messages at the Mosquito server and in serial monitor, and the loop runs as expected. Due to the logic I had to put in to keep the program running, after the first reading from the DHT11, temp and hum come back as 0 forever. This is obviously not what I want.
What is obvious:
Something happens between the first reading of the DHT11 and the next that makes it unhappy.
What is not:
What that something is. That something occurs in the MQTT connection, but for the life of me I cannot figure out what it is or isolate it.
So now I leave it to the community. What the heck is happening here?!

Hint(s): What could make the DHT11 read fail? Assuming 3.3V VDD to DHT11: How large pullup resistor? Extra capacitor on VDD-GND at the sensor? Extra long cables? Checked with logic analyzer?

So normally I would agree with this assessment, and I tried rejiggering the hardware every way I could find online, however, the sensor only errors if the software connects to MSMQ. If I remove all connection code from the program (going back to the simple DHT11 test works fine) then the sensor reads flawlessly for hours on end, wired as is. (3v, direct from the 3v pin on the ESP, on a breadboard, maximum wire length of about 15 CM total roundtrip)
The issue in this case is definitely software as the hardware works flawlessly with different code.

What happens if you try to print hum and temp after this line:
Serial.println("Failed to read from DHT sensor!");

@linhartr22 - I think you might be a genius - I was thinking that when I send the values to MQTT, that these lines:
String payload2 = String(input_string) + "\"Humidity\":\"" + hum + "\", \"Temperature\":\"" + temp + "\", \"Light\":\"" + L1 + "\"}";
  payload2.toCharArray(data2, (payload2.length() + 1));

Might be changing the variable type. Based on the error when I try to print them, I am sure of it.
invalid operands of type 'const char [6] and float to binary operator +
So the question is, what is the declaration to redeclare those variables. TO THE GOOGLE MACHINE!

Turns out that wasn't it. I changed my string method to use sprintf() syntax and it still exhibits the same issue - when it loops back to the "top" of the loop, the red LED comes on as instructed in the code, and then it sits forever, indicating the error is happening on the read of the humidity from the DHT11. I still think this might be the right track, in that the humidity variable is somehow not compatible on the second loop, but the dtostrf() code I added should have remedied that. So I am still at the original issue - with MQTT turned on, DHT11 does not work. Turned off, works great.

This could be a conflict between the DHT11 library and the MQTT library, trying to use the same timer or other resource in the MCU.

I suspect so as well, but that is beyond my ability or desire to fix. I have simply told the ESP to reset after each loop. Incredibly inelegant, but functional.

Leaving this here in case anyone else has a similar issue as an "answer" to my own question:
Simply put - DHT11 library as used, and MQTT library as used conflict. That's it, that's the answer.
There are two options for correcting this depending on your needs:

don't use or deeply examine and rebuild one of the libraries - frankly this was a negative ROI for me and not worth it
Add an  ESP.restart();  at the end of the main program loop and AFTER the sleep timer - this reboots the ESP and allows the DHT11 to read BEFORE the MQTT connection happens and the solution works.

This, in my mind is not "a fix" it is a workaround, but it does address the primary issue.

I think that's not a conflict, you just forgot to subscribe the topic first before sending the data.

No you can see it in the code above - there is no subscribe - it is a publish only. I moved the publish and messaging all over the place in the logical flow and literally it does not matter. The second you publish a message via MQTT, the DHT11 stops reading. The only way to get it to read again is to restart the ESP32.
I do not believe this is a hardware issue, or even a library issue for each library (as they work fine on their own) it is just a conflict in the two libraries. Thus I left this here for others who might experience this.

I've used the DHT11 library, not the DHT library in my sketches. The Example sketch should make it clear what minimal changes you'll need to make to your code.  It always worked well for me.

So I literally used the example code inside my larger program. It is (except for the pin I used, and later the variable names) completely unmodified. You can find the example code here:
http://www.esp32learning.com/code/esp32-and-dht11-sensor-example.php
The issue is not that it doesn't work, it does work, but not in conjunction with MQTT. As soon as my ESP32 connects to the MQ server, the DHT stops reading. No MQTT code, and it works like a charm.


text:
PUT request: PHP code to Arduino HTTPClient
I'm uploading a file to Azure blob storage using REST API request. The file uploaded successfully using PHP curl request. But when I transfer the code into ESP32 HTTP client I'm getting an Authentication error. I also verify the HMAC key generated by the ESP32 Arduino code in PHP code.
I'm thinking that I'm missing something in adding header.
Here is my PHP code :
       $header = array (
        "x-ms-blob-type: BlockBlob",
        "x-ms-date: " . $date,
        "x-ms-version: " . $version,
        "Authorization: SharedKey account_name:" . $signature_str,
        "Content-Type: text/plain; charset=UTF-8",
        "Content-Length: " . strlen($fdata),
        );

    $url =  "https://acount_name.blob.core.windows.net/container/test.txt";
    $ch = curl_init ();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'PUT' );
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fdata);
    curl_setopt ( $ch, CURLOPT_HEADER, True );
    echo($ch);
    curl_exec ( $ch );

and here is the corresponding Arduino IDE code:
    String sig = get_hmac();
      Serial.println(sig);

      if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
        HTTPClient http;
        http.begin("https://account_name.blob.core.windows.net/container/test.txt");  //Specify destination for HTTP request

        http.addHeader("x-ms-blob-type", "BlockBlob");
        http.addHeader("x-ms-date", Date);
        http.addHeader("x-ms-version", "2018-03-28");
        http.addHeader("Authorization", "SharedKey account_name:"+sig);
        http.addHeader("Content-Type", "text/plain; charset=UTF-8");
        http.addHeader("Content-Length",  "20");

        int httpResponseCode = http.PUT(d);
        if (httpResponseCode > 0) {
          String response = http.getString();
          Serial.println(httpResponseCode);
          Serial.println(response);
        } else {
          Serial.print("Error on sending POST: ");
          Serial.println(httpResponseCode);
        }
        http.end();  //Free resources
      } else {
        Serial.println("Error in WiFi connection");
      }

The error I'm getting is :

The MAC signature found in the HTTP request
  'sVrSFpplX+Gkcb4R/iSDf6eqUP4srkZuVD68/pAeYwE=' is not the same as any
  computed   signature.....

Although the HMAC signature created from same String works in PHP
here is the reference page of the API:
https://docs.microsoft.com/en-us/rest/api/storageservices/put-blob
Thanks

the http.PUT(d); adds the Content-length header, Host header, User-Agent header, Accept-Encoding header and Connection header. Is it OK for the SharedKey authorization?

It looks like that error message is coming from the web-service; seems like this might be more debugging the webservice, than arudino. What status code are you getting?

the first code uses 'SharedKey mikeiot,' the second code uses 'SharedKey account_name:' could this be the problem? You are also hard coding the content-length in the second code, could you be sending an incorrect amount?

@Juraj I need custom header like given in Arduino code 'addHeader'. It's ok to send these headers. should I skip Content-length header?

@esoterik I'm getting 403 response code from the server and the error message shown in post

@esoterik the acount_name is same in the code just change in the post description. Now I have edited it

I got clue from @esoterik answer and manage to send request successfully.
The problem were in adding header parameter:
 http.addHeader("Content-Length",  "20");

This duplicate the header( 2nd one added in PUT method). I just comment it and the code works.
Thanks for every one response


text:
Arduino timer to turn a serve at a certain time
i am working on a project for my school tech class. Our goal is to make a vehicle that will travel along a cable and drop an egg to a target while going down the cable. i am using an arduino to to open a trap door with a servo after a certain amount of time that is set by two push buttons, and a third push button will control when the timer starts.
Here is my circuit

Here is the code:
#include <Servo.h>
#include <LiquidCrystal.h>

int b = 0;
int up = 0;
int down = 0;
int val = 100;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

Servo myservo;

int pos = 0;

void setup()
{
  pinMode(b, INPUT);
  pinMode(up, INPUT);
  pinMode(down, INPUT);
  lcd.begin(16, 2);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  digitalRead(down);
  digitalRead(up);
  digitalRead(b);
  lcd.setCursor(0, 0);
  lcd.print("milli seconds:");

  while (b == HIGH)
  {
    digitalRead(down);
    digitalRead(up);
    digitalRead(b);
    lcd.setCursor(0, 1);
    lcd.print(val);
    myservo.write(0);
    if (up == HIGH, down == LOW)
    {
      val + 1;
    }
    if (down == HIGH, up == LOW )
    {
      val - 1;
    }

    delay(val);
    myservo.write(100);
    delay(1000);
  }
}

you did not ask any questions ... you also did not say if anything is working incorrectly

The (pull-down) resistor on the top right button in on the wrong leg of the button.

in setup you are calling
pinMode(b, INPUT);
pinMode(up, INPUT);
pinMode(down, INPUT);

but b, up and down all equal 0 so this is what you are doing is :
pinMode(0, INPUT)
pinMode(0, INPUT)
pinMode(0, INPUT)

This doesn't do what you want at all, these need to be assigned to pins. All you are doing is repeatedly setting arduino digital pin 0 to INPUT 3 times.
secondly
while(b == HIGH)

will never fire since b is 0 and is never set to anything else. so it will never == HIGH
Finally,
digitalRead(down);

doesn't do anything useful; what it does is read from pin down which is set to 0, and then drops the return value on the floor
also, this,
if (up == HIGH, down == LOW)

is just very wrong, sholud be
if (up == HIGH && down == LOW)

anyway based on you scematic, fixing this code:
#include <Servo.h>
#include <LiquidCrystal.h>

const int B = 7;
const int UP = 8;
const int DOWN = 9;
int val = 100;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

Servo myservo;

int pos = 0;

void setup()
{
  pinMode(B, INPUT);
  pinMode(UP, INPUT);
  pinMode(DOWN, INPUT);
  lcd.begin(16, 2);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  lcd.setCursor(0, 0);
  lcd.print("milli seconds:");
}

void loop()
{
  // todo: debounce the switches
  int up = digitalRead(UP);
  int down = digitalRead(DOWN);
  int b = digitalRead(B);

  if (up == HIGH && down == LOW)
  {
     val += 1  // todo: handle overflow
  }

  if (down == HIGH && up == LOW )
  {
     val -= 1
  }

  lcd.setCursor(0, 1);
  lcd.print(val);

  if(b == HIGH)
  {
    myservo.write(0);
    delay(val);
    myservo.write(100);
    delay(val);
  }

}

this will do what the origonal code was trying to do, more or less, but the
proper way to do this would be (in psuedo-code):
// Setup pins etc.
// Setup(): pinMode(...) ... etc.
// Loop():
//   debounce buttons
//   handle up/down
//   record milliseconds when button is pressed
//   see how much time has passed
//   trigger servo when timer has passed

thanks for your response but it didn't work. the servo would just move randomly and the timer didn't work it just increased and then reset and increased again.


text:
Arduino UNO and TB67H303HG Ic driver: Wiring question
I would like to control the TB67H303HG (a full bridge driver IC for DC motor
adopting MOS in output transistor) with my Arduino UNO.
This is its datasheet.
I was thinking to connect:

PIN 3 INPUT to Arduino Digital Output 13 and set it to LOW to use the direct PWM mode
PIN 5 Vref to 24VDC
PIN 6 Vcc to 24VDC
PIN 7 STBY to Arduino pin 8
PIN 8 IN1 to Arduino Pin 12
PIN 9 IN2 to Arduino Pin 11
PIN 16 OUT1A and 12 OUT1B in parallel to the Motor
PIN 14 OUT2A and 10 OUT2B in parallel to the Motor
PIN 13 and 17 to GND
PIN 20 Vcc to 24VDC
PIN 22 PWM to Arduino PWM 10

I do not know if I'm wrong, but I think I should use IN1 and IN2 to select the motor spin rotation and the Pin 12 PWM to change the velocity by setting the Arduino pin 10 with the PWM output from 0 to 255. Is it correct?
Can you tell me if the wiring is correct?
Thank you a lot!

The Vref potential should not be 24V. As mentionned in the datasheet:
Vref = 0.3V to 1.95V depending on what you want.

sorry for the mistake, you are right! Thank you for the correction! Do you think the other considerations are OK?

Maybe the pin 23 is to connect with a resistor of 51kOhms ? For the clock


text:
Maximum power rating for Arduino UNO revision 2 (SMD)
I have located the 5V voltage regulator chip on my Arduino board which I am hoping to use to power an attached device (which draws up to 500 mA at 5V).  The chip is next to the plug for the external voltage supply.  It says: ON RUX 117-5.  It looks like it's in a SOT−223 package (body about 6.1 by 3.4mm).
I used this page to shows 3 different possible voltage regulators from ON Semiconductors: https://www.mouser.co.uk/ON-Semiconductor/Semiconductors/Power-Management-ICs/Voltage-Regulators-Voltage-Controllers/LDO-Voltage-Regulators/_/N-5cgac?P=1z0wa29Z1z0xwtvZ1z0zlrjZ1ywvc7yZ1yxz1yoZ1ywvc5z
This gives two unique data sheets for NCP1117LP and NCP1117, NCV1117.  But this is where I'm stuck.  They look pretty similar but not exactly the same data sheets.  Also I don't know what RUX stands for, perhaps this is important in figuring out what power rating the Arduino 5V line has.
Additionally the mouser.co.uk site says they're in SOT-223-3 packages but then gives dimensions which a) aren't the dimensions of the chip I have and b) are the dimensions of the SOT-223-4 package (6.3mm wide instead of the ~6.1 mm I have).
I don't care about the dimensions but I would like to correctly identify the chip on the Arduino board to be able to know what power I can draw from it before it shuts itself down.

The Arduno UNO SMD R2 uses an MCP33269 not an LM1117.What you have is probably some cheap Chinese clone of the Arduino, and in that case the regulator will be the cheapest Chinese copy of the LM1117 available. Impossible to tell what the specs of that specific chip are.Suffice it to say, though, that the specs of the chip are pretty much irrelevant since they rely on good heatsinking, which you most certainly don't have on a little Arduino board.500mA though is a lot to push through a linear regulator like that (depending of course on your unspecified input voltage which is a critical factor).

Better to get a proper switching regulator that can cope with the current without melting.

Thank you very much @Majenko .  It makes sense now that this is a clone (I got it from a friend who would have just ordered it from the cheapest place)... that's what was tripping me up.
Input voltage is 4 x 1.5V AA so ~6V.
I will get a proper step down converter.  Please add as an answer if you wish.

If you're running from batteries then you definitely want the added efficiency of a switching regulator.

@Majenko, OP has in Question NCP1117 not LM1117. According to schematics orginal Uno R3 uses NCP1117ST50T3G

@Juraj I know. The NCP1117 is NCP's copy of the LM1117. The two are one and the same. But that's a moot point since The OP has an R2 not an R3!

ON RUR 117-5 is made by Chinese "ON Semiconductor" :-)

It's definitely ON RUX 177-5 but maybe they made a typo ;P @Juraj

The Arduno UNO SMD R2 uses an MCP33269 not an LM1117.  What you have is probably some cheap Chinese clone of the Arduino, and in that case the regulator will be the cheapest Chinese copy of the LM1117 available.  It's impossible to tell what the specs of that specific chip are.  Suffice it to say, though, that the specs of the chip are pretty much irrelevant since they rely on good heatsinking, which you most certainly don't have on a little Arduino board.
500mA, though, is a lot to push through a linear regulator like that, and when running from batteries the excess power loss imposed by the regulator will be a major factor in longevity.
You are better off investing in a proper switching regulator (such as a UBEC from a model aircraft supplier like Hobbyking).


text:
Compiled sketch vs text file size
OK,so this is my first program written via the Tinkercad utility. I have saved the program as a text file, and it equates to about 22K.
My simple question is, when uploaded / compiled to the actual board, is the size increased or decreased? I plan to use the Nano (32K) If it shrinks or stays roughly the same, I should be OK. However,if it 'bloats' due to extra C code ...
** As someone used to working with sub routines, arrays and variables, found it a bit of a hassle that everything has to be in one loop, only conditional statement breaking the flow - leastin TinkerCAD. And when you want to control 8 LED outputs, having to switch each one on and off via a digital write line. For example, the four output lines below:
11001100
01100110
00110011
10011001

... needs 32 digital write commands !! (And whilst the above is 4 lines, there are nearer 150 similar lines in final code, hence it's size)
The way I wrote it using ths above utility was something like:
for(counter=0; counter<4; counter){
if (counter==0){
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    digitalWrite(4, LOW);
    digitalWrite(5, LOW);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
  }
if (counter==1){
    digitalWrite(2, LOW);
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
    digitalWrite(6, LOW);
    digitalWrite(7, HIGH);
    digitalWrite(8, HIGH);
    digitalWrite(9, LOW);
  }
//etc
}

Though I don't know if this works in Tinkercad, but you can use direct port manipulations to do this. Then you are able to write a complete port (8 outputs) in one statement (actually 1 atomic operation). Have you tried this?

and why do you use TinkerCAD if you can code? use Eclipse with Sloeber plugin. or at least the Arduino IDE

"direct port" ... "1 atomic operation".Sorry, only been coding for four days,so that's gone right overmy head ! WHy use Tinkercad if you can code? Well, I know PERL,HTMLand Javascript ... but Arduino is  all a new game for me

The size of the text file and the size of your compiled code are impossible to relate. The compiled size purely depends on what your code consists of, not the size.
To find out how much room your code will take on the chip you need to compile it. The IDE will then tell you how much flash and RAM it takes.
For example:
Sketch uses 3730 bytes (13%) of program storage space. Maximum is 28672 bytes.
Global variables use 157 bytes (6%) of dynamic memory, leaving 2403 bytes for local variables. Maximum is 2560 bytes.

You can compile the code without even having the board. So you could even compare different boards, before buying. (Though it shouldn't be that different between the nano and the uno)

Thanks for the feedback Majenko. You've sort of said what I thought might happen, that there are certain 'housekeeping' codes that also have to go into the storage space in order to be able to 'read' the text (or ino?) file. The only way to know for sure will be to run it through the IDE,but not save it to board, (if that's even poss: Still very much a noob!)

@Cristofayre In the IDE you can compile the code (called "verify" in the IDE IIRC) which creates a file that can be installed into a board or a later date. Or you can compile and upload in one go. You can just hit the compile (or is it verify?) button and it will convert the C code into machine language for running on the board (the board does not run C) and it tells you how big the result is.

Thanks Majenko. I will look into that. I've also just signed up for an online (FREE) course, so we'll see what I can learn from their coding. (Sorry, I can't 'upvote' your answer at this stage)

Does counter increase somewhere?  As written, it would always be 0, yes?
I would use
for(counter=0; counter<4; counter = counter +1){ // or counter++

You could store your 8 bits in an array
byte ledArray[] = {
0b11001100, // or hex format, 0xCC
0b01100110, // 0x66
0b00110011, // 0x33
0b10011001, // 0x99
};

Then use a function call (subroutine by another name) to manipulate the outputs.

Apologies. You're right, I missed the "counter ++" off the end of the loop. I think what you suggest of "byte ledArray" enters the realm of manual coding, (which, now I know it can be done, might look further) But Tinkercad uses Codeblocks,so the code they build is 'basic'. (And if you switch to manually editing code...you lose all the previous blocks set up!)

What I like about TinkerCad is that it shows the Arduino PCB, and you can add virtual resistors and LED's etc to it, and then you get a visual indication of what the code blocks will do. (But even to add a library, you have to edit manually; no blocks to help.That will be OK once I start to know more of whatI'm doing !)

Not sure of the correct way to do this on the forum, but I have "devised" a possible solution. Since this is my first atttempt at manual coding - jumping in at the deep end - I have posted it as another question, and wondered if those more knowledgable to give it the once over ... especially as it involves arrays, binary 'strings', and reading individual bits !


text:
Remembering a colour
Hey guys I have a led grid. it's 8 sides that are addressable with the bytes '1' through '8'. (a Kinect is sending these bytes through processing)  I have also creates three buttons in processing that change the colour of the leds. ('R','G','B').
I'm stuck in the code, my code now when receiving the bytes: 'R', 'G' or 'B' changes all leds to that colour. instead of remembering the colour and only lighting up the sides determined by the '1', '2', '3', '4', '5', '6', '7', '8' values.
I need it to remember the chosen R,G,B colour until another colour is chosen and only  use the bytes '1', '2', '3', '4', '5', '6', '7', '8' to select what side of the grid to light up.
Here is my code so far:

#include <FastLED.h>

#define LED_PIN     6
#define NUM_LEDS    360

CRGB leds[NUM_LEDS];
CRGB saved_color;

void setup()
{
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(50);

  Serial.begin(9600);

  FastLED.clear();
  FastLED.show();

}

void loop()
{

  if (Serial.available() > 1)
  {
    int incomingByte = Serial.read();

    if (incomingByte > '0' && incomingByte < '9')
    {
      FastLED.clear();
    }

    if (incomingByte == 'R') {
      saved_color = CRGB(255, 0, 0);
    }
    else if (incomingByte == 'G') {
      saved_color = CRGB(0, 255, 0);
    }
    else if (incomingByte == 'B') {
      saved_color = CRGB(0, 0, 255);

    }

    if (incomingByte == '1')
      for (int i = 0; i <= 44; i++) {
        leds[i] = saved_color;
      }

    else if (incomingByte == '2')
      for (int i = 44; i <= 89; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '3')
      for (int i = 90; i <= 134; i++) {
        leds[i] = saved_color;
      }

    else if (incomingByte == '4')
      for (int i = 135; i <= 179; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '5')
      for (int i = 180; i <= 224; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '6')
      for (int i = 225; i <= 269; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '7')
      for (int i = 270; i <= 314; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '8')
      for (int i = 315; i <= 359; i++) {
        leds[i] = saved_color;

      }

    FastLED.show();
  }
}

I'll describe the project a bit more to elaborate. It's a lamp (octagon shape) with 45 leds on the 8 sides. each side is triggered by movement and  sends a byte ('1', '2', '3', '4', '5', '6', '7', '8') to turn on one side of the lamp.
I want to be able to select the colour before sending the bytes. so I need arduino to remember the 'R', 'G', 'B' bytes and only change when I send the other byte.

you receive bytes not 'serials'

I am sending "Bytes" from processing to arduino. 1,2,3,4,5,6,7,8. @jsotola I edited my code

first, you need to identify the problem clearly .... the arduino is receiving data correctly, so kinect and processing are irrelevant .... next, read through your program listing .... what happens if R is received? ... what should happen? .... what happens if 3 is received? ... what should happen?

@jsotola clearly the problem is in the arduino code. I want to know how to remember the R,G,B bytes and how to swap between them.

I don't fully understand what is the expected and what the seen behavior. The code will change all LEDs to one color on R G or B. That what  you have programmed. On 8 only the LEDs 315 to 359 will be set to red, leaving the rest untouched. Is that unexpected?

@chrisl no, 1,2,3,4,5,6,7,8 each do their job. they trigger 45 LEDS on one side of the octagon. but before triggering the sides I want to choose the colour they will become. I want to use RGB bytes to send to arduino, and arduino to remember them and be able to swap between them. I also edited my post

i do not understand why you are unable to set a variable to some chosen value when, for instance, R is received

The array CRGB leds[NUM_LEDS] only holds the current state of the LEDs. It is used to push the data out to the LEDs. If you want the code to save one color to use later, you need an extra variable, that can hold the color.
Add a variable at global scope:
CRGB saved_color;

In the if statements for R, G and B you can set this variable to the corresponding value, for example:
if(incomingByte == 'R'){
    saved_color = CRGB(255,0,0);
}

And in the if statements of 1 to 8 you can use this value, for example:
if (incomingByte == '1'){
    for (int i = 0; i <= 44; i++) {
        leds[i] = saved_color;
    }
}

Note: The above code does not change any LEDs on R, G or B. They just set the color for future operation 1 to 8.

Okay, and how do I make it switch? would that be with the else if statement? I have updated my post to show my code with your tips

What do you mean? You would send R, G or B to select the corresponding color (red, green, blue) for the future action 1 to 8. So if you send an R, the lamp will have the color red preset (not lighting up). If you then send 4, the side 4 will light up in red. If you then send 2, side 2 will light up in red. If you then send G, the internal preset will be set to green (not changing the lights yet). If you then send 5, side 5 will light up in green.

nevermind sir, I spoke too soon. it's working now bro!!! thank you so much


text:
How does use an arduino like a A/D converter for convert 3 analogue signal from 3 poteciometer to a raspberry?
I am developing a control system in my raspberry, but i have the problem that it doesn't have any analogue port, so if i use an arduino to convert de signal from analogue to digital and after send this signal into a I/o digital port from anduino to raspberry, thas is posible?
my plan was receive the analog signal in arduino and transforms here in a digital signal and after send it by Digital port to rasberry

It is not clear what you mean by “digital port”. The simplest mean to
communicate from the Arduino to the Raspberry is to use the Arduino's
serial port, which gets into the Raspberry Pi through USB. Just like you
would do if you had a PC instead of the Raspberry:
/*
 * Continuously report the analog readings on pins A0 through A2.
 */

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

void loop() {
    Serial.print("0 "); Serial.println(analogRead(A0));
    Serial.print("1 "); Serial.println(analogRead(A1));
    Serial.print("2 "); Serial.println(analogRead(A2));
}

This program will continuously output a text stream like this:
0 145
1 220
2 865
0 142
1 223
...

where the first column is the analog channel number and the second
column is the ADC value. How you handle this stream on the Raspberry
side is up to you.

i could manipulate this data in my rasberry? to make a controller?

@JesusMiguelHerrera: Of course! It's your data, you do whatever you want with it.

the last question, how could i activate the serial port in my raspberry with the goal of receive this signal?

@JesusMiguelHerrera: On the Raspberry side, the serial port (usually /dev/ttyACM0) is activated by connecting the USB cable.

thank you edgar i will proud this


text:
Arduino Nano drivers
I got a Arduino Uno awhile ago and it took me awhile to set up but it worked when I downloaded the IDE. This time when I bought an Arduino Nano it doesn't pop up with the driver. Doesn't show up anywhere in device manager. I've tried to reinstall the IDE to see if that would work but it didn't. What should I do/try next?

Is it a real Nano or did you get some cheap POS from eBay / Amazon?

@Majenko That was quick, yes it is a real one. Arduino Nano A000005.

I'm not sure if the IDE comes with the FT232RL drivers any more - if it doesn't you may need to manually install them from the ftdichip website.

I downloaded a FTDI VCP driver and I ran it until nothing popped up anymore but after all of that nothing happened nothing in device manager still. Doesn't make any sound when I plug it in.

Check your usb cable.

It is on if thats what you're saying, green light on the top

That means nothing. Some cheap usb cables lack data wires. Power works but nothing else.

Well I did burn out the cables that I used last night so I'm gonna have to go find another one

How the hell do you burn out a usb cable?!?!

12v through usb hub but I found another cable and it works lol ty for suggestions. :)


text:
Measure position of gear with arduino
So, my plan is to be able to turn a motor, with a gear on the end, for a certain amount of gear teeth then stop it. I can’t find a data sheet for the motor but it is very fast, brushed and DC. I was thinking putting something like this below the gear so when a tooth goes past, it turns on and off. Like I said before the motor is very fast (faster then being able to see the teeth as it spins)  and I don’t think the arduino will be able to read that kind of speed with digital read, I may be wrong. Any suggestions would be appreciated. Thanks.
EDIT:
The motor runs off 2 cell or three cell lipo which is 7.4-11.1v, it’s maximum current is 20 amps.
Edit: For anyone wondering how to use the sensor, the datasheet is here and it shows the positions of the collector, emitter, anode and cathode.

I know, it’s not helpful at all but I couldn’t find a data sheet and I wanted to say it’s going much too fast to see

you could certainly try that sensor .... paint one of the gear teeth white

I am sure Arduino is fast enough to read the frequency of a gear

You can try to use an encoder attached to the shaft of the motor in this way you can measure the amount of steps per turn and thus you can calculate when and how you turn the motor. Or just get a stepper motor. And for the concern that the Arduino is not fast enough you can use interrupts which are very fast.

unfortunately, for the application in airsoft, it needs to be very compact and sit below the gear, hence why I thought using some sort of IR sensor would be appropriate.

If memory serves, the clock speed of an arduino Uno is 16Mhz. Some are faster, some much faster and a few are slower.
Most assembler instructions take around 1-3 clock cycles. A few take more. Assuming an average of 3 ticks per instruction, that translates to executing over 5 million instructions per second.
So, unless your motor is approaching supersonic speeds, the arduino should be able to "keep up" with polling your motor's sensor in your loop() function.
If you are doing a few other things in your loop, you might consider using an interrupt to trigger some code when the motor "activates" the sensor. In this case you will unlikely need to worry about the speed of the CPU at all. When using an interrupt, you do not need to worry about polling the state of your sensor inside the loop() function.
Always remember to keep the code in your interrupt service routine as short and fast as possible. In this case, probably you would just turn off the motor and return when the interrupt is triggered.
Having said all of that, you will still need to do some work to get the most appropriate implementation as only you know what other things you need to take into account at this time.
One other thing to note is that a single high level instruction will normally equate to more than one assembler instruction. Even a simple statement like int x = 1000; will be more than one assembler instruction and thus take more than 1 clock tick. However, if memory serves, the individual instructions generate to execute x = 1000 will all take just one clock tick.
Others will vary the amount of instructions that are generated to execute them. For example

float x = 1.0;
x = x + 2.0;

will likely take more instructions to execute than it's integer counterpart:

int x = 1;
x = x + 2

I hope this helps and enables you to try controlling your motor via Arduino. If not, you can always ask a more specific question later.

Thank you very much, this is unbelievably helpful. I’ll have to try and condense my code down. Do you know if that sensor will pick up the gear even if it’s not painted white? Thanks

Sorry, i am not familiar with that particular sensor. I suggest scrutinising the data sheet on the web page; Asking the manufacturer; And/or posting a new question either here or on the Electronics site.

Alright, I’ll take a look at the datasheet first. Thanks