text:
I am trying to rewrite an RFID with a MEGA2560 and a RFID-RC522
I have been trying to rewrite an RFID tag so it is the same as my other one. I have code that will read both separately but I cannot find any already written for the MEGA2560 that will work for me. The code that works to read the RFID's is:
void setup()
{
  Serial.begin(9600);
  /* Enable the SPI interface */
  SPI.begin();
  /* Initialise the RFID reader */
  RC522.init();
}

void loop()
{
  /* Has a card been detected? */
  if (RC522.isCard())
  {
    /* If so then get its serial number */
    RC522.readCardSerial();
    Serial.println("Card detected:");
    for(int i=0;i<5;i++)
    {
    Serial.print(RC522.serNum[i],DEC);
    //Serial.print(RC522.serNum[i],HEX); //to print card detail in Hexa Decimal format
    }
    Serial.println();
    Serial.println();
  }
  delay(1000);
}

So I have been trying to mess around with code that was designed to clone the RFID that wasnt working for me before but I keep getting errors, mainly with double void looping etc. I have tried to fix the obvious issues. I am now getting an expected unqualified-id before 'if' but at this point I think I may just be making something that doesnt work. I would greatly appreciate it if someone could have a look at this and tell me where I am going wrong!
    /*
 * Copy the RFID card data into variables and then
 * scan the second empty card to copy all the data
 * ----------------------------------------------------------------------------
 * Example sketch/program which will try the most used default keys listed in
 * https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys to dump the
 * block 0 of a MIFARE RFID card using a RFID-RC522 reader.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

byte buffer[18];
byte block;
byte waarde[64][16];
MFRC522::StatusCode status;

MFRC522::MIFARE_Key key;

// Number of known default keys (hard-coded)
// NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
#define NR_KNOWN_KEYS   8
// Known keys, see: https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] =  {
    {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
    {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
    {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
    {0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
    {0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
    {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
    {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}  // 00 00 00 00 00 00
};

char choice;
#include <SPI.h>
/* Include the RFID library */
#include <RFID.h>

/* Define the DIO used for the SDA (SS) and RST (reset) pins. */
#define SDA_DIO 9
#define RESET_DIO 8
/* Create an instance of the RFID library */
RFID RC522(SDA_DIO, RESET_DIO);

void setup()
{
  Serial.begin(9600);
  /* Enable the SPI interface */
  SPI.begin();
  /* Initialise the RFID reader */
  RC522.init();
}

  /* Has a card been detected? */
if (RC522.isCard())
  {
    /* If so then get its serial number */
    RC522.readCardSerial();
    Serial.println("Card detected:");
    for(int i=0;i<5;i++)
    {
    Serial.print(RC522.serNum[i],DEC);
    //Serial.print(RC522.serNum[i],HEX); //to print card detail in Hexa Decimal format
    }
    Serial.println();
    Serial.println();
  }
  delay(1000);
}

 //Via seriele monitor de bytes uitlezen in hexadecimaal

void dump_byte_array(byte *buffer, byte bufferSize) {
    for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
    }
}
//Via seriele monitor de bytes uitlezen in ASCI

void dump_byte_array1(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.write(buffer[i]);
  }
}

/*
 * Try using the PICC (the tag/card) with the given key to access block 0 to 63.
 * On success, it will show the key details, and dump the block data on Serial.
 *
 * @return true when the given key worked, false otherwise.
 */

bool try_key(MFRC522::MIFARE_Key *key)
{
    bool result = false;

    for(byte block = 0; block < 64; block++){

    // Serial.println(F("Authenticating using key A..."));
    status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return false;
    }

    // Read block
    byte byteCount = sizeof(buffer);
    status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
    if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Read() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
    }
    else {
        // Successful read
        result = true;
        Serial.print(F("Success with key:"));
        dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
        Serial.println();

        // Dump block data
        Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
        dump_byte_array1(buffer, 16); //omzetten van hex naar ASCI
        Serial.println();

        for (int p = 0; p < 16; p++) //De 16 bits uit de block uitlezen
        {
          waarde [block][p] = buffer[p];
          Serial.print(waarde[block][p]);
          Serial.print(" ");
        }

        }
    }
    Serial.println();

    Serial.println("1.Read card \n2.Write to card \n3.Copy the data.");

    mfrc522.PICC_HaltA();       // Halt PICC
    mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD
    return result;

    start();
}

/*
 * Main loop.
 */
void loop() {
  start();

}

void start(){
  choice = Serial.read();

  if(choice == '1')
  {
    Serial.println("Read the card");
    keuze1();

    }
    else if(choice == '2')
    {
      Serial.println("See what is in the variables");
      keuze2();
    }
    else if(choice == '3')
    {
      Serial.println("Copying the data on to the new card");
      keuze3();
    }
}

void keuze2(){ //Test waardes in blokken

  for(block = 4; block <= 62; block++){
    if(block == 7 || block == 11 || block == 15 || block == 19 || block == 23 || block == 27 || block == 31 || block == 35 || block == 39 || block == 43 || block == 47 || block == 51 || block == 55 || block == 59){
      block ++;
    }

  Serial.print(F("Writing data into block "));
  Serial.print(block);
  Serial.println("\n");

    for(int j = 0; j < 16; j++){
      Serial.print(waarde[block][j]);
      Serial.print(" ");
    }
    Serial.println("\n");

  }

  Serial.println("1.Read card \n2.Write to card \n3.Copy the data.");
  start();
}

void keuze3(){ //Copy the data in the new card
Serial.println("Insert new card...");
  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent())
        return;

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial())
        return;

    // Show some details of the PICC (that is: the tag/card)
    Serial.print(F("Card UID:"));
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
    Serial.println();
    Serial.print(F("PICC type: "));
    MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
    Serial.println(mfrc522.PICC_GetTypeName(piccType));

    // Try the known default keys
    /*MFRC522::MIFARE_Key key;
    for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
        // Copy the known key into the MIFARE_Key structure
        for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
            key.keyByte[i] = knownKeys[k][i];
        }
    }*/
    for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
    }

  for(int i = 4; i <= 62; i++){ //De blocken 4 tot 62 kopieren, behalve al deze onderstaande blocken (omdat deze de authenticatie blokken zijn)
    if(i == 7 || i == 11 || i == 15 || i == 19 || i == 23 || i == 27 || i == 31 || i == 35 || i == 39 || i == 43 || i == 47 || i == 51 || i == 55 || i == 59){
      i++;
    }
    block = i;

      // Authenticate using key A
    Serial.println(F("Authenticating using key A..."));
    status = (MFRC522::StatusCode) mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
    }

    // Authenticate using key B
    Serial.println(F("Authenticating again using key B..."));
    status = (MFRC522::StatusCode) mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_B, block, &key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
    }

    // Write data to the block
    Serial.print(F("Writing data into block "));
    Serial.print(block);
    Serial.println("\n");

    dump_byte_array(waarde[block], 16);

     status = (MFRC522::StatusCode) mfrc522.MIFARE_Write(block, waarde[block], 16);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Write() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
      }

     Serial.println("\n");

  }
  mfrc522.PICC_HaltA();       // Halt PICC
  mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD

  Serial.println("1.Read card \n2.Write to card \n3.Copy the data.");
  start();
}

void keuze1(){ //Read card
  Serial.println("Insert card...");
  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent())
        return;

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial())
        return;

    // Show some details of the PICC (that is: the tag/card)
    Serial.print(F("Card UID:"));
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
    Serial.println();
    Serial.print(F("PICC type: "));
    MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
    Serial.println(mfrc522.PICC_GetTypeName(piccType));

    // Try the known default keys
    MFRC522::MIFARE_Key key;
    for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
        // Copy the known key into the MIFARE_Key structure
        for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
            key.keyByte[i] = knownKeys[k][i];
        }
        // Try the key
        if (try_key(&key)) {
            // Found and reported on the key and block,
            // no need to try other keys for this PICC
            break;
        }
    }
}

Where did you get the second code? It has code outside of any function, so it cannot compile


text:
Relative position using Accelerometer
I have a simple scenario please:
Two Arduino Nano 33 IoT devices started moving randomly from the same exact origin(Point = [X0, Y0, Z0]);
Can I use the coordinates queried from each device Accelerometer to get the Euclidean Distance between them?
In other words, Is the relative coordinate/position retrieved from the Accelerometer reliable?
Because I read that getting the relative position every time requires double integrations which leads to big accumulated error over time. Though I might be totally wrong.
Your help is very much appreciated.

What you heard (about double integration and accumulating errors) is correct. Mathematically, you can do this, by integrating each device's acceleration to get its current speed, and integrating the speed to get it's current position, then taking the vector difference in the their positions to get the distance between them.
If you had highly accurate accelerometers in a very noise-free environment (both mechanical and electrical noise), you could do it for a (short) while before the inevitable tiny errors (which are also being integrated!) begin to dominate the data and make the results useless. But as a practical matter - especially for us experimenters using inexpensive equipment and subject to a lot of mechanical and electrical noises on the experimental platform, plus environmental electrical noise - this will happen even more quickly.

Thanks for this level of details Robert.

source: Stack Exchange

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

sort: votes


text:
Bluetooth multithreading
I'm using my Arduino to make a speaker-like device. Instead of sound, it receives the beat of the song, thus the data comes in an array of floats. Each item in the array is a timestamp, an LED is turned on based on that value.
For example, [0.01,0.53] means sleep 0.01s, turn on LED, pop off 0.01, sleep 0.53 seconds, turn on LED.
I have two questions:
1)How can I receive data and pop off data at the same time? I'm thinking I can send maybe 10 items for the Arduino to buffer at one time, and repeat that until the whole action is done. The popping off action is time sensitive, so I can't do it sequentially. How can I run both functions at once? Are arduinos capable of multithreading?
2)I'm using an arduino with BLE and sending over the data using serial.read() from an iPhone. and the device only allows 18 bytes to be sent over at one time and it is very slow. What other methods can I use? I need to send 18 bytes from my iPhone, wait 2 seconds, then send it again otherwise the arduino treats it as one single send and the other values are not sent over.
3)Is there a better way of doing all of this that I'm missing?
Thank you very much.

The arduino keeps time in microseconds.  You can't have fractional microseconds.  It only lets you have integer microseconds.  floats are inherently inaccurate.  They simply cannot hold many values exactly, they're just approximations.  Using floats here is not good.  You should be using unsigned long variables instead and keeping time in milliseconds instead of seconds.  That will greatly improve performance once you get it done and also make your work easier.

Arduino can't multithread, but you can certainly have code that is constantly switching back and forth checking each thing once every few microseconds.  You just have to write your code to do things in short chunks.  It's called "non-blocking" code.  Look that up.

Answer to #2:  It really depends on what exactly you're using.  That doesn't sound like a normal limitation.  It has to be an issue with either the module you have or the software you're using somewhere.  You have to share all those kinds of details if you really want help.

Answer #3.  You haven't really explained the end goal or what you want to actually accomplish.  Are you blinking lights to the beat or something?  Either way, there is probably a better way to do it.

What exactly do you mean when you say "pop off"?

why do you need to transmit a float? ... a beat is more along the lines of a single bit data

@Delta_G Didn't know that about floats. Thanks! I will change it. 2) I'm using Beetle BLE. I've read from multiple threads that BLE has a packet limit. Am I wrong? How do I go about increasing this value? 3) Yeah that is what I'm trying to do. The timestamps of the beats are stored in an array on the iPhone and it is sent over to the Arduino over BLE, which is then supposed to light up LEDs based on that time. By pop off I mean removing an element from the array.

@jsotola I'm transmitting timestamps of every beat of a song in an array. How would a beat be transmitted as a single bit?

a pulse in realtime

Why would you send timestamps of every single beat?  They're beats.  They're rhythmic.  You don't need that much information to convey what to do.  A start time, a rate, and a number of beats or a stop time.

@Delta_G I'm looking for precision. Some songs have different bpm in different parts of the song.

Yes, so you send a new BPM marker and change the beat.  You still don't have to send a timestamp for every beat.  Unless the drummer really really sucks you only need to send something at most every few measures.

@Delta_G That's a solution I guess. It would certainly make my job a lot easier. However, the device is meant to be a learning tool for beginner dancers/ musicians so if possible I'd still like to make it as precise as possible. I'll look up non blocking functions, and if that doesn't work use the bpm marker method. Thanks for your help!

This is a trap nobies fall into a lot.  You say, "as precise as possible".  So in computers you have to put a number to everything.  There's no such thing as absolute precision here.  At the very least there will be some small time difference between the audio player and the clock on the Arduino.  In reality it takes 200ms for a human to blink their eye.  Think about how fast that is.  So when we talk about something being off by 20 or 50 milliseconds, that is an amount of time that is completely imperceptible to humans in most situations.  You and I are talking microseconds.

So many people fall into the trap of trying to get something to be absolutely perfectly at the same time when such a thing is a physical impossibility.  If a professional drummer were behind the scenes hitting buttons to blink the lights with the beat you'd have timing discrepancies on the order of tens or even 100 milliseconds and everyone in the room would call it exact.  When you are dealing with timing and measurement in computers, you have to start thinking about what precision is really necessary.

@Delta_G Huh, I've never thought of it that way before. Makes a lot of sense.

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


text:
Node.js cannot recognize characters from the serial port
The following script prints everything fine, it recognizes integers from the serial port, but cannot recognize characters.  The if statement does not work with characters.  I have tried both == and === in the if statement
var SerialPort = require('serialport')
var Readline = SerialPort.parsers.Readline
var serialPort = new SerialPort('/dev/ttyAMA0', {//ttyAMA0
  baudRate: 9600
})

var parser = new Readline()
serialPort.pipe(parser)
parser.on('data', function (data) {
if(data === 'c'){/// c is not recognized
  console.log('data received: ' + data)
}

})
serialPort.on('open', function () {
  console.log('Communication is on!')
})

The Arduino code is as follows:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(12, 13); // RX, TX
int x = 0;
int y = -30000;
int z = 0;
String data;
char command = 'q';
int left = 0;
int right = 0;
int left_pwm = 0;
int right_pwm = 0;

void setup() {
  mySerial.begin(9600);     // opens serial port, sets data rate to 9600 bps
  Serial.begin(9600);
  }
void loop() {//map and compass data
if (y==30000) {
 mySerial.println('c');
 delay(5);
 mySerial.println(299);
 delay(5);
 z = -25000;
 }

 if(z==30000){
 mySerial.println('lon');
 delay(5);
  mySerial.println(529);
  delay(5);
  mySerial.println('lat');
 delay(5);
   mySerial.println(522);
          y = -30000;
    }
  y++; z++;

  if (!mySerial.available()) {
    return;
  }

  data = mySerial.readString();
   sscanf(data.c_str(), "%c%01d%01d%03d,%03d", &command, &left, &right, &left_pwm, &right_pwm);

  if (command == 'n') { // we got a navigation command
    // update the GPIO accordingly, this only happens once after a new 'n' command has been received
    Serial.print(command);
    Serial.print(left);
    Serial.print(right);
    Serial.print(left_pwm);
    Serial.print(",");
    Serial.println(right_pwm);
    }

    }////end loop

why is this command not before the if statement? console.log('data received: ' + data)

Have you tried trimming data from all white space?

@jsotola  Console Log is telling me the if statement is not working.

@chrisl   data = data.trim();  Bingo,   Thanks!

@HarryHobson, console log inside the if statement is preventing you from seeing what data is being received ... it is a poor debugging procedure

If you use the line parser in Nodejs, it does not remove all line ending characters. I think (though I currently cannot cite it), that only the 'ņ' character is removed from the string. But Serial.println() sends "\r\n" as line ending. That means, that your string is "c\r", which is not equal to "c".
By using the trim() method of the String type, you can remove all white space from start and end of the string, including line ending characters like '\r'.


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

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

About every 1 minute or so.

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

That isnt really good. What about the flash memory?

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

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

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

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

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

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


text:
How to power ESP32 with 230V AC
I want to power ESP32 with 230V AC and I don’t know how to do it. The requirement is that it must never overheat. What components should i use? The ESP will be in small space with no airflow. Will it be even possible?

with an AC/DC switching power supply?

What do you mean "overheat"? The ESP32 is robust microcontroller, according to the datasheet, the board can work in a temperature range of -40 to +125 degrees Celsius. Do you think that your setup will get that hot?

And regarding the power, you can just use a standard 5V Wall adapter with a  voltage regulator

I’m not experienced with changing voltage and this kind of stuff, but I expexted it to produce quite a lot of heat. Am I wrong?

Yes, it generates very low heat. It gets a bit warm during Wifi operation, but even without any airflow in a tight container it will not get damaged.

Switched mode power supplies do not generate any major heat, and if your only load is the ESP32 then good luck trying to get anything hot

@Coder9390 thanks

I would just suggest standard USB chargers. They give you 5V and are very cheap

The folks over at Random Nerd Tutorials offer a solution for this exact scenario using a HLK-PM03 Hi-Link 100-240V AC to 3.3V 1A DC converter. They add electrical and thermal fuses to mitigate some of the possible failure modes of over-temperature or over-current.
The specifications of the HLK-PM03 are here. I suspect there will be a few alternatives available that do a similar function.
My suggestion is to be hyper-aware of the safety issues of dealing with mains power, and to be realistic about your own capabilities.


text:
How to split 12V power suply to arduino and led matrix panel
I'm trying to build my Arduino project with Arduino mega and led matrix panel. I'm wondering what power supply should I buy, my first thought was to power the matrix panel from a 5v Arduino pin, but I read here that it's not really a good idea. So now I'm wondering if I can buy a 12V power supply and somehow split it to 6V and 6V (or something like it). To connect one end to Arduino and the other to the matrix panel. If it's possible, how do I do that? Thanks for any help!

what is the arduino mega power supply voltage requirement?

6-12V, but it runs on USB too, so 5V minimum i quess

so, if it runs on a 12 V supply, then connect it to a 12 V supply

https://forum.arduino.cc/index.php?topic=618723.0 - In this forum, they don't recommend that, because if a large current is drawn, it will overheat the built-in power regulator.

you don't want to use the arduino to supply current to drive peripherals anyway ... LEDs and motors should be supplied externally ... arduino should only provide control signals ... if you are still worried, then use a buck converter to supply 5 V to the arduino

That's why I'm asking if and how to split power from that 12V power supply.

I wouldn't recommend to share power-supply as disturbance from the high power load could cause erratic Arduino behavior. A simple decoupling capacitor could be enough,  https://en.wikipedia.org/wiki/Decoupling_capacitor or a more complex solution such as buck converter and so on...

No,you cannot split the voltage and expect the devices (Arduino and LED strip) to work correctly together (would lead to different ground levels beside other problems). For getting a different voltage you would need a voltage regulator. A switching "buck" regulator is the better choice here than a linear regulator (lile the one on the Arduino), since it is way more efficient (To get from 12V to 5V a linear voltage regulator would burn up the excessive 7V as heat).
But since both Arduino and LED strip use 5V, why not just buying a 5V power supply, which can provide enough current. Then you can connect it to the Arduino and the LED strip in parallel. No need for voltage regulation in that case.

Figure out the amp draw of each component, i.e. Arduino and LED strip.  Buy a voltage regulator that supplies the voltage needed but, more importantly, can supply the Arduino amp draw plus the LED strip amp draw.


text:
How to work with WS2812B 16x16 matrix panel from aliexpress
I'm completely new to Arduino, and I want to build the project using an LED 16x16 matrix, but I don't know where to start. On the internet, I keep finding these custom matrix panels and they aren't similar to mine. So I'm asking here. Does anyone have experience with this Arduino-compatible RGB LED matrix panel? This is the link to the Aliexpress product.

Will I need an additional power supply? What will I need to install to make it work? Where do i plug what wire into my arduino? Thanks for any answer!

It's just a string of WS2812B LEDs that have been "bent" into a grid. You treat it exactly like any other WS2812B strip of LEDs.
You have 256 LEDs, and as far as the Arduino is concerned, they are just in a line numbered 0-255.
The "grid" arrangement is solely down to you to you to calculate.  Fortunately 256, or 16x16, is very easy to work with: you have a byte which can represent any one of the LEDs, and each half of the byte (a nibble) is one coordinate.
The traditional calculation to convert X and Y into a linear number is:
num = x + y * width

where width is the number of LEDs in the X direction (16).  However since we're working with a width of 16 that can be optimized to use bit-shifting and bitwise operations:
num = x | (y << 4)

That is assuming LED 0 is on the left (either top or bottom) and LED 1 is one place to the right.
Will you need an external power supply for it? Yes, most certainly (and they even provide you with a dedicated power connection for it). 256 LEDs, if all are turned on full brightness at once, could consume up to about 15 amps (20mA per channel, three channels per LED, 256 LEDs).

Just want to add more to your answer. Theoretically, 5V - 15A the power supply he needs. But he may get away with just 2A power supply if he's careful not to turn on all LEDs at a time and just use about 80/255 brightness on each colour. From my experience, I had a project that used 18 panels of 8x8 ws2812b. It was just a single letter (using just one colour) displayed on each LED panel so that I could get away just with a single 12V - 2A power supply for the whole system. Step down (buck) to about 3V3 at each LED panel and each panel had its own nano clone to control it.


text:
Optimised random alphanumeric string generator
I'm trying to build arduino nonce generator, but the only thing I found is this question on arduino forum but I can't find out how to make it work for me. I checked and Serial.available() is always 0 for me and if I delete the If I still get nothing
My code:
void setup() {
    Serial.begin(9600);
    randomSeed(analogRead(0));
}

void loop() {
    byte randomValue;
    char temp[5];
    char letter;
    char msg[50];     // Keep in mind SRAM limits
    int numBytes = 0;
    int i;
    int charsRead;

    if(Serial.available() == 0)
    {
        charsRead = Serial.readBytesUntil('\n', temp, sizeof(temp) - 1); // Look for newline or max of 4 chars
        temp[charsRead] = '\0';   // Now it's a string
        numBytes = atoi(temp);
        if(numBytes > 0)
        {
            memset(msg, 0, sizeof(msg));
            for(i = 0; i < numBytes; i++) {
            randomValue = random(0, 36);
            msg[i] = randomValue + 'a';
            if(randomValue > 26) {
                msg[i] = (randomValue - 26) + '0';
            }
            }
            Serial.println("Here is your random string: ");
            Serial.println(msg);
            Serial.print("I received: ");
            Serial.println(numBytes);
            delay(1000);
        }
    }
}

How do I make it work?
Do you have some working random alphanumeric string generator that you are using?

Why do you check for if(Serial.available() == 0)? If you want to read data from Serial you should check for if(Serial.available() > 0), which can be written shorter as if(Serial.available()). Please try that

Is this right? You are reading in a 4-digit number, and then using that as the number of digits to put random characters into a 50-byte array? Why not read a 2-digit number? Or at least test if the number is > 49 or not.

if(randomValue > 26) should be if(randomValue >= 26). Other than the fixes suggested in these three comments, the sketch should work as advertised.

@chrisl even with that, the code never goes into that if

Your problem seems to be related to how you get the actual length you want to generate. There are other ways you could do that. Since your max seems to be 4 characters, you could possibly enter "9999" which would overflow the 50 bytes temp variable.
You could simply read until \n and then atoi. Then cap at 50.
As a side note, here's a function I've used in the past to generate (pseudo)random strings for network requests (e.g. state or nonce parameters)
#define MAX_UID 8 /* Change to whatever length you need */

const char * generateUID(){
  /* Change to allowable characters */
  const char possible[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  static char uid[MAX_UID + 1];
  for(int p = 0, i = 0; i < MAX_UID; i++){
    int r = random(0, strlen(possible));
    uid[p++] = possible[r];
  }
  uid[MAX_UID] = '\0';
  return uid;
}


text:
Strange behavior from uint32_t, acting like signed int (Nano clone)
I'm having trouble with these variables. As you can see they're uint32_t type, so they should have a maximum value of 4 million or so, but they're rolling over and going negative at 32,767 like a signed int. Here's the relevant code:
byte lPin = 7;
char buff[100];
uint32_t loAvg = 0;
uint32_t hiAvg = 0;

void setup() {
  pinMode(lPin, OUTPUT);
  digitalWrite(lPin, HIGH); // Active LOW, so this is off

  Serial.begin(9600);
  // Generate high/low averages
  for(int i = 0; i < 100; i++) {
    loAvg += analogRead(A0);
  }
  loAvg /= 100;

  digitalWrite(lPin, LOW);
  delay(500);

  for(int i = 0; i < 100; i++) {
    hiAvg += analogRead(A0);
  }
  hiAvg /= 100;

  digitalWrite(lPin, HIGH);
  delay(500);

  sprintf(buff, "loAvg=%d, hiAvg=%d", loAvg, hiAvg);
  Serial.println(buff);

  Serial.println(hiAvg);
  digitalWrite(lPin, LOW);
  hiAvg = 0;
}

void loop() {
  sprintf(buff, "test=%d", hiAvg);
  Serial.println(buff);
  hiAvg+=100;
}

I removed a bunch of stuff from the code to save posting the whole (much longer) thing. If it ends up being relevant I can though, I just think I narrowed the problem down to this. Observing the serial monitor I get this on startup:
loAvg=287, hiAvg=0
933
test=0
test=100
test=200
...

The test=# repeats until 32700, then continues at -32736. I'm confused by the hiAvg=0 followed by the 933, showing that it totally is getting a high average, because that's around what it should be. Even if it's the sprintf() messing with it, in the setup function the value should only be around the 900 range so it wouldn't overflow there. Any ideas anyone?

there are only three lines involved ... my bet is on sprintf() ... specifically the %d ... that formats the data for output

"%" PRIu32  There's almost no reason to use sprintf over snprintf. In this code as written, no reason to use either.

This code above is only the parts that were relevant to the question so I can understand not seeing the point. The sprintf is only used during testing. When DEBUG is defined, the serial prints are between #ifdef / #endif blocks so they're not present during normal operation. I did end up figuring out that I needed %lu. Thank you for the replies and answers.

%d expects a signed int. %u expects an unsigned int. Insert the l modifier to expect a long in each of those cases. So you need a format code of %lu to print a uint32_t.
The following code:
#include <Arduino.h>

void setup()
{
    uint32_t x=110000;
    char buf[50];

   // Open console
   Serial.begin(115200);

    sprintf(buf, "%%d: %d\n", x);       Serial.print(buf);
    sprintf(buf, "%%u: %u\n", x);       Serial.print(buf);
    sprintf(buf, "%%ld: %ld\n", x); Serial.print(buf);
    sprintf(buf, "%%lu: %lu\n", x); Serial.print(buf);
}

void loop() {
   ;
}

prints this:
%d: -21072
%u: 44464
%ld: 110000
%lu: 110000

*printf and bit-width specified types
#include <inttypes.h> or C++'s #include <cinttypes> counterpart (when you have it; not on AVR-based Arduinos) gives access to macros defined for the format specifiers for each of the fixed, fast, and least versions of these types.  All of these macros expand to some string literal or another.
For uint32_t the macro defining to its format specifier is PRIu32.  For an AVR, this is "%lu".  It needn't be "%lu" in  the general case.  uint32_t is one of the types where you can often get away with using "%lu" and have it either work out being exactly correct for the platform or somewhat incorrect but working anyway because it's a platform where unsigned int and unsigned long happen to have the same representation.
In C and C++, and so Arduino, adjacent string literals are concatenated into one logical string in the early phases of compilation that follow the macro preprocessor.  So, the intention is that you choose the correct macro and you put them following something like "%" or "%12" if you wanted a minimum-width of 12.  As in "%" PRIu32 and "%12" PRIu32 respectively.  So, in your case,  having included (directly or indirectly) <stdint.h> for uint32_t and <inttypes.h> for PRIu32 or their C++ counterpart headers, and then your code looks something like:
snprintf(
  buf,
  sizeof buf,
  "loAvg=%" PRIu32 ", hiAvg=%" PRIu32,
  loAvg,
  hiAvg
);

There's little to no reason to not use the snprintf.  The reason why the non-n version exists at all is mostly that snprintf showed up in 1999, instead of circa the mid 1970s.  I'd say it's pretty safe to use snprintf now.  There probably hasn't been an Arduino that doesn't support it.  About the only reason to use sprintf would be if you were calling it with a null pointer for the buffer argument to get it to do a dry run and tell how much memory you need for the result, and you just didn't want to supply a limiting size.
There are PRI... macros for all of the combinations of standard bit width and choice of signed decimal, unsigned decimal, lowercase hex, uppercase hex, etc.  E.g "%" "PRId16" is  for int16_t in decimal, "%" PRIX64 for uint64_t in hexadecimal with uppercase alphabetics.  The are ones for the fast and least bitwidth types, and whole show is repeated with macros starting with SCN for the scanf specifiers, not that you should use the scanf family functions for anything really.
snprintf and sprintf are variadic functions.  After the format specifier there's no type information available to the compiler to know what conversions to apply.  It will convert types smaller than int rank up to int on unsigned int, but that's about it.  E.g. it will not reliably down-convert an unsigned long long into an unsigned int, the way it would if the types were known.  Modern compilers will sometimes warn you if you grossly misapply format specifiers, but they're not required to.  They're not expected to dissect the format string and attempt to recover type information.  So it's up to you to make sure whatever you pass in for arguments matches with the format specifiers.  As you've seen it's confusing if you get it wrong with printf-type functions, but it doesn't cause real problems unless you, you know, don't limit it to stay within the output buffer with the snprintf version.  In the case of passing in an unsigned long long where an unsigned int was expected, in practice, for a little-endian system like AVR, it may appear to do that for one argument.  But then it may fail on the next argument, because the size of the last argument was in correct, it is now reading from the wrong place.
Print/Stream/Serial concatenating and buffering
The way you're using sprintf in your code isn't taking advantage of any of its features that Serial/Print doesn't do.
Serial.print(F("loAvg="));
Serial.print(loAvg);
Serial.print(F(", hiAvg="));
Serial.println(hiAvg);

Despite taking four lines, this is actually smaller, faster, more reliable code than the sprintf one-liner.
Putting the output into a buffer first might make sense if you were going to put it into a packet, like for UDP or nRF24L01.  But, Print/Stream/Serial already concatenates and buffers things for you.

Incidentally, if you're going to use printf functions and you're doing it on an AVR-based Arduino, look at the avr-libc documentation for the _P variants that take their format strings from PROGMEM and the PSTR macro.
It is also possible to complete the implementation of <stdio.h> for stdout and stderr through libc-specific means.  So, if you really want to, you can have the regular printf function pushing data out through Serial (among other things) such that you don't need to buffer repeatedly with sprintf.


text:
Send packet of multiple sensors data to Bluetooth module
In my project I am using 3 sensors. I am sending a regular stream of sensors data to Bluetooth module  but now I want to send data in form of packet (which may be 30 bytes or 40 bytes of size) in which first 10 bytes contain the first sensor data while next 10 bytes contain second sensor data and so on. But problem here is I am not finding something relevant to my approach. Can any one suggest me some link or some way to do this.
Thanks in advance.

https://en.wikipedia.org/wiki/Struct_(C_programming_language)

It is unclear to me, what the actual problem is here. For imposing a packet protocol onto the serial stream for binary data you normally just send a start byte (or start byte sequence), which you defined, then send the length of the packet and then the data. Not much more to it. Is that, what you are asking for?

Yes i want this. Can you please help me how to do this using arduino IDE software?

There are many ways to transmit binary data over a byte-stream based interface like Serial (which is used by common bluetooth modules like the HC-05/HC-06). I will only describe one here.
First we need to define a start byte, which marks the start of a new packet. That can be any arbitrary value, for example 0xFF. It is also possible to use a specific byte sequence as start marker. This start byte/sequence is what we send first when transmitting a packet.
Then we want to transmit the size of the following data. With small to normal packet sizes a single byte is enough here (giving room for up to 255 bytes).
Sometimes you might want to compute a CRC hash value to check for data corruption. That could also be send here. But unless you have a system, which really is loosing/corrupting data, you don't need it. I suggest you first try it without and check, if corrupted data is really a thing for your setup.
And then we are sending the actual data. How exactly you are doing this depends on how the data is stored in your code. Though you will use Serial.write() in some way. If you want a more specific answer in this regard, you need to include your code, so that we can see how you are storing your sensor data.
On the receiving side you would then wait for the start marker, read the size byte and then read bytes until you have received as many, as the size byte said. As you have multiple sensors, you could send the sensor data of each sensor in it's own packet. The data could then be formatted like: 1 byte sensor ID, X byte sensor data.


text:
TimedAction.h: No such file or directory
I am new to Arduino and I am trying one of the library TimedAction.h for sudo multithreading on Arduino. However the library is not present in the Arduino. How do I install external library(if it is)?

Have you googled how to install libraries? The [playground site]https://playground.arduino.cc/Code/TimedAction/) of that library even has a section about how to install it. Didn't it help you in some way?

You can use three ways to install libraries in the Arduino IDE:
The probably easiest way is to go to Sketch > Include Library > Manage Libraries, (you can use Ctrl+Shift+I too) search for the library you want to install and click the install button. After that you need to include the library in your sketch with a #include <LibraryName.h>, or if you don't know the name, head again to Sketch > Include Library and click on the library you want to include.
If a library is not in the Library Manager from step one, you have to download the .zip file, go to Sketch > Include Library > Add .ZIP Library and search for the file. You just have to do that once, and it will be moved to your library folder. Again, make sure to include the library into the sketch.
If you just have a single file, you can move it to the sketch folder and include it by using #include "LibraryName.h", but you have to do it all over again for a new sketch, so I would recommend the other solutions if you can and want to use it permanently.


text:
Problem with push button
I am making a project where if the push button is pressed, the LCD screen will show a message. But with many trial and errors, it doesn't give the right result.
Here is the circuit:

Here is the code:
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
#define BUTTON 7
void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  pinMode(BUTTON, INPUT);
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 0);
  // print the number of seconds since reset:
  lcd.print("Press Button");
  lcd.setCursor(0,1);
  lcd.print("to make COFFEE");
  if (digitalRead(BUTTON) == HIGH) {
    lcd.clear();
    lcd.print("SENT TO MACHINE");
  }
}

It looks like you have several issues.

The positive and negative supply "rails" on your prototyping board are not connected together internally. You should add a positive jumper wire.

You are trying to detect when the button provides a HIGH logic level, but there is no possibility of doing so with the current "wiring".

One more thing that could help to determine this, or another possible issue, is a picture of your setup from a different angle so we can see exactly how that button, capacitor, and resistor are connected.
This is the area which would be nice to see from a different angle.

I haven't analyzed (yet anyway) their circuit as you have, but message on the LCD indicates that lcd.print("SENT TO MACHINE");  was executed at some point (because of the trailing INE on first line), which seems to cast doubt on "no possibility of doing so". So, you may want to acknowledge it in the answer, if only to dismiss it, assuming it doesn't inform you that something different is going on in their circuit.

@timemage -  You mis-quoted me. It's "You are trying to detect when the button provides a HIGH logic level, but there is no possibility of doing so with the current "wiring".", which is an accurate statement. I also suspect, just like you,  the OP's declaration pinMode(BUTTON, INPUT); has turned the input into a radio antenna, and it just happens to trigger the message "SENT TO MACHINE". HINT: The best part of SE is the fact that multiple people can answer the same question.

The quote seems accurate. Your reply indicates that you've misunderstood what I'm saying. What you're doing right here in this comment is what I meant by acknowledging what is happening on the LCD, if only to dismiss it. Only, not doing it in the answer. What you're saying about the behavior of it without the pullup is inline with what thinking I have done on it. So, no need, to my make own answer. However, your answer can be improved by saying both of these things, in the answer itself.

@timemage - LOL, every answer on every SE stack can be improved. Instead of complaining about my answer, try posting a better one. I suggest one of those "book report" answers. Use all the tools in the "compose answer tool box", like bold text, italic, H1, H2, etc. Make sure it is the maximum number of chars you can enter (30K or is it 60K now?), because that's exactly what  a new user is looking for, right?

It's an honest attempt to be helpful. I'm not sure what is going to convince you of that.

The point of having comments under answers is so that answers, which may be quite good, can be tweaked further to make them better. Or, to point out inaccuracies.

I appreciate your help! Everything is working (and sorry for the bad angle :/ )

you should implement debouncing because when you press the button with your hand it will bounce and make the signal instable so no High/Low, here's the doc from Arduino:
https://www.arduino.cc/en/Tutorial/BuiltInExamples/Debounce


text:
Stopping a motor after a given time period
I have a code to turn on a LED when IR Proximity sensor having a object less than 6cm in front of it,
and the LED goes down after it is removed.
Now, I want the LED to run for 3 seconds only, even if the object is not removed, how should I modify my code?
Many thanks in advance!
int LED = 13; // pin for the LED
int Sensor = 2;// pin for the IR Sensor

void setup(){

  pinMode (LED, OUTPUT);
  pinMode (Sensor, INPUT);
}

void loop(){

  if (digitalRead(2)){

      digitalWrite(LED , LOW);
  }

  else{

    digitalWrite ( LED, HIGH);
    // if the IR sensor detects an object, the LED turns on or else it should not turn on
}

what are you doing? ... you already asked this question, and it was answered, and you accepted the answer

int LED = 13;
int Sensor = 2;

void setup(){

  pinMode (LED, OUTPUT);
  pinMode (Sensor, INPUT);
}

void loop(){

 if (digitalRead(2)){

        digitalWrite(LED , LOW);
        delay(3);
  }

 else{

    digitalWrite ( LED, HIGH);``
 }

I do not see any relation to the question, sorry.


text:
When trying to write multiple bytes to a serial port, all 0x00s are skipped
I am using a dynamixel XL320 servo, and am trying to control it using an Arduino Uno. I’m trying to send a simple packet that turns on an LED. I believe the correct format of this packet according to the dynamixel documentation is the following: FF FF FD 00 01 09 00 03 19 00 01 00 00 00 3F 1D (However, the correctness of this packet at the moment is ultimately unimportant to my problem). Before actually writing any more of my servo library, I decided to try to just send an array using Serial.write, to ensure that would transmit properly. I used puTTY session logging, and then a hex editor to track what was actually sent. The results are:
FF FF FD 01 09 03 19 01 3F 1D.
I’ve seen other issues where 0x00 is interpreted as null in a string and so a string like 0x10, 0x00, 0xDD would only send 0x10. But here as an array that shouldn’t be a problem. Here, it seems like the 00’s are just being skipped. Would really appreciate help here, and please let me know if more clarity is needed this is first time posting here.
My code for this test is as simple as I could think to make it:
Serial.begin(9600);
while(!Serial) {;}
uint8_t data[16]= {0xFF, 0xFF, 0xFD, 0x00, 0x01, 0x09, 0x00, 0x03, 0x19, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3F, 0x1D};
Serial.write(data, sizeof(data));```

Works for me. Are you sure PuTTY is not messing up with your bytes?

I would certainly second Edgar's sentiment. The biggest suspect is your receiving setup, not the Arduino.

I’m not sure, that could be true. How did either of you set up the receiving end?


text:
How to keep track of millis during sleep mode
In my application, I need to keep track of the time the application has been running as well as use sleep modes. However, when using the sleep modes, Timer0 is disabled, and therefore millis stop counting.
Is there a way to measure/count how long the Arduino was in sleep mode for?
To give you some more background info, this is what I'm trying to achieve:
I am using a pressure sensor which sends an interrupt to the Arduino every 80ms and wakes it up.
The program does various routines to process the data which can take anywhere from 2ms to 60ms.
It then goes into sleep mode until another external interrupt occurs, approx 20-78ms later.
The application has many processes based on time, such as a stopwatch, timer and alarm, so I need to be able to keep track of this, preferably using millis().
The device is running on a single cell 250mah LiPo battery which at present only lasts about 4 hours.
I'm using an ATMega1284.
In most of the sleep modes Timer0 is disabled. Which means that millis() stops counting. Is there a way, without using an RTC (Both Space and weight are at a premium), to keep millis counting whilst in sleep mode?
I notice that SLEEP_MODE_IDLE keeps Timer0 running, but that means that for every millisecond an interrupt wakes up the device. Please correct me if I'm wrong, but given that my loop can take about 60ms to execute, I don't see much advantage to sleeping for 1ms.
Possible solutions:

Use Timer2 for the millis function?
Use the Watchdog Timer to count how much time has passed whilst in
sleep mode and add this to millis() when waking up?
If there was a VERY small SMD RTC which didn't need any external
components such as oscilators etc then this might be feasible.

MAX31343 in a 2.1mm x 2.3mm, 8-Pin WLP Package...?

I think you'd need an RTC anyway, if you are doing alarms. The millis will drift to much to be very useful for accurate time keeping. If space is an issue, you could use the timer2 asynchronous mode and connect a 32khz crystal to the TOSC pins. Then you can use the Power-save sleep mode. I've done in on a clock project, but it's a bit of work figuring out how to set it up the code. After calibration it now accurate to within a minute per year.

@Majenko - the MAX31343 only records seconds, not milliseconds

The only way to keep millis() running is sleep mode is to sleep in
SLEEP_MODE_IDLE. Switching to Timer 2 would make no difference, as
all timers but the watchdog are stopped in other sleep modes. The
watchdog is horribly inaccurate, so you do not want to rely on it for
any kind of timekeeping.

I don't see much advantage to sleeping for 1 ms.

Sleeping for 1 ms saves a little bit of power. But if you do that
60 times every 80 ms you will save a lot of power. I suggest
you do just that: sleep when you are done with your calculations. When
you wake up, if you see that the waking up came from the external
interrupt, the you process it. Otherwise you just go back to sleep.
Note that if the 80 ms period of the external interrupt is
consistent enough, you could use that as time source.

Thanks @Edgar. As soon as I posted the question I went searching through the library at the 80ms interrupt but it turns out that the library just requests data every 80ms, and the sensor sends an interrupt once the data is ready.

I've tried permanently turning off timer 1 and timer 3, as well as turning off the ADC and BOD for 59.95 seconds of every minute, and using sleep mode idle. The main loop checks if an interrupt has happened otherwise it goes back to sleep. The impact this has had on power consumption has been minimal. I'm now trying with a real time clock.

I found a RealTimeClock that I could use: RV-8803.
It's only 3.2mm x 1.5mm x 0.8mm, has an internal XTAL, and can provide time in 100th of a second.
Sparkfun do a breakout board (BOB-16281), and accompanying library.
Given that I've already got a bunch of decoupling capacitors in my circuit and can use the internal pullups of the ATMega1284, I think I can probably integrate the RV-8803 without the need for any additional components.
On the breadboard, interrupts are working well and I can now use EXTENDED_STANDBY sleep mode instead. The only downside is that the RTC records time in 100ths of a second, whereas my program was using milliseconds previously. I'll need to see if 100ths is accurate enough for my needs.
Failing that, I'll have a look at @Gerben's suggestion above.


text:
How do I debounce multiple external interrupt buttons?
I have an Arduino sleeping most of the time to save power and there are two buttons attached to different interrupt pins that run different functions.  These functions are different from each other, but both have to run long blocking code.  I don't want the button bouncing (or even deliberately being pressed multiple times during the blocking code) to queue up multiple runnings of the interrupt function.  I also don't want the sleep period to be short because I'm trying to keep if off as much as possible to save power.  I don't want to have to wait 8 seconds after a button press before the button's action happens.  As such, I would think flags or polling the pins from the main loop are not the way to handle this because of power inefficiency and long latency between button press and action.  Should I have each ISR detached its own interrupt pin until its action is complete and then reattach?
const int buttonA = 6;
const int buttonB =  10;

void setup() {
  pinMode(buttonA, INPUT_PULLUP);
  pinMode(buttonA, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonA), actionA, FALLING);
  attachInterrupt(digitalPinToInterrupt(buttonB), actionB, FALLING);
}

void loop() {
  sleep_function();  //takes 8 seconds
}

void actionA(){
  //some blocking code that takes 2 seconds, but that I want to run immediately upon button press
}

void actionB(){
  //some blocking code that takes 10 seconds, but that I want to run immediately upon button press
}

the blocking code is like having one driver with one vehicle, and without a cell phone, picking up packages

When using interrupt, I personally prefer to use hardware debouncing with a RC circuit and a Schmitt Trigger. See "RC Debouncer" section of Jack Ganssle's A Guide to Debouncing.

do not do action on button press ... insert a layer of separation between a button press and the desired action ... a button press should set a flag, nothing more ... the desired action should only occur when flag is set ... that way, multiple button presses are ignored if the flag is already set

Just set a flag in the interrupt, and run your code in the loop
const int buttonA = 6;
const int buttonB =  10;
volatile byte flagA = 0;
volatile byte flagB = 0;

void setup() {
  pinMode(buttonA, INPUT_PULLUP);
  pinMode(buttonA, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonA), actionA, FALLING);
  attachInterrupt(digitalPinToInterrupt(buttonB), actionB, FALLING);
}

void loop() {
  if(flagA){
    //some blocking code that takes 2 seconds, but that I want to run immediately upon button press
    flagA = 0;
  }
  if(flagB){
    //some blocking code that takes 10 seconds, but that I want to run immediately upon button press
    flagB = 0;
  }
  sleep_function();  //takes 8 seconds
}

void actionA(){
   flagA = 1;
}

void actionB(){
   flagB = 1;
}

will the interrupt always end the sleep or will it just resume the sleep?

The interrupt ends the sleep, and if you want to sleep, you have to put it to sleep again.  https://www.gammon.com.au/power


text:
What is happening when digitalWrite(pinname, LOW) is invoked after pinMode(pinname, INPUT_PULLUP)?
I read the Arduino official docs on digitalWrite and am confused about what is happening from an electrical perspective when digitalWrite is invoked on INPUT_PULLUP pins.
Say my code says this:
pinMode(4, INPUT_PULLUP);
digitalWrite(4, LOW);

The docs say:

If the pin is configured as an INPUT, digitalWrite() will enable
(HIGH) or disable (LOW) the internal pullup on the input pin. It is
recommended to set the pinMode() to INPUT_PULLUP to enable the
internal pull-up resistor. See the Digital Pins tutorial for more
information.

Does this mean pin 4 is floating or is it at ground?  Are those two lines of code equivalent to pinMode(4, OUTPUT); digitalWrite(LOW);  ?

look at section 14.2 of https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf

Thanks, I a noob in EE and arduino so I think I need some help understanding what this doc means.  I'm trying to get at what kind of behavior to expect.  Are you also saying this is chip dependent?

definitely chip dependent, but probably very much the similar

It's pretty explicitly stated there in your quote: if you write a LOW when in INPUT mode it disables the pullup resistor. That's all it does.
pinMode(4, INPUT);
digitalWrite(4, HIGH);

is exactly the same as:
pinMode(4, INPUT_PULLUP);

And
pinMode(4, INPUT_PULLUP);
digitalWrite(4, LOW);

is exactly the same as
pinMode(4, INPUT);

Of course this exploits a peculiarity of the AVR's IO block, but any decent core will emulate that functionality for compatibility with older code.

Thanks, can you address the part of the question about if pinMode(4, INPUT); leaves the pin floating or if it is at GND?

A pin set to INPUT with no pullup and not connected to anything is always floating. It can never output anything or be set to any level unless it is explicitly set to OUTPUT.


text:
Help- Optical Sensor interfacing with Arduino
I am a newbie and I wanted to know if it is safe to connect this NPN output sensor directly to one of the GPIO pins of the Sparkfun redboard. Do I need some extra circuitry or components? Thanks

top left schematic on page 5 ... safe ........ bottom schematic ... not safe


text:
ESP8266 Repeated Crashing When Pulling JSON Information
I am trying to create a simple LCD device that pulls a random Jeopardy question from here: http://jservice.io/api/random, then cycles through the category/value, clue, and correct question at the push of a button. However, I am running into problems when I pull the clue. I am running this on an AdaFruit Feather Huzzah esp8266, but the board repeatedly crashes before returning the GetJeopardy function. In particular, I get errors like this:
--------------- CUT HERE FOR EXCEPTION DECODER ---------------

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 3584, room 16
tail 0
chksum 0xb0
csum 0xb0
v2843a5ac
~ld

The function is as follows:

typedef struct {
  const char* cat;
  int val;
  const char* clue;
  const char* corr;
} jeop_problem;

jeop_problem GetJeopardy(){
  jeop_problem JQ;
  const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) +
                            JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8) + 370;
  DynamicJsonDocument doc(bufferSize);
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("Pulling Jeopardy");
    HTTPClient http; // Object of class HTTPClient
    WiFiClient client;
    http.begin(client, "http://jservice.io/api/random");
    int httpCode = http.GET();
    deserializeJson(doc, http.getString());
    http.end(); // Close connection
    const char* cat = doc[0]["category"]["title"];
    JQ.cat = cat;
    Serial.println(cat);
    int val = doc[0]["value"];
    JQ.val = val;
    Serial.println(val);
    const char* clue = doc[0]["question"];
    JQ.clue = clue;
    Serial.println(clue);
    const char* corr = doc[0]["answer"];
    JQ.corr = corr;
    Serial.println(corr);
  }
  else {
    // We don't have a connection, return blank problem
    JQ = {"ERROR: RESET", -1, "ERROR: RESET",
                                    "ERROR: RESET"};
  }
  Serial.println("Pulled Jeopardy!");
  return JQ;
}

In particular, the board is always crashing before printing "Pulled Jeopardy" to the Serial console.
Thanks in advance!

I should have mentioned, it does get through all the Serial.println(corr); but does not get to Serial.println("Pulled Jeopardy");

To be sure any of them were reached, you'll want a following .flush() call.  Otherwise it may crash/reset immediately afterwards and you wouldn't know the difference.  Put differently, without a .flush() after, Serial.println("Pulled Jeopardy"); you can't be as sure that it didn't actually get to that line.

I don't know how your code relates to your reset cause.  It's possible that it doesn't at all.  But so long as you're providing information about where it hangs, it might as well be as accurate as possible.

the responses are over 1kb, how will that fit in such a small buffer? try a 4kb buffer (you have an 8266 here, not an UNO ;) )

I had the same issue caused by definition of StaticJsonDocument<200> jsonDoc inside a function. When I moved the definition as a global variable (out of the function) the problem was solved. I would suggest to try moving DynamicJsonDocument doc(bufferSize) out of the function.


text:
SPI Arduino slave not recieving data correctly
Using an STM32L476RG Nucleo microcontroller board as the SPI master and an Arduino mega as a slave with pin 52 for SCLK, pin 53 for SS and pin 51 for MOSI on the Arduino. There is no issue with the STM32 transmission as the USB logic analyzer I'm using (parallel to the arduino) shows a correct output on the master side so this is an Arduino issue:

The problem is the Arduino isn't recieving properly. The arduino code:
    #include <SPI.h>
#include<stdint.h>
#define SPI_SCK 52
#define SPI_MISO 50
#define SPI_MOSI 51
#define SPI_SS 53
char dataBuff[500];

//Initialize SPI slave.
void SPI_SlaveInit(void)
{
  // Initialize SPI pins.
  pinMode(SCK, INPUT);
  pinMode(MOSI, INPUT);
  pinMode(MISO, OUTPUT);
  pinMode(SS, INPUT);
  //make SPI as slave

  // Enable SPI as slave.
  SPCR = (1 << SPE);
}

//This function returns SPDR Contents
uint8_t SPI_SlaveReceive(void)
{
  /* Wait for reception complete */
  while(!(SPSR & (1<<SPIF)));
  /* Return Data Register */
  return SPDR;
}

//sends one byte of data
void SPI_SlaveTransmit(char data)
{
  /* Start transmission */
  SPDR = data;
  /* Wait for transmission complete */
  while(!(SPSR & (1<<SPIF)));
}

// The setup() function runs right after reset.
void setup()
{
  // Initialize serial communication
  Serial.begin(9600);
  // Initialize SPI Slave.
  SPI_SlaveInit();
  Serial.println("Slave Initialized");
}

// The loop function runs continuously after setup().
void loop()
{
  uint32_t i;
  uint16_t dataLen = 0;
  Serial.println("Slave waiting for ss to go low");
  while(digitalRead(SS));

  i = 0;
  dataLen = SPI_SlaveReceive();
  for(i = 0 ; i < dataLen ; i++ )
  {
    dataBuff[i] =  SPI_SlaveReceive();
  }

  //  Serial.println(String(i,HEX));
  dataBuff[i] = '\0';

  Serial.println("Rcvd:");
  Serial.println(dataBuff);
  Serial.print("Length:");
  Serial.println(dataLen);
}

The message i'm transmitting is my full name and is 12 characters long. The master first sends the length of the message (12 in this case) so the arduino knows how many characters to recieve and then the message is transmitted. On the logic analyzer output everything looks fine and I can see the message. However I keep getting results like this in the Arduino serial monitor:

I should also note I'm using a sparkfun logic level converter between the master and slave to step the STM32 3.3v signal to 5v for the arduino input: (Imagine the arduino is not uno but master in the following image with the pins changed to the ones I've listed above)

I'm seeing no message next to 'Rcvd:' and a length of 0 most of the time, if not than a number much larger than 12. What seems to be the issue?

Your logic analyzer decodes a bunch of NUL bytes between the letters, the first of which would be interpreted by Serial.println() as an end of string. If you want to know what the Arduino receives, you should instead print all the bytes (in hex) in a loop. Also note that receiving in an ISR would be more robust than relying in the received byte count and busy-waiting.

Slave code is quite rare, you can take a look at nick gammon's implementation here: https://forum.arduino.cc/index.php?topic=52111.0 . The thread is quite old, but this is how a slave would be implemented.


text:
Clock Problem when Migrating from Arduino IDE Mighty Core to Atmel Studio
I've been programming an ATMega1284 using the Arduino IDE with the MightyCore package.
I'm now trying to migrate to Atmel Studio.
Atmel Studio (7.0) will now compile the sketch and all required libraries (that took some time) and upload the output via USBAsp to the ATMega (Essentially just calling avrdude). However...
The uploaded sketch is running differently. It seems slower. For example, the Tone() function seems to output a lower pitch. My best guess is that Atmel Studio has the xtal/clock setting wrong, but I can't find where to inspect/change it?
I'm using a 12mhz external xtal, and can only communicate with the chip via UART. If I upload the sketch from Arduino IDE then it reverts back to normal.

Do you have correct F_CPU in project?

Thanks KIIV, where would I find that? (Apologies, new to Atmel Studio)

First result of Google showed where to find it. That fixed the problem, Thank you @KIIV

For anybody else who comes across this: In the Solution Explorer, Click on ArduinoCore, click on the spanner icon, go to Toolchain, and for both C and C++ compilers, go to Symbols, and have a look at F_CPU. Repeat the above for the sketch.

Or Alt-F7 (Project - 'projectname' properties), click on Toolchain, then Symbols under AVR/GNU C compiler. Also don't forget to set the correct fuses, under Device Programming (Ctrl-Shift-P)


text:
Removing spaces between characters in MD_Parola
I'm using ESP8266 and Max7219 module (8*32) and MD_Parola library. To create my own font, at first I used of MDParolaFontEditor and created the following fonts.

I edited file MD_MAX72xx_font.cpp using Arduino IDE and saved them as 150 and 151. I want to have the output as the following.

But, the output is as:

As you can see, there is a space between them! I think this space is automatically added between characters. My problem is that, how can I remove this space?
My code:
void loop () {
char MyText[]={151,150,0};
P.displayText(MyText, PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
P.displayAnimate();
delay(3000);
}

add this line in the void setup part
P.setCharSpacing(0);

The matrix with the extra space is 9 (not 8) columns wide (possibly because is was designed to be able to display a colon on a clock).


text:
Motor does not work for a specific case when programming with L293D motor driver shield
I tried to make a car that moves using a 4x4 keypad.
Pressing "12" unlocks the car and sets the motors to move forward. After that, if I press 4, the speed of the left motor is reduced to half allowing the motor to turn left, and vice versa for right wheel when key 6 is pressed.
Here is the code:
#include <Key.h>
#include <Keypad.h>

char* startCar = "12";
int position = 0, state = 0;

/*
 * state 0: off
 * state 1: forward
 * state 2: backward
 *
 */

const byte rows = 3;
const byte cols = 3;
char keys[rows][cols] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'}
};

byte rowPins[rows] = {2,3,4};
byte colPins[cols] = {PD7, PD6, PD5};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, rows, cols);

int a=12,b=11,c=10,d=9;
void setup()
{
  pinMode(a,OUTPUT);
  pinMode(b,OUTPUT);
  pinMode(c,OUTPUT);
  pinMode(d,OUTPUT);
  Serial.begin(9600);
  setLocked(true);
}

void loop()
{
  char key = keypad.getKey();
  Serial.print(key);
  if (key == '9')
  {
    position = 0;
    setLocked(true);
  }
  if (key == startCar[position])
  {
    position ++;
  }
  if (position == 2)
  {
    setLocked(false);
  }
  if(state)
  {
    if(key=='2')
     {
      //Move forward
        state = 1;
        runmotors(255,0,0,255);
     }
     if(key=='8')
     {
      //Move backward
        state = 2;
        runmotors(0,255,255,0);
     }
    if(key == '4')
    {
      if(state == 1)
      {
        runmotors(127.5,0,0,255);
      }

      else if(state==2)
        runmotors(0,127.5,255,0);
    }
    if(key == '6')
    {
      if(state == 1)
        runmotors(255,0,0,127.5);
      else if(state==2)
        runmotors(0,255,127.5,0);

    }
  }
  delay(100);
}

void setLocked(int locked)
{
  if (locked)
  {
    state = 0;
    runmotors(0,0,0,0);
  }
  else
  {
    state = 1; // Moves forward
    runmotors(127.5,0,0,255);
  }
}
void runmotors(int s1,int s2,int s3,int s4)
{
  analogWrite(a,s1);
  analogWrite(b,s2);
  analogWrite(c,s3);
  analogWrite(d,s4);
}

Everything works perfectly, except for the fact that when the state is 1, i.e. car is running forward, and I press 4 the left motor completely stops instead of reduced speed. The LED on the motor driver shield which shows whether a motor is running or not also goes off.
It is not a fault of the motor shield or the arduino as it worked when I test it individually with the motors (i.e. without the keypad etc).
Here is a photo of the shield:

Although my problem is not quite visible in this, but here is a video of the car: https://www.youtube.com/watch?v=bq19gNOL8Pg

If you pick the car up off the ground do the motors turn?  In my experience you can't control speed on DC motors all the way to 0.  At some point you hit a point where you're giving the motor power but just not enough to turn.  On my tank robot a PWM of 127 usually just gets me a hum and no movement.  Sometimes if I pick it up so that there is less rolling resistance the motor will turn a little.  Try using like 200 or so instead and see if it works like that.  That will at least tell you that the code is working.

Also note that analogWrite only takes integer values.  Sending 127.5 is the same as 127 in that case.

@Delta_G, The LED on the motor shield shows whether a motor is getting power or not. That LED itself goes off.
I think the particular pin (pin 12) of L293D is defective and is only supplying digital power, either full or 0.

What board?  On an UNO pin 12 is not a PWM pin.  It will give full power for anything above 127 and nothing for 127 and below.  It is truly a digital pin.

Yes an Arduino Uno board using the L293D motor driver shield. https://www.robomart.com/l293d-motor-driver-shield-for-arduino-raspberry-Pi-robotics?search=l293d&dsearch=l293d.  According to the documentation, the pins for connecting the robots are 9,10,11,12. All other pins are working perfectly except pin 12.

On an UNO pin 12 is not a PWM pin.  Pin 12 can only be high or low.  If you try to use analogWrite on a pin that isn’t capable of PWM then it will give you HIGH for any value greater than 127 and will give LOW for values 127 and below.  It will not produce PWM at all.

Yeah, this seems right.
I am a beginner at this and so just be confirm, when I say pin 12 in my code, it is the same pin irrespective of whether I have shield attached or not, right?
This makes sense. If you add this as an answer, I will mark it as correct. Thank you.

Yes, the pin numbers in the code are the pin numbers on the Arduino board itself regardless of what is connected to them.

On an UNO only certain pins are capable of PWM.  Pin 12 is not one of them.  When you try to call analogWrite with pin 12 it will recognize this and will simply call digitalRead for you with HIGH or LOW depending on whether your input is greater than 127.
With most motor controllers you can use one pin as a direction pin and the other as a PWM pin.  So to go one direction you set pin 12 HIGH and do inverted PWM on 11 (if those indeed go to the same motor I didn't look at your shield).  To go the other direction you write LOW on 12 and PWM on 11.
The motor turns when one pin is HIGH and the other is LOW.  When you set pin 12 high then PWM pin 11, whenever 11 is LOW in the PWM cycle it is turning the motor on and when it is HIGH it is turning it off.  So to make it run you might have to PWM 0 for go and 255 for stop.  Sometimes your PWM is on the enable line and then you still use 255 for go and 0 for stop.  It just depends on how things are wired.
When pin 12 is set to LOW then the motor is on when 11 is at the high part of the PWM cycle and off when it's low so you use 255 for go and 0 for stop.  But the whole time pin 12 doesn't have to change.
Now I am not 100% sure that this is the case with your particular motor controller, I'm more of a coder than a hardware guy.  But I've written enough code for motor controllers to know that you usually either need two direction lines and one PWM line or one direction and one PWM.  If that's not the case here then we can let someone else work on why.


text:
HC-08 Bluetooth module not showing up on iPad
I have an HC-08 Bluetooth module Bluetooth module hooked up to an Arduino Uno but for some reason, it doesn’t show up in the Bluetooth menu in my iPad settings. Can you help?

Can you check, if you show up on other devices? Maybe you have access to an android device? That can show you, if the problem is with the iPad side or with the HC-08 side

Ok, I will try that.

Just tried that and it worked. Weird.

This article describes, that the HC-08 should work with iPhones. I think iPads are similar. Maybe on your iPad try to turn off and on bluetooth, restart the iPad or try to update it. Difficult to say, what the problem is here. And we are experts in Arduino, not in iPads.


text:
How to upload code to an Arduino Uno using HC08 Bluetooth module
How do you upload code to an Uno from a Mac using the HC08 Bluetooth module? I know I need to use this wiring.

Anyone know?

you can only upload to Uno over RX/TX and the Arduino must be reset to bootloader


text:
Interfacing Arduino nano ,adxl335 ,nrf24l01
I'm trying to make a project with this conection diagram  but I don't think it's correct , and my adxl sensor died . Can you help me with a modified one ?

the Nano ground is not connected to the battery ground

what do you need help with? ... you said nothing about any problems that you are having ... adxl sensor died does not mean anything ... description of what you observed would mean something

I want to connect that transceiver and accelerometer to arduino nano and I don't know how to make the connections correctly , I used that picture and destroyed my adxl sensor.Battery's -, accelerometer and tranceiver should all be connected  to arduino's ground and adxl's VCC should be connected to arduino's 3V3 ?

did you get the solution i have the same project


text:
AJ-SR04M Screw Purpose
I've got 3 AJ-SR04M sensors working on an Arduino MKR Wifi 1010, but I was curious what the purpose of this screw on the sensor boards is. It seems to somehow impact the accuracy/performance, but I can't seem to find any info on it. Anyone know what this is called/what it does exactly?

Adjustable inductor

could be a selector switch

@jsotola No, it's an adjustable inductor. You get them by the hundred in old radios. The black thing in the middle is a ferrite core that screws in and out to change the inductance. You need a special plastic screwdriver to adjust them so that the metal of the screwdriver doesn't affect the inductance while you're tuning it.

The purpose is probably to tune a bandpass filter. At a guess.

As @Majenko says, it's probably for inductor tuning. Since it's not mentioned in the documentation, I would suppose it may already be tuned or adjusted at the factory during final test. That's not the say you can't tinker with it, but as you noted, it requires a little more detail on what it exactly does to do that.

@Majenko thank you! Luckily I only fiddle with one of 3 that I bought so I'm just going to try to tune it back to look like the other 2.


text:
NodeMCU server stops responding after a while
I'm new to NodeMCU and ESP. I've created a basic web server on my NodeMCU.
The server works fine for the first few minutes after resetting the board or re-uploading code. But after about half an hour, the server just stops responding and becomes unreachable. Funny thing is, after sending a few failed requests, server starts to respond normally again.
The code i'm using:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

String wifiName = "blablabla";
String password = "blablabla";

ESP8266WebServer server(9090);

void setup() {
  Serial.begin(115200);
  pinMode(5, OUTPUT);
  digitalWrite(5,LOW);

  connectToWifi();
  server.on("/", handleHomepage);
  server.on("/action", handleAction);
  server.begin();
}

void loop() {
  server.handleClient();
}

void handleHomepage() {
  server.send(200, "text/plain", "Welcome to esp8266 homepage!");
}

void handleAction() {
  String parameter = server.arg("value");

  if (parameter == "") {
    server.send(200, "text/plain", "No parameter supplied.");
    return;
  } else {
      if (parameter == "on") {
        digitalWrite(5,HIGH);
      } else if (parameter == "off") {
        digitalWrite(5,LOW);
      }
    server.send(200, "text/plain", "Action received successfully.");
  }
}

void connectToWifi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifiName, password);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}

What should I do to keep the server always active? Thanks in advance.

research on ESP8266WiFiGratuitous

https://github.com/esp8266/Arduino/pull/6889


text:
Can i use PL2303 USB to TTL Serial Converter Module send keystrokes using Arduino nano?
If I can, which library to use (an example code will be great).
Here is the module:

Like Majenko said in their answer.  If you don't want to get a board with native USB support for whatever reason, and want to use your Nano, the easiest thing is to have the Nano pretend to be a PS/2 keyboard, at which point you're likely using a PS/2 to USB adapter, rather than a logic level serial to USB adapter.  Odds are good that you can acquire a USB to PS/2 adapter locally from someone that has old computer junk, assuming you don't just happen to have one yourself.

it may be possible ... research FreePIE ... https://andersmalmgren.github.io/FreePIE/

@timemage, how?

@Juraj, you want me to write an article in the comments about how to make a Nano behave like a PS/2 keyboard?

@timemage, more about how to convert it to USB signal. but now I realized what you mean.

@Juraj, in my comment "PS/2 to USB adapter" refers to this sort of thing, in case that wasn't clear.

No. That is serial. Just like every other USB to TTL Serial converter. The clue is in the name.
You need an Arduino with a dedicated native USB interface, like those based on the ATMega32U4 chip.
Or dedicated software on the PC that will read serial data and emulate keypresses (which is outside the scope of this website).

Is there any module that lets me do this

I posted something to that effect in a comment on your question itself.  Had it been worded differently, I might have put it as an answer, or part of one.  Now that you have an answer addressing what you actually asked, you should avoid changing the nature of the question though.

@WHITE_DEVIL yes there is. It's called an Arduino based around the atmega32u4.


text:
Inconsistent values from NTP client
Hardware- ESP8266 Based NodeMCU
I am using NTP Client for time in my alarm project.
I am facing an issue where NTP client is not returning proper values, in the sense that it works properly for the first few hours- returning the time every second, however after some time the values go haywire.
First few hours:-
21:00:45
21:00:46
21:00:47
21:00:48

After sometime:-
06:00:02
06:00:45
06:00:49

What could be the cause of this and how do prevent it?

don't use NTP library on esp. esp has 'built-in' ntp functions. see the esp8266/NTP-TZ-DST.ino in IDE examples menu

returning the time every second ... maybe the NTP server starts to ignore your request

@jsotala I'm only using timeClient.getFormattedTime and timeClient.update() , in my loop, I have found out that timeClient.update() does not return anything until the update interval is over, which in my case is about 10 mins


text:
How to use Atmega328p-PU from an Uno, on a breadboard without a crystal
How do you use Atmega328p-PU from an Uno, on a breadboard without a crystal?

By changing the fuses to use the internal oscillator.

You could have the 328P's "fuses" set so it uses it's internal 8Mhz oscillator. In the Arduino IDE you can then select, for example, the Arduino Pro Mini 3.3V (which also runs at 8Mhz)

How do you set the fuses?

With a programmer or another Arduino acting as a programmer.

So all I have to do is bootload it as a Pro Mini 3.3v?

bootload it as a Pro Mini 3.3v? how do you do that ? There's an Upload Using Programmer, which requires that you use a Programmer.

Go online for a tutorial on how to do it.

If you buy your ATmega as supplied by Microchip, through one of the
large electronic parts resellers, it will come with its default fuse
configuration:

clock source: internal 8 MHz RC oscillator
clock prescaler enabled at ÷8, yielding a 1 MHz system clock
bootloader disabled

You could use it in this configuration, but you will probably want to
disable the prescaler. This can be done by changing the right fuse or,
alternatively, by some code running early in setup(). Note that, with
no bootloader, you will need an ISP programmer in order to load the
code. If you want the convenience of serial downloading (i.e. you would
use an FTDI cable rather than an ISP programmer), you will have to burn
the bootloader using an ISP programmer, and adjust the fuses to enable
it and set its size.
If you take the ATmega from an existing Uno board, or buy one
preconfigured with the bootloader, the fuses will be set differently:

clock source: external crystal
clock prescaler disabled
bootloader enabled and sized to 0.5 KiB

In this case you will have to change the clock source.
In any case, you would tell the IDE you are using an Arduino Fio, or a
Pro or Pro Mini with a 328P clocked at 8 MHz. And you will need an
ISP programmer to load either your program or the bootloader. You could
use an Arduino running the “Arduino as ISP” firmware for this.
Check the datasheet for the details on configuring the fuses. You can
also use one of the online fuse calculators, like this one or this
one.

Ok thanks for the help.

You can use another IC like the 555 timers as an external oscillator.


text:
How to connect HC-06 with HC-08 with the HC-06 as master and HC-08 as slave?
How do you connect HC-06 with HC-08 with the HC-06 as master and HC-08 as slave? I will try it using 2 Arduino Unos.

Ok sorry. Thanks.

You cannot. The HC-06 is a slave only device.
So you need to use a device as master, that is actually capable of it. I don't know, if the HC-08 can do it. Another typical bluetooth master device is the HC-05. Just like HC-06, but can also be a master.

Ok thanks for the help.


text:
Is there a way for an Arduino to flash another one without a computer?
I am going to create a game console. The games will be in an SD card and an Arduino (or an Atmega chip) will read a hex file's contents to RAM and will flash it to another one. Something like this but here, the guy says that this only works for atmega328, and I am planning to use a ATSAM3X8E chip and also I am worried about the power levels (5v - 3v3).
Is there any way for me to use an Atmega chip like Atmega16u2 and use that to flash something like an ATSAM3X8E? If so, what protocol should I use and how may I implement it in my code?

That video isn't really relevant. Unless you want to waste two arduinos for this project, which is a bit wasteful. What you want to do is have the Arduino program itself. This is normally done via a bootloader (at least on the ATMegas). I found a bootloader that updates it main program via a SD card

As for the ATSAM, have a look at https://stackoverflow.com/questions/14960075/can-i-run-a-program-from-a-sd-memory-instead-of-flash-on-an-evaluation-board-em

@Gerben I want to waste two arduino's, actually I will use an Atmega16u2 for flashing the ATSAM3X8E from the sd card.

application on ATSAM3X8E  can write to flash without problems so it can update itself. Arduino has SDU library for SAMD21 to load sketch from SD card

@Juraj I need to display a GUI to ask the user about which program to flash.

On which Arduino do you want to run this GUI? The one doing the uploading, or the one running the game (which probably is the one with the screen and buttons)?

@Gerben on the one with a screen and some buttons. Like this: When the console powers up, the Atmega16u2 flashes gui.hex file to the ATSAM3X8E. Then, when user selects a game to load, ATSAM3X8E sends the name of the game to 16u2 and the 16u2 flashes the game to ATSAM3X8E.

I'd have the GUI write the new "programs" id to some file on the SD card and then reset the Arduino. The bootloader can then check this file, to see if it needs to program a new game to flash.

you don't need the 16u2

Good idea @Gerben , I may try that approach.

@Juraj how may I flash then?

read from SD and write to flash. of course there are many details to solve. the SDU library code checks at boot for new firmware binary on SD card and loads it to flash at address after the loader code, then executes it. this is close to what you want.


text:
Using Arduino to control a high voltage DC device
I am an amateur hobby electronics enthusiast , and given the situation , I too am trying to make a contactless hand Sanitizing system like everyone else. My project requires a 36V DC solenoid valve to be actuated through the arduino momentarily for the sanitizer to drop. Obviously I will be using a relay module to electrically isolate both the circuits. But I don't have a 36 V DC adapter . So what is the best way to power up the solenoid valve? Batteries are available to me right now? How do I calculate how many 9v batteries do I need ? How many AH would they require ? Would they get drained too fast?

36/9 = 4. AH defines the amount of time they will last at a certain current draw. You need to know the current draw and how long the solenoid will be powered for.

If you’re talking about the square looking 9V batteries then save yourself some money and don’t even buy them.  They’re not appropriate for driving motors.  They can’t produce the current you need.  Get AA batteries for this.  You need enough to make 36V.  It will be a lot.  You’d be better off getting a LiPO pack or just using a smaller servo.

My HP printers had 32V adapters, which will probably work too. Maybe you can salvage one from an old printer gathering dust somewhere in your house.

two old 18v ungrounded laptop supplies could be put in series to get 36v; those are safe and dirt-cheap.

For the record, 36V is hardly a "high voltage" DC device. The term high voltage usually implies something well over mains voltage. It makes me think of thousands, or even tens of thousands, of volts

Batteries are going to be annoying because they're run out and have to be recharged/replaced. A mains power supply would be easier to "set and forget.
I did a google search on "36V DC power supply" and found a 4A power supply from "Alitove" on Amazon for $22.99 US. That should be fine. (Assuming you are somewhere with 120VAC mains power. If you live somewhere with 240VAC mains power you would need a different unit, but since I found one, I would expect a google search in your region would find one for your area.)
I would suggest using a logic-level MOSFET transistor + flyback diode to switch your DC power. That's easier to do than a relay (That would require another power supply.)


text:
How do I generate a graph from Arduino sensor data?
I used a DHT 11 sensor with an Arduino Uno to measure temperature and humidity. I used the following code to print the temperature and relative humidity in Serial Monitor.
dht DHT;

#define DHT11_PIN 7

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

void loop()
{
  int chk = DHT.read11(DHT11_PIN);
  delay(1000);
  Serial.print(DHT.temperature);
  Serial.print(" , ");
  Serial.println(DHT.humidity);
  delay(1000);
}

The Serial monitor printed the following data values in a list in the order of: time, temperature (Celsius), humidity (percentage).
22:17:55.686 -> 25.00 , 55.00
22:17:57.713 -> 25.00 , 55.00
22:17:59.741 -> 25.00 , 54.00
22:18:01.769 -> 25.00 , 54.00
22:18:03.793 -> 25.00 , 55.00
22:18:05.813 -> 25.00 , 54.00
22:18:07.837 -> 25.00 , 54.00
22:18:09.868 -> 25.00 , 55.00
22:18:11.880 -> 25.00 , 55.00
22:18:13.900 -> 25.00 , 55.00
22:18:15.915 -> 25.00 , 56.00
22:18:17.950 -> 25.00 , 56.00
22:18:19.972 -> 25.00 , 56.00
22:18:21.994 -> 25.00 , 56.00
22:18:24.024 -> 25.00 , 56.00
22:18:26.043 -> 25.00 , 56.00
22:18:28.093 -> 25.00 , 55.00
22:18:30.122 -> 25.00 , 55.00
22:18:32.141 -> 25.00 , 55.00
22:18:34.142 -> 25.00 , 55.00

I used the PuTTY software to save the sensor data to a CSV file. However, I end up with a few strange numbers at the top before the values start printing properly.
25.25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00
25.00 , 53.00

Also, when I open the CSV file in Excel, the time values have disappeared, even though they were there in the serial monitor.

What can I do to get the time stamps to show up in my spreadsheet? Additionally, is there a way I can have the graph automatically update as more data is read?

Your post title is how to generate the graph, but what you actually described  and asking is how to get ride the unnecessary garbage from the Putty.

The time stamps you see in the serial monitor are generated by the serial monitor.

You could write a visualization with processing

Perhaps the built-in Arduino Serial Plotter is all you need to visualize your data.  I wrote a tutorial a while back that might help you.

I  used the serial plotter. I get a plot of both temperature (as a blue line) and humidity (as a red line). However, I can't still get time to display on the x-axis. How do I accomplish this?

I believe the x-axis is the number of samples.  If you send your plot values on a particular time cadence, the x-axis should then correspond to time.


text:
Cant find Sdl and Sca pins in lcd display
My project is of non contact temperature sensor.I am using RG1602A lcd display and mlx90164 temperature sensor.
But the problem is, there's no sdl , sca pins in my lcd display.
Is there any way, to overcome?

Why should there be SDA/SCL pins? That display doesn't have an I2C interface, but the standard parallel interface.

Yes, is there any way I can use other pins to connect with Arduino and sensor.

Of course you can still connect that display to the Arduino, you just need more pins as with an I2C display. There are tons of tutorials out there about that and the standard LiquidCrystal library supports that communication mode. Have you troed some of those tutorials?

No, I will check now, tq

You will need an I2C adapter board like this to interface your LCD 1602 via I2C.


text:
how to "skip" one parameter of a method with a default value letting it use it's default value, but change parameters after it
lets say we have a function like this(fictional):
function1(int Z, int X, bool Y=true, int Count=10, int ID=1,bool TeaTime=false);

And I want to run this function, but I want to change all parameters, except for "Count", and I want that to keep using it's default value.
Disclaimer
in this fictional case and in the real case where I faced it I found the default value in the header file and I manually coded it in. but I do not want that, at least not to rely on it, for example if the default value changes in the library then in my code it would still be forced to use that old value. also for ease of use and reducing the chance at problems/mistakes.
What I tried:
I already tried NULL and DEFAULT, both of them actually let my code work perfectly fine, but I made a test function which had such default values and printed the variables to the serial output and I found that using NULL actually overwrites it to 0 and DEFAULT overwrites it to 1.
I also tried some things like keeping one empty and such but those would give compile faults.
in short:
is there a way to let one parameter somewhere in the middle of the parameters of a function use it's default value while still manually setting the later ones?

No, you have to define everything until the last non default value you are passing. Everything after gets default values. You can make overloaded functions or you can pass the structure..

your question belongs at https://stackoverflow.com/questions ... it is a general programming question

Most intuitive would be builder pattern with "chaining" ability (=returning reference to itself)
Something like (computer version, in arduino remove main, iostream and cout):
#include <iostream>

struct SomeParams {
    int        X;
    int        Z;
    bool       Y = true;
    int    count = 10;
    int       ID = 1;
    bool teaTime = false;

    SomeParams(int x, int z) : X{x}, Z{z} {};

    SomeParams & noY() { Y=false; return *this; }
    SomeParams & setCount(int c) { count = c; return *this; }
    SomeParams & setId(int i) { ID = i; return *this; }
    SomeParams & yesTeaTime() { teaTime = true; return *this; }
};

void function(SomeParams const & p) {
    std::cout << "X: " << p.X
              << " Y: " << p.Y
              << " Z: " << p.Z
              << " ID: " << p.ID
              << " count: " << p.count
              << " teaTime: " << p.teaTime
              << "\n";
}

int main() {
    function(SomeParams{45,68}.yesTeaTime().setId(154758).noY());

    // without chaining:
    auto params = SomeParams{4457,5468};
    params.setCount(4515);
    params.setId(15);
    function(params);
}

Ah, I see what you mean, that would indeed work well.
took a while to look how it works since I didn't code that much lately and then indexes tend to blend between languages in memory.
but this seems very usefull and fun for making more dynamic things.
however in my case the problem faced mostly was that in some normal libraries they had noting like this(just checked if there was), so instead of making better functions, I originally was looking for using existing ones better.

still I am happy, since I came to learn/get inspire with something new, and got that now, by learning something nice and interesting(I think I even sought for something like this some years ago)

Added other way without chaining (if you have those setters without returning reference to itself eg like: void noY() { Y=false; })