text:
Store values in array
I'm trying to implement the "BNO055 9 Axes Motion Shield".
There is an existing Arduino sketch GitHub that reads out the Euler data, I changed it a bit to print out quaternion data.
#include "NAxisMotion.h"        //Contains the bridge code between the API and the Arduino Environment
#include <Wire.h>

NAxisMotion mySensor;         //Object that for the sensor
unsigned long lastStreamTime = 0;     //To store the last streamed time stamp
const int streamPeriod = 20;          //To stream at 50Hz without using additional timers (time period(ms) =1000/frequency(Hz))

void setup() //This code is executed once
{
  //Peripheral Initialization
  Serial.begin(115200);           //Initialize the Serial Port to view information on the Serial Monitor
  I2C.begin();                    //Initialize I2C communication to the let the library communicate with the sensor.
  //Sensor Initialization
  mySensor.initSensor();          //The I2C Address can be changed here inside this function in the library
  mySensor.setOperationMode(OPERATION_MODE_NDOF);   //Can be configured to other operation modes as desired
  mySensor.setUpdateMode(MANUAL);   //The default is AUTO. Changing to MANUAL requires calling the relevant update functions prior to calling the read functions
  //Setting to MANUAL requires fewer reads to the sensor
}

void loop() //This code is looped forever
{
  if ((millis() - lastStreamTime) >= streamPeriod)
  {
    lastStreamTime = millis();
    mySensor.updateQuat();        //Update the Quat data into the structure of the object
    mySensor.updateCalibStatus();  //Update the Calibration Status

    Serial.print("Time: ");
    Serial.print(lastStreamTime);
    Serial.print("ms ");

    Serial.print(" W: ");
    Serial.print(mySensor.readQuatW());

    Serial.print(" X: ");
    Serial.print(mySensor.readQuatX());

    Serial.print(" Y: ");
    Serial.print(mySensor.readQuatY());

    Serial.print(" Z: ");
    Serial.print(mySensor.readQuatZ());

    Serial.println();
  }
}

Here is a snippet of the "NAxisMotion.h" header file:
    /*******************************************************************************************
    *Description: This function is used to return the w-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    W-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatW(void);

    /*******************************************************************************************
    *Description: This function is used to return the x-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    X-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatX(void);

    /*******************************************************************************************
    *Description: This function is used to return the y-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    Y-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatY(void);

    /*******************************************************************************************
    *Description: This function is used to return the z-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    Z-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatZ(void);

I understand that the output data type is signed integer, but what syntax do I need to use to store them in an array?
Because it seems the only way to access them is through "mySensor.readQuatX()"

It would be better if you adopted the habit of including system libs first.  The reason behind this is it is theoretically possible (very unlikely) that a header file will include a the system lib header and then redefine a pre-processor variable that the system library uses and so you might get different/conflicting header files for the library.  Very very unlikely, unless you work with true coding cowboys.

Do you mean in this case Wire.h should come before NAxisMotion.h?

Yes  #include <xxx> before #include "xxx".
This also means if you get a duplicate definition int foo = 7 the error will be reported against the code you are more likely to have written rather than suggesting some system library is wrong.
Others will argue I'm wrong, but it would be boring if we all thought the same.

If I understand correctly you want to store a number of signed integers in an array.  Arrays have fixed sizes so you need to know the number of values you want to store.
// Global declarations
enum QIndex {WAxis, XAxis, YAxi, ZAxis, MaxIndex};
int16_t qData[MaxValues] = {0};

// Code inside loop
qData[WAxis] = readQuatW();
qData[XAxis] = readQuatX();
qData[YAxis] = readQuatY();
qData[ZAxis] = readQuatZ();

// Pass the array  of values to another function with the declaration
// void SomeFunction (int *ar);
// or
// void SomeFunction (int ar[]);
SomeFunction (qData);

Is that what you mean?

So basically I tried it out and your code worked, thanks a lot. But now I my problem is, I can't convert the unsigned int sensor data to floats (which would also have to be unsigned) for further proccesing in the program "Processing" for visualization. Is there any way?

Yes, but it will only give you a whole number, because that's all you have.  float fValue = (float)iValue;

I want to divide each element of the int16_t data-type array by 1000 and then convert them to float. It works but only gives me whole numbers like you said. What am I doing wrong? I need at least 2 decimal places.

You are doing integer division, you want float division.  float result = ((float)input) / 1000.0f;  You have to make both number floats and then divide.


text:
espcomm_sync failed when connecting ESP8266 (ESP-01)
I'm new to the Arduino (I'm a developer but didn't have a chance to work with this kind of device before) and wanted to connect my ESP8266 to the Arduino Uno. I followed this tutorial but I got errors:
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_memfailed
error: espcomm_upload_mem_failed

I tried running WiFiScan from the examples. I've installed SiLabsUSB Driver (I'm on macOS) and tried different solutions across the internet and I couldn't make it work.
There are screenshots of the settings.

that error usually means the ESP isn't in programming mode when you try to upload a compiled sketch to it

@JaromandaX so how to put in the programming mode?

Of course, I'm assuming you're trying to flash new firmware onto the ESP-01, if so, read the tutorial again - see step 19 in the tutorial you "followed"

@JaromandaX actually I didn't get to the 19th step as I couldn't get past step 2 but this flasher contains only .exe file and I'm on mac

That instructable is rubbish then. To flash the firmware, you need to ground GPIO 0, then power up (or reset) the ESP01 - then it's in flashing mode

you do something else like the instructable. you installed the esp8266 core into Arduino IDE and you try to upload a sketch. but you did not put the module into flashing mode.

the wire connections in the instructable will damage your esp. esp rx pin is not 5 V tolerant. you need a level shifter. the 3.3 V pin on Uno can supply only 50 mA. the esp8266 needs 170 mA for WiFi transmition

@Juraj - According to the data sheet the pins of most ESP are 5V tolerant, I think I remember they support 6.7v but please check, before you trust me.  (There is a post on here about it somewhere)

I checked http://espressif.com/sites/default/files/documentation/0a-esp8266ex_datasheet_en.pdf

I used different scheme to connect and when I connect the Arduino to the MacBook then it flashes blue LED but I still cannot select COM port and get espcomm errors

I connected GPIO 0 to GND and clicked Upload it started blinking blue light but still got espcomm warnings.

i see that when some settings are off, or if i have a module wired to GPIO1/3

@Juraj The CEO of Espressif confirmed that the IO is 5V tolerant. And an older datasheet (bottom of p17) mentions over-voltage protection.

ok, so why doesn't it work for me?

I connected GPIO 0 to GND and clicked Upload ... no, connect GPIO0 to GND, then reset or power cycle the ESP01, only now is it in flash mode

@JaromandaX noob question but how can I reset it?

you could add a momentary switch between the reset pin and ground

@JaromandaX any other solution? I don't have a switch

as I said, power cycle (turn power off then on) while GPIO0 is held to ground

source: Stack Exchange

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

sort: votes


text:
Is it possible to access GPIO9 and GPIO10 as DIO?
I have a nodemcu dev board with the esp12 chip. (Not the esp12e one).
I have tried to make use of gpios 9 & 10 for digital output. On the board, they are marked as SD2 & SD3. I suppose they must be serial data pins by default.
Ideally you can change the pin functions using the PIN_FUNC_SELECT() macro. So I tried the following:
PIN_FUNC_SELECT(PERIPHS_IO_MUX_SD_DATA3_U, FUNC_GPIO10);

However, on flashing this code, I notice my MCUs reboots. So it must have crashed at some point.
Am I doing this right?
PS: I was hoping to have at least 12 pins that can serve as digital output.

do you compile and flash with DOUT flash mode? btw SD label is not "serial data", but from SDIO a protocol for SDIO card (they are similar to SD card but not same).

I use platformio ide to do all the flashing

board_build.flash_mode = dout

https://github.com/espressif/esptool/wiki/SPI-Flash-Modes

Yes that seemed to make a difference. However GPIO9 still has the same problem.

with DIO set at build the mux setting should not be necessary

I am hoping we can make time and work together and nail this. Join here and mention availability: https://chat.stackexchange.com/rooms/110184/nodemcu-users

sorry, I don't know what else you could try. and I don't have a NodeMcu. other esp8266 boards and modules don't break this pins out. so I never tested this.

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


text:
Text send via HC-05 is broken up by first character on the receiving end?
On the receiving end, I have an mit app inventor app which acts like a client.
In arduino, I check for connection status and do a serial write to send the text. The code for that is below:
#include <SoftwareSerial.h>

#define D2 2
#define D3 3
#define BT_STATE_PIN 4

SoftwareSerial BTSerial(D3, D2);
long lastMark;

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

  int counter = 0;
  lastMark = millis();
}

bool isBTConnected() {
  return (digitalRead(BT_STATE_PIN) == HIGH);
}

void sendText(char* message) {
  Serial.println("SEND: " + String(message));
  if(isBTConnected()) {
    BTSerial.write(message);
  }
  else {
    Serial.println("did not send");
  }
}

int msgCount = 0;
void loop() {
  long now = millis();

  if(now - lastMark > 2500) {
    msgCount++;
    String msg = "This is a really really long MSG" + String(msgCount);
    sendText(msg.c_str());
    if(msgCount == 5) {
      msgCount = 0;
    }
    lastMark = millis();
  }
}

This is how the device is wired currently:

simulate this circuit – Schematic created using CircuitLab
On the app inventor side of things, I have a very simple app that connects to the bluetooth module; it listens for anything received, and then just receives the text.
aia file

Here is a pic showing the issue I am facing currently:

Sometimes the breaking up happens randomly at some other place. Hoping someone can help sort this issue.

Without having experience in AppInventor, I see the following problem:
In your app you are outputting the received data regularly with a timer in form of distinct messages. This code can naturally only display text, that was already received. You seem to think, that only because you use a single line oft code on Arduino for sending the message data, the data would be send in one big chunk. For Serial that is not the case. Actually the write() function only fills the libraries buffer and the actual data will then be send serially (thus the name). There is nothing like a chunk of data or a message on a serial interface, unless you yourself impose this principle on the data stream. All the bytes in the libraries buffer are the same and are being send in the order of the buffer. Moreover Bluetooth does consist of packages of data, but they will be automatically packed; in a way that will not correspond to your messages.
So in the end, arbitrary parts of your message will be received by the phone at arbitrary times, that highly depend on timing conditions. In your code you should constantly receive the data and only display a message, when you have received an \n character, which is the delimiter of a message. It is a very common and helpful technique to first receive a full message and then processing it, when the message is complete.

I did something similar (multiBT) using HC-05 and PC BT, with the same App.
Results: all the incoming data from the PC_BT to the phone are right, but with the HC-05 sometimes is chunked as @deostrol show. I think is a bug with the HC-05 firmware.
To correct this, I've implemented StartBegin and StopFinish character in the received string before use.

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


text:
Arduino and PCA9685 - Suddenly stopped working
I'm using an Arduino Uno and a PCA9685 board to run 4 servos (of type MG996R).
For that, I set up the following connections:

SCL -> SCL
SDA -> SDA
Ground -> GT
VCC -> 3.3V

As the servos require high current under draw, I've used an external power supply that is also connected to the PCA9685 at the intended place. The power supply is at 6V (DC) - and max 3 ampere.
Everything just worked fine for about 1 month. Then, suddenly the servos did not move anymore.
What I checked:

the power supply still gives the desired 5-6V at the PCA9685 board
I bought a new PCA9685 board
I used another power supply at 5.2V and max 2 ampere (only 1 servo connected)

The strange thing is that even with the new PCA9685  board and power supply, the servos don't move. However, they move if a remove the external power supply and connect the v+ pin of the PCA9685  to the arduino's 5V output pin.
You have any idea whats going on or what might be broken?

sounds like the external power supply is not powering the PCA9685 board

It would help if you posted links to each of the hardware devices and a schematic, not a frizzy thing. Do this after you verified that the pull ups for the I2C are correct and all the grounds are connected.


text:
Arduino ESP32 Import Error No module named serial
I googled and couldn't find a solution to my nice problem:
I have Ubuntu and I want to program a ESP32 ...............
I tried a lot of pip commands ... but it didnt work.
You have any idea how to install the correct packages?
Maybe you can tell me what to do. I am really lost.
I tried it last year and also failed.. Now I want to try it another time :)
   /.arduino15/packages/esp32/tools/esptool_py/3.0.0/esptool.py", line 38, in <module>
        import serial
    ImportError: No module named serial

I know this is old, but I was able to get around this on debian with sudo apt-get install python3-serial, hope it helps somebody

Open terminal and enter this command python -m pip install pyserial it will download pyserial for you and you will not receive the above error. The above error is because you don't have pyserial installed on the system.
The related documentation for pyserial could be found here

python -m pip install pyserial
/usr/bin/python: No module named pip

@jento you will first need to install pip I considered you have pip installed to install pip use the following command sudo apt install python3-pip for python3 or you can use sudo apt install python-pip for python 2

How about doing this but in a virtualenv, so not installing packages system wise?

I had the same issue compiling the CameraWebServer example. I'm using Ubuntu 20.04. The problem occurs during the linking stage when the script invokes python. On my system this runs the system python which is python 2.7.18. I don't think the serial module (supplied by pyserial) is available on Ubuntu 20.04 for python 2.x.
My solution was first to abandon the Arduino IDE and use the arduino-cli to compile the example. I created a virtual python 3 environment, activated it, installed pyserial under the virtual environment and run arduino-cli to make the runtime. The python scripts appear to be compatible with python 3.

the arduino esp32 python scripts work with python 2 and you can install pyserial into python 2.

I'm not sure it's available for 2.7.18. In any case, I did not want to install libs into the system python just to make a runtime when I can use a virtual env.

Problem resolved, Thank you.  I had installed pyserial.  The error surprisingly was related to the incorrect processor speed (!) in the Arduino IDE.  I have no idea why that would influence the serial/pyserial function.

Reference: https://www.how2shout.com/linux/how-to-install-python-2-7-on-ubuntu-20-04-lts/
I think Arduino IDE expects Python2 to be installed. My Version is Arduino-1.8.13
You also need Python2 modules so you need to install pip2
:~/curl https://bootstrap.pypa.io/pip/2.7/get-pip.py --output get-pip.py
:~/sudo python2 get-pip.py
:~/pip2 install pytools
:~/pip2 install pyserial


text:
Using Soft UART - how include library
I want to use the soft serial communication example.

But when I compile it, it sais:
/home/xxx/Arduino/SoftwareSerialExample/aa/aa.ino:28:28: schwerwiegender Fehler: SoftwareSerial.h: Datei oder Verzeichnis nicht gefunden
Kompilierung beendet.
exit status 1
Fehler beim Kompilieren für das Board Arduino Uno.

What is going there?
I  have a directory also with AFSoftSerial.h at /Arduino/libraries/AFSoftSerial/AFSoftSerial

the library should be here /home/xxx/.arduino15/packages/arduino/hardware/avr/1.8.6/libraries/SoftwareSerial

Check to make sure you have the line:
#include <SoftwareSerial.h>

... at the top of your Sketch.
Also, compare your code with that found on the Arduino Software Serial Library web page here.
Finally, make sure your Arduino Application and all your Arduino Libraries are up to date.

I have a directory also with AFSoftSerial.h at /Arduino/libraries/AFSoftSerial/AFSoftSerial

The code is looking for the "SoftwareSerial" library and that is the library you need include and call, not "AFSoftSerial". Or, if you intend to use AFSoftSerial, then change your code to say that instead.

Download Arduino SoftwareSerial library, extract it and put it into your libraries folder. Libraries folder is in your project folder. If you haven't changed project folder in Preferences, it will be in C:\Users\your_username\Documents\Arduino. Be careful that there are not two SoftwareSerial folders.
Then try to upload your code again.

just no. the Arduino SoftwareSerial library is bundled with the AVR boards package

But the compiler said "No such file or directory". Which means that the library is not installed anywhere.

which means something went wrong with the boards package installation and just putting random SoftwareSerial library into the libraries folder will not fix it


text:
connecting 4 wire camera to esp8266
I am looking for the arduino code to stream video to a webpage using the ESP8266.
here is the 4 wire camera I have: https://www.ebay.com/itm/172272466793
The other tutorials I'm finding online are all for a different cameras or are not using the ESP8266 for webpage streaming.
Any help or pointers would be most appreciated.

As a side note I have LiFePo 3.3v batteries that I plan to use to power both the ESP8266 and the 5v camera (by wiring them in series).
The thing I am completely lost on is how to wire the video and audio to ports and access them with arduino code.

Questions may not rely on external links for basic information.  "Four wire camera" does not capture the key fact that this is an analog NTSC camera.

No.  Your link is to an analog NTSC camera.   Digitally handling data from this would require a high speed analog to digital converter and some fairly sophisticated cleanup logic.
It is simply not compatible to use this with a small embedded system.
If you really want a camera for a resource constrained embedded system, seek a still camera with a serial or SPI output.
Most video tasks will however be better done on more capable embedded systems falling outside the realm of Arduino-style approaches, and therefore soundly off-topic here.

So if I understand you correctly if I can find a digital camera with a serial output then it would be compatible for the esp8266?

Yes but it's likely a terribly bad idea as a project.

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


text:
Whats wrong with my code?
Basically what i am trying to do is use an ir remote to turn an rgb on/off and have a few preset colors as well as being able to increase/decrease red/green/blue independently. I don't know much about C/C++ so this is really hard to troubleshoot.
#include <IRremote.h>

int rbright;
int gbright;
int bbright;
int before;
int RECV_PIN=12; //data out of IR receiver connects to pin 12
int redPin=11;
int greenPin=10;
int bluePin=9;
int steps=5;
IRrecv irrecv(RECV_PIN);
decode_results results;

//uncomment this line if using a Common Anode LED
#define COMMON_ANODE

void setup()
{
    before=0;
    rbright=80;
    gbright=0;
    bbright=80;
    irrecv.enableIRIn(); // start the receiver
    pinMode(redPin, OUTPUT);
    pinMode(greenPin, OUTPUT);
    pinMode(bluePin, OUTPUT);
}

void loop()
{
    if (irrecv.decode(&results)) {
        if (results.value==B54A3AC5){ //Code to turn the LED ON/OFF
            if(before==0){ // if the LED was turned off, then we turn it on
                digitalWrite(redpin,HIGH);
                digitalWrite(greenpin,HIGH);
                digitalWrite(bluepin,HIGH);
                before=1; //LED is now turned on
            }
            else{
                digitalWrite(redpin,LOW);
                digitalWrite(greenpin,LOW);
                digitalWrite(bluepin,LOW); //if the LED was turned on, then we turn it off
                before=0;
            }
        }
        if (results.value==B54A8A75 && before==1){ //Code to decrease the red
            if(rbright-255/steps<0){
                analogWrite(redpin,rbright);
            }
            else{
                rbright=rbright-255/steps;
                analogWrite(redpin,rbright);
            }
        }
        if (results.value==B54A7A85 && before==1){ //Code to increase the red
            if(rbright+255/steps>255){
                analogWrite(redpin,rbright);
            }
            else{
                rbright=rbright+255/steps;
                analogWrite(redpin,rbright);
            }
        }
        if (results.value==B54AB24D && before==1){ //Code to decrease the green
            if(gbright-255/steps<0){
                analogWrite(greenpin,gbright);
            }
            else{
                gbright=gbright-255/steps;
                analogWrite(greenpin,gbright);
            }
        }
        if (results.value==B54A32CD && before==1){ //Code to increase the green
            if(gbright+255/steps>255){
                analogWrite(greenpin,gbright);
            }
            else{
                gbright=gbright+255/steps;
                analogWrite(greenpin,gbright);
            }
        }
        if (results.value==B54A0AF5 && before==1){ //Code to decrease the blue
            if(bbright-255/steps<0){
                analogWrite(bluepin,bbright);
            }
            else{
                bbright=bbright-255/steps;
                analogWrite(bluepin,bbright);
            }
        }
        if (results.value==B54ACA35 && before==1){ //Code to increase the blue
            if(bbright+255/steps>255){
                analogWrite(bluepin,bbright);
            }
            else{
                bbright=bbright+255/steps;
                analogWrite(bluepin,bbright);
            }
        }
        if (results.value==B54AA956 && before==1){ //Code yellow
            setColor(255, 255, 0);
        }
        if (results.value==B54A2AD5 && before==1){ //Code purple
            setColor(80, 0, 80);
        }
        if (results.value==B54AEA15 && before==1){ //Code aqua
            setColor(0, 255, 255);
        }
        irrecv.resume();
    }

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
    red = 255 - red;
    green = 255 - green;
    blue = 255 - blue;
#endif
    analogWrite(redPin, red);
    analogWrite(greenPin, green);
    analogWrite(bluePin, blue);
}

The errors i get are

rgbcontrolir_ino.ino: In function ‘void loop()’:
  rgbcontrolir_ino.ino:35:24: error: ‘B54A3AC5’ was not declared in this scope
  rgbcontrolir_ino.ino:37:20: error: ‘redpin’ was not declared in this scope
  rgbcontrolir_ino.ino:38:20: error: ‘greenpin’ was not declared in this scope
  rgbcontrolir_ino.ino:39:20: error: ‘bluepin’ was not declared in this scope
  rgbcontrolir_ino.ino:43:20: error: ‘redpin’ was not declared in this scope
  rgbcontrolir_ino.ino:44:20: error: ‘greenpin’ was not declared in this scope
  rgbcontrolir_ino.ino:45:20: error: ‘bluepin’ was not declared in this scope
  rgbcontrolir_ino.ino:48:22: error: ‘B54A8A75’ was not declared in this scope
  rgbcontrolir_ino.ino:50:19: error: ‘redpin’ was not declared in this scope
  rgbcontrolir_ino.ino:54:17: error: ‘redpin’ was not declared in this scope
  rgbcontrolir_ino.ino:56:22: error: ‘B54A7A85’ was not declared in this scope
  rgbcontrolir_ino.ino:58:19: error: ‘redpin’ was not declared in this scope
  rgbcontrolir_ino.ino:62:17: error: ‘redpin’ was not declared in this scope
  rgbcontrolir_ino.ino:64:22: error: ‘B54AB24D’ was not declared in this scope
  rgbcontrolir_ino.ino:66:19: error: ‘greenpin’ was not declared in this scope
  rgbcontrolir_ino.ino:70:17: error: ‘greenpin’ was not declared in this scope
  rgbcontrolir_ino.ino:72:22: error: ‘B54A32CD’ was not declared in this scope
  rgbcontrolir_ino.ino:74:19: error: ‘greenpin’ was not declared in this scope
  rgbcontrolir_ino.ino:78:17: error: ‘greenpin’ was not declared in this scope
  rgbcontrolir_ino.ino:80:22: error: ‘B54A0AF5’ was not declared in this scope
  rgbcontrolir_ino.ino:82:19: error: ‘bluepin’ was not declared in this scope
  rgbcontrolir_ino.ino:86:17: error: ‘bluepin’ was not declared in this scope
  rgbcontrolir_ino.ino:88:22: error: ‘B54ACA35’ was not declared in this scope
  rgbcontrolir_ino.ino:90:19: error: ‘bluepin’ was not declared in this scope
  rgbcontrolir_ino.ino:94:17: error: ‘bluepin’ was not declared in this scope
  rgbcontrolir_ino.ino:96:22: error: ‘B54AA956’ was not declared in this scope
  rgbcontrolir_ino.ino:100:24: error: ‘B54A2AD5’ was not declared in this scope
  rgbcontrolir_ino.ino:104:24: error: ‘B54AEA15’ was not declared in this scope
  rgbcontrolir_ino.ino:112:5: error: a function-definition is not allowed here before ‘{’ token
  rgbcontrolir_ino.ino:121:5: error: expected ‘}’ at end of input

The errors i get are it tells you that those macros are undefined. you need to figure out what they are first before you can fix the errors.

redpin bluepin etc where defined in the beginning right? Or did i miss something.and the other alpha numeric codes refer to the ir codes from the remote i will use.

I used the arduino rgb tutorial and the tutorial from great scott on youtube. he used ir library to control led strips with varying brightness. I downloaded the ir libraries and used the irrecvdemo sketch to find the codes on the remote i plan to use

i feel like it has something to do with the brackets

The errors are self-explanatory. You just have to read them carefully.

‘B54A3AC5’ was not declared in this scope

The compiler doesn't know what "B54A3AC5" means. Nor do I, but I gess
you may mean an hexadecimal 32-bit value. If that's the case, write it
with the prefix "0x", as in 0xb54a3ac5.

‘redpin’ was not declared in this scope

Same thing, it doesn't know what "redpin" is. Oh, wait, you have
declared a variable named redPin. Maybe that is what you meant:
"redPin", with an uppercase "P".

a function-definition is not allowed here before ‘{’ token

You tried to define setColor() within the loop() function. You
cannot define a function within a function in C++ (well, you can have
lambdas, but that's irrelevant to your problem).
Had you tried to indent your code properly (like I did in my edit), the
error would have been obvious: there is no closing brace to match the
opening one at the start of loop().

expected ‘}’ at end of input

Another symptom of the problem above.

Edit: After reading your code, I have a few suggestions for making
it clearer are more efficient:

Declare all the constants with the const keyword, at the beginning
of your program. A common convention is to write them in all caps
with underscores, to distinguish them from variables.
Avoid "magic numbers" within your code (e.g. the IR codes), and use
properly named constants instead.
before is hard to understand, give it a name that makes sense. I
suggest leds_are_on. And make it a bool, because it can only be
either true or false.
One way to avoid deeply nested loops is to use return statements to
get out of loop() as soon as you know you have nothing to do.

With these suggestions, I would start the program like this:
#include <IRremote.h>

// Pinout.
const int RECV_PIN  = 12;  // data out of IR receiver
const int RED_PIN   = 11;
const int GREEN_PIN = 10;
const int BLUE_PIN  = 9;

// Number of steps between black and full brightness.
const int STEPS     = 5;

// IR codes.
const uint32_t CODE_ON_OFF     = 0xb54a3ac5;
const uint32_t CODE_LESS_RED   = 0xb54a8a75;
const uint32_t CODE_MORE_RED   = 0xb54a7a85;
const uint32_t CODE_LESS_GREEN = 0xb54ab24d;
const uint32_t CODE_MORE_GREEN = 0xb54a32cd;
const uint32_t CODE_LESS_BLUE  = 0xb54a0af5;
const uint32_t CODE_MORE_BLUE  = 0xb54aca35;
const uint32_t CODE_YELLOW     = 0xb54aa956;
const uint32_t CODE_PURPLE     = 0xb54a2ad5;
const uint32_t CODE_AQUA       = 0xb54aea15;

bool leds_are_on;
int r_bright;
int g_bright;
int b_bright;
IRrecv irrecv(RECV_PIN);

and the loop() would be like this:
void loop()
{
    decode_results results;
    if (!irrecv.decode(&results))
        return;

    // If the LEDs are OFF, the only valid action is to turn them
    // ON.
    if (!leds_are_on) {
        if (results.value == CODE_ON_OFF) {
            digitalWrite(RED_PIN,   HIGH);
            digitalWrite(GREEN_PIN, HIGH);
            digitalWrite(BLUE_PIN,  HIGH);
            leds_are_on = true;
        }
        irrecv.resume();
        return;
    }

    // The LEDs are ON: all codes are valid.
    switch (results.value) {
        case CODE_ON_OFF:  // turn OFF
            digitalWrite(RED_PIN,   LOW);
            digitalWrite(GREEN_PIN, LOW);
            digitalWrite(BLUE_PIN,  LOW);
            leds_are_on = false;
            break;
        case CODE_LESS_RED:
            r_bright = constrain(r_bright - 255/steps, 0, 255);
            analogWrite(RED_PIN, r_bright);
            break;
        case CODE_MORE_RED:
            r_bright = constrain(r_bright + 255/steps, 0, 255);
            analogWrite(RED_PIN, r_bright);
            break;
        // etc...
    }
    irrecv.resume();
}

Thanks I will try some editing and see what I can come up with. the Arduino ide isn't very friendly for writing code. The only code writing exp i have is with BASH scripting. Usually I use a text editor and save the file with the correct prefix and that helps.

Thanks again! This is a lot of help. After reading your first answer i got the code to compile without errors however the code didnt work as expected. it only turned on/off with full brightness not the purple i was expecting. Is there a good site that will define things for me? specifically I don't know what "case" does

@KeithBybee: Any book on C or C++ will tell you about switch/case/break.

After changing over to the formats you suggested I am getting the following error during compilation. "core.a(main.cpp.o): In function main': /usr/share/arduino/hardware/arduino/cores/arduino/main.cpp:11: undefined reference to setup'
collect2: error: ld returned 1 exit status
"

@KeithBybee: That means that you forgot to write setup().

Well i guess that was obvious. So now i have to versions of this sketch. The one i originally wrote with the errors kinked out and of with case/break instead of if statements. The new one doesnt respond to any buttons being pressed and the old one woth the if statements works until i use any red and then it "freezes". If use the preset purple or the increase/decrease it just stops responding. Other than than it seems think think its on when its off. It will only let me turn individual colors if its off first. I tried putting digital write low for each color in the setup but that did not help

@KeithBybee: I think I had a logic error within the if (!leds_are_on) {} block. Should work better now.

1) You are missing the braces for void loop()
2) Oops !! You have to double check - redpin and redPin etc. Case sensitive !


text:
Problem in upload bootloader into esp32
I have problem with my esp32 Device and asked one question as you can see below:
How to understand the ESP32 is working (Error: Arduino unknown board ...)
As it is not fixed, so I am thinking to upload the bootloader codes on the ESp32.
SO I have tried the ArduinoISP example codes and tried to  use the bootloader icon on Arduino, but it doesn't work,
and I get below error:
java.lang.NullPointerException
    at cc.arduino.packages.uploaders.SerialUploader.burnBootloader(SerialUploader.java:329)
    at processing.app.Editor.lambda$handleBurnBootloader$61(Editor.java:2379)
    at java.base/java.lang.Thread.run(Thread.java:829)
Error while burning bootloader.

Also, the whole process is show below:

So I have asked here for some comments or answers.
Thanks.

esp32 has a fixed bootloader in read only memory. it is not replaceable

ArduinoISP sketch is a programmer only for classic ATmega MCU boards

in valid case you would have to select the programmer in Tools menu before using Burn Bootloader. (There are no options in your Programmer menu, because no programmers are defined for esp32 boards package)


text:
Pass a char array to a function that uses File as parameter
I am in serious need for help here. I have a rather small function that get's the number of files from within a given directory. Now, the directory name (that is the path) is stored in a char array within my main loop.
My problem is, I have no idea how to pass this char array to my function.
This is my code (it's of course just a subset but it's the part that is obviously wrong) and you can also see the complete program at the end:
In the setup() routine I define my current working directory:
char plrCurrentFolder[9];

In the main loop I want to get the number of files of a given directory (in the final program this directory name will come from an NFC tag):
String temp = "findorie";
temp.toCharArray(plrCurrentFolder, 9);
unsigned int numberOfFiles = countFiles(plrCurrentFolder);

This is the function to return the number of files:
unsigned int countFiles(File dir){
  unsigned int counter = 0;
  while (true){
    File entry = dir.openNextFile();
    if (!entry){
      // no more files
      break;
    }
    counter++;
    entry.close();
  }
  dir.close();
  return counter;
}

To be honest I have two issues with this. First, I don't really like to create a temp String variable to create the char array here as I would rather stick with the char array in itself to safe on memory and maybe this would also aid in performance (although I'm not sure about that).
Second, The way this whole thing is structured right now, it simply doesn't work. When building, the compiler correctly complains:
exit status 1
could not convert '(char*)(& plrCurrentFolder)' from 'char*' to 'SDLib::File'

Can anyone help me out and give me a code snippet how to make this work???
Kind regards to all,
Christian
--- below you may find the complete code as of now ---
/*
 * Fairytale Main program
 *
 * This programm will read an nfc tag. It will check for a directory name and optional a filename
 * and start playing this on the music maker shield.
 *
 * Restrictions:
 * 1. All filenames mus be in the format  trackXXX.mp3  - where XXX is a numbering from 001 to 999
 * 2. All directory names must be exactly 8 chars long
 *
 */

// make sure to change this to 0 before uploading in production as it turns on lots and lots of serial messages
#define DEBUG 1
// we only show light effects, in case this is set to 1
#define LIGHTEFFECTS 0
// we only use the nfc reader if this is set to 1
#define NFCREADER 0

//
// setup SPI, MP3 and SD libraries
//
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>
// These are the pins used for the music maker shield
#define SHIELD_RESET  -1     // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)
#define CLK 13 // SPI Clock, shared with SD card
#define MISO 12 // Input data, from VS1053/SD card
#define MOSI 11 // Output data, to VS1053/SD card

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

Adafruit_VS1053_FilePlayer musicPlayer =
  // create shield-example object!
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

//
// setup NFC Adapter
//
#ifdef NFCREADER
/*
  #include <PN532_SPI.h>
  #include <PN532.h>
  #include <NfcAdapter.h>

  #define PN532_SCK (13) //changed from pin 2
  #define PN532_MISO (12) //changed from pin 5
  #define PN532_MOSI (11) //changed from pin 3
  #define PN532_SS (10) //changed from 4

  PN532_SPI pn532spi(SPI, PN532_SS);
  NfcAdapter nfc = NfcAdapter(pn532spi);
*/
#endif

// these variables are used for the light effects
int lightValue1, lightValue2, lightValue3;
const int redPin = 7;
const int greenPin = 8;
const int bluePin = 9;

// these are timing counters for the light effects
long time=0;
int periode = 20000;
int displace = 500;

// uptime counters
unsigned int runCounter = 0;
unsigned long startUpTime = 0;
const unsigned long maxUpTime = 120000; // 1800000L;  // 30 Minutes

// these are variables for the nfc card
boolean cardScanned = false;    // did we already scan the card?? using this to suppress reading in the card data while it is on the reader
char cardId[16];                // the uid of the card as read in through the nfc reader

// mp3 player variables
boolean plrIsPlaying = false;                         // is the mp3 player already playing?
char plrCurrentFile[13];                              // which track is the player playing?
char plrNextFile[13];                                 // which track is the player playing?
char plrPrevFile[13];                                 // which track is the player playing?
char plrCurrentFolder[9];                             // which directory is the player playing?
uint8_t plrCurrentPosition = 0;                       // on which position in seconds are we in the current track?
char currentTrackFileName[] = "/system/current.txt";  // a file we might use to store the last played track

// volume control variables for the analog poti
int volumePotPin = A0;        // the analog input pin that we use for the potentiometer
int sensorDrift = 7;          // difference to last received sensor value that must be exceeded to activate a change in the volume
int compareValue = 0;         // just a convenience variable to make comparison easier
int sensorValue = 0;          // read the value from the potentiometer
int lastSensorValue = 0;      // keeps the last read sensor value
uint8_t soundVolume = 0;      // the sound volume is derived via a map function from the sensor value

// other button settings
int btnLinePin = A1;         // pin on which the button line (4 buttons) is connected
int btnVal = 0;

// these are the prototypes for the nfc card reader
void getNfcCardData();

// these are the prototypes for the mp3 player controller
uint8_t getVolume(void);        // function that returns the volume setting based on the analog read
char plrNext(void);             // play next file in album
char plrPrev(void);             // play previous file in album
void plrPlayTrack(char, char);  // play a single track
void setupSound(void);          // initializes the sound system and plays the startup sound

// these are the prototypes to work on files
void printDirectory(File, int);   // print out the content of specified directory on serial console
unsigned int countFiles(File);    // return the number of files in a directory passed as a File descriptor
//unsigned int countFiles(char[]);    // return the number of files in a directory passed as a File descriptor

// these are the prototypes for the light effects
void fader(void);
void startuplight(void);
void highlight(int);
void flash(int);
void pulse(int);

void setup() {
  #ifdef DEBUG
    Serial.begin(115200);
  #endif

  plrCurrentFile[0] = 0; // we initialize the fiirst element of the array to 0 to later check if a current file was given.

  // initialise the music player
  if (! musicPlayer.begin()) { // initialise the music player
    #ifdef DEBUG
      Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
    #endif
    while (1);
  }
  #ifdef DEBUG
    Serial.println(F("Music Maker Shield VS1053 found"));
  #endif

  //musicPlayer.sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working

  if (!SD.begin(CARDCS)) {
    #ifdef DEBUG
      Serial.println(F("failed to detect the SD-Card"));
    #endif
    while (1);  // don't do anything more
  }
  #ifdef DEBUG
    Serial.println("SD found and operational");
  #endif

  // set the buttons as input
  pinMode(volumePotPin, INPUT);
  pinMode(btnLinePin, INPUT);

  // setup music maker shield and start playing startup file
  setupSound();

  #ifdef DEBUG
    // list files
    printDirectory(SD.open("/"), 0);
  #endif

/*
  // now as the last thing, start the nfc reader
  #ifdef DEBUG
    Serial.print("initializing NFC TAG reader ... ");
  #endif
  nfc.begin();
  delay(1000); // wait some time for
*/

  // check our current time, so we know when to stop
  startUpTime = millis();
  #ifdef DEBUG
    Serial.println("we are up and running and ready to play audio");
  #endif
}

//
//      LL       OOOOOO    OOOOOO   PPPPPPP
//      LL      OO    OO  OO    OO  PP    PP
//      LL      OO    OO  OO    OO  PP    PP
//      LL      OO    OO  OO    OO  PPPPPP
//      LLLLLL   OOOOOO    OOOOOO   PP
void loop() {
  #ifdef LIGHTEFFECTS
    // turn off all the lights. we only want to have fading lights, while the playr is active
    //analogWrite(redPin, 0);
    //analogWrite(greenPin, 0);
    //analogWrite(bluePin, 0);
  #endif

  // NFC Tag reader functions
  // now we only do this, when an nfc tag is present
/*
  if (nfc.tagPresent()){
    Serial.println("NFC tag Found!\n");
    NfcTag tag = nfc.read();
    Serial.print("Tag Type: ");
    Serial.println(tag.getTagType());
    Serial.print("UID: ");
    Serial.println(tag.getUidString());

    getNfcCardData();
*/

    String temp = "findorie";
    temp.toCharArray(plrCurrentFolder, 9);

    // now let's get the number of files in the album directory
    //unsigned int numberOfFiles = 0;
    unsigned int numberOfFiles = countFiles(plrCurrentFolder);
    #ifdef DEBUG
      Serial.print("Directory ");Serial.print(plrCurrentFolder);Serial.print(" contains ");Serial.print(numberOfFiles);Serial.println(" files");
    #endif

    // if we did not get the current file from the tag, we are hardcoding it to track001.mp3
    if ((plrCurrentFile[0] == 0)) {
      temp = "track001.mp3";
      temp.toCharArray(plrCurrentFile, 13);
    }

    #ifdef DEBUG
      Serial.print("currentFolder holds: ");Serial.print(plrCurrentFolder);Serial.print(" / currentFile contains: ");Serial.print(plrCurrentFile);
    #endif

    temp = "/";
    temp.concat(plrCurrentFolder);
    temp.concat("/");
    temp.concat(plrCurrentFile);
    char filename[temp.length() + 1];
    temp.toCharArray(filename, sizeof(filename));
    Serial.print(" / filename contains: ");Serial.println(filename);

    if (SD.exists(filename)) {
      Serial.print(filename);Serial.println(" exists.");

      // mp3 player functions playback
      // Start playing a file, then we can do stuff while waiting for it to finish
      if (! musicPlayer.startPlayingFile(filename)) {
        #ifdef DEBUG
          Serial.print("Could not open file ");Serial.println(filename);
        #endif
        while (1);
      }
      #ifdef DEBUG
        Serial.print(F("Start playing "));Serial.println(filename);
      #endif

      while (musicPlayer.playingMusic) {
        // file is now playing in the 'background' so now's a good time
        // to do something else like handling LEDs or buttons :)

        // play some nice light effects, if wanted
        #ifdef LIGHTEFFECTS
          //fader();
        #endif

        // volume control functions
        // read the input on analog pin 0 and check if we have a change in volume.
        sensorValue = analogRead(volumePotPin);
        if (lastSensorValue > sensorValue) {compareValue = lastSensorValue - sensorValue;} else {compareValue = sensorValue - lastSensorValue;}
        // If we have a high enough difference in the sensor reading, calculate it so we may set it on the player
        if (compareValue > sensorDrift){
          #ifdef DEBUG
            Serial.print("changing volume: ");
          #endif
          soundVolume = getVolume();
          musicPlayer.setVolume(soundVolume,soundVolume);
        }
      }
      #ifdef DEBUG
        Serial.println("Done playing ");Serial.println(filename);
      #endif
      #ifdef LIGHTEFFECTS
        //startuplight();
      #endif
    } else {
      Serial.print(filename);Serial.println(" does not exist.");
    } // end of file does not exist

  //} // end of tag found
} // end of loop

//
//        NN    NN  FFFFFF   CCCCCC
//        NNNN  NN  FF      CC
//        NN  N NN  FFFF    CC
//        NN  NNNN  FF      CC
//        NN    NN  FF       CCCCCC
//  BELOW THIS LINE THE NFC CONTROL IS DEFINED
//
void getNfcCardData(){
/*
  NfcTag tag = nfc.read();
  boolean usableContent = false;
  if (tag.hasNdefMessage()){
    NdefMessage message = tag.getNdefMessage();

    // If you have more than 1 Message then it wil cycle through them
    int recordCount = message.getRecordCount();
    for (int i = 0; i < recordCount; i++) {
      NdefRecord record = message.getRecord(i);

      int payloadLength = record.getPayloadLength();
      byte payload[payloadLength];
      record.getPayload(payload);

      String payloadAsString = ""; // Processes the message as a string vs as a HEX value
      for (int c = 0; c < payloadLength; c++) {
        payloadAsString += (char)payload[c];
      }

      String cleanString = payloadAsString;
      cleanString.remove(0,3);
      #ifdef DEBUG
        Serial.print("content element "); Serial.print(i); Serial.print(": "); Serial.println(cleanString);
      #endif

      // now populate the vars for the player
      int spacePosition = cleanString.indexOf(':');
      if (cleanString.charAt(spacePosition - 1) == 'A') {
        String contentString = cleanString.substring(3);
        #ifdef DEBUG
          Serial.print("Album info: ");Serial.println(contentString);
        #endif
      }
      if (cleanString.charAt(spacePosition - 1) == 'D') {
        usableContent = true;
        String contentString = cleanString.substring(3);
        plrCurrentFolder = contentString;
        #ifdef DEBUG
          Serial.print("Directory: ");Serial.println(contentString);
        #endif
      }
      if (cleanString.charAt(spacePosition - 1) == 'T') {
        String contentString = cleanString.substring(3);
        plrCurrentFile = contentString;
        #ifdef DEBUG
          Serial.print("Track: ");Serial.println(contentString);
        #endif
      }
      if (cleanString.charAt(spacePosition - 1) == 'P') {
        String contentString = cleanString.substring(3);
        plrCurrentPosition = contentString.toInt();
        #ifdef DEBUG
          Serial.print("Position: ");Serial.println(contentString);
        #endif
      }

      String uid = record.getId();
      if (uid != "") {
        #ifdef DEBUG
          Serial.print("  ID: ");
          Serial.println(uid);
        #endif
      }
    }
    if (!usableContent){
      #ifdef DEBUG
        Serial.println("THIS CARD DOES NOT HAVE THE NECESSARY MESSAGES FOR THE MP3 PLAYER");
      #endif
    }
  } else { // does the card have NDEF messages?
    #ifdef DEBUG
      Serial.println("THIS CARD DOES NOT HAVE MESSAGES AT ALL - NOT USABLE FOR THE MP3 PLAYER");
    #endif
  }
*/
}

//
//        MM      MM   PPPPPP   33333
//        MMMM  MMMM  PP    PP      33
//        MM  MM  MM  PP    PP    3333
//        MM      MM  PPPPPP        33
//        MM      MM  PP        33333
//  BELOW THIS LINE THE MP3 PLAYER CONTROL IS DEFINED
//
uint8_t getVolume(){
  soundVolume = map(sensorValue, 0, 1023, 0, 100); // map the sensor value to a sound volume

  #ifdef DEBUG
    Serial.print("last sensor value (if any) was ");Serial.print(lastSensorValue);Serial.print(" / new sensor value is ");Serial.print(sensorValue);Serial.print(" which is a volume of ");Serial.println(soundVolume);
  #endif
  lastSensorValue = sensorValue;
  return (soundVolume);
}

void plrPlayTrack(char dir, char file) {
  String temp = "/";
  temp.concat(dir);
  temp.concat("/");
  temp.concat(file);
  char myFile[temp.length() + 1];
  temp.toCharArray(myFile, sizeof(myFile));

  // mp3 player functions playback
  // Start playing a file, then we can do stuff while waiting for it to finish
  if (! musicPlayer.startPlayingFile(myFile)) {
    #ifdef DEBUG
      Serial.print("Could not open file ");Serial.println(myFile);
    #endif
    while (1);
  }
  #ifdef DEBUG
    Serial.print(F("Start playing "));Serial.println(myFile);
  #endif

  while (musicPlayer.playingMusic) {
    // file is now playing in the 'background' so now's a good time
    // to do something else like handling LEDs or buttons :)
    #ifdef DEBUG
      Serial.print(".");
    #endif
    #ifdef LIGHTEFFECTS
      //fader();
    #endif

  }
  #ifdef DEBUG
    Serial.println("Done playing ");Serial.println(myFile);
  #endif
}

char plrNext(void){
  char track[12] = "track003.mp3";
  #ifdef DEBUG
    Serial.println("plrNext toggled");
  #endif
  #ifdef LIGHTEFFECTS
    //pulse(bluePin);
  #endif

  return track;
}
char plrPrev(void){
  char track[12] = "track001.mp3";
  #ifdef DEBUG
    Serial.println("plrPrevious toggled");
  #endif
  #ifdef LIGHTEFFECTS
    //pulse(greenPin);
  #endif

  return track;
}

void setupSound(){
  // This option uses a pin interrupt. No timers required! But DREQ
  // must be on an interrupt pin. For Uno/Duemilanove/Diecimilla
  // that's Digital #2 or #3
  // See http://arduino.cc/en/Reference/attachInterrupt for other pins
  // *** This method is preferred
  if (! musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT)) {
    #ifdef DEBUG
      Serial.println(F("DREQ pin is not an interrupt pin"));
    #endif
    while (1);
  }

  // Start playing a file, then we can do stuff while waiting for it to finish
  if (! musicPlayer.startPlayingFile("hello.mp3")) {
    #ifdef DEBUG
      Serial.println("Could not open file hello.mp3");
    #endif
  } else {
    #ifdef DEBUG
      Serial.print("playing welcome file hello.mp3 ");
    #endif
  }

  // now we play the welcome sound
  startUpTime = millis();
  while (musicPlayer.playingMusic) {
    if (millis() - startUpTime > 500) {
      #ifdef DEBUG
        Serial.print(".");
      #endif
      startUpTime = millis();
    }
    // file is now playing in the 'background' so now's a good time
    // to do something else like handling LEDs or buttons :)
    #ifdef LIGHTEFFECTS
      //startuplight();
    #endif
  }
  #ifdef DEBUG
    Serial.println(" done");
  #endif
  getVolume();
  musicPlayer.setVolume(soundVolume,soundVolume);
}

//
//        FFFFFF  II  LL      EEEEEE
//        FF      II  LL      EE
//        FFFF    II  LL      EEEE
//        FF      II  LL      EE
//        FF      II  LLLLLL  EEEEEE
// BELOW THIS LINE THE FILE HELPER FUNCTIONS CAN BE FOUND
//
// counts the number of files in directory
//unsigned int countFiles(char dir[]){

unsigned int countFiles(File dir){
  unsigned int counter = 0;
  while (true){
    File entry = dir.openNextFile();
    if (!entry){
      // no more files
      break;
    }
    counter++;
    entry.close();
  }
  dir.close();
  return counter;
}

// store last played track
void rememberCurrentTrack(){

}

// read last played track
void getLastPlayedTrack(){

}

// File listing helper
void printDirectory(File dir, int numTabs) {
   while(true) {
     File entry =  dir.openNextFile();
     if (! entry) {
       // no more files
       //Serial.println("**nomorefiles**");
       break;
     }
     for (uint8_t i=0; i<numTabs; i++) {
       Serial.print('\t');
     }
     Serial.print(entry.name());
     if (entry.isDirectory()) {
       Serial.println("/");
       printDirectory(entry, numTabs+1);
     } else {
       // files have sizes, directories do not
       Serial.print("\t\t");
       Serial.println(entry.size(), DEC);
     }
     entry.close();
   }
}

//
//        LL      EEEEEE  DDDDDD
//        LL      EE      DD    DD
//        LL      EEEE    DD    DD
//        LL      EE      DD    DD
//        LLLLLL  EEEEEE  DDDDDD
//  BELOW THIS LINE THE LIGHT EFFECTS ARE DEFINED
//
// fading organically
void fader(){
  time = millis();
  lightValue1 = 128+127*cos(2*PI/periode*time);
  lightValue2 = 128+127*cos(2*PI/periode*(displace-time));
  lightValue3 = 128+127*cos(2*PI/periode*(2*displace-time));
  analogWrite(redPin, lightValue1);           // sets the value (range from 0 to 255)
  analogWrite(greenPin, lightValue2);        // sets the value (range from 0 to 255)
  analogWrite(bluePin, lightValue3);         // sets the value (range from 0 to 255)
}
// illuminate the 3 led with some fancy lightning during startup
void startuplight(){
  for (int i = 0; i<150; i++) {
    analogWrite(redPin, i);
    analogWrite(greenPin, i);
    analogWrite(bluePin, i);
    delay(10);
  }
  for (int i = 150; i>0; i--) {
    analogWrite(redPin, i);
    analogWrite(greenPin, i);
    analogWrite(bluePin, i);
    delay(10);
  }
  analogWrite(redPin, 0);
  analogWrite(greenPin, 0);
  analogWrite(bluePin, 0);
}
//turn on the desired pin for 5000 milliseconds
void highlight(int pin){
  time = millis();
  while (millis()<time+5000){
    analogWrite(pin, 255);
  }
  analogWrite(pin, 0);
}
//turn on the desired pin for 5000 milliseconds
void flash(int pin){
  time = millis();
  while (millis()<time+1000){
    analogWrite(pin, 255);
  }
  analogWrite(pin, 0);
}
//turn on the desired pin for 5000 milliseconds
void pulse(int pin){
  for (int i=0;i<3;i++){
    time = millis();
    while (millis()<time+2500){
      analogWrite(pin, 255);
    }
    analogWrite(pin, 0);
  }
}

You need to open the file then pass that file. Or have your function accept a char array and do the file opening itself. Either way, at some point, you will need to open the file.

Actually that function does not open a file at all. It simply counts the number of files in a directory. But you have a point nonetheless. Maybe best would be to restructure the function and find a way to count files in a directory without the need to pass a File descriptor to the function. Would you have, by any chance an idea on how to count files in a directory where the directory name is past as a char array???

As far as filesystems are concerned (in general) a directory is just another file. You just use special functions to read the contents of it. To do any operation on a directory you need to open it. Like a file.

Thank you so very much. As posted below, I was really blindfolded here. Thanks for your help

OMG. I'm so sorry for posting such a stupid question. And I'm also sorry for not seeing the obvious even after Majenko pointed me to it.
Of course I need to call the function like this:
numberOfFiles = countFiles(SD.open(plrCurrentFolder));

That way, the directory get's opened and my function can operate on it.
I see I still have to learn a lot :-)


text:
sizeof() on custom library constructor returns wrong result
I made a custom library (let's call it DigitalOutput.h) to learn a bit about librairies and to simplify my work. Here is the basic constructor in the .h file:
DigitalOutput(uint8_t pin);

Here is the code in the .cpp file :
DigitalOutput::DigitalOutput(uint8_t pin)
{
    _pin    = pin;
    _status = LOW;
    pinMode(pin, OUTPUT);
}

So very simple stuff. Now, in my program, I call the function the usual way:
DigitalOutput LED(7); // pin #7 will be configured
                      // as an output pin to control the LED

Now the issue comes when I create an array and then use the sizeof() function.
Here is the code from my program (using an Arduino Mega):
DigitalOutput   LED_array[] = {22,23,24,25,26,27,28,29,
                               30,31,32,33,34,35,36,37};

So, the array contains 16 elements. But when I do for instance...
#define         LED_NUMBER    sizeof(LED_array)
//...
void setup(){
    //...
    Serial.println(sizeof(LED_array));
    Serial.println(LE_NUMBER);
}

...I get 160 as a result in both cases instead of 16...
So I end up doing a weird #define LED_NUMBER sizeof(LED_array) / 10 in order to get the proper result which is then used throughout the program. Any idea of why this isn't working right?

Please give a full working example that we can test ourself. Then we will tell you why a single object uses 10 bytes. Despite the compiler optimizations, I think that when the same object is declared more than once, that the size will be the same for every object.

As you already have the answer, I'll just mention a macro to address this very issue, #define countof(a) (sizeof(a)/sizeof(a[0])), where countof(LED_Array) evaluates to the number of members in the array, not to its memory size. I keep this definition in an 'h' file on my local system (named, oddly enough, local.h!) with other simple-but-useful tools I need on occasion.

It is working perfectly correctly.
sizeof doesn't return the number of elements in an array, it returns the number of bytes the array takes up. Since each entry in your array is an instance of your DigitalOutput class, the size is the number of elements multiplied by the size of the class - in this case 10 bytes.
To get the number of elements you must divide the number of bytes by the size of one element:
int numEles = sizeof(LED_array) / sizeof(DigitalOutput);

or
int numEles = sizeof(LED_array) / sizeof(LED_array[0]);

Well thanks to you all. This was the problem, I did not understand sizeof() well enough and read its definition in the Arduino documentations without really understanding what it was doing. I went back to it with your comments and now I'm getting it. Thanks for your help guys.

Note that the first is more robust (using sizeof(DigitalOutput)), in case you ever make LED_array dynamic and it has zero elements.

If you make the array dynamic you won't be using sizeof. That will just return the size of the pointer (2 or 4 depending on architecture) regardless of the size of the array. sizeof is a compile-time command not a library function.

Thanks Michel, I actually went with sizeof(DigitalOutput)but without foreseeing the issues you were mentioning. Good to know! Thanks Majenko, that's some good input I actually totally assumed it was a function.

Most people do. The C++ reference actually lists it as an operator - that is, in the same class as +, /, etc.

Indeed. By the way, does it mean I shouldn't use sizeof during runtime and only use it for compile-time operations? Will it cause unexpected errors? Or, as it is listed as an operator, will it be fine?

It will be replaced at compile time with the size of whatever you specify. Since sizes of static things never change at runtime what you ask makes no sense.

@Majenko ... I meant more like the (amount of bytes used by the dynamic array) / sizeof(DigitalOutput ) ... returning 2 or 4 does not really give helpful information :-)

You are checking the size of the object (DigitalOutput).
This object contains:

_pin
_status

And this probably results in 10 bytes per object, times 16 objects = 160 bytes.
So you are not creating an (unsigned byte) array which is 16 bytes.


text:
#define VS local static const char
Could someone give me a hint regarding what would be the best practice to save memory: should I #define strings or use local static const char arrays?
Code example, option #1:
#define         LCD_LIMIT   "Number of hours"
...
setup(){
    DisplayData(LCD_LIMIT, actual_Data);
}
...
void DisplayData(const char *theme, String data){
}

Code example, option #2:
setup(){
    DisplayData(actual_Data);
}
...
void DisplayData(String data){
    static const char theme[] = "Number of hours";
}

Cheers

Check out PROGMEM to put data in flash mem.

Thanks @JohnnyMopp! Does it mean both my two options are similar in terms of memory footprints and digging PROGMEM is much more interesting?

The #define will be substituted in at compile time. So as far as memory usage goes
#define MYSTRING "hello world"
DisplayData(MYSTRING);

and
DisplayData("hello world");

are completely identical.
but
static const char theme[] = "hello world";
DisplayData(theme);

Will store the text in memory and then call DisplayData with a pointer to that memory location. This will require one memory pointers worth of memory extra (unless that is the compiler is being smart that day and realizes it can substitute in the string and save a few bytes).
However if you are using the same string twice or more then things are different.
The static const will only include the string once and then point to it each time, each reference to the string adds only a couple of bytes to the code size.
If you #define the string then every time it is referenced the whole string is inserted into the code at a cost of n+1 bytes where n is the string length.

Thanks for this detailed reply. So does this also apply to static const char arrays declared only locally (and therefore only called when the function itself is called?

A static variable declared within a function is basically a global variable that the compiler won't let other parts of the code access. It exists at all times, not just when the function is called and so takes a constant amount of memory. If it was local but not static then it would only use RAM when in the function but you would have the performance hit of copying the string from flash to RAM every time the function was called.

As Michel indicated in his answer the F() macro will store the string in flash and not copy it to RAM which will use less memory but may give a tiny performance hit.

Thanks @Andrew for the clear explanation, I really got it.

I think they both are similar with respect to memory stored in the heap.
However, since you pass one extra pointer, it cost 2 of 4 bytes extra on the stack (temporary space).
To save more memory use the F() function to store it in FLASH (32 KB on Arduino Uno) instead of the heap (only 2 KB). By using
static const char theme[] = F("Number of hours");


text:
Switch between ntc resistor sensors time based for other device
We have a heating system that uses an ntc resistor to measure water temperature. I would like to replace that ntc resistor by a fixed one (low enough to disable heating) temporary on a 5 minute schedule, or any other.
It's to prevent the warm water using up all the heat and not leaving any for the central heating of the building. We got fooled by the contractor and a proper upgrade would now cost several thousands, so we just want to trick the system. ;p
The arduino is not supposed to measure anything, just to connect one of the two resistors to the heating system.
Is an arduino the right choice for that? If yes, which model? What extra elements would I need? Transistors? Relays? They shouldn't have too much own resistance to not influence the measuring of the heating system when the NTC is connected.
Just a simple connection of the extra resistor would work too because the resulting resistance would be lower and still indicate "water is hot enough" to the heating system.
Any help is welcome, even if it is not arduino based.

It sounds like what you want is a small SPDT relay (maybe a reed relay).

simulate this circuit – Schematic created using CircuitLab
Turn on the GPIO, the MOSFET (or NPN BJT if you choose - increase R1 if you do) turns on, which energises the relay. The relay then switches between the NTC and the resistor being connected into the circuit.

For the benefit of the OP, I suggest you clarify what M1 is - and suggested part numbers or specs.

@NickGammon That portion of the circuit is the standard relay switching circuit. There are a brazillian tutorials and examples citing parts and specs online. Why replicate it needlessly?

cool, think that is what i need! would you use the arduino or is it overkill in that simple scenario? 5 mins on, 5 mins off, repeat ..

Arduino is a good choice.


text:
My outputs are not outputting any current at only two of my pinmodes but work fine on the others
My pinMode output 5 and 6 don't works with this code but will work when they are stand alone.
What is causing the Arduino to not output anything from these outputs within my code?
#include <SoftwareSerial.h>                    // use the software serial library
SoftwareSerial mySerial(3,4); // receive data at pin 3; transmit data at pin 2
int setpoint;
float val;
int roomtemp;
int UCL;
int LCL;

float salinity;
void setup()
{
    // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(5,OUTPUT);
    pinMode(6,OUTPUT);
    pinMode(3,OUTPUT);
    pinMode(2, OUTPUT);
    roomtemp=25;
    setpoint=7.0291*roomtemp+334.73;
    UCL=setpoint+6.12;
    LCL=setpoint-6.12;
    Serial.print("Setpoint =");
    Serial.print(setpoint);
    Serial.print("Degrees Celsius");
    Serial.print("UCL =");
    Serial.print(UCL);
    Serial.print("Degrees Celsius");
    Serial.print("LCL =");
    Serial.print(LCL);
    Serial.print("Degrees Celsius");
    mySerial.begin(9600);
    delay(500);           // set data rate to 9600 baud; wait for bootup
    mySerial.write(254);
    mySerial.write(128);
    mySerial.write(254);
    mySerial.write(1);    // clear screen & move to top left position
    mySerial.write(254);
    mySerial.write(132);
    mySerial.print("LCL");
    mySerial.write(254);
    mySerial.write(139);
    mySerial.print("SP");
    mySerial.write(254);
    mySerial.write(144);
    mySerial.print("UCL");
    mySerial.write(254);
    mySerial.write(192);
    mySerial.print("S:");
    mySerial.write(254);
    mySerial.write(195);
    mySerial.print(0.072,3);
    mySerial.write(254);
    mySerial.write(201);
    mySerial.print(0.100,3);
    mySerial.write(254);
    mySerial.write(207);
    mySerial.print(0.108,3);
    mySerial.write(254);
    mySerial.write(148);
    mySerial.print("T:");
    mySerial.write(254);
    mySerial.write(152);
    mySerial.print("24.1");
    mySerial.write(254);
    mySerial.write(158);
    mySerial.print("25.0");
    mySerial.write(254);
    mySerial.write(164);
    mySerial.print("25.9");
    mySerial.write(254);
    mySerial.write(212);
    mySerial.write(254);
    mySerial.write(212);
    mySerial.print("S=");
    mySerial.write(254);
    mySerial.write(220);
    mySerial.print("T=");
}

void loop()
{
    Serial.println();
    int val=analogRead(5);
    Serial.print("Analog Value =");
    Serial.print(val);
    Serial.print("Temperature =");
    Serial.println((0.14227*val)-47.621);

    if(val<LCL) { digitalWrite(3,HIGH); }
    else if(val>UCL) { digitalWrite(3,LOW); }

    mySerial.write(254);
    mySerial.write(227);

    if(val<LCL) { mySerial.write("H= ON"); }

    mySerial.write(254);
    mySerial.write(227);

    if(val>UCL) { mySerial.write("H=OFF"); }

    digitalWrite(2, HIGH);
    delay(100);
    int analogS=analogRead(4);
    digitalWrite(2, LOW);
    Serial.println(analogS);
    delay(1000);
    salinity = 2.0955*pow(10,-19)*pow(analogS,5.8106)*100.000;
    Serial.print("Salinity =");
    Serial.println(salinity);
    mySerial.write(254);
    mySerial.write(214);
    mySerial.print(salinity);
    mySerial.write(254);
    mySerial.write(222);
    mySerial.print((0.14227*val)-47.621,1);
    Serial.println("analog value");
    Serial.print(analogRead(4));
    float target= (salinity-(salinity-.1)*.60);
    float numer=((((target)*.08585-(salinity)*.08585)/(.1-(.1*.15+salinity*.85)))*60.0);
    float denom= ((.1));
    float valve= ((numer/denom)/10.00);

    if(.096<salinity>.104) {
        delay(5000);
    }

    if(salinity>.104) {
        Serial.print("Entering DIon Function");
        digitalWrite(6,HIGH);
        delay(valve);
        digitalWrite(6,LOW);
        delay(5000);
    }

    if(salinity<.096) {
        Serial.print("Entering Saltyon Function");
        digitalWrite(5,HIGH);
        delay(valve);
        digitalWrite(5,LOW);
        delay(5000);
    }

    Serial.print("time");
    Serial.println(valve);
}

So you are sure that the code parts in which a digitalWrite with 5 or 6 pin is executed, but you don't see the pin values chaning? Can you print out the value of valve, too, or put more delay after setting it HIGH?

And what is printed out to serial monitor?

@Juraj analogRead(5) selects the same ADC pin as analogRead(A5), which is the same as analogRead(19). (Even analogRead(13) will work). As it will subtract 14 if the value is bigger or equal to 14, and only use the lower 3 bits.

@Gerben, yes I remembered and deleted the comment (somehow wrong, because it is still there :-) )

I think the problem is not in the output pin (which you say works elsewhere) but in your calculations. I made a Minimal, Complete, and Verifiable example of the part of the code that does the calculations, testing every possible reading you might have got from analogRead(4) (mainly because I found the calculations code rather obscure). Here it is:
float salinity;
void setup()
  {
  Serial.begin(9600);
  }

void loop()
  {
  for (int analogS=0; analogS < 1024; analogS++)
    {
    Serial.print ("analogS = ");
    Serial.print (analogS);
    salinity = 2.0955*pow(10,-19)*pow(analogS,5.8106)*100.000;
    Serial.print (", Salinity = ");
    Serial.print (salinity);
    float target= (salinity-(salinity-.1)*.60);
    float numer=((((target)*.08585-(salinity)*.08585)/(.1-(.1*.15+salinity*.85)))*60.0);
    float denom= ((.1));
    float valve= ((numer/denom)/10.00);
    Serial.print(",  valve = ");
    Serial.println(valve);
    }
   Serial.flush ();
   exit (1);
  }

Testing that reveals:
analogS = 0, Salinity = 0.00,  valve = 3.64
analogS = 1, Salinity = 0.00,  valve = 3.64
analogS = 2, Salinity = 0.00,  valve = 3.64
analogS = 3, Salinity = 0.00,  valve = 3.64
... some lines omitted ...
analogS = 1016, Salinity = 6.21,  valve = 3.64
analogS = 1017, Salinity = 6.25,  valve = 3.64
analogS = 1018, Salinity = 6.28,  valve = 3.64
analogS = 1019, Salinity = 6.32,  valve = 3.64
analogS = 1020, Salinity = 6.35,  valve = 3.64
analogS = 1021, Salinity = 6.39,  valve = 3.64
analogS = 1022, Salinity = 6.43,  valve = 3.64
analogS = 1023, Salinity = 6.46,  valve = 3.64

As you can see, valve is always 3.64, so you will be doing this:
    digitalWrite(6,HIGH);
    delay(3);
    digitalWrite(6,LOW);

In other words, port 6 will be HIGH for 3 milliseconds, probably too short a time for you to notice. Ditto for port 5.

Also this doesn't do what I suspect you think it does:
if(.096<salinity>.104) {
    delay(5000);
}

That will evaluate .096 < salinity to be 0 or 1. Then it will evaluate:
0 > 0.104
1 > 0.104

This is not what you are intending, I think. Try:
if(salinity < .096 || salinity > .104) {
    delay(5000);
}

If that is what you mean, I can't be sure - maybe you mean the opposite:
if(salinity > .096 && salinity < .104) {
    delay(5000);
}

If you write things out clearly, without trying to do shortcuts, it will be much more obvious what the test really is.

I think Cobol used to work like that, however that is pretty old. :)


text:
How to externally power HC-05 module with Arduino Pro Mini?
guys, I am new to arduino. I am trying to power my HC-05 (5v with regulator to 3.3v) from Arduino Pro Mini 3.3v but I can't get it to power on.
There is a problem: The site I bought HC-05 from says that it needs 3.3-6 volts to power on but the back of HC-05 shows only 5v pin. To confirm that it runs only on 5v I need to connect it to external 5v supply.
But how do I make the connection? What do I connect to negative of the battery if I choose to externally power it?
Second Problem: If my HC-05 turns out to need only 3.3v input voltage, how many coins cells do I connect in series to power both pro mini and HC-05 module.
I am using a coin cell (3.3v) for powering the pro mini.
Thanks...

If you can't figure out the battery connection (it goes to ground) then I doubt that you connected the module correctly in the first place. Have a look at this question ( https://electronics.stackexchange.com/questions/280500/why-do-you-have-to-use-a-voltage-divider-with-hc-05-bluetooth-module-arduino ) to make sure you got the wiring correctly. And as far as I know a coin cell usually is 3.3 V, so if you don't specify what cells you have it's hard to tell. edit: if 5 V is printed on it I would trust that over the vendor specs. I found images of HC-05 modules that have 3.6 - 6 printed.

5V is within the valid range of 3.3V to 6V. What makes you assume that it only works on 5V?

@sa_leinad Who do you mean? I meant that I found modules that have 3.6 to 6 V printed on them. If his module has 5 V printed on it I would suspect it needs 5 V and not the range, since they could have printed 3.3 V to  6 V then.. I don't know these modules so I don't know if all work with 3.3V, but I also mentioned that wiring needs checking. If it works with 3.3 V and OP did everything correctly it should have worked when powering with 3.3 V.

@idkfa I have a regulator in my HC - 05 which levels it to 3.3v. Should I still use a voltage divider?                                                                                You are probably right about that I should trust what is printed on the board and consider my HC-05 to be 5v input and a regulator to 3.3v (which is mentioned as level 3.3v on the board).                                                    If I don't require a voltage divider? Where do I connect the negative of the power supply?

As I mentioned I don't know the module. I'm sure if you read the link / do some further research you can find out if you need a voltage divider or not. I would have to read that myself, too. As I already wrote: it goes to ground. @chrisl wrote in his answer "In this case be sure to connect the grounds of both power supplies, so that they have a common ground."

@idkfa I was actually speaking to Hardik Sharma with my comment. Sorry for the confusion.

The HC-05 (the PCB that is mounted on the PCB of the module) itself runs on 3.3V. Many microcontrollers run on 5V, so people are selling the HC-05 mounted on a PCB with extra components, for example a voltage regulator from 5V to 3.3V.
Voltage regulators have a minimum input voltage for which they can hold the output voltage at the specified value. Refer to this question for more information about this. So supplying the module with 3.3V instead of 5V will result in a supply voltage for the HC-05, that is significantly lower than 3.3V, so it most likely won't work correctly.
If you want to use the HC-05 module as it is, you have to provide 5V supply voltage from another source. In this case be sure to connect the grounds of both power supplies, so that they have a common ground.
If you don't want to use an extra power supply, than you may bridge the voltage regulator on your modules PCB and provide the 3.3V as supply voltage, that are used by the Arduino. Doing so would not be an easy task for a beginner, since you would have to solder small SMD components. Also the outlay of the modules PCBs are very different (depending on manufacturer). Note that in this case you should never ever put 5V on the Vcc pin of the module again, since it is then directly passed on to the HC-05 chip, which would be destroyed from the 5V supply.

I don't want to use a divider so I should connect the negative of the battery to GND on the pro mini. RIGHT?

Yes, negative battery pin to ground of HC-05 and to ground oft arduino. Positive battery pin only to HC-05. This way the current for HC-05 only comes from the battery, but the HC-05 can also evaluate digital signal Form arduino, since they have a common ground


text:
AccelStepper motor current position
When using the AccelStepper library to control the motor, I need the current position of the motor at any given time when in motion. However, the functions in this library blocks so currentPosition() cannot return the position until the move()/run() function blocks completely to the desired/set position. How can I circumvent this to move and display the position simultaneously?

yes, you can ... step only one step at a time


text:
Playing a sound file with Arduino Uno Wifi
I have an Arduino Uno Wifi (Rev2) and I want to play a sound file. I found two libraries so far but neither of them work. The TMRpcm library (https://www.arduino.cc/reference/en/libraries/tmrpcm/) only works on the base Arduino Uno and anther library called AudioZero (https://www.arduino.cc/reference/en/libraries/audiozero/) does not seem to be compatible with Arduino Uno Wifi.
Is there any other library that I could use to play a sound file. I have an SD card attached and a library that can read in a .wav file but no library to actually output the sounds on a basic speaker.
I need to use the Arduino Uno Wifi for what I am trying to achieve since communicating with the internet is crucial.
Using a base Uno with a wifi attachment did not prove to be promising since the attachment acted as it's own board and need to be flashed.

The Uno a) doesn't have analog outputs and b) only a tiny RAM. You better look for a more suitable microcontroller or at least a hardware extension to do the job of buffering and playing the output signal.

Hi @SimSon thank you for your reply. Do you have any recommendations? I have only used the Arduino Uno so far and I am not very familiar with other microcontrollers.

I have no experience with playing audio files on microcontrollers, but I'd personally start with a controller that has a reasonably large RAM (e.g. ESP32) and an external DAC.

If the controller is compatible with the Arduino environment, there shouldn't be much difference from how you would program the Uno

No sounds library seems to exist that is compatible with the architecture of the Arduino Uno Wifi specifically. Other micro-controllers need to be looked into.


text:
Can't manage my calculator to work
Yesterday, I've got myself an arduino uno. Since I'm pretty newbie in it, I'd like to ask here for a hint, because I can't manage to make my "calculator" working. I don't have much experience in programming, but I thought, the loop should wait for one of the function called to end, instead of it, it looks like it is running all function, over again, and probably that's why I getting error in console output.
Code:
  #include <Key.h>
#include <Keypad.h>

const byte rows = 4;
const byte columns = 4;

char first_number;

char keyboard[rows][columns] = {
    {'1','2','3','+'},
    {'4','5','6','-'},
    {'7','8','9','/'},
    {'C','0','=','*'}
  };

byte  rowsPins[rows] = {9, 8, 7, 6};
byte columnsPins[columns] = {5, 4, 3, 2};

Keypad keys = Keypad(makeKeymap(keyboard), rowsPins, columnsPins, rows, columns);

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

int getNumber(){
    char user_input = keys.getKey();
    int value;

    if (user_input){
    switch (user_input){
          case '0':
            value = 0;
            break;
          case '1':
            value = 1;
            break;
          case '2':
            value = 2;
            break;
          case '3':
            value = 3;
            break;
          case '4':
            value = 4;
            break;
          case '5':
            value = 5;
            break;
          case '6':
            value = 6;
            break;
          case '7':
            value = 7;
            break;
          case '8':
            value = 8;
            break;
          case '9':
            value = 9;
            break;
          default:
            Serial.print("Error int");
    }
  }
  return value;
}

int calculate(int first_number, int second_number){
    char operation = keys.getKey();
    int value;

    switch(operation){
        case '+':
          value = first_number+second_number;
          break;
        case '-':
          value = first_number-second_number;
          break;
        case '*':
          value = first_number*second_number;
          break;
        case '/':
          value = first_number/second_number;
          break;
        default:
          Serial.println("Error cal");
      }
      if (value){
          Serial.println(value);
        }
     return value;
  }

void loop(){

  int first_number = getNumber();
  int second_number = getNumber();
  int test = calculate(first_number, second_number);
}

What I wanted to do, is read numeric input from the keypad twice (it's just for now. I know it should be done different), and then, input the operation, such as multiply, but since the loop calling the function all over again, I can't actually do it. How I should approach it?

include a flag ... valueValid ... set it after calculation is done ... clear it after value is printed

Consider this excerpt from your code:
int getNumber() {
    char user_input = keys.getKey();
    int value;
    if (user_input) {
        // ...
    }
    return value;
}

Think about what would happen if the condition if (user_input) turns
out to be false. The function would simply return an uninitialized
variable, which contains basically garbage.
The method getKey() from the Keypad library is intentionally
non-blocking. It returns immediately in order to avoid the rest of
your program being stuck while waiting for keypad input. If some key is
pressed, the method returns that key. Otherwise it returns NO_KEY,
which is zero and, as a boolean, evaluates to false. This means that,
when no key is pressed, the function getNumber() returns immediately,
and it returns garbage.
The correct approach would probably involve some sort of finite state
machine. However, for this simple example you can get away with a
quick-and-dirty solution: block while waiting for user input:
// Wait for user input.
do {
    user_input = keys.getKey();
} while (!user_input);

Keep in mind though that, if your program is going to evolve, at some
point the blocking approach can become an issue, and you may have to
completely rewrite the logic in a non-blocking fashion.


text:
How to read and Serial.print the contents (current values) of an 8-bit register?
Currently I'm using:
  ADMUX = 0b01100000; //example
  for (int i = 7; i >= 0; i--) {
    Serial.print(bitRead(ADMUX, i));
  }

This correctly prints:
  01100000

But is there a simpler way?
Before coming up with above for loop I tried using just:
Serial.println(ADMUX);       //converts to integers: 96
Serial.println(ADMUX, BIN);  //leaves out leading zeros: 1100000
Serial.write(ADMUX);         //converts to ASCII char: `

Anything else I don't know of?

Are you asking because you're trying to avoid writing a loop yourself, because you're wondering if it's possible to do with fewer moving parts (whether that's done in your code or someone else's), or are you asking because you're under the impression that without a built-in thing you'd need to write a loop each time you wanted to print a value this way?

I'm not entirely sure what you're asking either ;)

Me being new to using timers and registers, and having done some reading and experimenting recently, I just want to know what is the preferred or most elegant way to do this. I couldn't find an answer here myself. So I tried above ways. Maybe there is something better. If there is I'd like to know it ;)

itoa(n, buffer, 2) is not part of C++, but available in  Arduino, and achieve the same as Serial.println(num, BIN);. It need to define the buffer like char buffer[33] before using, so it is not much simpler.

If you look how print_number is defined which is called by all Serial.print(number, base), and how binary is defined in Arduino Core, there is really no simpler way. Just define your for..loop as a function print_binary() and use it if you need.

"better" (without qualification) and "preferred" are highly contextual and mostly opinion based, which something that questions get closed for on stackexchange.  So, if you have a way to make the question more specific or objectively answerable, it's probably a good idea to do that.

@timemage I did ask 'simpler'.

@hcheung itoa() followed by Serial.print still no leading zeros. So indeed the same. Thanks for your input. Happy with the for loop then for printing. And I guess for other purposes I shouldn't be bothered by the left out leading zeros, as I suppose they don't make a difference when reading or comparing anyway.

@Gaai i noticed. that's part of what prompted my original question. maybe it's just me.

Another option:
#include <LibPrintf.h>
printf("%.8b", ADMUX); //prints: 0110000

The LibPrintf.h library is standard included on ESP boards.
%b stands for binary. .8 for 8 decimal places, which adds leading zero's to all truncated (binary) numbers.
It becomes *simpler if you wanted to print the variable name along with it like:
printf("ADMUX: %.8b", ADMUX);

Results in:
ADMUX: 01100000

*Simpler in the way it now only occupies a single line of code.

Where the question was tagged UNO and NANO the following may be worth knowing for anyone considering this route. A minimal test framework around code in question results in Sketch uses 1542 bytes (4%) of program storage space. Maximum is 32256 bytes.  The same around the code in answer results in Sketch uses 11456 bytes (35%) of program storage space. Maximum is 32256 bytes.

You're right of course. And answer is cheating anyway as it uses a complete library. You could achieve the same one liner with a simple function for multiple calls. But thought it worth a mention especially as the library is standard on esp boards, even though not tagged. Might be good knowledge for people looking to do it on those boards aswell.

Or just that the cost is sort of amortized (through not removed) by more use of LibPrintf. I didn't think so much about whether or not it was cheating. Only that this can be particularly important to be aware of. Any implementation of printf is a beast. However, on a project of any serious size the avr-libc (or whatever) one has often already been paid for, so to speak, by having been used at least once in someone else's code, whether you like it or not.

So if any printf or the like is already been used elsewhere (taking up that costly memory space anyway), you might aswell use it for this? That what you mean? (had to look up amortized, learning everyday ;)

No, it is not that simple. This happens per printf implementation. The cost-per-call for any given individual printf() implementation enormous when you use it once. So the worst case scenario is where you have one usage of avr-libc one and one usage of the libprintf one. Also, the author(s) have documented how you can remove features to trim the library size. There's only so much more I can say about this relevant to your answer.


text:
Cannot make https request on esp32
I have esp32 cam. I want to send https request to azure function. I have exposed https port via ngrok.
HTTPClient http;

if (http.begin("https://4b21-31-183-241-151.eu.ngrok.io/", rootCACertificate)) { //Specify the URL and certificate
  int httpCode = http.GET();                                                  //Make the request

  if (httpCode > 0) { //Check for the returning code

      String payload = http.getString();
      Serial.println(httpCode);
      Serial.println(payload);
    }

  else {
    Serial.println("Error on HTTP request");
  }

  http.end(); //Free the resources
} else {
  Serial.println("Cannot begin");
}

I have generated cert as openssl s_client -showcerts -connect 4b21-31-183-241-151.eu.ngrok.io
http.begin returns 1, but http.GET() returns -1.
I want to do it with minimal effort. I saw that HttpClient allows https, so I don't need explicitly init WiFiClientSecure.
What I'm doing wrong?


text:
How can I use a LCD I2C and a RTC3231 on a Arduino Pro Mini?
On a small project, I have a DS3231 RTC module and a LCD I2C module that I'm trying to connect on a Arduino Pro Mini board. However, both the RTC and LCD require connecting the SDA and SCL to the pins A4 and A5 respectively.
The libraries do not seem to allow changing the connected pins. Why is that? I have other pins available, like A6 and A7, can those be used?

Wow! First question and already downvotes without comments or answer. This is a real nice community! I feel welcome!

I guess, the downvotes are, because you didn't research your problem. you would find that I2C is a bus

SDA and SCL are the lines of the I2C bus. It being a bus means that you can connect multiple devices to it. Each device on an I2C bus has an address. You cann connect both devices on these pins and talk to each device one after another

@Juraj well, I'm asking because I'm researching. Seriously. It's like an employer asking for 5 years experience; someone has to give a guy a chance.

Welcome, I understand where you are coming from, without a background you do not know what to ask. Were were all where you are at one time. I hope this helps.  You need to do some studying on the I2C bus, online tutorials will make it easy. You you will find you can connect over 100 devices to it at one time The SCL and SDA lines go from module to module. Note each module has its own address, sometimes they are selectable. Some modules have pull up resistors, others do not. To keep it interesting the pull up resistors are mostly 10K but that is not a constant.
There are loading rules etc to be careful of if you have long wires or maybe more than three units. You need to add pull ups to each of the two lines (example: 4.7K from SCL to +5) or use something in the 3K range for a 3V3 system. The reason is because the bus has both dominant and recessive states where the recessive is high which the resistor provides. The SCL and SDA output/input on the parts have open collector/open drain outputs so they cannot source anything.
Once you have it hooked up you need to run a program called I2C scan or something like that. If you have wired it correctly it will give you the address of the module, you will probably get two or three as there is the RTC, Memory device and possible a temperature sensor.
The #1 rule is the Arduino A Power Supply it is NOT! A small module or two connected to the 5V out is fine but never connect a motor directly to any arduino you will probably fry the Arduino.
I use Vin and supply it with about 8 volts by using either a Buck or Sepic converter from a 12V 2A or larger supply. I do it this way because I get a more stable voltage on the Arduino because of the extra filtering etc built into the analog regulator section. Real nice when using the A/D, keeps things stable. Were here to help, ask questions any time and do not worry is some over eager person decides to vote you down. Read the guidelines etc and  you will do great.
You can search online for "Arduino RTC" and find a lot of programs with software.

Thank you for this very helpful explanation! I had noticed a drop-down in voltage when connecting a 4 channel multi-function relay module, I already figured to connect it's power source directly to the power source, and NOT on the Arduino! I was not aware of the I2C protocol. I find a lot of the tutorial confusing since there are so many different modules and boards! It'll get clearer with time. Thanks!

Just for fun answer your question in two weeks, you will be surprised at how much you learned. Have fun!


text:
Avrdude verification error when uploading to Arduino Mega 2560
I have been getting the error
avrdude: verification error, first mismatch at byte 0x036c
0xb8 != 0xf8
avrdude: verification error; content mismatch
avrdude done.  Thank you.

When trying to upload the example blink sketch to an Arduino mega 2560.
I did some googling and found that the common recommendation to solve this is to flash the bootloader.
Which does fix the issue for the first upload after flashing, but the issue reappears after one upload. But every time I flash the bootloader I do get one successful upload following that with no errors.
The mismatch is always at 0x036c every time.

Did you see this answer?

I did see that and flashed a new bootloader, the voltage of the board seems stable 4.9V
and I think the usb driver or cable are unlikely because I was able to try an identical Arduino that does not have the errors which means maybe its be a hardware issue with this specific board?

The verification is there to check two possible error situations: Transmission error while uploading or faulty flash memory. Apparently, the error can also happen for a bunch of other reasons (see the linked answer), but these two cases should still be considered. Since another Arduino works with the same cable, it's unlikely a communication error and hence, based on all we know, I am assuming your Arduino is bad.
You might be lucky that for some reason (the fault is in some piece of code that's not actually used) the program works despite the error, but it's likely that sooner or later you'll get very strange crashes or otherwise undefined behavior.

Yeah its probably just a bad arduino. I just found it weird that the verification seemed to work fine after flashing the bootloader but then went back to failing.

Maybe something is different the first time internally. Or the bootloader itself already doesn't work correctly.