text:
Convert C string to C++ string
My program is running on ESP32. I'm retrieving some data from Bluetooth, and the Bluetooth string is a C string. I need to save that data in an RTC_DATA_ATTR String, which is a C++ string.
Just doing c++string = cstring.c_str(); won't work, since it will just save a pointer to the location in the memory of the C string, and the purpose is to save the data in the RTC memory, so the ESP32 can go to deep sleep without losing the data.
All other data than RTC gets wiped on deep sleep, so there would just be a pointer, pointing to nothing.
How do I get the data copied from the C string to the C++ string?
Any help would be appreciated. A bit of extra info: this is how it is set up at the moment:
RTC_DATA_ATTR String ssid;

BLECharacteristic *cSsid = NULL;

ssid = cSsid->getValue().c_str();

you mixed it up. you want a C string from String? .c_str() of String returns a constant pointer to the internal C string (zero terminated char array) of String which is in heap. but to save it to RTC memory something must copy it to the RTC memory. it is not neccessary to copy it into 'C string' in memory.

yes, my question is: how do i copy the c string to my rtc memory

I agree with  @Juraj . I believe you misused the terms cstring and c++ strings. As I understand your question, you have a class  RTC_DATA_ATTR that allocates its content memory (string typed) from the RTC EEPROM. Now you ask how you are able to initialize that Class with content from a "cstring". (as you use .c_str() I believe this is also a c++ string) Because I don't know the library RTC_DATA_ATTR is from I can not say how to copy text into a string of that type. You should at least add the library name to the question or give us some information what that type is like.

Your code would lead to a null pointer exception, which will be silently skipped..

i have no idea what library the RTC is apart of, I haven't #include any library which it is in

it doesnt give any error, when i compile it, but in the serial monitor, it println(rtcstring)  just prints clear line, as if rtc string was = null

i would guess the RTC and Deep_sleep commands come from the installed board in ArduinoIDE

but all im looking for is a way to copy the value of the string from bluetooth into the RTC string, which in my head the solution should just be todo: =

RTC_DATA_ATTR char ssid[33]; strcpy(ssid, cSsid->getValue().c_str());

A null pointer is a runtime error, which you can not see at compile time. In the arduino context you will not recognize the null pointer exception. But I'm sure you get one as you initialized the BLECharacteristic *cSsid = NULL; and then used the null pointer cSsid->getValue(). Or did I missed something and NULL is an option object? Can C++ handle option objects in the meantime? But anyway whithout knowing the library I can not help you. If you just want to make your string persistent you could probably write it to the FLASH memory. https://randomnerdtutorials.com/esp32-flash-memory/

solution found, using the strcpy, thanks

Sorry, now I understand what you tried. Yes it's part of the ESP32 software. And you might not want to store the date in EEPROM, just make it persistent while deep sleep. (I think I should go to sleep now ;-) ) https://randomnerdtutorials.com/esp32-timer-wake-up-deep-sleep/ @Juraj gave you the solution. But the null pointer problem is still there. Or is this not all of the code.

simply, using strcpy, and using a char with a given length, works
RTC_DATA_ATTR char ssid["dedicated length"];
strcpy(ssid, cSsid->getValue().c_str(), "dedicated length");


text:
Test for wrong Wifi password?
Maybe this is a dumb question, but is there a way to test for wrong Wifi password?
I know you can do WL_CONNECT to check if the password works, but is there a command for checking if the password is wrong? Not just by waiting.

my esp is trying to connect to the WiFi

i guess that makes my esp client

https://github.com/esp8266/Arduino/blob/40f456aca3a568a09a5bec275b36a79869ce8bef/libraries/ESP8266WiFi/src/ESP8266WiFiSTA.cpp#L633

there's no way to tell if a password is right or wrong other than by trying to use it.

@dandavis but the WiFi class does not return the info even though it's available. It simply returns an error.

@Juraj I think this comment is worth to be posted as an answer as it might be really useful for others in the future.

The information is available on SDK level. If you include #include "user_interface.h", you can use function wifi_station_get_connect_status(). It returns one of:
STATION_GOT_IP
STATION_NO_AP_FOUND
STATION_CONNECT_FAIL
STATION_WRONG_PASSWORD
STATION_IDLE

The WiFi.status() function uses function wifi_station_get_connect_status(),  but returns WL_CONNECT_FAILED for STATION_WRONG_PASSWORD.

one can check for wrong password using the following code snippet
  if (WiFi.status() == WL_CONNECTED)
  {
    Serial.println("Connected successfully");
  }
  else if (WiFi.status() == WL_NO_SSID_AVAIL)
  {
    Serial.println("Wifi network is not avaliable");
  }
  else
  {
    Serial.println("Password is not correct");
  }

more information can be found on GitHub here:
https://github.com/aeonSolutions/aeonlabs-ESP32-C-Base-Firmware-Libraries

source: Stack Exchange

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

sort: votes


text:
Why does the standard Arduino IDE not include the CH341G USB Drivers?
Can anyone explain why the standard Arduino IDE 1.6 distribution does not include support for the popular CH341G USB/serial drivers?
I am using these USB/serial chips in several teaching projects for CoderDojo and it is somewhat difficult to have each student download the drivers and reboot their PCs for each class. It seems like both Mac and PC users would benefit from having these drivers loaded directly into the standard Arduino IDE.
Is there possibly some security concern? I know that the latest Mac requires that the drivers are digitally signed. In fact for many modern Macs to use the drivers we have to disable the digital signature checks.
Here is the link to the official drivers.
Here is a good article on how to download the drivers.
BTW, the command to disable the digital signature check on the mac we need to do the following:
In the Mac "Terminal" application enter:
sudo nvram boot-args="kext-dev-mode=1"

Then we must reboot the mac. Then when we want to re-enable the checks change the 1 to 0:
sudo nvram boot-args="kext-dev-mode=0"

If we don't do this command, the Arduino App will not show the serial ports. Do to this go to Tools -> Port Menu within the Arduino application.
/dev/tty.SerialPort
/dev/cu.SerialPort

I should mention that the CH340G are also used in many "Arduino Nano" clones from China. Perhaps that is why the drivers are not included?
Tags: Driver CH340 Setup Installation

Because no Genuino uses them.

A question about why the Arduino company does not ship certain drivers would be best addressed to them. We would have no way of knowing why they made that decision.

This is simply because the CH340G is not supported officially. The Arduino IDE is meant primarily for genuine Arduinos.
What you could do is repackage the Arduino zip file with the required library and create a basic script file to install the drivers with just a couple of clicks.
Or you could shift to another board that uses the ATMEGA32u4 as this might not require anything special. Have a look here. I don't have tested this board so you will need to check the quality and whether it works with your projects.

I should mention that the CH340G are also used in many "Arduino Nano" clones from China.

I believe that the Arduino company already has concerns about the number of unofficial clones (many pretending to be genuine) and have lost a considerable amount of revenue to those knock-off products.
I imagine they are not going to make things worse for themselves by including drivers for unofficial boards, so that the job of the clone-makers is even easier.

Remember that Arduino driver is for the USB/Serial chip, not the Arduino Nano devices that included it.  I am not sure it is fair to discriminate against a USB/Serial chip manufacturer just because their chip is preferred by some products.

That is a unique and bizarre interpretation of the word "discriminate". By that definition, Arduino "discriminates" against sound card creators by not including any sound card drivers with their IDE.

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


text:
Arduino, exit status 1. Can't compile for Arduino Uno
#include <LedControl.h>

void setup() {
// put your setup code here, to run once:
}

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

This is my code: with LedControl.h it gives me exit status 1, can't compile for Arduino Uno. Please help.
If I remove the #include it works normally.
Also Arduino says that the library has been installed.
What I have tried (but didn't work):
Re-installing the library.
Re-downloading Arduino.

"Exit status 1" means "there was an error". You forgot to tell us what that error is.

@Majenko  "exit status 1 can't compile to arduino uno" it's literally in the title

No, that is NOT the error message. Paste in the entirety of what is in the output pane if you don't understand what an error message is.

Don't cross post. You already asked this on Stack Overflow.

@gre_gor I was told on stackoverflow to ask my question here

@nordinleije Did you check the link?

I tried compiling your code with Arduino 1.6.12. As you found, without the #include, it compiles OK. With the #include, it fails. Here is the error message I got:
/var/folders/bl/s5kzhm3s0lb2rcvp3md8c7040000gp/T/untitled1814027053.tmp/sketch_may17a/sketch_may17a.ino:1:24: fatal error: LedControl.h: No such file or directory
 #include <LedControl.h>
                        ^
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno 115.2.

The error - at least in my case - is that the library, LedControl.h, was not found. Try to find out why not.

also aruino says that the library has been installed.

It's easy to check: "Installing" library foo.h, only means your sketchbook folder contains a library folder called libraries (all lower case); libraries contains a folder foo; and foo contains the file foo.h and any other files necessary for that library, such as a foo.cpp if needed:
- Sketchbook - libraries - foo
                             foo.h
                             foo.cpp
                             anything.else.you.like

Update:
The library documentation is on github and has links to some sample code. Sorry I can't be more help - I haven't used the library or those LED devices.

thank you for you anwer, could you please also show how to use this library properly I kinda need it, because I use a MAX7219 LED.

how to use this library properly ... don't get ahead of yourself .... you don't even know if you have the library installed

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


text:
Xbee can send from arduino to XCTU, but not the other way around
I have two arduinos that I would like to use to communicate with two xbees. I programmed both xbees with the xbee explorer breakout boards in XCTU, and got them to communicate on XCTU. They are XB24Cs, with the Zigbee function set, both on the same PAN ID, one as a Coordinator and one as a router, not on API mode. When I put the router on an xbee shield on an arduino, I run a program on the arduino that should allow me to communcate both ways, However I can send something through the serial and have it show up on the XCTU, but anything typed in XCTU will not show up in arduino. The arduino shield is the sainsmart xbee pro shield, and I tried it both with the jumpers in USB and XBee mode, however I can only ever upload first when it is on USB mode. How can I make communication possible from the computer to the arduino?
Here is my arduino code:
#include <SoftwareSerial.h>
SoftwareSerial Xbee(2,3);

void setup() {
  Xbee.begin(9600);
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
 Serial.println("test");
 delay(1000);
  if(Xbee.available()){
    Serial.println(Xbee.read());
  }
  if(Serial.available()){
    Xbee.write(Serial.read());
  }
}

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


text:
Attiny13 analogread() not working on all pins
I am new here and perhaps you could help me. I am trying to program Attiny13 with the following short sketch which uses ADC (analogread()) function, that is supposed to work like this:

reads voltage from voltage divider using photoresistor - analogread() from A1 (ADC1)
turns LED on/off whenever there is low light (covering photoresistor) - digitalwrite() LED at 3 (PB3)

however it does not work on each of the ADCs:
- works when I use A3 (ADC3) as analogread
- does not work when I use A1 (ADC1) or A2 (ADC2) as analogread
Do you know what might be the reason? Same code, but works on 1 of the ADCs only.
I program uC with USBASP programmer, but I don't think this matters since with 1 of the ADCs all works fine. Also it works on Arduino Mega 2560 and uC Atmega88, so something wrong with Attiny13.
Sketch that does not work:

int state = 0;

void setup()
{
pinMode(3, OUTPUT);
}

void loop()
{
    int reading = analogRead(A1);

    if (reading < 100) // ONCE I COVER PHOTORES. IT GOES INTO THIS LOOP AND TURNS ON/OFF THE LED
    {
        state = !state;
        digitalWrite(3, state);
        delay(200);
    }

    delay(100);
}

Please add links to attiny core and version info. for all components and tools.

Agreed. The fault will be in the definitions for the "board" or the core - whatever that may be for your setup.


text:
Get Battery voltage on raw
I power my Arduino Mini with 3 AA batteries on RAW input. Is it possible to get the voltage on RAW and therefore the expected longevity of the batteries?

No. Not directly. You can use voltage divider and measure the result with using internal reference. But it's another current consumption and you can't reduce it by (for example) entering one of the sleep modes.
And if you have 5V Arduino Mini variant, you can power it directly through 5V power pin. Otherwise you are losing about 1.5V on voltage regulator. On 3.3V variant it might be better, but it also depends on used regulator voltage drop and would be better to power it directly (if you don't have connected anything strictly with 3.3V power, and for AVR based Arduinos it's not a problem)
Anyway, if you power it directly, you can measure the power source voltage by measuring internal bandgap voltage reference against power as reference. But, as far as I know, it can't be done by analogRead, as it doesn't support other sources than analog pins.

What you can do is making a voltage divider using high value resistors and read that out on an analog pin. This isn't super accurate but gives an impression of the state of your batteries.

@Len Yes, I just don't like voltage dividers on batteries, when you need output impedance about 10k. However it's possible to use big resistors and capacitor big enough to charge sampling capacitor without bigger voltage drop.

Voltage dividers on batteries for measuring the voltage with the device they are powering can only work if the battery voltage is greater than the regulator voltage + dropout - otherwise your VRef will be a percentage of the battery voltage which makes measuring a percentage of the battery voltage meaningless. You need a stable reference (such as the band-gap) to measure what the Vref (Vcc) is. https://hackingmajenkoblog.wordpress.com/2016/02/01/making-accurate-adc-readings-on-the-arduino/

@KIIV I completely agree, I don't like it either but it is something. Majenko also points out some solid information.

You can indeed use a stable builtin voltage as reference. So you can check it against the max voltage.

Using internal voltage reff with voltage divider will solve your problem. Some arduino have 2.5v internal voltage reff while some have 1.1v


text:
WS28213B Loop 241230
Hello Stack Exchange Arduino,
Running LED strip WS2812B using
Arduino compatible SEEED XIAO SAM D21
microcontroller.

Code marked
"WS2812b_turn_on_and_off_w_for_241230_ino"copied
herewith below, turns on all strip LEDs in twp
colors for a second and a half, then turns the LEDs
off for one tenth of a second.
These two phases begin when the PCB is powered
and continues going on and off until power
is disconnected
Code marked
"WS2812b_move_three_241230.ino" also copied
below, chases groups of three LEDs across
the strip once and stops.
It was expected that the Move Three function
would repeat because it is in the void Loop()
section but it only runs once.
Why does the Move Three function not loop?
Thanks.
Allen Pitts
++++++++++ WS2812b_turn_on_and_off_w_for_241230_ino  +++++++++
#include <FastLED.h>

#define LED_PIN     3
#define NUM_LEDS    150

CRGB leds[NUM_LEDS];

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

void loop() {
 // for (int i = 0; i < 146; i = i + 2) {
  for (int i = 0; i <= 146; i = i + 2) {
    // turn on
    leds[i] = CRGB(255,160,16);
    // Show the leds
    FastLED.show();
    //delay(50);
  }

  for (int i = 1; i <= 146; i = i + 2) {
    // turn on
   leds[i] = CRGB(0, 255, 0);
    // Show the leds
  FastLED.show();
//delay(50);
 }

   delay(1500);

  for (int i = 0; i < 150; i++) {
    // turn off
    leds[i] = CRGB(0, 0, 0);
    // Show the leds
    FastLED.show();
   // delay(10);

  }
}

++++++++++ end of WS2812b_turn_on_and_off_w_for_241230_ino  +++++++++
++++++++++ WS2812b_move_three_241230.ino  +++++++++
#include <FastLED.h>

#define DATA_PIN    3
#define NUM_LEDS    150
#define BRIGHTNESS  10
#define LED_TYPE    WS2812B
#define COLOR_ORDER GRB

// Define the array of leds
CRGB leds[NUM_LEDS];

#define UPDATES_PER_SECOND 100

void setup() {
  FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
  FastLED.setBrightness(BRIGHTNESS);
}

void loop() {
  for (int i = 0; i < NUM_LEDS; i++) {
    leds[i]     = CRGB::Red;
    leds[i + 1] = CRGB::Green;
    leds[i + 2] = CRGB::Blue;
    FastLED.show();
    delay(.9);
    for (int i = 0; i < NUM_LEDS; i++) {
      leds[i] = CRGB::Black;
      delay(.7);
    }
  }
}

++++++++++ end of WS2812b_move_three_241230.ino  +++++++++

Please give a detailed description of what you expected to happen and what actually happened. Ther is so move three function in the second code. And what does the first code have to do with your question?

put the programming ideas from the first sketch in your second sketch ... increment the for loop by three ... correct the delay(.9); and delete everything after it


text:
What type of power supply is the Arduino Due’s 5v pin and what is its current?
I’m looking to use a Futaba Servo with my arduino Due and was told it requires a “high current 5 volt supply” and I don’t know much about current so excuse my arrogance.
I know the arduino Due has a 5 volt pin. But what type of power supply is it? (Linear power supply, switching power supply, etc.) and how much current does it provide? If I get this information to my instructor he can tell me if it will suffice.
Thank you!

An Arduino should not be used as a power supply for a servo. The 5V pin is connected to the the 5V supply of the USB connector, OR to the output of a step-down buck regulator converting the DC barrel jack to 5V.
None should be considered "high current" for servo or motor use.
Most PC USB ports will max out at 500mA current output unless the device connected asks for more from the PC. The Arduino does not.
The buck-converter controller chip is a LM2434, whose datasheet specifies 1A maximum output current.
Driving motors or servos will draw enough current, intermittently, to overload either of those and will likely cause the Arduino to reset.
If you need to power a motor-type device, power it separately from the control signals. Power should go from the source to the motor, and the control signal from the Arduino to the servo, making sure to connect the ground wires of all to each other (motor, Arduino, power source).

Thank you! So just to confirm.. powering the servos from the 5v pin is a bad idea and I should instead find a 5 volt 1A battery to directly power the servos? Thank you for your help

Don’t power a servo through the 5V pin. However you power the servo, just avoid making the Arduino the power supply.


text:
Help reading orientation from gyroscope
I recently bought a L3GD20H Triple-Axis Gyro to use it to measure orientation, but found out it instead reports the rate of rotation in degrees per second. I was told this means that to detect the total degrees of rotation, I need to integrate the rate of rotation over time.
I was wondering if someone could help me with this since I'm having trouble wrapping my head around a formula to create. here is my code so far if it helps:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_L3GD20_U.h>

/* Assign a unique ID to this sensor at the same time */
Adafruit_L3GD20_Unified gyro = Adafruit_L3GD20_Unified(20);

void displaySensorDetails(void)
{
  sensor_t sensor;
  gyro.getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" rad/s");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" rad/s");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" rad/s");
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

void setup(void)
{
  Serial.begin(9600);
  Serial.println("Gyroscope Test"); Serial.println("");

  /* Enable auto-ranging */
  gyro.enableAutoRange(true);

  /* Initialise the sensor */
  if(!gyro.begin())
  {
    /* There was a problem detecting the L3GD20 ... check your connections */
    Serial.println("Ooops, no L3GD20 detected ... Check your wiring!");
    while(1);
  }

  /* Display some basic information on this sensor */
  displaySensorDetails();
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  gyro.getEvent(&event);

  /* Display the results (speed is measured in rad/s) */
  Serial.print("X: "); Serial.print(event.gyro.x); Serial.print("  ");
  Serial.print("Y: "); Serial.print(event.gyro.y); Serial.print("  ");
  Serial.print("Z: "); Serial.print(event.gyro.z); Serial.print("  ");
  Serial.println("rad/s ");
  delay(1);
}

So in summary, I need help creating the code/a formula that will use my Gyro to measure its orientation. Thank you for your time! I'm very lost.

To “integrate” is a slight oversimplification: you will have to compose many small rotations in order to get the current orientation. You should probably search for a library that does that for you, unless you are willing to dig into the heavy math.

Take a look at this example.
#include <Wire.h>

const int MPU = 0x68; // MPU6050 I2C address
float AccX, AccY, AccZ;
float GyroX, GyroY, GyroZ;
float accAngleX, accAngleY, gyroAngleX, gyroAngleY, gyroAngleZ;
float roll, pitch, yaw;
float AccErrorX, AccErrorY, GyroErrorX, GyroErrorY, GyroErrorZ;
float elapsedTime, currentTime, previousTime;
int c = 0;

void setup() {
  Serial.begin(19200);
  Wire.begin();                      // Initialize comunication
  Wire.beginTransmission(MPU);       // Start communication with MPU6050 // MPU=0x68
  Wire.write(0x6B);                  // Talk to the register 6B
  Wire.write(0x00);                  // Make reset - place a 0 into the 6B register
  Wire.endTransmission(true);        //end the transmission
  /*
  // Configure Accelerometer Sensitivity - Full Scale Range (default +/- 2g)
  Wire.beginTransmission(MPU);
  Wire.write(0x1C);                  //Talk to the ACCEL_CONFIG register (1C hex)
  Wire.write(0x10);                  //Set the register bits as 00010000 (+/- 8g full scale range)
  Wire.endTransmission(true);
  // Configure Gyro Sensitivity - Full Scale Range (default +/- 250deg/s)
  Wire.beginTransmission(MPU);
  Wire.write(0x1B);                   // Talk to the GYRO_CONFIG register (1B hex)
  Wire.write(0x10);                   // Set the register bits as 00010000 (1000deg/s full scale)
  Wire.endTransmission(true);
  delay(20);
  */
  // Call this function if you need to get the IMU error values for your module
  calculate_IMU_error();
  delay(20);

}

void loop() {
  // === Read acceleromter data === //
  Wire.beginTransmission(MPU);
  Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 6 registers total, each axis value is stored in 2 registers
  //For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
  AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
  AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
  AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value
  // Calculating Roll and Pitch from the accelerometer data
  accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * 180 / PI) - 0.58; // AccErrorX ~(0.58) See the calculate_IMU_error()custom function for more details
  accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * 180 / PI) + 1.58; // AccErrorY ~(-1.58)

  // === Read gyroscope data === //
  previousTime = currentTime;        // Previous time is stored before the actual time read
  currentTime = millis();            // Current time actual time read
  elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
  Wire.beginTransmission(MPU);
  Wire.write(0x43); // Gyro data first register address 0x43
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 4 registers total, each axis value is stored in 2 registers
  GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
  GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
  // Correct the outputs with the calculated error values
  GyroX = GyroX + 0.56; // GyroErrorX ~(-0.56)
  GyroY = GyroY - 2; // GyroErrorY ~(2)
  GyroZ = GyroZ + 0.79; // GyroErrorZ ~ (-0.8)

  // Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
  gyroAngleX = gyroAngleX + GyroX * elapsedTime; // deg/s * s = deg
  gyroAngleY = gyroAngleY + GyroY * elapsedTime;
  yaw =  yaw + GyroZ * elapsedTime;

  // Complementary filter - combine acceleromter and gyro angle values
  roll = 0.96 * gyroAngleX + 0.04 * accAngleX;
  pitch = 0.96 * gyroAngleY + 0.04 * accAngleY;

  // Print the values on the serial monitor
  Serial.print(roll);
  Serial.print("/");
  Serial.print(pitch);
  Serial.print("/");
  Serial.println(yaw);
}

void calculate_IMU_error() {
  // We can call this funtion in the setup section to calculate the accelerometer and gyro data error. From here we will get the error values used in the above equations printed on the Serial Monitor.
  // Note that we should place the IMU flat in order to get the proper values, so that we then can the correct values
  // Read accelerometer values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    // Sum all readings
    AccErrorX = AccErrorX + ((atan((AccY) / sqrt(pow((AccX), 2) + pow((AccZ), 2))) * 180 / PI));
    AccErrorY = AccErrorY + ((atan(-1 * (AccX) / sqrt(pow((AccY), 2) + pow((AccZ), 2))) * 180 / PI));
    c++;
  }
  //Divide the sum by 200 to get the error value
  AccErrorX = AccErrorX / 200;
  AccErrorY = AccErrorY / 200;
  c = 0;
  // Read gyro values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x43);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    GyroX = Wire.read() << 8 | Wire.read();
    GyroY = Wire.read() << 8 | Wire.read();
    GyroZ = Wire.read() << 8 | Wire.read();
    // Sum all readings
    GyroErrorX = GyroErrorX + (GyroX / 131.0);
    GyroErrorY = GyroErrorY + (GyroY / 131.0);
    GyroErrorZ = GyroErrorZ + (GyroZ / 131.0);
    c++;
  }
  //Divide the sum by 200 to get the error value
  GyroErrorX = GyroErrorX / 200;
  GyroErrorY = GyroErrorY / 200;
  GyroErrorZ = GyroErrorZ / 200;
  // Print the error values on the Serial Monitor
  Serial.print("AccErrorX: ");
  Serial.println(AccErrorX);
  Serial.print("AccErrorY: ");
  Serial.println(AccErrorY);
  Serial.print("GyroErrorX: ");
  Serial.println(GyroErrorX);
  Serial.print("GyroErrorY: ");
  Serial.println(GyroErrorY);
  Serial.print("GyroErrorZ: ");
  Serial.println(GyroErrorZ);
}

https://howtomechatronics.com/tutorials/arduino/arduino-and-mpu6050-accelerometer-and-gyroscope-tutorial/

Do not do Wire.read()<<8|Wire.read(): the C++ language does not guarantee the order of evaluation of the two calls to Wire.read(). Do val=Wire.read()<<8;val|=Wire.read() instead. Also, this naive integration will only work if the roll and pitch angles remain small.


text:
Using c_str() on String for IPAddress with NTPClient provides wrong values
Libraries

NTPClient

Board
Olimex ESP32-POE board
Behaviour
I have written a code that connects the board to a local NTP Server (which is an embedded board). I tried assigning the IP Address of the above NTP Server using IPAddress and then convert it to c_str() to pass into the NTPClient constructor as follows:

 WiFiUDP ntpUDP; // udp socket object for NTP

 IPAddress NTPServer(192.168.3.11); // Local NTP Server IP Address

 NTPClient timeClient(ntpUDP, NTPServer.toString().c_str(), 0, 60000);

The reason for this is because the NTPClient class uses const char* for the IP Address of the NTP Server.
The values that are obtained once the code is flashed on the board are wrong because the timestamps are have the year 2106.
On the contrary, when I use
 NTPClient timeClient(ntpUDP, "192.168.3.11", 0, 60000);

and run the code on the board, this provides me perfect values of UTC time.
Why is there some discrepancy here?
Code
#include <Wire.h>
#include <ETH.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
#include <RTClib.h>

WiFiUDP ntpUDP;
/* IP CONF for NODE */
///////// >>>> MODIFY Values Here <<<< ////////
const IPAddress node_static_ip(192, 168, 3, 101);
const IPAddress default_gateway(192, 168, 3, 250);
const IPAddress subnet_mask(255, 255, 255, 0);
const IPAddress dns_add(192, 168, 3, 250);
const IPAddress NTPServer(192, 168, 3, 11);

NTPClient timeClient(ntpUDP, "192.168.3.11", 0, 60000); // This works
NTPClient timeClient(ntpUDP, NTPServer.toString().c_str(), 0, 60000); // This won't (provides timestamps of 2106)

void setup() {
  // put your setup code here, to run once:
  Wire.begin(I2C_SDA, I2C_SCL);
  Serial.begin(115200);
  ETH.begin();
  ETH.config(node_static_ip, default_gateway, subnet_mask, dns_add);
  delay(1000);
  if (!rtc.begin()) {
    Serial.println("No RTC");
  }
  timeClient.begin();

}
void loop() {
  // put your main code here, to run repeatedly:
  timeClient.update();
  Serial.println(timeClient.getEpochTime());
  DateTime now_time(timeClient.getEpochTime());
  Serial.print(now_time.year(), DEC);
    Serial.print('/');
    Serial.print(now_time.month(), DEC);
    Serial.print('/');
    Serial.print(now_time.day(), DEC);
    Serial.print(now_time.hour(), DEC);
    Serial.print(':');
    Serial.print(now_time.minute(), DEC);
    Serial.print(':');
    Serial.print(now_time.second(), DEC);
Serial.println();

  delay(2000);

}

Don't you mean toString().c_str(), not toString.c_str()?

Sorry Typo! I meant the latter.

I thought so, since the former doesn't compile.  A simple test of printing to serial works fine. I suggest adding that into your program to make sure it's actually converting it wrong and not something else.  Serial.println(NTPServer.toString().c_str());

The String object created as return from IPAddress.toString() as parameter to constructor of NtpClient is temporary. It contains the char array returned by c_str(). NTPClient doesn't copy the string, only stores a reference to it. And the referenced string (char array) doesn't exist at the time the NTPClient wants to use it.
class TestClass {
public:
  TestClass(const char* _ip) : ip(_ip) { }

  void test() {
    Serial.println("--");
    Serial.println(ip);
    Serial.println("--");
  }

private:
  const char* ip;
};

//String s("abc");
//TestClass Test(s.c_str()); <- this works

TestClass Test(String("abc").c_str()); // <- this can't work

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


text:
Wemos D1 mini freezing after a few minutes
I´m using a Wemos D1 mini board to control a RGB LED Strip and programmed a simple code with the Arduino IDE. The Wemos conects to my Internet just fine and with the IP adress I can change the RGB values of the Strip. Everything works but after a few minutes the board freezes and nothing works. After a reset it works again.
I also conected a simple circuit to the board just to controle a RGB-LED Strip with a few transistors nothing that should cause an issue and also if i conect nothing to the board the problem occurs.
I also tested a example from the Wemos Library but there is the same problem.
Here is my code I used (And sorry if the code isn´t that well programmed I´m a beginner ;)):

#include <ESP8266WiFi.h>

const char* ssid = "my SSID";
const char* pass = "my password";

void setup() {
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D5, OUTPUT);

  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) delay(500);

  Serial.begin(9600);
  //Serial.println(WiFi.localIP());
  server.begin();
}
void setColor(String rgb)
{
  String rgb_val = rgb.substring(4, rgb.lastIndexOf('H'));
  String red_val = rgb_val.substring(1,rgb_val.indexOf(':'));
  String green_val = rgb_val.substring(rgb_val.indexOf(':') + 1,rgb_val.indexOf(':',rgb_val.indexOf(':') + 1));
  String blue_val = rgb_val.substring(rgb_val.lastIndexOf(':') + 1);
  int redval = red_val.toInt();
  int greenval = green_val.toInt();
  int blueval = blue_val.toInt();
  analogWrite(D5, redval);
  analogWrite(D2, greenval);
  analogWrite(D1, blueval);

  redval = redval >= 1023 ? 1023 : redval <= 0 ? 0 : redval;
  if (redval == 0)
    analogWrite(D5, 0);

  greenval = greenval >= 1023 ? 1023 : greenval <= 0 ? 0 : greenval;
  if (greenval == 0)
    analogWrite(D1, 0);

  blueval = blueval >= 1023 ? 1023 : blueval <= 0 ? 0 : blueval;
  if (blueval == 0)
    analogWrite(D2, 0);

  return;
}

void loop() {
  //delay(50) //just a test if there are not so many updates
  WiFiClient client = server.available();
  if (!client) return;

  while (!client.available()) delay(1);

  String request = client.readStringUntil('\r');
  client.flush();

  //Serial.print(request);
  setColor(request);
  client.stop();

  client.print("HTTP/1.1 200 OK\r\n");
  client.flush();
  return;
}

Is there someone who know what I have done wrong?

Are you certain that is the actual code you are using? It doesn't compile because  you call server.begin(), but haven't declared server.

First you stop the client, then you continue writing to it. I have no idea how exactly the client is implemented, but you can imagine how this could lead to memory problems.

I doubt this is the problem, but this code looks wrong.
  int redval = red_val.toInt();
  analogWrite(D5, redval);
  redval = redval >= 1023 ? 1023 : redval <= 0 ? 0 : redval;
  if (redval == 0)
    analogWrite(D5, 0);

I think it should be more like this:
  int redval = red_val.toInt();
  if (redval > 1023)  // If its =1023 you do need to set it to 1023.
    redval= 1023;
  else if (redval < 0)
    redval = 0;
  analogWrite(D5, redval);

The inline if statement is too ugly and doesn't really add anything.
To be honest I would look at pulling this code into functions to make it easier to read and I suspect you will find the problem.
When these microprocessors stop after a while its usually memory, heat or electrical.  If you have checked the electrics and its stopping quite quickly its probably a memory leak.  So refactoring your code might help people spot the problem easier.
You might want to replace you call to setColour()  with a call to Serial.println() and see if that cure the problem.  If it doesn't then your problem is with the way you are calling client.

Ok I just edited the code like you said and also replaced the call function with the Serial.println() but the issue occured after a few seconds again


text:
Why declare analog pins as ints?
I often see code like this:
const int piezo = A0;
const int sensorPin = A1;

From my understanding, an int variable can hold things like -123, 0, 1, 456, etc.
How can A0 or A1 be an int?

The board definition (pins_arduino.h) has this:
static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
static const uint8_t A3 = 17;
static const uint8_t A4 = 18;
static const uint8_t A5 = 19;
static const uint8_t A6 = 20;
static const uint8_t A7 = 21;

Since A0 is a constant variable equal to 14, if you assign that to a variable, it just assigns 14.
In other words:
A = 14.
B = A.
Therefore B = 14.

They are defined in the Arduino libraries, and the Arduino libraries will translate them into the appropriate pins and registers before they are used. But in the meantime they're numbers.


text:
How to convert Arduino example sketch to a complete c++ project?
I'm experimenting something new with my Arduino Leonardo. I removed its original bootloader and flashed it with LUFA mass storage example with added functionalities(now its a firmware). I'm trying to now add RFID reader(read/write) example to my firmware. For that I have to convert the sketch to a c++ code. So I copied relevant header file and cpp file from the library folder(libraries->rfid-master->bla.h,bla.cpp). But I'm confused what to do with the .ino file under examples(libraries->rfid-master->examples->ReadAndWrite->blabla.ino). I guess this code should be copied to the main class of my firmware. Any ideas?

Basically *.ino is *.cpp without headers. So you can

rename it to *.cpp,
If you have any functions which are used before they have been defined, provide declarations for each function before its first use
#include <Arduino.h> on the top
#include <Wire.h> if you are using Wire and so on

and you have "normal" CPP file.
If you are making library this way, than you create also *.h file, where you declare all exported functions and objects and #include that file in your *.cpp as first line (than you do not need/have to forward declare any of that exported functions)
You may like to take a look at https://github.com/arduino/Arduino.git https://github.com/sudar/Arduino-Makefile and https://github.com/ladislas/bare-arduino-project
the Bare Arduino have 2 projects each using 2 libraries, so you can get inspiration there

The Makefile you are linking to seems like a slightly outdated fork of Sudar Muthu's Arduino-Makefile. Why not link to the original instead?

Just because I first found the Bare-Arduino, which used this version (and then patched it with the sudar version as I now see). Anyway it is able to compile my files against Arduino 1.8.0, so it could work as starting point. Or the original Sudars makefile, but the Bare project have nice examples, how to organise your project, which I think would help @Isuru with the start. And later he can migrate to other version/system. (I build simple one over that too, to help my projects, nothing much but helped me to sort my mind faster)

Whereas it makes sense to pull WeAreLeka/Arduino-Makefile as a submodule of ladislas/Bare-Arduino-Project, it doesn't make sense to provide a direct link to that fork, as it has no added value over the original. If you do want to give a direct link to Arduino-Makefile, you should edit your answer in order to link to the real project.

You forgot about having to predeclare functions.

@Pharap "for each function, which is used before declaration write its header before first use" is (IMHO) exactly that... and functions used after declaration are already declared. Or are there some other cases, where usual ino -> cpp needs it?

@gilhad .ino files allow you to use your own functions without declaring them first, .cpp files do not, they require you to declare a function before it's used or the compiler won't know it exists. Here is an example. I wouldn't take "write its header before first use" to mean "you must forward-declare your functions before using them", because a header is a specific kind of file and it doesn't require a header file, it just requires a function declaration.

header file is something different from header of funfction. In your example is writen void sendMessage(void); before sendMessage is used. (and #includes as I mentioned too). No other difference.


text:
Reading ground signal from circuit
I am trying to detect whether a signal is high or low from an ESU LokSound 5 decoder for HO locomotives. My idea was to use one of the auxiliary pins used to drive an LED (AUX 3 in my case).

The problem is that these decoders are common positive rather than common negative, which means I can't directly connect AUX 3 to a digital pin on the Arduino and expect it to work flawlessly since it outputs a negative voltage rather than positive.
I'm trying my best to not use an op amp, as the locomotive I'm making this accessory for is already cramped. It sort of works if I directly connect it, but it is not smooth at all. I've tried using the built-in pull-up resistor, I've tried using an external pull-down resistor, I've tried using a resistor in line and I can't seem to figure out how to solve this without resorting to using an op-amp.

i think that you are misunderstanding how the circuit is wired ... one side of a lamp is connected to the +V ... the other side of the lamp is connected to an open collector AUX output ... the output gets pulled low to light a lamp .... connect arduino ground to decoder ground ... connect the AUX3 to arduino data pin ... do not connect lamp to AUX3 ... enable arduino internal pullup resistor .... AUX output acts like a switch that connects AUX to ground


text:
Arduino Uno still boots and runs but no serial communication over USB
After having the Arduino Uno running for a short period of time, it seems to no longer communicate over the USB port when connected to the computer. It still seems to turn on and run the program uploaded. However, it no longer receives or outputs any data and any attempts to re-upload code are met with timeout errors in the Arduino IDE. The TX/RX lights do not blink at all, but the "L" light always flashes right after the Arduino is plugged in.
I have the Arduino/Genuino Uno board selected in the Arduino IDE.
This is a legitimate board that I bought directly from Arduino.
Loopback test fails.
Nothing is connected to any of the pins on the Arduino whatsoever.
I have an Arduino Nano that communicates fine with my Windows 10 PC so that rules out the drivers and the PC itself.
My computer still recognizes the USB device as an Arduino Uno and assigns it to COM5.
Leaving it plugged in for a solid 15 minutes shows no chips on the board getting hot to the touch.
I have tried resetting the board before, during, and after attempting to upload code, no dice.
Are there other steps that I can take to try to fix the board, or am I going to have to accept that I fried the ATMEL16 chip on my Uno?

if the port shows up as Arduino Uno, then the 16u2 is ok. you could try USB to TTL Serial adapter on RX/TX.

@Juraj Is that what this is? https://rootsaid.com/arduino-usb-to-serial-converter-programming/

yes, but never call it RS232. R232 is a different communication protocol on electrical signal level. the Arduino RX/TX pins are TTL UART

I think you have fried it really, it happened to me before, I accidentally forwarded 12v to 5v pin on an Arduino nano, I quickly shut off everything I unplugged the Arduino board from anything connected to it, and connected it to computer, the computer recognize it as a USB serial device but it never uploads and I also found that the temperature hits more than 70 C° so it becomes very hot to touch. So yeah I think your board is now burned, ACCEPT if the problem is in the ATMega328p chip itself.

As @Juraj mentioned, if it's enumerating as a serial port, the atmega16u2 is fine.
You may be able to replace the atmega328p/au. It will take some doing; you'll need to remove the chip, insert a new one, and use another Arduino as an ArduinoISP to program the bootloader into your new blank atmega328p.
Any chance you might have uploaded a sketch that is spamming the serial port on startup? If so, try this procedure (h/t to the Arduino forums, it has saved my bacon a number of times):

Disconnect the usb connection
Begin holding the Reset button
Connect the Arduino
Initiate upload (while still holding Reset continuously)
As soon as you see the RX light flash, release the Reset button.
The first attempt to upload will fail, but with luck, the second try will occur before the 2-second bootloader delay ends (and your sketch begins to execute).

If this works, I'd suggest including a delay(3000); or similar in your setup().

try changing the baud rate according to the code...
the standard baud rate is 9600

how would it help for sketch upload?

I meant that if the baud rate on the serial monitor is different then you wont be able to see the output

it happened to me. Try reinstalling the arduino board, that is, enter the board manager, remove the board and the link from your board, restart the computer and then enter the link and update the board, it is a driver problem. Greetings.


text:
Need help with converting Celsius to Fahrenheit in the code
I'm new to Arduino and trying to figure out how to convert Celsius to Fahrenheit with the parameters listed below. Do I need to create a separate file for the calculations? If so, can someone help me on how I can go about doing that?
#include <DHT.h>
#include <DHT_U.h>

int SENSOR = 2;
int TEMPERATURE;
int HUMIDITY;

DHT dht(SENSOR, DHT11);

void setup() {
  Serial.begin(9600);
  dht.begin();
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  TEMPERATURE = dht.readTemperature();
  HUMIDITY = dht.readHumidity();
  Serial.print("Temp: ");
  Serial.print(TEMPERATURE);
  Serial.println(" celsius ");
  Serial.println(" ");
  Serial.print("Humidity: ");
  Serial.println(HUMIDITY);
  delay(2000);

  //Built In LED
  digitalWrite(LED_BUILTIN, HIGH);  // turn the LED on (HIGH is the voltage level)
  delay(250); // wait for a second
  digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
  delay(250);
}

If dht.readTemperature() and dht.readHumidity() return floating point numbers then you may want to change TEMPERATURE and HUMIDITY to "float" instead of "int".

If you are using the Adafruit DHT sensor library, then you can get a
Fahrenheit reading by passing true as an argument to
readTemperature(). C.f. the comment in the source code. For
example:
Serial.print("Temp: ");
Serial.print(dht.readTemperature(true));  // true -> Fahrenheit
Serial.println(" deg. F");

Note that this library offers also the conversion functions
convertCtoF() and convertFtoC().

You could add a function to your sketch.
// Celsius to Fahrenheit conversion
double Fahrenheit(double celsius){
  return 1.8 * celsius + 32;
}

Then add this code to your loop().
Serial.print("Temp: ");
Serial.print(Fahrenheit(TEMPERATURE));
Serial.println(" fahrenheit ");


text:
Why are commands executing on their own?
This is the program I have used. It's working fine. But I don't known why sometimes it operates on its own. It is used to control a welding machine (Arduino is isolated from earthing). When there is a little vibration the code executes a command. This is the code:
int a = 9;  //right actuator forward relay 1
int b = 12; //right actuator reverse relay 2 (orange 10)
int c = 10; //left actuator forward relay 4
int d = 11; //left actuator reverse relay 3
int x = 0;
int y = 0;
const int stepPin = 8; // HIGH =DOWN; LOW == UP
const int dirPin = 7;

void setup() {
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  pinMode(4, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  Serial.begin(9600);
  digitalWrite(b, HIGH);
  digitalWrite(d, HIGH);
  delay(2000);
  digitalWrite(b, LOW);
  digitalWrite(d, LOW);
  delay(1000);
  Serial.println("press the foot swtich"); // Serial Monitor for Debugging
}

void loop() {
  int Val = digitalRead(5); //   Actuator 1 Clamping
  int ValR = digitalRead(6);//   Actuator 2 Clamping
  int ValS = digitalRead(4);//Stepper Motor anticlockwise
  int ValM = digitalRead(2);//Stepper Motor Clockwise
  if (Val == LOW && x == 0  ) {
    Serial.print("Val000=");
    Serial.println(Val);
    digitalWrite(c, HIGH);
    delay(1750);
    digitalWrite(c, LOW);
    x = 1;
    Val = digitalRead(5);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (Val == LOW && x == 1  ) {
    digitalWrite(d, HIGH);
    digitalWrite(b, HIGH);
    delay(2000);
    digitalWrite(d, LOW);
    digitalWrite(b, LOW);
    x = 0;
    Val = digitalRead(5);
    Serial.println("fwd");
    y = 0;
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValR == LOW && y == 0 ) {
    digitalWrite(a, HIGH);
    delay(1350);
    digitalWrite(a, LOW);
    y = 1;
    ValR = digitalRead(6);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValR == LOW && y == 1 ) {
    digitalWrite(b, HIGH);
    delay(1200);
    digitalWrite(b, LOW);
    y = 0;
    ValR = digitalRead(6);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValS == HIGH) {
    Serial.println(Val);
    Serial.println("up");
    digitalWrite(dirPin, HIGH);
    // Enables the motor to move in a particular direction
    // Makes 100 pulses for making half cycle rotation
    for (int x = 0; x < 100; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(1000);
    }
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
  }
  if (ValM == LOW) {
    Serial.println("down");
    Serial.println(ValR);
    digitalWrite(dirPin, LOW);
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
    for (int x = 0; x < 100; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(1000);
    }
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
  }
}

By “it operates on its own” do you mean it acts as if the buttons are pressed, including printing the debugging output? 2. The internal pullups enabled by INPUT_PULLUP are quite weak (around 30 kΩ). In a noisy environment, you way want to use stronger external pullups (i.e. lower resistance).

yes its act like the button is pressed, on serial debugging also and the machine runs too. Can debouncing solve if yes how can I add it?

Debouncing may help if it does also deglitching. But it is probably safer to have a clean signal to start with. Thus I would try the weak pullup first. How much distance is there between the buttons and the Arduino board?

What exactly is happening? What messages are you seeing on the serial monitor? Could it be loose wires or wires touching? More information will help us help you.

anyone one of the if() loop starts randomly. There is a relay which used to switch on the welding gun.. it is not controlled by arduino it is independent ... but whenever the relay activates, the arduino execute a if statement.... no wires are loose

Are 10k resistor enough for stronger signals?

I would go straight to 1 kΩ. Also, if your buttons are more than, say, 10 cm from the Arduino board, I would wire them with a twisted pair (signal and ground on the same pair) in order to prevent inductive pick-up.

@EdgarBonet Please don't answer in comments. This totally goes against the Stack Exchange model. Make an answer.

Comments under questions are for seeking clarification of the question. They are not for making mini-answers.

Can you give details of your circuit hardware, in terms of whether wiring is soldered or breadboard/push fit together.  If you had a loose connection that would be susceptible to vibrations.

SOLDERED.  there is strong electro magnetic feilg by the welding  gun relay

Trying to write a proper answer...
According to your description, it looks like you are victim of inductive
noise pickup. The circuit [MCU → Arduino ground pin → foot pedal →
Arduino digital input pin → MCU] is a loop that can pick up magnetic
flux. If this flux varies, either because the magnetic field varies
(ambient electromagnetic noise) or because the geometry of the circuit
changes (you move the wires), this will induce an electromagnetic force
that can make your Arduino read LOW even when the button is not
pressed.
There are two things you can try to overcome this effect:

Replace the weak internal pullup of the Arduino by a much stronger
external pullup. Something around 1 kΩ should make it quite hard for
the noise to pull the signal low.
Connect the pedal to the Arduino board using a twisted pair of wires,
like the ones found in telephone or network cables. This kind of
cable does a good job at minimizing inductive pickup.

I will try with 1k resistor. The Button is actually a foot switch at a distance of 10 feet from arduino

The problem is same with 1K resistor too.. the wires are shielded properly

It only happens when welding gun relay is activated

The welding gun may be a source of huge electromagnetic noise.

what can i do now?


text:
Buffer overflow error in ESP8266_SoftwareSerial library
I am running into buffer issues when running the Firmware.ino example here.
The output from my Arduino serial log on baudrate 115200 (I put the ESP on baudrate 9600):
Begin
01:17:15.538 -> Baudrate set success
01:17:15.585 -> Station + softAP - OK
01:17:18.631 -> Joining AP successful, IP: 192.168 r⸮+@⸮
01:17:18.991 -> Single Mode OK
01:17:18.991 -> Sending Request to www.google.com
01:17:19.084 -> create tcp - OK
01:17:19.710 -> not sentbuffer is full!
01:17:20.022 -> HZiw93GUFmVJYFz-yRmahGURP_UBbRb4EF0Ahwzx8MJ1GOyC5Z0dns8UD41G8kUqnL0oxNPxa6xF9nAqNF3X3B_hKW11zoyaBPn8trvUNt-69qbFCNOZwNjgoaloKbOQs7NN-B3tpmwFKpHfKsfKyZfiMdhulN3SgZMhewYBg9c; expires=Wed, 05-Feb-2020 05:17:18 GMT; path=/; domain=.google.com; HttpOnly
01:17:20.162 -> Accept-Ranges: none
01:17:20.162 -> Vary: Accept-Encoding
01:17:20.209 -> ConnecS,
01:17:24.179 -> Sending Request to www.google.com
01:17:24.774 -> create tcp - ERROR
01:17:28.759 -> Sending Request to www.google.com
01:17:29.432 -> create tcp - ERROR
01:17:33.402 -> Sending Request to www.google.com
01:17:34.021 -> create tcp - ERROR
01:17:38.028 -> Sending Request to www.google.com
01:17:38.669 -> create tcp - ERROR
01:17:42.681 -> Sending Request to www.google.com
01:17:43.294 -> create tcp - ERROR
01:17:47.298 -> Sending Request to www.google.com
01:17:47.954 -> create tcp - ERROR
01:17:51.925 -> Sending Request to www.google.com
01:17:52.595 -> create tcp - ERROR
01:17:56.563 -> Sending Request to www.google.com
01:17:57.204 -> create tcp - ERROR
01:18:01.222 -> Sending Request to www.google.com
01:18:01.871 -> create tcp - ERROR
01:18:05.839 -> Sending Request to www.google.com
01:18:06.460 -> create tcp - ERROR
01:18:10.456 -> Sending Request to www.google.com
01:18:10.596 -> create tcp - OK
01:18:11.049 -> buffer is full!
01:18:11.049 ->
01:18:11.049 ->
01:18:11.049 -> +IPD,1430:HTTP/1.1 200 OK
01:18:11.096 -> Date: Tue, 06 Aug 2019 05:18:09 GMT
01:18:11.096 -> Expires: -1
01:18:11.096 -> Cache-Control: private, max-age=0
01:18:11.143 -> Content-Type: text/ht
l; charset=ISO-8859-1
01:18:11.143 -> P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
01:18:11.190 -> Server: gws
01:18:11.190 -> X-XSS-Protection: 0
01:18:11.190 -> X-Frame-Options: SAMEORIGIN
01:18:11.224 -> Set-CooS,
01:18:15.192 -> Sending Request to www.google.com
01:18:15.822 -> create tcp - ERROR
01:18:19.849 -> Sending Request to www.google.com
01:18:20.473 -> create tcp - ERROR

As you can see, at first it starts ok, gives a buffer error, runs in error for a while, then runs OK again. This happens a couple times, then it runs only in error. I imagine this is some issue with the buffer of the ESP or the Arduino, but I'm not sure how to diagnose it further.
Things I have tried to fix the error:
 - As mentioned in the Firmware.ino example comments, I uncommented #define ESP8266_USE_SOFTWARE_SERIAL
 - Also as mentioned in the comment, I changed line 42 from 64 to 256. It didn't work either time.
 - There is a MAX_BUFFER_SIZE in the included ESP8266.h library that I also changed, from 300 to 256, because I thought that might help, but the error persisted.

You are sending/receiving too much data and you're out of memory is what the error is saying.

There's some heavy String usage in that library, would not recommend it for anything you want to be stable, especially with an Uno.
The library seems to create a connection by first clearing the SoftwareSerial buffer and then issuing the right AT command. It waits for 500ms for a response before giving up. I suspect the wait interval is sometimes not long enough for the module to receive, parse and handle the command before responding. So you should try increasing it to 2000 ms at line 773.
The buffer is full message just refers to the library's own buffer for holding received data, which is 300 bytes by default. The buffer's getting filled so quickly (and the SoftwareSerial internal buffer likely overrun too) because you're loading a webpage like Google's which has more than 300 bytes in the response header alone. It's even possible that by the time the next request commences with another AT command, the ESP8266 is still dumping the response from the previous request, and so the command's response is still way down the queue and so doesn't get read before the timeout.
Instead, try loading a simple webpage like httpbin.org/ip. That is, at lines 952, 954:
char* request =  "GET /ip HTTP/1.1\r\nHost: www.httpbin.org\r\nConnection: close\r\n\r\n";

if (createTCP("www.httpbin.org", 80))

Thank you! Can you recommend any better libraries for making simple http requests (maybe simpler than google.com) on the Arduino Uno using ESP8266?

@garson This looks popular with a decent interface: https://github.com/bportaluri/WiFiEsp. If this solved your problem, don't forget to upvote and accept the answer.

It's a step in the right direction, though I still have timeout errors with that library :(

Oh my god, it works! Thank you!


text:
TIMEOUT error when connecting ESP8266 to Arduino Uno
I am trying to set up my Arduino Uno to receive information from the internet, but I am having a very hard time finding proper guides online. I am using an Arduino Uno and ESP8266-01. I am trying to use the "WebClientRepeating" example from this library:
https://github.com/bportaluri/WiFiEsp
Here is the code I am running (updated the SSID and password):
/*
 WiFiEsp example: WebClientRepeating

 This sketch connects to a web server and makes an HTTP request
 using an Arduino ESP8266 module.
 It repeats the HTTP call each 10 seconds.

 For more details see: http://yaab-arduino.blogspot.com/p/wifiesp.html
*/

#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6,7); // RX, TX
#endif

char ssid[] = "MY-SSID";            // your network SSID (name)
char pass[] = "MY-PASSWORD";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "arduino.cc";

unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10000L; // delay between updates, in milliseconds

// Initialize the Ethernet client object
WiFiEspClient client;

void setup()
{
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");

  printWifiStatus();
}

void loop()
{
  // if there's incoming data from the net connection send it out the serial port
  // this is for debugging purposes only
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if 10 seconds have passed since your last connection,
  // then connect again and send data
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server
void httpRequest()
{
  Serial.println();

  // close any connection before send a new request
  // this will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");

    // send the HTTP PUT request
    client.println(F("GET /asciilogo.txt HTTP/1.1"));
    client.println(F("Host: arduino.cc"));
    client.println("Connection: close");
    client.println();

    // note the time that the connection was made
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection
    Serial.println("Connection failed");
  }
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

My wiring is as follows:

ESP8266 RX - Uno Pin 7
ESP8266 TX - Uno Pin 6
ESP8266 VCC - 3.3V power source (not from Uno)
ESP8266 GND - Uno GND
ESP8266 CH_PD - 3.3V power source (not from Uno)

I also connected the GND of the 3.3V power source to the other GNDs.
When I go to run the WebClientRepeating example, my Serial output says:
11:05:04.764 -> [WiFiEsp] Initializing ESP module
11:05:05.760 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:07.785 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:09.758 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:11.780 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:13.803 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:14.794 -> [WiFiEsp] Cannot initialize ESP module
11:05:20.794 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:20.794 -> [WiFiEsp] No tag found
11:05:20.830 -> WiFi shield not present

The tutorial specifies that it uses a "ESP WiFi shield" but I am using a ESP8266 card only - could that be part of the problem? If that is a problem, are there any simple guides out there for how to connect the Arduino Uno to the internet to read information? I am frustrated with the lack of good documentation, and would really appreciate some help.

That's not a tutorial. That's a library. What code are you actually running? And how exactly have you wired your ESP-01?

Thank you, I updated the posting to include this information

So... you wired the ESP-01 to pins 0 and 1, not to pins 6 and 7 as specified in your sketch?

Oh sorry no that was wrong, I did wire to 6 and 7

There are a number of different AT firmware versions for the ESP-01. And they all use different baud rates. It may well be that you have one with 115200 baud, not 9600 baud. 115200 baud doesn't work well with SoftwareSerial, so you will have to change the baud rate on the ESP-01 to 9600 - however, how you do that depends on the firmware version, and some versions are known to commit suicide when you try changing the baud rate. You should confirm the baud rate by connecting the ESP-01 direct to the computer with a USB to UART adaptor.

OK, yes I think my ESP is 115200. I was able to get through this tutorial completely fine and it uses 115200: http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/. This is so frustrating lol.

It means that your ESP8266 is not detected
Because of you connect RX and TX (6 and 7) to secondary pin.
Use your standart RX TX pin to solve the problem


text:
Why does attaching Nokia 5110 LCD make my otherwise fine MKR1000 disconnect USB after 15 secs?
This problem just started after 3 days of working on a project.
I am using Arduino IDE in Windows 10.
When I go to upload "Blink," everything works fine. I connect the USB (sometimes I have to change the port from COM6 to COM5) and upload and it blinks. All good. Well, one weird thing: sometimes I'll upload Blink when it's COM5 and then after the upload I'll notice that the Arduino has switched to COM6. So I have to go in and manually update the Port.
But after I switch to whichever Port has MKR1000 listed on it and go to upload my other more complicated program that uses WiFi and the Nokia 5110 LCD, it seems to throw the Arduino for a loop. All of a sudden it either won't upload properly or say port cannot be found and starts disconnecting from the port about 15 seconds after I connect it, and I'm not able to upload anything.
Anyone have any clues what might be going on? Thank you.
Adding some information about the connections from NOKIA 5110 (also using a breadboard in between):
RST: to pin 6  on MKR1000
CE: to pin 4 on MKR1000
DC: to pin 7 on MKR1000
Din: to pin 3 on MKR1000
Clk: to pin 5 on MKR1000
VCC:to VCC on MKR1000
BL: to VCC on MKR1000
GND: to GND on MKR1000

Are you powering MKR1000 via USB? That only gives you about 1/2 amp of total current. I wonder if you're exceeding the available current of your power source. Add up the peak current requirements of your Arduino, (with WiFi active) the LCD, etc.

The MKR board connects to computer over native USB support of the MCU. The handling of the USB is done by Arduino core functions linked at build to your sketch.
A consequence of using the native USB port is, if your sketch has a problem, it influences the USB communication. In this case you can activate the bootloader to handle the USB port and the upload. It is done by double clicking the reset button on board.
This applies to other SAMD boards (Zero, M0) and to AVR boards with native USB port (Leonardo, Micro) too.

I've tried doing that and still run into the same problems. The error says: "Port name - COM6; Method name - openPort(); Exception type - Port not found."

the reset changes USB port. set in IDE the first port that the board usually uses. if the upload doesn't start do the double reset again while the IDE attempts to upload. the bootloader waits after reset for upload almost 10 seconds


text:
How to jump outside the loop? in below Programme how to use goto or any other Jump related Programme
const int analogPin1 = A1;
const int analogPin2 = A2;
const int analogPin3 = A3;
const int ledPin = 13;
const int ledPin2 = 7;
const int thresold = 400;
unsigned int x1, x2, x3, fault = 0;
void setup()
{
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
}
void Config()
{
    delay(1000);
    Serial.print("ATE0r");
    Response();
    Serial.print("ATr");
    Response();
    Serial.print("AT+CMGF=1r");
    Response();
    Serial.print("AT+CNMI=1,2,0,0,0r");
    Response();
}
void Response()
{
    int count = 0;
    Serial.println();
    while (1) {
        if (Serial.available()) {
            char data = Serial.read();
            if (data == 'K') {
                Serial.println("OK");
                break;
            }
            if (data == 'R') {
                Serial.println("GSM Not Working");
                break;
            }
        }
        count++;
        delay(10);
        if (count == 1000) {
            Serial.println("GSM not Found");
            break;
        }
    }
}
void loop()
{
    int analogValue1 = analogRead(analogPin1);
    int analogValue2 = analogRead(analogPin2);
    int analogValue3 = analogRead(analogPin3);

    if (analogValue1 < thresold) {
        x1 = 1;
        fault = x1;
    }
    if (analogValue2 < thresold) {
        x2 = x1 + 3;
        fault = x2;
    }
    if (analogValue3 < thresold) {
        x3 = x1 + x2 + 5;
        fault = x3;
    }

    switch (fault) {
    case 1:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("PHASE 1 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        goto nsr;
        break;

    case 3:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("2 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        goto nsr;
        break;

    case 4:
        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("1 AND 2 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        goto nsr;
        break;

    case 5:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        Serial.print("AT+CNMI=2,2,0,0,0");
        goto nsr;
        break;

    case 6:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("1 AND 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        goto nsr;
        break;

    case 8:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("2 AND 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        goto nsr;
        break;

    case 10:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("ALL 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        goto nsr;
        break;

    default:
        x1, x2, x3, fault = 0;
        digitalWrite(ledPin, LOW);
        break;
    }

    x1, x2, x3, fault = 0;
    digitalWrite(ledPin, LOW);
    do {
        int analogValue1 = analogRead(analogPin1);
        int analogValue2 = analogRead(analogPin2);
        int analogValue3 = analogRead(analogPin3);
    } while (analogValue1 < thresold || analogValue2 < thresold || analogValue3 < thresold);
}

do {
    int analogValue1 = analogRead(analogPin1);
    int analogValue2 = analogRead(analogPin2);
    int analogValue3 = analogRead(analogPin3);
} while ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));
}

nsr : if ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th))
{

    digitalWrite(ledPin, HIGH);
    Serial.begin(9600);
    Serial.print("\r");
    delay(1000);
    Serial.print("AT+CMGF=1\r");
    delay(1000);
    Serial.print("AT+CMGS=\"+919\"\r");
    delay(1000);
    Serial.print("ALL 3 Phase Restored");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);
    Serial.print("\r");
    delay(1000);
    Serial.print("AT+CMGF=1\r");
    delay(1000);
    Serial.print("AT+CMGS=\"+919\"\r");
    delay(1000);
    Serial.print("ALL 3 Phase Restored");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);

    do {
        int analogValue1 = analogRead(analogPin1);
        int analogValue2 = analogRead(analogPin2);
        int analogValue3 = analogRead(analogPin3);
    } while ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));
}

Please format your code properly. I can't follow what goes with what there.

Yes, nasty piece of spaghetti code (really nicely said).

And after using C++ formatter it's pretty obvious why it can't be working

Just for the curriosity x1, x2, x3, fault = 0; is supposed to set those variables to zero? I have bad news for you.

You want to create separate function nsr and use it instead of goto.
void nsr(void){
  if ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th))
  {

    digitalWrite(ledPin, HIGH);
    Serial.begin(9600);
    Serial.print("\r");
    delay(1000);
    Serial.print("AT+CMGF=1\r");
    delay(1000);
    Serial.print("AT+CMGS=\"+919\"\r");
    delay(1000);
    Serial.print("ALL 3 Phase Restored");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);
    Serial.print("\r");
    delay(1000);
    Serial.print("AT+CMGF=1\r");
    delay(1000);
    Serial.print("AT+CMGS=\"+919\"\r");
    delay(1000);
    Serial.print("ALL 3 Phase Restored");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);

    do {
        int analogValue1 = analogRead(analogPin1);
        int analogValue2 = analogRead(analogPin2);
        int analogValue3 = analogRead(analogPin3);
    } while ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));
  }
}

Instead of using
goto nsr

Use a boolean to skip parts you do not want to execute. It is (almost) never a good idea to use goto.
Due to the misalignment of { and } I do not know what you exactly want to execute.


text:
Arduino Due: multiple TCS sensors
I am trying to run 2 TCS3200’s from one Arduino Due. Next, I must increase to 4 sensors. I need to read the data from the 2 digital pins but how do I read both within the same loop rather than in series to save time. The code reading one sensor tasoOutPin1 (pin 10) works but why can’t I place the second read command int detectColor(int taosOutPin2) before the { symbol?
int detectColor(int taosOutPin1) {

float white1 = colorRead(taosOutPin1,0,1);
float red1 = colorRead(taosOutPin1,1,1);
float blue1 = colorRead(taosOutPin1,2,1);
float green1 = colorRead(taosOutPin1,3,1);
}

Thanks,
Scott

What happens when you place the second / third / fourth read in?  Why doesn't it work?

Downvoted because you didn't provide enough information for us to help you and you didn't respond to the request for more information.

Seems you have to run these serially, but not sure why it's an issue, a due is quick.
seems more programming related... 'detectColor' is a function, and this is run inside the loop i assume.
int taosOutPin1 = 10; //color detector 1
int taosOutPin2 = 2; //Pins are examples, change to actual pin...
int taosOutPin3 = 3;
int taosOutPin4 = 4; //color detector 4

typedef struct {
   float white;
   float red;
   float blue;
   float green;

} color;

void setup() {
  // put your setup code here, to run once:

}

void loop() {

color detectedColorForSensor1 = detectColor(taosOutPin1);
color detectedColorForSensor2 = detectColor(taosOutPin2);
color detectedColorForSensor3 = detectColor(taosOutPin3);
color detectedColorForSensor4 = detectColor(taosOutPin4);

Serial.print(detectedColorForSensor1.red);
Serial.print(detectedColorForSensor1.green);
Serial.print(detectedColorForSensor1.blue);
Serial.print(detectedColorForSensor1.white);

//etc for sensor 2,3,4............

}

color detectColor(int taosOutPin1) {

color detectedColor;

detectedColor.white = colorRead(taosOutPin1,0,1);
detectedColor.red = colorRead(taosOutPin1,1,1);
detectedColor.blue = colorRead(taosOutPin1,2,1);
detectedColor.green = colorRead(taosOutPin1,3,1);

return detectedColor;

}


text:
Reading ADS1232 with Arduino
I'm a newbie and I'm trying to read an ADS1232 with an Arduino for a Weight Scale Project.
I read data through the SPI interface, but i don't receive the result.
#include <SPI.h>

#define MISOPIN  50  //DATA
#define SCLKPIN  52  //SCLK
#define PDWN     53  // SS
#define SPEED       5
#define GAIN0       7
#define GAIN1       6
#define CLKIN       10
#define A0          9
#define TEMP        8

uint32_t byte1;
uint32_t byte2;
uint32_t byte3;
uint32_t finaladc = 0;

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

  pinMode(PDWN, OUTPUT);
  pinMode(MISOPIN, INPUT);
  pinMode(SCLKPIN, OUTPUT);
  pinMode(SPEED, OUTPUT);
  pinMode(GAIN0, OUTPUT);
  pinMode(GAIN1, OUTPUT);
  pinMode(A0, OUTPUT);
  pinMode(TEMP, OUTPUT);

  digitalWrite(GAIN0, HIGH);
  digitalWrite(GAIN1, HIGH);
  digitalWrite(SCLKPIN, LOW);
  digitalWrite(A0, LOW);
  digitalWrite(TEMP, LOW);
  digitalWrite(SPEED, HIGH);//0-->  10SPS ,1-->80SPS
  digitalWrite(PDWN, HIGH);  //0-->  POWERDOWN(SLEEPING -NO CONVERSION) ,1-->WORKING MODE

  reset_adc();

  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE1);

  digitalWrite(SCLKPIN,LOW);

}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(MISOPIN)== LOW) read_adc();

  delay(1000);

}

void reset_adc()  {
  digitalWrite(SCLKPIN,HIGH);
  delayMicroseconds(1400);

}

void read_adc()  {
  drdy_wait();
  uint8_t i;
  finaladc = SPI.transfer(0xff);
  finaladc |= (uint32_t)SPI.transfer(0xff) << 8;
  finaladc |= (uint32_t)SPI.transfer(0xff) << 16;
  Serial.print ("ADC_value:  ");
  Serial.println(finaladc,DEC);
  Serial.println();

}

void drdy_wait()
{
  delayMicroseconds(30);
}

Has anyone worked with this? Can you help me?  Thank you

Welcome to stackexchange. Would you show your code please? It is hard to recognise problems without it.

This is here Google

the ADS1232 doesn't have SPI

I've used SPI with the ADS1232.  You've a lot of problems, but the first one is your reset_adc() is all wrong, among other things reset is via pulling the PWDN pin low for more than 10 uS.  Start there.

I fished out some code I wrote a while back while evaluating the 1232.  SPI is a headache because of the need toggle the clock signal to prevent the last data bit from 'sticking', which will botch repeated reads when the last data bit is high.
If you are absolutely required to use SPI stop reading this answer.
Everything you need to know is on pages 18 and 19 of the ADS1232 datasheet.  Note this is strictly demo material, for example it doesn't take into account settle time when switching channels.
int32_t read_adc(const uint16_t wait_millis) {
   int32_t data = 0;
   // reset ADC
   digitalWrite(ADS1232_PDWN, LOW);
   delayMicroseconds(10);
   digitalWrite(ADS1232_PDWN, HIGH);
   delayMicroseconds(10);

   for (; data < wait_millis && digitalRead(ADS1232_DRDY_DOUT) != LOW;
        delay(1),
        data++);

    if (data == wait_millis) {
        // timeout
        return -1;
    }

   // read in 24 bits, see Page 19 of the datasheet

   data = 0;
   for (uint8_t i = 0; i < 24; i++) {
        digitalWrite(ADS1232_CLK, HIGH); // clock out next data bit
        data <<= 1;
        data |= digitalRead(ADS1232_DRDY_DOUT);
        digitalWrite(ADS1232_CLK, LOW);
    }
    // adjust for sign. See page 18 of datasheet
    if (data & 0x00800000)
        data |= 0xFF000000;
    // avoid having DRDY/DOUT remain in the state of the last bit
    // see page 19 of datasheet
    digitalWrite(ADS1232_CLK, HIGH);
    delayMicroseconds(10);
    digitalWrite(ADS1232_CLK, LOW);

    return data;
}

Thank you!! Ramblin Rose!! I will try and respond to you


text:
analogRead() takes >400 us on Arduino Zero but ~100 us on Uno, why?
I've been trying to figure out why the analogRead() function takes about four times as long on an Arduino Zero than on an Uno, when the Zero has a faster clock than the Uno.  Arduinos website says that it should take around 100 microseconds, and it does on the Uno, but it takes a little over 400 microseconds on the Zero. To time it, I've been setting a digital pin high immediately before the function call and low immediately after and measuring the period on a digital osscilloscope.  I'm just trying to test analogRead, so I'm not doing anything else in this code.  I've tried putting the ADC in freerun mode, and it trims ~15 us off of the ~415 us it currently takes.  I've also used the on-chip debugger to look at the disassembly, and the line that takes too long is always the line waiting for the conversion to complete.  I was also wondering if other ARM-based Arduinos (like the Zero) take over 100 us.  Thanks!
int   sensorPin = A1;
int      ledPin = 11;
int sensorValue = 0;

void setup() {
  analogReadResolution(12);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  digitalWrite(ledPin,HIGH);
  sensorValue = analogRead(sensorPin);
  digitalWrite(ledPin,LOW);
}

Do you have a code used for these measures?

Sorry, meant to post this the first time.
 `int sensorPin = A1;
 int ledPin = 11;
 int sensorValue = 0;

 void setup() {
     analogReadResolution(12);
     pinMode(ledPin, OUTPUT);
 }

 void loop() {
     digitalWrite(ledPin,HIGH);
     sensorValue = analogRead(sensorPin);
     digitalWrite(ledPin,LOW);
 }`

You might consult the data sheets for the two MCUs particularly the number of peripheral clocks to perform a conversion in a given mode and see if what you are measuring seems consistent.

@hiitsali, thank you for mentioning this. I suppose there is no solution for this yet ? I did some tests with the Arduino functions and the Arduino M0 is 3 to 7 times faster. The pinMode() takes 2µs, that is only 2 times faster. The analogRead() takes 422µs which is 4 times slower. I don't want to use interrupts for the ADC, so I have to keep in mind that it is very slow when using the average with many samples.

Arduino is universal platform, lot of wrappers to hide real hardware and it is slow. For example digital write is about 100times slower than direct access to hardware.
For example for AVR Mega328p based Arduino analogRead looks like (without macros):
int analogRead(uint8_t pin)
{
    uint8_t low, high;

    if (pin >= 14) pin -= 14; // allow for channel or pin numbers

    // set the analog reference (high two bits of ADMUX) and select the
    // channel (low 4 bits).  this also sets ADLAR (left-adjust result)
    // to 0 (the default).
    ADMUX = (analog_reference << 6) | (pin & 0x07);

    // start the conversion
    sbi(ADCSRA, ADSC);

    // ADSC is cleared when the conversion finishes
    while (bit_is_set(ADCSRA, ADSC));

    // we have to read ADCL first; doing so locks both ADCL
    // and ADCH until ADCH is read.  reading ADCL second would
    // cause the results of each conversion to be discarded,
    // as ADCL and ADCH would be locked when it completed.
    low  = ADCL;
    high = ADCH;

    // combine the two bytes
    return (high << 8) | low;
}

There are no extra function calls, no much extra actions and ADC is enabled in the startup code (as most of hw).
On the other side there is ARM based arduino with SAM3X8E:
uint32_t analogRead(uint32_t ulPin)
{
    uint32_t ulValue = 0;
    uint32_t ulChannel;

    if (ulPin < A0)
      ulPin += A0;

    ulChannel = g_APinDescription[ulPin].ulADCChannelNumber ;

    static uint32_t latestSelectedChannel = -1;
    switch ( g_APinDescription[ulPin].ulAnalogChannel )
    {
        // Handling ADC 12 bits channels
        case ADC0 :
        case ADC1 :
        case ADC2 :
        case ADC3 :
        case ADC4 :
        case ADC5 :
        case ADC6 :
        case ADC7 :
        case ADC8 :
        case ADC9 :
        case ADC10 :
        case ADC11 :

            // Enable the corresponding channel
            if (adc_get_channel_status(ADC, ulChannel) != 1) {
                adc_enable_channel( ADC, ulChannel );
                if ( latestSelectedChannel != (uint32_t)-1 && ulChannel != latestSelectedChannel)
                    adc_disable_channel( ADC, latestSelectedChannel );
                latestSelectedChannel = ulChannel;
                g_pinStatus[ulPin] = (g_pinStatus[ulPin] & 0xF0) | PIN_STATUS_ANALOG;
            }

            // Start the ADC
            adc_start( ADC );

            // Wait for end of conversion
            while ((adc_get_status(ADC) & ADC_ISR_DRDY) != ADC_ISR_DRDY)
                ;

            // Read the value
            ulValue = adc_get_latest_value(ADC);
            ulValue = mapResolution(ulValue, ADC_RESOLUTION, _readResolution);

            break;

        // Compiler could yell because we don't handle DAC pins
        default :
            ulValue=0;
            break;
    }

    return ulValue;
}

As you can see there is little bit more actions to do single measure using HAL (Hardware Abstraction Level) so you have another level of abstraction here.
If you want faster actions, you can access hw directly, or use HAL and skip unnecessary steps. It would be much faster then.

Thanks, I've actually tried this already.  It shaves off some time, but it's still slower than the time cited by the datasheet (100 microseconds) on the Zero.  On the Uno this helps get it under that, but I don't understand why the baseline time of the Zero is so much longer.  I've spent quite a while looking at the C files and the disassembly.  On the zero, in the disassembly, it's always the line that's waiting for the flag indicating that the conversion is done that takes a long time

@hiitsali abviously the waiting for the result would take more time as the setting up (if done efficiently). Is the problem that you'll have to wait, or that it simply takes too long? You can try setting the ADC to do less samples and/or lower accuracy, that may improve speed. Otherwise, you can implement an interrupt when ADC is complete, so you're not waiting for the ADC (it's not faster, but more efficient).

Code abstraction is not the issue for something already relatively slow like that.  Rather the issue would be the actual time required for a conversion with the configured ADC clock and mode.


text:
Atmega 328pu as stand alone
I am used atmega 328pu as stand alone.i used 7805 as regulator.
I regulated from 12 VOLT 2 amp smps.
When I connect my dc 12 VOLT pump in between 12 VOLT and ground dc motor working fine but Atmega stops working.
Please help me with this.
EDIT: Information added from the comments.
Q: Does the Arduino work with the motor disconnected?
A: Yes it's works fine

The first thing is that you have no decoupling capacitors.

Where I need to put decoupling capacitor .can you please send a diagram if possible.

Also 7805 might be unstable without input and output capacitors.

perhaps the pump drops the voltage below 5v? seems a long-shot, but if the PSU is massively over-loaded that can happen.

I used two 10uf/63 volt capacitor with 7805 in the input and out put.still I have the problem.

When connected pump at the same time I measured the voltage it is still 5 volt.

Perhaps your circuit sketch is different from reality, but: The GND signals should not be connected to a bus type line. especially Pin 8, 22 and 22pF crystal cap GND should be directly connected with short wires and have only one connection to the 12V GND and 7805 GND

Add 0.1uF caps from pin 7 to 8, and from pin 20 to 22. Keep them close to the chip.
If you will be doing any analogRead()s, then add one from 21 to 22 as well.


text:
How to get Json String from URL?
I want to get JSON string from a URL which goes like this

https://maps.googleapis.com/maps/api/directions/json?origin=7649+Paseo+Santa+Cruz&destination=SJSU&key=MY_API_KEY

and here is my code:

#include <Bridge.h>

//#include <b64.h>
#include <HttpClient.h>

//#include <ArduinoHttpClient.h>

#include <Arduino_JSON.h>
#include <SPI.h>
#include <WiFiNINA.h>

//#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "my_wifi_ssid";        // your network SSID (name)
char pass[] = "my_wifi_password";    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the Wifi radio's status

WiFiSSLClient wifi;
char serverAddress[] = "maps.googleapis.com";

void setup() {
  //Bridge.begin();
  Serial.begin(9600);
  //listNetworks();
  //Initialize serial and wait for port to open:

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < "1.0.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.print("You're connected to the network");
  printCurrentNet();
  printWifiData();
  Serial.println("\nStarting connection to server...");
  // if you get a connection, report back via serial:
  if (wifi.connect(serverAddress, 80)) {
    Serial.println("connected to server");
    // Make a HTTP request:
    wifi.println("GET /maps/api/directions/json?origin=7649+Paseo+Santa+Cruz&destination=SJSU&key=MY_API_KEY");
    wifi.println("Host: maps.googleapis.com");
    wifi.println();
  }
}

void loop() {
  while (wifi.available()) {
    char c = wifi.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client:
  if (!wifi.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    wifi.stop();

    // do nothing forevermore:
    while (true);
  }

  // check the network connection once every 10 seconds:
  delay(10000);
  }

It only printed in Serial Monitor:
Starting connection to server...

disconnecting from server.

Bridge.h is for Yun. remove it. and change the unsuitable variable name wifi to client

you connect for https to port 80? default https port is 443. use wifi.connect(serverAddress, 443)

Better use <WiFiClientSecure.h> example


text:
Float to String Convert in Udp.write() in esp8266
I want to convert float value to String for send Udp.Write()
 method
 and receive another side (esp) with Udp.read()
and
Copy in the one Variable for use ..
please help me
Thanks for every answer ^__^
code :
void loop () {
    int signal = analogRead (A0) ;
    float Adc = (signal * 3.3) / 4096 ;
    Udp.beginPacket ({192,168,4,1} , 1234) ;
    Udp.write ( " please help me fill this section ") ;
    Udp.endPacket () ;
}

i have one more problom . . .
and in the other side:
i want take theAdc value from esp1 and convert char to float for Dac
(digital analog converter) with MCP4725 ..
** i just need put in float value of Adc in a variable for convertation use ..**
code:
void loop ( ) {
int noBytes = Udp.parsePacket();

String received_command = "";

if ( noBytes ) {

  Udp.read(packetBuffer,noBytes);

  for (int i=1;i<=noBytes;i++){

  received_command += char(packetBuffer[i - 1]);
}

Serial.print("packaet receive: ");

Serial.println(received_command);

float Adc_value_received = float(received_command); //*helpppp please char-to-float convert*

}
thanks from everyone ^__^

Have you considered reading the documentation for String?  https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/

Or even googling it? Normally you find various examples when googling for "Arduino convert X to Y"

Try something like: String msg = String(Adc, 3); Udp.write(msg.c_str());

Special thanks to Mikael Patel .^___^

The Arduino String class can be used to convert to a character string.
void loop () {
    int signal = analogRead (A0) ;
    float Adc = (signal * 3.3) / 4096 ;
    String msg = String(Adc, 3);

    Udp.beginPacket ({192,168,4,1}, 1234) ;
    Udp.write(msg.c_str());
    Udp.endPacket () ;
}


text:
ESP8266 I2C datasheet pins not the same as several examples
According to espressif datasheet of the ESP8266 it uses
MTMS (I2C_SCL) and GPIO2(I2C_SDA) for I2C.
However in several examples I've seen the typically use is GPIO(4&5) or GPIO(0&4) to connect to the I2C.
I guess all method works? but what is the real difference?

Many modules don't have the right pins for I2C available. Thus it was decided that the sensible option would be to use a bit-banged implementation of I2C using software only.
Also GPIO2 has a special meaning for booting, and using it is risky at best, and should be avoided.
Doing it 100% in software has the advantage that any pin combination can be used for I2C.


text:
Nodemcu ESP12-E (ESP8266), Can I reprogramming when the UART pins are defined as GPIO?
I wonder if there may be any problems using the pins that the UART are using as GPIOs, if now I want to be able to reprogram the circuit?
(Of course I will detach the ESP12-E from the mainboard before so)

flash mode is achieved using a combination of GPIO 0, 2 and 15 ... so, since UART is on 1 and 3, it will be flashable if powered up with 0-LOW, 2-HIGH and 15-LOW - since your sketch won't be running in this mode

keep in mind that this pins are the only way to change the application in esp8266 in any case. (OTA is the other way, but it must be supported by the running application)

Sure, you can use the UART pins as general purpose IO pins - however, it's far from ideal - for one simple reason:

The ROM issues messages on the UART at boot time.

This means that when you power the chip up whatever is connected to the UART TX pin will receive pulses of HIGH and LOW.
That may or may not be a problem, depending on what is connected. It's something you need to bear in mind though.

Is the UART TX pin the only pin of this concern then?

Yeah. The RX pin is an input, and during normal boot isn't actually used for anything.

However, the RX (gpio3) pin is apparently pulled HIGH on boot, just like pins 12, 13 and 14 - also, driving gpio 1 (TX) low on boot will prevent boot - one common use for RX is i2s - it's the SD pin for i2s output


text:
Arduino Nano use SPI pins as I/O pins? and still be able to do ISP?
I wonder if can use the Arduino Nano SPI-pins(MOSI,MISO & SCK) as I/O pins in a sketch? and still be able to program over ISP?
Of course I will physical disconnect the Arduino from any other hardware before programming.

why do you ask this?

Yes, you can use SPI in your sketch just as you like. The programming over ISP is triggered by resetting the microcontroller. That means, that when trying to program over ISP your sketch (which configures the SPI hardware for use) doesn't run. The programming is starting at a stage, before the sketch runs, thus the sketch cannot interfere.
By the way: The same is correct for programming over Serial, though for a different reason. Programming over Serial is done by the bootloader, which runs before your sketch.

So I can use them as digital I/O:s and I can also use the TX/RX as I/O:s but then I will be unable to use the COM-port to talk to the PC during operation, have I got it correctly?

Yes, you can use the SPI pins as IOs, as you like. For the hardware Serial pins TX and RX: You can configure them as IO, but you should consider cutting the traces to the USB Serial chip, that are connected to them. The lines of Serial (UART) are actively high. The USB Serial chip can interfere with the intended functions of the pins, when you don't cut the traces.

@chrisl - Usually that is not a problem. The USB serial interface connects to the processor via 1k resistors. When used as an output the processor can overdrive the resistor. When used as an input the driving source needs to be powerful enough to drive the 1k resistor as well as the processor.