text:
Passing a NeoPixel object reference to a custom library
I'm new to Arduino programming and haven't programmed in C++ in the past. I'm trying to create a custom library to cycle a rainbow on my NeoPixel LED strip. I want to pass a reference or pointer or whatever into the library class so I can keep the code in my project file as simple as possible.
Here is my current project code:
#include <YaNeoPixelCycle.h>
#include <Adafruit_NeoPixel.h>

#define CONTROL_PIN 3
#define LED_COUNT 8
Adafruit_NeoPixel neoPixel(LED_COUNT, CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
YaNeoPixelCycle cycle = YaNeoPixelCycle(neoPixel,255,100,200);

void setup() {
}

void loop() {
  cycle.tryStep();
}

And here is the library I tried to create:
/*
    Youkai's Artificery NeoPixel cycle library.
    A super basic RGB LED cycle.
*/

#ifndef YaNeoPixelCycle_h
#define YaNeoPixelCycle_h

#include "Arduino.h"
#include <Adafruit_NeoPixel.h>

class YaNeoPixelCycle{
    public:
        YaNeoPixelCycle(Adafruit_NeoPixel& neoPixel, int saturation, int brightness, int hueStep);
        void tryStep();
    private:
        Adafruit_NeoPixel& _neoPixel;
        unsigned int _ledHue = 0;
        int _saturation;
        int _brightness;
        int _hueStep;
};

#endif

/*
    Youkai's Artificery timer library.
    Some basic non-blocking timer functions.
*/

#include "Arduino.h"
#include "YaNeoPixelCycle.h"

YaNeoPixelCycle::YaNeoPixelCycle(Adafruit_NeoPixel& neoPixel, int saturation, int brightness, int hueStep){
    _neoPixel = neoPixel;
    _saturation = saturation;
    _brightness = brightness;
    _hueStep = hueStep;
    _neoPixel.begin();
    _neoPixel.show();
}

void YaNeoPixelCycle::tryStep(){
    _ledHue += _hueStep;
    _neoPixel.fill(_neoPixel.ColorHSV(_ledHue, _saturation, _brightness));
    _neoPixel.show();
}

The first step would be getting this to function at all. Uploading this to my Sparkfun ProMicro bricks it and I have to reset it to upload code again.
After that it would be awesome if it was possible to declare the NeoPixel in the project file but not actually initialize it until the library file. I'd love to pass CONTROL_PIN and LED_COUNT as variables to the library with YaNeoPixelCycle(..., int controlPin, int ledCount) so I don't have to set up a bunch of duplicate variables in my main file if I'm running more than one NeoPixel strip.
This is my own custom library so I'm not too worried about it being obscure. If it's possible/easier I would be fine just moving all of the NeoPixel code entirely into the library and never creating it at all in the main file. Just passing the control pin and LED count as parameters and having to "know" that those refer to a NeoPixel would be fine too.

If you want to initialize it in the library, why do you need an instance of NeoPixel, that is external to the library? You could simply put the complete declaration of it into the library. I currently don't see your problem

I wasn't thinking originally of declaring it in the library. But if that works it would be fine too.

Yes, it works. You can simply have it only there

You call _neoPixel.begin() and _neoPixel.show() in the constructor of your class. This constructor runs before the Arduino is initialized. This is why   begin() functions are used. Add a begin() function to your class and call cycle.begin() in setup().
void YaNeoPixelCycle::begin() {
  _neoPixel.begin();
  _neoPixel.show();
}

Of course remove the _neoPixel.begin() and _neoPixel.show() from the constructor.

This helped. I also needed to apparently use a "member initializer list" instead of doing the assignment in the constructor. I guess my NeoPixel object wasn't getting set properly the way I was doing it above.

Thanks for this!  I also had my members being set in the ctor which didn't work.  I was going crazy trying to figure out why it didn't work.  Switched to member initializer list and it's working fine now.


text:
How far can a HC-SR04 can stand from the microcontroller?
I was wondering if I connect a HC-SR04 to an Arduino or any other microcontroller by normal cables, what would be the maximum length of this cable so that the measurements will still be true, and not affected by the length of this cable?

this problem consists of 2 things :

supply level drop (this one has severe effect)
signal level drop (a little more forgiving)

as the signals on the cables don't have high frequencies, the problem narrows down to just voltage level drop due to cable resistance.
supply level drop: the datasheet for SR04 says a maximum active current of 20mA is required for device to work properly. the supply voltage is 4.5~5.5v. so if you provide a 5v power for it, the cable must not drop it under 4.5v. the maximum resistance for the cable is calculated

R=V/I => R = (0.5/20)*10^3 = 25 Ohms

. you can use this value to find out maximum cable length using resistance tables provided by cable makers. e.g. if you have bought a 5ohms/meter cable, the maximum length should be under 5 meters to ensure a good power delivery.
the signals on the other hand, have very little current going between them. as the MCU/Module pins have a very high input impedance. so they are not as severe as the supply drop.
using a 100uF cap near SR04's supply pins would be great.

I have a couple measuring the liquid level of two tanks.
The units are distanced from the microcontroller by 12' of 18ga solid-core copper cable.
Testing was done with another microcontroller with the sensor attached by 6" cable to ensure accurate readings.
That's the longest I needed, so I haven't tested beyond that.

The signal of an HC-SR04 is the pulse on the "Echo" wire. The length of that pulse is directly proportionate to the distance from the object.
Since cable length does not affect the duration of that pulse, measurement accuracy isn't affected either.

Though that doesn't mean, that you can use any cable length. At some point the resistance of the cable might get too high, thus pushing the voltage too low for the Arduino to detect correctly. Also the increasing capacitance can smooth out the edges of the signal. But that can only be tested with the used cable, since there is no standard for a "normal cable".

Oh, absolutely. I don't think it'll have much influence in practise though - the input impedance on Unos is quite large, and so is the pull-up resistor. If all else fails, you could probably even analogRead the port.

source: Stack Exchange

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

sort: votes


text:
Self made ATMega32U4 board first programming
I'm stepping into Arduino world and decided to build a small board to implement a gamepad. Prior designing the board I tested my firmware on a Arduino Pro Micro USB so I decided to make something similar. My board use an ATMEGA32U4-AU instead  ATMEGA32U4-MU because it's simpler to solder. Connecting the board to my PC I noticed a new device named ATmega32U4 appear between Windows devices this sounds like the board is working.
Now the problem is how to program it with the correct bootloader (?) and make it a real Arduino board.
I found some spurious articles about how to make it but I have not a clean idea. Someone can help me?
I can share everything you need to focus on the board.
UPDATE ---------------------------------------------------------------------
Before installing Arduino bootloader I tried programming a sample firmware on the board trough Atmel FLIP (successfully). After that I never been able to program the board again (neither trough FLIP or other means)
I connected my board to Arduino ISP and since Windows seems unable to find the correct driver I had to install it manually, after that I tried to install the bootloader trough Install bootloader option of Arduino IDE (selecting Arduino ISP as programmer) but I had no success:
This's the log:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\tux\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : arduinoisp
avrdude: usbdev_open(): Found USBtinyISP, bus:device: bus-0:\\.\libusb0-0001--0x2341-0x0049
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : USBtiny
         Description     : Arduino ISP Programmer
avrdude: programmer operation not supported

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

avrdude done.  Thank you.

Error during bootloader writing.

I can clearly see that my firmware is not running when I start the booloader process (probably because it reset the board).
From the log it seems that everything is going correctly until:
programmer operation not supported
What does it means? Is the programmer unable to program such chip? How can I fix this?
If I reset my board prior trying to burn again a new firmware over it will it work or I just have to put a brand new micro on it?
Best regards,
 Mike

Sounds like you're in DFU programming mode. There's an app for that.

You mean this: https://www.microchip.com/developmenttools/ProductDetails/flip#additional-summary ?

Looks like it. I never use it, so don't know for sure, but it certainly rings a bell.

I don't think it can be used to replace a bootloader probably I can use it to program flash with a Arduino hex.

You could use a different Arduino with the ArduinoAsISP sketch, and burn the bootloader (and fuses) using the ISP pins on the ATMega32u4

I see ... should I use the install bootloader function in ArduinoIDE?

The problem was a wrong MISO connection given by a bugged ATMega32U4 footprint.

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


text:
Set SPI MOSI pin to idle low on a Due?
I have an SPI slave connected to Due. I send the SPI slave into sleep mode. During sleep, I need to pull all pins low, including MOSI. What's the best way to pull the SPI-4 pin low on a Due?
Here's a similar question but it's about an AVR chip and the answer obviously doesn't apply to SAM3X8 which is an ARM.

Is it the only slave that is connected to the Due?

@SimSon Yes it's the only one.

Then you could disable the SPI and set the MISO pin as output low

Disable SPI, disable peripheral clock for SPI, change back corresponding pins from alternate functions to normal pin functions and set proper outputs. But you should also disable power for the slave. Otherwise low on its chip select pin means it'll be active

@KIIV Is SPI-4 available as a digital IO pin? Which one?

@DmitryGrigoryev There are just two SPI's and another four USARTs with SPI mode. However it doesn't matter, pins are fixed and so alternate functions for that pins. You have to use datasheet for the MCU to figure it all out.

@KIIV I'm talking about the SPI-4 pin available on the Duo

@DmitryGrigoryev https://www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf -> SPI header pin 4 is PA26. So, you have to take a look into datasheet and figure out, how to set/reset it's alternate function

I have managed to set MOSI to low by setting bit 26 in PIOA->PIO_PER, PIOA->PIO_OER and  PIOA->PIO_CODR registers. To use SPI again, bit 26 in PIOA->PIO_PDR has to be set (this cancels the effect of PIOA->PIO_PER).


text:
Keep 5V on while sleep with LowPower library
Is it possible to keep the 5V on, while putting the Arduino (ATMEGA328P) in sleep more, using LowPower library?
I'm trying to use this HAT:
https://spellfoundry.com/product/sleepy-pi-2-usb-c/
to control the power of my Raspberry Pi. But on top of it, I want to have a second HAT that I want to feed 5V input, event after I shut down Raspberry Pi and put the Arduino to sleep.

The 5V of an Arduino is always on. It's power, not a controllable pin. Or are you on about some functionality of this Pi hat that you link to (to a site which is completely meaningless TBH...)

If I read the schematics at https://spellfoundry.com/download/sleepy-pi-2-usb-c-schematic/ correctly, you need to draw continuous 5V power from the SUPPLY_5V pin instead of the SUPPLY_EXP_5V pin (the latter seems to be switched via some MOSFETs connected to pin 2 of the ATMEGA328p). Which means that you need to connect the 5V power of your second HAT to JP4 pin 3 on the Sleepy Pi HAT (instead of JP5 pin 3).


text:
Convert float to char array on ATtiny85
I'm having a hard time trying to convert a float into a char array so it's stored like '7.125' just like the float looks.
I'm trying to communicate with an ATtiny85 (slave) and a program on a Raspberry Pi (master) over I2C.
The master expects 31 bytes from the slave when data is sent to it.
When I use this code on the ATtiny85 everything works as it should, the Pi gets the data correctly.
    char computerdata[35];
    computerdata[0] = '3';
    computerdata[1] = '.';
    computerdata[2] = '8';
    computerdata[3] = '7';
    computerdata[4] = '7';

    TinyWire.send(1);
    TinyWire.send(computerdata,30);

Of course I need to put a float variable in the array and not define numbers like I have for testing and this is where it breaks.
When I do something like this, it doesn't work, the Pi reports parsing error yet when I do this on the Due with Serial prints the char array looks good but something is different about it.
  sprintf(computerdata, "%2.32f", pH);

OR

  snprintf (computerdata, 35, "%f", pH);

What am I missing? Any ideas?
Thanks

Just to complement Michel Keijzers’ answer: sprintf() or snprintf()
are normally the right solution. On the AVR platform, however, float
conversions are left out of their default implementation, because they
take quite a lot of flash space, even when not used. On the other hand,
the avr-libc provides the non-standard function dtostrf()
for doing this conversion. The program
void setup() {
    float f = 3.877;
    char str[35];
    dtostrf(f, 0, 3, str);
    Serial.begin(9600);
    Serial.println(str);
}

void loop(){}

outputs
3.877

perfect, thank-you!

The reason is that the library which implements snprintf and sprintf can be dependent on the compiler used for your MCU, so in your case it's not supported.
If you always need the form %2.32f why not put it in directly, like:
int i = int(3.877 * 1000.0); // Assuming f of form a.bcd, i will be 3877
char str[6];
str[0] = (i / 1000) % 10;
str[1] = '.';
str[2] = (i / 100) % 10;
str[3] = (i /  10) % 10;
str[4] = (i      ) % 10;
str[5] = '0';

It will be much faster too.

Thanks for the answer but that wouldn't compile, got this error. Edgar's worked good.
sketch_feb28b.ino: In function 'void setup()':
sketch_feb28b:21: error: invalid operands of types 'double' and 'int' to binary 'operator%'
sketch_feb28b:22: error: invalid operands of types 'double' and 'int' to binary 'operator%'
invalid operands of types 'double' and 'int' to binary 'operator%'

True, I changed it, now it compiles (did not check it on an Arduino).
I will keep it despite dtostrfis better in most cases.

works good now. :)

Thanks for the confirmation

On an attiny85, the real question is why you got a float in the beginning. :)

@DataFiddler Because you need one (?) … or do you mean it's normally better to avoid floats and multiply a float value to an integer with some specific digits (e.g. use an integer value * 1000, to have 3 digits in form a.bcd ?)

You convert the float to an int. Probably it became a float by * 5.0 / 1023 or similar nonsense

@DataFiddler that's for the op to answer I guess.


text:
Error compiling for board Arduino Nano 33 BLE
I am trying to use pulse sensor with Arduino Nano 33 BLE sense, but when I verify it, it shows Error compiling for board Arduino Nano 33 BLE. The code is from the pulse sensor website. The code works with all Arduino board, but it is not working with the Arduino Nano 33 BLE.
This is the code:
/*  Getting_BPM_to_Monitor prints the BPM to the Serial Monitor, using the least lines of code and PulseSensor Library.
 *  Tutorial Webpage: https://pulsesensor.com/pages/getting-advanced
 *
--------Use This Sketch To------------------------------------------
1) Displays user's live and changing BPM, Beats Per Minute, in Arduino's native Serial Monitor.
2) Print: "♥  A HeartBeat Happened !" when a beat is detected, live.
2) Learn about using a PulseSensor Library "Object".
4) Blinks LED on PIN 13 with user's Heartbeat.
--------------------------------------------------------------------*/

#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

//  Variables
const int PulseWire = 0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
                               // Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
                               // Otherwise leave the default "550" value.

PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

void setup() {

  Serial.begin(9600);          // For Serial Monitor

  // Configure the PulseSensor object, by assigning our variables to it.
  pulseSensor.analogInput(PulseWire);
  pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);

  // Double-check the "pulseSensor" object was created and "began" seeing a signal.
   if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.
  }
}

void loop() {

 int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
                                               // "myBPM" hold this BPM value now.

if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
 Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
 Serial.print("BPM: ");                        // Print phrase "BPM: "
 Serial.println(myBPM);                        // Print the value inside of myBPM.
}

  delay(20);                    // considered best practice in a simple sketch.

}

The error text:
    Arduino: 1.8.7 (Mac OS X), Board: "Arduino Nano 33 BLE"

In file included from /Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.h:439:0,
                 from /Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.cpp:16:
/Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.cpp: In member function 'boolean PulseSensorPlayground::sawNewSample()':
/Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/utility/Interrupts.h:72:41: error: 'cli' was not declared in this scope
 #define DISABLE_PULSE_SENSOR_INTERRUPTS cli()
                                         ^
/Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.cpp:105:5: note: in expansion of macro 'DISABLE_PULSE_SENSOR_INTERRUPTS'
     DISABLE_PULSE_SENSOR_INTERRUPTS;
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/utility/Interrupts.h:73:40: error: 'sei' was not declared in this scope
 #define ENABLE_PULSE_SENSOR_INTERRUPTS sei()
                                        ^
/Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.cpp:108:5: note: in expansion of macro 'ENABLE_PULSE_SENSOR_INTERRUPTS'
     ENABLE_PULSE_SENSOR_INTERRUPTS;
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
exit status 1
Error compiling for board Arduino Nano 33 BLE.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

The code is from the pulse sensor website: https://pulsesensor.com/pages/installing-our-playground-for-pulsesensor-arduino.

wow! you are one of the very few people that has actually formatted the code when asked ... upvote for that

I tried #define USE_ARDUINO_INTERRUPTS false, but it is still the same error


text:
First time arduino attempt. 4 switch inputs controlling 8 LED outputs
This is my first venture into Arduino. I am unsure which one to use even for this. As this will be a dedicated unit, and size is a small priority, the smaller the better.
Here is more info on the scheme I am looking for.
Switch 1 on turns on LED groups 1 and 2
Switch 2 on turns on LED groups 3, 4, 5, 6, 7 and 8
Switch 3 on turns on 1 for say 500 ms, then turns 1 off, turns on 3 for 500 ms, then turns off 3, then turns on 5 for 500 ms, then turns off 5, turns on 7 for 500 ms, then turns off 7, then loops back and turns on 1 repeating the cycle.
Switch 4 on turns on 2 for say 500 ms, then turns 2 off, turns on 4 for 500 ms, then turns off 4, then turns on 6 for 500 ms, then turns off 6, turns on 8 for 500 ms, then turns off 8, then loops back and turns on 2 repeating the cycle.
Will I need an Arduino uno, nano or micro?
I am hoping this will be an easy to do project in order to learn the world of Arduino

Any Arduino would be able to do this trivially small task.  Any of them are capable of way more if you want it.  If size is your biggest concern then get a small one.

nano and uno use the same atmega328p controller, which is the most common "Arduino" type. Nano is more breadboard-friendly.

Micheal well easy solution is to use arduino nano as its bread board friendly and easy as it comes with the arduino IDE installed, well if size is what you are looking for then digispark attiny 85 can also do the task and its size is almost equal to a coin but for that youll need to install it in the arduino IDE which is a bit difficult.
if you need any help with attiny 85 you can come here

The Nano does not come "with the arduino IDE installed", but the Arduino IDE comes with the Nanos board definition installed. Small but important difference in wording.

Promini is even smaller. Plug an FTDI Basic onto it for loading code, remove it when done.

Won't need any more inputs it this as this is the entire project completely. I just have no idea where you start with the coding. I've made circuit boards from bare copper sheets, but never done any coding. Your help and advice is greatly appreciated.

sorry for my words but i meant arduino IDE comes with arduino nano board definition installed, for size attiny85 is best for this application but code would need to be concise and also youll need to install board definition for the attiny85

First of all, you need to have an overview over the whole project because you need to know what components you are going to use, how many digital/analog pins do you need, then check the official Arduino website to see if the board fulfills your needs.
If there is no special need, like more EEPROM or more analog inputs, almost most of the board will work for you (because most of them have the same microcontroller: ATMEGA328P), so it is up to what form factor you prefer more.
Personally, I would like to go with the Micro board because it has microusb connector, it is breadboard friendly (which is a big plus when you are prototyping) and it can be recognised as a mouse or keyboard.


text:
How can I fix this error "invalid operands of types 'const char [17]' and 'float' to binary 'operator+'"?
#include <Wire.h>

long aX,aY,aZ,gX,gY,gZ;
float rtX,rtY,rtZ,gfX,gfY,gfZ;

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

void loop()
{
  recordAccelregisters();
  recordGyroregisters();
  printData();
  delay(100);
}

void setupMPU()
{

  Wire.beginTransmission(0b1101000);
  Wire.write(0x6B);
  Wire.write(0b00000000);
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000);
  Wire.write(0x1B);
  Wire.write(0b00000000);
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000);
  Wire.write(0x1C);
  Wire.write(0b00000000);
  Wire.endTransmission();
}

void recordAccelregisters()
{
  Wire.beginTransmission(0b1101000);
  Wire.write(0x3B);
  Wire.endTransmission();
  Wire.requestFrom(0b1101000,6);
  while(Wire.available()<6)
  {
    aX = Wire.read()<<8|Wire.read();
    aY= Wire.read()<<8|Wire.read();
    aZ = Wire.read()<<8|Wire.read();
    processAData();
  }
}

void processAData()
{
  gfX= aX/16384.0;
  gfY = aY/16384.0;
  gfZ = aZ/16384.0;
}

void recordGyroregisters()
{
  Wire.beginTransmission(0b1101000);
  Wire.write(0x43);
  Wire.endTransmission();
  Wire.requestFrom(0b110100,6);
  while(Wire.available()>6)
  {
    gX = Wire.read()<<8|Wire.read();
    gY = Wire.read()<<8|Wire.read();
    gZ = Wire.read()<<8|Wire.read();
    processGdata();
  }

}

void processGdata()
{
  rtX= gX/131.0;
  rtY = gY/131.0;
  rtZ= gZ /131.0;
}

void printData()
{
  Serial.print("Gyro degree(x)= "+ rtX + " ");// this line shows error mentioned above in the question
  Serial.print("Gyro degree(y)= "+ rtY + " ");// this line shows error mentioned above in the question
  Serial.print("Gyro degree(z)= "+ rtZ + " ");// this line shows error mentioned above in the question
  Serial.print("Accel Gforce(x)= "+ gfX + " ");// this line shows error mentioned above in the question
  Serial.print("Accel Gforce(y)= "+ gfY + " ");// this line shows error mentioned above in the question
  Serial.print("Accel Gforce(z)= "+ gfZ + " ");// this line shows error mentioned above in the question
}

this is a code of mpu6050.  Why am I getting this error and How Can I resolve it?

Side note: you should not write Wire.read()<<8|Wire.read() because the order of evaluation of the calls to Wire.read() is unspecified. See also this thread in the Arduino forum. Use gX=Wire.read()<<8;gX|=Wire.read(); instead.

These lines give you errors, because you cannot simply add character arrays (aka c-strings) and floats together with the + operator. C/C++ is very strict, when it comes to variable types. The compiler does not know, how it should add these types together.
In other high level languages a string literal (characters enclosed by " in the source code) are more complex types, than c-strings. They mostly have various different methods and also an implementation of the + operator for adding a float number in human readable form. This complex type in the Arduino world is the String type. You can convert the float variable into a String and then add them together. But that's not the way, that you should do it. Strings on AVR based Arduinos (like Uno, Nano, ...) can be very evil due to the limited RAM. See Majenko's blog entry about The Evils of Arduino Strings for more information.
Instead you should just use multiple print statements. As Serial data is send out serially (one byte after another), it doesn't matter, if you put all the data to send in one print statement, or in multiple onces. So each of the offending lines can be converted to something like this:
Serial.print("Gyro degree(x)= ");
Serial.print(rtX);
Serial.print(" ");

It does exactly, what your code does. But it will not produce an error, since the Serial.print() method is also implemented for using float arguments.


text:
Flow control between ESP32 and RS323 device
I'm trying to communicate an RS232 device with an ESP32 (Heltec Wifi/LoRa 32 v2) my problem is that I don't receive any response from the device, doing some research, I'm thinking that the trouble can be the flow control because I don't use these pins and the modules I've used neither have these pins. Do you know a way to, at least, solder the DB9 pins to have a sort of flow control to communicate the devices?

What kind of device are you trying to communicate with?

Also: do you use a TTL->RS232 converter?

This can only be answered by looking at the data sheet of "the RS232 device". You can emulate RTS/CTS flow control by connecting them to two unused GPIO pins and then taking care of them in your own code while sending data back and forth. Also, a real RS232 interface communicates on signal levels between 3 and 15V, so if you are not absolutely sure that "the RS232 device" answers on a signal level of less than 3.6V, you will absolutely need a level shifter. Better use a dedicated RS232 shield for that -- which is the only answer I can give from the information in the question.

You could use ESP-IDF calls to setup your UART correctly for hardware serial communication on pin 4 and 5 (and perhaps also other pins).
In the sample below, you just have to:

assign UART_CLIENT_RTS and UART_CLIENT_CTS to the pins of your need
change uart_config_t to whichever parameters are relevant for your RS232 device
set flow_ctrl to UART_HW_FLOWCTRL_RTS, UART_HW_FLOWCTRL_CTS, UART_HW_FLOWCTRL_CTS_RTS or UART_HW_FLOWCTRL_MAX

    #define BUFFER_SIZE 1024

    #define UART_CLIENT_TXD  (GPIO_NUM_4)
    #define UART_CLIENT_RXD  (GPIO_NUM_5)
    #define UART_CLIENT_RTS  (GPIO_NUM_?) // Set this
    #define UART_CLIENT_CTS  (GPIO_NUM_?) // Set this

    uart_port_t uartNum = UART_NUM_1;

    uart_config_t uart_config = { // Set this
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity    = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS
    };

    uart_param_config(uartNum, &uart_config);
    uart_set_pin(uartNum, UART_CLIENT_TXD, UART_CLIENT_RXD, UART_CLIENT_RTS, UART_CLIENT_CTS);
    uart_driver_install(uartNum, BUFFER_SIZE * 2, 0, 0, NULL, 0);

Communication can be done with the various uart_write_* and uart_read_* methods as defined in the documentation.


text:
Can't find a #include
I'm using the Marlin 2.0.3 for a 3D printer project. I'd like to tear apart the code, but I don't see a #include to anything in the Marlin.ino, Configuration.h, Configuration_adv.h, nor Version.h.
If I use a verbose compilation, I see the ./src/HAL/HAL_AVR/HAL.cpp is the first thing it tries to include, but I don't see that writen in the code.
How does it know what to include?
Incase you can answer without downloading it:
Marlin.ino and Version.h is just comments.
Configuration.h and Configuration_adv.h are just a bunch of #defines.
Link to Marlin: https://github.com/MarlinFirmware/Marlin/releases/tag/2.0.3

The IDE compiles everything in the src/ folder too...

Ah, that makes a lot more sense. Thanks!


text:
Problem with PWM pins on Arduino uno
I am working on an Arduino Uno Project of a car with two motors. The motor driver board is an L9110 H-Bridge. Here is how everything is connected:

And here is the code I am trying to run:

//Define all the pins for the motors
#define motorPinA1 3  //A pin right motor
#define motorPinB1 5  //B pin right motor
#define motorPinA2 6 //A pin left motor
#define motorPinB2 9 //B pin left motor

//Movement functions
void stopCar();
void frwrd(int motorSpdRight, int motorSpdLeft);
void back(int motorSpdRight, int motorSpdLeft);

//Global Variables
int motorSpeedRight = 0;  //The speed of the right motor
int motorSpeedLeft = 0;   //The speed of the left motor

void setup() {
  //Movement
  pinMode(motorPinA1, OUTPUT);
  pinMode(motorPinB1, OUTPUT);
  pinMode(motorPinA2, OUTPUT);
  pinMode(motorPinB2, OUTPUT);

  //Serial Monitor for debugging
  Serial.begin(9600);

  motorSpeedLeft = 100;
  motorSpeedRight = 100;

  frwrd(100, 100);
  delay(2000);
  stopCar();
  delay(1000);

  back(100, 100);
  delay(2000);
  stopCar();
  delay(1000);
}

void loop() {

  Serial.print("Forward");
  Serial.print("\n");

  frwrd(motorSpeedRight, motorSpeedLeft);
  delay(2000);
  stopCar();
  delay(1000);

  back(motorSpeedRight, motorSpeedLeft);
  delay(2000);
  stopCar();
  delay(1000);

}

// functions we need to make the code run
void stopCar(){
    Serial.print("Stoping Car\n");
    // Put motor 1 in halt
    analogWrite(motorPinA1, 0);
    analogWrite(motorPinB1, 0);

    // Put motor 2 in halt
    analogWrite(motorPinA2, 0);
    analogWrite(motorPinB2, 0);
}

// For the farward direction A pins will be high
void frwrd(int motorSpdRight, int motorSpdLeft){
    // Put motor 1 (Right) in forward motion with speed = motor_spd
    analogWrite(motorPinA1, motorSpdRight);
    analogWrite(motorPinB1, 0);

    // Put motor 2 (Left) in forward motion with speed = motor_spd
    analogWrite(motorPinA2, motorSpdLeft);
    analogWrite(motorPinB2, 0);

    /*
    // Put motor 1 (Right) in forward motion
    digitalWrite(motorPinA1, HIGH);
    digitalWrite(motorPinB1, LOW);

    // Put motor 2 (Left) in forward motion
    digitalWrite(motorPinA2, HIGH);
    analogWrite(motorPinB2, LOW);
    */
}

// For the backward direction B pins will be high
void back(int motorSpdRight, int motorSpdLeft){
    // Put motor 1 (Right) in backward motion with speed = motor_spd
    analogWrite(motorPinA1, 0);
    analogWrite(motorPinB1, motorSpdRight);

    // Put motor 2 (Left) in backward motion with speed = motor_spd
    analogWrite(motorPinA2, 0);
    analogWrite(motorPinB2, motorSpdLeft);

    /*
    // Put motor 1 (Right) in backward motion
    digitalWrite(motorPinA1, LOW);
    digitalWrite(motorPinB1, HIGH);

    // Put motor 2 (Left) in backward motion
    digitalWrite(motorPinA2, LOW);
    digitalWrite(motorPinB2, HIGH);
    */
}

Pins 3, 5, 6 and 9 are PWM so I can alalogWrite() to them and control the speed of the motors. Code uploads fine but although both motors move forward normally motor 1 (on pins 3, 5) doesn't move backward. The strange thing is that if I use digitalWrite (the commented code in the two functions) instead everything works normally but the motors move in full speed so it's not usable for my project. I have tested all the pins in other projects and everything worked fine so I know my board is not faulty.
I have also taken some measurements with a multimeter while the code was running. In the forward motion, both pairs of pins measured 1.95V. In the backward motion, the problematic pins measured 0V.
Any help would be appreciated!!

start debugging by testing the motor driver ... swap wires on the arduino output pins .... not related to the question, but the pin naming in your sketch is somewhat confusing motorPinA1 is not as clear as motor1fwd or motorLeftFwd

The l9110 has 4 input pins named IA1, IB1, IA2, IB2 so that's why I named them that way. As for the swaps, I have tried a lot of combinations but I did not get consistent results so I was a bit confused

@Juraj This is not exactly my problem. I don't have reverse movement at all on one motor.

Try different pins than 5 and 6, because those PWM generators share the timer with delay(), which I'd interpret as: You use analogWrite() to set the timer to fire every n microseconds to toggle your PWM signal  -- and then you call delay(1000), which sets that same timer to fire in one second to continue the program.
Pins 10 and 11 do use a different timer, so try these.
Reference: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

"The PWM outputs generated on pins 5 and 6 will have
  higher-than-expected duty cycles. This is because of interactions with
  the millis() and delay() functions, which share the same internal
  timer used to generate those PWM outputs."

I will try that and I will get back on you.

delay() doesn't interfere with PWM the way you imagine. Actually, using delay() does not interfere with PWM at all. The fact that the timer is shared does have some consequences on the timer settings. On pins 5 and 6, the PWM frequency is higher (976.6 Hz instead of 490.2), and the duty cycle slightly larger: (n+1)/256 instead of n/255, where n is the value you analogWrite().

Your solution seems to have solved the problem for now so I will accept your answer. Although when I try to run the same code as part of a more complicated project I get the previous results. I will try to debug and if I don't get results I will open another question. Thanks for your time


text:
Motors would make the car go extreme left instead of forward (Self Driving car)
This is my very first day in the community, please bear me until I make myself comfortable here.
Coming to my question,
I'm making a self Driving car.
My car instead of moving forward it moves on the left rigorously which makes the car go round and round.
Along with my arduino, I'm using the L298 bridge to control my motors.
The motors seem to work fine until put on the ground.
Can you guys help me with what could be the possible solution to this and make my car go forward.
Here's my code :

    const int EnableL= 5;
const int HighL = 6;  //Left side motors
const int LowL = 7;

const int EnableR= 10;
const int HighR = 8;  //Right side motors
const int LowR = 9;

void setup() {
 pinMode(EnableL, OUTPUT);
 pinMode(HighL, OUTPUT);
 pinMode(LowL, OUTPUT);

 pinMode(EnableR,OUTPUT);
 pinMode(HighR, OUTPUT);
 pinMode(LowR, OUTPUT);

}

void Forward()
{
  digitalWrite(HighL,HIGH);
  digitalWrite(LowL,LOW);
  analogWrite(EnableL, 255);

  digitalWrite(HighR,LOW);
  digitalWrite(LowR,HIGH);
  analogWrite(EnableR, 255);
}

void Backward()
{
  digitalWrite(HighL,LOW);
  digitalWrite(LowL,HIGH);
  analogWrite(EnableL, 255);

  digitalWrite(HighR,HIGH);
  digitalWrite(LowR,LOW);
  analogWrite(EnableR, 255);
}

void loop() {
  Forward();

}

Components used :
3 pack lithium ion cells at 12V to power L298 bridge
A 9v cell to power Arduino Uno

what does this mean? ... put on the ground ...  placed on ground ...or ground wire connected

https://arduino.stackexchange.com/questions/62889/l298n-motordriver


text:
Displaying when Button has been pressed for LED and returning 1
I've just started using Arduino and I'm having trouble getting my code right.
Here is the task I need to do.
"Create a button read function
  Hint: the function header should be int checkbutton ( void )
in the loop function, add code such that if the button has been pressed (i.e. the checkbutton function
returns 1), a message is sent to the serial monitor with your username."
There are no errors in the code but nothing happens in the serial monitor when I press the LED button and it does not return 0 when i don't press the LED button.
Any sort of help would be appreciated!
Thanks!
int Button = 15; //LED and output are on the same pin

int last = 0;

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

int button() {
  pinMode(Button, INPUT);

  int current = digitalRead(Button);

  if (current and not last) {
    delay(5);

    pinMode(Button, OUTPUT);

    Serial.print("Hey");
    return 1;
  }

  else {
    pinMode(Button, OUTPUT);

    current == last;

    return 0;
  }
}

void loop() {
  if (button >=0)
  {
    button();
  }

  else
  {
    ;
  }
}

Look up the StateChangeDetection example that is provided within the Arduino IDE, as well as https://www.arduino.cc/en/Tutorial/Button

Also, it depends on the microcontroller, but on most arduino products the LED is on pin 13 not 15

is this a school assignment?

In your button() function, the line
if (current and not last) {

is less common syntax. The more common equivalent is:
if (current && !last) {

(see https://stackoverflow.com/questions/2376448/the-written-versions-of-the-logical-operators)
This line:
current == last;

Has no effect and is incorrect. This ( “==“ ) is not an assignment but a comparison and does not do what you want it to do.
I also think you have this the wrong way around. You want to save the “last” button state to compare it with the current button state when you call button() the next time. So you would need to set “last” to the current button state, like this:
last = current;

The next time you call button(), “last” contains the previous button state, so your comparison to the current button state will work.
And I think your button detection code would work better if you set last = current each time you call button(), whether a button has been pressed or not. Otherwise your code would repeatedly keep printing “Hey” until you stop pushing the button (unless that’s what you want). Like so:
int button() {
  pinMode(Button, INPUT);

  int current = digitalRead(Button);

  if (current &&  !last) {
    ...
    ...

    Serial.print("Hey");
    last = current; // Insert here
    return 1;
  }

  else {
    pinMode(Button, OUTPUT);
    ...

(This has not been tested but should give you a general idea).

Thank you very much! Fixed my code and helped increase my understanding, much appreciated.

Your problem may only be that you are not calling the button function. Try changing if (button >=0) to if (button() >=0).

Ah yes, you're right. I made the change and now the serial monitor is printing hey but its not returning 1, nor am i getting 0 when i do not press the button. Btw, thanks for the edit! Much appreciated.

If you want to print 0 and 1 to the serial console you'll need to add the Serial.print(...) calls. If I understand what you want correctly, you may be able to replace the entire body of loop() with Serial.println(loop());


text:
First time working with arduino, need help adapting project from UNO to NANO
This is my first time working with an arduino and I'm having some issues when trying to copy a program I found online on my Nano.
Basically, my project consists in a pulse sensor that sends the pulse information to the arduino and then to the hc-05 Bluetooth module so my phone can receive this information in real-time.
On my nano: D2 receives the output of the sensor, D8 and D9 are connected to pins RX/RT on HC05 and D13 has a LED connected to it.
Now here's the thing, I really don't know much about this and the code I found uses different pins from the ones I'm using.
The LED keeps blinking and isn't synchronized with the sensor output, when the led blinks I receive a response in the Bluetooth serial app but I would like to synchronize the heart sensor with the led so than I can receive the pulses on my phone. I've been trying to solve this but I still can't find a solution.
Full code can be found at
https://www.instructables.com/id/Pulse-Sensor-With-Bluetooth-and-Arduino/
Here's part of my code
//bluetooth
#include <SoftwareSerial.h>// import the serial library

SoftwareSerial Genotronex(8, 9); // RX, TX
int ledpin=13; // led on D13 will show blink on / off
int BluetoothData; // the data given from Computer

//  Variables
int pulsePin = 2;                 // Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 13;                // pin to blink led at each beat
int fadePin = 5;                  // pin to do fancy classy fading blink at each beat
int fadeRate = 0;                 // used to fade LED on with PWM on fadePin

// Volatile Variables, used in the interrupt service routine!
volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

// Regards Serial OutPut  -- Set This Up to your needs
static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse

void setup(){
  pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!
  pinMode(fadePin,OUTPUT);          // pin that will fade to your heartbeat!
  Serial.begin(115200);             // we agree to talk fast!
  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS
   // UN-COMMENT THE NEXT LINE IF YOU ARE POWERING The Pulse Sensor AT LOW VOLTAGE,
   // AND APPLY THAT VOLTAGE TO THE A-REF PIN
//   analogReference(EXTERNAL);
Genotronex.begin(9600);
  Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
  pinMode(ledpin,OUTPUT);
}

//  Where the Magic Happens
void loop(){

    serialOutput() ;

  if (QS == true){     //  A Heartbeat Was Found
                       // BPM and IBI have been Determined
                       // Quantified Self "QS" true when arduino finds a heartbeat
        digitalWrite(blinkPin,HIGH);     // Blink LED, we got a beat.
        fadeRate = 255;         // Makes the LED Fade Effect Happen
                                // Set 'fadeRate' Variable to 255 to fade LED with pulse
        serialOutputWhenBeatHappens();   // A Beat Happened, Output that to serial.
        QS = false;                      // reset the Quantified Self flag for next time
       }
      else {

      digitalWrite(blinkPin,LOW);            // There is not beat, turn off pin 13 LED
      }

   ledFadeToBeat();                      // Makes the LED Fade Effect Happen
  if (Genotronex.available()){
BluetoothData=Genotronex.read();
   if(BluetoothData=='1'){   // if number 1 pressed ....
   digitalWrite(ledpin,1);
   Genotronex.println("LED  On D12 ON ! ");
   }
  if (BluetoothData=='0'){// if number 0 pressed ....
  digitalWrite(ledpin,0);
   Genotronex.println("LED  On D12 Off ! ");
  }
}
  delay(20);                             //  take a break
}```

why do you believe that synchonizing an LED with the sensor will actually send the pulses to the phone?

Because everytime the led blinks I receive it as a pulse on the phone

to port a sketch from Uno to Nano do: nothing

@Ricardo, the pulse transmit action causes the LED to flash, not the other way around .... what you want to do is for the pulse to be transmitted every time the sensor gets triggered ... the LED is irrelevant

I don't understand your problem. What should the LED do in relation to what? Also: Can you post the complete code. There are missing some function implementations, that might be important for whatever you want.

@chrisl the led on D13 should blink everytime the arduino receives a pulse from D2.  The complete code is in the link, I don't know how to post multiple tabs here. Basically I'm having trouble with changing the pins in the code to use it on my nano, everything should remain the same.

@jsotola Yes, you're right

@juraj all I need to do is change the pins from the original program so it works with my arduino nano, I know that's super easy, but I'm stuck

The original code uses PIN A0 to receive the output from the sensor, I'm using D2. I replaced the 0 for a 2 in the variable pulsePin, but still the arduino wont receive the pulse information, in my phone I get random pulses but they're not coming from the sensor.

you can't use pin 2. the sketch uses analogRead which works only on A pins. if you changed it to 2, then it is A2. why did you change the pin?

@juraj I changed it to pin A0 and it worked fine!! I still would like to know how to change it from A0 to D2. I really have no idea and already switched analogRead to digitalRead but it didn't work, also, thank you :)

for analogRead the pin have to be analog. I don't know why analogRead is used here

First: There is no need to change pin assingments, when changing from Uno to Nano. They use the same microcontroller and have the same pins.
You have set pulsePin to 2, which corresponds to pin D2. But the pulse sensor gives you an analog signal. D2 is not capable of measuring analog voltages, it can only measure digital voltages. Meaning you need to use one of the analog pins, A0 to A7, so use one of these pins in the declaration of pulsePin.
The reason for this is, that the microcontroller uses an extra peripheral device included in it for measuring analog voltages: the ADC (Analog to Digital Converter). It can only be connected to a limited number of pins (internally via a multiplexer). That also means, that you can only measure the analog voltage at one pin at a time.


text:
Run servo when image is capture
I am trying to create a program when the camera capture the servo will rotate in 90 degrees continously, but my code will stop in print output 2 any idea to run the servo continously?
Here's the Code
import numpy as np
import cv2
import serial
import struct
import time

ser = serial.Serial('COM11',9600)

x=0

while(True):

 # Capture frame-by-frame
    cap = cv2.VideoCapture(0)
    #framerate = cap.get(5)
    ret, frame = cap.read()
    cap.release()
    # Our operations on the frame come here

    filename = 'C:/Users/DELVO/Desktop/tryTest/bruises/main/images' +  str(int(x)) + ".png"
    x=x+1
    cv2.imwrite(filename, frame)
    print(ser.write(x))
    time.sleep(5)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

Arduino Code
#include <Servo.h>
int data_x = 0;
int data_y = 0;
int data[1];
Servo myservo_x;
Servo myservo_y;// create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  Serial.begin(9600);
  myservo_x.attach(7);  // attaches the servo on pin 9 to the servo object
  myservo_y.attach(10);
  myservo_x.write(90);
  myservo_y.write(90);
}

void loop() {
  while (Serial.available() >= 2) {
    //    data_x=Serial.read();
    //    data_y=Serial.read();
    for (int i = 0; i < 2; i++) {
      data[i] = Serial.read();
    }

    myservo_x.write(data[0]);
    myservo_y.write(data[1]);

    Serial.println(data[0]);
    Serial.println(data[1]);
  }

}

"code will stop in print output 2" Where is "print output 2" exactly? I don't understand your problem. Please describe it more. What is the code actually doing and what did you expect it to do?

did you use my program? when the output 2 print the servo will stop

No, I did not. We are first trying to find an error by looking at the code. Also I don't have a free pi with cam lying around, so I cannot test your code. So you mean, when 2 gets printed on the Pi

no no im just using arduino anyway my main problem is when the 2 gets printed the servo will stop.

is the arduino code giving error because you have initialized the array data with length of 1 (int data[1];) and in the for loop the length is exceeding the allocated length of the string: for (int i = 0; i < 2; i++) {
  data[i] = Serial.read();
                       }

How to do it? that my servo won't stop if im not close the program.

@TrialAndError Have you tried writing int data[2]; instead of int data[1];? That is your first step, since it is the obvious error

I see. Thank you.


text:
While Loop does not stop when condition is false
Here's the code:
void loop() {
  while (1 == 1) {
    ObsLeft();
    while (SeeLeft < 50 || SeeLeft == 50) {
      Urong();
      ObsLeft();
      if (SeeLeft > 50) {
        Hinto;
        break;
      }
    }
  }
}

ObsLeft() analogReads the Infrared sensor input and Serial.prints it
Urong() makes the sumobot go backward
Hinto() stops the robot
SeeLeft is the analog value given by the Line Sensor (in my experience, white is 42, black is 800+)
The Problem:
When I run the program with the sensor seeing White, it makes the robot go backward, but when I move the bot so that the sensor sees Black, it still keeps going.
When I run the program with the sensor seeing Black, it does nothing.

while (1==1) is redundant. the loop() loops

Hinto; is the address of the function. Hinto(); calls the function.

Please post a full functioning code. Also I think you have forgotten the parenthesizes after Hinto, since it is a function. Maybe a copy paste error. Is 50 really a good value to distinguish between black and white, when white is 42 and black is over 800? In such a situation the analog value might easily go over 50 due to noise. Have you tried a threshold value a bit higher, maybe 100?

while (SeeLeft < 50 || SeeLeft == 50) { is same as while (SeeLeft <= 50) {

Usually, in arduino programming while loops should rather be ifstatements and leave looping to the loop() function. This is a good example. As long as there's no definition of variables (SEELEFT) and no hint where, why and how they ever change, any more help is questionable.

have you considered the possibility that the condition is not false?


text:
Arduino Nano 33 battery power/charging
I have a project with an Arduino Nano 33 BLE Sense. My project is working great, but I need to transition it to battery power, and I'm having a bit of confusion about exactly what's required.
I have a small 3.7V Li-ion battery I'd like to use (similar to this one {0}) if possible.
I have read what seems to be some conflicting information, so I'd like to see which of the following are true:

I can power the Arduino directly from the 3.3v pin? I'm suspicious of this advice since on the datasheet the 3.3v pin is marked output only. There's a note on the product page that says:

Note: for ultra low-power functionality, you should cut the 3V3 jumper on the back of the board, and use an external battery at 3V3.

Is this something I should do? It seems difficult to reverse, I'm worried I might break my project.

I can power the Arduino directly from the VIN pin? This again seems to contradict the datasheet, which says the VIN pin can only handle 4.5 - 21V. 3.7V is less than this.
I could use a Step-up DC-DC transformer - like this {1}? I'd rather not wait for shipping from China.

Furthermore, I'd like to be able to charge the battery, so if I use a charging board like this one {2}, would that just work?
I don't want to connect the battery anywhere it might not be welcome for the risk of frying anything. Any help would be appreciated.

Link references (in case ebay listings go away):
0: Lithium Ion Battery - 110mAh

1: Mini 3V 3.3V 3.7V 5V 9V to 12V Step Up Boost Converter Module Voltage Regulator

2: 4.2V 5V 1A Micro USB Li-ion Battery Charger TP4056 Protection Chip Lithium-ion

the pads near the 3.3 V pin where you can cut the tiny trace between them are easy to bridge with solder.

https://forum.arduino.cc/index.php?topic=665272.msg4481636#msg4481636

Thanks, that's good to know. So if I cut the bridge, enabling 3.3V mode, the USB cable will stop working, but I can power directly from that pin. It seems to suggest there's no voltage conversion going on, so I could damage the board if I supply 3.7+?

the power from USB will stop, not the data

Did you find a solution to this problem?

The VIN (and the USB) goes into a 3.3V switching regulator. This has a minimum input voltage of 4.5V.
You isolate the output of that regulator from the rest of the circuit by cutting that one link (which is easy to re-solder). You are then free to feed 3.3V from your own power source directly into the board.
Yes, if you provide more than 3.3V you are liable to damage the board (note that a Li-Poly can be around 4.2V when fully charged).
You need to take your battery power and feed it through a nice efficient switching voltage regulator that has a low enough "dropout" voltage to allow good use from the battery. Note that many devices "rated" at 3.3V will also work much lower. For example:

Nina-B3 series module will run at down to 1.7V.
The APDS-9960 will operate down to 2.4V.
The HTS221 will run at down to 1.7V.
MP34DT06J can go as low as 1.6V.
LSM9DS1 can run from 1.9V.
LPS22 is 1.7V minimum

So it could be good to reduce your power to 2.5V instead of 3.3V to give more life from the battery. You should check each of the components in the both the device schematic and the rest of your circuit (by reading the datasheets) to find the highest "minimum" voltage they will work on.


text:
How to switch between multiple BMP180 sensors?
I have six BMP180 sensors for measuring temperature and pressure. The problem is that I can get the value from one sensor but I need values from all six sensors using a single Arduino Mega board. How can I do that? I have already tried powering each sensor with digitalWrite but that didn't work. If you have a solution, can you also provide the code for that?

what have you tried? ... what problems did you have?

The BMP180 uses the I2C bus and you cannot simply turn off the device, since that can block the I2C bus. Also it has only one, not changeable address. Thus you would need one I2C bus for every BMP180.
So know you have 2 ways to go:

You could use a Software I2C library and define one I2C port for each BMP. That would use 12 digital pins and you need to find a fitting library, that supports multiple instances. Due to the timed nature of the I2C bus, you most likely will only be able to service one bus at a time.
You could buy a multiplexer chip for both signal lines. Then you could switch the SCL and SDA lines to each BMP. For that you need the multiplexer chips, 2 pins for I2C and 3 digital pins for input of the multiplexer chips (assumes an 8-channel multiplexer)

how can i define port ports for each bmp, i checked the I2C library on github but i am a bit confused. Also which library should i use as i am alreading using bmp180 library and i dont think it supports multiple instances.

I don't know, what you mean by "the I2C library on github". There are surely many I2C libraries on github. You cannot use the Wire library, since it is a hardware I2C library, not a software I2C library. I haven't used such a library, so I cannot suggest a good one. I googled "github arduino software i2c" and found this in the first few results. You need to try yourself and look, which library gives you the needed functionality.

Maybe you don't find a library, that can have multiple instances, but where you can repeatedly begin() the library with different pins, everytime, that you want to communicate with one of the BMPs.

thanks chris i will look into it.

If you have n-MOSFETs available, a simple multiplex solution would be: SCL directly from master to all slaves. SDA from master to Source of MOSFET (for each slave one MOSFET), Drain of MOSFET with pull-up resistor (e.g. 4.7k) will be the SDA signal. Gate of MOSFET to select slaves (active <-> Gate=high level). Make sure your MOSFET turns on based on your used voltage levels.


text:
On compiling I get #endif without #if error. Here is the code. Please help!
#include <Arduino.h>
#endif
#include <ESP8266WiFi.h>
#define watersensor D2
const char* ssid = "pooja";
const char* password = "ranip2780@";
WiFiServer server(301);
IPAddress ip(192, 168, 43, 67);
IPAddress gateway(192, 168, 43, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(192, 168, 43, 1);
void setup() {
  Serial.begin(115200);
  delay(10);

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

  WiFi.config(ip, dns, gateway, subnet);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  server.begin();
  Serial.println("Server started");

  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}

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

  // Wait until the client sends some data
  Serial.println("new client");
  while (!client.available()) {
    //    delay(1);
    client.setNoDelay(1);
  }

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

  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println("");
  client.println("");
  client.println("");
  client.println("<meta http-equiv='refresh' content='20'>");
  client.println("<title>WATER OVERFLOW ALARM WITH ONLINE UPDATES</title>");
  client.println("");
  client.println("");
  client.println("

");
  client.println("
");
  client.println("
");
  client.println("WATER OVERFLOW ALARM WITH ONLINE UPDATES
");
  client.println("USING NODEMCU 1.0 BOARD");
  client.println("
	");
  client.println("
");

  if (digitalRead(watersensor) == LOW)
  {
    client.println("<button style='background-color:red;width:200px;height:100px'>FULL LEVEL ALERT</button>
");
  }
  else
  {
    client.println("<button style='background-color:gray;width:200px;height:100px'NOT FULL</button>
");
  }

  client.println("
	");
  client.println("
");
  client.println("

");
  client.println("");
  client.println("
");
  client.println("

");
  client.println("LEGENDS:  <button style='background-color:gray;width:100px;height:50px'><font color='white'NOT FULL</button>");
  client.println("WATER LEVEL IS BELOW SENSOR.
");
  client.println("
<button style='background-color:red;width:100px;height:50px'>FULL LEVEL ALERT</button> WATER LEVEL IS ALREADY FULL.");
  client.println("

");
  client.println("");
  client.println("");
  delay(1);
  Serial.println("Client disconnected");
  Serial.println("");
  delay(500);
}

remove the #endif

You probably could have found this out yourself by just reading what the error message says. Maybe this tutorial will help you get started with coding for the Arduino.

The Arduino IDE gives you a massive clue
Arduino: 1.8.12 (Windows 10), Board: "Arduino Uno"

sketchX:2:2: error: #endif without #if

 #endif

  ^~~~~

sketchX:3:10: fatal error: ESP8266WiFi.h: No such file or directory

 #include <ESP8266WiFi.h>

          ^~~~~~~~~~~~~~~

compilation terminated.

exit status 1
#endif without #if

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

That's pointing at lines #2 & #3 in the sketch as having the error. So we fix those and try again
//#endif

I'll also install the ESP8266 stuff since that's missing on my new laptop.
Arduino: 1.8.12 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new
can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz,
DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower
Memory, Disabled, None, Only Sketch, 115200"

C:\Users\winuser\Arduino\sketchX\sketchX.ino: In function 'void loop()':

sketchX:42:3: error: expected primary-expression before '<' token

   < WiFiClient client = server.available();

   ^

sketchX:42:16: error: expected primary-expression before 'client'

   < WiFiClient client = server.available();

                ^

sketchX:42:16: error: expected ';' before 'client'

sketchX:43:8: error: 'client' was not declared in this scope

   if (!client) {

        ^

sketchX:49:11: error: 'client' was not declared in this scope

   while (!client.available()) {

           ^

sketchX:54:20: error: 'client' was not declared in this scope

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

                    ^

sketchX:4:21: error: 'D2' was not declared in this scope

 #define watersensor D2

                     ^

C:\Users\winuser\Arduino\sketchX\sketchX.ino:79:19: note: in expansion of
macro 'watersensor'

   if (digitalRead(watersensor) == LOW)

                   ^

exit status 1
expected primary-expression before '<' token

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

So all in all it's simple to use the messages that the IDE gives you to find your error and correct them, working from top to bottom in your sketch. It's not something that needs to be posted on StackExchange until you've corrected the basics.


text:
serialEvent only read 63Bytes and this is not the complete data incoming
hi everybody im working in a software for a pcb based in the chip ATmega2560
im use this with Xbee in API MODE, so im driving short string data and long string data.
with the short data i dont have any problem but my long data is of 78bytes.
so the serial event only show me 63 bytes and i dont find reason for it.
this is the complete block:
void serialEvent2(){
while (Serial2.available()){
    frameReceived[n] = Serial2.read();
    Serial.print("  ");
    Serial.print(frameReceived[n], HEX);
    n++;
    //Serial.print("\t" + String(n));
   /* if (n == (frameReceived[1]+frameReceived[2]) + 4){
        Serial.println();
        Serial.println((frameReceived[1]+frameReceived[2])+4);
        Serial.println("IF");
    }*/
    if ( n == 3 ){
        lfr = frameReceived[2] + 4;
    }

    if (n == lfr){
        receivedDone = true;
        Serial.println();
        Serial.print("[INFO] N: ");
        Serial.println(n);
        Serial.print("[INFO] LFR: ");
        Serial.println(lfr);
    }

    if (receivedDone){
        clearValuesToReceiveFrame();
        processFrame();
        receivedDone = false;
    }
}

Serial.println();
Serial.println("[While]n:");
Serial.println(n);
Serial.println("[While]LFR: ");
Serial.println(lfr);
n=0;
lfr=0;

}
in this block i learn to the programe that the posion 2 in my array is the lenght of the frame in API MODE:
        if ( n == 3 ){
        lfr = frameReceived[2] + 4;
    }

here i learn to the programe that the n number of bytes have to equal lfr (lengh of the data). if this is true my flags gonna work.
        if (n == lfr){
        receivedDone = true;
        Serial.println();
        Serial.print("[INFO] N: ");
        Serial.println(n);
        Serial.print("[INFO] LFR: ");
        Serial.println(lfr);
    }

    if (receivedDone){
        clearValuesToReceiveFrame();
        processFrame();
        receivedDone = false;
    }
}

the problem is that the program only rad 63 n number and my LFR is diferent so the flags never going true, n numbers ever is 63 from 78 real bytes :(
please help me.

serialEvent is called after the loop(). if your loop() takes time, the Serial receive buffer overflows

ok i read about it and yeah it is called to the final row in the loop, but any solution for it?look an another way to get the data?

write the code so that the loop() can loop. slow nested loops can always be integrated into the main loop. function can remember the last state of their work in static variables. If I am not mistaken, your sketch has a function which draws to a display in some for loop. remove the for loop, make the incremental variable static and return from the function after every increment. this way the sketch will multitask, drawing to display and reading Serial in time.

thank you bro, is a little bit hard to implement because i dont see a sample, but i'll try, thankk you


text:
Reading data from an Ohaus Defender 3000 with a RS-232 shield
I have a project where we have to read the weight from an Ohaus Defender 3000 by using an Arudino Mega 2560 and a RS-232 shield. Right now we have the RX of the Arduino to the TX of the shield, and the TX of the Arduino to the RX of the shield. In our code, we get both the RX and the TX lights of the shield to light up but we can't receive data from the scale into the Arduino. Could someone help me understand what is going on or am I doing something wrong. This is the following code that I used for the Arduino. I found this code at: Reading Arduino Serial Input. Thank you for the help in advance.
#define HWSERIAL Serial1

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

void loop() {
  int incomingByte;

  if (Serial.available() > 0) {
    incomingByte = Serial.read();
    Serial.print("USB received: ");
    Serial.println(incomingByte, DEC);
    //HWSERIAL.print("USB received:");
    //HWSERIAL.println(incomingByte, DEC);
  }
  if (HWSERIAL.available() > 0) {
    incomingByte = HWSERIAL.read();
    Serial.print("UART received: ");
    Serial.println(incomingByte);
    //HWSERIAL.print("UART received:");
    //HWSERIAL.println(incomingByte);
  }
}

I don't know the specific instrument you're trying to connect to, but have you configured it to send output to its serial port with the speed you expect in your sketch (9600 baud)? Also, for troubleshooting, have you tried to connect your instrument to a PC (via usb to serial) to see if it outputs any data on the serial port?

Can you provide a photo of your hardware setup, and the full code for your project?  Please use the "code sample" formatting widget (the "{}" icon) to surround the code section, and look at the preview to make sure the code is formatted correctly.
Just a guess, but you may have the TX/RX lines to the scale connected to 'Serial' on the Mega instead of 'Serial1'. That would definitely cause problems


text:
I2C and softwareserial
Attempting to make gps unit with screen. GPS unit communicates over serial (Adafruit Ultimate GPS Breakout) and I can get GPS data through USB to my pc with Adafruit GPS library softwareserial examples. The screen communicates over I2C (Sunfounder OLED-SSD1306 Module) and I can get display with Adafruit SSD1306 examples. However I cannot get both to happen simultaneously. Board is Adafruit Metro Mini 5v 16MHZ. GPS is using pin 8 for TX and pin 9 for RX. Display is using A4 for SDA and A5 for SCL.
If "Adafruit_GPS GPS(&mySerial);" is not commented the screen will not display anything. If it is commented the screen displays just fine. How do I get both to function simultaneously?
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET     -1
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8, 9);
Adafruit_GPS GPS(&mySerial);

void setup() {
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    for(;;);
  }
  display.display();
  delay(2000);
  display.clearDisplay();
  display.drawPixel(10, 10, SSD1306_WHITE);
  display.display();
  delay(2000);
  testdrawchar();
}

void loop() {
}

void testdrawchar(void) {
  display.clearDisplay();

  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.cp437(true);

  for(int16_t i=0; i<256; i++) {
    if(i == '\n') display.write(' ');
    else          display.write(i);
  }

  display.display();
  delay(2000);
}

I guess, you run out of memory

The problem was indeed running out of memory (as suggested by Juraj). After finding smaller libraries I was able to get it to work together just fine.

This is an incomplete answer. What libraries were chosen?

Final list of libraries:
#include <AltSoftSerial.h>   #include <TinyGPS.h>   #include <SoftwareSerial.h>   #include "SSD1306Ascii.h"   #include "SSD1306AsciiAvrI2c.h"   #include <Wire.h>
All of the Adafruit libraries were too large, so they all got switched out for more concise, compact libraries that fit my purposes


text:
Matching incoming data with a variable
I have a system where an RFID tag can be checked and Its individual 4byte UID will be printed. My task is to check if subsequent tags have the same UID and if not, print “access denied”. I'm assuming i need to use const char but I'm not sure. I get an error at if (myrfid.serNum[i] == ID) saying comparison between pointers and integers are forbidden.
Any sort of clarity would be appreciated, thanks!
(Code is only a section from the for loop)
void loop()
{
    int i;
    const char ID[] = "111 11 11 11";

    cardpresent = myrfid.isCard();

    if (cardpresent && ! lastcardpresent)
    {
        if (myrfid.readCardSerial())
        {
            for (i = 0; i < 4; i++)
            {
                if (myrfid.serNum[i] == ID)
                {
                    Serial.print("Acess granted ");
                }
                else
                {
                    Serial.print("Acess not granted ");
                }
            }
        }
        Serial.printf("%3d ", myrfid.serNum[i]);
    }
    Serial.print("\n");

    // ...
}

The accepted way to initialize an array in C follows this example:
const char ID [] = {111, 11, 11, 11};

You can read more about it here.
You later use an array name ("ID") with no index ("ID[0]").  The C compiler assumes the programmer who uses an array name with no index is interested in the memory address of the first element of the array.  But you wanted the value in that memory location.  So you should use the array name with the appropriate index.  Guessing, it would appear you intended to use "ID[i]" in the above code fragment.

Ah, i see. Thanks for the explanation, fixed the major issues i had!

Good.  If you understood that - welcome to C Programming with pointers.  Pointers are very useful.  And, honestly, you have a leg up on a lot of C programming beginners if you understand the difference between the address of a variable verses the value of the variable.


text:
Help Needed! How do I attach a color sensor to a 2WD robot and use it to control its movement?
I'm relatively new to the world of Arduino, so don't be frustrated if I ask questions that could be silly. This project has a deadline, so any input is appreciated.
THE PROJECT:
I am planning to build a 2WD vehicle, with an arm using 2 servos, and a TCS3200 color sensor. The goal is to make the robot avoid obstacles while simultaneously searching for a GREEN colored object (using the color sensor). After finding the GREEN object, it would stop and use the robotic claw to grab the object. Finally, it would continue to avoid obstacles until you reach a RED colored area. It would drop the object and start again.
QUESTIONS:
That said, I have some questions about the use of different sensors to control a robot (do not hesitate to put any input that may be useful)
1) How would you connect it to the sensor shield considering the other components? Could you use analog pins or (converting digital to analog) or use fewer pins? (I just need Green and Red)
2) How would make it so that the Arduino receives data from both sensors at the same time? How can I make both sensors control the same two motors?
WIRING:

NOTE: in the second image the ultrasonic sensor should be connected to the bottom right pins
EDIT:
@Peter Paul Kiefer---Could you please elaborate on how I can achieve for both sensors to control the same motors at the same time? Link to website where it is explained?
@jsotola 1) what do you mean by output? 2) I know that, I just want for the Arduino Uno to receive data from both the Ultrasonic and color detection at the same time. Using the data, I want the Arduino to control the motors to avoid obstacles, while using the color sensor to detect the GREEN object(at the same time)
The sensor It is called a TCS3200 color sensor by the way, and seems to only use digital pins. I am connecting it to the sensor sensor shield along with other things. (refer to images in the first post)This is how it looks like:

what type of output does the color sensor use?

How can I make both sensors control the same two motors? ... the sensors do not control the motors ... the arduino controls the motors ... the sensors only provide data to the arduino

You do not need to use an "PWM"-pin. The sensor reacts on different colors by changing the frequency at the OUT pin. The S2 S3 inputs are used to specify the color your want to measure. You can use S0 and S1 to switch to different frequency ranges. Use the  pulseIn(sensorOut, LOW); function to read the LOW pulse length of the  emitted frequency to get the intensity of the light of the chosen color. You could  use the pulseIn function to read Time of Fly  for the HC-SR04 too. You can use both sensors to read the values sequentially in the loop method.

Here are some further infos: https://randomnerdtutorials.com/arduino-color-sensor-tcs230-tcs3200/ I found it by goggel the words "TCS3200" "color" "sensor".

How did you go with this? Any progress?


text:
Multiple data packets with CIPSEND, associate each with pathway
When using a CIPSEND from an Arduino Uno to a ESP8266 connected to the Uno is there a way to associate the data packet sent with a pathway so it can be retrieved at said pathway from the browser?
For example ESP8266WebServer.h has a command like this:
server.on(“/specificArgs”, handleSpecificArg);   //Associate the handler function to the path

where the first argument is the path/filename - what's the equivalent of this using using CIPSEND?

The Arduino sends the CIPSEND to the ESP8266, not the other way around. It's hard to understand quite what you're asking.

I have rephrased the question. Refer to the ESP8266WebServer.h example here https://techtutorialsx.com/2016/10/22/esp8266-webserver-getting-query-parameters/ and you will see what I mean about associating the data packet with a path/filename.

So you are using the Arduino and ESP8266 as a web server?  The browser sends a request with a path in it, and your CIPSEND is what you send in response to that. The "association" is the fact that you are responding to a request.

https://github.com/khoih-prog/ESP8266_AT_WebServer

@Juraj useful as a last resort but I'd prefer to get it working with the AT commands rather than jump from that to a library.

Your "CIPSEND" is already associated with a path.
The sequence is generally:

You configure the ESP8266 as a server, including turning on multiple connections
You browse to the IP
The browser sends a HTTP request including a path. This has a "channel" number associated with it.
You generate a HTTP response and send it to the channel given in 3 using AT+CIPSEND.

The fact that you're sending the response to the browser through the channel that the request came in through "associates" the response with the request.
To do different things depending on the path it's up to you to recognise that path in the request and generate a different response accordingly.

"To do different things depending on the path it's up to you to recognise that path in the request and generate a different response accordingly." - yes how? If i want the first datapacket sent to the esp8266 to be associated with '192.168.4.1/' and the second to be associated with 192.168.4.1/data', how is that done?

When you receive the request to get / you send the response for /.  When you receive the request for /data you send the response for /data.

Ok I think I'm beginning to understand what you mean - If I understand correctly I should be doing a esp8266.find("/"); and esp8266.find("/data"); in my arduino code and then an if () to determine what path has been requested by the esp8266. I need to test this as there is an added complexity I didn't mention in my question. Data packet 1 is a webpage with ajax, data packet 2 is an json string. The json is constantly being updated by the arduino, the ajax webpage is directly requesting the ajax. As far as I understand this doesn't change anything but need to test...


text:
Arduino Firebase connection refused error
I am making a project for school where I have to send data from a sensor to a webpage. After doing some research I decided to use a Real-Time Firebase database. Security is not really important and I want to focus on other aspects of the project, so this seemed like an easy and quick option. I am using a d1 mini (esp8266) and a DHT11 humidity and temp sensor. For libraries I am using DHT, FirebaseArduino and ESP8266WiFi. The code is:
#include <ESP8266WiFi.h>                                                    // esp8266 library
#include <FirebaseArduino.h>                                                // firebase library
#include <DHT.h>                                                            // dht11 temperature and humidity sensor library

#define FIREBASE_HOST "xx"                   // the project name address from firebase id
#define FIREBASE_AUTH "xx"            // the secret key generated from firebase

#define WIFI_SSID "xx"                                             // input your home or public wifi name
#define WIFI_PASSWORD "xx"                                        //password of wifi ssid

#define DHTPIN D5                                                           // what digital pin we're connected to
#define DHTTYPE DHT11                                                       // select dht type as DHT 11 or DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  delay(1000);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);                                     //try to connect with wifi
  Serial.print("Connecting to ");
  Serial.print(WIFI_SSID);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("Connected to ");
  Serial.println(WIFI_SSID);
  Serial.print("IP Address is : ");
  Serial.println(WiFi.localIP());                                            //print local IP address
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);                              // connect to firebase
  dht.begin();                                                               //Start reading dht sensor
}

void loop() {
  float h = dht.readHumidity();                                              // Reading temperature or humidity takes about 250 milliseconds!
  float t = dht.readTemperature();                                           // Read temperature as Celsius (the default)

  if (isnan(h) || isnan(t)) {                                                // Check if any reads failed and exit early (to try again).
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  Serial.print("Humidity: ");  Serial.print(h);
  String fireHumid = String(h) + String("%");                                         //convert integer humidity to string humidity
  Serial.print("%  Temperature: ");  Serial.print(t);  Serial.println("°C ");
  String fireTemp = String(t) + String("°C");                                                     //convert integer temperature to string temperature
  delay(4000);

  Firebase.pushString("Humidity/", fireHumid);                                       //setup path and send readings
  Firebase.pushString("Temperature/", fireTemp);                                //setup path and send readings

}

replaced some 'sensitive' information with "xx". When running this code, it connects to my wifi connection and shows data from the DHT11 in the serial monitor. However NOTHING changes in Firebase. After enabling the feature to display extensive feedback/errors in the serial monitor, I noticed it's displaying this:
[HTTP-Client][begin] host: https://testtesttest-bd679.firebaseio.com/ port: 443 url: /Temperature/.json?auth=xxxx httpsFingerprint: 03 D6 42 23 03 D1 0C 06 73 F7 E2 BD 29 47 13 C3 22 71 37 1B
[HTTP-Client][sendRequest] type: 'POST' redirCount: 0
[HTTP-Client] failed connect to https://xxx-xxx.firebaseio.com/:443
[HTTP-Client][returnError] error(-1): connection refused
[HTTP-Client][returnError] error(-4): not connected
[HTTP-Client][end] tcp is closed
Humidity: 43.00%  Temperature: 22.50°C

I have tried the following things:

Using a different version of the FirebaseArduino library (5.13.x (still using this one))
Manually updating the fingerprint of the FirebaseArduino library (see current fingerprint in 2nd code section above)
Using different versions of the Arduino IDE, using 1.8.12 now

And some other minor changes like creating a new Firebase Database or using something different from pushString to add data to the database.
None of this helped and I am running out of time for my project, hope someone here knows what's wrong and can help me out! :)

You added a / to the end of the Humidity and Temperature collections.
e.g
    Firebase.pushString("Humidity/", fireHumid);
    Firebase.pushString("Temperature/", fireTemp);
The firebase API translates it to an address
https://testtesttest-bd679.firebaseio.com/Temperature/.json?auth=xxxx`

as we can see in the output.
I'm pretty sure the correct address is ...Temperature.json... and not ...Temperature/.json....
Please try to remove the slashes from the end of the collection names in the pushString statements..
Firebase.pushString("Humidity", fireHumid);
Firebase.pushString("Temperature", fireTemp);

If this does not help, it is possibly a problem with the auth string or the Host name. e.g trailing or leading space characters or something like that.

Thank you for your answer. It is able to connect to Firebase now. However i am getting this error now, maybe you know how to resolve this one aswell :) [HTTP-Client][handleHeaderResponse] RX: 'HTTP/1.1 400 Bad Request' This error occurs after it connects and it starts trying to push information into the database.

I deleted my former comment because my explanation was not correct. I do not know Firebase very well. The message says that page (respective the api method ) you try to access did not exist, Perhaps it works if you use other access methods. Perhaps push is not supported (for what reason ever): try setString insteadof pushString for example. If that works, I can not explain why, but you have a start point for further investigations. It would be helpful to know that, the Firebase. ... methods are translated to REST api calls and send as HTTP Requests to the firebase server.


text:
Continue playing sound during interrupt routine
I'm trying to play a tone (on an Arduino Mega through the tone library) and have the tone not be interrupted if an interrupt routine is called while the tone is playing. I'm not sure it's possible. The code block is below. Relevant functionality is:
-A while loop runs indefinitely until Button S1 is pressed. Pressing Button S1 triggers an interrupt routine in which interruptFlag_s1 is set to 1.
-This starts a tone playing for 300ms.
-There's a possibility that another button press interrupt is triggered during the 300ms tone. This interrupts the tone for about 0.5ms, enough to make a perceptible break in the tone that I'd like to avoid.
-Ideal scenario is that the audible tone isn't interrupted by the interrupt routine.
    while (restart == 0) {
      if (interruptFlag_s1 == 1 || interruptFlag_s2 == 1) {
        if (interruptFlag_s1 == 1) {
          primary_sensor = 1;
          interruptFlag_s1 = 0;
          rBot = false;
          gBot = true;
          bBot = false;
        } else if (interruptFlag_s2 == 1) {
          primary_sensor = 2;
          interruptFlag_s2 = 0;
          rBot = false;
          gBot = false;
          bBot = true;
        }

        interruptFlag_rtc = 0;
        finish_id = 0;
        button_flag = 0;
        time_diff = 0.00;
        alt_finish_time = 0.00;
        tone(speakerPin, 3000, 300); // Start tone
        restart = 1;
      }
    }

Interrupts should not affect tone() unless the ISR takes too long to execute. Keep your ISR short and all should be good.

Did you try it and experience discontinuity?

The sound is itself generated by an interrupt routine. Since only one interrupt routine can happen at a time, if your own interrupt routine takes too long, then you will get interruption in the sound.
There is nothing you can do about that other than making your interrupt routine short enough that it doesn't cause any interruption in the sound.


text:
Help printing Serial Monitor to LCD16x2
I have a motion sensor that triggers an LED and buzzer. That part works fine and it displays Motion detected in the serial monitor. I'm trying to get the LCD to print that as well but I can't get it to work. The LCD backlight turns on but that's it. At first I tried with the LCD16x2 I2C and now I'm trying with the regular LCD16x2. Here's my code:
#include <LiquidCrystal.h>

const int MOTION_SENSOR_PIN = 7;   // Arduino pin connected to the OUTPUT pin of motion sensor
const int BUZZER_PIN        = 3;   // Arduino pin connected to Buzzer's pincon
int motionStateCurrent      = LOW; // current  state of motion sensor's pin
int motionStatePrevious     = LOW; // previous state of motion sensor's pin
LiquidCrystal lcd(12, 11, 6, 5, 4, 2);

void setup() {
  Serial.begin(9600);                // initialize serial
  pinMode(MOTION_SENSOR_PIN, INPUT); // set arduino pin to input mode
  pinMode(BUZZER_PIN, OUTPUT);          // set arduino pin to output mode
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
}

void loop() {
  motionStatePrevious = motionStateCurrent;            // store old state
  motionStateCurrent  = digitalRead(MOTION_SENSOR_PIN); // read new state

  if (motionStatePrevious == LOW && motionStateCurrent == HIGH) { // pin state change: LOW -> HIGH
    Serial.println("Motion detected!");
    if (Serial.available()) {
      delay(0);
      lcd.clear();
      while (Serial.available() >0) {
         lcd.print("Motion detected!");
      }
    }
    digitalWrite(BUZZER_PIN, HIGH); // turn on
  }
  else
  if (motionStatePrevious == HIGH && motionStateCurrent == LOW) { // pin state change: HIGH -> LOW
    Serial.println("Motion stopped!");
    if (Serial.available() > 0) {
      delay(0);
      lcd.clear();
      while (Serial.available()) {
         lcd.print("Motion stopped!");
      }
    }
    digitalWrite(BUZZER_PIN, LOW);  // turn off
  }
}

start with the LCD example sketch instead of your sketch ... at this point, you do not know if the LCD module works correctly

Why are you using delay(0)? You don't need it. Also try to reset the cursor to a known position, before you print to the LCD

while (Serial.available()) is != 0 if there's something the SerialMonitor has sent. Until you do a Serial.read() inside the while. That means, it would fill your lcd with lots of "Motion stopped!" and seem blocked, then. (probably not your intention)

Yes the LCD works. Both have been used previously. @DataFiddler what do you mean with !=0? It doesn't need to have the while (Serial.available()). It was just something else I tried because I thought it might be an easier approach. Also, I didn't realize I took out setCursor(0, 0). Ill take out delay and add it again and see if it works.

!= not equal , here the same as > 0 (Be happy that it doesn't work, it would not work as intended)

Are you sending anything the Arduino on Serial?  You appear to only be writing and then checking available.  available is for seeing if something is sending TO the arduino, your sending data FROM the arduino won't change available.  IF you want the LCD to display the same as the Serial then put an lcd.print line right after the Serial.print line.  You seem to have some fundamental misunderstanding of what Serial.available() does.


text:
5V on HIGH Digital Pins, Only While Using USB Power
So I have a small problem with my Arduino Pro Mini here. May be worth noting that it is a clone, but otherwise this is still some weird functionality. I have done some experimenting so I'll just set the scene for you. I have everything that requires power connected to the + and - lines on my breadboard, that way I can avoid drawing more than about 20mA across any individual pins. I currently have my Arduino Pro Mini hooked up to the 5V power supply via the RAW and GND pins, but the supply is a regulated 5v wall supply. It actually is currently outputting 5.36V.
I have made sure all my pins I'm using for output are indeed set as output, the problem only arises when I attempt to power the device from something OTHER than USB power. I tested the output from my wall adapter connected to RAW and to a random VCC pin, both have the same effect.
When powering the device via USB (USB to Deek-Robot ASP, then to Pro Mini), if I set my digital output pin to HIGH, I get 5v. This is enough to turn on a 5v relay that then supplies power from the supply to a small water pump. However, if I use the regulated wall-power, I get about 3.7 to MAYBE 4.15v, which sadly is not enough to switch the relay to the NO position.
I have tested the voltage coming from the USB ASP as well, it is 4.95v.
EDIT: The wall-plug voltage drops from 5.36 with no load except the meter to 4.7v with the Arduino and a couple LEDs attached, if that means anything.

RAW pin requires at least 6 V

Power supply was dropping to 3.8 volts under basic load, once it turned on some LEDs it was just too low to activate the relay switch. Crappy Chinese parts.

So your problem is mainly related to the weak power supply, and to your attaching it to the wrong pin (RAW instead of Vcc). However, external supply at Vcc + USB in parallel is forbidden. Additionally, there are only few 5V relais that need only 20 mA.

The question does not mention relays that I see.  However, there are many 5V, 20mA coil relays.  A simple search at Digikey turns up 42 for example in SMD and thruhole (with some duplication for differents methods of delivery packaging) https://www.digikey.com/products/en/relays/signal-relays-up-to-2-amps/189?k=relay&k=&pkeyword=relay&sv=0&pv1989=0&pv72=249586&umax671=20&rfu671=mA&sf=1&FV=-8%7C189&quantity=&ColumnSort=0&page=1&stock=1&pageSize=25

"Arduino Pro Mini hooked up to the 5V power supply via the RAW and GND pins, but the supply is a regulated 5v wall supply. "
That is the problem. RAW pin expects more like 6V to 6.5V for the regulator to output 5V.
If you are supplying 5V, connect to the 5V, or VCC and GND pins.
If you are connecting to USB via an  FTDI Basic or equivalent, and the 5V supply at the same time, then the computer may not like having the USB 5V line back driven from an external source (mine complains about a "power surge" and shuts down the USB port). Make up a breakout cable between the FTDI and the Promini and either disconnect the 5V line, or put a diode in series so the Promini can't supply 5V back thru the FTDI and into the USB port.  That way the FTDI chip is powered from USB, but the Promini is not, and all the hardware is happy.
Make sure to use series resistors with LEDs to avoid overcurrent from the Promini output pin, which will either damage the IO pin, possibly damaging the 328P, or damaging the LED from overheating from excess current.  (5.36V - 2.2V)/.02A = 156 ohm. A 180 ohm, 220, 270, 330, some value in that range will do. 1K will probably be fine, LEDs these days can be quite bright even at lower current; 20mA can be blindingly/annoyingly bright.


text:
How does the ssd1306 handle different screen sizes?
I noticed that if I have two SSD1306 displays, the 128x32 display will lose every other row if written in x64 mode, and the 128x64 display will show blank horizontal lines if written in x32 mode. How does this physically work, and can I expect this to be a reliable feature?
I would have thought that half the screen would get cut off somehow, but it appears that it must interlace the data instead (which seems a lot more complicated). Yet there's also some sort of configuration to the driver chip to make it do this (It seems to be the 0xDA command, but I'm not clear how/why it has these options).
Can I expect that, at least if I use the same driver library, that using the wrong screen will always have this behavior? I was planning to use it to help the user detect what screen they have.

What does your own efforts reveal? What does the data sheet say? Did you look into the driver's source? You can answer most of your questions yourself with some web recherche and reading.

I looked up the datasheet, and there is some sort of muxing going on, but I didn't really understand it much, and some of it is library/implementation specific. As apparently mentioned below, it's a convention thing apparently...

The SSD1306 does not handle different sizes, it's ever only handling it's maximum size 128x64. But one can decide to only use less pins of the driver for a smaller display.
The SSD1306 has 128 segment pins, which activate the current column, so that the states of the 64 common signal pins will be used by the display for that column. For smaller display sizes there are just some pins of the SSD1306 left unconnected. They get set like all the other pins, but they are not connected to anything, thus the information gets lost.
For accommodating that, the library sets the pixel according to the size by not using every second row (aka common signal) for half size displays. That's why you get horizontal black lines, when using a 128x64 display with the library in 128x32 mode. The library thinks, that every second row is not connected either way and thus sets these pixels to black. The 128x32 display is loosing every second row when used with the library in 128x64 mode, because every second row is not connected.
Note, that nor the library neither the SSD1306 know about how the display is connected. You need to tell the library this, by setting the mode, and it will control the SSD1306 accordingly. So there is no feedback about the display, that you could use.

Can I expect that, at least if I use the same driver library, that using the wrong screen will always have this behavior?

Yes and no. The library handles it this way, because it is the common way to leave out every second pin for displays of half size. But it comes down to the manufacturer to decide this. We cannot guarantee, that nobody will ever connect the SSD1306 in a different way to a display.
For most manufacturers you will be good. If you simply plan to provide the displays for your user, so that they can change them their selves, you can be sure. If the user should be able to use her/his own display, purchased anywhere else, you might run into problems (though rarely).

I'd be providing the screens, so that part at least is easy. The worrying part is how do I know if the ones I'll be buying are wired normally...

By trying, just as you already did

...Thanks? That's not really the most encouraging...

Depending on where you are buying them, you might be able to get this information from the reseller/manufacturer. You will be fine in most cases. When you have found a reseller, that is selling the correctly wired modules, just buy the modules from him. There is no study, how many modules are wired that way,but I think it will be the wast majority of cases