text:
AVR & PIC 8-bit Microcontrollers - Can you add: external flash memory, external RAM, video & audio output, more address busses?
so I was planning on creating a mini PC out of basic ICs and 8-bit microcontrollers such as ATTinys and/or PICs and I have several questions regarding those:

Can you add external RAM, say with SRAM, DRAM chips, so the microcontroller can handle larger programs? (ones requiring more memory to be executed). I've seen an excellent discussion here: External Flash Memory for ATtiny85, which exclaims that I can't do that with AVRs (but why exactly is that? What about PICs, or any 8-bit uCs for that matter).
Can you add external memory, like flash or EEPROM, so that the microcontroller can store some files (sort of a hard drive (but more like an SSD I guess).
Also, how would you go around connecting memory chips together to get more memory out of them? Would there be a difference with memory chips like serial flash and parallel flash?
Can you use them to output and create basic audio & output HDMI? (or communicate with external ICs to do that task)
Can you somehow connect say 2 8-bit ATTinys to get a pseudo 16-bit microcontroller? Would that mean they could process more data at the same time?

Thanks,
some guy on the internet.

Why do you want to do that, simply for the sake of it?  There are several extremely low-cost 64-bit computers around incl Raspberry Pi.  P.S. the question is not about Arduino, voting off topic.

You’re much better off with a general purpose microprocessor or a single board computer. AVRs and PIC are great and versatile devices but simply not the best suitable for what you describe.

I know what you're getting at, I would be better off with anything else, but I just wanted to use these uCs as a proof of concept that they can be converted into a "usable computer".

I’m voting to close this question because it should be migrated to electronics.stackexchange.com

Dmitry Grinberg built an ARM emulator on an AVR microcontroller, then booted Linux on the emulated ARM. Emulation lifts some of the limitations of the microcontroller, like the inability to execute instructions from RAM.

Yes, you can connect external RAM chips through the typical interfaces (mainly SPI or I2C). But you cannot execute code from it. The microcontroller is an IC, meaning Integrated Circuit. It is hard wired internally to execute from internal flash. You cannot change that. That is valid for most microcontrollers, that executes from internal flash (which is somewhat a definition of a microcontroller). A processor - in contrast- like in a computer, is build to execute code from elsewhere. Note: Some microcontrollers have the ability to execute from external flash. The ESP boards are a good example for this, because they already use an external flash chip, which is soldered onto the board. You can extent the available flash over the SPI flash pins (the SPI bus, where the flash is connected); though this is not really a topic for beginners. You might wanna look into that.
If your code, that you want to store externally, isn't that complex, you could save the code there as an own (most likely binary) data format and write code for the microcontroller, that takes that data and executes corresponding functions. So basically an interpreter. Though on the small microcontrollers only code for rather small functionality will fit.

Yes, you can add external storage. Which storage depends on many factors. You can by external flash or EEPROM chips, just like external RAM chips. Common storage devices for microcontrollers are SD cards, because they can easily interfaces via SPI. You can even have a file system there (though the size is somewhat limited by the available RAM of your microcontroller, because it needs to load the file table). Maybe you can even connect an SSD, but you will have to look, if you can set up the corresponding interface for it. A microcontroller does not have SATA interfaces or similar. And adding extra chips for these leaves you fastly with interfacing chips, that are way more capable as the main chip itself (see Wifi and the ESPs: You could add Wifi to an Arduino Uno project with it, but the ESP is way more capable, than the Uno). Then you would need to ask yourself: Is this really a good idea?

I think most memory chips (whichever kind) are not daisy chainable. Mostly they use a Single-Master-Multiple-Slaves interface like SPI. You could connect multiple memory chips to the SPI bus and communicate sequentially with them. The difference between parallel and serial flash chips is their communication interface. Serial can be something like SPI. Parallel communication will send multiple bits at once over the corresponding amount of wires (mostly 8, means 1 byte). Here you need the corresponding number of free pins on your microcontroller. Though parallel interfacing is often not advisable. Especially the small microcontrollers are too slow, to profit from the faster interface. And instead of using at least 9 pins, you could also use 3 for SPI and get the same transmission speed in the end.

Yes, they can. Though it really depends on the used microcontroller and the project topology. When using something like the DFmini player, any microcontroller can play audio (from files on a micro SD card in the player). When the microcontroller should play sounds itself, you can get very different results, depending on the chip capabilities. An ESP32 for example has a dedicated I2S interface, which is build for transmitting sound to an output device.
About video: AVR based microcontrollers (or similar PICs) cannot really handle video. For example: The most, that you can get out of an Arduino Uno (Atmega328p) is a very very limited VGA signal (very small resolution, only a few colors). HDMI is out of range for any of them. Surely you would want to draw on the screen, that is connected to the HDMI interface, to build up a visual interface. I think, that is just not possible with such small microcontrollers. They are not meant for this. Though you might find some very specialized chip, that you could use in such a way. If, that chip would be way more expensive as buying multiple Raspberry Pis. But if you are willig to compromise you may find a smaller sized display (like a few inches) with a connected controller, that you can control via the Arduino. But still you will have very low refresh rate, so no moving images, more like still images.

No, just as 2 32-bit computers do not make 1 64-bit computer. That is just not, how everything works. Each microcontroller can still only process 8 bit at a time out of it's own memory. Depending on the task, you may try to give them different tasks. That would give you more computation power in theory, but it's not the same as a 16-bit controller.

I assume, that you are doing this for fun or for the grind, so I will not say, that you should buy a Raspberry Pi. Though I think, you might look into the wrong way. You cannot make a truck out of parts for a mini, though many of the components work in a similar way. To get all the difficult functionality (audio, video, big storage, ...) out of your self build computer, you need to use computer parts, not microcontroller parts.
If you are happy with much less capabilities, many people in the past have build their own computers out of more basic parts as microcontrollers (down to the big range of logic gates). Microcontrollers live in the world between computers and basic logic components. They are too integrated for extending their capabilities much.

Yes you can, and even execute code from it on PIC18 and PIC17 microcontrollers up to 2MB if external program memory can be added but most variants lac the external program memory interface.
For example the pic18f8x8x you can even implement a memory bank system to address much more than 2MB like PCs did in the early times of the x86 called XMEM extended memory.


text:
Can I emulate Arduino in a headless CI/CD setup?
6 years ago, there has been a question "How to emulate Arduino on PC".
Since then, probably many more Arduino emulators have been introduces.
With this question, I would like to narrow the search scope down to the following criteria:

Linux compatible
headless operation mode without UI/IDE possible to run in a CI/CD (continuous integration/delivery) system in collaborative environment where many code versions need to be merged and tested.

Do such setups exist already?

The Arduino itself is usually only a tiny portion of a project. The rest is other devices and sensors which interact in a "real world" way. Such things can not always be reliably simulated. Sure, you could run an AVR emulator, but what do you do about that ultrasound detector? How do you know that the motor is spinning right? What do you do when the device you want to use isn't even simulated at all?

Please close this question as accepted as you have already the next one -this is not a forum but one question at a topic knowledge base

I am not sure it's mandatory to accept a question with just 1 answer; the comment by Majenko does contain valuable information, too. My following question addresses another aspect of the knowledge base.

The problems with this kind of software is:

always behind the recent releases of cores/ hw variations.
reliable only for simple programs/tasks
Imho all the products I tested (mainly on Win) are actually a (somewhat crippled ) teaching and visualization help.
if you look into the emulators you mostly see only support for different chips and not the whole micro computer, which is far more complex to create

Due to the low cost of the hardware it is easier to run real HW setups with HW diagnostics (and get also feedback for thermal/electric issues) So this kind of SW is for the low cost avr/esp HW and its hundreds of variants (even between production batches from one manufacturer) hard to develop and mantain. So you'll only find nice "play around" emulators which won't fulfill any professional requirement (even if some claim it)

source: Stack Exchange

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

sort: votes


text:
How to install a dependency library to an Arduino compilation environment?
Following approach A from this Arduino SE answer, I managed to kick off an Arduino CLI compilation in a Docker environment.
However, the project I am trying to compile has a dependency on a LCD control library.
Error output:
...../OpenSourceVentilator/OpenSourceVentilator.ino:494:116:
fatal error: LiquidCrystal_PCF8574.h:
No such file or directory
compilation terminated.

What is the proper way to link dependencies to the compilation environment of an Arduino project?
While the source suggests a direct compiler call, maybe I need a Makefile instead of the following?
arduino-cli compile --fqbn esp32:esp32:esp32 -o ignored.bin OpenSourceVentilator.ino

The tutorial, that you linked to as approach A from the other question, also has a part, which explains how to install extra libraries

@chrisl is that also an "Arduino-like" way or is there a more standard approach/package manager?

Why do you expect a non-Arduino like or more standard approach, when using the Arduino CLI?

I just wonder there is no management for external libraries Golang-style, but maybe it's even good.

If the library is installed the Arduino IDE (or CLI I assume too) just finds it and compiles/links it for you.

so what activities does installation of a library include if the library is on GitHub?

https://www.arduino.cc/en/guide/libraries

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


text:
What are examples of large Arduino code bases and how are they organized?
I'd like to find out:

how big can an Arduino project get, is there some limit?
are there examples of large open source code bases? I did some research but find only example projects with single .ino file. Are there projects with multiple files e.g. functions, constants in separate files say to avoid a 10K+ .ino file?

check the source code for some of the libraries

here https://github.com/jandrassy/Regulator

and a new one https://github.com/jandrassy/IsgModbusTcpSG

Yes, there are limits--as with any programming environment. 3d printer apps tend to be super-tight wrt space.

Again im late to the party...
If you are planning on making a larger project and splitting things up you can take advantage of libraries. This will work even if you are married to the arduino ide for some reason. if your not married to the arudino ide platformio doesn't suck too bad, and makes libraries a bit less messy when your doing the grunt work of setting them up the first time.
The idea should be to break your problem into smaller testable pieces of  code into smaller testable libraries.  If your code doesn't depend on arduino features you may be able to use test your library fully on a bigger machine to make sure there are no bugs (for example abuse clangs static analysis tool to see if you made any dumb pointer errors https://clang-analyzer.llvm.org/)
I kinda set an example of  this (https://gitlab.com/mikealger/ExampleArduinoProjectStructure) up for students a while back but i still think its handy for anyone looking to build /manage the lifecycle of a project, I still use the basic ideas when i'm doing one off small projects based on others work to keep my notes straight i.e.  https://gitlab.com/mikealger/celstronhomebrewgps
yea its probably shameless promotion but i haven't logged in for like 2 years...

Big projects are likely not developed with Arduino IDE. Arduino IDE was make for designers/inventors, not for programmers.

Arduino was born at the Ivrea Interaction Design Institute as an easy tool for fast prototyping, aimed at students without a background in electronics and programming.

Source
Programmers will use a fully-fledged IDE which has many features a programmer needs on a daily basis, such as:

handling multiple files efficiently
allowing to create libraries instead of just setup() and loop()
code completion (suggestions as you type)
debugging (inspection and changing of variables at runtime)
refactoring (modifying the structure of your code without changing the behavior)
integrated version control (like Git / Github)

Such an IDE could be Eclipse with an Arduino Plugin or Atmel Studio and perhaps Visual Studio.
So, what do you need to look for? Don't look for .ino files. Instead, look for .h and .cpp code, just like other non-Arduino C++ code.
Some examples:

SPI: 297 lines
Wire: 453 lines
SoftwareSerial: 486 lines
I2S: 533 lines
USBHost: several files, up to 1600 lines

Thats an example how to organize by function groups.Other good complex examples can be found when searching for Arduino esp8266 webserver site:github.com The limit is basically your IDE -If you use ArduinoIDE the limit is (without already tested and working lib files) around 20 files, more is a pain in the a** to handle. I keep the length of my files between 500 - max 1000 lines. For documentation and keeping relationship diagrams (valuable for debug) I use doxygen with the graph extension.When using an IDE like eclipse you can use more files, you have a good overview over your classes, but time to spend (and learn) configuring a project is initially much higher and there are sometimes (release dependent) breaking changes in the tool chain.

Each sketch uses Flash memory, you can see this when you compile your project.
You also can see how much percentually you have used.
And as jsotola explains, libraries are examples how multiple files can be used.
However, next to you .ino scene (in the same folder) you can put .h, .c and .cpp files which are automatically compiled (when used by the .ino file). However, if you use too many files, because tabs are placed horizontally in the Arduino IDE, it's better to use a decent editor. And while doing that, you use the Arduino IDE to compile (only).


text:
Update class attribute with attachInterrupt
I want to refactor this code
/*
YF‐ S201 Water Flow Sensor
Water Flow Sensor output processed to read in litres/hour
Adaptation Courtesy: www.hobbytronics.co.uk
*/
volatile int flow_frequency; // Measures flow sensor pulses
unsigned int l_hour; // Calculated litres/hour
unsigned char flowsensor = 2; // Sensor Input
unsigned long currentTime;
unsigned long cloopTime;
void flow () // Interrupt function
{
   flow_frequency++;
}
void setup()
{
   pinMode(flowsensor, INPUT);
   digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
   Serial.begin(9600);
   attachInterrupt(0, flow, RISING); // Setup Interrupt
   sei(); // Enable interrupts
   currentTime = millis();
   cloopTime = currentTime;
}
void loop ()
{
   currentTime = millis();
   // Every second, calculate and print litres/hour
   if(currentTime >= (cloopTime + 1000))
   {
      cloopTime = currentTime; // Updates cloopTime
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency = 0; // Reset Counter
      Serial.print(l_hour, DEC); // Print litres/hour
      Serial.println(" L/hour");
   }
}

Originally found here: source
to an Class based solution:
/*
YF‐ S201 Water Flow Sensor
Water Flow Sensor output processed to read in litres/hour
Adaptation Courtesy: www.hobbytronics.co.uk
*/
class FlowSensor {
  volatile int flow_frequency;
  unsigned int l_hour;
  unsigned char pin;
  unsigned long currentTime;
  unsigned long cloopTime;
  public:
    void flow () {
      flow_frequency++;
    };
    void setup() {
      pinMode(pin, INPUT);
      digitalWrite(pin, HIGH); // Optional Internal Pull-Up
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(pin), flow, RISING); // Setup Interrupt
      sei(); // Enable interrupts
      currentTime = millis();
      cloopTime = currentTime;
    }
    void loop() {
      currentTime = millis();
      // Every second, calculate and print litres/hour
      if(currentTime >= (cloopTime + 1000))
      {
        cloopTime = currentTime; // Updates cloopTime
        // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
        l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
        flow_frequency = 0; // Reset Counter
        Serial.print(l_hour, DEC); // Print litres/hour
        Serial.println(" L/hour");
      }
    }
    FlowSensor() {
      setup();
    };
};
FlowSensor flowsensor_intake;
void setup()
{
   flowsensor_intake = FlowSensor();
}
void loop ()
{
   flowsensor_intake.loop();
}

But i get the following error in the Arduino IDE:

/tmp/087639235/water_flow/water_flow.ino: In static member function
  'static void FlowSensor::flow()':
/tmp/087639235/water_flow/water_flow.ino:17:19: error: cannot call
  member function 'void FlowSensor::update_flow()' without object
update_flow()
^
exit status 1

I understand that flow is not a static function and that i cannot make it static because it is midifying a non static member.
But i cannot think of an alternate solution to this Problem. My goal is to monitor multiple flow sensors by creating an object in the setup() function, and updating them with every loop() call.

You've run into a classic trap.  There are a couple of things to think about.  First off, if this is a singleton class (as in there will only ever be one instance) then you can just have a non-member function that you use with attachInterrupt and have that function just call the member function you want.  Normally what I would do would be to create the instance in the .cpp and put an extern declaration for it in the header so that it can just be used without creating it.  Look at how Serial works for an example.  Then put all the configuration type stuff into a begin or init method to call from setup.  That way the non-member function for the interrupt can be part of the header and the user never has to see or mess with it and it feels like it's part of the class.
If this is not a singleton class and you might one day have several instances of this in one program then you have to start asking yourself how will the interrupt know which instance to act upon.

Yes i want to have multiple instances. Thinking of a struct approach now.

Ok then you've got a problem.  How will each instance know which interrupt to attach itself to?  How will the interrupt know which instance goes with which interrupt?  That turns out to be a can of worms, and it's the reason it's not allowed.

I agree. Singlton or static member functions won't work.
My current work around is a member function which is called by a specific function for each attachInterrupt.


text:
Connecting a FireBeetle ESP32 to Arduino
I have a very basic question, because I struggle to upload files to my FireBeetle ESP32 Board.
When I try to upload to the board I get an
A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header

On other boards you have to press & hold the flash button, but this specific board just has a reset button.
What can I do?

I suspect you do not have the right drivers installed. That's the issue I just solved for myself. And it can be easy to think you installed the right driver, when in fact you didn't.
Have you followed the instructions on DFRobot's product wiki?
I'm not sure if you have the ESP32-E or the earlier ESP32-IOT Firebeetle, but here's the link to the drivers mentioned for the Firebeetle ESP32E and here for the prior version, the Firebeetle ESP32 IOT
But I would suggest double checking which board you have an very meticulously ensuring you have the right driver installed.

The flash button is virtual and controlled by the RTS signal from the computer through the USB port (why are you trying to connect through an Arduino?). It should automatically enter bootloader mode when you go to program it. There should be nothing you need to do.
However, if you do want to manually enter bootloader mode, just connect IO0 (note: not D0) to GND and press the reset button.


text:
Arduino Uno and 7 segment display - wrong value displayed
I am working at this project and I found that if I have set the temperature by rotating the pot to 312 C, the iron started heating up, but when it was at about 60 C then on the display (7 segment, 3 digit) appeared 312 (the temperature that I have set) and then appeared about 70 C. I did not rotate the pot, the 312 appeared from "nowhere".
I powered on again the soldering station and it showed 35 C - then 312 C - and then 52 C and then the temperature rise normally.
I set the pot randomly at 244 C and the problem did not appeared.
The problem also appeared at 344 C set temperature.
I tried with different soldering irons and 2 different potentiometers and the problem still persist.
I have also tried with different Arduino boards, but the problem still persist.
Is there a solution for this problem ?
The project page: https://www.allaboutcircuits.com/projects/do-it-yourself-soldering-station-with-an-atmega8/?utm_source=eetech&utm_medium=eetech-social&utm_campaign=reposts-projects/
Explanation of the schematic: J2 from "schematic.jpg" is connected to J1 of "7 segment.jpg", pin to pin. The last 4 pins of J2 from "schematic.jpg" are connected to J3 from "7 segment.jpg" and the last pin from J2 ("schematic.jpg") is connected to J6 from the "7 segment.jpg".
https://ibb.co/Zdrt1Hq
https://ibb.co/DC0LzV2
My code:
//Thank you Alex from https://geektimes.ru/ for help with led array function
//AllAboutCircuits.com
//epilepsynerd.wordpress.com

#include <PID_v1.h>

//This array contains what segments need to be turned on to display numbers 0-9
byte const digits[] = {
  B00111111, B00000110, B01011011, B01001111, B01100110, B01101101, B01111101, B00000111, B01111111, B01101111
};

int digit_common_pins[] = {8, 9, 10}; //Common pins for the triple 7-Segment LED display
int max_digits = 3;
int current_digit = max_digits - 1;

unsigned long updaterate = 1200; //Change how fast the display updates. No lower than 500
unsigned long lastupdate;

int temperature = 0;

//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Define the aggressive and conservative Tuning Parameters
double aggKp = 4, aggKi = 0.2, aggKd = 1;
double consKp = 1, consKi = 0.05, consKd = 0.25;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);

void setup()
{
  DDRD = B11111111;  // sets Arduino pins 0 to 7 as outputs
  for (int y = 0; y < max_digits; y++)
  {
    pinMode(digit_common_pins[y], OUTPUT);
  }
  //We do not want to drive the soldering iron at 100% because it may burn, so we set it to about 85% (220/255)
  myPID.SetOutputLimits(0, 220);
  myPID.SetMode(AUTOMATIC);
  lastupdate = millis();
  Setpoint = 0;
}

void loop() {
  //Read temperature
  Input = 0;
  for(int i=0;i<50;i++)
  Input += analogRead(A0);
  Input /= 50;
  //Transform the 10bit reading into degrees celsius
  Input = map(Input, 0, 550, 25, 400);
  //Display temperature
  if (millis() - lastupdate > updaterate) {
    lastupdate = millis();
    temperature = Input;
  }
  //Read setpoint and transform it into degrees celsius(minimum 150, maximum 350)
  double newSetpoint = analogRead(A1);
  newSetpoint = map(newSetpoint, 0, 1023, 150, 400);
  //Display setpoint
  if (abs(newSetpoint - Setpoint) > 3) {
    Setpoint = newSetpoint;
    temperature = newSetpoint;
    lastupdate = millis();
  }

  double gap = abs(Setpoint - Input); //distance away from setpoint

  if (gap < 10)
  { //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  }
  else
  {
    //we're far from setpoint, use aggressive tuning parameters
    myPID.SetTunings(aggKp, aggKi, aggKd);
  }

  myPID.Compute();
  //Drive the output
  analogWrite(11, Output);
  //Display the temperature
  show(temperature);
}

void show(int value) {
  int digits_array[] = {};
  boolean empty_most_significant = true;
  for (int z = max_digits - 1; z >= 0; z--) //Cycle through each digit
  {
    digits_array[z] = value / pow(10, z); //We now take each digit from the number
    if (digits_array[z] != 0 ) empty_most_significant = false; //Do not display leading zeros
    value = value - digits_array[z] * pow(10, z);
    if (z == current_digit)
    {
      if (!empty_most_significant || z == 0) { //Check to see that we do not have leading zeros and display the current digit
        PORTD = ~digits[digits_array[z]]; //Remove ~ for common cathode
      }
      else
      {
        PORTD = B11111111;
      }
      digitalWrite(digit_common_pins[z], LOW);//Change to LOW for common cathode
    } else {
      digitalWrite(digit_common_pins[z], HIGH);//Change to HIGH for common cathode
    }

  }
  current_digit--;
  if (current_digit < 0)
  {
    current_digit = max_digits; //Start over
  }
}```

change your code to display the value of newSetpoint continuously ... that will determine if the value is "bouncing"

The value of newSetpoint seems to be good, it's not bouncing.

if (abs(newSetpoint - Setpoint) > 3) { is sometimes true without you changing the pot position


text:
Freezing ESP8266 after 4-8h
Build my own 'Artnet to WS2812b Neopixel' boxes for lighting in a club. Working fine. I have 20 stripes with 50 pxls each. One ESP8266(NodeMCU) is feeding 6 stripes, so it gets 2 DMX universes via Artnet. Depending on the FPS(~20-40FPS) i'm sending, thats about 200-300kbp/s constant bitrate for each of the ESPs.
Every 4-8h one of my boxes freezes randomly. No pinging possible anymore. The other boxes continue working as usual. Only chance of resetting is to disconnect the power.
First, i thought the ESP gets to hot (installed at the clubs ceeling and the power supply is also in such a box) or the humidity is to high, but it must be a software problem (tested it in the oven, dont laugh ;)).
So why isn't the watchdog resetting? I am not able to provoke any of those freezes at home (only waiting)
The code is pretty straight forward:

test the leds
connect to wifi (if no wifi, go to 1)

Loop:

check UDP packets for Artnetdata
update the WS2812 with the fastled-lib

any ideas?
#define FASTLED_ESP8266_NODEMCU_PIN_ORDER
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

#include <FastLED.h>

// ARTNET CODES
#define ARTNET_DATA 0x50
#define ARTNET_POLL 0x20
#define ARTNET_POLL_REPLY 0x21
#define ARTNET_PORT 6454
#define ARTNET_HEADER 17

WiFiUDP udp;

#define NUM_LEDS 50

CRGB leds[NUM_LEDS];
CRGB leds2[NUM_LEDS];
CRGB leds3[NUM_LEDS];
CRGB leds4[NUM_LEDS];
CRGB leds5[NUM_LEDS];
CRGB leds6[NUM_LEDS];

unsigned long previousMillis = 0;
int offset=0;

uint8_t uniData[514];
uint8_t maxuni=0;
uint16_t uniSize;
uint8_t hData[ARTNET_HEADER + 1];

const char* ssid     = "*";
const char* password = "*";

IPAddress local_ip(192, 168, 0, 111);
IPAddress gateway_ip(192, 168, 0, 1);
IPAddress subnet_ip(255, 255, 255, 0);

void setup() {
  WiFi.begin(ssid, password);
  WiFi.config(local_ip, gateway_ip, subnet_ip);

  while (WiFi.status() != WL_CONNECTED) {
   delay(500);

delay(2000); // sanity delay
FastLED.addLeds<WS2812, 1, GRB>(leds, NUM_LEDS);
FastLED.addLeds<WS2812, 2, GRB>(leds2, NUM_LEDS);
FastLED.addLeds<WS2812, 3, GRB>(leds3, NUM_LEDS);
FastLED.addLeds<WS2812, 4, GRB>(leds4, NUM_LEDS);
FastLED.addLeds<WS2812, 5, GRB>(leds5, NUM_LEDS);
FastLED.addLeds<WS2812, 6, GRB>(leds6, NUM_LEDS);
initTest();

  }

  udp.begin(ARTNET_PORT); // Open ArtNet port
}

void loop() {

  if (udp.parsePacket()) {
    udp.read(hData, ARTNET_HEADER+1);
    if ( hData[0] == 'A' && hData[1] == 'r') { //checking first two letters, if its Artnet data
      if ( hData[8] == 0x00 && hData[9] == ARTNET_DATA) {
      uniSize = (hData[16] << 8) + (hData[17]);
      udp.read(uniData, uniSize);

      if(hData[14]>maxuni){maxuni=hData[14];}

     switch(hData[14]+1-maxuni){

      case 0: //for each DMX universe updating the pixels
         for (int j=50; j--;){
            leds[j].setRGB(uniData[j*3+offset],uniData[j*3+1+offset],uniData[j*3+2+offset]);
          leds2[j].setRGB(uniData[j*3+150+offset],uniData[j*3+151+offset],uniData[j*3+152+offset]);
          leds3[j].setRGB(uniData[j*3+300+offset],uniData[j*3+301+offset],uniData[j*3+302+offset]);
         }
         break;

      case 1:
         for (int j=50; j--;){
           leds4[j].setRGB(uniData[j*3+offset],uniData[j*3+1+offset],uniData[j*3+2+offset]);
          leds5[j].setRGB(uniData[j*3+150+offset],uniData[j*3+151+offset],uniData[j*3+152+offset]);
          leds6[j].setRGB(uniData[j*3+300+offset],uniData[j*3+301+offset],uniData[j*3+302+offset]);
         }
         break;
     }
}
}
}

FastLED.show();
}

void initTest()
{
//only at Startup checking the LEDs, so nothing special here....}

disconnect the LED strip ... does it still freeze?

it could be power fluctuations, maybe a fat cap from gnd to vcc would help. or a memory leak, keep an eye on the heap size and see if it ticks down over time. Worst case, work on getting them to boot faster, then reboot every few hours.


text:
4x4 matrix keypad not working
I'm working on a research project that allows me to press a button on a matrix that then outputs a parameter like temperature, humidity etc. But I cannot find out what is wrong with the buttons, when I press them nothing is happening. Thank you very much! I've attached what the connection between the Arduino and the keypad looks like.
#include <EEPROM.h>
#include <GravityTDS.h>
#include "DHT.h"
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <Servo.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Keypad.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define DHTPIN 7
#define DHTTYPE DHT11   // DHT 11
#define SensorPin A0            //pH meter Analog output to Arduino Analog Input 0
#define Offset 0.00            //deviation compensate
#define LED 13
#define samplingInterval 20
#define printInterval 800
#define ArrayLenth  40    //times of collection
#define PUMPPIN 9
#define ONE_WIRE_BUS 4
int pHArray[ArrayLenth];   //Store the average value of the sensor feedback
int pHArrayIndex = 0;
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
Servo myservo;
GravityTDS gravityTds;
DHT dht(DHTPIN, DHTTYPE);

char incomingByte;
String inputString;
int pump = 9; // Output for pump Control
double avg;
int h;
float t;
float tdsValue;
float temperature = t;
static unsigned long samplingTime = millis();
static unsigned long printTime = millis();
static float pHValue, voltage;

const byte ROWS = 4;
const byte COLS = 4;

char hexaKeys[ROWS][COLS] = {
  {'A', 'B', 'C', 'D'},
  {'E', 'F', 'G', 'H'},
  {'I', 'J', 'K', 'L'},
  {'M', 'N', 'O', 'P'}
};

byte rowPins[ROWS] = {44, 42, 40, 38};
byte colPins[COLS] = {36, 34, 32, 30};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

void setup() {

  lcd.begin();
  pinMode(pump, OUTPUT); //sets the digital pin as output
  digitalWrite(pump, LOW); // Initial state of the pump
  Serial.begin(9600);
  gravityTds.setPin(A1);
  gravityTds.setAref(5.0);
  gravityTds.setAdcRange(1024);
  gravityTds.begin();
  dht.begin();
  sensors.begin();
}

double averagearray(int* arr, int number) {
  int i;
  int max, min;
  long amount = 0;
  if (number <= 0) {
    Serial.println("Error number for the array to avraging!/n");
    return 0;
  }
  else if (number < 5) { //less than 5, calculated directly statistics
    for (i = 0; i < number; i++) {
      amount += arr[i];
    }
    avg = amount / number;
    return avg;
  } else {
    if (arr[0] < arr[1]) {
      min = arr[0]; max = arr[1];
    }
    else {
      min = arr[1]; max = arr[0];
    }
    for (i = 2; i < number; i++) {
      if (arr[i] < min) {
        amount += min;      //arr<min
        min = arr[i];
      } else {
        if (arr[i] > max) {
          amount += max;  //arr>max
          max = arr[i];
        } else {
          amount += arr[i]; //min<=arr<=max
        }
      }//if
    }//for
    avg = (double)amount / (number - 2);
  }//if
  return avg;
}

void loop() {
  lcd.print("working so far. test1");
  delay(5000);
  char customKey = customKeypad.getKey();
  int pumptime = 1000;
  switch (customKey) {
    case 'A':
      // pump
      digitalWrite(pump, HIGH); // on pump
      delay(pumptime);
      digitalWrite(pump, LOW);//off pump
      break;
    case 'B':
      // add pump time
      pumptime += 500;
      break;
    case 'C':
      // less pump time
      pumptime -= 500;
      break;
    case 'D':
      // reset pump time
      pumptime = 1000;
      break;
    case 'E':
      //temp
      sensors.requestTemperatures();
      lcd.setCursor(0, 0);
      lcd.print("Celsius temperature: ");
      lcd.print(sensors.getTempCByIndex(0));
      lcd.print((char)223);
      lcd.print("C");
      delay(5000);
      lcd.clear();
      break;
    case 'F':
      // Temperature & humidity
      h = dht.readHumidity();
      t = dht.readTemperature();
      lcd.setCursor(0, 0);
      lcd.print("Humidity:");
      lcd.print(h);
      lcd.print("%");
      lcd.setCursor(0, 1);
      lcd.print("Temperature:");
      lcd.print(t);
      lcd.print((char)223);
      lcd.print("C");
      delay(5000);
      lcd.clear();
      break;
    case 'G':
      // TDS
      h = dht.readHumidity();
      t = dht.readTemperature();
      temperature = t;
      gravityTds.setTemperature(temperature);
      gravityTds.update();
      tdsValue = gravityTds.getTdsValue();
      lcd.setCursor(0, 0);
      lcd.print("TDS: ");
      lcd.print(tdsValue);
      lcd.print("ppm");
      delay(5000);
      lcd.clear();
      delay(5000);
      lcd.clear();
      break;
    case 'H':
      // pH
      lcd.clear();
      lcd.setCursor(0, 0);
      if (millis() - samplingTime > samplingInterval)
      {
        pHArray[pHArrayIndex++] = analogRead(SensorPin);
        if (pHArrayIndex == ArrayLenth)pHArrayIndex = 0;
        voltage = averagearray(pHArray, ArrayLenth) * 5.0 / 1024;
        pHValue = 3.5 * voltage + Offset;
        samplingTime = millis();
      }
      if (millis() - printTime > printInterval)  //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
      {
        lcd.print("Voltage:");
        lcd.print(voltage, 2);
        lcd.print("    pH value: ");
        lcd.println(pHValue, 2);
        digitalWrite(LED, digitalRead(LED) ^ 1);
        printTime = millis();
      }
      delay(5000);
      lcd.clear();
      break;
    case 'I':
      // test buttons
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'J':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'K':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'L':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'M':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'N':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'O':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'P':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
  }//switch
  lcd.print("working so far. test2");
  myservo.write(0);
  delay(10000);
  myservo.write(90);

  delay(1800000);

}

start by reducing your code ... read a keypress and print the result ... nothing else

i suspect that you are not pressing the button in the millisecond window after the 30 minute delay ... are you actually waiting 30 minutes for the window when keypress is accepted?

Imho, your delay function in loop() is a root cause.
First, you should remove the below code
  myservo.write(0);
  delay(10000);
  myservo.write(90);

  delay(1800000);

Then,please reduce delay(5000) -> delay(200).
Build and execute your code.
Press and hold a single button and take a look what happen in LCD. At least, you able to confirm the keypad hardware works well or not.


text:
EM-18 RFID module not reading Card ID
I am using EM-18 Rfid module with Arduino mega the problem is that when i swipe the card for reading the card ID nothing will shown in serial monitor.Code given below.EM-18 connection diagram is given in attachments.
int count = 0;
    char card_no[12];
    void setup()
    {
       Serial.begin(9600);
    }
    void loop()
    {
       if(Serial.available())
       {
          count = 0;
          while(Serial.available() && count < 12)
          {
             card_no[count] = Serial.read();
             count++;
             delay(5);
          }
          Serial.print(card_no);
       }
    }

your code is unnecessarily complex .... furthermore,  you do not print anything until 12 characters have been received .... that is "shooting yourself in the foot" .... print the characters as they arrive ... that means, get rid of the while block .... reduce the code to if serial data is available, then get serial data and print it

Is this ok?
int count = 0;
char card_no[12];
void setup()
{
Serial.begin(9600);
}
void loop()
{
if(Serial.available())
{
         card_no = Serial.read();

      Serial.print(card_no);
   }
}


text:
How to set maximal execution time of operation
I'm JSON deserializing output from ESP8266 in  my Arduino UNO, but when it fails (for some reason every time after it deserializes successfully) the program lags for few seconds and I don't want that to happen (at least not for a long time)
#include "SevSeg.h"
#include <ArduinoJson.h>
SevSeg sevseg;

StaticJsonDocument<500> response;

String data;

void setup(){
  Serial.begin(74880);
  Serial.setTimeout(10000);
  while (!Serial) {
     // wait for serial port to connect. Needed for native USB port only
  }
  byte numDigits = 4;
  byte digitPins[] = {2, 3, 4, 5};
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_ANODE; // See README.md for options
  bool updateWithDelays = false; // Default 'false' is Recommended
  bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
  bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or isn't connected. Then, you only need to specify 7 segmentPins[]

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments,
  updateWithDelays, leadingZeros, disableDecPoint);
  Serial.println("running");

}

void loop(){

       if (Serial.available()) {
            Serial.write(Serial.read());
            const auto deser_err = deserializeJson(response, Serial);

            if (!deser_err) {

                if(response["type"] == "num"){
                  sevseg.setNumber(response["data"],response["dot"]);
                }else{
                  sevseg.setChars(response["data"]);
                }
                String data = response["data"];
                Serial.println(data);

            }else{
              Serial.print(F("Failed to deserialize, reason: \""));
              Serial.print(deser_err.c_str());
              Serial.println('"');
            }

      }

  sevseg.refreshDisplay();

}

The response
running  //runs everytime I turn on the arduino
21:43:03.797 -> {null
21:43:03.797 -> :null
21:43:03.797 -> ,null
21:43:03.797 -> :null
21:43:03.797 -> ,null
21:43:03.797 -> :Failed to deserialize, reason: "InvalidInput" // for some reason I have to send request 2 times because for the first time it always fails
21:43:03.797 ->
Uove //correct data received
21:43:04.772 -> // this timestamp isn't right it is like 5 seconds after correct data
Failed to deserialize, reason: "EmptyInput"

What can I do for this not to happen for the first time or in a shorter duration?
I'd be really thankful for any answer.

so, the program does something different when it deserializes successfuly and you want to know why it does something different?

Yes that too, I have a lot of questions about this weird behaviour

What exactly are you sending over serial? The first character will be echoed back over Serial. It does not get used by the deseriallzation. That might be a problem depending on what you are sending.

Do you know, what the timeout of the deserialization from serial is? That timeout is propably what takes so long.

I don't know and i couldn't find it either, but I've noticed that the lower Serial.setTimeout the shorter the duration of waiting, but when u set it too low, it doesn't want to deserialize anything (the current 10s is minimum for it to work correctly)

I think you shouldn't deserialize directly from Serial. Instead send the json data with a newline character at the end, read the data into a buffer, until you read the newline character. Then do the deserialization on that buffer. Currently you are clearly butchering the json string. You still didn't write, what exactly you are sending via serial. Please include that information in your question

remove the big timeout. add while (Serial.read() != -1); after deserializeJson to read out the newline characters which cause to enter the deserialization without data. and remove Serial.write(Serial.read());


text:
Various Bluetooth HC-06 modules erratic in different ways
I am trying to make a Bluetooth controlled robot and have troubles with the Bluetooth modules. I used  3 HC-06 Bluetooth module. All of them have different problems.

I could not find the 1st HC-06 under the list of Bluetooth devices in the settings.
The 2nd HC-06 could be paired with the phone but I could not send the message on the Bluetooth terminal app (The error message from the app is below).
The 3rd HC-06 could be paired and I could send a message but the message was not registered on the Arduino nor on serial monitor. On the Bluetooth terminal app, the message was received but not replied.

What could be the problem? I'm pretty sure my connections are correct as I have checked them and they used to work.

Check your power supply for the BT module. Try 1000uF or more decoupling close to the module.

why would putting capacitors around the bluetooth help, is it also subject to EMI?


text:
No Websockets Server for Arduino mkr1010?
I've seen some interesting explanations on using websocket comms on mkr 1010 but it's always handling the mkr 1010 as the client and the server being always a computer or some other "non-arduino" server . I'm working on a system with several mkr 1010's in a master/slave setup and bidi comms i.e. i want to use one of the mkr's as a server (does the calculations etc.) and the other as clients (get result from calculations ans send back sensor info). I did not found any library or example of websocket server for mkr1010. I found it for ESP systems. Please help as i tried my bidi comms with webclient and webserver using http but not good enough for my applicaton (not realy bidi).
thanks a lot !

Most websocket libraries work over a Client. Client is base class for all EthernetClient and WiFiClient classes.
But why do you want to use a Websocket for communication of two MCU in the same LAN? Websockets are intended for communication over HTTP infrastructure (firewalls, proxies) to a web server in Internet or from browser to a web server.
Use a basic TCP socket over Arduino Client.
WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.
If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read only from the WiFiClient object on the other side.
client socket
if (client.connect(serverIP, PORT)) {
  client.print("request\n");
  String response = client.readStringUntil('\n');
  Serial.println(response);
  client.stop();
}

server side
WiFiClient client = server.available();
if (client && client.connected()) {
  String request = client.readStringUntil('\n');
  Serial.println(request);
  client.print("response\n");
  client.stop();
}

thanks a lot ! I have also used the chatserver example to work it out !


text:
Unable to understand the acquisition of data from Magnetometer HMC5883L and Accelerometer ADXL345
Below are the X,Y,Z registers for HMC5883L.

while this is the Arduino code for HMC5883L to acquire X,Y,Z reading.
If you look at this code, we do not mention the X, Y, Z address specifically.
  Wire.beginTransmission(0x1E);
  Wire.write(0x02);
  Wire.write(0b00000001);
  Wire.endTransmission();
  delay(10);

  Wire.requestFrom(0x1E,6);
  if (Wire.available() > 5)
  {
    x = readValue();
    y = readValue();
    z = readValue();
  }
  else
  {
    Serial.println("No data found");
  }
int readValue()
{
  int val = Wire.read()<<8;
      val |= Wire.read();

  return val;
}

We only write Wire.request() and do not mention X,Y,Z addresses specifically for HMC5883L.
While in the case of ADXL345 we mention every register of X,Y,Z separately to acquire data. Which is exactly my question like why not simply use Wire.requestFrom() for ADXL345 too. When will we access each X,Y,Z register separately? and when will we do not?
Below is Arduino ADXL345 code for reading X axis data.
  Wire.beginTransmission(0x53);
  //Ask the particular registers for data
  Wire.write(0x32);
  Wire.write(0x33);
  Wire.endTransmission();
  Wire.requestFrom(0x53,2);
  if(Wire.available()<=2) {
    X0 = Wire.read();
    X1 = Wire.read();
    X1=X1<<8;
    X_out =X0+X1;
    Xa=X_out/256.0;
  }

Datasheets for both sensors are available on the link.
The code above is not mine.
https://drive.google.com/open?id=1AswNTdBz55Rfg3nu4-YsLFj4ANrsCL5I

use the datasheet to determine the correct way to retrieve data from the device

If you read the datasheet for the mentioned magnetometer, it is clearly mentioned that the data is to be read at once. Below is the implementation of pseudo code mentioned in the datasheet.
void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  //send 0x3C 0x00 0x70 (8-average, 15 Hz default, normal measurement)
  Wire.begin();
  Wire.beginTransmission(0x1E);
  Wire.write(0x00);
  Wire.write(0x70);
  Wire.endTransmission();
  delay(10);
  //send 0x3C 0x01 0xA0 (Gain=5, or any other desired gain)
  Wire.beginTransmission(0x1E);
  Wire.write(0x01);
  Wire.write(0xA0);
  Wire.endTransmission();
  delay(10);
  //send 0x3C 0x02 0x00 (Continuous-measurement mode)
  Wire.beginTransmission(0x1E);
  Wire.write(0x02);
  Wire.write(0x00);
  Wire.endTransmission();
  delay(10);

}
void loop()
{

  Wire.requestFrom(0x1E,6);
  if (Wire.available() > 5)
  {
    x = readValue();
    y = readValue();
    z = readValue();
  }
  else
  {
    Serial.println("No data found");
  }
  data = String(x) + "   ,   " + String(y) + "   ,   " + String(z);
  //Send 0x3C 0x03 (point to first data register 03)
  Serial.println(data);
  Wire.beginTransmission(0x1E);
  Wire.write(0x03);
  Wire.endTransmission();
  delay(100);
}

Similarly, it is mentioned in the datasheet for ADXL345 as well that the data should be read separately from each axis register separately.


text:
ESP32 and wifi router
I connected my ESP32 to Wifi and I can see this in my Wireless Statistics:
ID |       MAC Address      |Current Status| Packets Received | Packets Sent | SSID
1  | 3C: 71: BF: 0D: CB: 00 | Connected    |         52       |       47     |mySSID

I can ping via IP but I can't see ESP device in the DHCP list or ARP.
Could you explain why? And how I can fix this?

where does the statistics info come from? ... how are you performing the DHCP list and the ARP? ... please update your question to make it clear what you did ... as it stands, it appears that the question is not related to the Arduino

I made a binding IP and MAC and now I see my ESP)

how did you do the binding?


text:
L LED on Arduino is constantly on and com is not detected
When I connect the Arduino to the computer, the L LED is constantly on and com is not detected. However, when I press the reset button, the L LED starts blinking for about 10 seconds and com appears. But then he leaves.

What happens if you upload the Blink example in the moment when the com port appears?

Hold the Reset button down with one hand and start uploading the sketch (like, an empty sketch or the Blink sketch) with the other. Once you see "uploading" release the Reset button.


text:
PubSubClient constructor parameter type mismatch
I am just learning an Arduino so this is totally educational purpose call.
I want to instantiate PubSubClient client with WiFiClient parameter.

#include <WiFiClient.h>
#include <PubSubClient.h>

WiFiClient *wifi = NULL;
PubSubClient client(wifi);

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

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

compilation gives me back:
Compilation error: no matching function for call to /home/tepo/Arduino/libraries/PubSubClient/src/PubSubClient.h:116:4: note:   candidate expects 0 arguments, 1 provided
/home/tepo/Arduino/libraries/PubSubClient/src/PubSubClient.h:88:7: note: candidate: 'PubSubClient::PubSubClient(const PubSubClient&)'
 class PubSubClient : public Print {
       ^~~~~~~~~~~~
/home/tepo/Arduino/libraries/PubSubClient/src/PubSubClient.h:88:7: note:   no known conversion for argument 1 from 'WiFiClient*' to 'const PubSubClient&'

exit status 1

Compilation error: no matching function for call to 'PubSubClient::PubSubClient(WiFiClient*&)'

and listing all the other constructors.
type chain seems to hold:
class WiFiClient : public ESPLwIPClient -> class ESPLwIPClient : public Client -> class Client: public Stream
PubSubClient ctor:
 PubSubClient(Client& client);

so why is it not accepting a WifiClient as a parameter?

PubSubClient client(*wifi);. it will compile, but it will just crash in runtime since there will be no WiFiClient object at address 0

look at the example code in the library

The issue you're encountering with the PubSubClient constructor in Arduino is related to how you're passing the WiFiClient object. You're currently using a pointer (WiFiClient *wifi), but the PubSubClient constructor expects a reference to a Client object, not a pointer.
The WiFiClient class inherits from the Client, so it can be used with PubSubClient. However, you need to pass an instance of WiFiClient, not a pointer to an instance.
Here's how you can correct your code:
#include <WiFiClient.h>
#include <PubSubClient.h>

WiFiClient wifi;
PubSubClient client(wifi);

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

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

In this corrected version, wifi is an instance of WiFiClient, not a pointer. When you pass wifi to the PubSubClient constructor, it correctly matches the expected Client& client parameter type.
In C++ a pointer (WiFiClient *) is a variable that holds the memory address of an object.
A reference (WiFiClient &) is an alias for an object.
The PubSubClient constructor expects a reference because it needs to interact with the Client object throughout its lifecycle, and references are generally safer and more straightforward to use in this context than pointers.

yeah, that got it working; however I'm failing to understand where the actual instance of 'wifi' is comming from as I'm not constructing int, rather in the sketch I am using WifiManager that seems 'injecting' it to the declared variable. (I come from java-spring world) That's why I thought pointer will do in this case; it seems a bit weird to me it just "gets supplied" somehow..

What do you mean you're not constructing it? WiFiClient wifi; constructs it. Unlike Java you don't need to do a new procedurally to instantiate a class variable.


text:
Arduino L led glows continuously
can someone tell me why my L led on arduino uno glowing continuously I tried restarting my pc, changing USB port
I also tried uploading an empty file and resetting the  Arduino board but nothing seems to work. Does it mean I have to buy a new one?

What happens if you upload the example blink sketch? And what, if you try to blink an LED on another pin (you need an extra LED for this)

… and a resistor

Some Arduino boards drive that LED through an op-amp. If pin 13 is set to INPUT Then the input to the op-amp will be effectively floating. That can cause the LED to glow since it lacks further instruction on what to do.

I ran a blink code using pin 13 and an LED both L and LED is now blinking. But if I ran an empty code the L led is on continuously  also if I connect an LED with the empty code uploaded both the L Led and external LED goes out

Does L LED glowing continuously mean something? bcuz the programs that I run seem to do the work

Don't let that pin float undefined: If undefined (INPUT), pull it to GND to have the led OFF.
If ever possible, try to use the LED_BUILTIN pin as an OUTPUT pin.
And signal some information there. On an UNO (or other 328-based Arduino), this hint might collide with the SPI_SCK pin, which is D13 (PB5 on an atmega328). But as an SPI Master, this pin is at least OUTPUT (and thus will signal SPI activity).


text:
DIfferent baud rates of 434 MHZ transceiver
What are the different baud rates that I can set for 434 MHZ Transmitter? (I am using Arduino UNO and RadioHead lib to change the baud rates)

does the transmitter actually have baud rate settings?

If your 434MHz transmitter actually uses UART, you would have to look into the datasheet. If it is just a part of the RadioHead library (it seems so for me), have you searched it's documentation?


text:
How do I change the scope of an object?
I am using the File/Examples/Adafruit MQTT Library/mqtt_ESP8266 example as a model for my code.  In the example, the mqtt object is created as a global variable, and everything works fine.  However, I need to create the mqtt object in setup(), because the constructor parameters are not known until then.  If I move the constructor call
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

from the global namespace to inside setup(), I can no longer see it from inside loop().
I have tried declaring a pointer to mqtt in the global namespace, but don't know how to change it to point to the mqtt object that is created in setup().  How can I do this?
David

In general there is several ways to do it, none of them is the perfect one...

pointer to mqtt at global scope Adafruit_MQTT_Client * mqtt_ptr; and initialize it by mqtt_ptr = new Adafruit_MQTT_Client(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); in setup. Then you have to use arrow operator instead dot to access its methods. Or you can make an alias in loop (or whenever you need it) by Adafruit_MQTT_Client& mqtt = *mqtt_ptr; and access it in the same way as before.
returning reference to static variable created inside of function (singleton), but you have to provide parameters every time, even they're needed only for the first time. The static variable gets constructed only for the first call of function.
For esp8266 there might be available std::optional template. It's similar to pointer, but you don't have to use arrow -> operator. But there might be extraneous copy when you assign (create) it's value.
You can also extend 1. or 2. by own class to hold parameters and then return instance of Adafruit_MQTT_Client


text:
What is difference between ATMEGA32 and ATMEGA328?
I'm new in electronics. Just playing with Arduino boards.I just wanted to program ATMEGA328 micro-controller and use it without Arduino for compact design for my personal hobby project. I found there are ATMEGA32 and ATMEGA328 micro controllers in my local store. So, I wanted to know can I use ATMEGA32 instead of ATMEGA328 ? Which one is latest and whats are benefits. Thanks in advance.

The ATMega32 looks to be essentially the "big brother" of the ATMega328.  Just the same chip internally, but with more IO pins. I don't know about register / code compatibility, or Arduino core API support, having never used one.

you can't put ATmega32 into the DIP socket on Uno. the DIP version has a different size

I cannot tell for sure, but from a cursory look at the datasheets, the
ATmega32 looks older:

16 MHz maximum frequency v.s. 20 MHz for the ATmega328
4.5 V minimum supply voltage v.s; 1.8 V for the ATmega328
only one PWN channel per 8-bit timer

From an Arduino-programming point of view, I would prefer the 328, as it
would allow you to prototype your code on an Uno, and then move it to
the bare MCU, knowing it would work identically. The ATmega32 would be
worth consideration if you need more IO than the Uno can provide.

I can't post comments.
One difference is that the ATmega32 has JTAG; ATmega328P has not.

+1 It's not terribly complete, but it seems okay to post an answer.  It's answer type material at least.  And something not pointed out by others.

To answer this you'd need to study the according data sheets:
ATmega32
ATmega32u4
ATmega328
ATmega328P
ATmega328PB
Despite a similar name, the chips are quite different.
32u4 for examle has USB built in.
328PB has more 16-bit Timer/Counters.
... and many more differences.
They only differ on the hardware features and can be programmed in more or less the same way. It is up to you to choose which one you want to use.

The only nearly identical ones are 328 and 328P. If you don't care about the "picopower" feature you just have to know they have different signatures. To easiest move from an arduino (UNO or NANO) to a standalone controller, atmega328p is your choice.


text:
MP3 File through ARDUINO
Hey question is that it is possible to play MP3 file in arduino without changing it into .wav file if possible ,then your suggestions are welcome
Thanks

Yes, with an MP3 shield.

The UNO doesn't have the processing power to decode MP3.

Ok i will try for this ,thanks for your response :)

This little device is really good and easy to set up.
https://www.dfrobot.com/product-1121.html
You can use a pin and set it to ground with a resistor between to change songs if you don't need something fancy.


text:
How to connect Big Dome Button with arduino
I am quite new to arduino and for a project I want to use big dome button which when pressed it will count how many times has been pressed.It is using 12 volts.The button is this https://www.sparkfun.com/products/9181

a switch doesn't need voltage. the 12 V is for the indicator LED. you can wire the microswitch like any button

I looked at their demo video https://www.sparkfun.com/news/874 (@3:05) and did not see much about a 12V LED driver. If you own that Button already, just unscrew it and have a look at the led. Counting and score display has nothing to do with the button hardware.

More info from sparkfun: > "They use a 12V LED for illumination, but we found it works fine at 5V, albeit a bit dim."  I read:  unscrew it, search for the resistor or replace the led by a real one and your own resistor. The 12$ are charged for the plastic garbage, the "electronics" is for free.

As others have said, the 12V powers the switch's internal LED.

EDIT:
Switches don't need power. If you skip all power to the switch it will still work but it won't light up.
End of edit:

If you want the switch to light up, connect the V in to 12V, or if you connect it to 5V, it will be dim, but -probably- still light. (You are certain to have a 5V pin on your Arduino board. Using that means you don't need a separate 5V supply.)
Now connect one lead of the switch to a digital input, and the other lead to ground.
Then set your switch pin to INPUT_PULLUP mode. Now your switch will read HIGH until it's pressed, then it will read LOW.
create a variable at the top of your code called buttonState:
byte buttonState = HIGH;

Also define an unsigned long variable nextReadMillis:
unsigned long nextReadMillis = 0;

and a pressCount variable:
unsigned int pressCount = 0;

And define a debounceTime:
#define debounceTime 50

In your loop, do something like this:
void loop() {
    //Get the new millis(value)
    unsigned long newMillis = millis();

    //only look at the new button value if enough time has elapsed.
    if (newMillis >= nextReadMillis) {
       byte newButtonState = digitalRead(buttonPin);

       //Only do something if the button state has changed
       if (buttonState != newButtonState) {
          buttonState = newButtonState;
          nextReadMillis = newMillis + debounceTime;
          //If the button is now in the pressed (LOW) state, increment the count
          if (buttonState == LOW) {
              pressCount++;
          }
       }
    }
}

That's pseudo-code. It likely has syntax errors. It's not meant to be copy/pasted. Use it as a guide for your project.
The code using millis() is a version of "software debouncing." Electrical switches tend to "jitter" or "bounce" between their on and off states very rapidly when they are first pressed/released. By only checking for state changes after a brief delay, you ignore the jitter in the readings.
Note that if you want your LED to only light when the button is pressed, you could control it with another digital pin. You'd assign a different pin to controlling the LED output, set that pin to OUTPUT mode, and switch the pin based on button state inside the body of the if (buttonState != newButtonState) if statement.
If your LED draws ≤20mA at 5V, you could connect it directly to your output pin. If it draws more than that, you will need a transistor to drive it so you don't draw too much current from your output pin and burn it out. Wiring a transistor driver is beyond the scope of this post however.


text:
Converting 8 bit binary to a hexadecimal pair as unsigned char
I have a function:
void Epd::SendData(unsigned char data) {
  digitalWrite(dc_pin, HIGH);
  SpiTransfer(data);
}

At the moment I am hardcoding data sent to it by calculating on paper and then writing the result as code, but I want to improve that. For example, I am calling:
SendData(0x03);
SendData(0x1f);

To get those two values (0x03 and 0x1f) I am converting the decimal value of 799 to binary: 1100011111 and then adding 0 at the beginning to make sure my binary result is 16 digits long: 0000 0011 0001 1111. After that, I convert every 4 bits to hexadecimal value and sending them as pairs using the SendData function.
I feel like I am almost there, but I don't know how to convert my result to proper type in order to send it to the SendData function:
void Epd::SendDecAsData(int dec) {
  int binary[16];
  for (int i = 0; i < 16; i++) {
    binary[i] = dec % 2;
    dec = dec / 2;
  }

  int dec1 = binary[15] * 8 + binary[14] * 4 + binary[13] * 2 + binary[12];
  int dec2 = binary[11] * 8 + binary[10] * 4 + binary[9] * 2 + binary[8];
  int dec3 = binary[7] * 8 + binary[6] * 4 + binary[5] * 2 + binary[4];
  int dec4 = binary[3] * 8 + binary[2] * 4 + binary[1] * 2 + binary[0];

  String val1 = "0x" + String(dec1, HEX) + String(dec2, HEX);
  String val2 = "0x" + String(dec3, HEX) + String(dec4, HEX);

  SendData(val1); // error because I'm sending `String` instead of `unsigned char`
  SendData(val2);
}

I need help converting those strings (val1, val2) to the right data type, or even better, optimizing this process to get the final result in the right type with less code/computation (probably avoiding conversion to String).

If I understand you correctly, you want to split a 16-bit int into two unsigned chars and send them. Why the convoluted conversion to hex? Why not use something like SendData(dec >> 8); SendData(dec & 0xff);. It's just binary data, no need to convert.

@StarCat I just got the existing code (e-ink board) and I see they are sending hex value so I assumed I have to do the same. There is a ton of hardcoded SendData that is manually converted from dec to hex (for some reason as two SendData calls of 2 digit hex). So even when I just need to send 0 dec it is sent as SendData(0x00) called twice. I hope that explanation helps

What you are sending with SendData(0x00) is not a hex value. It's just represented in your code text by a hexadecimal value but it is converted to an (unsigned char) binary value during compilation. You can replace all occurences of 0xNN with their decimal value (as long as they're not part of a string) and your program will work exactly the same. Just try it.

799, 0x031f and B0000001100010111 are all stored as the same 16 bit binary number ... the differences are only in the source code for human reading ....  compiled code always deals with 0000001100010111 ... your whole conversion program is a waste of resources ... do what @StarCat suggested in the first comment

Thank you guys. I'll try as soon as I get to the office tomorrow

I am hardcoding data sent to it by calculating on paper and then writing the result as code ... what exactly are you doing here? ... please provide an example of the data involved in the calculation

@jsotola for example 031f is 799 which represents the width of the image I'm adding to the e-ink board. The code I'm using says that it needs to be broken into two separate calls of SendData but I will try the suggestions above. If that works I can delete sooooo much code :D

ok, the image width is hard coded ... if same value is used a lot then define something like width_h and width_l ... otherwise use the code that @StarCat suggested ... the reason that you have to break down 16 bit values is because the data is transmitted in bytes .... check the library, there may be 16 bit transmit function that does it for you

@jsotola there are a lot of images and each one with values (x, y, width, height) and not easily understandable because they are split as those two SendData commands so I wanted to make it easier to add new images and make the existing ones easier to read + delete a lot of code

I can indeed send decimal values instead of hexadecimal (mind blown). The board I'm working with can only take 8 bits of data at once so in order to send 799 decimal I first send 3 and then 31 (3*256 + 31). Knowing this I will manage to drastically clean up the code. I will just write a new method that breaks the decimal value I send as a pair of smaller decimal values. Thank you StarCat and jsotola

As StarCat suggested, I can just send decimal values using the same function SendData I was provided with. Because the e-ink board can only communicate in 8-bit commands I still had to split my decimal value before sending it.
This is the function I used to send decimal data in 8-bit pairs:
void Epd::SendDecAsData(int dec) {
  if (dec == 0) {
    SendData(0);
    SendData(0);
  } else {
    SendData((dec-1) / 256);
    SendData((dec-1) % 256);
  }
}


text:
Programming Questions / Capacitive Soil Moisture Sensor
Good day All,
This is my first time posting to this forum and kind off my last resort as I would've liked to figure it out myself. I am trying to create a soil moisture probe which can be used on farms to determine soil moisture at different depths. The project consists of a Arduino Nano, a DIY capacitive moisture reading setup (schematic attached- My setup is the same except for the LED moisture indicator)) and an LCD screen to display the required value.
My initial setup was a Arduino Nano (328P Old Bootloader) with a resistive soil moisture sensor. However, these sensors (as they are resistive) do not give reliable readings when measuring at different spots in a field. I believe it is largely influenced by pH, salt content etc.
My next approach was to build a DIY capacitive soil moisture sensor. After searching the web I came across a setup on hackster.io ( https://www.hackster.io/Pedro52/arduino-capacitive-soil-moisture-sensor-diy-with-esp32-d7ad72 ) where a signal is sent via a ESP 32 microcontroller to a probe in the soil and a signal is returned. I implemented the same setup with the same components however I only used optimization of the timers on the Nano to generate the PWM wave (Once again this code was also obtained from another website and I am still a bit confused on how the code works).
I seem to get a reading from the sensor but the zero value seems to very volatile. Even if the wire is only picked up, the output reading changes. Is there a way to get around this and can someone please help me to get my system working optimally.
It would be highly appreciated.

 /

    /The setup uses a Chinese Arduino Nano, a 10M ohm, a 10k ohm, a 1N4007 diode and a 1 microfarrad capacitor as shown in the schematic.
    //The LED moisture indicator in the schematic can be ignored

    //#include <LiquidCrystal_I2C.h>
    //#include <LcdBarGraphRobojax.h>
    #include <Wire.h>

    //LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 16, 2);
    //LcdBarGraphRobojax lbg(&lcd, 16, 0, 0);

    float Moistlevel = 0;
    float Moistpin = A1;
    float Moisture = 0;
    float RESET;
    float factor;
    const byte CLOCKOUT = 9;

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

  TCCR1A = bit (COM1A0);                  //Code which I obtained to initiate the onboard timer 1 to give a signal through D9
  TCCR1B = bit (WGM12) | bit (CS10);
  OCR1A =  0;                             // Apparently this should be changed for prescaling. Is it necessary?

  RESET = analogRead(Moistpin);           // Take a initial reading to zero the setup

  for (int j = 1; j < 5 ; j++)            // Take another 5 readings of which the average will be determined
  {
    RESET = RESET + analogRead(Moistpin);
    delay(200);
  };

  RESET = RESET / 6;

  Serial.print(RESET);
  Serial.println();

  Serial.print("Moistlevel");
  Serial.print("\t");
  Serial.print("\t");
  Serial.print("Moisture");
  Serial.println();
}

void loop() {

  Moistlevel = analogRead(Moistpin);                  //Take an average reading every second

  for (int i = 1; i < 5 ; i++)
  {
    Moistlevel = Moistlevel + analogRead(Moistpin);
    delay(200);
  };

  Moistlevel = Moistlevel / 6;
  Moisture = (RESET - Moistlevel) / (RESET / 100);    //Conversion to go from a voltage reading to a percentage reading

  if (Moisture < 0)                                   //Moves the initial if a negative moisture is obtained.
  {
    RESET = Moistlevel;
  };

  Moisture = (RESET - Moistlevel) / (RESET / 100);    //Obtains the new moisture value and prints it.

  Serial.println(Moistlevel);
  Serial.print("\t");
  Serial.print("\t");
  Serial.print("\t");
  Serial.print(Moisture);
  Serial.println();
  delay (500);
}

https://arduino.stackexchange.com/tour

Touching a capacitive sensor will change its readings, that's normal. Are you sure your code is sending the right frequency to the right pin?

I have tried different signals, all without any success...

Thanks to all for the advice,
I have chosen to divert the whole system and rather make use of a 555 timer to sent a frequency to the measuring pins. It has been tested and seems to resolve the issue completely.

Calling this a capacitive sensor may be inaccurate. And that could be the least of its problems. The "fritzing" schematic is unclear, and seems to be at odds with the explanation in Step 4 of the description. Fortunately, a legible schematic was derived here.
The author of the hackster.io article cites Andreas Speiss' well-known YouTube video on "Why Most Moisture Sensors Suck"... and then proceeds to design a moisture sensor that... sucks! This design seems to "miss the point": dc current causes an electrolytic reaction when the conductor is in direct contact with an electrolyte (like water and damp soil).
Wrt the OP's comment that touching the wire changes the output reading: It's almost certain that there is more capacitance in the lead wire than there is in the "fondue forks". According to the article, audio cable was the author's choice for transfer of a 600 kHz signal from his breadboard to the sensor. The long-ish lead wires to the sensor strike me as an odd choice.
I've been more than a little critical of this hackster.io project. But of course I may have overlooked something important - I make mistakes each and every day. If someone cares to point out any mistakes I've made here, I'll be glad to revise or delete this post. Until then, my proposed answer is to find a better DIY project.
Nevertheless - you are on the right track by deciding to build a capacitive moisture sensor. Unless the "fondue forks" are insulated to render them non-conductive when immersed in the soil/water electrolyte, this is not a capacitive sensor - it is resistive. And its flaws may go even deeper. Another DIY guide may yield better results.
For anyone interested, an LTspice simulation of the sensor circuitry may provide insights into its operation. In one case, the sensor is modeled as a purely capacitive device (i.e. the "Fondue Forks" are insulated to prevent dc current from flowing through the soil), and in the second case as an R-C circuit (i.e. the "Fondue Forks" are un-insulated, and dc current flows through the soil). The values for Rw2 and C2/C1 were based on measurements I made with a similar sensor:

I made the following observations using this model of the sensor:

the time constant for the RC filter on the sensor output may be substantially longer than necessary.

Note the dc current flow through Rw2 averages ~ 0.18mA. Knowledge of this value will allow use of Faraday's Law of Electrolysis to estimate how much of the chrome plating will be dissolved in your soil over time.

The value of Rw2 largely determines the value of the output voltage; the value of the capacitance plays a much smaller role. Thus, this sensor is mostly resistive rather than capacitive.

The LTspice .asc file follows; all feedback welcomed:
Version 4
SHEET 1 908 720
WIRE 336 32 288 32
WIRE 352 32 336 32
WIRE 512 32 432 32
WIRE 288 80 288 32
WIRE 336 80 336 32
WIRE 416 80 336 80
WIRE 512 80 512 32
WIRE 512 80 480 80
WIRE 512 96 512 80
WIRE 160 208 128 208
WIRE 288 208 288 144
WIRE 288 208 240 208
WIRE 480 208 288 208
WIRE 288 288 288 272
WIRE 288 288 128 288
WIRE 480 288 288 288
WIRE 288 304 288 288
WIRE 320 368 272 368
WIRE 336 368 320 368
WIRE 512 368 416 368
WIRE 272 400 272 368
WIRE 320 416 320 368
WIRE 416 416 320 416
WIRE 512 416 512 368
WIRE 512 416 480 416
WIRE 512 432 512 416
WIRE 160 528 128 528
WIRE 272 528 272 464
WIRE 272 528 240 528
WIRE 384 528 272 528
WIRE 464 528 384 528
WIRE 272 608 272 592
WIRE 272 608 128 608
WIRE 384 608 272 608
WIRE 464 608 384 608
WIRE 272 624 272 608
FLAG 288 304 0
FLAG 272 624 0
FLAG 480 208 Vsensor1
FLAG 464 528 Vsensor2
FLAG 512 96 0
FLAG 512 432 0
FLAG 288 32 Vout-insul
FLAG 272 368 Vout-unins
SYMBOL voltage 128 192 M0
WINDOW 3 -172 139 Left 0
SYMATTR Value PULSE(0 3.3 0 20n 20n 833.5n 1667.0n)
SYMATTR InstName V1
SYMBOL voltage 128 512 M0
WINDOW 3 -140 138 Left 0
SYMATTR Value PULSE(0 3.3 0 20n 20n 833.5n 1667.0n)
SYMATTR InstName V2
SYMBOL cap 256 528 R0
SYMATTR InstName C2
SYMATTR Value 80.0p
SYMBOL res 368 512 R0
SYMATTR InstName Rw2
SYMATTR Value 5000
SYMBOL res 256 192 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName Rs1
SYMATTR Value 10k
SYMBOL res 256 512 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName Rs2
SYMATTR Value 10k
SYMBOL cap 272 208 R0
SYMATTR InstName C1
SYMATTR Value 80.0p
SYMBOL diode 304 144 R180
WINDOW 0 24 64 Left 2
WINDOW 3 24 0 Left 2
SYMATTR InstName D1
SYMATTR Value 1N4007
SYMBOL diode 288 464 R180
WINDOW 0 24 64 Left 2
WINDOW 3 24 0 Left 2
SYMATTR InstName D2
SYMATTR Value 1N4007
SYMBOL res 448 16 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName R1
SYMATTR Value 1Meg
SYMBOL res 432 352 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName R2
SYMATTR Value 1Meg
SYMBOL cap 480 64 R90
WINDOW 0 0 32 VBottom 2
WINDOW 3 32 32 VTop 2
SYMATTR InstName C3
SYMATTR Value 10.0n
SYMBOL cap 480 400 R90
WINDOW 0 0 32 VBottom 2
WINDOW 3 32 32 VTop 2
SYMATTR InstName C4
SYMATTR Value 10.0n
TEXT 96 696 Left 1 !* .tran 0 2m 1.99m\n.tran 0 50.0m 49.99m
TEXT 312 168 Left 2 ;Insulated "Fondue Forks"
TEXT 288 488 Left 2 ;Non-insulated "Fondue Forks"
RECTANGLE Normal 256 184 640 316 2
RECTANGLE Normal 256 508 640 628 2

Seems the OP cross-posted this question here & got some answers.


text:
I'm looking for a way to emulate addressable LED strip using LED diodes in a custom arrangement
What I want to achieve is, I want to use my own LED pin diodes, customly place them into my sculpture and animate them. This is as I understand quite straightforward. The problem is the amount of wiring . I would want them to connect one another in series with addresses, rather then each led needing a direct data from the controller on a separate cable.
I know that addressable LEDs use a single data line through the all lights, eliminating the need to connect each led physically to the controller to get data. Is there any way to build a similar system with a bus-like structure, I believe it is possible. And if so, how? What would I need? I guess I need individual small chips for each LED, but I don't know if that's the case or even if it is how so.
I consider myself quite a newbie in electronics-arduino or LEDs, however I'm actively looking into it and researching.

You could buy the same chips, that are on the addressable LED strips, the WS2811 or its siblings.

If you connct ordinary LEDs to the same wire, the will behave relativly the same. You would have no chance to control them separately. If you use a PWM controller like WS2811, or 3 PWM pins from an Arduino to control one single LED you can control the LEDs separately. But from the amount of work and money you have to invest, this is only adviceble, if you can not exchange the currently used LEDs for the project/scupture. If possible use prebuild WS2811 LEDs like neopixels.

you can buy addressable LEDs that have leads

You can buy individually addressable LEDs like the ones in LED strips. If you are fairly new to electronics I would not try to build your own serial LED controller.

I think this may be the safest option. I'm trying to understand the size limitations and the cost of these kind of systems. It turns out that there are even small pin LEDs  with IC that are addressable! Thank you


text:
Using ESP32CAM board but no face is enrolled
I was working on a project to use the ESP32CAM board to detect faces and open some sort of lock. The program can detect the face using the yellow box that shows up as you can see from the following image:

But after clicking "Enroll Face", nothing changes. I'm currently using the default CameraWebServer application located in the ESP32CAM board examples. Any advice to solve these issues would be greatly appreciated

The short version is you need an ESP32-S3 (which the ESP32CAM isn't) if you want practical face recognition from this example. But you may be able to make face recognition work on the ESP32CAM with this example very slowly if you really want to try it.

A comment the example code explains:

You must select partition scheme from the board menu that has at least 3MB APP space.
Face Recognition is DISABLED for ESP32 and ESP32-S2, because it takes up from 15
seconds to process single frame. Face Detection is ENABLED if PSRAM is enabled as well

My understanding is "detection" refers to just what you're seeing in the image you've included, that it can find faces (any face) and draw a box around it. This makes sense because the board has PSRAM.
"Recognition" is detection of the specific face you "enroll", which "is DISABLED for ESP32". And the ESP32CAM uses an ESP32 (importantly not more powerful ESP32-S3)
You can see this again in the form of code rather than a comment in the web server code.
The web page served is not configured to show anything different when those features are disabled. It it just passes events back to the web server code. However, if you're looking at the serial output you should see messages saying "Unknown command: face_enroll" and "Unknown command: face_recognize" if you have the Core Debug Level setting at Info level or higher.

They say it takes 15 seconds on an plain ESP32, which apparently means it is possible if a bit useless. So, if you really want to try it you may be able to modify this line in app_httpd.cpp to read:
#define CONFIG_ESP_FACE_RECOGNITION_ENABLED 1

I may try it later if I find my ESP32CAM. But the expectation is that it will "work" but have horrible performance. Well, I found my ESP32CAM and edited that line and yes, it barely functions, but you can see that does technically work, at least for a little while. I may be crashing it during the enroll process or it might just be picking up what it thinks are extra faces and it's so bogged down that it stops responding, which may have motivated why they just disabled it outright. Either way, yeah, it behaves more or less as explained by the comment.


text:
More than one port available in Arduino IDE in Ubuntu
I'm using Jetson AGX Xavier, and in my Arduino IDE, there are dev/ttyUSB0, dev/ttyUSB1, dev/ttyUSB2, dev/ttyUSB3. I'm sure I connect Arduino in USB0, but I cannot download the code. The device is also correct. Even if I disconnect the Arduino, the available ports are the same.
When I googled it, it turns out the port should be only one. Like, should be only "dev/ttyUSB0". So it really confused me.

You can find what your serial port are with ls -l /dev/serial/by-id

Exactly what Arduino are you using? Is it genuine? Is it a Chinese clone?

If you're sure that you choosed the right port, try reinstalling the Arduino IDE. Maybe this will solve your problem. If it won't, try installing an older IDE.


text:
How to increase the frequency of data transmission of SIM900A GSM Module connected to Arduino Uno?
I have a SIM900A GSM Module hooked onto an Arduino Uno board. The Arduino is connected to a MPU6050 Accelerometer which is constantly monitoring data at 1 second interval. I am trying to transmit the gathered data to ThingSpeak server. I have successfully established the connection with the server and the transmission is occurring. However, the interval between two transmitted readings are very large, varying between 1 to 3 minutes. That interval is too large to use the data. Is there any way I can enhance the transmission frequency so that the data points are close enough? At least to a few seconds distance?

Just to verify, could you check if once per 20s works better? A free account will reject updates more frequent than once every 15s (showing HTTP 200 with a "0" response).

My thingspeak account is operated through my university granted mathworks account. It is a licensed account. The problem I am encountering concerns the transmission part. The module processes a whole bunch of AT commands then only gathers the data and send to server.

Start simple and add features as the simple things work.  Also, with out your code we can suggest little.  That said, create a version of code to send fixed data to the server and verify you can post data as often as you would like.  Many servers will throttle your updates if you post to fast.  Then add the accelerometer.  Get that working.  Then add the GPS.

Why not buffer 15 mins worth of samples and send them all at once?

@dandavis Your solution has crossed my mind and I did give that a go. But I could not make that work, mostly because of my lack of expertise. Can you point me towards the right direction?

There does not appear to be a complete description of how ThingSpeak throttling works.  However there is this text on the Thing Speak License FAQ web page:

As a reference, one unit provides the ability for a device sending
data to ThingSpeak at once per second to send data to ThingSpeak for
one year.

Assuming your code is working as expected and the ThingSpeak throttling is to suspend your service for 15 minutes, it may be that you are sending data faster than ThingSpeak will allow.
To test this, try to send messages slower than once per second.


text:
Speed data logging using arduino and GPS module
I am using a Quectel L80-R GPS Module coupled with an Arduino UNO to read and log my car's coordinates and speed. I am currently using TinyGPS++ library which works okay. It does spell out coordinates and speed but with some inaccuracies and delays. After some literature review I realized that NeoGPS library might be a better option. I found a thread over stackexchange where a code block is provided written by slash-dev who most possibly is the writer of NeoGPS library. However, when I am trying to compile the code, I get the following error
'class gps_fix' has no member named 'lat' .I can not get rid of the issue even tough I've tried a whole bunch of workarounds.

Have you looked at the NeoGPS library source code or one of the examples that come with the library to see what class members are available with gps_fix?

Looking at this documentation you might need fix.latitudeL() and fix.longitudeL() instead of fix.lat and fix.lon.

I was under the impression that latitude, longitude & speed (and many other values) were products of the GPS module.  Software like TinyGPS and NeoGPS mostly just configure the GPS module and parse the data stream.  What do you mean by inaccuracies and delays?  On a good day, a cheap (uncorrected) GPS module should be about +/- 10 meters latitude and longitude.  And much worse (maybe 5 to 10 times as bad) for altitude.

According to the NeoGPS documentation for the gps_fix class, it looks like .lat and .lon are no longer part of the gps_fix class.
It looks like instead you will have to use .latitudeL and .longitudeL for high precision (Long Integer scaled by 10,000,000) GPS coordinates.
The solution would be to replace fix.lat in your code with fix.latitudeL and fix.lon with fix.longitudeL.


text:
How do I make a motor spin every 10 minutes?
I am new to Arduino, please don't be harsh. I want to make a motor spin at every x amount of time (Lets say 10 minutes). Once the program is started, I want it to start the motor (stop after 10 seconds), and every 10 minutes, it continues the process. Is it possible to make it?,

Yes, possible and a good start for a beginner. Look into the BlinkWithoutDelay example. Try some tutorials about millis(). That will give you the understanding about how you can do timed things with an Arduino. If you have any specific problems with that, you can always come back here and ask about it :)

The simplest option is to use delay() to implement the waits:
void loop() {
    turn_motor_on();
    delay(10000);  // 10 seconds
    turn_motor_off();
    delay(600000);  // 10 minutes
}

Since these long numbers may be difficult to read, you can make them
more readable by defining some units:
const unsigned long second = 1000;
const unsigned long minute = 60000;

Then you can for example delay(10 * minute);
Beware there is a trap if you try to do arithmetics with integer
literals. The following:
delay(10 * 60 * 1000);  // BUG!

will not work on most Arduinos, as the multiplications will be
performed on the int data type, which can only hold numbers up to
32,767. It is safer to use either explicitly typed constants (unsigned long is the appropriate type for delays) or integer literals typed with
the suffix UL (which stands for “unsigned long”).
Note that the Arduino will do no useful work while delaying. If you want
to do any kind of work during the delay, see the “Blink Without Delay”
Arduino example.

Dude! Teaching a newbie to use delay? That path leads quickly to madness! (To the OP: It's fine until you want to check for a button press, read a sensor, or do anything else during that delay. The Arduino comes to a screeching halt in a delay.)

I would advise learning to use millis() to accomplish the same thing, right away. If you use delay() you will only end up having to rewrite your code later.

@DuncanC: Yes, when a beginner is at level 0, I think starting with the simplest possible approach is better. And delay() is simpler than millis(): that's why Blink is in section 1 of the Arduino examples while BlinkWithoutDelay is in section 2. Also “having to rewrite your code later” is actually a good thing for a beginner. That's how you learn! But note that I warned the OP that he may have to use the BlinkWithoutDelay approach at some point.

Yes, of course it's possible.  The loop() function might look something like:
loop(){
    turn_motor_on();
    wait_seconds(10);
    turn_motor_off();
    wait_minutes(10);
}

Now all you have to do is write your turn_motor_on() and off functions and also wait_seconds() and wait_minutes().  I'll leave the motor controls to you since you have not provided any detail on how the motor is hooked up.
You could use the Arduino delay() function:
void wait_seconds(int num_seconds){
    for(int i=0; i<num_seconds; i++){
        delay(1000);
    }
}

void wait_minutes(int num_minutes){
    for(int i=0; i<num_minutes; i++){
        delay_seconds(60);
    }
}

Of course there are many other ways to do this but this method is simple and easy to understand and will get you started easily.


text:
Is it possible to configure uboot without the "Yun Serial Terminal" sketch by using the hardware serial on pins 0 and 1 instead?
Trying to rescue a Yun with the 1.5.3 image.
It's not possible to upload the required "Yun Serial Terminal" sketch  because the device hangs at U-Boot (hence the rescue attempt).
Using putty serial with:
Pin 0 (Rx)
Pin 1 (Tx)
Baud: 250000
8N1
This capture shows the result (which is the best I can find so far).
How do I properly connect to the serial console using the GPIO pins?

Hold the MCU in RESET to prevent it interfering.


text:
I2C protocol doesn't work properly
I am trying to make I2C Communication between NodeMCU and arduino Uno boards. However it is not working properly. It makes communication for once time when i uploaded code.
Master Device Code(NodeMCU 1.0)
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <Wire.h>

HTTPClient client;

StaticJsonDocument <200> doc;

const char* ssid = "MY_SSID";
const char* pass = "MY_PASSWORD";

void setup() {
  Serial.begin(9600);
  Wire.begin(D1,D2);
  WiFi.begin(ssid,pass);
  while(WiFi.status() != WL_CONNECTED) {;}
}

void loop() {

  const char* cd = getCode();
  if(cd==nullptr) {
    Serial.println("Problem Occurred.");
    delay(10000);
    return;
  }
  //Bad code is starting...
  //Basically, sending 24 bytes of data for a Wire Transmission

  int n = strlen(cd);
  int rem = n%24; //remainder
  int quo = (n-rem)/24; //quotient

  while(quo!=0) {
    char sel[24];

    for(int i =0;i<24;i++) {
      sel[i] = cd[((((n-rem)/24)-quo)*24)+i];
    }

    Wire.beginTransmission(8);
    Wire.write(sel);
    Wire.endTransmission();
    quo-=1;
  }

  char sel[rem];

  for(int i =0;i<rem;i++) {
    sel[i] = cd[n-rem+i];
  }

  if(rem>0) {
     Wire.beginTransmission(8);
     Wire.write(sel);
     Wire.endTransmission();
  }
  //Bad code finished!

  //this is also not working.
  Wire.requestFrom(8,3);

  while(Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }

  delay(15000);
}

//get code from server.
const char* getCode() {
  client.begin("http://...");

  int res = client.GET();

  if(res<0) {
    return 0;
  }

  String root = client.getString();
  deserializeJson(doc,root);
  const char* code = doc["Liste"][0]["code"];
  return code;
}

Slave Device Code(Arduino Uno)
#include <Wire.h>

void setup() {
  Serial.begin(9600);
  Wire.begin(8);
  Wire.onReceive(received);
  Wire.onRequest(requested);
}

void loop() {delay(200);}

void received(int bytes) {

  while (Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }

}

void requested() {
  Wire.write("abc");
}

Circuit:
D1-SDA
D2-SCL
GND-GND

To which voltage 3.3V or 5V do you pull up the SCL and SDA line? Is the MCU a 3.3V  controller? Just connecting D1-SDA D2-SCL is not enough. If the electrical setup is OK, you could remove all the Wifi and JSON code from the MCU prog and try I2S alone. Another strange thing: you call client.begin("http://..."); each time you call the getCode() method without client.end(). Perhaps this crashes the connection to the server. I don't know if the client.begin is safely callable twice without calling close before..

You may need to do some additional research. I'm debugging some I2C problems myself at the moment. Happy to share what my research has turned up:
Guiding Ideas - What could break?

Physical Layer

Unintentionally switched connections (SDA<>SCL)
Incorrect Pins selected on Microcontroller
Pull-up Resistors

Too many

Devices often have pull-ups installed by default. Only one set is needed per bus. Rule of parallel resistors applies to calculate effective resistance.

Too big (too high resistance)
Too small (too low resistance)

Voltage Conversion / Mismatched  devices
Spikes or noise on SDA, SCL or Vcc
Parasitic Capacitance

wire / trace design
bus too long

Protocol Layer

Bus Addresses incorrect / collisions
No ACK received from slave  (ref. TI article "Troubleshooting I2C Bus Protocol" below)

Timing
Missing / Unexpected SCL pulses
Incomplete 8 bit block
Missing Bytes
False slave address
Unsuccessful address change

NACK signal meaning ambiguity
Clock speed mismatch (should be running at the speed of the slowest slave on the bus)
Blocked bus (i.e., a device has reset or dropped during transmission putting the bus into an invalid state. There is no timeout.)
Multimastering (too many masters on bus?) - if more than one all must support multi-master mode
Clock stretching (a slave is holding the clock low)
What part of the message is missing? Is the initial ACK from the slave received?

Code Layer

For boards with multiple I2C ports, correctly passing the desired port to the relevant library.
Use of interrupts causing timing problems
Use of blocking code structures causing timing problems

Testing Methods

Bus Pinging / Bus Scan (like Arduino Multi-speed scanner https://forum.arduino.cc/index.php?topic=197360)
Connect additional devices to the bus and see which combinations work to identify the failing item
Multimeter checks

Stable Vcc?
Common Ground?
(Open Drain) pull-up resistance from SDA & SCL to Vcc

Test devices like Bus Pirate
Oscilloscope Analysis / Decode (references below)
Sifting out which device is causing the problem. (See Hackaday article) Put different-value resistors on the output of all chips on the bus. The low voltage values will be slightly different for each chip, allowing you to see on a scope which chip is talking at any given time, and diagnose when they’re talking over each other.
install I2C multiplexor to seperate bus into a single connector for each device (i.e., from bus to star topology) (e.g., PCA9544A)

References
I2C General

For Arduino Programming Arduino Next Steps - Going Further with
Sketches Chapter 7
For ESP32
https://randomnerdtutorials.com/esp32-i2c-communication-arduino-ide/

I2C Debug Advice

I2C Primer (I2C-bus.org) - a good reference for everything discussed here https://www.i2c-bus.org/i2c-primer/

Common Problems https://www.i2c-bus.org/i2c-primer/common-problems/
Obscure Problems https://www.i2c-bus.org/i2c-primer/obscure-problems/ Analysing Obscure Problems https://www.i2c-bus.org/i2c-primer/analysing-obscure-problems/

WHAT COULD GO WRONG? I2C EDITION (Hackaday) https://hackaday.com/2016/07/19/what-could-go-wrong-i2c-edition/
How to design and debug a custom I2C master-slave system? (Stack Exchange) How to design and debug a custom I2C master-slave system?
Troubleshooting I2C Bus Protocol  https://www.ti.com/lit/an/scaa106/scaa106.pdf

Oscilloscope Analysis of I2C

How to debug I2C through waveform analysis (Texas Instruments) https://www.ti.com/lit/an/slyt770/slyt770.pdf
Using an oscilloscope to debug the I2C protocol https://www.electronicproducts.com/using-an-oscilloscope-to-debug-the-i2c-protocol/

I will get reference this answer for my future projects. I found solution but unfortunately can't remember, however i guess it was related with code layer.

A few of my tips:

if Arduino is powered using VIN port, the battery must STRICTLY between 7 to 12 volts, otherwise the Arduino board is unstable. Serial communication typically require good board stability
A capacitor (100 to 500uF) across the 5V (or 3.3V) and GND port helps to give I2C device a consistent voltage level, which is essential