text:
Can I flash hoodloader2 or HEX files on Arduino Simulators?
I want to make a HID Keyboard out of Arduino UNO, in UNO board the script runs perfectly fine, but the UNO board requires me to flash it every-time I want to put in a new script in it, so can I do the same on an Arduino Simulator? can I Flash Hoodloader2 on Arduino simulators by shorting the ICSP pins on UNO Board on a Simulator? if yes, please suggest the name of the application/ website.

which simulator?  ... why don't you just test it instead of asking?

Only Arduino boards with ATmega16u2 as USB adapter can use Hoodloader. So not even all Uno clones can use it.
I doubt the simulator is so precise that it would simulate the second MCU on Uno to allow flashing it over its ICSP heeader (ICSP2). I guess it doesn't even support flashing the main MCU over ICSP.
If the simulator supports Arduino Lenonardo, then you can maybe use the HID library. Leonardo has ATmega32u4 which has native USB support.


text:
Does anyone have code that successfully calculates velocity from an accelerometer
I'm trying to calculate the speed of a rocket for my project. I've been given the task of calculating this with an adxl3xxx accelerometer sensor. I'm not sure how to go about this as an accelerometer takes gravity acceleration into account. Can someone provide some form of code to help me understand. I've heard some theory like caliculatong yaw, pitch and roll then using trig to factor out gravity. Not sure how that works. I've also heard about quartenions not sure what they are. If someone could help me out that would be great thx

https://arduino.stackexchange.com/search?q=velocity+accelerometer

Calculating velocity from acceleration is not easy.  Simply put, velocity is derived by calculating the integral of acceleration with respect to time.  In practice, however, this leads to accumulated errors which generally render the process impractical for any but the shortest amount of time.
For further reading, this Wikipedia Kinematics page does a good job at relating acceleration, velocity and position using math.

… calculating yaw, pitch and roll then using trig to factor out
gravity …

Essentially, this is the first of two steps in coding up a tilt compass (the type you find in your cell phone).  You need the yaw, pitch and roll information before you can make sense of the magnetometer data.  Consider reading the first half of a tilt compass description to understand how to calculate yaw, pitch and roll.  Like this one.

I've also heard about quartenions not sure what they are.

Quaternion are an alternative to using trigonometry to derive (in this case) yaw, pitch and roll.  There are two advantages (in this case).  First, Quaternions are easier for a computer to calculate. Second, Quaternion yaw, pitch and roll calculations do not go to infinity for certain situations.  In the real world using physical gyroscopes this is commonly known as Gimbal lock.
Added later...

How would i go about using trig?

Trigonometry is not necessary if it is physically arranged such that all acceleration to gain the velocity of interest occurs only in 1 of the X, Y or Z directions of the accelerometer.  Then all that is need is to integrate the accelerometer readings in that direction with respect to time.
If this happens to be in the same direction as earth's gravity, simply subtract 9.8m/s2 out.
If you can't physically arrange it, then you need to read all 3 (X, Y & Z) accelerometer values. From this data pitch and roll can be calculated.  The trigonometry equations for this is on page 21 of the  "tilt compass description" link above.

That said we notice on that same page an equation to calculate the magnitude of acceleration.

So it may be possible that we can calculate the velocity due to the magnitude of the overall acceleration by sampling the accelerometer X,Y & Z sensors over time.  And avoid trigonometry entirely.
However there is a problem.  We have not accounted for gravity.  Again, if we assume gravity is in the same direction as travel we can subtract it it out.  But if travel is, say, 45 degrees off from the gravity vector, we would only want to subtract cos(45) * 9.8m/s2.  Consider only knowing the overall acceleration magnitude does not supply enough information to determine the angle between the acceleration due to gravity and acceleration due to a change of velocity from zero to an unknown velocity with respect to earth.
At this point decisions need to be made regarding how to account for gravity.  9.8m/s2 may be trivial when compared to the vehicle's acceleration and therefor can be ignored.  Or it may be so critical that extreme measures like tracking where the sun is in the sky become a feasible way to find the actual pitch and roll of the vehicle.

OMGoodness, did I really say "gumball lock"?

How would i go about using trig?

I can not answer that in the space of a comment.  So I will add it to the end of the above answer.

Also, this video may help.  But pay attention to what he says at this point in that video.

source: Stack Exchange

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

sort: votes


text:
Getting more Hz while working with 3 serial ports (IMU sensors)
im doing a university project where we use 2 IMU sensors and a SD card reader to save the data from sensors.
As you will probably see from the code, we specify the sensor port we listen to, save data to strings and then we open a port to SD reader and save the data.
Everything is in loop.
The problem is we only get around 5Hz (10Hz with only one sensor) - visible by the timer, which is sadly not enough for our project.
I heard about using a fifo buffer, but im not so good at low level programing. Anyway you can help?
Also, do you think removing all Serial.print could help with a little performance boost?
sensors - https://wiki.dfrobot.com/Serial_6_Axis_Accelerometer_SKU_SEN0386#target_0
uCon - Arduino Uno Rev3
#include <DFRobot_WT61PC.h>
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

#define FILE_BASE_NAME "Pomiar"
#define VCC2 7

const uint8_t CS_PIN = 4;

SoftwareSerial mySerial(2, 3);
SoftwareSerial mySerial2(5, 6);
DFRobot_WT61PC sensor(&mySerial);
DFRobot_WT61PC sensor2(&mySerial2);

File myFile;
File file;

const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
char fileName[] = FILE_BASE_NAME "00.txt";

void setup()
{

  pinMode(VCC2,OUTPUT);
  digitalWrite(VCC2,HIGH);

  //Use Serial as debugging serial port
  Serial.begin(9600);
  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  while (SD.exists(fileName)) {
    if (fileName[BASE_NAME_SIZE + 1] != '9') {
      fileName[BASE_NAME_SIZE + 1]++;
    } else if (fileName[BASE_NAME_SIZE] != '9') {
      fileName[BASE_NAME_SIZE + 1] = '0';
      fileName[BASE_NAME_SIZE]++;
    } else {
      Serial.println(F("Can't create file name"));
      return;
    }
  }

  //Use software serial port mySerial as communication seiral port
  mySerial.begin(9600);
  mySerial2.begin(9600);
  //Revise the data output frequncy of sensor FREQUENCY_0_1HZ for 0.1Hz, FREQUENCY_0_5HZ for 0.5Hz, FREQUENCY_1HZ for 1Hz, FREQUENCY_2HZ for 2Hz,
  //                        FREQUENCY_5HZ for 5Hz, FREQUENCY_10HZ for 10Hz, FREQUENCY_20HZ for 20Hz, FREQUENCY_50HZ for 50Hz,
  //                        FREQUENCY_100HZ for 100Hz, FREQUENCY_125HZ for 125Hz, FREQUENCY_200HZ for 200Hz.
  sensor.modifyFrequency(FREQUENCY_100HZ);
  sensor2.modifyFrequency(FREQUENCY_100HZ);
}

void loop()
{

  long timestamp = millis();

  String acc1 = "";
  String acc2 = "";
  String acc3 = "";
  String gyro1 = "";
  String gyro2 = "";
  String gyro3 = "";
  String angle1 = "";
  String angle2 = "";
  String angle3 = "";

  String acc12 = "";
  String acc22 = "";
  String acc32 = "";
  String gyro12 = "";
  String gyro22 = "";
  String gyro32 = "";
  String angle12 = "";
  String angle22 = "";
  String angle32 = "";

  mySerial.listen();
  if (sensor.available()) {

    acc1 = sensor.Acc.X;
    acc2 = sensor.Acc.Y;
    acc3 = sensor.Acc.Z;
    gyro1 = sensor.Gyro.X;
    gyro2 = sensor.Gyro.Y;
    gyro3 = sensor.Gyro.Z;
    angle1 = sensor.Angle.X;
    angle2 = sensor.Angle.Y;
    angle3 = sensor.Angle.Z;

    Serial.print("Acc\t"); Serial.print(sensor.Acc.X); Serial.print("\t"); Serial.print(sensor.Acc.Y); Serial.print("\t"); Serial.println(sensor.Acc.Z); //acceleration information of X,Y,Z
    Serial.print("Gyro\t"); Serial.print(sensor.Gyro.X); Serial.print("\t"); Serial.print(sensor.Gyro.Y); Serial.print("\t"); Serial.println(sensor.Gyro.Z); //angular velocity information of X,Y,Z
    Serial.print("Angle\t"); Serial.print(sensor.Angle.X); Serial.print("\t"); Serial.print(sensor.Angle.Y); Serial.print("\t"); Serial.println(sensor.Angle.Z); //angle information of X, Y, Z
    Serial.println(" ");
  }

  mySerial2.listen();
  if (sensor2.available()) {

    acc12 = sensor2.Acc.X;
    acc22 = sensor2.Acc.Y;
    acc32 = sensor2.Acc.Z;
    gyro12 = sensor2.Gyro.X;
    gyro22 = sensor2.Gyro.Y;
    gyro32 = sensor2.Gyro.Z;
    angle12 = sensor2.Angle.X;
    angle22 = sensor2.Angle.Y;
    angle32 = sensor2.Angle.Z;

    Serial.print("Acc2\t"); Serial.print(sensor2.Acc.X); Serial.print("\t"); Serial.print(sensor2.Acc.Y); Serial.print("\t"); Serial.println(sensor2.Acc.Z); //acceleration information of X,Y,Z
    Serial.print("Gyro2\t"); Serial.print(sensor2.Gyro.X); Serial.print("\t"); Serial.print(sensor2.Gyro.Y); Serial.print("\t"); Serial.println(sensor2.Gyro.Z); //angular velocity information of X,Y,Z
    Serial.print("Angle2\t"); Serial.print(sensor2.Angle.X); Serial.print("\t"); Serial.print(sensor2.Angle.Y); Serial.print("\t"); Serial.println(sensor2.Angle.Z); //angle information of X, Y, Z
    Serial.println(" ");
  }

  myFile = SD.open(fileName, FILE_WRITE);

  if (myFile) {
    myFile.print(timestamp);
    myFile.print("|");
    myFile.print(acc1);
    myFile.print("|");
    myFile.print(acc2);
    myFile.print("|");
    myFile.print(acc3);
    myFile.print("|");
    myFile.print(gyro1);
    myFile.print("|");
    myFile.print(gyro2);
    myFile.print("|");
    myFile.print(gyro3);
    myFile.print("|");
    myFile.print(angle1);
    myFile.print("|");
    myFile.print(angle2);
    myFile.print("|");
    myFile.print(angle3);
    myFile.println("");

    myFile.print(timestamp);
    myFile.print("|");
    myFile.print(acc12);
    myFile.print("|");
    myFile.print(acc22);
    myFile.print("|");
    myFile.print(acc32);
    myFile.print("|");
    myFile.print(gyro12);
    myFile.print("|");
    myFile.print(gyro22);
    myFile.print("|");
    myFile.print(gyro32);
    myFile.print("|");
    myFile.print(angle12);
    myFile.print("|");
    myFile.print(angle22);
    myFile.print("|");
    myFile.print(angle32);
    myFile.println("");

    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }
}

do you think removing all Serial.print could help with a little performance boost? ... why are you asking this? ... what is preventing you from doing a test?

Have you tried checking via millis() what exactly is taking so much time? And why are you saving all the data in strings? The data is of type float

Converting floats into Strings will take some time, did you benchmark this? -- To get least overhead for debugging, you can simply toggle some pin and measure the time with an oscilloscope. With respect to the communication signals to/from the sensors you will see where the time is spent.

There is a memory device called FRAM, It is available in many sizes. I work with 32Kx8 which is under $5.00 US from my favorite china supplier. No write delays, works with SPI or I2C you can get either already mounted on a PCB. For you I would recommend SPI. It is non volatile memory so it will retain the date when power fails. It is good for over 1 trillion cycles.

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


text:
Problem with reading MIFARE 13.5Mhz with MFRC522 lib
I'm trying to read the UID of MIFARE 13.5Mhz cards with MFRC522 lib and I have defined the following function for it.
void getUID() {
if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
  Serial.println("Scanned PICC's UID:");
  tag = "";
  for (byte i = 0; i < mfrc522.uid.size; i++)
   {
    tag.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    tag.concat(String(mfrc522.uid.uidByte[i], HEX));
   }
  tag.toUpperCase();
  Serial.println(tag);
  mfrc522.PICC_HaltA(); // Stop reading
}
}

this function works perfectly fine in void loop() but when I call it in the following web request my esp8266 crashes.
controlserver.on("/searchuid", HTTP_POST, [](AsyncWebServerRequest *request){

    transmit = request->arg("idcode");
    if (request->hasArg("configmodule")) {
    File file = SPIFFS.open("/inputString.txt", "r");
    if (!file) {
    Serial.println("Failed to open file");
    return;
    }
    getID();
    delay(500);
    Serial.println(tag);
    String content = file.readString();
    if (content.indexOf(tag) >= 0) {
    Serial.println("Found search string");
  } else {
    Serial.println("Did not find search string");
  }

    }
  });

and I cannot understand why, any help will be appreciated.

Under "Important Things To Remember" in the ESPAsyncWebServer README:

You can not use yield or delay or any function that uses them inside
the callbacks

Your code calls delay() in the callback, and calls functions that you cannot know do not call delay() or yield().
You need to rewrite your code to follow the instructions in the web server's documentation.


text:
how to make this code work with spiffs?
So, I have a page to select a txt file from the user's device and save it to SD card:
<!DOCTYPE html>

  <title>File Upload </title>

File Upload

<form method='POST' action='/upload' enctype='multipart/form-data'>
<input type='file' name='upload'>
<input type='submit' value='Upload'>
</form>

and here is my esp8266 code for handling the form :

  controlserver.on("/UPL", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/html", upl);
  });
 controlserver.on("/upload", HTTP_POST, [](AsyncWebServerRequest *request) {
        request->send(200); }, handleUpload);

void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  String logmessage = "Client:" + request->client()->remoteIP().toString() + " " + request->url();

  if (!index) {
    logmessage = "Upload Start: " + String(filename);
    request->_tempFile = SD.open("/" + filename, "w");
  }

  if (len) {
    request->_tempFile.write(data, len);
    logmessage = "Writing file: " + String(filename) + " index=" + String(index) + " len=" + String(len);
  }

  if (final) {
    logmessage = "Upload Complete: " + String(filename) + ",size: " + String(index + len);
    request->_tempFile.close();
    request->redirect("/");
  }
}

My project is not big and it doesn't require SD card, and esp8266 has 4mb memory, I have tried to replace SD with spiffs, but I wasn't successful. I don't know that if it's possible to directly write the txt file to spiffs, but it will be ok if I could save it to a string the write it to a file in spiffs.

reduce your code to writing "x" to spiffs and reading it back

Thanks to this post, I did solve the problem.
Here is the full code,
My html code for the upload page, the form is in the  tag:

<!DOCTYPE html>

  <title>File Upload Example</title>

File Upload Example

<form method="POST" action="/upload" enctype="multipart/form-data" target="iframe"><input type="file" name="upload"><input type="submit" value="Upload">
</form>

code for ESP:

void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){
if (!index) {
    request->_tempFile = SPIFFS.open("/" + filename, "w");
    Serial.println("1");
}
if (len) {
    request->_tempFile.write(data, len);
     Serial.println("2");
}
if (final) {
   Serial.println("3");
    request->_tempFile.close();
    request->redirect("/");
}
}

 controlserver.on("/upload", HTTP_POST, [](AsyncWebServerRequest *request) {
        request->send(200); }, handleUpload);

  controlserver.on("/UPL", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/html", upl);
  });

  readFile(SPIFFS, "/11.txt"); // show the content of the uploaded file, obviously you should know the name of the uploaded file!

you can write a function like this to make sure the file was delivered:
  readFile(fs::FS &fs, const char * path){
  Serial.printf("Reading file: %s\r\n", path);
  File file = fs.open(path, "r");
  if(!file || file.isDirectory()){
    Serial.println("- empty file or failed to open file");
    return String();
  }
  Serial.println("- read from file:");
  String fileContent;
  while(file.available()){
    fileContent+=String((char)file.read());
  }
  file.close();
  Serial.println(fileContent);

}


text:
Interrupt is sporatic, potentially after 220Hz or so
Background although likely not needed: I am recieving a frequency on the destination side of a opto isolater.  A fan trips a hall effect sensor, and grounds a circuit which lights the opto.  On the recieving end I have a fully isolated arduino circuit that accurately reads this 550Hz (peak) signal.  However, my Uno stopped reading this value correctly.  So I debounced the circuit which did not fix the issue.  I now brought in a new (and isolated) Uno that has nothing else going on but reading this signal and its Interrupt is also sporatic after several seconds.
I believe it is operating OK until the signal gets to about 420Hz (which is nothing..).  PulseIn also returns many "0" durations with the "900ns" good durations.  So it seems the high/low trigger is flipping too often, which was not fixed with debounce. I can see using the oscilloscope that the signal is good at 550Hz
21:34:12.750 -> Htz: 0
21:34:14.575 -> L: 44
21:34:14.575 -> Htz: 88
21:34:15.265 -> L: 70
21:34:15.265 -> Htz: 140
21:34:15.479 -> L: 89
21:34:15.479 -> Htz: 178
21:34:15.913 -> L: 109
21:34:15.913 -> Htz: 218
21:34:16.452 -> L: 117
21:34:16.577 -> Htz: 234
21:34:16.986 -> L: 134
21:34:16.986 -> Htz: 268
21:34:17.511 -> L: 186
21:34:17.511 -> Htz: 372
21:34:18.036 -> L: 213
21:34:18.036 -> Htz: 426
21:34:18.567 -> L: 702
21:34:18.567 -> Htz: 1404
21:34:19.195 -> L: 1913
21:34:19.196 -> Htz: 3826
21:34:19.838 -> L: 3508
21:34:19.838 -> Htz: 7016

code
unsigned long timestamp;
int lsensorpin = 2;
int PWMpin = 3;
String printout;
unsigned int reading;
unsigned long L;
unsigned int lRPM;
unsigned int Htz;

void setup() {
  pinMode(lsensorpin, INPUT);//_PULLUP); //2
  pinMode(PWMpin, OUTPUT);
  analogWrite(PWMpin, 100);
  Serial.begin(9600);
  Serial.println("FInish Setup");
}

void loop() {

  //printout=" High:";
  //reading= pulseIn(lsensorpin, HIGH);
  //printout=printout + reading + " Low:";
  //reading= pulseIn(lsensorpin, LOW);
  //printout= printout + reading;
  //Serial.println(printout + reading);

  L=0;
  attachl();
  delay(500);
  detachl();
  Htz=L*2;
  lRPM= L*60;
  Serial.print("L: ");
  Serial.println(L);
  //Serial.print("Htz: ");
  //Serial.println(Htz);

  //Serial.print("RPM: ");
  //Serial.println(lRPM);
}

void tickL() {
L=L+1;
}

void attachl(){
    attachInterrupt(digitalPinToInterrupt(lsensorpin), tickL, RISING);
}

void detachl(){
    detachInterrupt(digitalPinToInterrupt(lsensorpin));
}

Did you consider that delay() is influenced by the interrupts? Each interrupt service takes some run time, and the delay is prolonged by that run time. The function realizes the delay through a certain number of instruction cycles. You might want to use a timer to realize the measurement interval.

Why are you attaching and detaching the interrupt in your main loop? Try using a faster baud rate, eg. 115200 baud. (9600 is really slow).

From my post about interrupts:

I have seen example code suggesting you count things for a second by turning interrupts off for a second and then on again. I don't recommend this, because for one thing, you can't do serial prints if interrupts are off.
Example (not recommended):
volatile unsigned long events;
const unsigned long INTERVAL = 1000;  // 1 second

void eventISR ()
  {
  events++;
  }   // end of eventISR

void setup ()
  {
  Serial.begin(115200);
  attachInterrupt (digitalPinToInterrupt (2), eventISR, FALLING);
  }   // end of setup

void loop ()
  {
  events = 0;       // reset counter
  interrupts ();    // allow interrupts
  delay (INTERVAL); // wait desired time
  noInterrupts();   // stop interrupts

  Serial.print ("I counted ");
  Serial.println (events);
  }  // end of loop

That may work for simple situations, but turning interrupts off means that the Serial prints won't work until they are turned on again (which they may not be in a more complex sketch).
It is better to use the millis() result and just detect when the time limit is up.
Improved sketch:
volatile bool counting;
volatile unsigned long events;

unsigned long startTime;
const unsigned long INTERVAL = 1000;  // 1 second

void eventISR ()
  {
  if (counting)
    events++;
  }  // end of eventISR

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  attachInterrupt (digitalPinToInterrupt (2), eventISR, FALLING);
  }  // end of setup

void showResults ()
  {
  Serial.print ("I counted ");
  Serial.println (events);
  }  // end of showResults

void loop ()
  {
  if (counting)
    {
    // is time up?
    if (millis () - startTime < INTERVAL)
      return;
    counting = false;
    showResults ();
    }  // end of if

  noInterrupts ();
  events = 0;
  startTime = millis ();
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  counting = true;
  interrupts ();
  }  // end of loop

In loop() here we wait for the interval (1 second in this case) to be up, otherwise we return, effectively doing nothing. You could of course do other things instead of just returning.
If the time is up we display the count.
If counting is not currently active (and presuming we want it to be active) we remember the start time, reset the counter to zero, and let it start counting up.
That code seemed to work OK up to 100 kHz, although the counts were getting a bit inaccurate. You can do more precise timings by using the hardware counters / timers. Details here:
http://www.gammon.com.au/timers

Also you should declare the variable L to be volatile.

Interresting formatting, looks somehow like python style.. I can't see blocks properly either :D (subjective feeling)

@KIIV  Why? The entire block is indented. I find that is the easiest to read. I think it is called Whitesmiths style. "It was also popular in the early days of Windows, ..." - I've been around for a while, so I probably picked up that style years ago.

It's just that I'm not used to this style. I'm somehow used to search end bracket with smaller indentation than code. You know, almost 2 decades of using one or two similar styles


text:
How often should we poll the 74HC165 if we wish to detect 'button' presses?
I am going to either chain 4 shift registers, or connect 4 shift registers to an ESP32 that is connected to a computer with bluetooth.
I understand at 3.3 volts, the 74HC165 can run at a clock speed of up to 18mhz. (5mhz at 2v, 25mhz at 4v).
What is normal for monitoring events on the shift registers? Is it normal to endlessly poll the shift registers? Or is a short delay between each read possible and/or desirable?
I cant imagine a reason for wanting to check for "events" (button presses, etc...) 1 million times per second. We could I guess, I just don't know if we should.
(I am new to the ESP32, so I am not sure how maintaining a bluetooth connection impacts things)

your question can easily be answered by you running some test code and pressing buttons ... it's not a question about Arduino, so it is off topic here ... questions about optimum sampling intervals belong at https://electronics.stackexchange.com/questions

I was going to ask why this downvoted (I dont really understand why) but then I looked at the "Top questions" tab and see most questions are downvoted ♂

it was probably downvoted because the Arduino is irrelevant to your question ... you could be using a PIC chip or a PC or a Raspberry Pi or any of the many development boards and your question would not change

@jsotola Im not sure if thats true though? I didn't think I was asking an electronics question, because I am not sure how bluetooth and other activities on the ESP32 impact or don't impact reading from the chip. (For example, I don't know if reading from the buttons is interrupted by bluetooth events? Maybe it does? Maybe it doesnt? I just don't know what I dont know about programming these things yet.)

For this you can employ the nyquist-shannon theory for signal sampling.
In short it states that "to sample a signal frequency of X you need at least 2x X samples per second".
So if you know how long a button will be pressed for (or released for, whichever is faster, i.e., the "highest frequency component of interest") then you know you need to sample with an interval of at most half that time.
So for a button that you may press for 100ms you know you need to sample at most every 50ms, preferably faster.

Thank you! that gives me a logical way to think through the numbers. The only thing that is not clear, then, from an electronics perspective (battery consumption, EMF, etc... ) do people tend to sample as infrequently as possible, or will the ESP32/74HC165 use basically the same power either way?
(Apologies if these are basic questions, I am primarily a coder, enjoying exploring building basic electronic devices)

@Jay most people don't over think it unless they're doing something battery operated with sleep modes. As long as you do it fast enough just do whatever makes sense for your program. It makes no difference from a power consumption perspective unless you're sleeping.

Yes, it's pretty normal to endlessly poll the buttons. Even the original NES controller did it exactly that way, its protocol works exactly like you'd talk to a shift register. Majenko alredy gave an answer on a good polling frequency, here's the additional hardware you'd need to work with interrupts instead of polling:
You'd need to add a bunch of OR gates (or AND gates if your buttons pull down instead of up) in "parallel" to your shift registers, so that you've got one signal with the semantics "(at least) one of the buttons have been pressed".
This signal then can be connected to the SH/LD input of your shift registers, triggering the shift registers to load (i.e. sample and hold) the inputs. In addition, it needs to be connected to one GPIO of your Arduino/ESP, to which you connect an interrupt handler on the software side. That interrupt handler then polls the shift register once (or sets a flag that causes your main loop to poll it). You may need an additional gate and GPIO to allow the polling routine to keep SH/LD HIGH while polling, depending on your use case and how bouncy your buttons are.
You could even use that signal to wake the ESP from deep sleep, poll the buttons once, do whatever needs to be done as a reaction to that button, then go back to deep sleep.
In conclusion: Endless polling is mostly the way to go, because of the hardware overhead to implement an interrupt solution.


text:
Is it possible to use assembly with arduino?
I want to learn assembly, but would like to learn by doing, is it possible to learn and make something useful with arduino hardware? I dont know where or how to start something like this.

yes it is very possible ... you can write same kind of code as the C++ compiler generates

Which Arduino? The assembly language/instruction set is dependent on the microcontroller family.
At least some of the C++ compilers used in Arduino toolchains allow you to include inline assembly code.

What do you want to reach in the end? Assembly is hardware-dependent, so if you know learn how to program an Arduino uno using assembly, that will help you only to a very small degree if you later want to program Intel CPUs in assembly.

I suggest the ARV libC project as a starting point to HOW to get assmbler code running. And the AVR Instruction Set Manual to get hold of the actual assembler mnemonics.
Maybe also my own AVR Assembly Project might be a helpful starting point with its code available on GitHub.


text:
External Interrupt not working on 3.3V atmega168
I made a 3.3V board and I've put both atmega328p (that I pulled off of a 3.3V pro mini), and an atmega168 that I bootloaded (using USBtinyISP whilst selecting board "Arduino Pro or Pro Mini" and "atmega168 (3.3V, 8MHz") .
Everything works perfectly with the atmega328 - code works and interrupts do as well - which function to pull the Arduino out of sleep when INT0 rises.
However on the Atmega168, the interrupt doesn't seem to work. All the normal code works as expected (communications, instructions etc), just not the interrupt. After the Arduino goes to sleep, I can't wake it since the interrupt isn't working.
Basic code below:
#include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes

byte interruptPin = 2; //Turn board on/off
unsigned long shutDownTimer = 0; // Timer for shutdown

void setup() {
  Serial.begin(57600);
  pinMode(interruptPin, INPUT); //Set pin d2 to input using the buildin pullup resistor
  Serial.println("Starting");

}

void loop() {
  Serial.println("Awake");
  delay(1000);

  // Shutdown control
  if (digitalRead(interruptPin) == LOW ) {
    Serial.println("Shutdown detected");
    shutDownTimer = millis();
    while (digitalRead(interruptPin) == LOW ) {
      if (millis() - shutDownTimer > 1000) {
        Serial.println("sleep mode triggered");
        Going_To_Sleep();
      }
    }
  }
}

void Going_To_Sleep() {
  sleep_enable();//Enabling sleep mode
  delay(1000);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);//Setting the sleep mode, in our case full sleep
  delay(1000); //wait a second to allow the led to be turned off before going to sleep
  attachInterrupt(0, wakeUp, RISING);//attaching a interrupt to pin d2

  Serial.println("Interrrupt attached");//Print message to serial monitor
  sleep_cpu();//activating sleep mode
  Serial.println("just woke up!");//next line of code executed after the interrupt

}

void wakeUp() {
  sleep_disable();//Disable sleep mode
  detachInterrupt(0); //Removes the interrupt from pin 2;
  Serial.println("Interrrupt Fired - wakeup");//Print message to serial monitor

}

Instead of using "attachInterrupt(0, wakeUp, RISING);" Ive also tried the following which also don't work:
attachInterrupt(INT0, wakeUp, RISING);
attachInterrupt(digitalPinToInterrupt(interruptPin), wakeUp, RISING);
attachInterrupt(32, wakeUp, RISING);  //since its the pin of the chip? Hail Mary
attachInterrupt(2, wakeUp, RISING);  //obviously this won't work, Hail Mary 2

I have no idea why the interrupts aren't working. I have an inkling it might be due to something fuse related within the boot loader, but I don't really understand things at that level (Though I'm happy to dive in with some guidance). Any guidance will be appreciated!

Your Serial.println inside the ISR is putting you in danger of locking up there. Test using an LED or something instead.

According to the datasheet for the Atmega168:

Note that recognition of falling or rising
edge interrupts on INT0 or INT1 requires the presence of an I/O clock, described in
Section 6.1 “Clock Systems and their Distribution” on page 23. Low level interrupt on INT0 and INT1 is detected
asynchronously. This implies that this interrupt can be used for waking the part also from sleep modes other than idle mode.
The I/O clock is halted in all sleep modes except idle mode

In other words, only the LOW interrupt wakes it from sleep.
Having said that, the Atmega328P does wake from sleep with a rising or falling interrupt, as I have previously had confirmed by Atmel, however I can't say for sure that this enhancement (over what is stated in the datasheet) applies to the 168.
You could try doing a bit of testing to confirm that. Maybe rejig so that the interrupt occurs when the signal goes low rather than high, and then use a LOW interrupt and not a RISING one.
Also, don't do serial prints inside an ISR. The modern versions of the library handles that better than in the past, but this may still be an issue. As suggested in a comment, try flashing an LED rather than printing something. Or don't print anything, after all you print something when it wakes up. Why print something extra inside the ISR? That is just asking for trouble.

I didn't see the information in the Atmega328P data sheet stating that it works with rising, and that the Atmega168 does not work with rising. However it is indeed functioning consistently with what you say. I'll just have to use Atmega328's for this application. Thanks.

Depending on what signal you are using to wake the Arduino, you may also find pin change interrupts an alternative to the edge triggered interrupts you are currently using.
These are usually more predictable in behaviour and less subject to nuanced interpretations of the data sheets.
See https://playground.arduino.cc/Main/PinChangeInterrupt/ for examples of how to use these.


text:
Can't pair two HC-05 (Master - Slave)
I want to connect two HC-05 modules, one master and one slave. So to that I need to access 'AT Commands'.
Theoretically, I just needed to upload an empty code, and then connect the module to the arduino in command mode (I use a Nano) TX and RX pins and then go to the Serial Monitor at 38400 baudrate and sent the AT commands. In the past this worked for me, but now this ain't working anymore.
So I went for some code online and aparently AT commands started working. I configured master and slave, and binded the address of the slave to the master.
I connected the modules to an input voltage and I was expecting a connection between them but they are not pairing. On youtube videos they say to connect with two different arduinos, but doesnt make any sense to me because they should connect by themselves just for being ON.
I don't know what to do, I need these working for a project and I'm just wasting time searching on the internet, because nothing works for me. I just didnt tried using them with 2 arduinos with code on them, but I dont think thats the issue AND IF IT IS, please tell me what's the correlation.

Are you sure about that the modules should connect automatically on startup? Honestly I wouldn't think that to be the case. Also: What exactly are you trying to do if you don't use 2 Arduinos with your two HC-05 modules?

@chrisl I saw man videos on youtube and after they configure the modules they just put them both in data mode and they pair by themselves, I dont really know why they put them alingside 2 arduinos. I'm using an arduino and an STM32, but as I said, they should connect by themselves

Are you sure you've binded master to slave? Try writing AT+BIND? for master and AT+ADDR? for slave, they should match.


text:
How to get variable from callback function?
There is a library  davetcc / IoAbstraction. The only library working as expected with my rotary encoder. The problem that on rotation I can only see serial output with position data, but I cannot get these data as some variable value.
There is the swithch initialization and function definition in main.cpp
switches.addSwitch(spinwheelClickPin, onSpinwheelClicked);
void onSpinwheelClicked(uint8_t pin, bool heldDown) {
  Serial.print("Button pressed ");
  Serial.println(heldDown ? "Held" : "Pressed");
}

The definition from SwitchInput.cpp
bool SwitchInput::addSwitch(pinid_t pin, KeyCallbackFn callback,uint8_t repeat, bool invertLogic) {
    if(internalAddSwitch(pin, invertLogic)) {
        KeyboardItem item(pin, callback, repeat, invertLogic);
        return keys.add(item);
    }

    return false;
}

There is the callback function type definition from SwitchInput.h
typedef void(*KeyCallbackFn)(pinid_t key, bool heldDown);

I canon just change void to bool. So how can I get this heldDown variable value?
Sorry if the question is stupid.

Callback functions are usually void and don't return real data, because they are called by some type of event handling system, like the mentioned library. As this is calling the callback function, not you, it does not make much sense to return data from it. To get that return value, you would need to change the library for every bit of data, that you want. Thus return values of callback functions are either void or some message to the event handling system (for example to make the event system send down the event to the next possible handler).
But you can use global variables to get the data from the callback. Define a global variable for the value, that you want to extract, and inside the callback function set that variable. Then at other places in your code you can use that global variable.
The library, that you linked, seems to handle the event in the main code and not in interrupts. So you are safe to just use the global variables as you like.
Though to be complete: When interrupts are involved and you change global variables inside an interrupt service routine, you need to be very careful. Single byte variables are not problem, but with multi-byte variables you can get scrambled data, as the interrupt might occur in the middle of processing that variable. Then you need to introduce a critical section, where interrupts are disabled for a very short time.


text:
Why HDOP in TinyGPS++ is less than 1?
HDOP is supposed to be greater than 1: https://en.wikipedia.org/wiki/Dilution_of_precision_(navigation)
But I get HDOP about 0.7. What does it mean?

Where can I found explanation of the output parameters?

HDOP can be less than 1 - See this article

Make the answer and I will mark it as the best

HDOP can be less than 1 according to this article.. I am no expert in this area, but according to the article, the HDOP=1 limit is based on 4 satellites; visibility and use of more than 4 satellites can reduce HDOP below this limit. When you think on it, this makes sense.
GPS specifications limit the inherent accuracy of a position solution through timing errors and vagaries in rf propagation through our atmosphere. Imagine drawing a vector from a GPS satellite to your receiver. The length of that vector represents the distance from the satellite to your receiver, but we depend on signal timing to infer distance/vector magnitude. In other words, we can only measure distance as accurately as we can measure time.
Now think about the accuracy of a position solution based on a single satellite. If we assume the receiver is confined to the surface of the earth (and the satellite is geostationary), the single vector of length L1 will intersect the surface of the earth forming a circle. Your position could be anywhere on that circle - which could be quite a large range of values!
Now imagine a 2nd satellite, a 2nd vector of length L2 tracing a second circle. Now your position is constrained to be those points where the two circles intersect - two points! With a third satellite, a 3rd vector of length L3, one of these two points will be eliminated.
Now replace those sharp lines with bands or swaths of some width D. In this case, the intersection describes a polygon instead of a point. We know our position is within the polygon, but with only three satellites that is the best we can do.
As you can see, adding more satellites will begin to "slice off" sections of the original polygon, making it progressively smaller. So: HDOP=1 represents the limit with 4 satellites; more satellites yield a smaller polygon, and smaller HDOP.

While writing this, I found a video that does a far better job than my words at describing the position solution process with multiple satellites.
This video is quite good also!


text:
Is there any way to connect my old phone camera with an arduino?
I have an esp8266 wifi module, arduino uno and an old mobile. I was wondering if there is any way by which i could remove the camera from the mobile and connect it with my arduino in order to view video captured by the camera.
Is this possible by the hardware which i currently have? Or i will have to buy more hardware?
Please let me know if more information is required also give the link of helpful articles.

No. Just... no.

By the use of any additional hardware.

The phone and a WiFi/bluetooth connection and some software to perform the camera sharing?

It's not a question of hardware. It's a question of documentation. You will NOT be able to find anything anywhere about what the camera is or how it works. Without that there is ZERO chance of you doing anything.

is there any cheap way to perform the above task?

Buy an ESP32-CAM

Ok then please guide me if i buy an ESP32-CAM then will i be able to show the content captured to the browser using some web application?

Yes. There is an example in the ESP32 core. It even does facial recognition.

An Uno is undersized and underpowered (speed) for this job. Without even considering how to transfer the image, an Uno has nowhere for it to go. The most modest cell phone cameras' images were probably 3 Megapixels, and even assuming 2 bytes of storage per pixel (allowing 5 bits for each of 3 colors), you'd need 6 MB  or 6000 KB to store the image. An Uno's RAM is 2K bytes before you subtract whatever RAM its program needs besides room to store the image. Based on those assumptions, an Uno would need another memory, 3000 times the size of its RAM, to hold the image.
Update:

Is there any possibility that the image is not stored in the arduino
  rather sent to the server in stream (i.e in small packets)?

I can't imagine why not - at least in theory - but I have no idea what kind of communication hardware might be built into the camera, or if you'd need to develop something on your own. But somehow you'll need to get the image data to the Arduino and in some kind of format you understand and can work with, at least once it gets to the web application. At this point, the critical piece of knowledge would be to know the specs of how the camera delivers image data - how fast, in what format, must the Arduino and the camera interact or does the data just pour out in a flood once started, ... ?
Your first steps will probably need to be to learn how some typical cameras handle this, and to figure out what specific camera you have and how that camera works. Then you'll have a much better idea about what it will take to complete your project.

Is there any possibility that the image is not stored in the arduino rather sent to the server in stream (i.e in small packets)?(because i am trying to develope a realtime web application)

Is there any way to connect my old phone camera with an arduino?

Yes, but it may be a huge amount of work requiring expensive equipment and skills that take decades to acquire.
See Mike's Electric - Interfacing a cheap phone camera module to a PIC32 microcontroller. which is a great video and will give you an idea of what is involved. Note that he's using a 32-bit microcontroller with relatively large RAM on the chip. You might need to use a 32-bit Arduino (Due etc) not one of the 8-bit Arduinos (Uno etc).
Mike is the kind of person who could reverse-engineer a random camera module from an old phone but this isn't a project for a typical Arduino user like you or I.
Since these camera modules cost about $1, it is probably best to look for a camera breakout for Arduino that comes with documentation and software libraries.


text:
Fading LED with different frequencies
I have a potentiometer attached to one analog port of arduino (assume A0)
I'm reading the value of that using input_voltage = analogRead (A0); which is a value between 0-1023.
So I want to map this value to frequency from 1Hz to 20Hz. Then I want to fade my LED using this frequency.
Tried to doing this map using int frequency = map (input_voltage, 0, 1023, 1, 20);
But how can i apply this frequency to LED?
I mean PWM has a constant frequency (about 500Hz). How should I apply frequencies from 1 to 20 to this LED in order to fade it?

Do you want to blink or flicker instead of dimming the led ? Or does 1Hz mean you want to fade for 1 sec between ON and OFF (20 Hz = 50 ms between On and Off will be no visible difference to immediate switching)

What is your goal? Do you want to change the rate at which you flash an LED? PWM (Pulse width modulation) doesn't to vary the  frequency of the output - it varies the duty cycle (ratio of on-time to off-time) of a fixed frequency output. If you want to dim the output of your LED based on the input pot, it seems to me you should map 0-1023 to 0-255 , an use the 0-255 output to control a PWM output pin. If you want to control the flashing rate of the LED, you need to use something other than PWM.

@DuncanC Thanks for your help. What is that "something other than PWM" ? For example timers?

There is a library in which you can change the frequency
Here is my example code I did long time ago I had the same problem
Get the library from here
Go ahead and try example code there and try to understand too.
Include the library first to code
my code
void setup() {
  pinMode(13, OUTPUT);
  pinMode(8, OUTPUT);
  digitalWrite(8,LOW);
  Serial.begin(115200);
  InitTimersSafe();
}
void loop() {
  //mapping
  long x = map(analogRead(A0),0,1023,1,20);
  bool b = SetPinFrequencySafe(9,x);
  digitalWrite(13,b);
  pwmWrite(9,127);
  Serial.print(x);
  Serial.print(" Hz ");
  Serial.println(b);
  delay(100);
}

Built in led will turn on if the frequency is stetted.
By the way led will turn on in 50% on and 50% off in one cycle in pin 9.
Use only the PWM pins in Arduino 3,9,6 etc.
Now you can change the PWM frequency...
I just put a led in the female socket in for easiness + terminal in 9 and - terminal in 8 to go to ground that's why I did put pin 8 to low.

Thank you for this complete and helpful answer!

Wouldn't it be easier to modulate the duty cycle of the PWM for fading a LED? By adapting the frequency between 1Hz and 20Hz, you'll just get changing flashing rates, unless you integrate the PWM output with a (rather large) capacitor.

@imalipusram I understand but the question asked me to do this using frequency...


text:
LCD stays blank when it is on and all wiring seems correct

So I have to do this project for school and it involves using a lcd display on tinkercad. I followed the wiring on this tutorial here: https://www.arduino.cc/en/Tutorial/HelloWorld. When I turn it on, the display is just blank even though I've tried to print.
Here is the code I have for this
#include <Servo.h>
#include <LiquidCrystal.h>

//TESTING
//ULTRASONIC WORKS
//SERVO WORKS
//BUZZER WORKS
//POTENTIOMETER WORKS

//Variables:

Servo pump;

LiquidCrystal lcd (12, 11, 5, 4, 3, 2);

bool blnPump = true;

long lngTimer = 0;
long lngDistance = 0;

int intPumpTime = 0;
int intLightLevel = 0;
int intCount = 0;

//soundDistance:to use the ultrasonic distance sensor and find the distance of an object above

//input
    //intSignalPin: to indicate which pin to use for the sensor
//output
    //lngDistance: the distance between the sensor and the object in cm

long soundDistance (int intSignalPin)
{
  long lngTime = 0;
  long lngDistance = 0;
  //gather the time is takes for the sound to travel back

  pinMode (intSignalPin, OUTPUT);
  digitalWrite (intSignalPin, LOW);
  delay (2);
  digitalWrite (intSignalPin, HIGH);
  delay (10);
  digitalWrite (intSignalPin, LOW);
  pinMode (intSignalPin, INPUT);
  lngTime = pulseIn (intSignalPin, HIGH);

  //Serial.println (lngTime);
  //calculating the distance

  lngDistance = lngTime * 0.01723;

  return lngDistance;
}

void setup()
{
  pinMode (A0,INPUT);
  pinMode (A1, INPUT);
  pinMode (9, OUTPUT);
  pinMode(13, INPUT);
  Serial.begin (9600);

  pump.attach (10);

  lcd.begin(16, 2);
  lcd.print ("hello");
}

void loop()
{
  //turning lcd off
  digitalWrite (8, LOW);

  lcd.print ("hello");
  //determining how many times the servo will pump
  intPumpTime = analogRead (A0);

  if (intPumpTime >= 0 && intPumpTime <= 341)
  {
    intPumpTime = 1;
  }

  else if (intPumpTime >= 342 && intPumpTime <= 683)
  {
    intPumpTime = 2;
  }

  else //if (intPumpTime >= 684 && intPumpTime <= 1023)
  {
    intPumpTime = 3;
  }

  //Pumping if theres a hand in range of 5cm to 25cm and pumping different amounts of sanitizer based on potentiometer, playing a tone if it does and turning the lcd on or off based on light level

  if (soundDistance (13) >= 5 && soundDistance (13) <= 25 && blnPump == true)
  {
    //turning lcd on or off
    intLightLevel = analogRead (A1);
    if (intLightLevel <= 300)
    {
      lcd.noDisplay();
    }

    else
    {
      lcd.display();
    }

    //playing tone to indicate its pumping
    tone (8, 500);
    delay (100);
    noTone (8);

    //lighting up led to indicate its pumping
    digitalWrite (9, HIGH);

    //pumping
    for (intCount = 0; intCount < intPumpTime; intCount++)
    {
        pump.write (90);
        delay (1000);
        pump.write (0);
        delay (1000);
    }

    //shutting off the led and turning the servo off
    digitalWrite (9, LOW);
    blnPump = false;

    lngTimer = millis();

    //waiting here to display hand scrubing time, no more sanitizer will be dispensed in this 20 seconds
    while (millis() - lngTimer < 20000)
    {

      if (millis() - lngTimer <= 1000)// && intLightLevel > 300)
      {
        lcd.clear();
        lcd.print ("19 seconds left");
      }

      else if (millis() - lngTimer > 4000 && millis() - lngTimer <= 5000)// && intLightLevel > 300)
      {
        //blnPump = true;
      }
    }

    //decide if to use LCD or not here
  }

  else
  {
    pump.write (0);
  }

  //Serial.println (soundDistance (13));
  //long lngTest = soundDistance (13);
}

Sorry for all the extra code, they're for the other parts. I think I have followed what needs to be followed with inputting the pin into the LiquidCrystal class, the begin method but it just doesn't print.

For clarification, I inputted the pins into the liquid crystal class near the top under variables. Begin() and print() is in setup

You're probably taking too much power out of the 5V pin and nothing is getting proper power.  The 5V pin isn't there to power your whole project.  Try using a separate power supply for all the stuff involved there and see if that doesn't help.

You certainly shouldn't be trying to power a motor or servo off the 5V pin.  That's a good way to end up needing a new Arduino.

Never thought about that since I've always just used the 5v pin and everything before worked. I'm going to try that out tomorrow

I hope unused GND pin on LCD is just a mistake in schematic.

Oh I was messing with the wiring on it, might've accidentally took it off but I don't think it worked with it connected anyways

Twiddle with contrast potentiometer. Uninitialized LCD usually has first row blacked - wrong contrast results into either nothing is visible or all pixels are black or something inbetween. But there is also possibility it's already burned by missing GND connection. Those LCDs are pretty sensitive to miswiring power lines.

Most (all?) pins can deliver (source) 20 mA recommendable ( 40 mA max, but better to stay under 20 mA), and there are also maximums for groups of pins. the 5V pin can handle more (not sure out of my head) but it's in the order of 100's of mA, probably too much for the servo, LCD and especially both together.


text:
Arduino Due SPI clock pauses each octet
I'm trying to communicate with SPI slave using Arduino DUE as master. Device requires commands to be 32 bit wide, SPI mode 3.
I've ran the minimum code (using Arduino IDE 1.8.12) to send some 32 bit wide nonsense, and I've noticed that clock stops for a while after each octet is sent. Also the pause after CS goes LOW is too long.
What is the best practice to achieve a clean 32 bit wide transmission?
#include <SPI.h>

const int cs_pin = 25;
const SPISettings spi_settings(2000000, MSBFIRST, SPI_MODE3);
uint8_t tx_buffer[4];

void setup() {
  pinMode(cs_pin, OUTPUT);
  SPI.begin();
}

void loop() {
  tx_buffer[0] = 0xDE;
  tx_buffer[1] = 0xAD;
  tx_buffer[2] = 0xBE;
  tx_buffer[3] = 0xEF;

  SPI.beginTransaction(spi_settings);
  digitalWrite(cs_pin, LOW);
  SPI.transfer(tx_buffer, 4);
  digitalWrite(cs_pin, HIGH);
  SPI.endTransaction();
}

SCLK - CH1 (Yellow)
CS - CH3 (Purple)
MOSI - CH4 (Blue)

Expected signal:

Noticed timing states it's actually 40, not 32 bits, but that doesn't seem to affect the question.

The SPI data register is only 8 bits wide.  So you have to have some time once one byte is out to load the next byte in.  There’s not really anything you can do about it aside from using different hardware.

@Delta_G yep, thought so too. But it actually happens even if I set slower SPI clock. Looks like this is intentional. I guess I should have a look at what's going on in the library.

SPI is synchronous. That means that within certain constraints the timing and the width of any part of the signal is irrelevant.
What makes you think that it's bad to have a slight variance in the timing, or that the "pause after CS goes LOW!" is "too low"?
If you think it's from the timing diagrams, those times are minimum times (generally) and all things happen at either the rising or falling edge of the clock (depending on the SPI mode).

Well if you look at bottom diagram, you can see that after 8 raising edges of clock signal the 9th doesn't happen right away as it would in continuous stream. It pauses for one cycle before transmitting next byte. I understand it will work, just will take a bit longer. Just wonder why and if I can avoid it.

It is completely normal. Why would you want to avoid it?

In SPI there's no requirement to wait so many cycles after pulling CS low before starting transmission. It waits about 6 Tcl extra time.

@IceGlow The Arduino way of working with SPI is that it is blocking. You get a byte. You put it in the SPI data register. You wait for it to send. You retrieve the received byte. You store it somewhere. You get the next byte. You put it in the SPI data register... etc. If you want to make it more "fluid" for some reason then you will have to do it outside the Arduino API and directly interface with the SPI registers. And even use DMA for ultimate background operation.

well I'm playing around with directly controlling currents on the actuator from SPI commands. I'd like to have a predictable and minimum delays between commands, as that increases the accuracy. Does that make sense? But the question is - could I control those delays, before first byte is sent, between bytes, after last byte, if I want to.

And sorry, I didn't mean to say that something is broken. Default library behaviour is not violating any requirements for SPI. There are just some margins, I presume, to increase the stability of some devices. I wonder may I avoid them.

@IceGlow Yes, but not with Arduino API code.


text:
Can't Send Text Messages Using TinyGSM Module, but it works if I do it manually using the ESP-IDF Environment - Sim7600
I am using the following device: https://www.aliexpress.com/item/1005003152097545.html?spm=a2g0o.order_list.order_list_main.119.222218028PapM6
I am trying to make an IoT sound-measurer which will send an SMS, once a sound above a certain threshold has been registered for a certain amount of time. Furthermore, it should send a "pulse" SMS every Nth hour, to ensure, that the module is still alive.
To achieve the SMS-part of this project I am using the TinyGSM module. It worked for a long time, and then suddenly it wouldn't work anymore. The only related event I can think of that happened before this, is that I tried to use the modem on the ESP-IDF, and I tried to use the GPS capabilities of the modem, once again on the ESP-IDF.
I believe this might have had something to do with the settings I had sat on the ESP-IDF, which are defined through the following AT-commands:
"AT+CFUN=0\r", "AT+CPIN="1234"\r", "AT+COPS=0,0,"Telenor DK Telenor DK",7\r", "AT+CMGF=0\r".
But after running "AT+CRESET" and "AT+CPOF" and rerunning the Arduino script, I am still stuck with the original error.
The error occurs, when I try to run the sendText method, and the message (With my phone number redacted) is:
AT+CMGF=1
AT+CMGF=1

ERROR
AT+CSCS="GSM"
AT+CSCS="GSM"

ERROR
AT+CMGS="+REDACTED"
AT+CMGS="+REDACTED"

ERROR

The full Arduino code (Where I've once again written REDACTED instead of my actual IRL phone number):
//SIMKORT indstillinger

// Pincode for simkortet
#define GSM_PIN "\"1234\""

// GRPRS credentials for simkortet
const char apn[]  = "Telenor Internet";     //SET TO YOUR APN
const char gprsUser[] = "";
const char gprsPass[] = "";

// Nummer til SMS samt besked
#define SMS_TARGET_NOISY  "+REDACTED"
#define SMS_TARGET_PULSE "+REDACTED"
#define SMS_MESSAGE_NOISY "B"
#define SMS_MESSAGE_PULSE "L"

//Netværks indstillinger fra Debugging 1 koden
#define NETWORK_MODE 2
#define PREFFERED_NETWORK_MODE 2

//Modem indstillinger
#define TINY_GSM_MODEM_SIM7600 //Om du bruger SIM7000 eller SIM7600 (TTGO'en er 7600)
#define TINY_GSM_RX_BUFFER 1024 // Set RX buffer to 1Kb
#define SerialAT Serial1

//Libraries
#define DUMP_AT_COMMANDS  //Bruges til debugging

#include <TinyGsmClient.h>
#include <SPI.h>
#include <SD.h>
#include <Ticker.h>

#ifdef DUMP_AT_COMMANDS  // if enabled it requires the streamDebugger lib
  #include <StreamDebugger.h>
  StreamDebugger debugger(SerialAT, Serial);
  TinyGsm modem(debugger);
#else
  TinyGsm modem(SerialAT);
#endif

//ESP32-Modem Forbindelser Indstillinger
#define uS_TO_S_FACTOR 1000000ULL  // Conversion factor for micro seconds to seconds

#define UART_BAUD   115200
#define PIN_DTR     25
#define PIN_TX      27
#define PIN_RX      26
#define PWR_PIN     4

//SD Kort forbindelser
#define SD_MISO     2
#define SD_MOSI     15
#define SD_SCLK     14
#define SD_CS       13
#define LED_PIN     12

int counter, lastIndex, numberOfPieces = 24;
String pieces[24], input;

//Indstillinger for dBAMåleren
#define VREF 3.3 //Voltagen som din MCU bruger, Arduino = 5
#define soundSensorPin 25 //Den pin på MCU'en, der er forbundet til outputtet på dBA måleren
#define analogMaxRange 4096 //Analog max range for din MCU, esp32: 4096, Arduino: 1023

//Funktionelle indstillinger
#define dBAMax 3.0 //Hvornår der skal sendes en SMS
#define errorMeasurement 0.0 //Fejlmarginen
#define waitBeforeSendingtext (10*1000) //Målt i millisekunder, tid før vi sender noisySMS
#define waitBeforeGoingIdle (100*1000) //Hvor lang tid dBAMeasurement må være under vores dBAMax, før vi går tilbage til idle stadiet
#define waitIntervalBetweenPulseText (1000*1000) //Antal millisekunder i mellem, at vi sender en pulse SMS

//Variable vedrørende FSMD'en - MÅ IKKE ÆNDRES
//States:
//Idle 0, dBA above Max 1, dBA momentarily below max 2, send noisy text 3, send pulse text 4
int state = 0; //Initialiserer stadiet ved 0
float dbAMeasurement;
unsigned long timeSinceLastIdle; //Bruges til at triggere loudSMS
unsigned long timeSinceLastPulse = 0; //Bruges til at pulseSMS
unsigned long timeSincedBAMax; //Tid der er gået siden, vi optog vores første dBAMax i denne omgang

//Funktioner

void sendText(String SMSTarget,String message,TinyGsm modem){
    modem.sendSMS(SMSTarget, message);
}

float getdBAMeasurement(){
  float dbAMeasurement = ((analogRead(soundSensorPin) / 4096.0 * VREF)*50.0); //Slipper for at bruge clock cycluser på at definere variable
  delay(125); //Sampling cyclus delay for stabilitet
  return dbAMeasurement;
}

bool isAbovedBAThreshold(){
  float dbAMeasurement = getdBAMeasurement();
  if(dbAMeasurement>(dBAMax - errorMeasurement)){
    return true;
  }else{
    return false;
  }
}

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

  //Opstart af Modem
  // Set LED OFF
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);

  pinMode(PWR_PIN, OUTPUT);
  digitalWrite(PWR_PIN, HIGH);
  delay(300);
  digitalWrite(PWR_PIN, LOW);

  //Tjekker for SD kort
  SPI.begin(SD_SCLK, SD_MISO, SD_MOSI, SD_CS);
  if (!SD.begin(SD_CS)) {
    Serial.println("SDCard MOUNT FAIL");
  } else {
    uint32_t cardSize = SD.cardSize() / (1024 * 1024);
    String str = "SDCard Size: " + String(cardSize) + "MB";
    Serial.println(str);
  }

  Serial.println("\nWait...");

  delay(1000);

  SerialAT.begin(UART_BAUD, SERIAL_8N1, PIN_RX, PIN_TX);

  // Restart takes quite some time
  // To skip it, call init() instead of restart()
  Serial.println("Initializing modem...");
  if (!modem.restart()) {
    Serial.println("Failed to restart modem, attempting to continue without restarting");
  }

  // Unlock your SIM card with a PIN if needed
  if ( GSM_PIN && modem.getSimStatus() != 3 ) {
      modem.simUnlock(GSM_PIN);
  }
  modem.sendAT("+CFUN=0 ");
  if (modem.waitResponse(10000L) != 1) {
    DBG(" +CFUN=0  false ");
  }
  delay(200);

  /*
    2 Automatic
    13 GSM only
    38 LTE only
    51 GSM and LTE only
  * * * */
  String res;
  // CHANGE NETWORK MODE, IF NEEDED
  res = modem.setNetworkMode(NETWORK_MODE);
  if (res != "1") {
    DBG("setNetworkMode  false ");
    return ;
  }
  delay(200);

  /*
    1 CAT-M
    2 NB-Iot
    3 CAT-M and NB-IoT
  * * */
  // CHANGE PREFERRED MODE, IF NEEDED
  res = modem.setNetworkMode(PREFFERED_NETWORK_MODE);
  if (res != "1") {
    DBG("setPreferredMode  false ");
    return ;
  }
  delay(200);

  /*AT+CBANDCFG=<mode>,<band>[,<band>…]
   * <mode> "CAT-M"   "NB-IOT"
   * <band>  The value of <band> must is in the band list of getting from  AT+CBANDCFG=?
   * For example, my SIM card carrier "NB-iot" supports B8.  I will configure +CBANDCFG= "Nb-iot ",8
   */
  /* modem.sendAT("+CBANDCFG=\"NB-IOT\",8 ");*/

  /* if (modem.waitResponse(10000L) != 1) {
       DBG(" +CBANDCFG=\"NB-IOT\" ");
   }*/
   delay(200);

  modem.sendAT("+CFUN=1 ");
  if (modem.waitResponse(10000L) != 1) {
    DBG(" +CFUN=1  false ");
  }
  delay(200);

  SerialAT.println("AT+CGDCONT?");
  delay(500);
  if (SerialAT.available()) {
    input = SerialAT.readString();
    for (int i = 0; i < input.length(); i++) {
      if (input.substring(i, i + 1) == "\n") {
        pieces[counter] = input.substring(lastIndex, i);
        lastIndex = i + 1;
        counter++;
       }
        if (i == input.length() - 1) {
          pieces[counter] = input.substring(lastIndex, i);
        }
      }
      // Reset for reuse
      input = "";
      counter = 0;
      lastIndex = 0;

      for ( int y = 0; y < numberOfPieces; y++) {
        for ( int x = 0; x < pieces[y].length(); x++) {
          char c = pieces[y][x];  //gets one byte from buffer
          if (c == ',') {
            if (input.indexOf(": ") >= 0) {
              String data = input.substring((input.indexOf(": ") + 1));
              if ( data.toInt() > 0 && data.toInt() < 25) {
                modem.sendAT("+CGDCONT=" + String(data.toInt()) + ",\"IP\",\"" + String(apn) + "\",\"0.0.0.0\",0,0,0,0");
              }
              input = "";
              break;
            }
          // Reset for reuse
          input = "";
         } else {
          input += c;
         }
      }
    }
  } else {
    Serial.println("Failed to get PDP!");
  }

  Serial.println("\n\n\nWaiting for network...");
  if (!modem.waitForNetwork()) {
    delay(10000);
    return;
  }

  if (modem.isNetworkConnected()) {
    Serial.println("Network connected");
  }

}

void loop() {

  switch(state){
    case 0:  // Idle: Venter på at dbAMeasurement går over dbAMax - Error
      Serial.println("Back in state 0");
      dbAMeasurement = getdBAMeasurement();
      timeSinceLastIdle = millis(); //Millisekunder siden start
      Serial.println(dbAMeasurement);
      Serial.println(timeSinceLastIdle);
      Serial.println(timeSinceLastPulse);

      if((timeSinceLastIdle - timeSinceLastPulse) > waitIntervalBetweenPulseText){ //Vi vil hellere sende pulse SMS'en, før vi advarer
        state = 4;
      }
      if ((dbAMeasurement>(dBAMax - errorMeasurement))&(state != 4)){ //If we go above the allowed dBAMeasurement, we start counting until we send noisySMS
        state = 1;
      }

      break;
    case 1:  // We're counting up to sending the loudSMS
      Serial.println("Back in state 1");

      dbAMeasurement = getdBAMeasurement();
      Serial.println(dbAMeasurement);

      timeSincedBAMax = millis() - timeSinceLastIdle;
      Serial.println(timeSincedBAMax);
      if(timeSincedBAMax>waitBeforeSendingtext){
        state = 3; //SendnoisySMS
      }
      if(dbAMeasurement<(dBAMax - errorMeasurement)){
        state = 2; //Momentært under dBAMax
      }

      break;
    case 2:  // Hvis vi momentært går under dBAMax
      Serial.println("Back in state 2");
      dbAMeasurement = getdBAMeasurement();

      if((millis() - timeSincedBAMax)> waitBeforeGoingIdle){ //Når der er gået lang nok tid, hvor vi ikke måler en høj nok lyd, så genstarter vi timeren for at sende noisySMS
        state = 0;
      }

      if(dbAMeasurement>(dBAMax - errorMeasurement)){ //Vi går igen over vores threshold og går tilbage til tælle op til at sende noisySMS uden at genstarte timeren
        state = 1;
      }

      break;
    case 3:  // Send noisySMS
      sendText(SMS_TARGET_NOISY,SMS_MESSAGE_NOISY,modem);
      Serial.println("Back in state 3");
      state = 0;
      break;

    case 4:
      Serial.println("Back in state 4");
      timeSinceLastPulse = millis();
      sendText(SMS_TARGET_PULSE,SMS_MESSAGE_PULSE,modem);
      state = 0; //Go back to idle
      break;
  }
}

The odd thing here however, is that if I manually send the AT commands over UART using the ESP-IDF, I can make it send text messages without a hick.

TinyGSM has the capability of turning on DUMP_AT_COMMANDS for debugging , have you done that?

modem.setNetworkMode() return a bool true or false, not a char or string as you are checking in if (res != "1").

@hcheung I do not believe that is the issue. I believe it is boxed into a boolean.

Well, you can believe whatever you want, did you read the source code?  You had #define DUMP_AT_COMMANDS turn on, what does the log on the Serial Monitor shown?


text:
code not getting uploaded to Arduino
when I try to upload any code to Arduino it isn't getting uploaded the "RX LED" keeps blinking about 10 times but the "TX LED" doesn't light up. I have done a loopback test but it failed the cable is working there is no problem with my cable "Pin 13 LED" and "ON LED" are working, also my Arduino is not getting recognized in the device manager, my Arduino was working before. My Arduino model is: "UNO R3".
the error I get when I upload the code:
An error occurred while uploading the sketch
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding

i dont have another Arduino to burn bootloder


text:
Why won't IP mode change to 1 in ESP01 using the AT commands?
I was trying to send some data to a webpage using an Arduino Uno R3 connected to an ESP01. I simply uploaded the BareMinimum and started sending AT commands through the Serial Monitor. It worked fine for the first time, but now its IPMODE is stuck to 0 (Single IP mode). Everytime I try to set it back to 1 (Multiple IP mode), it throws an error "IPMODE must be 0". I tried resetting the ESP01 but that didn't work.

you mean AT+CIPMODE? set AT+CIPMUX=0 first

I'm doing that, for AT+CIPMUX=0, I get "OK" as response, which means that the IP mode is set to 0. But whenever I send AT+CIPMUX=1, it returns "ERROR IP mode must be 0". I don't understand why it MUST be 0, when I have already used this feature once.

CIPMODE 0 is normal mode and CIPMODE 1 is "passthrough mode".  CIPMUX is : 0 single connection, 1: multiple connections. And multiple connections can only be set when transparent transmission is disabled (AT+CIPMODE=0).


text:
ESP32CAM fails to initialise camera with error 0xffffff
There is a simple PlatformIO sketch (arduino format) that has the following main.cpp file:
#include <Arduino.h>
#include "esp_camera.h"
#include "camera_pins.h"

#define CAMERA_MODEL_AI_THINKER

#define LED_BUILTIN 33 // Define LED_BUILTIN for ESP32

void setup()
{
    pinMode(LED_BUILTIN, OUTPUT);
    Serial.begin(115200);
    delay(500);

    Serial.println("Camera initialising...");

    camera_config_t config;

    // Declaring pins in the config
    {

        config.ledc_channel = LEDC_CHANNEL_0;
        config.ledc_timer = LEDC_TIMER_0;

        config.pin_d0 = Y2_GPIO_NUM;
        config.pin_d1 = Y3_GPIO_NUM;
        config.pin_d2 = Y4_GPIO_NUM;
        config.pin_d3 = Y5_GPIO_NUM;
        config.pin_d4 = Y6_GPIO_NUM;
        config.pin_d5 = Y7_GPIO_NUM;
        config.pin_d6 = Y8_GPIO_NUM;
        config.pin_d7 = Y9_GPIO_NUM;
        config.pin_xclk = XCLK_GPIO_NUM;
        config.pin_pclk = PCLK_GPIO_NUM;
        config.pin_vsync = VSYNC_GPIO_NUM;
        config.pin_href = HREF_GPIO_NUM;
        config.pin_sccb_sda = SIOD_GPIO_NUM; // Replaced `sscb` with `sccb`
        config.pin_sccb_scl = SIOC_GPIO_NUM; // Replaced `sscb` with `sccb`
        config.pin_pwdn = PWDN_GPIO_NUM;
        config.pin_reset = RESET_GPIO_NUM;
        config.xclk_freq_hz = 20000000; // Can be set to 10000000 for slower refresh rate but could lead to stable (slower) execution
        config.pixel_format = PIXFORMAT_JPEG;
    }

    // Initialize the camera
    if (psramFound())
    {
        Serial.println("PSRAM FOUND! Setting framesize to QVGA");
        config.frame_size = FRAMESIZE_QVGA; // 320x240 resolution
        config.jpeg_quality = 10;
        config.fb_count = 2;
    }
    else
    {
        Serial.println("PSRAM NOT FOUND! Setting framsize to CIF");
        config.frame_size = FRAMESIZE_CIF;
        config.jpeg_quality = 20; // not 12 (0-63; lower means high quality)
        config.fb_count = 1;
    }

    esp_err_t err = esp_camera_init(&config);

    /* PSRAM NOT FOUND! Setting framsize to CIF
    E (650) cam_hal: cam_dma_config(301): frame buffer malloc failed
    E (650) cam_hal: cam_config(385): cam_dma_config failed
    E (651) camera: Camera config failed with error 0xffffffff
    Camera init failed with error 0xffffffff */

    if (err != ESP_OK)
    {
        Serial.printf("Camera init failed with error 0x%x\n", err);
        return;
    }

    Serial.println("Camera initialized successfully!");
}

void loop()
{

    if (Serial.available())
    {
        String rcvdTxt = Serial.readString();

        Serial.print("I heard: ");
        Serial.println(rcvdTxt);

        digitalWrite(LED_BUILTIN, HIGH);
        // Serial.println("PING");
        delay(1000);
        digitalWrite(LED_BUILTIN, LOW);
        // Serial.println("PONG");
    }
}

Now the camera pins are set as per this article (pretty detailed article, I recommend checking out).
But the problem arises when I upload the code and start it up. The esp_camera_init(&config) chunk of code throws the following error:
E (650) cam_hal: cam_dma_config(301): frame buffer malloc failed
E (650) cam_hal: cam_config(385): cam_dma_config failed
E (651) camera: Camera config failed with error 0xffffffff
Camera init failed with error 0xffffffff

Also, the psramFound() returns false, meaning the PSRAM is not detected.

The error message:
E (650) cam_hal: cam_dma_config(301): frame buffer malloc failed
E (650) cam_hal: cam_config(385): cam_dma_config failed
E (651) camera: Camera config failed with error 0xffffffff
Camera init failed with error 0xffffffff

This means that the "esp_camera.h" library is not able to allocate enough memory in the ESP32CAM to process the images.
Elaborated:
The ESP32CAM, when its camera module captures an image, it stores that data in a buffer that is preallocated by the program. Think of it like defining a chunk of memory and keeping it reserved only for the image data that comes in (look up 'ESP32CAM DMA').
The PSRAM (Pseudo Static RAM) can be understood like the RAM of ESP32CAM in which the memory is gonna be allocated for the incoming image data. Now this 0xffffff and frame buffer malloc failed means that there is not enough room to allocate the said buffer.
Problem: The ESP32CAM has a PSRAM (usually) that its not able to access to allocate the buffer (there is usually enough space to store the incoming image data but ESP32CAM is not able to access it).
Cause: Some famous bug in the codebase that causes the PSRAM to "not be recognised" by the ESP32CAM, hence the psramFound() returning false.
Solution: A -D PREFER_PSRAM -mfix-esp32-psram-cache-issue in the build flags of the sketch.
Now I do not know how to do this in Arduino IDE but in PlatformIO, in the platformio.ini file, add the following:
build_flags = -D PREFER_PSRAM -mfix-esp32-psram-cache-issue

Are you using the FTDI USB to serial converter?


text:
Problem With interfacing of 16 Servo MG996R with Arduino Uno
I am using 16 MG996R servo motor with PCA9685 servo driver with Arduino Uno, but the motors are not working properly. What is the best power supply/battery for my project as it worked well earlier but is not working right now.

which part of your question is about the Arduino?

I am interfacing PCA using Arduino Uno

You need a power supply that is rated for the same voltage as your servos, and can provide at least the total amount of current for all the servos combined.

Same case here.... Have you solved the problem yet?
Thanks so much!


text:
Assigning an empty array row to reference
int colors[][3] = {
  { 255, 0, 0 },
  { 0, 255, 0 },
  { 0, 0, 255 },
  { 253, 7, 210 }
};
int (*EXCLUSIVE_COLOR)[3];

I have a two-dimensional array to store some color values.
I have a 2nd array, which I am using to assign an "EXCLUSIVE_COLOR" from the first colors array.
What is the best method to assign a null or empty value to the "EXCLUSIVE_COLOR" array to be used upon initialization and when the "EXCLUSIVE_COLOR" is unset?
Initially I tried just assigning a default value to the array upon initialization:
int (*EXCLUSIVE_COLOR)[3] = {0,0,0};
//Produces an error: scalar object ‘EXCLUSIVE_COLOR’ requires one element in initializer

int (*EXCLUSIVE_COLOR)[3] = {0};
//assigns non-zero values to all three elements

I know that I can add a "dummy" record to the colors array to reference, when there isn't an "EXCLUSIVE_COLOR" set.
int colors[][3] = {
  { 255, 0, 0 },
  { 0, 255, 0 },
  { 0, 0, 255 },
  { 253, 7, 210 },

  { 0, 0, 0, }   //dummy record
};
int (*EXCLUSIVE_COLOR)[3] = &colors[4];

However I wanted to know if there was a cleaner way to be able to assign an empty value to reference when a color is not set, and when the array is initialized.

use the pointer as I recommended in you previous question

I am currently using a pointer to a 3 int array, as suggested in the previous question. However that only specifies how to assign an array element by reference from the colors array, which is why I'm currently using the "dummy record" approach to set a default value. I was wondering if there was a better way to assign a default value to the pointer,  other than having it point to a dummy array element in the colors array.

int* EXCLUSIVE_COLOR = {0,0,0}; read my comment or the edit at the end of Edgar's answer

If you're using a pointer then there's no limit to what that pointer can point to.
The way I see it you have two sensible choices:

Point to a default value

This doesn't have to be in your array. It can be anything that is an int[3], since that is what your array consists of.
int[3] nothing = {0, 0, 0};

EXCLUSIVE_COLOR = nothing;

This means that it's actually pointing to something valid, in this case it's actually (I assume) the colour black.  That can make it easy to deal with, since EXCLUSIVE_COLOR[0] will be a valid value.

Point to nothing

You can point your pointer to NULL and it will be pointing to "nothing". This means that EXCLUSIVE_COLOR[0] is no longer valid, which can make handling it somewhat harder. However it does allow you to distinguish between "nothing" and "black", unlike option 1.
For example:
EXCLUSIVE_COLOR = colors[2]; // {0, 0, 255}
...
EXCLUSIVE_COLOR = NULL; // Not pointing anywhere

To test if it's pointing somewhere you can simply use if:
if (EXCLUSIVE_COLOR) {
   // you have a valid entry
}


text:
Assigning an element of a multidimensional array to a second array
I have two arrays. The first array is a multidimensional array holding color values.
The 2nd array stores an active color from the 1st array.
How can I assign an element from the multidimensional colors array to the 2nd EXCLUSIVE_COLOR array?
int colors[][3] = {
  { 255, 0, 0 },
  { 0, 255, 0 },
  { 0, 0, 255 },
  { 253, 7, 210 }
};
int EXCLUSIVE_COLOR[3] = {0};

I tried the following but neither seemed to work:
    EXCLUSIVE_COLOR = {
      colors[0][0],
      colors[0][1],
      colors[0][2]
    };
    // error: assigning to an array from an initializer list

    EXCLUSIVE_COLOR = colors[0];
    // error: invalid array assignment

what is the type of EXCLUSIVE_COLOR. you want a pointer to the array or a copy of the array?

Either one would work. EXCLUSIVE_COLOR is a 3 element int array.

int* EXCLUSIVE_COLOR = colors[0];. and then you can use EXCLUSIVE_COLOR[i]

Why do you use a two-dimensional array, if you have a one-dimensional array of Color elements in reality?

You can copy the array:
EXCLUSIVE_COLOR[0] = colors[0][0];
EXCLUSIVE_COLOR[1] = colors[0][1];
EXCLUSIVE_COLOR[2] = colors[0][2];

but this doesn't work in an initialization.
Alternatively, you can declare EXCLUSIVE_COLOR as a pointer to an
array of 3 integers:
int (*EXCLUSIVE_COLOR)[3]; // pointer to array 3 of int

Then you can have this point to a row of the 2D array, either by
assigning the pointer or in the initialization:
int (*EXCLUSIVE_COLOR)[3] = &colors[0];  // initialization

// Later in the program:
EXCLUSIVE_COLOR = &colors[1];

Note that when using this pointer, you will have to explicitly
dereference it:
for (int i = 0; i < 3; i++)
    Serial.println((*EXCLUSIVE_COLOR)[i]);

Edit: As pointed out by Juraj in a comment, you can instead make
EXCLUSIVE_COLOR a pointer to int. In this case you will make it point
to the first element in the row you want:
int* EXCLUSIVE_COLOR = &colors[0][0];

One nice thing of this approach is that you can use the “decay to
pointer” feature of the language to simplify the syntax:
int* EXCLUSIVE_COLOR = colors[0];

// Later
Serial.println(EXCLUSIVE_COLOR[i]);

a pointer to pointer? it doesn't look right

@Juraj: It's not a pointer to pointer, it's a pointer to an array.

Use arrays only where appropriate:
struct Color {byte r, g, b;};
const Color colors[] = {
  {0,255,0},
  {255,0,0}
};
const Color red = colors[1];

This works without const as well. But you should consider using const wherever possible.


text:
How many LED displays can be hooked to one Arduino board?
I am new to Arduino development. I need to connect multiple led displays(between 20 and 100), such as this one to an Arduino board. The led displays will be pretty far out from each other.
How can this be achieved? How can i uniquely identify the LCD displays? At this point i need some 101 orientation.

The product, that you linked, is an OLED display, not an LCD display

okay, thanks, so how many?

Without any additional electronics: Exactly one. On each I2C interface every address needs to be unique. Since you cannot change the address of the display, 1 is the limit. Majenkos answer gives you a hint how to deal with that.

@chrisl on the SSD1306 you can select a second address, but I'm not sure the PCB in the product listed, breaks out the D/C# pin. Even then, you can only connect two. You could bitbang I2C on other pins. But you'd need two pins for each display, and you would run out of pins pretty quick. Also the library you use for the displays might only support the hardware I2C pins.

The led displays will be pretty far out from each other.

Those are I2C connected displays. I2C is not designed (though there are technologies to allow it) to operate over long distances. It's designed primarily for communication between chips within a circuit board.

How can i uniquely identify the LCD displays?

Since you can't change the I2C address of the displays you would either need a separate I2C bus for each one or employ some form of I2C multiplexer.
All of this is getting too complicated. The more accepted way of doing this would be to have a small microcontroller directly connected to each display (one display per microcontroller) and then make the microcontrollers communicate with each other (or with a single master) over some suitable communication medium (some wireless system, or a serial bus like RS485 or CAN, for example).
You're then just rubber-stamping the units as many times as you want, and connecting them all together.


text:
4 RFID with Arduino Uno / add or remove card with master card /
i am new in coding for arduino. I need some help with the project i'm working on. my project is a object tracking by using the rfid rc522 for inventory system. so i need to have multi reader in this project. i would like to have 4 reder that will work at the same time.
this is how i want my project to work:
1. there is going to be 3 or 4 reader rc522, 1 i2s lec and leds.
2. one rfid tag will be use as the master card. the master card have the ability to add or remove card.
3. when 1 tag is tapped on 1 reader, the card quantity at the reader that it tapped will increase. example when we tap the tag at reader1, reader1 will add 1 card into its memory.
https://github.com/TasmanianDevilYouTube/Arduino/blob/master/RFID_master_slave_cards/RFID_master_slave_cards.ino

And what exactly is your problem with that? You didn't ask a question

what do you need help with ... right now, your post is like I'm new to house building and I need some help with a project.  I'm building a house with 3 bedrooms and a basement suite.

i want to have this coding to work with 4 rfid reader connected to arduino uno.

my bad. so do u know how to interface 4 rfid rc522 reader with arduino uno with the code in the link?

Still it is not clear, what your problem is. You need to narrow down the problem more. You already have a big code, which uses the MFRC522 library to interface with the RFID reader. Is that working? If not: How exactly is it not working? What did you expect and what actually happens? Are the examples working, that normally come with such a library? Or is the problem, that you don't know how to extent the code?

my problem is i dont know how to modified this code so it will work on 4 rfid reader with exactly the same as the code is now. the code here is working fine with only 1 reader. i wanted to extend it to 4 reader. so how should i do the modification on the code?

are you able to interface 4 rfid readers with Arduino UNO? .... start with simple code that reads a card on any of the four readers .... if it is not possible to use 4 rfid readers with the UNO, then it is pointless to waste time trying to modify your code

yess im able to interface 4 rfid with arduino uno.

that why I m now trying to do it


text:
Attiny85 microcontroller programming without arduino
I have decided to make a simple project so thinked about arduino but that seems very worthy so i decided to use attiny85 ic for my project,but i don't have arduino or avr to program it. Is there any way to program the below ic without arduino or avr?.

How about buying the Digispark USB Development board, which uses an Attiny85 and can be programmed via USB?

I use a “USBasp” ISP programmer. Those are cheap, compatible with avrdude, and more convenient than an Arduino running the ArduinoISP firmware. Beware there are some Chinese “USBISP” programmers (note the spelling) that are not compatible with avrdude.

Is there any way to program [a bare AVR microcontroller] without Arduino [hardware] or AVR [hardware programmer]?

Programming a bare AVR microcontoller like the ATtiny85 IC needs either another Arduino board or an AVR programmer device.

Programmer $4-$7
Something like the Pololu AVR Programmer v2.1 can be bought for $7 and used with the free Arduino development software (IDE). I have used this to program an ATtiny85. This is what I would suggest, because a programmer is the most versatile solution.
 Even cheaper, a $4 USBASP

Arduino as ISP $4.50
I have used an old Arduino Duemilanove using the Arduino as ISP sketch as a programmer for an ATtiny85 but any Arduino with inbuilt USB and enough GPIO could be used. There are some low cost ATmega328P or ATmega32u4 based Arduino clones that would be suitable. A Nano v3 clone costs $4.50.

Development Board with USB $3
As others have commented, you can buy a "digispark" (just Google and click "shopping") for three or four dollars. This is essentially a breakout board with an ATtiny85, a USB connector and a soft-USB-capable bootloader pre-loaded onto the ATtiny85. You can program it with the Arduino IDE after using the IDE's board-manager to install Digistump's "core" definitions for the Digispark. It doesn't need another Arduino nor an AVR Programmer. I bought three on Amazon for $9 a month ago.

Since it is an Arduino-compatible development board, it doesn't really meet your requirement of "without Arduino" - but it might be the closest solution to what you have in mind.

Useful resources and inspiration:

ATtiny-Based Beginner's Kit
Twelve PWM outputs from an ATtiny85.

Yes, 12 LEDs individually controlled with just four resistors and four pins of an eight-pin ATtiny85 and and no other components!
I have no affiliation with the above site, I just think it is one anyone new to electronics with an ATtiny85  would find interesting.

Is there a way to not use Arduino IDE for development, but just a text editor and compile from command line?

@rustyx: that's a great question - I see the original question can also be interpreted that way. I'll add another answer for that interpretation.

Is there any way to program [a bare AVR microcontroller] without Arduino [IDE software] or AVR [software development toolkit]?

I believe you can use

A text editor of your choice to create and edit source code files.
The GNU compiler GCC-AVR to compile source code into machine-code.
The avrdude program to install the compiled code onto the microcontroller.

All these can be obtained at zero cost.

Thanks! I've also found this and also this with links on how to debug and emulate AVR.


text:
current reading is not a sine like a voltage wave

I am working on a power meter project with ZMPT101B and SCT013. I want to see the phase difference between voltage and current in the serial plotter but the results are like this? Why do you think the current reading is not a sine like a voltage wave?]
2]2

because there is only a little load

When you look closely, the current is oscillating too. The signal is just too small to see it here. You should try to scale it up and/or make a measurement with more resolution

Current is only a sine wave with a purely resistive load. With other loads current changes all the time depending on what the load(s) is(/are) doing.

@Majenko and isn't it true that there is no such thing as a purely resistive load? There's always going to be some inductive and capacitive component, albeit a small one.

@DuncanC Often too small to measure though, at least with crude sensors like the SCT013, which itself will be an inductive load, thus changing your measurements by doing the measuring. But yes, it's impossible to get 100% pure resistive.

And doesn't the presence of capacitance and inductance in the circuit mean that the current graph is often visibly distorted from a pure sine wave?


text:
How to interpret Serial data received by Bluetooth module
I'm experimenting with a hc-05 knockoff the JDY-30 and am confused about the Serial data I'm getting from it. I downloaded an app called BlueUino to send commands from my Android to my Arduino Uno via Bluetooth. I then print the data I get via Serial port using the code below:
  if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = '1'; //Serial.read(); // Reads the data from the serial port0
    stateData = Serial.read();
    sprintf(data, "Data is %u", stateData);
    Serial.println(data);
    Serial.println();
 }

Here are some of the results I get in the log which I can't make sense of. For example, sending the string "def" doesn't contain the sequence of data from sending the command "e". Also, how does one convert these values to characters ?
Send Command "b"
Data is 128
Data is 0
Data is 248

Send Command "abc":
Data is 120 // doesn't contain the sequence of Data of "b"
Data is 120
Data is 120
Data is 0
Data is 120
Data is 0
Data is 248

Sounds like you have a baud rate mismatch.

you are correct from looking at datasheet. thank you!

seems to work now. But still wondering how to convert data to characters. Example: 'b' is received as '98'. Where do i look up the corresponding char for the data?

nvm ascii table

98 and b are the same thing. Just different ways of representing the data.

replace %u with %c

Or just storing the inbound data in a char type and use single quotes when parsing incoming bytes so that the compiler knows your dealing with ASCII, print them out on serial and they should be familiar characters, of course with the baud rate mismatch fixed

This might be sending the data in bytes so convert it and then try. You can convert it by doing String(data).


text:
Arduino Wont Run Program at 4 Mhz
I want my Arduino Nano to consume as little power as possible, so I have been lowering the clock frequency with CLKPR from the default 16 MhZ speed. I successfully ran the program at 8 Mhz by setting CLKPR=0x01, but am unable to see any output in the serial monitor or any sign of the program running successfully at 4 Mhz (CLKPR=0x02). My project involves transmitting data between Arduino and an Android via Bluetooth, and I can see the receive LED blink on the Nano at 4 Mhz. However, for some reason it does not step through the code, and Serial monitor wont print statements. My Nano is a cheap knockoff so it's possible the chip is not designed to run at 4 Mhz. I've also tried the same test on a knockoff Uno and got the same results. Please let me know if you have any suggestions. I've included the code I'm trying to run:
int state = 0;
int stateData = 0;
int ultraPin = 10;
int trigPin = 11;    // Trigger
int echoPin = 12;    // Echo
long duration, cm;
unsigned char inches;
unsigned long timer;

void setup() {
  CLKPR = 0x80;
  CLKPR = 0x02; // 4 Mhz
  pinMode(ultraPin, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  digitalWrite(ultraPin, LOW);
  Serial.begin(9600*4); // multiply baud rate by inverse of clock frequency factor
}

void loop() {
  if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    stateData = Serial.read();
    if (stateData == 48){ // ON signal from phone
      Serial.write(50); // confirm signal received
      timer = millis();
      digitalWrite(ultraPin, HIGH);
      while (true){
          digitalWrite(trigPin, LOW);
          delayMicroseconds(2/4);
          digitalWrite(trigPin, HIGH);
          delayMicroseconds(10/4);
          digitalWrite(trigPin, LOW);
          pinMode(echoPin, INPUT);
          duration = pulseIn(echoPin, HIGH);
          cm = (duration / 2) / 29.1;   // Divide by 29.1 or multiply by 0.0343
          inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
          Serial.write(inches);
          delay(50/4);
          stateData = Serial.read();
          if (stateData != 49){
            // receipt from android
            unsigned long timeElapse = millis() - timer;
            if (timeElapse > 5000/4) {
              break;
            }
          }
          else {
              // reset the timer
              timer = millis();
            }
      }
    }
 }
 delay(200/4);
}

delayMicroseconds(2/4); is just as calling delayMicroseconds(0); Not sure if this is a valid argument for this function.

How are you programming the Nano? How do you set the correct fuses for 4MHz? Are you using an external crystal or the internal oscillator?

I am using the internal oscillator. I don't know where the fuses are and didn't think I needed to touch hardware

A Nano is normally clocked at 16 MHz off a ceramic resonator. If you want to use the internal oscillator (which runs at roughly 8 MHz), you have to use an ISP programmer to change the fuses. CLKPR allows you to change the prescaler at run time, but not the clock source.

Not sure if changing the prescaler modifies power consumption.

@EdgarBonet But I could change prescaler to 8 Mhz at run time. Or was it still clocked at 16 Mhz?

As I said before: at run time you can change the prescaler (e.g. to divide the frequency by 4), but not the clock source (you cannot switch from the 16 MHz ceramic resonator to 8 MHz internal RC oscillator).

ok, so i guess what you are saying is changing the prescaler doesnt do anything without changing the clock source.

I think what I am looking for is sleep mode with some interrupt when serial message is received. Thanks for the help, my problem is resolved: https://www.megunolink.com/articles/wake-on-serial-message/#:~:text=Almost%20every%20digital%20pin%20on,interrupt%20to%20wake%20the%20device.


text:
Why Can't I Program my Atmega168 Pro Mini?
I'm trying to program a Atmega168 Pro Mini 3.3V/8mhz I bought online. I followed a tutorial that walks through the steps of how to program a Pro Mini with an Arduino Uno. However, in their example they are uploading code to a Atmega328 Pro Mini though I don't think it matters.
Anyway, I followed the same steps as they did (namely hooking up Uno's ground -> ground, 3v -> Vcc, Reset -> DTR, tx->tx, rx->rx). When I attempted to upload via Arduino IDE I got the message that the programmer was not responding. I also noticed that the transfer led on the Uno was not lighting up. Did I screw up something? Also, are my hookups correct? I would think tx pin should connect to rx pin, but I just followed the instructions. Would appreciate any thoughts

Did you remove the MCU from the Uno?

yup, I took off the 328 chip

Hookup is not correct, the RX, TX lines need to be crossed!

@UmarSear That's wrong. In this instance the Uno is only being used as a USB to UART adaptor, so TX->TX and RX->RX is correct. You would swap them only if you wanted the ATMega328P on the Uno to communicate with the ATMega168 on the Pro Mini.

Your hookup seems to be correct. However check if there is a capacitor on the pro-mini board between DTR and reset pin, some arduino clones don't come with one.
If there isn't any you can simply connect a capacitor like this:
Reset pin (Arduino Uno) -> Capacitor (0.01uF for example) -> DTR (pro mini). The reason for this hookup is exmplined well here

They're also interfacing the 5V UNO to the 3.3V Pro Mini with no consideration for the logic level difference.  Sometimes you get away with that.  Anyway, rather the start another answer, I figured I'd just tack this onto yours, for integration into it or not.