text:
Powering Atmega328p from 4.5V
I want to use Atmega328p controller to handle some very simple signals. I'm using the chip and not the whole arduino board because it is a lot cheaper. The problem is that chip itself doesn't have voltage regulator so I need to think of a rechargeable power source. My idea is to use 3 rechargeable AA batteries (~4.5V). I read that it can handle somewhere from 1.5V to 5.5V but I also read that clock speed is then reduced and a lot other complications. So, finally, the question, If I were to use described power source, what challenges should I be ready to face and how will it impact the performance and is it even possible to pull it off.

From the ATmega328P datasheet:

Within the range 2.7 V – 4.5 V, the maximum frequency is a
linear function of Vcc. From this graph, you can compute the minimum
value of Vcc required to run the microcontroller at 16 MHz: it's
3.78 V.
If you do want to run at 16 MHz, in order to emulate an Arduino
Uno, it may become unreliable once the supply voltage drops below
3.78 V, i.e. 1.26 V per cell. Whether this is a serious issue or
not depends on the cell chemistry. For reference, alkalines reach about
1 V at the end of their useful life, and NiCd has about 1.2 V
when fully charged. You will have to find the relevant voltage for the
chemistry you plan to use.
If you can afford running the microcontroller at 8 MHz, then you
will most certainly be safe.
Edit: If you want to run the microcontroller at 8 MHz, and you
are programming it with the Arduino IDE, you have to select a
board/processor combination that runs at 8 MHz. For example,
“Arduino Pro or Pro Mini” / “ATmega328P (3.3V 8MHz)”. This will ensure
that the time-related functions (millis(), delay(), etc.) and the
baudrates of Serial.begin() provide the correct timings. Other than
that, the drawback of running at a lower clock speed is that the
CPU-bound functions (computations) take twice as long.

+1, but I got 3.6 V.

@tim: The linear interpolation formula is Vcc = 2.7 + (f-10)/(20-10)*(4.5-2.7).

Ah, thanks, I see where I went wrong. There are two different gradients which I didn't initially spot and was using the gradient between 1.8 V to 2.7 V to calculate for 16 MHz which is on the second gradient between 2.7 V and 4.5 V.

What are side effects of running your board at lower clock speeds? I can see that it would be slower but is that really it?

@Mirakul It also affects your choice of PWM frequencies and UART speeds. But mostly just... everything takes twice as long :)

Personal anecdote: I've observed an ATmega644p running seemingly fine at 20 MHz on only 3.3 V.   You can operate outside the safe operating area, it's just not "safe" outside of it.

@Mirakul: See edited answer.

Thank you, that is what I needed.

They make SEPIC converters that will hold the voltage at 5V for you. The reason for the SEPIC is during charge what happens to the battery voltage and especially if the battery open circuits. If there is no chance for the battery voltage to go to high a boost converter will work just fine. This solution will allow it to run at full speed without degrading performance etc. The new converters are not very expensive and are generally greater than 95% efficient depending on the unit. If you can up the battery voltage things will get a lot more efficient but you would then need to change the boost to a buck, the SEPIC would be fine. I tend to use the China Nanos, they are inexpensive, probably less then your parts and readily available. I have not had problems with them. I like to supply them with about 8 volts via Vin, that gives me the additional filtering of the onboard power supply.

I am surprised that you claim an efficiency of 95%. The figures I have seen tend to be in the 70 to 90% range, and that is with currents of 500mA, An ATMEGA typically takes a few mA, and with consumption that low, the overheads of the switcher are likely to exceed the throughput (ie efficiency less than 50%).


text:
ATtiny85 plugin and removed it self
So I bought ATtiny85 recently, when I plug it to my PC it make sound like mouse has been plugin, but then it make sound like the device has been removed. It happen again and again until I remove the device. Is it the device problem or am I missing something? Can I fix it?

Please give more details about the exact board you have, any other observations (led lighting up on the board or not), if you've tried plugging it into another port or via a hub etc.

The Uno does not have an AtTiny85 processor so I will remove that tag.

The AtTiny85 is a processor and not a board. It always helps to give more details. A link to the exact board you bought would be helpful.

I'm assuming you've bought a Digispark (or compatible) ATTiny85 USB board.
The sound of a USB device inserting and removing is normal. When the digiSpark boots it listens to the USB bus for a short period so you can upload your sketches. Then it proceeds to boot your sketch.
If no sketch has been uploaded, it might just reboot until you upload one. The Digisparks I have, have all had a "blink" sketch preloaded but yours may not.
The "problem" will go away when you start running your own sketches. It will then only announce itself once and then remove itself from the USB bus, unless your sketch also communicates via the USB bus.

source: Stack Exchange

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

sort: votes


text:
ESP8266: error: 'getLocalTime' was not declared in this scope
I am getting

error: 'getLocalTime' was not declared in this scope

when I am compiling this code for ESP8266, however works for ESP32:
#include "time.h"

void gettime()
{
  static int16_t delaycount = 0 ;                         // To reduce number of NTP requests
  static int16_t retrycount = 100 ;

  if ( timeinfo.tm_year )                                 // Legal time found?
  {
    sprintf ( timetxt, "%02d:%02d:%02d",                  // Yes, format to a string
              timeinfo.tm_hour,
              timeinfo.tm_min,
              timeinfo.tm_sec ) ;
  }
  if ( --delaycount <= 0 )                                // Sync every few hours
  {
    delaycount = 7200 ;                                   // Reset counter
    if ( timeinfo.tm_year )                               // Legal time found?
    {
      dbgprint ( "Sync TOD, old value is %s", timetxt ) ;
    }
    dbgprint ( "Sync TOD" ) ;
    if ( !getLocalTime ( &timeinfo ) )                    // Read from NTP server
    {
      dbgprint ( "Failed to obtain time!" ) ;             // Error
      timeinfo.tm_year = 0 ;                              // Set current time to illegal
      if ( retrycount )                                   // Give up syncing?
      {
        retrycount-- ;                                    // No try again
        delaycount = 5 ;                                  // Retry after 5 seconds
      }
    }
    else
    {
      sprintf ( timetxt, "%02d:%02d:%02d",                // Format new time to a string
                timeinfo.tm_hour,
                timeinfo.tm_min,
                timeinfo.tm_sec ) ;
      dbgprint ( "Sync TOD, new value is %s", timetxt ) ;
    }
  }
}

What shall I replace getLocalTime with?

It looks like the esp8266 Arduino core don't have a similar function.
The getLocalTime in esp32 arduino core is a simple function implemented in esp32-hal-time.c.
bool getLocalTime(struct tm * info, uint32_t ms)
{
    uint32_t start = millis();
    time_t now;
    while((millis()-start) <= ms) {
        time(&now);
        localtime_r(&now, info);
        if(info->tm_year > (2016 - 1900)){
            return true;
        }
        delay(10);
    }
    return false;
}

The function compiles on esp8266 arduino as it is so you can copy it to your sketch.

there are two parameters you need to pass. Whereas in my example is only one

@BJackson, the declaration in header file has a default value for the second parameter bool getLocalTime(struct tm * info, uint32_t ms = 5000); (you can't set default value on function definition). you can call the function with 5000 as second parameter or remove the parameter and use the fixed value in the function.

It works, thanks. But is there a ESP8266 way? I was looking at https://github.com/scanlime/esp8266-Arduino/blob/master/cores/esp8266/time.c and there is nothing similar

@BJackson, it is a only convenience function only to wait with timeout until the very first response from NTP server is received and RTC is set

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


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:
ESP32 programing error (A fatal error occurred: Timed out waiting for packet content )
I am trying to find the proper model of my esp32 MCU and find out the reason for below errors:
esptool.py v3.1-dev
Serial port /dev/ttyUSB0
Connecting........__
Chip is ESP32-D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, Coding Scheme None
Crystal is 40MHz
MAC: 30:ae:a4:26:6f:44
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 921600
Changed.
Configuring flash size...

A fatal error occurred: Timed out waiting for packet content
A fatal error occurred: Timed out waiting for packet content

My ESP32 type and the board setting are shown below (link) :

Thanks.

In case where the upload procedure with esptool.py starts successfully but fails as soon as the baud rate is set to the high baud rate selected in Tools menu, select a lower baud rate in Tools menu.

This can also be caused by how certain pins are wired, if pin 12 is high at boot, programming will also fail with this message.


text:
ATtiny85 won't wake from sleep
My ATtiny 85 won't wake up!
The purpose of the device is to monitor a reed switch and give a 20 ms output pulse on every alternate positive-going transition of the reed switch input. The device should go to sleep after 30 s of inactivity. It should wake up on reed switch activity (rising or falling edge).
/*
          ATMEL ATTINY 85
              +-\/-+
        PB5  1|    |8  Vcc
        PB3  2|    |7  PB2 (INT0) reed switch input (1 MΩ ext. pull-up)
        PB4  3|    |6  PB1        output
        GND  4|    |5  PB0
              +----+
*/
#include <avr/sleep.h>
#include <avr/power.h>
#include <elapsedMillis.h>

const int hallPin = 2;            // Reed switch in this case.
const int magnetPin =  1;         // Output.
const long debouncing_time = 15;  // Debouncing time in milliseconds.

volatile int hallState = 0;       // variable for storing the hall counter
volatile bool hallMem = 0;        // One-shot memory.
volatile unsigned long last_micros;

elapsedMillis timer;

void setup(){
  pinMode(magnetPin, OUTPUT);
  pinMode(hallPin, INPUT);
  // Attach an interrupt to the ISR vector. DO I NEED THIS?
//  attachInterrupt(0, pin_ISR, RISING); //default interupt pin is always 0 on ATtiny85 (physical pin 7).
  timer = 0;                             //Reset the timer
}

void loop(){
  if(digitalRead(hallPin) && !hallMem){
    hallMem = true;               // One-shot memory.
    hallState++;
    delay(debouncing_time);       // Keep it simple.
    timer = 0;
  }
  if(!digitalRead(hallPin)){
    hallMem = false;              // Allow re-trigger.
  }
  if(hallState > 1) {
      digitalWrite(magnetPin, HIGH);        // Send 20 ms pulse to sensor activation coil.
      delay(20);
      digitalWrite(magnetPin, LOW);
      hallState = 0;                        // Reset the trigger.
  }
  if(timer >= 30000) {                      // No activity.
    system_sleep();
  }
}

// From http://interface.khm.de/index.php/lab/experiments/sleep_watchdog_battery/
void system_sleep() {
  GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
  PCMSK |= _BV(INT0);                     // Use INT0 (PB2) as interrupt pin
  ADCSRA &= ~_BV(ADEN);                   // ADC off
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sei();                                  // Enable interrupts
  sleep_cpu();                            // sleep

  cli();                                  // Disable interrupts
//  PCMSK &= ~_BV(INT0);                  // Turn off INT0 (PB2) as interrupt pin
  sleep_disable();                        // Clear SE bit
  ADCSRA |= _BV(ADEN);                    // ADC on

  sei();                                  // Enable interrupts

  timer = 0;          // Reset the sleep timer on wake-up.
}

ISR(PCINT0_vect) {
}

Can anyone spot my error that is preventing a wake-up?
What is the ADC enabling instruction doing? Do I need it?
Many thanks.

Try to replace the PCMSK |= _BV(INT0);  with PCMSK |= _BV(PCINT2);

@gbg, that seems to be doing something, thanks. I'm going to add in an "awakeLED" so I can monitor the sleep status. It's bedtime in Ireland.

I believe your problem lies here:
PCMSK |= _BV(INT0);  // Use INT0 (PB2) as interrupt pin

You seem to have mixed up two sorts of interrupts:

INT0 (External Interrupt), which only works on pin INT0 (i.e. PB2)
and can sense low-level, rising edge, falling edge, or any change.

PCINT0 (Pin Change Interrupt), which works on any IO pin, but can
only sense “any change”.

Since you are sleeping in PWR_DOWN mode, pin change interrupt is the
appropriate choice. All your program is consistent with this choice but
for the line above.
The INT0 macro has the value 6. It represents bit 6 of GIMSK, which
is used to enable the INT0 interrupt. Not what you want. Bit 6 of
PCMSK is reserved, so you are not supposed to touch it. If you want
the pin change interrupt to sense changes in pin PB2 (aka PCINT2), you
instead have to:
PCMSK |= _BV(PCINT2);  // sense changes in PCINT2 = PB2

Thanks for the clear explanation. It works now. Can I leave out the ADCSRA lines as I'm not using any analog functions?

@Transistor: Indeed you can.


text:
Flash HEX onto an Arduino board
The scenario: I have built a device off an Adafruit nRF52840 and I need a way to deploy firmware updates. I have delivered the device to my end user and will need to periodically send him updates.
I do not want to send him source, and he isn't technically savvy enough to compile and upload using the Arduino IDE anyway.
Searching around I see lots of suggestions to use avrdude command line to push a hex file to the board. The issue I have is my user is not going to be up for running command line... if its not a click next installer he's basically lost. I could create a BAT file and distribute a zip containing the BAT and HEX files... he double clicks the bat file and it pushes the hex to the board. This would be an acceptable solution.
My issue is the port number. Every example I am seeing of using avrdude command line includes a parameter along the lines of: "-PCOM21".
My user is not going to know what comm port the device is plugged into... and even if they knew that I dont think I can ask them to go edit the BAT file with the correct -PCOM value.
There has to be a simple solution to allow an end user to push hex firmware to Arduino boards? I am just not having much luck finding it. Is there a product that does this I should look at or could you point me to a solution?

In practice, does the port number change?

look at the Info section at https://github.com/dotKokott/listComPorts-csharp

turn on verbose mode in IDE and see the external command executed by the  IDE. you can use the same command

the UF2 bootloader allows drag and drop update https://github.com/adafruit/Adafruit_nRF52_Arduino#bootloader

There are several hex file loaders for the Arduino based Arduboy. Maybe the source for one of those can be modified to suit?

https://stackoverflow.com/questions/39043186/how-to-get-only-the-currently-used-serial-com-port-name-for-a-specific-usb-devic


text:
ESP8266 01 doesn't react after baud rate change
Hello guys I have my ESP8266 connected to my Arduino. Then I typed in AT in the serial monitor. It confirmed this command with OK. After that I typed in  AT+UART=9600, 8, 1, 0, 0 which gave me the response ERROR. Then I googled what I could do, which told me that I should try change the baud rate permanently with the command AT+IPR=9600. I  did this but I got no response. After that I wondered if everything was ok so I typed in AT. No response. Now I'm a little bit sad because everything started to be great but I don't know how I can fix the whole problem. I also tried to upgrade its firmware with XTCOM Utility but it says it can't connect.
#include <SoftwareSerial.h>

SoftwareSerial ESPserial(2, 3); // RX | TX

void setup() {
  Serial.begin(115200); // communication with the host computer

  //while (!Serial) { ; }

  // Start the software serial for communication with the ESP8266

  ESPserial.begin(115200);

  Serial.println("");

  Serial.println("Remember to to set Both NL & CR in the serial monitor.");

  Serial.println("Ready");

  Serial.println("");

}

void loop() {
  // listen for communication from the ESP8266 and then write it to the serial monitor

  if ( ESPserial.available() ) { Serial.write( ESPserial.read() ); }

  // listen for user input and send it to the ESP8266

  if ( Serial.available() ) { ESPserial.write( Serial.read() ); }
}

This is my code. I tried it with both 9600 and 115200 but if I use 115200 the serial monitor just shows some garbage signs. It's kind of frustrating because I can't even interact with the serial monitor as my typed commands don't show up anymore. Do you have any idea how I could fix this problem?

did you use ESPserial.begin(9600);?

Yes I tried that but it still gives me the same problem. It didn't gave me the rubbish like with 115200 but it still doesn't respond

It is quite common for changing the baud rate to cripple an ESP-01. The only cure is to reflash it.

If you feel lucky you can play around with different baud rates and see if you find one. The part has a default baud but I do not remember it but it is in the literature.

Alright so how do I reflash it?

I tried flashing it but it shows "Failed to connect"


text:
Can't stop the 3 pin active buzzer
I was simply trying to program a buzzer with the ultrasonic HC SR04 and 128x64 OLED display. The buzzer is an active buzzer (3 pin) on a small board. The problem is that, once on, it never stops buzzing. I have used the following code which is working fine except the buzzer.
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define trigPin 9
#define echoPin 8
int buzzer = 12;//the pin of the active buzzer
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzer,OUTPUT);//initialize the buzzer pin as an output
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); //initialize with the I2C addr 0x3C (128x64)
display.clearDisplay();

}

void loop() {
float duration;
float distance_cm;
float distance_in;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance_cm = (duration/2) / 29.1;
//distance_in = (duration/2) / 73.914;

display.setCursor(30,0); //oled display
display.setTextSize(1);
display.setTextColor(WHITE);
display.println("Distance");

display.setCursor(30,10); //oled display
display.setTextSize(1);
display.setTextColor(WHITE);

if(distance_cm<2.9)
 {
      noTone(buzzer);
      display.println("Too Close");

  }
else if(distance_cm>30)
 {
      noTone(buzzer);
      display.println("Out of Range");

  }
else if(distance_cm>2.9 && distance_cm<3.5 )
{

display.println(distance_cm);
display.setCursor(80,10);
display.setTextSize(1);
display.println("cm");
display.setCursor(30,20); //oled display
display.setTextSize(1);
display.setTextColor(WHITE);
display.println("Reading Data");
tone(buzzer,329);
delay(20);
noTone(buzzer);
}

else
{
 noTone(buzzer);
 display.println("Too Far");

}

display.display();

delay(500);
display.clearDisplay();
Serial.println(distance_cm);

}

I am a beginner in Arduino programming ( Although have basic knowledge in C and python). You can make any optimization of this code if you feel so. Please help.

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

Temporarily solved by replacing the active buzzer with a 2 pin passive buzzer. the behavior of the active buzzer remained mysterious to me.

often they are high to silence.


text:
Expected signature for ATmega328P is 1E 95 0F; I can not burn bootloader on my arduino Uno
well...
the problem starts from the time that I accidentally touched the crystal on my arduino and all of a sudden everything messed up; the leds on arduino turned on and off while being touched, and after that I was unable to program it...
after a lot of searches, I decided t burn bootloader again...
so I got a USBasp and wired it to arduino and tried to program it using programmer or burning bootloader...
but...
It is not posible because of the following ERROR:
**Arduino: 1.8.15 (Windows 10), Board: "Arduino Uno"

avrdude: warning: cannot set sck period. please check for usbasp firmware update.

avrdude: Expected signature for ATmega328P is 1E 95 0F

         Double check chip, or use -F to override this check.

Error while burning bootloader.**

I tried changing that 0xF in config file to 0x14, because of the difference between ATmega328 and ATmega328p...
but still no progress...
I will be very glad if someone can help me run this UNO...
by the way, is it possible that the crystal which I touched with hand is ruined or interrupted and all of these stuff is because of that?

What crystal? Is it a genuine Arduino or a cheap Chinese POS?

its a 16mHz smd crystal...

and I dont think it to be chinese...

The crystal by the ATMega328P chip or the crystal by the USB interface chip?

the one by the ATmega

Then if it's a real Arduino it's not a crystal but a ceramic resonator. But there's always a chance you zapped the chip with static. Did you feel a shock when you touched it?

no, nothing like a zap...just sth like a touch screen that when I touch it, things change like leds

Any chance you could take a short video?

Or upload it to google photos and share the link.

https://drive.google.com/file/d/1u4wfHMXPAMI16Mm7IDgOGQIH4MAds16J/view?usp=sharing

Ok, so it's not a genuine Arduino. It's just the TX and L LEDs that light up. The L could be being controlled by a sketch that is triggered from a floating input. The TX LED is connected to the CH340G chip and no one really know what goes on with those things.

I was thinking that there must be sth wrong with fuse bits and boot loader...so, reprograming it should have worked, but well...it is not working...any suggestion?

It's more likely the CH340G chip has died. They're known to be very sensitive.

thats really a bad news...but anyhow...thanks for the time you put on this...I do appriciate it... ;)

You could try a "loopback" test to see if the USB interface is working or not.  1. Connect RESET to GND. 2. Connect pin 0 to pin 1. 3. Connect the Arduino to the PC. 4. Open the serial monitor in the IDE with the right port selected. 5. Type something. You should see what you type echoed back to you.

well...I did as you said...nothing happens...i an not see the message I type in response...it fade...and when I press ENTER, for a moment RX and TX leds on arduino blink...just this...

It sounds like the CH340G may be dead then. You can try using an external USB to UART adapter connected to the TX/RX pins and bypass the CH340G to keep using your board. Treat it like a "breadboard arduino" but with the chip still on the PCB.

I would use it for a mechanical template and purchase a new one. At this point we do not know what all failed. If you have the time and skill set go for it.

Well a couple of options:

Plug the Arduino with USB, do you see a Serial PORT? If you do there is a good chance the USB CHIP is ok.
Try programming the Arduino with a 12v High Voltage Programmer and burn a 8Mhz Internal oscillator bootloader and see if it works, if it does, the the crystal is damaged.
Another alternative, e to use a 16mhz crystal and put it in parallel with that one, see if you can flash it like that, or just desolder that one and replace with a new one, doesn't matter if it's the same freq, you still be able to burn a bootloader, hopefully choose a osc that is supported by the bootloaders (8, 12, 16, 20) for example


text:
Unable to find headers from installed platformio library
I wrote a library that I intend to use in several project and I published it via platform.io's library management system.
https://platformio.org/lib/show/12820/FastLED-SectionManager
This is the first time I've published via platform.io (first time I've published any c++ library). I read over platform.io's docs on creating a library and structured my library accordingly with my headers in the include directory and the implementation files in the src directory:

And created the following library.json file:
{
  "name": "FastLED-SectionManager",
  "version": "1.0.2",
  "description": "A led strip index manager that allows for logical groupings of strip sections.",
  "repository": {
    "type": "git",
    "url": "git@github.com:chris-schmitz/FastLED-Section-Manager.git"
  },
  "authors": [
    {
      "name": "Christopher Schmitz",
      "email": "schmitz.chris@gmail.com",
      "url": "https://light-inspiration.com/"
    }
  ],
  "homepage": "https://github.com/chris-schmitz/FastLED-Section-Manager",
  "license": "MIT",
  "dependencies": {
    "fastled/FastLED": "^3.4.0"
  },
  "frameworks": "*",
  "platforms": "*"
}

The problem that I'm running into is that when I install the library in a different project via platform.io and try to include a header, the header can't be found:

I double checked in the pio directory for the project and I can definitely see the header and implementation files:

So I'm not sure why platform.io can't find the headers.
I can't quite tell what I'm doing wrong. any ideas?

your library has a typo in main.cpp ... want to flip the direction on every other row with the third boolean argument ....
sectionManager.addRangeToSection(0, 0, 3, true); .... the boolean is 4th argument

I woke up this morning and looked back at the documentation.
A part I mis-read was this:

We recommend to use src folder for your C/C++ source files and include folder for your headers. You can also have nested sub-folders in src or include.

I had my headers stored in the lib folder :facepalm:
I tried to search around in the platformio docs for the explanation of the lib vs include vs src folders (I knew I saw it at one point) but couldn't find it.
I then remembered that I read the purpose of each directory in the Readme files in the project structure itself generated when you create a new platformio project:

The gist being:

src: your compiled files, i.e. your cpp files

It's worth noting that you could just shove all of the files in here and it would work

lib: libraries private to your project/library itself
include: declaration and macro definition files, i.e. your header files

This explains how the header files in the lib directory worked in the SectionManager project itself but didn't work when using the SectionManager as an installed library; the lib directory is only "visible" local to a project, so when I tried to include the header files from another project they couldn't be found.
So in my SectionManager project I moved the headers to the include directory, bumped the version number, and published:

Then I switched to my main project that I'm pulling the SectionManager library into, adjusted the dependency version to include the minor bump, updated, and now it works!

Makes sense, I'm just still getting used to c++ and platform.io.


text:
esp8266 wifi/ read serial data with python
I'm trying to read some serial (ADC) data from my esp8266 nodeMCU v3 over wifi using python.
I connected the esp on my local wifi and set it with fixed local IP using arduino IDE, but I couldn't find a way to extract the data using Python.
In a normal case, I just type in my python code the COM Port number and the Baudrate and just read. But with Wifi I counld not find a simple solution.
any Ideas ?
Thanks

There is no simple Serial via Wifi. You can look into websockets. I think that would be the way to transmit the data over the wifi network

You can run an httpserver on the esp and request desired data via wifi. Here's a tutorial https://randomnerdtutorials.com/esp8266-web-server-with-arduino-ide/

A basic TCP connection via WiFiClient would be easier than web sockets or an HTTP server, and would provide a reliable byte stream.


text:
My PN532 doesn't detect RFID card when connected with ESP32 in I2C mode while it works perectly with Arduino Uno
I have a Elechouse PN532 module (bought here - https://robu.in/product/pn532-nfc-rfid-read-write-module-v3-kit/). When I try to use to it with I2C and connect it to my ESP32 (DOIT ESP32 DEV KIT V1, 30 pin version), the PN532 gets detected but it doesn't detect when a card or token shown to it. When I try the exact same code with Arduino Uno with I2C, it works flawlessly. Below are the connections for both boards, the code, the output and actual connection picture (since some said wire position matters for PN532).
Connections

ESP32

ESP32
PN532

GPIO 22
SCL

GPIO 21
SDA

3.3V
VCC

GND
GND

Arduino Uno

Uno
PN532

A5
SCL

A4
SDA

3.3V
VCC

GND
GND

The code
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>

PN532_I2C pn532i2c(Wire);
PN532 nfc(pn532i2c);

void setup(void) {
  Serial.begin(115200);
  //Wire.begin(21, 22);        //used this line only when connected with ESP32
  Serial.println("Hello!");

  pn532i2c.wakeup();    //delays 500ms
  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }

  // Got ok data, print it out!
  Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

  // Set the max number of retry attempts to read from a card
  // This prevents us from waiting forever for a card, which is
  // the default behaviour of the PN532.
  nfc.setPassiveActivationRetries(0xFF);

  // configure board to read RFID tags
  nfc.SAMConfig();

  Serial.println("Waiting for an ISO14443A card");
}

void loop(void) {
  boolean success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

  // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
  // 'uid' will be populated with the UID, and uidLength will indicate
  // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);

  if (success) {
    Serial.println("Found a card!");
    Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print("UID Value: ");
    for (uint8_t i=0; i < uidLength; i++)
    {
      Serial.print(" 0x");Serial.print(uid[i], HEX);
    }
    Serial.println("");
    // Wait 1 second before continuing
    delay(1000);
  }
  else
  {
    // PN532 probably timed out waiting for a card
    Serial.println("Timed out waiting for a card");
  }
}

Output

For Arduino Uno

For ESP32

Connection Placements

For Arduino Uno

For ESP32

Also, the configuration of ESP32 in Arduino IDE

The PN532 requires I2C clock stretching. It doesn't work well over I2C with the ESP8266 or ESP32 (Adafruit has it working with the ESP32 under certain conditions - using an interrupt and being the only device on the I2C bus - you might try their driver). Your best solution is to connect it via SPI and not I2C.

Are there pullups on the board? I don't know if the arduino enables its pullups in I2C master mode, bit I don't see any on those images. Try to enable them and use the I2CScanner sketch for debugging.

@romkey While using my PN532 with Adafruit library I need to connect 6 pins right? (VCC, GND, SDA, SCL, IRQ, RST)

@SimSon I will try with external pullups and one more thing, since the firmware on PN532 is getting detected, doesn't that mean I2C is working perfectly between PN532 & ESP32, and not require external pullups? I am beginner in I2C so forgive if anything is illogical.

To use PN532, UART or SPI seems to be a good choice. Also, the little red board needs a strong power supply, and the power supply capacity from the ESP32 DEV KIT will be insufficient; I recommend adding a capacitor of about 47uF on the PN532.


text:
Connect ESP8266 with Android Studio App
Hey guys I have ESP8266 and want to remote control a sailboat with it. Till now it works fine but how is it possible to send continuous data between the Arduino/ESP8266 and my smartphone? If you need any further information just add a comment.
Thanks guys

Do you have an ESP8266 dev board like a NodeMCU or an Arduino plus an ESP8266 with AT firmware on it? The design of the project is up to you, but normally you would let the ESP create a wifi access point, connect with the smartphone and then send messages over the network via websockets or similar (also depending on the question above)

@chrisl, why 'web'? plain TCP socket or UDP will be faster

@chrisl I use Arduino Uno + ESP8266


text:
Changing single bit in byte array
So I have a byte-array representing the display attached to my Arduino:
byte theDisplay[8] = {
    B00000000,
    B00000000,
    B00000000,
    B00000000,
    B00000000,
    B00000000,
    B00000000,
    B00000000
};

Now I want to flip a single bit at an arbitrary position:
theDisplay[3][6] = 1;

This (probably) faulty method produces these errors:
In function 'void setup()':
sketch_sep14c:13:18: error: invalid types 'byte {aka unsigned char}[int]' for array subscript
   theDisplay[3][6] = 1;
                  ^
exit status 1
invalid types 'byte {aka unsigned char}[int]' for array subscript

Is there an easy way to flip a single bit working with indexes like shown above?

https://www.arduino.cc/reference/en/ Bits and Bytes section

@Juraj I was aware of that, but I couldn't figure out how to set the 6th bit of the 3rd item in the array to 1.

The error occurs, because you try to use the syntax for a 2 dimensional array with a 1 dimensional array (since you have an array of bytes, not bits, and a microcontroller always works with at least one byte). For accessing the individual bits you need to use bitwise operators. For example this:
theDisplay[3] |= (1 << bitnumber); // for setting the bit
theDisplay[3] &= ~(1 << bitnumber); // for clearing the bit

with bitnumber being the number of the bit to change counted from least significant bit (in the binary representation in your code the rightmost digit) to most significant bit (the leftmost digit).
If you want to know, what exactly this does, you can google for bitwise operators in C++.

Arduino way is the bitSet function https://www.arduino.cc/reference/en/language/functions/bits-and-bytes/bitset/

Thanks for your answer. Do I understand correctly that the top one sets the bit to 1 and the lower one sets the bit to 0?

There is also theDisplay[3] ^= (1 << bitnumber); for toggling the bit.

@gurkensaas Yes, that is what "setting" and "clearing" means.


text:
Where to save time and other values so I can read them after arduino powered down?
I need to save some values (and be able to update them frequently) that will stay there even after powering down the Arduino. (I didn't specifically choose any board yet, but UNO or Mega will be probably best for me).
(the values will be a short time informations)

How often do you need to write? EEPROM is usually ok but has limited write cycles. I usually recommend adding an external EERAM chip like the 47C16.

About every 1 minute or so.

That frequency would kill EEPROM after about 2-3 months.

That isnt really good. What about the flash memory?

A week. Take a look at the 47C16 chip from Microchip.

It depends on how much data you want to save. If you just want to save one set of data everytime, replacing the old data, you might be able to extend the lifetime of the EEPROM significantly through wear leveling (spreading the writes over a bigger span of memory, so that the individual memory cell gets written less frequently). Thats also, what SD cards do with their flash memory. Please give us a bit more context of what you are trying to do

If the 47C16 Majenko mentioned is interesting but you want more cycles and are willing to pay for it, there are SPI FRAM chips also.  I'm not aware of any in DIP, but you can hand solder an SOIC8 to a DIP adapter if needed.  There are probably a few prefab modules kicking around also.

Personally I use FRAM, fast and unlimited read and almost unlimited writes. They are available on breakout boards for a few bucks.

You might like to search for a solution that detects a coming power loss and save only in this case. This commonly adds some hardware to your circuit. -- Instead of serial (flash) EEPROM you can also consider battery backed SRAM, available with serial interfaces. Just make sure to check and change the battery regularly.

As stated in one above comment, If same structure of datas (not "too big"), and can save not "too fast", use files saved onto SD cards with time/date as name ...


text:
Wire library causing samd21 based board to stop working
A bit of a general question, but asking in case someone has stumbled onto a similar problem before. A friend and I designed a custom PCB board based on the ATSAMD21G microprocessor. The board has a accelerometer connected on I2C and a NRF24 connected on SPI.
The rest of the functionality of the board is working as expected. My friend, who lives in a different country is able to use his copies of the board (all 5 copies were made by the same manufacturer in the same batch) without issue. But on my end, attempting to call the wire library causes loop to not execute. We wonder, if we are missing a potential software issue. We already checked that the core for the boards, the IDE and libraries are the same. And I have previously used the IDE for other wire.h based projects.

Does your board run your friend's .hex file ok?

Using J-flash (j-link programmer) I get a "cannot download file" error when I try to flash the .bin, .hex of the sketch he sent me. I will explore other options, but not sure how to flash atm. J-flash did work for flashing the bootloader.

why you don't upload over USB bootloader if you flashed it?

I wasn't aware this could be done in the IDE. Done some googling. So I should try to upload it via the command prompt, instead of j-link?

maybe try "Upload with programmer" from the Sketch menu

It turns out the microprocessor somehow got  locked when I was trying to upload the bootloader, and unable to get it fixed. I will have to let it go for now since I tried everything I could find online and couldn't unlock and erase it,


text:
Store and processing about 30000 values read in 30 seconds
I am reading an accelerometer using an esp32.

interval = 30000; (30 sec)
offsetx, offsety and offsetz are values calculated on another function which I am using to calibrate it.

If I do like this I get about 28000 readings ( value of i-1)
void reading_mpu(){
  Serial.println("Start reading mpu:");
  unsigned long StartTime = millis();

  int i = 0;

  while(1){
    unsigned long CurrentTime = millis();

    if (CurrentTime - StartTime < interval) {  //interval is 30000
      mpu.update();

      float total_acc = sqrt((pow((mpu.getAccX() - offsetx), 2) + pow((mpu.getAccY() - offsety), 2) + pow((mpu.getAccZ() - offsetz), 2) ));
      i++;
    }
    else if (CurrentTime - StartTime > interval) {
      Serial.println("Time end");
      Serial.println(i-1);
      break;
    }
  }
}

If I add before "i++"
Serial.println(total_acc);

I get around 4800 values so much less values , probably because of the time that serial print is take.
If I add before "i++"
file_acc.println(total_acc);

(try to store values in a txt file on spiffs) I get around 16700 values. Much more than on serial print but still less that what is in first try.
My project consists in calculate average and max of this array of values.
I also tried define an array to store them but esp32 is crashing (probably memory :) )
Any idea of how can I get those values (hopefully a number of values as close of 28000) stored and be able to calculate average and max ?
Thank you very much

calculating and printing are very different things.  accelerometers also need filtering (in your case max and average).  It's often pointless to store all the values.  for the max, just store the max so far.
for average consider only keeping something akin to a total or better yet- a low pass filtered value.  Then only print something for a very large number of values

You are partially right, but maybe I was not clear enough, except calculate average and max which can be done without storing them, I need to store them as well...

to store: allocate sufficient memory before even beginning the sampling.  do you need to store x,y,z, and magnitude or just that float total_acc magnitude?

What kind of processing, other than average and max, do you need to do with those values? Are you absolutely sure you need to store all the data? If you really have to store all that, and have not enough RAM, the only solution will be to find an MCU with more RAM.

You don't need to store values to know average and max. All you need is the total of all values, which you divide by the number of values, for the average, and the current max which you update if a sample exceeds it.

As sqrt() and pow() need some time, too, you might want to calculate the square by multiplication (probably faster than pow(..., 2)), and perhaps you don't need the sqrt() depending on the evaluation. However, check what you gain from this before using it in production code.


text:
Reverse engineering an i2c signal
I have an i2c device that i would like to rreverse engineer. Using the oringal master of the device here is a snapshot from the logical analyzer

I would like to replace the orginal master of the device with an arduino, the device has an interrupt pin that when detected it will do the trasaction above.
So far what i have figuerd out is the address is 0x53 (the first byte). I have also figured out by interactive with the device that the second,third, and last byte are data from the slave device.
How do i write an arduino code to simulate this transaction? Here is the code i have written and the response i got is not quite the same
#include <Wire.h>

void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Wire. setClock(100000)
  Serial.begin(9600);  // start serial for output
}

void loop() {
  Wire.requestFrom(0x53, 6);    // request 6 bytes from slave device #8

  while (Wire.available()) { // slave may send less than requested
    char c = Wire.read(); // receive a byte as character
    Serial.print(c);         // print the character
  }

  delay(500);
}

Are you sure that you should get the same answer everytime you request data from the device? And what happens with the real master before that read transaction? Often I2C devices work like "master write to tell the device what data you want to have --> master read to actually get that data". So if there is a master write cycle before the read transaction that can be important. Before trying to recreate the master with an Arduino I would try to understand the protocol. There is no easy way around that. Depending on what you expect from the device search for patterns in the data stream.

@chrisl i can assure that there is no write cycle, before each transaction or even the very first transaction during power-up. That is not difficult to check in a logic analyzer. And yes i have recorded all the possible oputs of the device( there are 11). Its just keeps reapting with the only different thing is the second,third, and last byte depending how you interact with the device. How do i add a bit of delay between each byte?

For introducing a delay you would need to change the Wire library. Though I doubt that this would help. The delay is introduced by the master (since if the slave would do the clock stretching here the Arduino couldn't overcome this). Why would the slave need it? It perfectly works in the communication. In I2C when the slave is too slow for the master the communication normally totally breaks apart, mostly resulting in a blocked I2C bus. Also you can see in the first picture, that the slave is releasing SDA line right after the acknowledgement pulse. That suggest, that it isn't too slow.

Customised Protocol
As has been mentioned in the comments, it may be that the controller and target are communicating using a customised protocol for which you will need to modify the Wire library and/or the TWI library.
Modifying the TWI library is not easy because it uses a very convoluted mixture of ISR code and non-ISR polling code.
I've re-written the TWI library so that you can use standard burst-read and burst-write protocols in either ISR mode or polling mode, or build your own protocol using building-block functions. It uses the watchdog timer to detect timeouts when the bus freezes due to an error.
Terminology
The terminology of my TWI library conforms to NXP Semiconductors recently released v7 of the I2C-bus specification which has:

Updated the terms "master/slave" to "controller/target" throughout to align with MIPI I3C specification and NXP's Inclusive Language Project


text:
RTClib.h problem
In Library Manager RTClib and DS3231 work somehow with older versions. RTC time can picked only once and then it give bullshit. Using newest versions screen is empty.
In picture first time is right, others no.
Problem occurs, when loading new driver versions.Earlier code  have been working for years. Sure driver problem ....?

so, what is your question?

More likely a bug in an earlier RTCLib version masked a bug in your code. The two kind of cancelled out. Now the bug (or "feature") has been fixed it's exposed the bug in your code.

Putting last version 1.14.0 of RTClib do not help. Simple call " DateTime now = rtc.now();  " works only one time; thats my question.

Thanks for kind help, problem nearly solved: IR remote and DS3231 clock don't live well in nano board, maybe still a bug in drivers.

@PetriHietala Putting last version 1.14.0 of RTClib do not help. Simple call " DateTime now = rtc.now(); " works only one time; is not a question ... it is a description of the observed behavior .... a question is something like how can I debug the problem? or where can I get the source code for the library? or what is the color of grass?


text:
Getting location working on SIM800L with TinyGSM?
Hey Arduino enthusiasts :)
I have purchased a LilyGo T-Call board. Which has a Esp32 processor and a SIM800L GSM module. For my project i want to send location data over the 2G cellular network. I am using the TinyGSM library for communicating with the GSM module, and it is working great so far. Communications with the modem, and sending SMS and cellular data is working correctly.
The challenge i am facing is retrieving the location data using the GSM network. In theory this should work fine. My module supports it as well as TinyGSM. But i just cannot seem to get a fix on the location. Running the example script allFunctions link with only gprs and GSM location test running I get the attached at logs. I have naturally read the TinyGSM readme and followed their troubleshooting section.
In my research i found some relevant resources. This github issue states the same problem, and with the exact same board. His problem however was about not getting SSL working which i do not need for my project. And from his AT logs you also see him getting a location after a little while. This SIM800L datasheet documents the CLBS AT command. What i understood from it is that I am getting the <locationcode> = 3 response which should be a NET error. But that does not really tell me much. There is also this TinyGSM gitter chat for the library.
I feel really lost here, so any help would be gladly appreciated :)

cannot seem to get a fix ... what does "seem to" mean? ... please describe the problem in detail, including a description of the data you expect and the data you actually get

You describe someone else's problem more than the problem you are facing, you provide nothing than "cannot seem to get a fix". TinyGSM behind the scene set the timeout for 2 minutes for querying GSM Location, and done twice (one for getting a String, another for getting a struct) in AlluFunction example, if all done right and you still don't get the location, you might want to check with your carrier whether the network support the feature or not. Not all the features that the module supported get supported by the carrier network, some need extra subscription fee.

BTW, GSM Location is Cell-based LBS, it does get a "fix" like GPS. It uses the cell-tower fingerprints that your module could "see" to querying a database to get back a lat,lng with accuracy of +/-500m.

thank you guys for comments. do you suggest i create a new more detailed post or should i edit this post?


text:
UNO's Internal EEPROM "read" returns incorrect values when it precedes "write"
I am an Arduino instructor and I was preparing some material on the utilization of the Arduino UNO's internal EEPROM when I encountered a problem.
The problem is, I am trying to show the original value on a specific EEPROM location using the EEPROM.read function, then I do write a new value to that location using the EEPROM.write function and try reading it again, please take a look at its code, I use the Serial Monitor to print those values.
#include <EEPROM.h>

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

  // Print to the Serial Monitor the value read from address 20. "Which should be 255"
  Serial.println(EEPROM.read(20));
  // Write to the EEPROM the value 143 in address 20.
  EEPROM.write(20, 143);
  // Print to the Serial Monitor the value read from address 20. "Which should be 143"
  Serial.println(EEPROM.read(20));
}

void loop() {

}

Now I have verified already that this location has a value of 255 using another sketch which basically does nothing but print the contents of the EEPROM on the Serial Monitor.
#include <EEPROM.h>

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

  for(int i = 0; i < 1024;i++)
  {
    Serial.print("Address: ");
    Serial.print(i);
    Serial.print(", Value: ");
    Serial.println(EEPROM.read(i));
  }

}

void loop() {

}

Now what is my problem?
My problem is in my first sketch, the EEPROM.read function does not return 255, instead it returns the value 143 which is not even supposed to be there until the next instruction.
I know the EEPROM.write takes around 3.3ms and the writing is what wears down the EEPROM cell, but I also do know that reading takes approximately 0ms and does not wear down the EEPROM cell.
Even though that in mind, I have deliberately placed a "delay(100);" after reading, still no result.
#include <EEPROM.h>

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

  // Print to the Serial Monitor the value read from address 20. "Which should be 255"
  Serial.println(EEPROM.read(20));
  delay(100);
  // Write to the EEPROM the value 143 in address 20.
  EEPROM.write(20, 143);
  // Print to the Serial Monitor the value read from address 20. "Which should be 143"
  Serial.println(EEPROM.read(20));
}

void loop() {

}

Further more, when I remove the EEPROM.write completely from the code and utilize the EEPROM.read only, I do read correct results, but of-course I do change the address as well to test it.
My setup is:
Windows 10 Pro 64-bit.
Arduino IDE 1.8.15
Arduino UNO china clone version. (not SMD)
My question is, what am I doing wrong here?
Do I have an invalid understanding of something around here?
I have worked with EEPROMs before (both internal and external) using PIC18F microcontrollers, so my experience (which may be incorrect) yields that this sketch should work perfectly.
Thank you in advance.

Try adding delay(5000); at the start of setup. What I think happens is; You upload your code. After uploading the code will run immediately. Then you open the serial console. Opening the serial console resets the Arduino. So now the code runs a second time, and will display the already written EEPROM data.

Excellent interpretation, but since I am not new into this I don't ever close my serial console so not to reset the Arduino, it is always open even before uploading the code, however I tried it, and it indeed worked.
But why?

The Arduino IDE suspends the serial connection while uploading, and then resumes when done. It looks like they added some delay before reopening the serial connection. So it looks like you code will run twice, even when you keep the Serial Console open.

Thank you so much for your clarification and your time.

This is NOT my answer, this is the answer of @Gerben, thank you.
The Arduino IDE suspends the serial connection while uploading, and then resumes when done. It looks like they added some delay before reopening the serial connection. So it looks like your code will run twice, even when you keep the Serial Console open

@Gerben should answer this. Your task is to accept his answer.

I agree, if he posts an answer I will definitely accept his, that's why I did not accept my answer.

Per the documentation at:https://www.arduino.cc/en/Reference/EEPROMWrite   An EEPROM write takes 3.3 ms to complete. What tells us is you must give it that amount of time or more to complete the operation. Insert your delay after "EEPROM.write(20, 143);" of at least 3.3 ms or delay(3300);. That should resolve your problem. You can also use that to have your students read the manual. Present as a problem so they can try to solve it. Once you get caught by it (we all have) you never forget.

Read the question more carefully. The issue is about the EEPROM.read() that happens before EEPROM.write(). Adding a delay after EEPROM.write() won't change anything.


text:
Help needed with I2C LCD + Arduino - DS-LCDD5
I am new to this forum and a relative beginner to Arduino (software wise) Have built many projects, but always just copy/paste/modify example code.
I found a couple of these modules (a PIC18 daughter board on the back of a common 16x2 LCD)
It says in the data sheet that it can be controlled via I2C, but my skill level is too low to figure out how to do it.
Can somebody please give me advice on how to proceed?
The "I2C Scanner" sketch identifies it at address  0x14 , but the usual I2C-LCD libraries don't work on it.
I use it with an Arduino UNO, SDA(A4), SCL(A5), 1k8 pullup resistors on each.
The module is working 100% with the 1 wire serial method as per the manual.
This is how I think it should work, but it does nothing:

// Include Arduino Wire library for I2C
#include <Wire.h>

// Define Slave I2C Address
#define SLAVE_ADDR 0x14   // 7bit address = 0010100D, 0x14 hex

void setup () {

 Wire.begin();                           // Initialize I2C communications as Master

  // Write something to the Slave
 Wire.beginTransmission(0x14);           //  0x14  (SLAVE_ADDR)  0010100
  Wire.write(0x28);                       //  00101000
  Wire.write(0x00);                      //  Register address  "0"
  Wire.write("A");                       //  some text
  Wire.endTransmission();

 }

void loop () {

}

Link to manual: http://www.i-lcd.com/PDFs/Drivers/Technical%20data%20on%20DS-LCDD5%20Interface%20Module%20(IDS).pdf

Try leaving out the Wire.write(0x28);.

If the leads are not long go to something in the 3.3 to 4.7K range. In my opinion there is a problem with the I2C libraries, they are not all compatible.  I found one that works and I put it in the folder with my sketch. Since doing that I have nad no more I2C-LCD problems.

Data sheet or firmware is wrong.
See this for solution:  https://forum.arduino.cc/t/need-help-with-i2c-code-for-a-16x2-lcd-ds-lcdd5/918289/28?u=jdev99
Thank you for all advice.
Joe

So, after I "remembered" that I have an oscilloscope, I hooked it up and noticed that I don't receive an "acknowledge" from the module.
Then I played around with the clock speed, and found I do get an "acknowledge" if I set it between 16000kHz and 18000kHz with the "Wire.setClock" command. :thinking:
Then by mere coincidence, I found that text must got to R1 NOT R0 and control commands to R2 NOT R1. :grimacing:
But I could not get any of the RGB commands to work.
I tried this on all 6 of the modules which I have, same results.
I will just stick to serial comms when I need to use any of these.
So, either the datasheet is wrong or the firmware in the module is flawed.
At least I learned a lot about the workings of I2C in the process, which my goal was.
https://forum.arduino.cc/t/need-help-with-i2c-code-for-a-16x2-lcd-ds-lcdd5/918289/28?u=jdev99
Thank you for all advice.
Joe
Working code:
'''
// Include Arduino Wire library for I2C
#include <Wire.h>
// Define Slave I2C Address
#define SLAVE_ADDR 0x14                      // 7bit address = 0010100D, 0x14h
void setup () {
Wire.begin();                                    // Initialize I2C communications as Master
Wire.setClock(16000);                            // only 16000 - 18000 work
//Clear display
Wire.beginTransmission(0x14);
Wire.write(0x02);
Wire.write(0x01);
Wire.endTransmission();
}
void loop () {
//Start print on line1, pos1
Wire.beginTransmission(0x14);
Wire.write(0x02);
Wire.write(128);
Wire.endTransmission();
// Write something to the Slave
Wire.beginTransmission(0x14);                       //  0x14  (SLAVE_ADDR)  0010100
Wire.write(0x01);                                   //  Register address  "0"
Wire.write("ABCDEFGHIJKLMNOP");                     //  some text
Wire.endTransmission();
delay(3000);
//Clear display
Wire.beginTransmission(0x14);
Wire.write(0x02);
Wire.write(0x01);
Wire.endTransmission();
//Start print on line2, pos1
Wire.beginTransmission(0x14);
Wire.write(0x02);
Wire.write(192);
Wire.endTransmission();
// Write something to the Slave
Wire.beginTransmission(0x14);
Wire.write(0x01);
Wire.write("1234567890-=+*/@");
Wire.endTransmission();
delay(3000);
//Clear display
Wire.beginTransmission(0x14);
Wire.write(0x02);
Wire.write(0x01);
Wire.endTransmission();
}
'''

Try Replacing the "A" to single quotes 'a'
Wire.write('A');
or
Wire.write(0x41);
you can also try and add (byte) before the hex value:
Wire.write((byte)0x28);


text:
FastLED and Adafruit Gemma M0 - Getting started
I just bought a Gemma M0 and I'm trying to use it with FastLED. There are several forums that discuss the same errors I get when I try to upload my code, but they all involve editing .h files, something I'm not comfortable doing without understanding the reason behind the change. Is there a place where I can get a basic starting point for using FastLED with the Gemma M0?
I tried the Quick Example in the FastLED Overview:
#include "FastLED.h" CRGB leds[1];

void setup() {
  FastLED.addLeds<NEOPIXEL, 6>(leds, 1); }

void loop() {
  leds[0] = CRGB::White; FastLED.show(); delay(30);
  leds[0] = CRGB::Black; FastLED.show(); delay(30); }

and I get these errors:
Arduino: 1.8.13 (Mac OS X), Board: "Adafruit Gemma M0, Small (-Os) (standard), Arduino, Off"

In file included from /Users/jaireaux/Documents/Arduino/blink/blink.ino:1:
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:14:21: note: #pragma message: FastLED version 3.004.000
   14 | #    pragma message "FastLED version 3.004.000"
      |                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:65,
                 from /Users/jaireaux/Documents/Arduino/blink/blink.ino:1:
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/fastspi.h:135:23: note: #pragma message: No hardware SPI pins defined.  All SPI access will default to bitbanged output
  135 | #      pragma message "No hardware SPI pins defined.  All SPI access will default to bitbanged output"
      |                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:48,
                 from /Users/jaireaux/Documents/Arduino/blink/blink.ino:1:
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/fastpin.h: In instantiation of 'class FastPin<6>':
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/fastpin.h:242:29:   required from 'class FastPinBB<6>'
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/platforms/arm/d21/clockless_arm_d21.h:10:54:   required from 'class ClocklessController<6, 12, 30, 18, GRB, 0, false, 50>'
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/chipsets.h:578:7:   required from 'class WS2812Controller800Khz<6, GRB>'
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:92:34:   required from 'class NEOPIXEL<6>'
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/FastLED.h:314:28:   required from 'static CLEDController& CFastLED::addLeds(CRGB*, int, int) [with CHIPSET = NEOPIXEL; unsigned char DATA_PIN = 6]'
/Users/jaireaux/Documents/Arduino/blink/blink.ino:4:60:   required from here
/Users/jaireaux/Documents/Arduino/libraries/FastLED/src/fastpin.h:210:24: error: static assertion failed: Invalid pin specified
  210 |  static_assert(validpin(), "Invalid pin specified");
      |                ~~~~~~~~^~
exit status 1
Error compiling for board Adafruit Gemma M0.

Thanks in advance for your help.

starting point... example code in the arduino IDE

The Arduino IDE Examples don’t cover the difference between types of hardware.

The Gemma does not have a pin 6. FastLED.addLeds<NEOPIXEL, 6>(leds, 1); I changed to pin 2 and it works. FastLED.addLeds<NEOPIXEL, 2>(leds, 1);


text:
Correct usage of SPI with ISR
My Arduino needs to do:

Run ISR as many times as possible/ as fast as possible.
Occasionally receive data over I2C.
Output data over SPI in ISR.

My question is regarding SPI and ISR.
The documentation about SPI I found, was quite poor.
SPI.beginTransaction(SPISettings(16000000, MSBFIRST, SPI_MODE0));
SPI.usingInterrupt(255);
SPI.begin();

void isr_function()
        SPI.transfer(data);
        pulse_latch();
};

Is this the correct use of SPI in my case?
Can it be faster?

The SPI library function; transfer is blocking. If you really need some additional cpu cycles, you can send the data between ISR calls instead. The SPI hardware can send the data while the CPU is doing something useful, instead of waiting for the SPI transfer to finish. You would then latch the data at the beginning of (the next) ISR.

PS You can't run SPI at 16Mhz on a Nano. The maximum speed is F_CPU/2, if I remember correctly, which would be 8MHz

If you need to push a lot of data quickly through SPI, it's a lot more convenient to use a micro with a SPI peripheral that supports DMA. Most likely the ARM-based arduinos will fit the bill.

It is actually fairly easy just to use the SPI peripheral without using the arduino libraries. The attached functions could be used to send a number of bytes through the SPI with one call: (Assuming ATMEGA328)
#include <avr/io.h>
#include <avr/interrupt.h>

static unsigned char spiCnt, *userBufr;

/* Call this function during setup */
void SpiInit (void)
    {
    PPR &= ~0x04;   // Be sure the SPI has power
    DDRB |= 4;      // Be sure SS signal on PORTB bit 2 is output
    SPCR = 0x50;    // Turn SPI on, maximum CLK rate
    }

/* Call this function to initiate the multi-byte send */
void SpiWrite (void *data, unsigned char bytCnt)
    {
    /* Save the the caller's messsage information */
    userBufr = data;
    spiCnt = bytCnt;

    /* Enable the SPI device, send first byte */
    SPCR |= 0x40;           // Enable SPI
    SPDR = *userBufr++;     // Send the first byte
    SPCR |= 0x80;           // Enable interrupts
    }

/* Call this one to be sure the message is finished */
int SpiIsDone (void)
    {
    /* Non-zero when operation is finished */
    return ( ! (SPCR & 0x80));
    }

/* Stay out of this one */
ISR (SPI_STC_vect)
    {
    /* Check the remaining number of bytes to send */
    if (--spiCnt)
        SPDR = *userBufr++;     // Send the next byte

    /* Operation is finished, shut down SPI */
    else
        SPCR &= ~0x80;  // Disable interrupts for SPI
    }


text:
Can a sensor have multiple I2C addresses?
So I'm having a weird issue with a TCA9548A multiplexer. When I run the scanning code given on the adafruit website, I get the following result:
TCAScanner ready!
TCA Port #0
TCA Port #1
TCA Port #2
Found I2C 0x0
Found I2C 0x44
TCA Port #3
TCA Port #4
TCA Port #5
TCA Port #6
TCA Port #7
done
And I suppose my question is, how is it possible that a device has two I2C addresses? I know for certain the address should be 0x44 but what does the 0x0 mean? and equally bizarre is that that sensor doesn't output numerical values when called. The sensor works perfectly when connected directly to an Arduino Mega 2560, but I can't get it to function with the multiplexer.

You are right that there's something wrong here. 0x0 is not a valid address for an I2C device. Maybe you should share the code that you use to do the scan.

Of course a device can have multiple addresses, theoretically. It's just a matter of comparing the received address with expected addresses, and acknowledging if one of them matches. Think about a microcontroller emulating multiple I²C chips. -- However, I don't think that a single chip exists that works like this. -- 0x00 belongs to the reserved addresses.

Can you link to the scanning code? The address 0x00 is the general call address. You can address every device on the bus with it (only master write, no master read transaction). Often these scanning codes only check for the acknowledgement after the address byte. For the general call address the protocol states that the devices on the bus all can acknowledge when receive a general call transaction. So seeing the address 0x00 does not by itself mean that something is wrong. And the standard I2C scanner doesn't even use 0x00 as address.

Some people consider I2C devices' read- and write-header as two separate addresses. I2C addresses are usually 7-bit plus one read/write bit. If all those 256 addresses are scanned, a device would acknowledge on 2 addresses.


text:
Store files in AT45DB161D SPI chip to use them from arduino
I am new to this concept but I am wondering if it is possible to store some files on the AT45DB161D dataflash chip. these files must be read by Arduino. I know that I should use a file system and I saw the FatFs library but I don't have any idea how to do that with my Arduino nano.
is it possible to format the chip with Arduino and store files on it?
thank you in advance for your help and sorry about the obvious mistakes.

It's just a flash chip. Sure, you could run some form of filesystem on it, but that's rarely done in a small MCU environment. Just treat it like a block of memory (EEPROM) and store things at specific addresses. What kind of data do you want to store, anyway?

.text , .css , .html files
like the SPIFFS on esp32
how can I store these types of files at specific addresses?
can you explain a bit more.

There's many ways you could do it. For that sort of data a filesystem would be a simpler interface, sure. I assume you're wanting to run a web server on the Nano?

I am gonna do it on mega. but currently, I don't have access to one.
sorry, but can you provide me with some examples or documentations to implement the file system format?

You would probably take the FatFS library and write a "driver" for your flash chip. The FatFS system is modular and allows you to add drivers for new devices reasonably simply (well, simply for an experienced embedded programmer).


text:
How to change brightness of LED light?
I'm trying to change the brightness of an LED light with RGB. I can change the brightness of simple colors like red, green, and blue. But I'm not sure how to change brightness of colors like purple, turquoise, and yellow green.

When it comes to adjusting the brightness of red, green, and blue. I have tried changing the values inside colorRGB().
With colorRGB():
int redPin = 9;
int greenPin = 10;
int bluePin = 11;

void setup(){
    pinMode(redPin, OUTPUT);
    delay(500);
    pinMode(greenPin, OUTPUT);
    delay(500);
    pinMode(bluePin, OUTPUT);
    delay(500);
}
void loop(){
    colorRGB(255, 0, 0); //Brightness level 255
    colorRGB(150, 0, 0); //Brightness level 150
    colorRGB(50, 0, 0); //Brightness level 50
}
void colorRGB(int red, int green, int blue){
    analogWrite(redPin, red);
    analogWrite(greenPin, green);
    analogWrite(bluePin, blue);
}

I have also tried using analogWrite(), however it needs the pin as one of its arguments so I'm not quite sure how to connect that with the already set up colors inside void loop(){}.

To change the brightness of any RGB color you need to multiply each color component by the brightness ratio. Lets look at some examples:

Red is 255,0,0 in RGB. Full brightness is represented by 1, half brightness by 0.5, quarter brightness by 0.25 and so on. So we get the following values (we are doing integer calculations, so cutting away any decimal digits):

half brightness: 255*0.5,0*0.5,0*0.5 --> 127,0,0
quarter brightness: 255*0.25,0*0.25,0*0.25 --> 63,0,0

Yellow is the combination of red and green, so 255,255,0. Doing the same math as above we get:

half brightness: 255*0.5,255*0.5,0*0.5 --> 127,127,0
quarter brightness: 255*0.25,255*0.25,0*0.25 --> 63,63,0

Cyan is the combination of red green and half blue, so 255,255,127. Doing the same math as above we get:

half brightness: 255*0.5,255*0.5,127*0.5 --> 127,127,63
quarter brightness: 255*0.25,255*0.25,127*0.25 --> 63,63,31

So you can change your function to include a brightness parameter:
void colorRGB(int red, int green, int blue, int brightness_percent){
    analogWrite(redPin, red*brightness_percent/100);
    analogWrite(greenPin, green*brightness_percent/100);
    analogWrite(bluePin, blue*brightness_percent/100);
}

Here I used not the value range from 0 to 1 but instead in percent from 0 to 100. This is because floating point operations on Arduinos are rather time intensive (because the Arduino has no hardware for that and needs to do all that in software) so its better to multiply by the percent value and then divide by 100. So we have only integer calculations which is way faster. The outcome is the same.
Note: As the the color components get in the lower values you might see color errors due to the quantification. Though normally RGB LEDs aren't really color accurate either so probably you won't notice.

Thank you so much. I was actually thinking about manually converting it with percentages or fractions in relation to the brightness, but I thought I would be wrong. Thank you very much once again.

I just created a simple simulation for the nice answer written.
Here is the code:
int redPin = 9;
int greenPin = 10;
int bluePin = 11;

void setup() {
  pinMode(redPin, OUTPUT);
  delay(500);
  pinMode(greenPin, OUTPUT);
  delay(500);
  pinMode(bluePin, OUTPUT);
  delay(500);
}
void loop() {
  colorRGB(255, 0, 0, 100); //Brightness level 100%
  delay(3000);
  colorRGB(255, 0, 0, 25); //Brightness level 25%
  delay(3000);

  colorRGB(255, 255, 0, 100); //Brightness level 100%
  delay(3000);
  colorRGB(255, 255, 0, 25); //Brightness level 25%
  delay(3000);

  colorRGB(255, 255, 127, 100); //Brightness level 100%
  delay(3000);
  colorRGB(255, 255, 127, 25); //Brightness level 25%
  delay(3000);
}
void colorRGB(int red, int green, int blue, int brightness_percent) {
  analogWrite(redPin, red * brightness_percent / 100);
  analogWrite(greenPin, green * brightness_percent / 100);
  analogWrite(bluePin, blue * brightness_percent / 100);

}

i hope this is helpful. I am from the Wokwi team and I will welcome all your questions.
You can have a look at the Wokwi Arduino simulation link here:
https://wokwi.com/arduino/projects/313797447551812161


text:
Hello, Please can someone assist me with in checking my code?..I try to generate a high freq signal (at least 150KHz) with Arduino Mega, CTC Mode
void setup() {
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  TCCR2A = TCCR2A & B01010000 | B00000010 ; // CTC mode activated, Toggle OC2A
  TCCR2B = TCCR2B & B11110000 | B00000001;//Prescaller set
  TCNT2=0;//Start Counting ffrom 0
  OCR2A=127;//Set TOP value)

}

void loop() {

}

It may not be strictly necessary, but it would probably good to say what you're seeing instead of the expected signal.

TCCR2A = TCCR2A & B01010000 | B00000010 ; // CTC mode activated, Toggle OC2A

What you have here clears TCCR2A's COM2A1 but preserves its original COM2A0.
When I print out TCCR2A prior to modification, I see a value of 0x01 (COM2A is 0; both bits of it).
Printing out TCCR2A after you've manipulated it 0x02.  So, in TCCR2A, you
are winding up with zeros for your COM2A1 and COM2A0 bits, which is all
cases is "Normal port operation; OC2A disconnected".  That is, you're not going
to see whatever signal you might otherwise have configured to generate because
it just hasn't been routed to the (Arduino pin 10)/(gpio PB4)/OC2A
It's usually better to not rely on the bootloader and the start code and the
Arduino core to have left a hardware register in a particular state.
The following is probably closer to what you intended:
TCCR2A = B01010000 | B00000010 ; // CTC mode activated, Toggle OC2A

It's still not entirely correct to the problem description (not the correct frequency), but it does send a signal out of the Arduino MEGA's digital pin 10.  It also is configured to toggle OC2B, so unless you wanted that:
TCCR2A = B01000000 | B00000010 ; // CTC mode activated, Toggle OC2A

This can be made more readable by using the bit field names for the given:
TCCR2A =
      (1 << COM2A0)  // CTC mode activated (note COM2A1 is zero)
    | (2 <<  WGM20); // lower two bits of WGM value 2

You can do this same sort of thing for TCCR2B. And likewise, it is best that you don't rely on the previous value of TCCR2B.
With OCR2A = 127;, you are toggling (reaching a half-period) every 128/16,000,000 seconds, or a 8 uS half-period, for a 16 uS period. Generating 62.5 KHz, which is below your target 150 KHz.  Knowing it's half-periods, an OCR2A of 63 gets you to 125 KHz.
An OCR2A of 52 or less gets you into the greater than 150 kHz range, at least if we take your 16 MHz clock rate very seriously. You might need to be a little lower to be sure.


text:
Libraries are not linked
I created 4 libraries, each in .h and .cpp files, and tested them individually. I kept the project flexibility by defining 3 flags that allow or disallow the usage of the libraries.
When integrating them into project I received linking errors.
During the debugging I reduced it to minimum - a single .ino file that contains the minimal declarations and calls; but the error messages are still fired.
I looked at the shrunk code (only 63 lines!) and saw no issue. I'd appreciate any help in finding the issue.

The code:
#define RadioIncluded
#define IrrigationStation
#define RTCincluded

/********************************************/

#ifdef RTCincluded
  class rtcHighLevel
  {
    public:
      String rtcInterpreter(String cmd);
  };
  rtcHighLevel rtc;
#endif

#ifdef IrrigationStation
class measureEC
{
  public:
  void   initMeasurementStation ();
    String SD12_Parser (String commandLine);
};
  measureEC soilParams;

class valveControl
{
  public:
    void   valveInit();
};
  valveControl valve;
#endif

#ifdef RadioIncluded
  class LoRaAddClass
  {
    public:
      void   LoRaBegin(long BAND);
  };
  LoRaAddClass LoRaAdd;
#endif

/*********************************************************/
void setup() {
  Serial.begin(9600);
  while (!Serial) {};

#ifdef RadioIncluded
  LoRaAdd.LoRaBegin(915000000);
#endif

#ifdef IrrigationStation
  valve.valveInit();
  soilParams.initMeasurementStation();
#endif

#ifdef RTCincluded
  String s = rtc.rtcInterpreter("A");
#endif
}
/*********************************************************/
void loop() {}

I see no code there for the functions, so of course it's not going to compile, and complain about there being no code for those functions.

If you had problems with the conditional code surrounding your declarations and class definitions in your header, you would receive an error from the compiler proper. That is, you'd get an error about something undeclared or undefined before linking rather than an unresolved symbol at linking. You're going to have to show more of the build output, ideally not as an image, and perhaps the .cpp file content as well.

I second Majenkos comment: You have the declaration of member functions in the declarations of your classes, but you never actually provide an implementation of those functions. You need to provide at least an empty implementation.

Linking to a library is another beast than separating your sketch into multiple source files. Please make clear what you want to do, and you might want to read relevant chapters about this in the documentation and/or Arduino forum. -- Commonly it is a sign of misunderstanding how libraries work, if you have preprocessor instructions like these conditionals. You might want to learn about the real concept before you try to go on. But as a primitive solution for a simple sItuation it might be OK, however, learn the Right Way as soon as possible. ;-)

Thank you very much for your constructive comments. Although I built some Arduino small sketches I never wrote such a project. First - the correct terminology I should have used is classes rather than libraries. Secondly, according to Majenko and chrisl, I added some lines of codes to every class declaration, and the errors disappeared. So I proceeded to adding the classes by including them.

The result was disappointing - linking errors. So I shrunk the classes to minimum and focused on the RTC and radio classes.. What I found is that: no errors when using the locally declared classes or when using the radio class only. Using the RTC class alone or together with the radio class causes error linkage.

#define RadioIncluded
#define RTCincluded
#ifdef RTCincluded
#include "RTC3231/rtcDS3231HighLevel.h"
/class rtcHighLevel
{
public:
String rtcInterpreter(String cmd) {return cmd;};
};/
rtcHighLevel rtc;
#endif
/***************************************/
#ifdef RadioIncluded
#define LoPowerLevel            5
#define HiPowerLevel            20
#include "communications/LoRaAdd.h"
/class LoRaAddClass
{
public:
void   LoRaBegin(long BAND) {long x = BAND;};
};/
//LoRaAddClass LoRaAdd;
#endif

Solved: while initially I devoted sub-directory for every class, no issues when all the classes were brought to the same folder with the INO file all the issues disappeared. Is this a known issue?

https://arduino.github.io/arduino-cli/0.19/sketch-specification/


text:
Modifying the neopixel rainbow function to work with 4pins
So my setup is i have strips that is separated into 4 pins and would like to modify this rainbow function from the neopixel so that it will work on 4 separate strip that are on 4 separate pins. I would like to look like strip number 2 is a continuation of strip number 1 and number 3 is to 2 and number 4 is to 3. A very cool feature about this function is the start and end is a continuation so this mean i basically have a ring setup.
void rainbow(int wait) {
  // Hue of first pixel runs 5 complete loops through the color wheel.
  // Color wheel has a range of 65536 but it's OK if we roll over, so
  // just count from 0 to 5*65536. Adding 256 to firstPixelHue each time
  // means we'll make 5*65536/256 = 1280 passes through this outer loop:
  for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
    for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
      // Offset pixel hue by an amount to make one full revolution of the
      // color wheel (range of 65536) along the length of the strip
      // (strip.numPixels() steps):
      int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
      // strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or
      // optionally add saturation and value (brightness) (each 0 to 255).
      // Here we're using just the single-argument hue variant. The result
      // is passed through strip.gamma32() to provide 'truer' colors
      // before assigning to each pixel:
      strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
    }
    strip.show(); // Update strip with new contents
    delay(wait);  // Pause for a moment
  }
}

I do not understand how hue and gamma works so it a bit more tricky for me to modify this function.
Here is my attempt but my attempt is so crude and hoggs so much memory
void rainbow(int wait) {

  unsigned int totalPixelCount = strip1.numPixels() + strip2.numPixels() + strip3.numPixels() + strip4.numPixels();
  uint32_t pixelHueList [totalPixelCount];
  for (long firstPixelHue = 0; firstPixelHue < 5 * 65536; firstPixelHue += 256) {
    for (int i = 0; i < totalPixelCount; i++) {
      int pixelHue = firstPixelHue + (i * 65536L / totalPixelCount);
      pixelHueList[i] = strip1.gamma32(strip1.ColorHSV(pixelHue));
    }

    unsigned int j = 0;
    for (j = j; j < strip1.numPixels(); j++)
      strip1.setPixelColor(j,pixelHueList[j]);
    for (j = j; j < strip1.numPixels() + strip2.numPixels(); j++)
      strip2.setPixelColor(j,pixelHueList[j]);
    for (j = j; j < strip1.numPixels() + strip2.numPixels() + strip3.numPixels(); j++)
      strip3.setPixelColor(j,pixelHueList[j]);
    for (j = j; j < strip1.numPixels() + strip2.numPixels() + strip3.numPixels() + strip3.numPixels(); j++)
      strip3.setPixelColor(j,pixelHueList[j]);

    strip1.show();
    strip2.show();
    strip3.show();
    strip4.show();
    delay(wait);
  }
}

Is there a way to make it more efficient?

"unsinged" compiles?

Doesn't setPixelColor() also need the index of the LED as parameter?

Ok, your code cannot compile due to some syntax errors. Also you don't need to build up an array first. You are iterating through the LEDs either way, so you can just calculare the needed values right there without saving them in an array inbetweeen. When I'm at my PC again I can write you an answer (if nobody is faster)

@chrisl Apologies i have fixed the syntaxes :) . I am still commuting going home so i just actually wrote the code here.

You still have a sytax error with the line pixelHueList[i] = (i, strip1.gamma32(. I will look again at your question tomorrow. In my country its now time to go to bed :)

@chrisl Sure ! i will wait for it :)

Why not make 1 (extended) string out of all 4 NeoPixels strings and control them via 1 single pin with much simpler code?

Currently you are first filling an array with values from a calcuation by going through all LEDs; and then you are again going through all LEDs to actually set them. You can do that in one step. Also your current code will most likely not work, since you just count from zero to the total number of LEDs, but the individual strip doesn't know of that much LEDs. That will get you in problems with everything after the first for loop where you set the LEDs.
For doing it in one step and simultaneously solve the problem:
void rainbow(int wait) {
  for (long firstPixelHue = 0; firstPixelHue < 5 * 65536L; firstPixelHue += 256) {
    int j = 0;
    for (int i = 0; i < strip1.numPixels(); i++){
      int pixelHue = firstPixelHue + ((j+i) * 65536L / totalPixelCount);
      strip1.setPixelColor(i,strip1.gamma32(strip1.ColorHSV(pixelHue)));
    }
    j = strip1.numPixels();
    for (int i = 0; i < strip2.numPixels(); i++){
      int pixelHue = firstPixelHue + ((j+i) * 65536L / totalPixelCount);
      strip2.setPixelColor(i,strip1.gamma32(strip1.ColorHSV(pixelHue)));
    }
    j += strip2.numPixels();
    for (int i = 0; i < strip3.numPixels(); i++){
      int pixelHue = firstPixelHue + ((j+i) * 65536L / totalPixelCount);
      strip3.setPixelColor(i,strip1.gamma32(strip1.ColorHSV(pixelHue)));
    }
    j += strip3.numPixels();
    for (int i = 0; i < strip4.numPixels(); i++){
      int pixelHue = firstPixelHue + ((j+i) * 65536L / totalPixelCount);
      strip3.setPixelColor(i,strip1.gamma32(strip1.ColorHSV(pixelHue)));
    }

    strip1.show();
    strip2.show();
    strip3.show();
    strip4.show();
    delay(wait);
  }
}

Here I used j as an index over the whole chain of LED strips and i as an index for the individual LED strip. So j is the index starting point of each strip. The calcuation of the hue is then done with the current total index (j as the offset of the current strip in the whole chain and i as the index of the current LED in the current strip) j+i. For actually setting the corresponding LED we use i as the index of the current LED in the current strip.
This solution eliminates the need for creating an additional array. Though it still can be optimized (mostly in terms of code structure). I will leave that to you if you really want to optimize further.
Note: I haven't tested the above code, nor did I compile it.

Hello ! Sorry for the long reply had to deal with something. I will try this out.


text:
what is the maximum number of servo motors that can be connected to a l293d motor shield?
I have a requirement in which I need to run 2 motors and 6 servos.
The motors and servos won't be running simultaneously at any given time.
what best can I use. I Was hoping to use l293d shield as it powers 2 DC motors and 2 servos, but how do I get other 4 running too ?
I'm aware that l293d shield has 2 free pins pin2 and pin13 that I leverage for signal pins for servo. (am I right in this ?, if so, i'll still need 2 more free pins for signal)

Please provide a link to the shield that you are using.

2 DC motors with 1 H bridge each need 6 pins in total (each motor 2 direction pins and 1 enable pin). I don't know what shield you are using, but in principle that would leave you with plenty of pins to connect your two servos. Though if the shield connects the enable pins (which are typically driven with PWM) to pins 9 or 10 the servo library would interfere with that. Then you would need a servo library, that uses the other hardware Timer

The servo motors I know don't require an h-bridge. Do you want to change their polarity or what's the purpose of the L293d?

Sorry, an image (which is unfortunately also in bad quality) is not really enough. Better would be a link to the actual product page where you bought it. I'm particularly interested in the pin connections of the shield (I mean which component of the shield is connected to which Arduino pin). That will tell you which pins are still free.

Bought it from an hobby store.
Attaching a link which I feel could be helpful.
https://robojax.com/learn/arduino/robojax_L293D_motor_shield_manual.pdf
Adafruit is the actual owner.
https://cdn-learn.adafruit.com/downloads/pdf/adafruit-motor-shield.pdf
I haven't been through their manual though.
(As it is difficult for me to understand electronics and schematics).

Do you think the best way would be,
Use a l293D H-Bridge and servos connected to arduino directly ?
In that case how would the power source be connected ?

As to the PDF Guide on page 19:

How can I connect to the unused pins?
The analog pins (analog 0-5 also known as digital pins 14-19) are broken out in the bottom right corner.
Pin 2 has a small breakout since its the only truly unused pin
The remaining pins are not broken out because they could be used by the motor shield. If you are sure
that you are not using those pins then you can connect to them by using stacking headers when
assembling the kit or soldering onto the top of the header with wires, or using a "Wing shield"

So you should have access to pins A0 to A5 (enough for 6 servos). You might need to solder a pin header in that place before you can actually use them.
The wording "Pin 2 [...] the only truly unused pin" is a bit weird, but if you follow the link to the schematics repo and look at mshieldv12schem.png (which seems to be the schematic just as an image, so you don't need to install Eagle for viewing it) it shows the Arduinos pins A0 to A5 only connected to the pin header and nothing else. This tells me that they are actually free.

I haven't used analog pins for any PWM application, I guess will have to experiment with that this time.
Thanks for the support.

The Servo library uses a Hardware Timer, but actually it doesn't use its PWM functionality. The pins are controlled in a timer ISR. Thus every digital pin can be used by the library. Otherwise the library wouldn't be able to support up to 12 servos on the Uno


text:
Is there any way to export a sketch from an Arduino to my laptop?
I was having a sketch but I accidentally downloaded a file which was containing a virus. That virus deleted all my Arduino sketches. I uploaded a sketch into my Arduino UNO and it is still in there.
Is there any way to get it back?

No. The sketch is not on the Arduino. The compiled binary code is on the Arduino. The sketch is gone. Don't you have a backup?!

As Majenko said you can never get the original sketch back from the Arduino, since it is compiled first to assembler and then to binary machine code. You can only get back that binary machine code. Then you can use a decompiler to get a corresponding assembler code. Though that won't be anything like a sketch. Especially the symbols (variable names etc) are totally gone. And it sounds like getting the machine code won't help you.

Like the others said. If you lost something you put a lot of effort into, it may be worth taking the time to run something like TestDisk to scrape the drive for chunks of text and then and grep the results for Arduino-related substrings, e.g. "Serial.print". This assumes they haven't been overwritten. If you try that and have questions about it, it's probably in the domain of superuser. If you had a complex project, the odds of success and required effort might be worth it. It wouldn't be particularly fun to do though.


text:
In which package file is a default programmer selected?
After a clean IDE install, the programmer submenu already has a default option selected as shown below:

I am working on creating a core package and would like a default programmer to be selected after choosing a board, though I'm not sure which file sets the default. For example, here is a different 3rd party package that does not select a default programmer when a board is chosen.

The default preferences.txt file in IDE installation has this setting. It is not read from the boards package configuration files.
The programmer key in preferences.txt contains the last selected programmer. The default preferences.txt in lib folder in IDE installation  has programmer = arduino:avrispmkii. It is used if preferences.txt in Arduino15 folder doesn't exist or doesn't have the specific key.
With the recent change in Arduino IDE only programmers from boards package of the selected board are displayed, so it happens that no programmer is selected.


text:
5V alternative to Due?
I've designed a circuit controlled by an Arduino Mega 2560 involving a number of external components all running on and sending out 5V signals. I'm now realizing that the 8Kb of SRAM on the Mega 2560 is insufficient, so I wanted to upgrade to an Arduino Due.  The Due, however, can't accept the 5V outputs from the rest of the components.
Is there an Arduino compatible 5V board with memory comparable to the 96Kb on the Due?
I know that level shifting is an option, but considering that almost every digital input on the board is being used, I'd rather not have to add so many level shifters to the circuit.  A voltage-compatible board is preferred.
I'm also not fixed on Arduino-compatibility.  If there is another convenient microcontroller development board available, I'd gladly consider it.
EDIT:
The Arduino is being used to read from a set of sensors that produce image data at a constant rate.  The data is recorded on the Arduino, then sent to a computer by USB.  The Arduino needs to store the whole image before sending it to the computer because performing a Serial write call delays the processor causing it to miss a data sample.  The ATMega2560 doesn't have enough SRAM to store the whole image at once.

please do some research ... come back with an actual question

What are you doing that requires so much memory?

If your code really gets to complex for the Mega, one option is also to move just the code away from the mega. Use the Due just for controlling the mega, over some serial protocol for instance. (In which case I'd even go for an ESP32, because it is much more powerful still than the due if the massive number of pins is not required)

Re “a Serial write call delays the processor”: if the input data rate is constant, and slower than what the output baud rate affords, you may consider foregoing the Serial object and just writing the incoming bytes straight to the serial port data register. That should take just a couple of CPU cycles.

@EdgarBonet I tried your suggestion to write to the serial register directly, and it is faster, but it still has to wait for the transmit buffer to be emptied before transmitting.  This variable delay causes the device to occasionally miss an incoming signal.

The Teensy 3.5 seems to be exactly what I was looking for.

It is an Arduino-IDE-compatible 5V tolerant microcontroller board with a whopping 256Kb of SRAM and 64 digital inputs.  It pretty much blows away the Due in every way.

The Arduino MKR Connector Carrier has input level conversion on analog inputs and logic level conversion on digital pins. It makes the 3.3 V MKR boards (SAMD21 MCU) compatible with 5 V sensors and actuators.
The SAMD21 on MKR boards has 256 KB internal flash memory and 32 KB SRAM.