text:
Recognition of the signal duration from the sensor
Good afternoon!
I create a human movement alarm.
I am signaling atmega328. I receive a signal from the sensor and if there is a signal, then using the "tone" I generate a sound.

I am using a motion sensor. I want that if one movement was noticed for a short time, then turn on a short melody, and if the movement continues longer than a certain time, then play a long melody.
I wrote the code to play a short melody. How can you track that the input from the sensor is at a high logical level for a long time and play a long melody in this case?
unsigned long timing; // Variable to store the starting point
int T = 15; // Signal playback time!
int S0 = PIND0; // With Doppler Probe

int S1 = PIND1; // Food
int S2 = PIND2; // Audio

void setup ()
{

  // Port control via registers:
  DDRD = B00000110; // Set the output pin (the first and second pins of register D as output pins, the rest (0.3-7) are set as input pins)
  // 76543210
  pinMode (PIND0, INPUT);
  pinMode (PIND1, OUTPUT); // Power for the audio amplifier
  pinMode (PIND2, OUTPUT); // Audio
}
void loop ()
{
  if (digitalRead (PIND0))
  {
    sendSignal ();
  }

  if (digitalRead (PIND0) == 0)
  {
    digitalWrite (PIND1, LOW); // Food
    digitalWrite (PIND2, LOW); // Sound
  }
}

void sendSignal ()
{
  digitalWrite (PIND1, HIGH); // Food
  for (int n = 0; n <4; n ++)
  {
    for (int i = 4800; i <5800; i ++)
    {
      tone (PIND2, i, 10); // tone (port, frequency in Hz, duration in ms) 600 - 6 sec.
    }
  }
}

And yes, if my code can be optimized, tell me how!

What is the threshold duration between a “short” and a “long” signal? How long are the short and the long melodies? Is the short melody a prefix of the long one? What should the program do if it reads a long signal while playing the short melody?

I don't see where you are even attempting to detect the long condition in your code.
First of all you need determine what constitutes a long vs. a short detection.  My recommendation is to write your code to do the following:

Initial detection.
Wait for your "short" interval.  If the detection is gone, then you know it was a "short" one and you can play your short music.
If the detection is still there, wait for the remainder of the time for your "long" detection.
If the detection is gone you know it was a "short" one since it didn't make it to the "long" state.  So play your "short" song.
Play your "long" music since the detection lasted for the duration of the long interval.

I'll leave the actual coding of that to you.  I'll also add that doing it this way, that is using the built-in delay() function is probably not the best approach overall.  The issue is that delay() blocks your loop() function and prevents you from doing anything else while it's delaying.
A better approach is to implement this as a state-machine coupled with an timer-driven interrupt.  That will give you much better control over your detections and also allow you do handle other inputs or set other outputs while you are waiting for detections to occur.
There are many resources online that discuss how to configure and handle AVR timers and their interrupts and there are also many resources discussing state machines and programming them in C.

You don't need both a “short” and a “long” interval: only a single “threshold” duration to tell them apart. If the signal stops before the threshold duration, short melody, otherwise long melody. 2. Nothing here is time-critical to the point where you would need a timer-driven interrupt. Timing with millis() is easier and perfectly appropriate in this case.

all the same, I do not understand, if the melody is playing and there are delays, then the microcontroller at this time does not look at what comes from the sensor. In fact, after being triggered, the sensor still remains in a high state for another 2 seconds, so I count 2 responses (4 seconds) - to play a short melody.
more than two - long. How to implement it? study interrupts? Two functions of short and long melody to write?

I am trying to make interrupts, but I cannot set pin PD0(PCINT16) for interrupt

@Антон It doesn't really help to say "I cannot set pin...".  It's also not directly related to this question.  Please ask another question, post your code, show how you are connecting the pin.  Then someone can help you.


text:
Convert from hexadecimal to binary

I need to simulate a pulse train. Everything is in order with this code, it solves its problem.
The question is: I need to change the keys, but it is too difficult to manually type in so many zeros and ones each time.
On the other hand, I know that my hexadecimal key looks much shorter: "B8C4F9".
Is it possible to create a string in such a way that the system itself translates to the binary system?
And the second question: How can you automatically measure the length of an array so as not to manually calculate KEY_LEN?
const int KEY_LEN = 24;
const char key[KEY_LEN] = {"101110001100010011111001"};

int T = 200; // Pulse repetition period in microseconds
int Zero = 80; //0.4*T; // Duration of zero in microseconds
int One = 120; //0.6*T;// Duration of a unit in microseconds

const int LED_PIN = 13; // Used digital pin 13 of the arduino to connect the transmitter

void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  for (int n = 0; n < KEY_LEN; n++)
  {
    if (key1[n] == '1') //If the bit read == 1
    {
      sendSignal(One);
    }

    else if (key1[n] == '0')//If the bit being read == 0
    {
      sendSignal(Zero);
    }
  }
}

void sendSignal(int duration)
{
  digitalWrite(LED_PIN, LOW);
  delayMicroseconds(duration);
  digitalWrite(LED_PIN, HIGH);
  delayMicroseconds(T - duration);
}

is this for a TV remote control?

This is to control the front door

There is really no reason to save the key as a string, as you are doing. You can just save it as a normal number. Then you can also use the hexadecimal representation on your code:
unsigned long key = 0xB8C4F9;

Then you need to send out each bit of that number:
for (int n = 0; n < KEY_LEN; n++)
{
    if (key & (1 << n)) { //If the bit read == 1
        sendSignal(One);
    } else {//If the bit being read == 0
        sendSignal(Zero);
    }
}

The following is happening in the if statement: (1 << n) will take the value 1 (binary 0b00000001) and will shift the bits to the left by n digits. For example: If n is 2, we get (0b00000001 << 2) = 0b00000100. With this we can select a bit in our number. Then we take that and do a bitwise AND & with the key. That will set all bits to zero, which are not currently selected. The resulting number is zero, if the corresponding bit in key is zero. If the corresponding bit is 1, this will return a number different from zero (which is interpreted as true. Thus we check, if the n-th bit of key is one or zero.

How can you automatically measure the length of an array so as not to manually calculate KEY_LEN?

Generally you can calculate the size of an array with the sizeof() function:
unsigned int size_of_array = sizeof(array)/sizeof(array[0]);

sizeof() returns the number of bytes. So to get the number of elements, we need to divide by the number of bytes in each element;
For the way shown above this is not that easy. Normally it is not really needed, since such keys normally don't change length very often. If you find a variable type, which exactly fits your key size, you could use sizeof(key)*8 to get the number of bits in it. But your current value 0xB8C4F9 only needs 3 bytes. I don't know a type with 3 bytes, but maybe somewhere you can get something like uint24_t. Honestly here I would just use a hardcoded size, just like you are using a hardcoded key value.

But in this case, the bits are output in reverse (from end to beginning). That is, if the key is in the form, for example "D", then 1011 will be displayed, but this is not true, you need 1101.

For the values to be read correctly, you need to do this, but it is very long and you can get confused:   if (key & (b100000000000000000000000>> n))

Or like this:: if (key & (0x800000>> n))

@Антон Actually no. If you want to change the endianess (from LSB first in my code to MSB first), you just need to  change the count direction in the for loop: for(int n = KEY_LEN-1; n>=0; n--) This would start at the KEY_LEN-1'th bit (MSB of your key) and count down to bit zero (LSB). No need to write that MSB directly as binary or hex.

Thank! Or you can ask another question:
How can you tell what the very last bit is?
key & (1 << KEY_LEN-1). So?

Or like this: key & 1

In general there is no "last bit". Instead the terms MSB and LSB (Monst/Least Significant Bit) are used. The numbers in C/C++ are right justified, having the LSB at the right, MSB at the left. key & 1 gives you the LSB. key & (1 << KEY_LEN-1) gives you the MSB. If you want to send the bits MSB first (then going down till LSB), you would start at key & (1 << KEY_LEN-1) as the first bit in your transmission and go down to key & 1 (aka key & (1 << 0)), which would then be the last in your transmission.

There was a problem. With a key length like this: unsigned long key = 0xB8C4, everything works fine, but with an increase in its length, for example: unsigned long key = 0xB8C4F9 everything breaks down. How can this be fixed ??

source: Stack Exchange

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

sort: votes


text:
What’s the most common (and low cost) microprocessor with at least two threads?
I want to make a next version of my current project. I’m hoping to use an Arduino compatible processor that also supports at least 2 processes simultaneously without using pro threading or any other software workaround. The more commonly used the processor is, the better the user support will be if something goes wrong.

What do you by "supports at least 2 processes simultaneously without using pro threading". What's "pro threading" in this context? Is that a specific library/framework?

ESP32.  Dual core 240MHz, plus an extra XLP state machine.  Cheap and easily available on eBay/Amazon/Ali Express etc.  And with full Arduino support.

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


text:
What’s the most stable digital communication protocol for sewable electronics?
I’ve spent the past few days trying researching communication protocols and I have a few issues. With sewable electronics, you need to work with cables with a fairly high resistance that are constantly moving. That means unreliable and noisy communication. Furthermore relying on multiple data lanes increases the needed number of stitches and the chances of failure.
Adafruit Neopixels use a good system that allows them to only use 1 data pin for a large number of individually controlled addressed devices with a total of 3 connections between each device. Disconnecting the devices while in use doesn’t cause them to crash most of the time, and there’s a lot of expandability. Best of all, the circuit design is incredibly simple because most of the hardware is on board the IC. The problem is that the communication type they use seems to be specifically designed for use on those circuits only, and to my knowledge there is no version of the logic circuit that isn’t coupled with the SMD RGB LED component, and even if there was there’s no way to directly adapt it to other components.
I’ve looked into I2C, SPI, UART, FTDI, USB, CAN-bus, and a bit of DMX and I’m still fairly certain none would work. All I need is to exchange bytes of data between two microcontrollers without them constantly crashing. I’m willing to try the most exotic solutions imaginable.

I found this some time ago ... did not test though ... https://www.pjon.org/SoftwareBitBang.php

Neopixel strings are like (well, not unlike) a giant shift register; the data for each LED is clocked in serially; not easily implemented for what you want. Two-wire RS-485 is very robust but requires transceivers and a two-wire bus. There is also differential I2C, which should be robust enough for your purposes, but it requires transceivers like the PCA9615 and twisted-pair connections. You'll notice why I didn't put this as an answer 8-). Maybe a slow connection over Maxim 1-Wire? Not sure if that is robust enough. Maybe the EE people could come up with a solution.

Try this one: https://en.wikipedia.org/wiki/1-Wire

Ya at this point I think my best solution is to build a new library inherited from the stream class based on 1 Wire. Instead of modulating the VCC supply it could just use a third connection to maintain power consistency, then add capacitors everywhere

You will not get reliable communications over intermittent connections.  one wire sounds great but in reality it needs a second wire called ground. If you go to error correction and detection the target has to respond to ACK or NACK the message. I think the best solution is to use better wire for the connections, you can probably hide them on the inside of the clothing.  You might Try some AWG 28 gauge silicone wire.

RS-485 would be the best if you want robust communication it works on differential voltage principle and also with twisted shielded pair of communication wire it provides very high noise immunity that's its very popular in industrial use.
If you want more out of RS485 then you can use RS-422.


text:
What are a few good ways to connect multiple I2C busses?
I have an issue with a project. I have a backplane with an Atmega328P based microcontroller controlling an I2C bus with multiple peripheral devices. One such peripheral is a removable card with another Atmega328P based microcontroller as the peripheral. I have a TCA4311ADR I2C hotswap buffer on the backplane connected to the port that connects to the card. The card is supposed to be a peripheral device that sends processed data from a sensor to the backplane.
Here’s my issue: one of the sensors I intend to use on the card is an I2C breakout board. To control it, the microcontroller on the card needs to act as a controller, but it also needs to be a peripheral to communicate with the backplane controller. Every time I try to make this work and the card tries to communicate with the sensor, it tries to start a new I2C bus and everything starts glitching.
I’ve tried a few options. Software used to turn normal digital pins into I2C pins didn’t work since the libraries don’t seem compatible. I can’t seem to get the card peripheral to wait until the controller starts the bus before trying to control the sensor to avoid a conflict.
I had an idea to use an I2C multiplexer like the TCA9543A to create two busses but I don’t know if that would work. I also don’t wanna just use SPI or Serial to connect the microcontrollers cause I’d have to undo months of work on coding and custom PCBs. Also using Serial would complicate the connection to the computer and using SPI wouldn’t work if I use an SPI sensor breakout later.
Is there any other way to make this system work?

I2C allows for multiple masters. So you could (indirectly) connect the breakout board to the main I2C bus. Then have the ATMega on the removable card change between master, and slave mode. You'd have to add a way to prevent collisions, as the ATMega doesn't support this part of I2C. Or gracefully deal with with them when they occur.

In an ideal world you would have your other sensor on a separate I2C bus. It can be done with software, but chances are you will have to re-write the library that supports it to use bit-banged I2C.
Yes, you could use an I2C MUX to share the single hardware I2C channel, however that will both be awkward and the results will be sub-optimal anyway.
Most I2C MUX chips, including the TCA9543A, are controlled themselves by I2C, so you can't really use them in your environment, since you really need to switch it to isolate your main bus from the MCU before you switch it from slave to master, which you can't do until after you have switched it from slave to master. If you switch to master before isolating the bus you risk a collision with the main master on the bus and everything going horribly wrong.
These MUX chips are really designed for allowing one master to talk to multiple slaves that share the same addresses.
And on top of that when you've isolated the bus the main master will no longer be able to communicate with that slave board, which will either cause the whole bus to lock up or other strange and unwanted things to happen.
So have another go at using software I2C to communicate with your sensor. Most I2C communication to sensors is pretty straightforward and follows the same rough format, so it really shouldn't be too hard to implement.
Either that or consider replacing the ATMega328P with a more capable microcontroller that has multiple I2C busses.


text:
listener for Plotter library doesn't work
I try to use Plotter to plot some data from my Adafruit Circuitplayground board, but the listener is kept showing "Scanning serial ports..." and not displaying any plot (as shown below in the picture).

I have java 1.8.0_271 installed (in order to run listener) and I put the listener folder under the same directory as the Arduino code file (though I'm not sure if there's a requirement of where to put the listener folder). Arduino is the latest version. Code is copied from the sample code of the Plotter library

close the console window

@jsotola if I close the Serial monitor Listener will be turned off automatically


text:
How to send Serial data from an Arduino Uno into the Serial of an ESP-01?
So, i need to send sound sensor data from an Arduino Uno to the ESP8266 (ESP-01), so it can output a push notification to my phone whenever there's a loud noise. I have the sensor just powered and hooked up to the Analog 0 pin, and the ESP powered and hooked up to the Arduino Serial pins in reverse (RX to TX, TX to RX)
This is the code i have on the Arduino:
void setup() {
  Serial.begin(115200);
}

void loop() {
  Serial.write(analogRead(A0) + "\r\n");
  delay(100);
}

And this is the code i have on the ESP:
(i'm omitting the notification part for clarity, it doesn't even use Serial, so i don't think it should interfere)
void setup() {
  Serial.begin(115200);
}
void loop() {
  String val;
  val = Serial.readString();
  if( val.toInt() < 50 ){ sendNotification("Hello!"); delay(10000);}
}

I have tested the Sensor output and it seems fine, whenever i snap or clap the readings show a peak (although reversed, it stays on 1023 constantly then peaks to around 0~50), and the ESP can also send notifications normally. But the trigger on the notification never seems to fire, so i guess the ESP is not receiving the data properly.
I'm new-ish to Arduino, so i don't know if i'm doing something wrong here,
Thanks in advance!

Serial.println(analogRead(A0)); will send the value as text terminated by \r\n. at receive side use at least readStringUntil

Writing Junk From Memory
Serial.write(analogRead(A0) + "\r\n");

This is advancing a pointer to "\r\n" by whatever number is being returned by analogRead.  In other words, you are not sending the measurement but junk from memory after (or sometimes at) "\r\n"'s memory location.
Serial.println(analogRead(A0)); appears to be what you were going for here.  println's line termination for the UNO serial connection is "\r\n".
Logic Levels
When it comes to attaching the serial connections together, there should be some level conversion going on.  Because an UNO's pins are 5V logic levels and the ESP-01 expects 3.3v levels.

Thanks for the info! Just writing the analogRead(A0) wasn't working, so i supposed the ESP needed the newline and carriage to accept input, just like the AT commands.
The level conversion you said is an hardware conversion, like reducing the 5V to 3.3V with a resistor, or is it a software conversion of some kind?

For the UNO TX to ESP-01 RX a resistor voltage divider will probably work fine.  Going in the other direction you'll need some kind of buffer to reliably get to the UNO's minimum logical level high voltage.

Thanks again! I'll go buy a regulator and see if it works. Another question, i only need to send the serial from the UNO to the ESP, the ESP never sends anything back. Do i need the buffer to regulate the tension for the ESP to UNO connection anyway?

@Jao: there are things called "logic level converters" available that are built for this sort of scenario. Worth a look instead I think.

@Jao, in the direction of UNO to ESP it is likely you just need to create a divider on your UNO TX's signal and the level converter would not be strictly necessary, although one can probably be more efficient.  A divider is a simple solution.  Keep in mind that your UNO TX/D1 is the same signal ultimately goes back to the PC, so when you use it to send to the ESP-01 you are also sending stuff to the PC/Serial Monitor.

Also your ESP-01 is not a 5V device.  So you don't want to power it from 5V in case you've been doing that.  You'll also want to avoid trying to power it from the UNO's 3.3V line, which won't likely provide the current the ESP-01 will demand when doing anything on WiFi.


text:
SD seems too slow for SMTP
I have asked this question on the arduino forum as well.
I have used SMTP before using client.print (and client.println) but I am now trying to move as much text as I can from RAM to SD (and so I need the <SD.h> library). It does not work and I am thinking it may be because the SMTP server "dies of boredom" as it waits for my Arduino to read from the SD card and write it to the client (server?).
In the code below, I have included what I am trying (it will be uncommented if you copy+paste the code) and what already works (which will be commented when you copy+paste the code, but you can uncomment and comment the other section relatively easily). The text file I have on the SD in the code (commented).
If anyone can think of a workaround, that would be great.
#include <SPI.h>
#include <SD.h>
#include <Ethernet.h>

//-v--- Ethernet -----------
byte MyMac[] = {0xFE, 0xED, 0xBE, 0xEF, 0xFE, 0xED}; // <- The physical address of the machine's network card. Should be unique (no two network cards have the same MAC address)
byte MyIp[] = {1, 1, 1, 1}; // <- This is the not the real IP address, but for the real address I have verified that the static IP works for sending mail
byte Dns[] = {1, 1, 1, 1}; // <- Not the real DNS but I got it once through Serial.println(Ethernet.dnsServerIP()); and I know that it works
byte Gateway[] = {1, 1, 1, 1}; //<- Not real
byte Subnet[] = {1, 1, 1, 1}; //<- Not Real

EthernetClient client ;
//-^--- Ethernet -----------

//-v-- Smtp --------
char ServerChar[] = "blahblah";
//-^-- Smtp --------

//-v--- SD ------
File theFile; String line;
//-^--- SD ------

void setup() {
  Ethernet.begin(MyMac, MyIp, Dns, Gateway, Subnet);
  SD.begin(4);
  bool test = TrySend();
}

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

}

bool TrySend(){

  //*-v---- What I am trying ---
  bool SuccessOrNot;

  if(client.connect(ServerChar, 25)){
    SuccessOrNot = true;
    theFile = SD.open("Smtp.txt");   //Smtp.txt is listed toward the bottom of the code

    if(theFile){
      while(theFile.available()){
        client.write( theFile.read() );
      }
      theFile.close();
    }
  }

  else{ SuccessOrNot = false; }
  return SuccessOrNot;
  //-^---- What I am trying --- */

  /*-v-- The following works if used in place of [What I am trying] ---
  bool SuccessOrNot;

  if(client.connect(ServerChar, 25)){
    SuccessOrNot = true;
    client.println("EHLO ktlan");
    client.println("AUTH LOGIN");
    //-v- Most SMTP servers require verification in the form of base64-encoded username and base64-encoded password. However, since your IP must be whitelisted by the SMTP server, you don't need authentication
    //client.println("ThisIsInBase64"); // Encoded version of 'sender@blah.blah'
    //client.println("ThisIsInBase64"); // Encoded version of the password
    //-^-
    client.println("MAIL FROM:<sender@blah.blah>");
    client.println("RCPT TO:<receiver@blah.blah>");
    client.println("DATA");
    client.println("to:receiver@blah.blah");
    client.println("from:sender@blah.blah");
    client.print("SUBJECT: TRIGGER");
    client.println();
    client.println("The temperature Monitor Triggered.");
    client.println(".");
    client.println("QUIT");
  }
  else{ SuccessOrNot = false; }

  //-^-- The following works if used in place of [What I am trying] ---*/
}

/*-v--- Smtp.txt -------
EHLO ktlan
AUTH LOGIN
MAIL FROM:<sender@blah.blah>
RCPT TO:<receiver@blah.blah>
DATA
to:receiver@blah.blah
from:sender@blah.blah
SUBJECT: TRIGGER

The temperature Monitor Triggered.
.
QUIT

//-^--- Smtp.txt -------*/

// NO NEED for authentication. For many Smtp servers you need:
//client.println("ThisIsInBase64"); // Encoded version of 'sender@blah.blah'
//client.println("ThisIsInBase64"); // Encoded version of the password
// My IP must be whitelisted by the SMTP server, and since it is, I don't need authentication

It would be very useful to also see the SMTP Server side of things (logs), if you have access to it. Also, you do not wait for any replies from the server so there's no way to determine when the server's ready for your next command.

You're reading and writing a byte at a time, which might not be optimal. Try and do that in larger chunks (SD page size if you have enough memory)

Many email servers will refuse to serve to a client that sends EHLO before it's sent its identification banner.

Thank all. Added a "ReadClient()", it works []. Tried readStringUntil(), print line by line, works [], tried not returning bool, works (!?) ... revert back to original code, works []. I say [] because when re-upload the code, email sends, but won't send another when reset-buttoned & won't send if re-uploaded with serial monitor active. Was 1 time in troubleshooting it worked fully & I saw output of client on serial monitor & email each reset. Couldn't replicate. Sorry for unclarity: since I claim unrepeatable results I should post [lengthy] instructions. I'll reinstall & if persists do so.

Try a simpler approach (with some code refactoring)
bool TrySend(){

  if(client.connect(ServerChar, 25)){
    theFile = SD.open("Smtp.txt");

    if(theFile){
      while(theFile.available()){
        client.print(theFile.readStringUntil('\n'));
        client.print('\n');
      }
      theFile.close();
      return true;
    }
  }
  return false;
}

As a side note, you might want to consider some better code structure (e.g. local variables). But I assume this is just a sample/test. Also, the code above assumes the file uses \r\n at the end of each line. If it only has \n, then you can simply use: client.println(theFile.readStringUntil('\n')); (notice the print*ln*).
println sends both \r\n.


text:
Arduino with interrupts enters in a locking state
I am quite noobish with using the interrupts on Arduino and I am facing a strange problem. I am using an Arduino Pro Mini, a light sensor and an RTC module(DS3231) which has set 2 alarms, one at sunrise and one at the sunset. Each time the DST triggers the alarm, the interrupt routine (here onAlarm()) blocks the state of Arduino and nothing happens form there. Is there anything wrong with the code I write?
The code bellow is a little bit simplified, I just let the method calls, not the whole declarations of them.
#include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes
#include <avr/power.h>
#include <DS3232RTC.h>  //RTC Library https://github.com/JChristensen/DS3232RTC

#define ldrInterruptPin  2
#define DS2331interruptPin 3

void setup() {

  Serial.begin(9600);//Start Serial Comunication
  Wire.begin();

  //_____________________setup DS3231 interrupts_________
  pinMode(DS2331interruptPin, INPUT_PULLUP);
  digitalWrite(DS2331interruptPin, HIGH);
  attachInterrupt(digitalPinToInterrupt(DS2331interruptPin), onAlarm, FALLING);

  //_____________________setup LD235R interrupts_________
  pinMode(ldrInterruptPin, INPUT);
  digitalWrite(ldrInterruptPin, HIGH);
  attachInterrupt(digitalPinToInterrupt(ldrInterruptPin), irq1, RISING);

  resetDS3231Alarms();

  time_t t = RTC.get();
  setUpAlarms();
}

void loop() {
 //read the light sensor vlaues
}

Adn this is the onAlarm function:
  void onAlarm() {
  Serial.println("ALARM");
  formatTime(timestamp, RTC.get());
  if (RTC.alarm(ALARM_1))
  {
    Serial << F("SLEEP alarm at ") << timestamp << endl;
    goToSleep();
  }
  else if (RTC.alarm(ALARM_2))
  {
    Serial << F("WakeUP Alarm at ") << timestamp << endl;

    Serial.println("Time to Wake up......!");
    sleep_disable();
    Serial.println("I woke up!!!");
    attachInterrupt(digitalPinToInterrupt(ldrInterruptPin), irq1, RISING);
  }
  //update the sleep and wakeup times based on curreent day
  setUpAlarms();
};

resetAlarms()
void resetDS3231Alarms() {
  // initialize the alarms to known values, clear the alarm flags, clear the alarm interrupt flags
  RTC.setAlarm(ALM1_MATCH_DATE, 0, 0, 0, 1);
  RTC.setAlarm(ALM2_MATCH_DATE, 0, 0, 0, 1);
  RTC.alarm(ALARM_1);
  RTC.alarm(ALARM_2);
  RTC.alarmInterrupt(ALARM_1, false);
  RTC.alarmInterrupt(ALARM_2, false);
  RTC.squareWave(SQWAVE_NONE);
}

Every time an alarm occurs, the code blocks and outputs exactly what is in the serial monitor capture bellow:
It just prints "AL" form the Serial.println("ALARM"); and nothing happens from there

Does anyone know what causes this issue and how can it be solved?

Never use Serial in an interrupt. It itself relies on an interrupt, which can't happen because your interrupt is the one running.

I removed all the Serial prints and the issue is still present. Nothing in the onAlarm() method is run and the code freezes

You may be calling a function that itself calls delay(). That will also break.  Interrupts should be the absolute minimum you can get away with - ideally just set a flag then examine that flag in loop() to do your actual work. The interrupt captures the event, but doesn't do the work.

When the AVR processor goes to sleep, the only way it can wake up is
by an interrupt. If it goes to sleep with interrupts disabled, then it
will never wake up.
Interrupt routines are by default non-interruptible: the first thing the
processor does when servicing an interrupt is to disable further
interrupts. Your onAlarm() function is thus running with interrupts
disabled. If it goes to sleep, it will lock the processor.
A quick and dirty fix would be to call interrupts() right before going
to sleep. I would not recommend that though, as you will end up piling
interrupt contexts one over another. The proper fix would be to trim
down your interrupt  service routines to the bare minimum that must be
done immediately, and handle everything else in regular code, within
loop(). In this particular case, setting a volatile bool might well
be the only thing you really need to do. Your loop() would test that
bool and take care of everything else.

Thaks, it works with both of the options you gave, but I chose the one with the bool


text:
ATTiny85 PWM on PB2 not working - only on/off, no fade
I have a custom ATTiny85 PCB with LEDs connected to GPIOs (PB0-4) through current-limiting resistors. All ports fade LEDs smoothly except PB2, which only switches on/off with no intermediate states.
The circuit is identical for all LEDs, ruling out hardware issues. I suspect this is related to PB2's specific capabilities.
#define pin PB1

void setup() {
  pinMode(pin, OUTPUT);
}

void loop() {
  for(int i = 0; i < 256; i++) {
    analogWrite(pin, i);
    delay(10);
  }
  for(int i = 255; i >= 0; i--) {
    analogWrite(pin, i);
    delay(10);
  }
}

MCU: ATTiny85
IDE: Arduino
All LEDs use identical circuits
Other ports (PB0,1,3,4) fade normally

Is there something specific about PB2 that requires different configuration for PWM functionality? How can I enable proper fading on this pin?

Have a look at the datasheet of the ATtiny85. Figure 11-5 shows how the Timers work when in Output Compare mode (which is the one used for PWM).

The wave generator on the bottom connects to the OCnx pins. So only pins marked this way can be used for hardware PWM. Now you can look at the pinout diagram at the start (Figure 1-1):

You see, PB2 doesn't have the OCnx marking. All other pins (besides Vcc, ground and reset) have it. So you cannot use this pin with hardware PWM.
If you really need PWM on that pin, you need to bit-bang it via software, so writing the pin directly in your code. If this fits for you depends on your code and what you want to do with it.

Also note, that you cannot generate hardware PWM signals with different duty cycles on PB3 and PB4, as one is the inverted signal of the other. May be relevant to you, if you wanted to use both these pins for PWM.

It's funny you mention PB3 - I just noticed it's also behaving in a binary fashion. PB4 is fine though. Thank you for your comment. I'll likely leave things as is.

PB3 has inverted output (/OC1B) of PB4 (OC1B), you can get the signal there, but not by using arduino's analogWrite and it'll be just inverted PB4 (that's why it's skipped in analogWrite)


text:
Sketch skipping the OPEN Arduino inputs
Folks,
I am a beginner to Arduino. I have a sketch that tests a set of INPUTS for HIGH or LOW by using a 'for' loop. When the for loop reaches an INPUT which is kept OPEN (no wires connected to it), the for loop apparently 'skips' that INPUT and move on to the next. However, if I have +5V connected to any INPUTS within the range of the for loop, it works correctly. Any thoughts what's is happening here?

probably bad programming ... the arduino will do exactly what you tell it to do, so you are giving it incorrect instructions

You can edit your code into the question if you want to try for a more a specific answer.

You should always connect something to an input to pull it high or low when no signal is present.  The simplest thing is to activate the built-in pullup resistor, which will result in the input returning HIGH when there is nothing connected.  If that's not compatible with your particular use, add a resistor from the input to ground (10k-100k is fine) so that it will return LOW when nothing else is connected.  If the input is just floating, it is susceptible to noise causing random state changes. The input impedance is very high (100 Meg) so it can pick up static and other mischief.

Thanks a lot. I'll avoid floating inputs.


text:
Is this a feasible circuit?
The last couple months I’ve been working on this project, I’m nearing its end and I’m getting really excited!  However, this is still pretty new to me and so I was hoping my electrical diagram/accumulated knowledge could be verified before I go and start spending money on parts.  All criticism is welcome as are any additional resources.
Thank you in advance!

Logic:
Arduino setup:
Arduino pins (aside from the power section) at the bottom are capable of outputting up to 40mA at most and when using multiple pins, no more than 200 mA should ever be drawn at once
Piezo buzzers are the only electrical component that do not need resistors
This was taken directly from How To Mechatronics, attaching a 330 Ohm resistor to the LED strip lowers its electrical noise
The other resistor attached to the LED strip should be 25 ohms, seeing as I don’t have one though I will be using a 27-ohm resistor instead.  Where 5 LED’s on the strip should take up 300mA (each GRB uses 20mA and I’m using 5 in total, therefore 20 x 3 x 5 = 300).  Using Ohms law R = V/I, therefore R = 7.5/0.3, therefore R = 25.
**I would like to add that I also looked at Watt’s law and was a big confused as I got a current of 200 mA instead (as the LED’s each use between 0.1 – 0.3 Watts, therefore I = W/V, therefore I = 1.5/7.5, therefore I = 0.2)  I went with the 27 ohms instead of the 37.5 ohms watts law gave me instead because How To Mechatronics really seemed to know what was up
I chose to power the board via the 7.5V, 1A adapter mostly because I wanted its voltage-in to be regulated and seeing as it won’t be plugged into a computer, I thought USB was a bit sketch and it made more sense to use the power port as opposed to the Vin pin.
Motor setup:
The motor was chosen based off of my need for high torque – the door handle I am trying to push requires 5 pounds (raised to 6 pounds for extra breathing room) and the entire handle is 4.5 inches (lowered to 3 inches for breathing room) in length (the measurements were provided by a friend as I wont be home for a little bit, might seem a bit overkill but its just cause I don’t think they are entirely accurate in the first place).  Using these measurements and the equation Torque = length x Force I got the required torque had to be greater than 0.3572kg/cm to open my door.  Knowing this I took a look at a bunch of Nema stepper motors and chose one capable of producing that torque (based off of its holding torque) that was the lightest and smallest.  I wanted something light as I am still unsure how I will be mounting this to my door…
Originally, I was going to use the L298N but seeing as how using the 5V pin off the Arduino is not recommended for powering it and that they generally don’t dissipate heat that well for their motors I decided not to
Lastly, the 12V 4A power supply was chosen because I needed something stronger than 9V and I wanted to save money.  Seeing as I would have the 0.5A - 0.7A current option selected (to my knowledge anything more could cause damage unlike with the Arduino, extra current is not necessarily a bad thing in this case) it’s a bit overkill.  I’m thinking it shouldn’t cause any thermal limiting though seeing as it is rated to 4A and its not as if my motor will be going that often anyways :)
Links (all links except for the motor which goes to pololu redirect to amazon):
7.5V 1A Power supply:
https://www.amazon.ca/Belker-Adjustable-Universal-Household-Electronics/dp/B07NKZCWT1/ref=cm_cr_arp_d_product_top?ie=UTF8
12V 4A power supply:
https://www.amazon.ca/COOLM-Adapter-100-240V-Doorbell-5-5X2-5MM/dp/B07H2T31JJ/ref=sr_1_6?dchild=1&keywords=10V+4A+POWER+SUPPLY&qid=1606959202&s=hi&sr=1-6
KEYESTUDIO W5500 Ethernet Arduino (Uno):
https://www.amazon.ca/gp/product/B079G4WDGW/ref=ppx_yo_dt_b_asin_title_o03_s00?ie=UTF8&th=1
NEMA 14 stepper motor (2.7V, 1 A/Phase):
https://www.pololu.com/product/1209
TB6600 stepper motor driver:
https://www.amazon.ca/TB6600-Stepper-Driver-Controller-tb6600/dp/B07B9ZQF5D/ref=asc_df_B07B9ZQF5D/?tag=googleshopc0c-20&linkCode=df0&hvadid=292963865944&hvpos=&hvnetw=g&hvrand=11283888445696292979&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9001232&hvtargid=pla-524548131497&psc=1
LED strip (WS2812B):
https://www.amazon.ca/gp/product/B01CDTED80/ref=ppx_yo_dt_b_asin_title_o06_s00?ie=UTF8&psc=1

what is the purpose of the device?

its a door unlocker :) gona set it up inside my apartment, the LEDs creates a colour code to be entered on a website I built, the speaker is to give me a minute heads up and the motor will pull a string to unlock the door

interesting ... the color code authentication is very clever

The 330 Ohms resistor does not lower any noise. It is not necessary. 2. The LED strip (WS2812B) can be powered by the Arduinos power pin. I would prefer an external power source, avoiding an overload of the Arduinos power regulator. It has no cooling and if you draw 500 mA it has to dissipate (7.5-5)*0.5 = 1.25 Watts. (It'll get really hot ;-) ) You could build an external regulator with an 7805 or LM317 or use a 5 Volt Power Supply. 3. If the color code is entered into Website, how does the Website communicate with the Arduino to control the motor? Have I misunderstood the setup?

Get a 5V power supply instead of the 7.5V. Get one with a  micro-USB plug. They are probably cheaper than the one you picked. Secondly; ohms law doesn't apply to WS2812 leds, as the regulate the current themselves. Thirdly, some buzzers require a transistor to drive, as some exceed the maximum current of an Arduino pin. Fourthly; it seems like a stepper motor is a bit of overkill for the application you're describing. I was thinking about maybe using a solenoid or one of the beefier hobby servos. But it kind of depends on how much force is required to unlock the door.

@Gerben Thank you so much as well :)  I really appreciate your help!  I dont know why I didnt think about getting a micro USB plug haha I'll definately go with that :) I have a lot of projects in mind  after this one so 2 & 3 will really help with those :)

Wow, that's a lot of work. I'm impressed. I can not help myself, but: ;-) In the Arduino code line 141 you increment the posi variable. Is this really necessary? You did inc. it already in the last line of the while loop. I'm really busy at the moment, so perhaps I'll have a look at it during the weekend.

@PeterPaulKiefer omg... thank you!  I haven't tested it yet but I'm sure that would've taken so long to debug!  I totally see what you mean :)  sounds good hoping to branch off of it too later in the future its been a big project and I've learned a lot since starting :)

Let's take a look at the LEDs.  Different kinds of LEDs have different forward voltage requirements. Non-bright LEDs tend to require less voltage than bright LEDs, since bright LEDs need more power to work. Typical VLED values are 1.7V for non-high-brightness red, 1.9V for high-brightness high-efficiency low-current red, 2V for orange and yellow, 2.1V for green, and 3.4 to 3.6V for bright white and most blue types.
In order to make sure that this voltage gets dropped across the LED, you should use a voltage greater than the LED's forward voltage. Use at least 3V supply voltage for lower-voltage LEDs and 4.5V for 3.4V types. Also add a resistor in series with the LED to limit excess current from burning out the LED, usually so that the current flowing through the LED is about 10mA. Make sure that the current doesn't exceed the maximum current specified on the LED's datasheet. You have 5 LEDs in series with (assuming keeps the math simple) a Vf of 2 Volts, therefore you need 5*2 (they add) or 10 volts to get them to light then a little more (2 volts) so you can control the current with a resistor. At this point you have 5 volts trying to push current through a 10V device circuit, nothing will happen. Using 12 volts and Ohm's law a 200 Ohm resistor will give you about 10 mA, a safe current for most LEDS. If you want them light replace the 27 Ohm with a 200 Ohm and connect to the +12V inplace of the 5V pin. Note LEDs do not work well in parallel unless the current is controlled in each LED or LED string. This is based on your schematic showing 5 LEDs powered by a 5V source.

The LEDs in the question are addressable LEDs that take care of their own current regulation. Your answer is not relevant to those.

An led's forward voltage does not depend on the power rating, all leds (of certain color) have the same forward drop (more or less, slight differences between manufacturers/materials). Power leds instead are driven at higher currents.

Take a look at a LUXEON 5050 It needs about 22V at 25mA and about 25V at 200mA.  Then there is the Violet Indium gallium which has a Vf range of 2.8 to 4 volts or Green which is 1.9 to 4 volts, over 200% Delta. Try this link: https://www.circuitbread.com/ee-faq/the-forward-voltages-of-different-leds The Vf is determined by the chemestry used and the process. LEDs also make great substitutes for low voltage zeners, just keep the current down, try it.


text:
Arduino LCD only display image for few second and turn screen to white
I have a problem with my Arduino and LCD touch screen. I create a few functional button in my Arduino. One of the button is START button. Right now, I want the image is display when I touch START button but the problem is when i touch the START button, the image is display only few second and turn to white screen. How can I solve this problem. Need someone help regarding on this simple issue. Here I attach my code.
page_testing_v2.ino
#include <Elegoo_GFX.h>                   // Core graphics library
#include <Elegoo_TFTLCD.h>                // Hardware-specific library
#include <TouchScreen.h>                  // Touch Support

#define TS_MINX 903
#define TS_MINY 914
#define TS_MAXX 90
#define TS_MAXY 108
#define YP A3                             // must be an analog pin, use "An" notation!
#define XM A2                             // must be an analog pin, use "An" notation!
#define YM 9                              // can be a digital pin
#define XP 8                              // can be a digital pin

TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

// macros for color (16 bit)
#define BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF
#define GREY    0xD6BA
#define TURQUOISE 0x448E
#define GREENEON  0x67E9
#define PURPLE    0x7018
#define LILAC     0xAC38

#define LCD_CS A3                         // Chip Select goes to Analog 3
#define LCD_CD A2                         // Command/Data goes to Analog 2
#define LCD_WR A1                         // LCD Write goes to Analog 1
#define LCD_RD A0                         // LCD Read goes to Analog 0
#define LCD_RESET A4                      // Can alternately just connect to Arduino's reset pin

Elegoo_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);

#define MINPRESSURE 10
#define MAXPRESSURE 1000

extern uint8_t tankIcon[];

boolean button1 = true;
int touch = 0;

char currentPage, selectedUnit;

const int led1 = 51;
const int led2 = 53;

int led1State = LOW;
int led2State = LOW;

unsigned long previous = 0;

unsigned long current = 0;
long elapsed = current - previous;

long cycle = 10000;

//Start the system sequence
void startSystem(){
  current = millis();
  elapsed = current - previous;

  if (elapsed >= cycle){  // this if statement resets the cycle timer
    previous = current;
    //previous = previous + cycle;
  }
  if (elapsed > 500 && elapsed < 5000){
    led1State = LOW;
    led2State = HIGH;
  }
  if (elapsed > 5500 && elapsed < 10000){
    led2State = LOW;
    led1State = HIGH;
  }
//
//  else
//  {
//    led2State = HIGH;
//    led1State = HIGH;
//  }

    // set the LED with the ledState of the variable:
    digitalWrite(led1, led1State);
    digitalWrite(led2, led2State);
}

void stopSystem(){
  current = millis();
  elapsed = current - previous;

  if(elapsed >= cycle)  // this if statement resets the cycle timer
    //previous = current;
    previous = previous + cycle;

    if (elapsed > 1000 && elapsed < 19999){
      led1State = LOW;
      led2State = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(led1, led1State);
    digitalWrite(led2, led2State);

    return millis() - current;
}

void drawHomeScreen(){
  tft.fillScreen(BLACK);                  // Black Background
  //Draw white frame
  tft.drawRect(0,0,319,240,WHITE);
   //Title at home screen
  tft.setCursor(25,5);
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("Compressed Air System");
   //Draw line under title
  tft.drawLine(0,30,320,30,WHITE);
  //Add text with frame 'SYSTEM'
  tft.setCursor(10,35);
  tft.setTextColor(YELLOW);
  tft.setTextSize(2);
  tft.print("SYSTEM");
   //Add START button
  tft.fillRect(95,38,105,70,GREEN);
  tft.drawRect(95,38,105,70,WHITE);
  tft.setCursor(115,55);
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("START");
   //Add PAUSE button
   //Add RESUME button
   //Add E-STOP button (to shut down the whole system if anything happens)
  tft.fillRect(205,38,105,70,RED);
  tft.drawRect(205,38,105,70,WHITE);
  tft.setCursor(230,55);
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("STOP");
    //Draw line
  tft.drawLine(0,115,320,115,WHITE);
   //Add text with frame 'MANUAL'
  tft.setCursor(10,120);
  tft.setTextColor(YELLOW);
  tft.setTextSize(2);
  tft.print("MANUAL");
   //Add text with frame 'COMPRESSOR 1'
  tft.setCursor(40,140);
  tft.setTextColor(MAGENTA);
  tft.setTextSize(1);
  tft.print("Compressor 1");
   //Add ON/OFF button
  tft.fillRect(0,150,80,75,GREEN);
  tft.drawRect(0,150,80,75,WHITE);
  tft.setCursor(25,180);
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("ON");

  tft.fillRect(80,150,80,75,RED);
  tft.drawRect(80,150,80,75,WHITE);
  tft.setCursor(100,180);
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("OFF");

    //Draw line
  tft.drawLine(160,115,160,240,WHITE);

   //Add text with frame 'COMPRESSOR 2'
  tft.setCursor(200,140);
  tft.setTextColor(MAGENTA);
  tft.setTextSize(1);
  tft.print("Compressor 2");

   //Add ON/OFF button
  tft.fillRect(160,150,80,75,GREEN);
  tft.drawRect(160,150,80,75,WHITE);
  tft.setCursor(185,180);
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("ON");

  tft.fillRect(240,150,80,75,RED);
  tft.drawRect(240,150,80,75,WHITE);
  tft.setCursor(260,180);
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("OFF");

}

void setup() {
  Serial.begin(9600);
  tft.reset();                            // Reset LCD
  tft.begin(0x9341);                      // Initialise LCD
  tft.setRotation(3);

  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);

  drawHomeScreen();

}

void loop() {
    TSPoint p = ts.getPoint();
    if (p.z > ts.pressureThreshhold) {
      p.x = map(p.x, TS_MAXX, TS_MINX, 0, 240);
      p.y = map(p.y, TS_MAXY, TS_MINY, 0, 320);
      pinMode(XM, OUTPUT);
      pinMode(YP, OUTPUT);
      Serial.print("("); Serial.print(p.x);
      Serial.print(", "); Serial.print(p.y);
      Serial.println(")");
//    if (p.z > MINPRESSURE && p.z < MAXPRESSURE) {
//      p.x = map(p.x, TS_MINX, TS_MAXX, tft.width(), 0);
//      p.y = map(p.y, TS_MINY, TS_MAXY, tft.height(), 0);

    //start button
    if (p.x > 38 && p.x < 108){
      if(p.y > 95 && p.y < 200) {
        touch = 1;
        }
     }

    //stop button
    if (p.x > 38 && p.x < 108){
      if(p.y > 205 && p.y < 310){
        touch = 2;
        }
      }

    //C1 ON button
    if (p.x > 150 && p.x < 225){
      if(p.y > 0 && p.y < 80){
        touch = 3;
        }
      }

    //C1 OFF button
    if (p.x > 150 && p.x < 225){
      if(p.y > 80 && p.y < 160){
        touch = 4;
        }
      }

    //C2 ON button
    if (p.x > 150 && p.x < 225){
      if(p.y > 160 && p.y < 240){
        touch = 5;
        }
      }

    //C2 OFF button
    if (p.x > 150 && p.x < 225){
      if(p.y > 240 && p.y < 320){
        touch = 6;
        }
      }

    //home button
    if (p.x > 10 && p.x < 40){
      if(p.y > 10 && p.y < 40){
        touch = 7;
        }
      }
  }
  if (touch == 1){
    tft.fillScreen(BLACK);
    tft.drawBitmap(200, 45, tankIcon, 120, 116,GREEN);
    tft.fillRect(10,10,30,30,GREEN);
    tft.drawRect(10,10,30,30,RED);
    tft.setCursor(120,160);
    tft.setTextColor(WHITE);
    tft.setTextSize(2);
    tft.print("Button 1");
    startSystem();
    //touch = 0;

    //return millis() - screen;
    }

  if (touch == 2){
//    tft.fillScreen(BLACK);
//    tft.setCursor(120,160);
//    tft.setTextColor(WHITE);
//    tft.setTextSize(2);
//    tft.print("Button 2");
//    touch = 0;
    stopSystem();
    }

  if (touch == 3){
//    tft.fillScreen(BLACK);
//    tft.setCursor(120,160);
//    tft.setTextColor(WHITE);
//    tft.setTextSize(2);
//    tft.print("Button 3");
//    touch = 0;
    digitalWrite(led1,HIGH);
    //touch = 0;

    }

  if (touch == 4){
//    tft.fillScreen(BLACK);
//    tft.setCursor(120,160);
//    tft.setTextColor(WHITE);
//    tft.setTextSize(2);
//    tft.print("Button 4");
//    touch = 0;
    digitalWrite(led1,LOW);
    touch = 0;

    }

  if (touch == 5){
//    tft.fillScreen(BLACK);
//    tft.setCursor(120,160);
//    tft.setTextColor(WHITE);
//    tft.setTextSize(2);
//    tft.print("Button 5");
//    touch = 0;
    digitalWrite(led2,HIGH);
    touch = 0;
    }

  if (touch == 6){
//    tft.fillScreen(BLACK);
//    tft.setCursor(120,160);
//    tft.setTextColor(WHITE);
//    tft.setTextSize(2);
//    tft.print("Button 6");
//    touch = 0;
    digitalWrite(led2,LOW);
    touch = 0;
    }
  if (touch == 7){
    drawHomeScreen();
    touch = 0;
  }
}

void drawBitmap(int16_t x, int16_t y,const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color) {
  int16_t i, j, byteWidth = (w + 7) / 8;
  uint8_t byte;
  for(j=0; j<h; j++) {
    for(i=0; i<w; i++) {
      if(i & 7) byte <<= 1;
      else      byte   = pgm_read_byte(bitmap + j * byteWidth + i / 8);
      if(byte & 0x80) tft.drawPixel(x+i, y+j, color);
    }
  }
}

  /*TSPoint p = ts.getPoint();
  boolean led_state = false;
  if (p.z > 10 && p.z < 1000)             // Check touch validity
  {
    p.x = map(p.x, TS_MINX, TS_MAXX, tft.width(), 0);
    p.y = map(p.y, TS_MINY, TS_MAXY, tft.height(), 0);
    if (p.x > 0 && p.x < 240)
    {
      if (p.y > 0 && p.y < 160)
      {
        led_state = true;                 // Touched in Green rectangle
      }
      else if (p.y > 160 && p.y < 320)
      {
        led_state = false;                // Touched in RED rectangle
      }
    }
    Serial.print("LED State ");
    Serial.println(led_state);            // Print the status of the LED
  }
  delay (100);*/

systemImages.c
#include <avr/pgmspace.h>
// 'tankIcon', 120x116px
const unsigned char tankIcon [] PROGMEM = {
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xf8, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x03, 0xfe, 0xf1, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x03, 0xff, 0xe0, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x03, 0xff, 0xe0, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x03, 0xff, 0xe1, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x03, 0xf8, 0xfb, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f,
    0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xc0, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xf0, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff, 0xfc, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x01, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x01, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
    0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
    0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff,
    0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff,
    0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
    0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
    0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff,
    0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff,
    0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
    0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
    0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff,
    0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff,
    0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
    0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
    0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff,
    0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff,
    0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

Your question is probably more related to processing button presses and the LCD drawing code is presents an obstacle to someone here trying to help you.  If you're able to ask the same question with code that compiles, runs, demonstrates the same problem, but without the LCD drawing code, you're more likely to get useful responses.

The question is tagged with all three of arduino-uno, arduino-mega, and arduino-due.  Why is that?


text:
Connect RGB LED board to Arduino?
I'm trying to repurpose an RGB LED (pictured) and use an Arduino board I've just gotten to reprogram the lights. I'm very new to electronics engineering and I don't really know how to get started. How would I connect it to the Arduino? What kind of wire(s) would be best for soldering this to as well as connecting to the Arduino? Can this be programmed like any other LED?
Images:
https://i.sstatic.net/u14Bd.jpg
https://i.sstatic.net/2inQB.jpg

that is not an RGB LED ... it is three separate LEDs ... Vdd would probably connect to positive voltage ... one of the other pins would connect to a resistor, which would connect to ground ... circuits are plentiful on the web

Connect each of the 3 "L" wires to 3 separate digital IO pins of an arduino e.g. D8, D9, D10 via a resistor say 470 ohms but the value is not too critical. Connect VDD to the arduino +5v.
Use the arduino IDE write a sketch that configures pins 8 9 and 10 as outputs and then see what happens when you send these pins HIGH or LOW. Theres lots more you can do. Good luck.

Ah that makes sense! I thought the VDD was for ground. Thanks so much!

Given that the pin is labeled VDD, it's likely that the LEDs are common anode. (You'd hook the VDD pin to a positive voltage, and then connect the other pins to ground in order to light them.)
You really need to know the specs of the LEDs in order to calculate the size of the current limiting resistors.
Say your LEDs have a 1.2v forward voltage and can take 20 mA of current (.02 amps)
You'd use the formula R = (supply_voltage - LED_voltage)/current
so R = (5-1.2)/.020  = 190 Ω. Use the next higher value. (220 Ω for 20% resistors, the cheapest/most common kind you're likely to have access to.)
Try hooking each of the LEDs through a 220 Ω resistor to ground and seeing what you get. (Note that different colors of LEDs can have different forward voltages, so the forward voltage you use in the above calculation might be different for each LED.) If it barely lights, move down to the next-lower resistor value and try again. (150 Ω for 20% resistors.) If it's crazy-bright, or gets warm to the touch, use the next higher resistor value.
You'd then control the LEDs using PWM pins on your Arduino, and vary the duty cycle on 3 different output pins to vary the apparent brightness of the different colored LEDs. Note that since these LEDS appear to be common anode (Common power connection, and you switch the grounds to turn them on and off) the PWM values will be reversed. Setting a PWM pin to 0 will make that LED burn the brightest, and setting it to 255 will turn it off. That's because at 0, the pin is at 5V 0% of the time and connected to ground (which lights it) 100% of the time.


text:
Remove a sudden pulse on pin d3 of nodemcu when powering it up
I am using node mcu and a 2 channel relay connected to the motor via pin d3.
When I power on the circuit, it shoots a pulse to the relay and i think it will damage the motor.
Please suggest me how to stop that pulse from turning on the motor.

Please share how you have the relay connected to your NodeMCU.  A schematic drawing would be very helpful.

Just use a different pin. Pins D1, D2, D5, D6 and D7 (GPIO's 5, 4, 14, 12, 13) are safe to use with a relay on a NodeMCU.

D3 is GPIO0, which is used as an active low input to signal the ESP8266 bootloader to expect programming after a reset.
Use a different pin.

all esp8266 io pins are pulled up at boot

@Juraj, If that were true, and I'm not sure that it is, it's a non sequitur.  I'm curious as to why you bothered leaving this on a closed question.

pins 4+5 are the only "silent" pins on bootup


text:
Unable to compile c++11 libraries despite having added -std=c++11 in platform.txt
I want to use c++ data structures such as vectors, arrays, map... in my Arduino sketch. I made sure to add -std=c++11 and -std=gnu++11 in platform.txt, I am still getting the following error message:

fatal error: unordered_map: No such file or directory
#include <unordered_map> compilation terminated. exit status 1 unordered_map: No such file or directory

Here's a snapshot from ~/arduino-nightly/hardware/arduino/avr/platform.txt:

Versions:

Arduino ide: 1.8.14
g++: 5.4.0
avr-g++: 4.9.2

What else should I set up?

The AVR-based Arduinos don't come with anything close to a full C++ standard library implementation.  They have avr-libc which is fairly complete to at least the C99 standard, that is the C standard from 1999, not C++.  What you're doing with -std=c++11 is influencing the standard used by the compiler to interpret the C++ language itself.  This does work fine on AVR based Arduinos, but is not going to give you the sort of C++ containers you may be used to on a desktop or larger embedded system, like an ESP8266.
Much of the C++ standard library would be completely out of place on an AVR based Arduino, particularly those parts that make use of dynamic allocation like unordered_map in your error message.
There are some parts of the C++ library implemented via Arduino STL.  Whether or not you should be using containers from it is another question.
If you do try to use Arduino STL, I'd encourage you to use more conservative parts of it.  Something like an unordered_map, but with less (or no) dynamic allocation could be implemented by using Arduino STL's std::array and functions from its <algorithm> header, like their std::find or std::lower_bound, etc.  Trying to use a C++ map or vector container or something of that sort is kind of asking for trouble, more so on the more common AVR-based Arduinos with only roughly 2 Kbyte of RAM.

Thanks for the answer. Could you show me a way to use std::array in arduino (I am having trouble #including)


text:
How to wire and control a 16mm button with 2 legs using arduino?
I can't find any tutorials online explaining how to wire and control a 16mm push button like the one in the picture:

Do  you have any suggestions as to how use it with an arduino or a raspberry pi?

Just look up any tutorial on a button. For the arduino, it doesn't make a difference whether they're 1mm or 100mm wide.

https://www.arduino.cc/en/Tutorial/BuiltInExamples/InputPullupSerial

it's just a switch ... pressing the button connects the two wires together electrically

One might suggest that a button is not controlled by an arduino. The button is an input device to control the action of the board's programming. It is to be used on digital inputs (on/off) and usually with a debounce routine.

@fred_dot_u One could argue that it is controlled digitally though....

I had forgotten the proctologist option

I suggest you look at the Bounce2 library, which can handle debouncing for you.

A pushbutton is a pushbutton. It is a momentary switch. Since it has flexible wires, and needs a place to mount, you should probably wire it using a breadboard.
That pushbutton looks like a panel mount pushbutton. You might want to mount it in a pice of plastic or sheet metal. (Unscrew that nut up by the red part that you press. Measure the outside diameter of the threaded part. Drill a hole ≈1/64" (≈0.4MM) bigger than the switch diameter into the plastic/metal. Insert the pushbutton from underneath the panel. screw the nut back on to secure it. Tighten moderately tight with needle-nose pliers, being careful not to round off the corners of the nut.
To wire it:
Get a breadboard. Run wires from your Arduino to the breadboard.
Wire the pushbutton into the breadboard as well.
There are various libraries that offer switch debouncing, or you can write your own fairly easily.
I suggest using INPUT_PULLUP mode, and wiring your switch between an Arduino digital input and ground. When the switch is open, the input will read HIGH. When you press the the switch, the input will drop to LOW.
If you want to debounce the switch input yourself: When the switch changes state, note the value of millis(), and ignore any new changes for a brief period (try 20-100 mS).


text:
Powering a NodeMCU as well as a GSM module
I'm trying to connect a GSM module(sim800L) with a NodeMCU to execute remote operations. But the GSM module cannot be powered using the NodeMCU. So, what are the other ways to power the board as well as the module. Also I want to connect directly to a wall power supply instead of using a battery.

connect them to the supply in parallel.

So, I would have to use a 5V 2A power adapter and then connect the devices in parallel to it. Right?

Check if your SIM800L can actually take 5V. If so, then you can connect both in parallel.

the sim800l module operates between 3.7 to 4.7 V

After a bit of researching, I have found the following solution:-
A DC-DC buck converter (such as the LM2596) can convert a 12 V 2A rated power supply down to 4 V (the value is adjustable) which can then be used to power the module.


text:
L298 Motor Driver not showing Red light when connecting power supply
I recently bought an L298 motor driver module for controlling 2 motors(5v each).
When i connect the power supply(which is a normal RC car battery holder(3)) the red light doesn't light up.
Instead if i connect the +ve to the 5v on the motor driver, the red light is glowing, but the motors don't work.

you accepted an answer that is not quite correct ... the reason that motors do not run is that the L298 is technology from last century and is very inefficient ... your power supply needs to be a bit higher than 7 V if your motor requires 5 V ... the L298 uses up a couple of Volts

You need to do math on the power consumption as arduino uno takes takes 5 V 500 mA at least for it to work. That is why it can be powered by USB cables too.
Now if you try calculating power consumption on the motors you would understand that the power you are giving is nowhere enough for the arrangement to work or you could have been able to run the motors without the motor driver.
Try upgrading the power you are giving.

Thanks. I tweaked up the power and now its working fine.

@RiteshSharma  your answer provides incorrect information ... Arduino Uno requires a lot less current than 500 mA to operate ... please research the correct value and update your answer .... you also used incorrect units of measure, which I edited

I would definitely do the research work on that @jsotola


text:
Looking for FOTA to update firmware with wi-fi over internet (ESP32)
I have tried ArduinoOTA and AsyncElegantOTA and they work, but only when you are in the same wi-fi as ESP32.
I need to update ESP32 firmware "remotely" meaning when I'm not in the same local wi-fi network as ESP32.
Has this been done yet for Arduino?

the HTTPUpdate library bundled with the esp32 Arduino core


text:
Max. external ADC speed with ESP32 (SPI or I2C)?
What is the maximum speed for external ADC I can expect to get with ESP32? I'm planning to have 16-bit ADC connected to I2C or SPI whichever gives more speed.
How that information is calculated from information in ESP data sheet?

Depends on the ADC and what technology it uses. Instead you should be asking what would be a suitable way of sampling whatever it is you want to sample. SPI will always be faster than I2C, but neither may be the right system to use. We need more detail about what you want to achieve.

How fast do you want it, or: how fast is you adc? There are different options to interface the spi/i2c peripherals (polling, interrupt, dma).

I2S is even faster, and supported on the 32.


text:
ESP8266 print garbage output
I am working on a project at school that need using ESP8266, but when i compile and run, the code run sucessful but print nothing, when i push the reset button on the ESP8266, it print some garbage output, i tried to reset it many times but it's still the same. I had success in running the code at the first time, but when i build it again, it's just showing garbage output
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <Ticker.h> //for LED status
#include <WiFiManager.h>
#include <String.h>
#include "ThingSpeak.h"
#include <PubSubClient.h>
#include <SoftwareSerial.h>
Ticker ticker;

//MQTT - mosquitto

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

const char* mqtt_server = "broker.mqtt-dashboard.com";

unsigned long myChannelNumber = 1260973;
const char * myWriteAPIKey = "ML0AX95ICWN71XKC";
const char * myReadAPIKey = "MT8FRNAUN4GJL8F5";

//Ultra Sonic Sensor
const int trig_pin = 5;
const int echo_pin = 4;

//Light Sensor
const int light_sensor = 0;

//LED for tree
const int led_tree = 2;

//LED for remaining water
const int led_red = 14;
const int led_yellow = 12;
const int led_green = 13;

//Soil Moisture Sensor
const int soil_moisture = A0;
int Soil_Value;
int limit = 300;

//Relay
int relay_pin = 15;

float getDistance(){
  float duration, distanceCm;

  digitalWrite(trig_pin, LOW);
  delayMicroseconds(2);
  digitalWrite(trig_pin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig_pin, LOW);

  duration = pulseIn(echo_pin, HIGH);

  distanceCm = duration * 0.034 / 2;

  return distanceCm;
}

//gets called when WiFiManager enters configuration mode
void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      client.subscribe("LED_tree");
      client.subscribe("Pump_water");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  if (topic == "LED_tree"){
    if (digitalRead(led_tree) == HIGH)
      digitalWrite(led_tree, LOW);
    else
      digitalWrite(led_tree, HIGH);
    }
  else if (topic == "Pump_water") {
      Serial.println("pump_water");
    }
  }

void setup() {
  // put your setup code here, to run once:
//  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(115200);
  // Ultra Sonic Sensor
  pinMode(trig_pin, OUTPUT);
  pinMode(echo_pin, INPUT);
  // Led for tree
  pinMode(led_tree, OUTPUT);
  // Light Sensor
  pinMode(light_sensor, INPUT);
  // Relay
  pinMode(relay_pin, OUTPUT);
  //led for showing remain water
  pinMode(led_red, OUTPUT);
  pinMode(led_yellow, OUTPUT);
  pinMode(led_green, OUTPUT);
  ThingSpeak.begin(espClient);
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
  // put your setup code here, to run once:

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wm;
  //reset settings - for testing
  wm.resetSettings();

  //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  wm.setAPCallback(configModeCallback);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if (!wm.autoConnect()) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.restart();
    delay(1000);
  }

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");
}

float waterRemaining(int distance) {
  float r = 2;
  float h = 5;
  float V = 3.14*r*r*(h - distance);
  return V;
}

void loop() {
  // put your main code here, to run repeatedly:
  float distance = getDistance();
  float light = digitalRead(light_sensor);
  String light_value;
  if (light == 1){
    light_value = "The light is enough for tree";
  }
  else {
    light_value = "The light is not enough for tree, suggesting turn on the LED";
  }
  float led_status = digitalRead(led_tree);
  float soil = analogRead(soil_moisture);
  float soil_percent = map(soil, 0, 1023, 0, 100);
  float water_remain = waterRemaining(distance);

  //Write data to field
  ThingSpeak.setField(1, distance);
  ThingSpeak.setField(2, light);

  int returncode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
  // Check return Code
  if (returncode == 200) {
    Serial.println("Channel update sucessful.");
  }
  else {
    Serial.println("Problem updating channel. HTTP error code " + String(returncode));
  }

  //Read data from ThingSpeak
  float Distance2 = ThingSpeak.readIntField(myChannelNumber, 1, myReadAPIKey);
  float Light2 = ThingSpeak.readIntField(myChannelNumber, 2, myReadAPIKey);
  // LED for showing remaining water

  float h_box = 20;
  float res = h_box - distance;

  if (res < 5)
  {
    digitalWrite(led_red, HIGH);
    digitalWrite(led_yellow, LOW);
    digitalWrite(led_green, LOW);
  }
  else if (5 <= res <= 10)
  {
    digitalWrite(led_yellow, HIGH);
    digitalWrite(led_green, LOW);
    digitalWrite(led_red, LOW);
  }
  else if (res > 10)
  {
    digitalWrite(led_green, HIGH);
    digitalWrite(led_red, LOW);
    digitalWrite(led_yellow, LOW);
  }
  // Relay pump water
  if (soil_percent < 60)
  {
    digitalWrite(relay_pin, HIGH);
    delay(3000);
    digitalWrite(relay_pin, LOW);
  }

  Serial.print("Distance: ");
  Serial.println(res);
  if (digitalRead(light_sensor) == 1)
  {
    digitalWrite(led_tree, HIGH);
    Serial.println("Light Sensor: HIGH");
    Serial.println(digitalRead(light_sensor));
  }
  else if (digitalRead(light_sensor) == 0)
  {
    digitalWrite(led_tree, LOW);
    Serial.println("Light Sensor: LOW");
    Serial.println(digitalRead(light_sensor));
  }

   if (!client.connected()) {
    reconnect();
  }
  client.loop();
  client.publish("soil_moisture", String(soil_percent).c_str());
  client.publish("water_remain", String(water_remain).c_str());
  client.publish("light_sensor", String(light_value).c_str());
  delay(2000);
}

maybe it is the bootlog at 74880 baud. what baud rate do you have set in Serial Monitor?


text:
How much voltage and amps for 2 SG90 servos?
Question is pretty straight forward: How much amps and voltage do I need for 2 SG90 servos? I want to use 4 but you might already know that Arduino Uno only has 2 5V ports.

Arduino Uno only has 2 5V ports ... no ... the arduino has one power regulator ... the 5 V pins are both connected together

The SG90 servo datasheet is here:
SG90 Servo Datasheet
As you can see, the voltage specification is 4.8 - 6.0 Volts.  But you do NOT want to power this or any other servo via the Arduino.  Servos are quite "noisy" electrically and this can cause instabilities with your Uno.
You want to supply power to the servo directly from a +5V power supply.
I don't see the current draw for this servo specified so you will need to do your own measurements based on the loading of the output shaft.  Be aware that these draw more current with increased load on the shaft.
As far as the control signal, the Arduino Uno can certainly drive it via its PWM outputs.

I know that I am suppose to feed the 2 servos directly from external power source but I still don't know how much voltage and current I need.

@YağızAlpErsoy, hobby servos aren't typically specified that well. The suggestion that your measure them yourself is a good one.

These are relatively low-powered servos.  The voltage is specified, use 5 Volts.  A common 5V 1A supply will likely do well here since you are just driving two servos + your Uno.

@jwh20 thank you! that's it!

A lot depends on what you are using the servos for if lightly loaded and will be operated infrequently you may be able to power them from the Arduino.
Firstly with Analogue servos they can hold position on the gears if the load if light even with the signal stopped. Digital servos store the signal and will  draw more power even if the position moves slightly.
Secondly if your code ensures only one servo is being moved at a time  this restricts the load so can then detach the servo (if using the servo library) or set the signal pin to low if just sending your own pulses. Once in position.
It is also wise to ensure there is flexibility in the operating arm in case there is an obstruction or jam to avoid a large stall current.
Ideally you should power the Arduino with about 7v which reduces the load on the voltage regulator. The higher the voltage the more power the regulator has to dissipate.
I would not use this method for robotics but something like model train signals which are a light load are suitable.


text:
How to upload code without closing puTTY
My question is quite simple: can you, somehow, upload Arduino code without closing puTTY's serial console? I hate having to close the program to open it again for reading the incoming information.

use Serial Monitor in IDE or a second USB to TTL Serial adapter for output to putty

You can't. Putty has no way of disconnecting without closing the program (as far as I can tell).
You could try "Tera Term" which apparently (though I don't use Windows so have no experience with it) has a disconnect option (which you would have to use before uploading).
Alternatively, as @Juraj has mentioned, you could use a separate USB to TTL UART adaptor to provide a second debug serial port (either with SoftwareSerial or mirroring the TX pin of the Arduino directly - don't connect RX in this case) which doesn't interfere with software upload.

`softwareSerial' works well if you've got a spare digital pin or two. I've been using it to send the status information I need to a Raspberry Pi, via a level converter, while the proper USB serial port is used for uploading from a desktop PC, as well as getting a copy of the status info.

There is an open source project that will do what you want.
http://com0com.sourceforge.net/
The com0com will create virtual com ports for the programs to connect to.
The hub4com will allow you to route data between the physical port and multiple virtual com ports.
http://com0com.sourceforge.net/hub4com/ReadMe.txt

I never knew about that.  It's a nice solution!


text:
esp32 Stack canary watchpoint triggered
I am writing a program for esp32 on Arduino IDE. On some point of execution of code for File reading I am facing this exception,
Guru Meditation Error: Core  1 panic'ed (Unhandled debug exception)
Debug exception reason: Stack canary watchpoint triggered (loopTask)

However on reading few forums I found an answer of increasing the depth of the stack for your FreeRTOS task.
My question is there any other way to handle this exception other than increasing stack size and avoid the program from crashing ?

The best way to handle this exception is to identify what's using so much space on the stack and rewrite your code to avoid it.
The three most common ways you'd use too much stack space are:

large local variables - for instance, declaring a large array as a local variable inside a function, like:

#define VERY_LARGE_STRING_LENGTH 8000

void loop() {
  char my_very_large_string[VERY_LARGE_STRING_LENGTH];

  for(i = 0; i < VERY_LARGE_STRING_LENGTH; i++)
    my_very_large_string[i] = ' ';
}

Local variables are stored on the stack, so a large array of them will use up a lot of stack space.

recursive functions - each time a function recurses it uses stack space. If it recurses deeply enough then it will trample the stack guard and cause this exception. For instance:

int count(i) {
  i--;

  if(i > 0) {
    Serial.println(count(i));
  }

  return i;
}

void loop() {
  count(8000);
}

Each time a function recurses, its return address and its arguments and local variables are all stored on the stack. If it recurses too many times it will use more storage than is allocated to the stack.

mistakes in your code like wild pointers and buffer overruns

void loop() {
  char my_bad_string[10];
  char *wild_pointer;

  // buffer overrun
  for(i = 0; i < 8000; i++)
    my_bad_string[i] = ' ';

  // who knows where this will end up pointing
  wild_pointer += rand();
  wild_pointer = ' ';
}

when you overrun an array on the stack you'll probably overwrite other variables and corrupt their values. Do it enough and you'll hit the stack guard. Remember that C strings (char arrays and pointers) need n+1 characters to store a string of length n because they're terminated with an extra null '\0' character.
If you're using recursive functions, look at ways to limit the recursion or use tail recursion which the compiler may be able to optimize to avoid using excessive stack space.
If you're using large variables, think about why and rewrite your code to be able to use smaller variables. For instance, if you're reading a large file, try to process it a line at a time rather than reading the entire file into memory. If you're downloading large JSON from a web server, try using a streaming JSON parser rather than downloading the entire thing and then processing it.
A mistake in your code will be the hardest to figure out, given that it's a mistake. Be careful about pointers and memory allocation. Although memory is allocated from the heap and not the stack, if it's overwritten or reused after it's been freed using it as a pointer can still cause stack corruption. Also be careful to not return pointers to local variables inside functions:
int *do_not_do_this() {
  int this_will_not_work_the_way_you_hope = 0;

  return &this_will_not_work_the_way_you_hope;
}

can also lead to stack corruption as the space occupied by the variable will no longer be reserved for it and may be used by something else.


text:
IRremote and PCM sound libraries interfering
I have a simple sketch which sends IR codes, plays a sound and toggles an LED when you press a button and toggles another LED when it receives that code. The idea is that I have two Arduinos with this same sketch and when you press the button on one, the LED is toggled and so is another LED on the other Arduino. This program works as intended when the sound is not included.
Here is the sketch:

#include <IRremote.h> // For the IR transmition and receiving
#include <PCM.h> // For the audio output

IRsend irsend; // Setup the IR transmitter
const int receiver = 8; // Initialize pin 13 as recevier pin.
IRrecv irrecv(receiver); // Create a new instance of receiver
decode_results results;

// Declare arrays to hold sound notes to play
const unsigned char gunShot[] PROGMEM = {}; // There is a huge list of numbers in this array, but I removed them to make the code easier to read

const unsigned char gunClick[] PROGMEM = {}; // There is a huge list of numbers in this array, but I removed them to make the code easier to read

// declare consants
const int button = 13;
const int greenLight = 7;
const int yellowLight = 2;
const int timeBetweenTransmittion = 800; // At least 800 milliseconds between two transmissions
// The speaker is fixed on pin 11

// declare variables
bool toggleGreen = true; // Bool variables to toggle the lights
bool toggleYellow = true;
long int previousTransmittion = 0; // Long int to store the timestamp in millis of the previous transmission

// put your setup code in here, to run once:
void setup()
{
  pinMode(button, INPUT_PULLUP); // Setup the button with an internal pullup resistor
  Serial.begin(9600);
  irrecv.enableIRIn(); // Enable the receiver
  Serial.println("start");
}

// put your main code in here, to run repeatedly:
void loop() {
  if (not digitalRead(button) && millis() > previousTransmittion + timeBetweenTransmittion) // If the button is pressed and it's been enought time since the last transmittion
  {
    Serial.println("send!");

    // Different orders of these lines of code were tried:

    //startPlayback(gunShot, sizeof(gunShot)); // Play shot before sending the code and enabling the receiver (play command 1 for reference)
    //delay(250);

    irsend.sendNEC(1367857, 32); // Send the code

    //startPlayback(gunShot, sizeof(gunShot)); // Play shot between sending the code and enabling the receiver (play command 2 for reference)
    //delay(250);

    irrecv.enableIRIn(); // Sending ir stops the receiver so start the receiver again

    startPlayback(gunShot, sizeof(gunShot)); // Play shot after sending the code and enabling the receiver (play command 3 for reference)
    delay(250);

    // Toggle the yellow light
    digitalWrite(yellowLight, toggleYellow);
    toggleYellow = not toggleYellow;

    previousTransmittion = millis(); // Set the record for latest transmittion to the currnt time
  }

  if (irrecv.decode(&results)) // If we have received an IR signal
  {
    Serial.println (String(results.value, HEX)); // Display HEX results
    if (String(results.value, DEC) == "1367857") // If the code is the right one
    {
      Serial.println("correct code");

      // toggle the green light
      digitalWrite(greenLight, toggleGreen);
      toggleGreen = not toggleGreen;
    }
    irrecv.resume(); // Prepare the receiver for the next code
 }
}

// End of sketch
As you can see, I tried putting the play sound line before, between and after the IR transmission lines of code. The delays are there so I can see if the audio starts to play and stops or if it just never plays. Here is what I found from all the combinations:

In all the combinations (play command 1, 2 and 3), The IR receiver worked as intended if used BEFORE ever pressing the button.

None of the combinations stop the loop as if I put <Serial.println("loop");> at the start of the loop() routine, it continues to print "loop", regardless of what I do.

In play command 1 and 2, the sound plays when I press the button, but stops after the 250ms delay. Once the button has been pressed once, it doesn't do anything when I press it again (doesn't print "send!" or toggle the light). The receiver receives one more code after pressing the button, but always prints the code "2a", regardless of what button on my tv remote I press (the tv remote usually prints a 6 character hex code). After it prints "2a", it doesn't receive any more codes.

Play command 3 plays the full sound and sends the right code, and allows me to do it as many times as I want (the button still works after pressing it more than once). However the receiver still no longer works after the first time I press the button. It doesn't receive "2a" the first time after pressing the button unlike the first 2.

I am using the libraries IRremote by shirriff, z3t0 and ArminJo (VERSION 2.6.1) and PCM by David Mellis, Michael Smith (VERSION 1.0.0) (http://highlowtech.org/?p=1963). I don't know if there is a simple way around this problem or if these libraries just cannot be used together.
I have the speaker on pin 11.
If you need anything clarifying please ask. Any help would be appreciated, thanks in advance.

The PCM library uses timer 1, and timer 2. The IRremote library uses timer 1. So they both need timer 1. So there's a conflict. So you can't use both libraries at the same time, unfortunately.

Okay, thanks. Do you know of any other libraries that I could use together that would allow me to use IR and sound which don't conflict?

Easiest would be to offload the sound playback to a different chip, like the dfplayer mini (which carries a micro SD card)

Okay, thanks. I've had a brief look and that looks like a good solution.

It works for me if i put a delay after startPlayback followed by a irrecv.enableIRIn();
startPlayback(sample, sizeof(sample));
delay(1000); // delay needed as long audio is playing
irrecv.enableIRIn(); // enable input from IR receiver after using PCM library startPlayback


text:
Will the noise from a voltage regulator interfere with IR LEDs and receivers on an Atmega328? (Arduino Uno sketch)
I have a project which uses an IR LED and receiver to communicate with other Arduinos. I am using the Atmega328 out of the Uno, rather than the whole Arduino board and I need it to be battery-powered, so I need to use a voltage regulator to maintain 5V to the chip.
I want to avoid a linear regulator if I can, as they are inefficient, but I'm worried that the other types will cause too much noise on the output and it will interfere with the IR communication.
Should I be concerned about this or am I making a fuss about nothing, I can always use a linear one if I need to.
Thanks in advance.

Depends on the switching frequency of the regulator. If it coincides with the IR carrier frequency, or a multiple thereof, then possibly.

If in doubt add some suitable filtering.

I bought a switching mode voltage regulator (buck-boost) to test it and it works fine, I put a 10uF capacitor across the output to reduce noise but that was just a precaution - I don't know if it was necessary.