text:
Arduino OOP and [this] keyword
Lets say I have a sketch called mysketch.ino with these contents:
String globalString = "ThisisGlobal";
void setup(){}
void loop(){}

How can I pass THIS sketch mysketch.ino as an object or its reference to a .h file named
StringChanger.h with the following contents, so that StringChanger.h can change somevariables belonging to mysketch.ino.
class StringChanger{
   template <typename T> // or type of mySketch.ino i don't know what i'm doing
   void changeString(T t) {  //a Reference Or Object Or Whatever
      t.globalString = "GotYouAndChangedYou";
   }
}

I wan't to have simple usage in the mySketch.ino.
For instance:
#include "StringChanger.h"

StringChanger change(**this**);  // perhaps default empty constructor here

String globalString = "ThisisGlobal";

void setup(){
    change.changeString(); // perhaps pass reference to **this** here
}
void loop(){}

How can I accomplish this (give a class an object so that it can change some value of that object) in general and not neccesarily in this context.
Errors I currently get:
invalid use of 'this' in non-member function
invalid use of 'this' at top level.

Arduino OOP and [this] keyword - it's C++. So whatever works in C++ works in Arduino.

StringChanger change(**this**); this doesn't make any sense at all, sorry.

I thought stack over flow would bold the string sorry. I meant change(this); and I understand Arduino has less of c++ especially the heavy complex parts because of the speed of micro controllers . I don't think if it works in C++ it's works in Arduino

It's nothing to do with speed. Exceptions are disabled by a command-line option. The rest is just pure C++.

A sketch isn't an object. It is merely a collection of variables, functions and, of course, classes.
Your example seems to be trying to make things incredibly complex when they don't need to be.
There are a number of ways of referencing things in one file from another - whether or not they are in a class.  The simplest is to use the extern keyword.  This is used in a file where you want to reference a variable or function that is defined in the global scope of another file. It says "This variable is global, but it's defined somewhere else."
// Sketch
String myString = "foo";

// Library
extern String myString;
// ... later on ...
myString = "bar";

Of course, that means that the name of the variable is fixed and cannot change.  So you can pass the variable to whatever it is you want to use that variable in.  That could be as simple as passing it to your "changer" function:
// Sketch
String myString = "foo";
StringChanger change;
// ... later ...
change.changeString(myString);

// Library
class StringChanger {
    public:
        void changeString(String &stringToChange) {
            stringToChange = "bar";
        }
};

If you want to "tie" the variable to the class so you don't have to pass it each time you could pass it to the constructor and have the class remember it:
// Sketch
String myString = "foo";
StringChanger change(myString);
// ... later ...
change.changeString();

// Library
class StringChanger {
    private:
        String *_string;
    public:
        StringChanger(String &string) {
            _string = &string;
        }
        void changeString() {
            *_string = "bar";
        }
}

And there's a myriad of other ways of doing it.

First part of your answer is what I want to do because I simply want that calling the constructor changes the string that is finds that extern string named myString and changes it to another. I don't want to use the function that accepts a string reference. Thanks @Majenko

Why not just make a function that changes an external string? I don't see why you would make a class just to change some external thing, which is not in the class, and doesn't do anything else.

@NickGammon Maybe that's just an example and he's really doing something completely different. Who knows with these kids? Either way, what he is doing is most likely not the right way of doing things and using getters and setters is more likely the right solution for managing his class.

Sounds like one of the better examples of the X-Y Problem that I have seen in a while.

@NickGammon Quite probably. I have pretty much given up trying to convince people that they are asking the wrong question though.

Yes, we need a close reason: "this is the wrong question". :)

@NickGammon I'm guilty of falling into x-y situations all the time. Not always but specifically when i write the type of usage i want then try to solve the problem. Speaking of which checkout my other problem here please.


text:
How do I erase internal EEPROM on a Arduino Pro Mini
I'm working on Arduino pro mini.
and I store some data in internal EEPROM.
So, I want to erase certain data from 0x00 to 0x28 address in EEPROM.
void loop()
{
 ...
 ...
 if(erase_eeprom_flag==1)
 {
   addr_uu=0;
          erase_eeprom_flag=0;
          for(kk=0;kk<28;kk++)
          {
              EEPROM.update(addr_uu,0);

              addr_uu=addr_uu+1;

          }
          Serial.println("OK");
          Serial.println(addr_uu,DEC);
          addr_uu=0;
      }
  }

But I got a data like(28 times '0' and other data 'xxx') "0000000000000000000000000000xxxxxxxxxxxx".
ex : 20170519    --->   expected data: 00000519
                        (inappropriate data: 000020170519)
So, here actually push "0" / add at begin operation happen but I want to remove data from those address.
Please tell which Arduino function help me for solving my issue.

You are clearing 28 decimal bytes, but your address range is 28 hex bytes, or 40 bytes of data.  Hence, the last 12 characters are untouched.

41 bytes (decimal), counting the zero-th byte. Regardless, good catch.

source: Stack Exchange

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

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

sort: votes


text:
Wake up ESP8266 with multiple GPIOs
I am building a ESP-07 based IOT device, that detects the status of 4 doors. The device must connect to WiFi and send an http request, when 1 of 4 doors is opened. I want to place a reed switch, for example on each door. The battery consumption should be minimal, so I thought of using deepsleep () or something similar to keep the device asleep most of the time, or keep it completely off (like most Dash buttons does).
I have studied several options, but almost all use a single GPIO to wake up the device. For example, this option wakes the device up if D3 goes high, and sleep if D3 is low.

    #include
    #include
    #define WAKE_PIN D3
const char* ssid = "SSID";
const char* pass = "PASSWORD";

extern "C" {
    #include "gpio.h"
}

extern "C" {
    #include "user_interface.h"
}

void setup(){
    WiFi.begin(ssid, pass);
    uint8_t i = 0;
    while (WiFi.status() != WL_CONNECTED && i++ < 10) delay(250);
    Serial.begin(115200);
    Serial.println("Setup");
    pinMode(WAKE_PIN, INPUT_PULLUP);
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, LOW);
    gpio_init(); // Initilise GPIO pins
}

void loop(){
    Serial.println("Do something...");
    if(!digitalRead(WAKE_PIN)){
        sleep();
    }
    delay(1000);
}

void sleep(){
    Serial.println("Going to sleep...");
    delay(10);
    wifi_fpm_set_sleep_type(LIGHT_SLEEP_T); // set sleep type
    gpio_pin_wakeup_enable(GPIO_ID_PIN(WAKE_PIN), GPIO_PIN_INTR_HILEVEL);
    wifi_fpm_open(); // Enables force sleep
    wifi_fpm_do_sleep(0xFFFFFFF); // Sleep for longest possible time
    delay(100);
    Serial.println("Woke up!");
}

Here, GPIO_ID_PIN(2) corresponds to GPIO2 on ESP8266-01 , GPIO_PIN_INTR_LOLEVEL for a logic low, can also do other interrupts.
My question is:
Can I use more than one GPIO, that is, one of 4 GPIOs to wake up the device?
I have the problem of knowing which of the four doors has been opened!
The other option I have thought is to use a latch circuit that turns on the (previously turned off) device using a single GPIO. Something like this:

What I meant is that ESP-07 can latch its own power on (and off) using an MOSFET pair connected in parallel with the physical (momentary contact) power switch. When the power switch is pressed (or a door is opened), one of the  first things the ESP8266 needs to do is latch the power on. When the current iteration of this programm is done, it simply turns it's own power off again.
#define POWER_SW   2   // GPIO connected to POWER_LATCH

void LatchOn() {
    pinMode(POWER_SW, OUTPUT);
    digitalWrite(POWER_SW, HIGH);
}

void LatchOff() {
    digitalWrite(POWER_SW, LOW);
}

What I want to know is how I can use more than one signal from each of the 4 doors, or, use 4 GPIOs to activate the latch circuit. I tried with one single door connected to the GPIO that wakes the chip up. I want to extend the functionality of my program so that any of the 4 doors turns the chip on.
Thanks in advance!
P.S.
I have opened a thread about this topic in Arduino Forum as well.

do you have the option of using a logic IC?

Sounds good! Any ideas?

Idea: Wire the  four door-GPIOs together with an OR gate, connect that to your wakeup pin, but still connect all door-GPIOs to 4 different GPIO pins on your ESP8266. When a wakeup is triggered (because ANY of the door GPIOs were triggered), read the state of the 4 door-GPIOs, act on it, then go back to sleep. You can use simple diode-ORs or CMOS (N)OR logic gates for this.

Also asked at https://stackoverflow.com/q/48279829

A friend from Arduino Forum told me that I can use a bunch of diodes to have all door switches trigger two pins: the shared wake-up pin, and a unique one for each switch. I have no idea how I could do that.
Any idea of what a circuit with these characteristics would look like?
Thanks in advance.

I don't know if an TTL-CMOS OR gate like CD4072 works with 3V3 logic. A simple circuit with diodes or resistor looks better. Any ideas?

http://www.ti.com/product/cd74ac32 . PDIP package, four 2-input OR gates, voltage working for 3.3V and 5V as well.

I think Diodes would use less power that an IC, but...

Great! I will try with CD74AC32 as well. Thanks!

How to make a circuit like that with diodes? It seems better to me, but I have no idea

And what if I use the ADC or analog input of the ESP-07? I think that with an array of resistors I can determine which of the 4 doors has been opened. Something like that --> link

Hello!
I have an idea. What if I connect each door using a DPST (double pole single throw) switch?
This would be the scheme using two single switches.
link
My idea is to use the same switch to connect at the same time the RESET PIN and the corresponding pin to each door (for example, GPIO12).
Would there be problems if two doors open at the same time? Would not the RESET pin be overloaded when two switches are connected to VCC?

Hi!
I have made a small card to connect my ESP8266. It is supposed to connect the GPIOs corresponding to the 4 doors I mentioned. My idea is to use, as I said before, a simple switch on each door, to connect each one to GND and the corresponding pin. I have connected each pin (GPIO12, ..., GPIO15) to the inputs of the 74HC32 and the output to the RESET (so that any of the doors can wake up to the ESP8266 of deep sleep.)
74HC32 is already connected to GND and VCC.
Click to see the schematics  --> link  My question is: Ok what I have done?

@JoseAlfredoSanchezDiaz - any chance you can draw a schematic for wiring of your example above - the code was really helpful to me in trying to set up sleep mode in my own project, but I can only make the esp go to sleep with a button, not wake up.

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


text:
Sending data to Arduino Via Nodejs: Arduino does not echo back the data
I have the following sketch that runs in a arduino UNO:
/*
 * Copyright 2018 Dimitrios Desyllas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

String inputString = "";         // a String to hold incoming data
bool seralReadEnded=false;

void setup() {
  Serial.begin(19200);
  while (!Serial);
}

void loop() {
  if(seralReadEnded){
    sendDataOverSerial((byte [])inputString.c_str(),inputString.length());
    inputString="";
    seralReadEnded=false;
    delay(5000);
  }
}

String concatHex(byte value,String string){
  string+="\\x";
  if(value<16){
   string+="0";
  }
  string+=String(value,HEX);
  return string;
}

void sendDataOverSerial(byte byteArray[],size_t arrayLength){
  String returnVal="BEGIN:";
  for(int i=0;i<arrayLength;i++){
    returnVal=concatHex(byteArray[i],returnVal);
  }
  returnVal+="\n";
  Serial.println(returnVal);
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    if(inChar == 0x11){
       char inChar = (char)Serial.read();
    } else if (inChar == 0x03) {
      seralReadEnded = true;
    } else {
     inputString+=inChar;
    }
  }
 }

And I made the following Node.js software in order to read and send data over the USB to arduino:
const SerialPort = require('serialport');
const Readline = require('parser-readline');
const Ready = require('parser-ready');
const Regex = require('parser-regex');
const crypto = require('crypto')

const valueIntoHex=function(value){
  switch(value){
    case 0x11:
      return "0x11";
    case 0x03:
      return "0x03";
    case 0x02:
      return "0x02";
    default:
      return value;
  }
}

/**
* Escaping NonPrintable Ascii Characters (bytes) of a buffer data
* @param <Buffer> data The data to read
*/
const formatDataForSerialSend=function(data){
  //I allocate double the length because I assume worst case scenario that all bytes to be the ones I need to escape
  const returnBuffer =  Buffer.alloc(2*data.length);
  indexToWrite=0;
  //I use indexToWrite index because during escapes the posision that I write the byte is different from the ne I read.
  for(let i=0;i<data.length;i++){
    const byte=data.readUInt8(i);

    if(byte == 0x11 || byte == 0x03 || byte == 0x02){
      console.log("Escaped Ascii: "+valueIntoHex(byte));
      indexToWrite=returnBuffer.writeUInt8(0x11,indexToWrite);
    }
    indexToWrite=returnBuffer.writeUInt8(byte,indexToWrite);
  }
  returnBuffer.writeUInt8(0x03,indexToWrite);
  //Because I do not want uneeded size of data in my buffer
  const lastIndex=returnBuffer.lastIndexOf(0x03);
  return returnBuffer.slice(0,lastIndex+1);//I want size and not the last index. (Size=lastIndex+1)
}

/**
* Application Specific send logic
* @param <Buffer> data Data te send
*/
const sendData=function(data){
  console.log("Escaping dirty Ascii");
  data=formatDataForSerialSend(data);
  console.log("SEND DATA: "+data.toString('hex'));
  port.write(data,'binary',(err)=>{
    if(err){
      console.err("Could not send data",err);
    }
  });
}

const portName = '/dev/ttyACM0';

const port = new SerialPort(portName, {baudRate: 19200});

//Look over: https://regex101.com/r/QcBTTj/1
const hexRegex=/((\\|0)(x|X)[0-9A-Fa-f]{2})+/g;
const parser = port.pipe(new Ready({ delimiter: 'BEGIN:' })).pipe(new Readline({ delimiter: '\r\n' }));

console.log("################# SEND ####################");
sendData(Buffer.from('hello','ascii'));
console.log("############# END OF SEND #################");

parser.on('data', function(input) {
    console.log("################# RECIEVE ##################");
    console.log("Message: "+input);

    const input2=input.replace(/^BEGIN:|(\r|\n|(\\|0)(x|X))/g,"");
    console.log("Sanitized Input: ",input2);

    try{
        const data=Buffer.from(input2,'hex')
        console.log("REPRINT HEX FOR VERIFICATION: "+data.toString('hex'));
        console.log("############ END RECIEVE ##############");
    } catch(e) {
        console.error(e);
    }
});

But for some reason I managed to make it send data but the arduino does not send them back. So I want to debug it, but I do not know how I can do that I mean over arduino code how I will launch a debugger in order to do that?
How I can at the same time look and analyze the USB traffic between an application and Arduino in order to determine the logic bug?
Also I could not distinguish why arduino does not echo back some data, if I use this code for this sketch, the node.js application reads the data fine:
/*
 * Copyright 2018 Dimitrios Desyllas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

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

void loop() {
  byte byteArray[]={1,10,255,3,4,2,1,55};
  for(int i=0;i<sizeof(byteArray);i++){
    Serial.print("\\x");
    if(byteArray[i]<16){Serial.print(0);}
    Serial.print(byteArray[i],HEX);
  }
  Serial.println("\n");
  delay(3000);
}

Edit1
So far I modified the sketch into this:
String inputString = "";         // a String to hold incoming data
bool seralReadEnded=false;

void setup() {
  Serial.begin(19200);
  while (!Serial);
}

void loop() {
  if(seralReadEnded){
    sendDataOverSerial((byte [])inputString.c_str(),inputString.length());
    inputString="";
    seralReadEnded=false;
  }
}

String concatHex(byte value,String string){
  string+="\\x";
  if(value<16){
   string+="0";
  }
  string+=String(value,HEX);
  return string;
}

void sendDataOverSerial(byte byteArray[],size_t arrayLength){
  String returnVal="BEGIN:";
  for(int i=0;i<arrayLength;i++){
    returnVal=concatHex(byteArray[i],returnVal);
  }
  returnVal+="\n";
  Serial.println(returnVal);
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    if(inChar == 0x11){
       char inChar = (char)Serial.read();
    } else if (inChar == 0x03) {
      seralReadEnded = true;
    } else {
     inputString+=inChar;
    }
  }
 }

And I tested it by running over my GNU/Linux terminal like that:
screen /dev/ttyACM0 19200

I typed some stuff and by pressing CTRL+C keyboard combination I managed to get them back (Somehow gives a character 0x03 that is the ETX ascii character that in my case indicated the data stream).
But How I get some random binary escape them with 0x11 charactes and send into arduino via bash, as fas ad I know is that on GNU/Linux systems I can use the /dev/random for generating data?

Do not use delay(). 2. Do not use String objects, as they are not memory friendly. Use plain byte arrays instead. 3. Do not use Node.js for testing your sketch. Use the serial console or a serial terminal emulator (e.g., putty), then add the Node part once you know your sketch runs fine.

Don't use 0x11 (DC1) as an escape, as the Linux terminal driver interprets it as a “start” (Xon). You may use 0x10 (DLE), which you can type at the keyboard as Control-P. Also, your handling of the escape is flawed: you do a Serial.read() which will most often return -1 (meaning: no character available), and you don't use the result.

There are too many String copies in your code. This is asking for
trouble, as it can lead to memory fragmentation and, ultimately, to
memory exhaustion. That's why I recommended in a comment to buffer the
data in plain byte arrays.
However, it appears your Node.js script is going to do the buffering
anyway (that's what the Readline parser does). Thus there is no point
in buffering also on the Arduino, which has one million (or more) times
less memory than the computer running the Node.js code. If the Arduino
just outputs the bytes as it gets them, the program becomes very simple:
void setup()
{
    Serial.begin(19200);
    Serial.print("BEGIN:");
}

// Send a byte over the serial port, formatted in hex.
static void send_hex(uint8_t value)
{
    Serial.print("\\x");
    if (value < 16)
        Serial.print('0');
    Serial.print(value, HEX);
}

void loop()
{
    static bool escaped;  // is the next character escaped?
    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\x10' && !escaped) {  // DLE (data link escape)
            escaped = true;
        } else if (c == '\x03' && !escaped) {  // ETX (end of text)
            Serial.print("\r\nBEGIN:");
        } else {
            send_hex(c);
            escaped = false;
        }
    }
}

Note that, upon receiving an “end of text”, the program terminates the
current line (by sending "\r\n") and immediately sends the preamble for
the next one ("BEGIN:"). On the receiving side, the readline parser will
take care of delivering only complete lines.
If, for whatever reason, you do need to buffer inside the Arduino, then
remove the Serial.print("BEGIN:"); line from setup() and change the
loop as follows:
void loop()
{
    static char buffer[1024];
    static size_t pos;    // current position in buffer
    static bool escaped;  // is the next character escaped?
    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\x10' && !escaped) {  // DLE (data link escape)
            escaped = true;
        } else if (c == '\x03' && !escaped) {  // ETX (end of text)
            Serial.print("BEGIN:");
            for (size_t i = 0; i < pos; i++)
                send_hex(buffer[i]);
            Serial.println();
            pos = 0;
        } else {
            if (pos < sizeof buffer)
                buffer[pos++] = c;
            escaped = false;
        }
    }
}

Note that the buffer is sized at half the RAM of your Uno. This is safe,
as it is a very simple program that uses very little dynamic memory
(stack only, no heap) and has no risk of fragmentation. Note also that
your original program stores both the raw data and the formatted hex
(which is 4 times larger) in memory at the same time, which means your
buffering would be limited to 1/5 of the available RAM.

I splited them because I want to look on how serial I/O will be done in https://arduino.stackexchange.com/questions/52151/how-to-indicate-an-end-of-a-stream-on-usb so I wanted  them as separate functions the send and the receive

Also the problem in on Node.js Application and not over arduino,

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


text:
Arduino Uno with Kubuntu 16.04: Unable to enumerate device
I try to connect my arduino uno R1 in order to program the atmega8u2 but I am not able to do so. When I run sudo dfu-programmer atmega8u2 erase I get the following results:
dfu-programmer: no device present.

So in order to diagnose it i run dmeesg with the following results:
 [ 1395.921051] usb 2-3: new full-speed USB device number 30 using
 xhci_hcd [ 1396.041175] usb 2-3: device descriptor read/64, error -71
 [ 1396.269135] usb 2-3: device descriptor read/64, error -71 [
 1396.497109] usb 2-3: new full-speed USB device number 31 using xhci_hcd [ 1396.617169] usb 2-3: device descriptor read/64, error -71
 [ 1396.845177] usb 2-3: device descriptor read/64, error -71 [
 1397.073163] usb 2-3: new full-speed USB device number 32 using xhci_hcd [ 1397.073371] usb 2-3: Device not responding to setup
 address. [ 1397.281311] usb 2-3: Device not responding to setup
 address. [ 1397.489086] usb 2-3: device not accepting address 32,
 error -71 [ 1397.609173] usb 2-3: new full-speed USB device number 33
 using xhci_hcd [ 1397.609382] usb 2-3: Device not responding to setup
 address. [ 1397.817200] usb 2-3: Device not responding to setup
 address. [ 1398.025176] usb 2-3: device not accepting address 33,
 error -71 [ 1398.025235] usb usb2-port3: unable to enumerate USB
 device

Do you know fellows how to make my arduino connect back into my computer?
Furthermore II forgot to mention my user is in dialout group as groups gnu/linux command mentions:
pcmagas adm dialout cdrom sudo dip plugdev lpadmin sambashare libvirtd docker wireshark

PS: That thing happened after soldering the resistor into the board so it is a new problem.

Looks like your board is either electrically damaged, or by previous attempts you put it in a bad software state where it does not function as a USB device.  If it is recoverable over USB, it would be by doing something electrically on startup to force it into a factory firmware recovery mode.  Likely you need to read the instructions you are following more thoroughly.  Did you solder the resistor as instructed at https://www.arduino.cc/en/Hacking/DFUProgramming8U2 ??

Well the board has already this problem: https://arduino.stackexchange.com/questions/50807/how-to-re-solder-the-resistor-in-order-to-reprogram-the-atmega8u2 I somehow managed to solder back the resistor in order to reprogram it in order to fix this problem but the problem still remains. The poer led works as ussual and the led in pin 13 blinks when I press the reset button.

Possible duplicate of How to re-solder the resistor in order to reprogram the Atmega8U2

And how do you know you were successful in soldering the resistor?  You have not achieved what the resistor should, so either it is not connected, or you're not doing the reset required after plugging in the USB, or there's another electrical fault on your board that disables the 8u2 but not the 328p.  This looks like a duplicate.

You should solder the resistor (in case you do not have the skills I reccomend doing into a proffessional, a professional close to me managed to solder it with a cost about 5 euros) and then hardware reset the atmega8u2 the documentation mentions. For quick reference just look over in this image:

In the dmesg you will see similar the same or message:
[ 1544.679504] usb 1-6: new full-speed USB device number 42 using xhci_hcd
[ 1544.808341] usb 1-6: New USB device found, idVendor=03eb, idProduct=2ff7
[ 1544.808350] usb 1-6: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[ 1544.808356] usb 1-6: Product: Arduino Uno DFU

Then look on the similar question for R1 boards or in case you have a newer board then follow the instructions mentiones to the documentation.


text:
Arduino yun is not creating it's wifi?
I have installed Arduino software into my PC and copied the bin files into the memory card that has to be fixed into Arduino yun.
After switching on the yun board it is not creating any Arduino yun wifi connection.
Can you help me to overcome this problem?
Thanks.

If there is no code that enables the WiFi, it won't be enabled.
Here's the link:
https://www.arduino.cc/en/Guide/ArduinoYun#toc14

Perhaps you need to reset wiffi. Press for 3 seconds. After this you must await for a while. Some leds will open and close. This process takes about 2 or 3 minutes. After this. Your white led will be flashing. That is all.
Have in mind some points:
First time you have to connect your yun by usb. Then you have to openIDE and choose IP PORT which will be showed(192.168....). Then go to your browser and type Ip and configurate your yun for wifi.


text:
Generate particular pulse using Arduino
How can I generate this pulse with an Arduino Micro?
Is it necessary an external component?

how much current will you be drawing / what will it be connected to?

is only for signal generator experiment

Looks like something for a 2-bit DA converter. https://en.wikipedia.org/wiki/Digital-to-analog_converter. A resistor ladder is the simplest solution; https://en.wikipedia.org/wiki/Resistor_ladder

Take two 10K or so resistors:
    +5V
     |
    10K
     |
Pin2-+---> output
     |
    10K
     |
    GND

The following program does the trick:
const uint8_t kPin = 2;
const uint32_t kDelay = 10;  // 100Hz

void setup() {
}

void loop() {
  pinMode(kPin, OUTPUT);
  digitalWrite(kPin, HIGH);
  delay(kDelay);

  pinMode(kPin, INPUT);
  delay(kDelay);

  pinMode(kPin, OUTPUT);
  digitalWrite(kPin, LOW);
  delay(kDelay);

  pinMode(kPin, INPUT);
  delay(kDelay);
}

When Pin2 (or any other pin for that matter) is set as INPUT, it is in high-impedance state (theoretically), so effectively you have a voltage divider giving you 1/2 Vcc. When it is set as OUTPUT, and now assuming that its output impedance is << 10KΩ, it drives the output to either +5V or 0V.

Obviously, this solution does not generalize to multiple levels; folllow @gerben's solution with a resitor ladder for that. However, I like using tri-state pins in creative ways. Charlieplexing is the canonical such example.

If both inputs are 0V, the output will be 0V.
If both inputs are 5V, the output will be 5V.
If one input is 0V and one 5V the output will be 2.5V.
However, if the device attached to the output doesn't have a high input impedance, the voltage will drop some. You could add an opamp to prevent this.
I think you can generate the 2 pins outputs using one of the timers in phase correct pwm mode. Freeing up the cpu and giving a very clean output signal, as using software "pwm" could be slightly of due to interrupts occuring.

ha! mine uses only one pin :)
What did you use to draw the circuit?

@JayEye cool solution. Didn't think about tri-state. I used kicad to draw the schematic.


text:
Is ATMEGA328P the same as 16U2?
I've been playing with my Arduino for a few months.
But, I just bought a shield that says it needs to be used with ATMEGA328P.  My box says I have a 328P, however, reading the chip, it's inscribed with "ATMEL MEGA16U2".
Does that mean the box is wrong, or is that the same as 328P somehow?
Thanks!!

Could you post a picture of your board?

The 16u2 is related to the ATmega328p, and includes USB, but is more limited in resources.   While it would be possible to make an Arduino-type board from alone, this is unlikely to be what you have.
Rather, it is likely that you have a board with an ATmega328p as the main processor, and also a 16u2 which serves as a USB interface for it.
You could know for sure from what board type you select in the dropdown menu of the Arduino IDE.  If you are selecting something like "Uno" or "Duemilanove" you have a 328p as the main processor.
(The other presently common type of board is the "Leonardo" style where a 32u4 - essentially a bigger version of the 16u2 - is used as a single-chip solution that is both the primary processor and the USB interface.  But if that is what you had, it would not say 16u2 on it, unless it was an attempt to make a more limited "budget" version).

You are correct - when I plug it in and use the IDE, I can connect to it as an Uno.  Thank you, @Chris Stratton!

the 328p is the microcontoller. It's the larger chip located in the middle of the arduino board surface. This one handles the code/ sketch/ programme that you write). The 16u2, on the other hand, is the smaller chip located near the USB port. This handles data communication through the USB port.


text:
My Arduino UNO turns LED ON forever when I connect it to my Laptop

My Arduino UNO Board keeps the LED light turned on forever whenever I connect it to my PC. And, when I try to upload even a sample sketch, it says avrdude: stk500_recv(): programmer is not responding.
How can I fix this error?

Could you try replacing the ATmega328P? You'll want to check if it's the board or the microcontroller.

Okay. My ATmega328p is a microcontroller over my Arduino UNO Board. I am a newbie. So help me in fixing that error.

Do you have a picture of the board? Could you add it to the question?

Yep. Did it. Check it now.

Hmm, the chip under the wordt "UNO" is your microcontroller, the brains of the device (: in some Arduino's, it's a replacable one, but this one is unlikely to be replaceable ;p

What is the chip right under the crystal, at the side of the USB labeled? And did the Arduino work before or is it a new one?

Cheap Chinese clone by the looks of things...

Yes, it was working fine. I even did run some programs efficiently over this piece. But, now since last 2 days, it's been giving me that error for whichever Laptop or PC I connect to.

And about that Chip, @Paul , I don't quite know what it is. A specification guide did not come with this piece.

@Abhay, it looks like a CH340G, does it have any markings like that? But when you get an upload error, it's often either the "USB chip" or the "microcontroller". (Or just complete fail) can you check the 5V and 3.3V pins, if they do givethe correct voltages?

When you connect (and disconnect) the device, are you getting the Windows "found device" sound?  If not, it's possible that your device driver is either corrupted or "confused".  If you don't get the sound, then I can walk you through checking the driver.  If you are getting the sound, make sure that in your IDE, that you select the UNO board, and then select the COM port.  It's possible that through plug and play, your COM number has changed, and you IDE is still trying to use the old one.

When you connect the device, if you hear the Windows "found device" sound, then you need to check your COM port driver, as it's very likely that the COM port number may have changed. On your Desktop or in File Manager, right click "This PC" or "My Computer", and select "Manage" from the submenu.  That will bring up the Computer Management console. On the left, select "Device Manager".  That will bring up your list of devices. In the list look for "Ports (COM & LPT)".

If you don't see, "Ports", then click "View" and check "Show hidden devices".  If this is the only Arduino that you've ever used, you should only see one listing. Make note of the COM Port Number the driver is using. It's possible that the port number may have changed since you first used the device. Plug-n-play will do this if you plug the cable into a different USB port that may be using a different USB controller, etc.
Then in your Arduino IDE, click "Tools", then expand "Boards" and select "Arduino/Genuino UNO" board, then re-click "Tools", and hover over "Port", and select the port number that is assigned to the Port that you found in Device Manager.
If that doesn't work, then you may have a problem with your driver.  Some of the "cheap chinese board" use a different FTDI chipset, so the plug-n-play windows driver may not work. In that case, the manufacturer should point you to the correct driver. Download their provided driver, then you can update the driver in Device Manager.

As answered by @Zacwolf , I checked that. It hasn't changed for my Arduino UNO. My Port is "USB-SERIAL CH340 (COM 3)" port. It was the same before too.

And, I discovered one thing more, that before this problem i.e. before few days, it used to connect to any laptop and run any Arduino program. And now, it doesn't connect to any of the Laptop. And, the LED for the Arduino still is ON continuously.

@Paul , the Chip which you had asked which is placed right under the crystal, at the side of the USB is labeled as AMS1117.

I do get the sound of Windows found device @ZacWolf whenever I plug it to the computer.

Help Anyone? ? ? !

Help me locate the ICSP header pins for Serial interface. I want to check this board by flashing  it's bootloader.

The 6 pins on the right in the photo are the ICSP header for the Atmega328P chip. You don't have an ICSP header for the Serial chip because it isn't a genuine Uno, and they have used a cheaper USB-to-serial chip which isn't programmable. Under the circumstances, presuming it was cheap, I would just replace the whole board.


text:
Connecting Pulse Sensor to RFDuino Simblee
I am trying to make a heart rate sensor watch. I am trying to do this using a Simblee (www.simblee.com) and a Pulse Sensor (www.pulsesensor.com) however they will not work! The original code from pulsesensor uses Timer2, which I commented out in favor of delay(2) (i'm new to Arduino and it seemed to work). I am getting readings over serial they just seem to be in a wave instead of a pulse. I need to get this working as I am out of time and money ;) Would anyone have any ideas on how I could get them working?
ALL CODE ON GITHUB (https://github.com/shadow85926/SimbleeArduinoCode)
Thank you.
Wave pattern:
https://i.sstatic.net/zw7tP.jpg


text:
Interval timer on Arduino: Doubt about TimerOne library
I want to synchronize a timer interrupt from a button is pressed. I want to read a button state 3 seconds later from the first pulse moment (to identify long pressed button, 3 seconds for this example). I'm trying to do with this code:
#include <TimerOne.h>
#define pinButton 3
#define POWER_ON_TIME 3 //Long press in seconds

volatile unsigned long pressed_Time = 0;
volatile unsigned long myTime_button = 0;
volatile unsigned long myTimeOn_button = 0;
volatile unsigned long myTime_pressed = 0;

unsigned long holdTime = 0;
bool button_state = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(pinButton, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);

  Timer1.initialize();
  Timer1.attachInterrupt(pressed_check);
  attachInterrupt(digitalPinToInterrupt(pinButton), button_act, CHANGE);
  Serial.begin(9600);
}

void loop() {

  Serial.println("myTime_pressed");
  Serial.println(myTime_pressed);

  if (!digitalRead(pinButton)){Timer1.attachInterrupt(pressed_check,POWER_ON_TIME*1000000 );}
    else {Timer1.detachInterrupt();}

}

void button_act(){
  if (!digitalRead(pinButton)){myTime_button = micros(); //Flanco de bajada
  }
  else{myTimeOn_button = micros(); } //Flanco de subida
}

void pressed_check(){
  myTime_pressed = micros();

}

This way I can start the timer interrupt when the button is pressed, but the problem is the time is not the time from the function is attached but from the beginning. Any advice to change this?

The function button_act() is missing from the posted code. Please add it. One problem is probably that you need to add L at the end of a big integer number. Otherwise the compiler will by default treat it as integer (which cannot hold the value 1 million). But also: I don't understand the logic of your program. In pressed_check() you don't check the button but only set myTime_pressed, which is only ever printed but not used in any way. In loop() you attach and detach the timer interrupt on button press and release, which doesn't really make sense to me.

And why do you want to use an extra hardware timer to record the press duration? I don't see a reason why millis() and micros() wouldn't be enough for this. No need to go through the hassle of using a hardware timer.

Hi @chrisl . I cut the code, sorry. Now all is ok. I have two interrupts: one external, connected to the button, the other by timer. On this code I'm testing the micros() capture with timer interruption and I wanted to see the results. I thought micros() could capture the time from attachInterrupt action, not from the Arduino start.

micros() gives you the microseconds from the startup. When you need a time difference you need to capture the start and end value and then take the difference. Though I still don't see why you would need a hardware Timer for distinguishing short and long button presses.

I now I now, it is possible that is easier make this without timers, but now I want to know why the timer function attached executes on interval times from the start, not from determinated event.

Why are you using interrupts at all? Look at the State Change Detection example in the IDE (File->examples->02.digital->State Change Detection) to learn how to detect when the button gets pressed or released and then record the time of that event. After the current time - event time is greater than 3 seconds, read your button again.
Or, make your life easier and use the Bounce2.h library. It has a Button class that will track the duration the button has been in any state.

Don't know if I understand what you want to do.
IMHO TimerOne is a good library for repetitive tasks, not for one shot events.
You should use Timer1.stop and Timer1.resume() to start the 3 seconds count whenever you press the button.
But TimerOne has a known issue: when you use restart or start the ISR is fired immediatly
Here is my version of your code. It waits for button press and then starts timer. After 3 seconds pressed_check is fired and the longPressDetected flas is set.
I hope I have correctly interpreted your question
#include <TimerOne.h>
#define pinButton 3
#define POWER_ON_TIME 3UL //Long press in seconds

volatile unsigned long pressed_Time = 0;
volatile unsigned long myTime_button = 0;
volatile unsigned long myTimeOn_button = 0;
volatile unsigned long myTime_pressed = 0;

volatile bool firstISR_Call = true;
volatile bool longPressDetected = false;

unsigned long holdTime = 0;
bool button_state = false;

void setup() {
    // put your setup code here, to run once:
    pinMode(pinButton, INPUT_PULLUP);
    pinMode(LED_BUILTIN, OUTPUT);

    Timer1.initialize();
    // Create an ISR that is called every POWER_ON_TIME seconds
    Timer1.attachInterrupt(pressed_check, POWER_ON_TIME * 1000000UL);
    // Stop Timer1 now
    Timer1.stop();

    //Timer1.attachInterrupt(pressed_check);

    attachInterrupt(digitalPinToInterrupt(pinButton), button_act, CHANGE);
    Serial.begin(9600);
}

void loop() {
    if (longPressDetected) {
        longPressDetected = false;
        Serial.println("Long press detected");
    }
    delay(100);
}

void button_act() {
    if (!digitalRead(pinButton)) {
        myTime_button = micros(); //Flanco de bajada
        firstISR_Call = true;       // Set to true toprevent "phantom" interrupt
        longPressDetected = false;  // Clear long press detection flag
        Timer1.restart();           // Restart timer from 0 - ISSUE: this fires immediatly an interrupt
                                    // causing a so called "phantom" interrupt
    }
    else {
      myTimeOn_button = micros() - myTime_button;
      Timer1.stop();
    } //Flanco de subida
}

void pressed_check() {
    // Detect "phantom" interrupt
    if (firstISR_Call) {
        firstISR_Call = false;
        return;
    }
    longPressDetected = true;
    myTime_pressed = micros() - myTime_button;
    Timer1.stop();
}

Thank you so much! This is the answer for my question! I tried with restart and start but it didn't work like I wanted. Thank you so much!

@Juanma you're welcome, my pleasure.


text:
Capacitive touch on Adafruit Trinket M0 goes unstable when USB cable from laptop is disconnected
Note that to get to this point, I used much of the helpful information from the Post
How to use capactive touch on Adafruit board in Arduino mode?
I am using a Trinket M0 with the Arduino IDE with the Adafruit_FreeTouch.h library.
Also used the example code found here
https://github.com/adafruit/Adafruit_FreeTouch/blob/master/examples/freetouch/freetouch.ino
I modified the code to use the A0 input as a touch sensor with a wire and aluminum foil.
Using a FET on the digital output A2 to turn a fan on or off when the foil is touched.
I am using a small 12VDC wall transformer (1.25A) and then a DC-DC converter to output 5vdc for the Trinket on the BAT in.  The 12Vdc also supplies power to the small computer fan ( uses about 200ma)
The circuit and code work great when the USB cable from my laptop is connected to the Trinket.
BUT, when I disconnect the USB cable from the Trinket and touch the sensor, everything goes unstable.  Fan and built-in led cycle on/off randomly at 0.5sec to 2sec intervals.
I've tried all different parameters for the library including the series resistor, sampling rate and frequency modes. I've checked grounds multiple times and this one is really stumping me.
I suspected fan noise early on so the most interesting experiment I've tried so far IMHO is to remove the 12vdc to the fan but keep it supplying the DC-DC converter for the 5v to the trinket-But, the onboard led has the same instability as when fan is connected.
Lastly, I used an Arduino Uno to develop the code and the circuit earlier and it worked fine without USB cable connected.
I feel so close.
Any suggestions or insights much appreciated.
Here is my code
/ touch - Capacitive touch demo using FreeTouch. Trinket M0 version.
// Note: the pin silkscreened 1 is Analog Pin 0.

#include "Adafruit_FreeTouch.h"

Adafruit_FreeTouch qt_1 = Adafruit_FreeTouch(A0, OVERSAMPLE_4, RESISTOR_0, FREQ_MODE_NONE);
int led = 13; // blink 'digital' pin 1 - AKA the built in red LED
int FAN = 2;  //

void setup() {
// initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(FAN, OUTPUT);
  digitalWrite(led, LOW);
  digitalWrite(FAN, LOW);
  delay(50);
  // Initialize A0 as a touch sensor
  if (! qt_1.begin())
    //Serial.println("Failed to begin qt on pin A0");
    digitalWrite(led, HIGH);    // Turn on the led
}
void loop()
{
  int counter;
  int result = 0;
  counter = millis();
  result = qt_1.measure();
  if (result > 950) {
    digitalWrite(FAN, HIGH);    // Turn on the FAN
    digitalWrite(led, HIGH);    // Turn on the led
  }
  else {
      digitalWrite(FAN, LOW);    // Turn off the FAN
      digitalWrite(led, LOW);    // Turn off the led
  }
  delay(50);
}

Here is schematic

Not sure if I'm doing this right by posting an answer?
I didn’t expect this to be as complex!  Unfortunately adding the suggestion to add the capacitors did not change anything.
But the answer makes sense to me because when I think of why it worked so well on my Arduino Uno development circuit, it could have been because I was using the Capacitive Sense library which utilized two pins that to my understanding measured a RC type of decay to achieve the touch sensing.
Too bad that the Trinket doesn’t operate the same way.  And my programming skills are not strong enough to come up with a similar design solution as the Arduino Uno RC sensing.
So, I will try the idea in the answer where I implement the “side by side with a gap” touch sensor just for learnings sake.  I’ve seen these touch sensors often as traces on a pcb.
But I should share what my ultimate design goal is.
That is to make a touch sensitive art lamp that has a steel body. The lamps are diodes and diodes strips which will be brightness controlled with a PWM input.  So, there is no need for an AC connection other than for the wall transformer which supplies DC.  The design needs to sense a touch whenever someone touches anywhere on the lamp body so that the SW can simulate a three-way switch.  So, a “side by side” gap doesn’t work in this application.  I was hopeful that the Trinket would work since I had everything working in my Arduino proto.  And I’m really looking for a “small” trinket type board solution to fit in the lamp.  In the past I have been successful achieving this functionality with AC power lamps by using those replacement touch circuit modules for 3-way AC switched bulbs.  But for this I wanted to use LED energy saving light sources with a microcontroller.
I think I will try to research “dedicated or discrete” touch sensing circuits that can give me digital input to the Trinket when a touch is sensed on the lamp body.
Any other suggestions/comments are greatly appreciated.
Cheers

What would happen if you connected the USB cable ground with a jumper wire to the 12v. power supply ground without plugging in the USB cable?

As far as I can tell from Trinker M0 schematic, there should be no difference by powering via VBUS or VBAT. So here are a few of suggestions that you could try, 1) add a 10uF e-capacitor at the output of your DC-DC converter (i.e. between 5V and ground), 2) add another 0.1uF between VBat and GROUND near the VBat pin. 3) You should also add a protection diode (1N4148 or equivalent) between the fan by connecting the cathode of the diode to +12V and anode to pin 1 of Q1. 4) reduce the expose or the surface of the aluminium foil, as it might be too sensitive and acts like an antenna...

Have you tried putting another foil connected to ground near the sensing foil? Capacitive touch sensors work by building a capacitor between the input pin and ground whose capacity is changed by the finger. Bringing to devices ground near the foil might help

The problem is most likely your power supply coupled with the poor design of the capacitive sensing system.
The capacitive sensing is done by measuring the capacitance between your foil plate and "ground". That "ground" is usually a connection through the USB cable and your computer's power supply through the earth wire of your power cable to the physical ground, so you are then between the two "plates" of the capacitor.  That ground connection is "clean". For a laptop the "ground" is usually just the case of the laptop or metal parts of the internals. This has no, or little, power supply noise.
However when you use a USB power supply you no longer have that "clean" connection. Instead your "ground" is going through the negative lead of the USB into the negative rail of the USB power supply which is then capacitively coupled to the neutral of the mains through a "class Y" capacitor across the transformer (there to remove inductive switching noise). That capacitor handles some quite high voltages and lots of noise, so you get that noise also reflected into your USB "ground", meaning the ground that you are using in your capsense "capacitor" is really quite noisy. Noisy enough to make your readings meaningless. On some laptops you may even notice a change when you plug the charger in compared to running on batteries for this same reason. (It's also why some early aluminium Apple laptops could give you an electric shock if you used them while plugged in...)
If you look at proper capacitive sensing arrangements you will see that the aren't just a bit of metal foil. They are properly arranged traces on a PCB which not only include the "sense" side but also the "ground" side of the capacitor. Your finger then affects the capacitance between these two points, not between a bit of foil and the floor of your room.
You should get a piece of cardboard and glue two pieces of foil side by side on it with a small gap between them. Then connect one of them to the Arduino's ground and the other to your input pin. Then recalibrate your readings to work with the new arrangement. You should find it far more stable and reliable.


text:
Multiple unique I2C devices interfere
I'm trying to make a fairly simple program that interfaces with the Adafruit TSL2591 light sensor as well as a MAX30102 pulse oximeter. They both use I2C for communication. I'm using the recommended libraries for both, Adafruit_TSL2591_Library Version 1.4.3 and SparkFun_MAX3010x_Sensor_Library Version 1.1.2 respectively. This is all running on an Arduino UNO, although I will be transferring it to a NANO in the near future. All of the following is using Version 2.0.2 of the Arduino IDE.
The issue I'm running into is that both sensors will work perfectly fine in isolation, but when trying to run at the same time it locks up and outputs nothing.
Example code that works for the Light sensor.
Example code that works for the pulse oximeter.
I know my wiring is good because the sensors work individually with either program even when both sensors are plugged in simultaneously.
The code that almost works:
#include <Wire.h>
#include "MAX30105.h"
#include "spo2_algorithm.h"
#include <Adafruit_Sensor.h>
#include "Adafruit_TSL2591.h"

MAX30105 particleSensor;

const byte LUX_ADDR = 0x29;
const byte OX_ADDR = 0x57;

Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591);

#define MAX_BRIGHTNESS 255

#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
//Arduino Uno doesn't have enough SRAM to store 100 samples of IR led data and red led data in 32-bit format
//To solve this problem, 16-bit MSB of the sampled data will be truncated. Samples become 16-bit data.
uint16_t irBuffer[100]; //infrared LED sensor data
uint16_t redBuffer[100];  //red LED sensor data
#else
uint32_t irBuffer[100]; //infrared LED sensor data
uint32_t redBuffer[100];  //red LED sensor data
#endif

int32_t bufferLength; //data length
int32_t spo2; //SPO2 value
int8_t validSPO2; //indicator to show if the SPO2 calculation is valid
int32_t heartRate; //heart rate value
int8_t validHeartRate; //indicator to show if the heart rate calculation is valid

void setup()
{
  Serial.begin(115200); // initialize serial communication at 115200 bits per second:

  // Initialize sensor
  if (!particleSensor.begin(Wire, I2C_SPEED_FAST, OX_ADDR)) //Use default I2C port, 400kHz speed
  {
    Serial.println(F("MAX30105 was not found. Please check wiring/power."));
    while (1);
  }

  byte ledBrightness = 60; //Options: 0=Off to 255=50mA
  byte sampleAverage = 4; //Options: 1, 2, 4, 8, 16, 32
  byte ledMode = 2; //Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
  byte sampleRate = 100; //Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
  int pulseWidth = 411; //Options: 69, 118, 215, 411
  int adcRange = 4096; //Options: 2048, 4096, 8192, 16384

  particleSensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange); //Configure sensor with these settings

  light_sensor_details();

  light_sensor_configure();

}

void loop()
{
  bufferLength = 100; //buffer length of 100 stores 4 seconds of samples running at 25sps

  //read the first 100 samples, and determine the signal range
  for (byte i = 0 ; i < bufferLength ; i++)
  {
    while (particleSensor.available() == false) //do we have new data?
      particleSensor.check(); //Check the sensor for new data

    redBuffer[i] = particleSensor.getRed();
    irBuffer[i] = particleSensor.getIR();
    particleSensor.nextSample(); //We're finished with this sample so move to next sample

    Serial.print(F("red="));
    Serial.print(redBuffer[i], DEC);
    Serial.print(F(", ir="));
    Serial.println(irBuffer[i], DEC);
  }

  //calculate heart rate and SpO2 after first 100 samples (first 4 seconds of samples)
  maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);

  //Continuously taking samples from MAX30102.  Heart rate and SpO2 are calculated every 1 second
  while (1)
  {
    //dumping the first 25 sets of samples in the memory and shift the last 75 sets of samples to the top
    for (byte i = 25; i < 100; i++)
    {
      redBuffer[i - 25] = redBuffer[i];
      irBuffer[i - 25] = irBuffer[i];
    }

    //take 25 sets of samples before calculating the heart rate.
    for (byte i = 75; i < 100; i++)
    {
      while (particleSensor.available() == false) //do we have new data?
        particleSensor.check(); //Check the sensor for new data

      redBuffer[i] = particleSensor.getRed();
      irBuffer[i] = particleSensor.getIR();
      particleSensor.nextSample(); //We're finished with this sample so move to next sample

      //send samples and calculation result to terminal program through UART
      Serial.print(F("red="));
      Serial.print(redBuffer[i], DEC);
      Serial.print(F(", ir="));
      Serial.print(irBuffer[i], DEC);

      Serial.print(F(", HR="));
      Serial.print(heartRate, DEC);

      Serial.print(F(", HRvalid="));
      Serial.print(validHeartRate, DEC);

      Serial.print(F(", SPO2="));
      Serial.print(spo2, DEC);

      Serial.print(F(", SPO2Valid="));
      Serial.println(validSPO2, DEC);
    }

    //After gathering 25 new samples recalculate HR and SP02
    maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);

    light_sensor_read();

  }
}

void light_sensor_details () {

  sensor_t sensor;
  tsl.getSensor(&sensor);

  delay(500);

}

void light_sensor_configure () {

  delay(200);
  tsl.setGain(TSL2591_GAIN_MED);
  delay(200);
  tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS);
  delay(200);
  tsl2591Gain_t gain = tsl.getGain();

}

void light_sensor_read() {

  uint32_t lum = tsl.getFullLuminosity();
  uint16_t ir, full;
  ir = lum >> 16;
  full = lum & 0xFFFF;

  Serial.print(F("Lux: ")); Serial.println(tsl.calculateLux(full, ir), 6);
}

The pulse oximeter part will function correctly with the last two lines of setup() and the last line of loop() commented. light_sensor_details();,light_sensor_configure(); and light_sensor_read(); respectively. The output with these two lines commented is as follows:
red=4229, ir=3967
red=4530, ir=3790
red=3629, ir=4104
red=3563, ir=5211
red=4555, ir=9076
red=7091, ir=16753
red=13068, ir=23695
red=10753, ir=11273
...
red=31031, ir=48271, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=31044, ir=48283, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=31017, ir=48289, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=31027, ir=48306, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=31022, ir=48291, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=31016, ir=48271, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=30997, ir=48294, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=30981, ir=48268, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=30966, ir=48289, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=30981, ir=48293, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
...

(An expected output given my finger wasn't on the sensor for this.)
If I uncomment the 2nd last line of setup() then it still manages to show the red and ir values but never starts to show the calculated values. Instead it will occasionally (unpredictably) show chunks of invalid characters, like so:

Going further and uncommenting the other two lines simply locks up and prints nothing to the serial monitor.
Also to clarify the three light sensor related functions do work in their own file, I'll include it here for the sake of completeness:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_TSL2591.h"

Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591);

void setup()
{
  Serial.begin(115200); // initialize serial communication at 115200 bits per second:

  light_sensor_details();
  light_sensor_configure();
}

void loop()
{
  light_sensor_read();
}

void light_sensor_details () {

  sensor_t sensor;
  tsl.getSensor(&sensor);

  delay(500);

}

void light_sensor_configure () {

  tsl.setGain(TSL2591_GAIN_MED);
  tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);

  tsl2591Gain_t gain = tsl.getGain();

}

void light_sensor_read() {

  uint32_t lum = tsl.getFullLuminosity();
  uint16_t ir, full;
  ir = lum >> 16;
  full = lum & 0xFFFF;

  Serial.print(F("Lux: ")); Serial.println(tsl.calculateLux(full, ir), 6);
}

Running this outputs:
...
Lux: 41.283641
Lux: 36.879783
Lux: 10.549278
Lux: 2.826355
Lux: 11.158865
Lux: 1.489472
Lux: 1.713600
Lux: 31.461915
Lux: 48.357471
Lux: 50.827312
...

I think the issue is something to do with the I2C bus, but because both sensors use their own libraries for communication I can't use the online examples for manually starting and stopping communication with the Wire library. I can't find anyone else online with this issue or any examples of multiple I2C devices that I'm able to make use of (to my understanding).
Am I on the right track with it being an I2C problem? Is there a simple fix that I'm simply unaware of? Or is there a separate issue with my code?
Many thanks for any help!
Edit: Changed Title

It turns out the issue was with limited dynamic memory. The MAX30105 requires a lot of space for its calculations and adding anything else, whether that be another sensor or even a software serial connection, would crash it. Even using Serial.println() put it over the edge. It became unstable beyond around 89% full, or about 250 bytes of empty dynamic memory.
I ended up using a 32u4 equipped board to solve the memory issue and it worked perfectly after that.
It had nothing to do with I2C.


text:
Nano 33 BLE Sense powered with Vin and USB at the same time
I have a project where I would like to power an Arduino Nano 33 BLE Sense
with USB and Vin at the same time.
The idea is to charge an external LiPo 3.7V through a charger module
that would take the load from the 3.3V pin (that would be powered through USB)
and at the same time keep powering the Arduino through Vin
because I want to avoid a power interruption when I unplugged the USB cable
that would interrupt the writing operation (on a text file on an SD card).
So the goal is to prevent data corruption on a writing operation on a text file.
I know text files are supposed to be less corruptible (compared to a database)
but I want to be sure the operation would be uninterrupted.
I've seen this post:
What happens if I power the Arduino with both the USB and external power voltage simultaneously?
But it's related to the Arduino UNO R3.
It basically says:
When Vin >6.6V the opamp turns the mosfet off.

so the USB disconnects.

When Vin <6.6V the opamp turns the mosfet on.

so the USB stays connected.

On Arduino's website:
https://store-usa.arduino.cc/products/arduino-nano-33-ble-sense
it says:

Vin: This pin can be used to power the board with a DC voltage source.
If the power is fed through this pin, the USB power source is disconnected.

It does not mention from what voltage it would disconnect the USB power.
I did not find the same schematic for the Arduino Nano 33 BLE Sense.
Just this:https://docs.arduino.cc/hardware/nano-33-ble-sense

Interactive Viewer
Interact with the schematics, the PCB and a 3D model of the product.

and this: https://docs.arduino.cc/static/353d3c445c28b1da1fe1f9d6eafa948d/ABX00031-schematics.pdf
I'm not very familiar with reading schematics but I could not find similar information about vin and USBVCC.
That'd be great if somebody had some insight on that.
I would welcome any suggestion.
Cheers!

If I connect a battery charger/controller on VIN, my battery would be protected.
And I could connect a booster 5V and add a shottky diode so its connection to VIN would be closed if booster+ < VIN
Like this ?

In this power block you can see there is only one Schottky diode with the voltage drop under 0.5V@2A. That means D2 is closed around the condition: VUSB < VIN.
On the other side if you add 3.6-4.2V battery on VIN there will be current flowing from VUSB to battery.
Basically you need another shottky diode Bat+ -> [A|K] -> VIN  so when there is bigger voltage on the VIN it'll "shut off" the battery (otherwise it'll be charged by almost 5V)
Depending on the application and sensors you are planning to use, you might want to consider for example Seeed Studio XIAO nRF52840 Sense that has battery charging circuit and pads for the battery on the bottom (although it's not the "bread board" pins)

That's awesome!
Thanks for the details.
I thought I had to charge the battery through the 3.3V.
But what you are showing is that VUSB feeds VIN.
So if I connect a battery charger/controller on VIN,
my battery would be protected.
And I could connect a booster 5V
and add a shottky diode so its connection to VIN would be closed
if booster+ < VIN
I even like the option with Seeed Studio XIAO nRF52840 Sense better.
It's smaller than the Arduino 33 BLE Sense
and it's got a USB-C connector.

Do you even need booster? If you don't need 5V, you can use VIN for charging only and 3V3 output from accu. Definitely not step up connected to charging input

I need a booster because the minimum operating input voltage on VIN is 4.5V (on the Arduino 33 BLE). And I want to use a small 3.7v LiPo battery.


text:
Error in using buttons to input numbers!
This is a mini project of mine, which is to be implemented in another.
Here, I'm trying to make arduino output numbers in the serial window based on the diff. buttons pressed(there are four of them in my case).
What I want:

the initial array is 0000.
if I press button one, then button three, the array should be 1010
if I press button one two times, and button 4 three  times, the
resultant array should be 2003......and so on.you might have got what
I'm trying to do here.   the problem is , all I'm getting is 0000,
ALL THE TIME.

My code is below, and I'm a newbie, so any corrections(+advice?) given would be greatly appreciated.
(Also I don't know where to print the output :P I did it in loop() so it keeps on printing it :P)
CODE:

//the buttons:

const int b1=8;
const int b2=9;
const int b3=10;
const int b4=11;
//variables to store previous button press and currend button press , used to eliminate switch bouncing
boolean pb1=LOW;
boolean cb1=LOW;

boolean pb2=LOW;
boolean cb2=LOW;

boolean pb3=LOW;
boolean cb3=LOW;

boolean pb4=LOW;
boolean cb4=LOW;

//variables to store numbers:

int w=0;
int x=0;
int y=0;
int z=0;

int var_array [4]={w,x,y,z};

void setup() {
  // put your setup code here, to run once:
  pinMode(b1,INPUT);
  pinMode(b2,INPUT);
  pinMode(b3,INPUT);
  pinMode(b4,INPUT);

 Serial.begin(9600);

}

boolean debounce1(boolean last)
{
   boolean current=digitalRead(b1);
  if(last != current)
  {
      delay(5);
    }
      current=digitalRead(b1);
      return current;
  }

boolean debounce2(boolean last)
{
   boolean current=digitalRead(b2);
  if(last != current)
  {
      delay(5);
    }
      current=digitalRead(b2);
      return current;
  }

  boolean debounce3(boolean last)
{
   boolean current=digitalRead(b3);
  if(last != current)
  {
      delay(5);
    }
      current=digitalRead(b3);
      return current;
  }

  boolean debounce4(boolean last)
{
   boolean current=digitalRead(b4);
  if(last != current)
  {
      delay(5);
    }
      current=digitalRead(b4);
      return current;
  }

void loop() {
  // put your main code here, to run repeatedly:
  cb1=debounce1(pb1);
  cb2=debounce2(pb2);
  cb3=debounce3(pb3);
  cb4=debounce4(pb4);

     if (pb1==LOW&&cb1==HIGH)
   {
      w++;
    }
    pb1=cb1;

    if (pb2==LOW&&cb2==HIGH)
   {
      x++;
    }
    pb2=cb2;

    if (pb3==LOW&&cb3==HIGH)
   {
      y++;
    }
    pb3=cb3;

    if (pb4==LOW&&cb4==HIGH)
   {
      z++;
    }
    pb4=cb4;

for(int i=0;i<4;i++)
Serial.print(var_array[i]);

Serial.println();

delay(500);

}

At first glance it looks like your problem is you have a fraction of a millisecond where the buttons are being read. The rest of the time you are stuck in a delay.

In your C program all the variables including the array occupy their own space in memory.  In the line "int var_array [4]={w,x,y,z};" all you did was create 4 more variables (elements of the array var_array) in memory and initialized them to the values found in variables (w, x, y & z) in a different part of memory.  So when you incremented the variables in memory pointed to by the names w, x, y and z... you did nothing to the variables in memory pointed to by the elements of the var_array.
For example, in this program:
main()
{
 int w=0;
 int x=1;
 int y=2;
 int z=3;

 int var_array [4]={w,x,y,z};

 printf("w %d x %d y %d z %d\n",w,x,y,z);
 printf("var_array %d %d %d %d\n", var_array[0],var_array[1],var_array[2],var_array[3]);

 w += 1;
 x += 2;
 y += 4;
 z += 5;

 printf("w %d x %d y %d z %d\n",w,x,y,z);
 printf("var_array %d %d %d %d\n", var_array[0],var_array[1],var_array[2],var_array[3]);
}

The output is this:
w 0 x 1 y 2 z 3
var_array 0 1 2 3
w 1 x 3 y 6 z 8
var_array 0 1 2 3

Notice how the array values do not change.
If you really want to do this, you need to make the array var_array an array of pointers and point each element to each variable (w, x, y & z).
For example:
main()
{
 int w=0;
 int x=1;
 int y=2;
 int z=3;

 int * var_array [4]={&w,&x,&y,&z};

 printf("w %d x %d y %d z %d\n",w,x,y,z);
 printf("var_array %d %d %d %d\n", *var_array[0],*var_array[1],*var_array[2],*var_array[3]);

 w += 1;
 x += 2;
 y += 4;
 z += 5;

 printf("w %d x %d y %d z %d\n",w,x,y,z);
 printf("var_array %d %d %d %d\n", *var_array[0],*var_array[1],*var_array[2],*var_array[3]);
}

Now produces this output:
w 0 x 1 y 2 z 3
var_array 0 1 2 3
w 1 x 3 y 6 z 8
var_array 1 3 6 8


text:
How to perform a data transfer to an external server
So I'm doing a project that involves getting sensor data from several sensors, and then sending them to an external server when a tragic occurs. But I've been having trouble figuring out how to send this data, and I am welcome to advice (I'm still relatively new to Arduino coding).
I'm using an Arduino mega, with a sim900 GSM shield and an SD card. The sensors are just analog reads and a GPS.
I've looked into FTP, a Xively account and http requests to a web server but couldn't figure it out.

Do you have internet service in that GSM shield?

Yup. The shield has a SIM card with 3G

You should check for: "Sim900 HTTP POST" on Google. There also should be a lot of libraries for this. You'll have to set up a webserver that accepts HTTP post messages. But you might try using a post dump test server first (https://posttestserver.com/) this worked great for me in the past. But I had an PIC microcontroller.

There is a good example of using the SubmitHttpRequest() in this article:
GPRS Shield SIM900 Arduino
You could easily modify:
mySerial.println("AT+HTTPPARA=\"URL\",\"www.yourwebsite.com/testing.php\"");
to include a string of the sensor value, and then using a PHP script to MySQL on your webserver. Maybe something like:
http://yourwebsite.com/testing.php?sensor1=5&sensor2=10


text:
Turning a motor on and a led at the same time for a given time period
I need help with this code, I want to have a motor turn on for a given time and at the same time have an led light up to indicate it is on which will also turn of once the motor has stopped. It is controlled by A TECT5000 SENSOR, which acts like a switch to transfer a signal to the motor and LED.
At the moment, I can get the motor to turn on and off for a given time but not the LED. Every time I activate the circuit with the sensor it turns on and stays on or turns of and stays of. Here is the current code I am using.

// Program: Led drive using reflective optical sensor
// Author: Arduino e Cia

int outgoingsignal = 8 ; // Pin of led
int pinsensor = 7 ;   // Connected to the "collector" pin of the optical sensor
int reading;      // Stores information about sensor reading
int statusled = 0 ;
int motorPin = 9;  // define the pin the motor is connected to
                   // (if you use pin 9,10,11 or 3you can also control speed)
                   // Stores led status (on / off)

void setup ()
{
  pinMode (outgoingsignal, OUTPUT); // Defines the led pin as
  pinMode (pinsensor, INPUT);   // Defines the sensor pin as input
   pinMode(motorPin, OUTPUT);
}

void loop ()
{
  // Le the sensor pin information
  reading = digitalRead (pinsensor);
  if (reading != 1 ) // Checks if the object was detected
  {
    while (digitalRead (pinsensor)!= 1)
    {
     delay (100);
    }

    statusled =! statusled;
    // Reverses the status of the led (on / off)

    // Turns on or off the led as "statusled"
    digitalWrite (outgoingsignal, statusled);
  motorOnThenOffWithSpeed(); }

}
void motorOnThenOffWithSpeed(){

  int onSpeed = 255;  // a number between 0 (stopped) and 255 (full speed)
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for

  int offSpeed = 0;  // a number between 0 (stopped) and 255 (full speed)
  //int offTime = 1000; //the number of milliseconds for the motor to turn off for

  analogWrite(motorPin, onSpeed);   // turns the motor On
  delay(onTime);                    // waits for onTime milliseconds
  analogWrite(motorPin, offSpeed);  // turns the motor Off
 // delay(offTime);                   // waits for offTime milliseconds
}

Easy three steps:

Connect the led to the motor control pin (via some means to limit the current).
Program your motor control pin to turn it on or off as you so desire.
Sit back and enjoy.

If you just want the led on with the motor then put a couple of digitalWrite statements in your motorOnThenOffWithSpeed function to turn the led on and off at the same time you turn the motor on and off.


text:
74HC595 shift register not working
I got my Arduino kit a few days ago and I've been going through some of the tutorials.
I got to the 8 LEDs with a shift register tutorial, where I got stuck. Nothing would light up after I plugged everything in and uploaded the sketch.

This is the circuit I've attempted to recreate using Fritzing, and the following is the code I used, from the tutorial :

int tDelay = 100;
int latchPin = 11;      // (11) ST_CP [RCK] on 74HC595
int clockPin = 9;      // (9) SH_CP [SCK] on 74HC595
int dataPin = 12;     // (12) DS [S1] on 74HC595

byte leds = 0;

void updateShiftRegister()
{
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, LSBFIRST, leds);
  digitalWrite(latchPin, HIGH);
}

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{
  leds = 0;
  updateShiftRegister();
  delay(tDelay);
  for (int i = 0; i < 8; i++)
  {
    bitSet(leds, i);
    updateShiftRegister();
    delay(tDelay);
  }
}

I have also attempted to use an 8-segment digit display using the same shift register, also failing.
Is there something wrong that I am doing or could it be that the little chip is broken?
I accidentally discovered that when I swap the ground from pin 8 on the 595 to 5V, all the LEDs will light up.
Update : I got the same circuit in Tinkercad, some kind of Arduino simulator.
After dropping in the code and running the simulation, after it lights up the 5th LED, I get this warning :

However, when I change the 220 ohm resistors to something like 500 ohm resistors, that pop-up is gone. Could this be another reason of why my chip could be possible broken at the moment?

LEDs light up because of protection diodes on the inputs/outputs. You've got negative voltage on the outputs, so current flows.
I'd worry about OE input, as it's hardwired to the ground. Protection diodes are for the small currents only so i'd expect burning protection diode and after that /OE might get destroyed.

BTW: code + schematics is working.

Okay... thanks for confirming that. Guess I'll have to buy a new shift register... the issue is I have no idea where in the town I can get electronics like that. Thank you, anyway!

And check if connections in breadboard aren't too loose. I've got one dead "pixel" because of it.

I tried the config in different places on the breadboard and with different wires... same result.

the power and ground rails on breadboards are sometimes interrupted int the middle of the breadboard

A few thoughts
Connecting 5v to pin 8 (=gnd) is not a good idea.  It may not cause any damage if pin 16(=vcc) is also connected to 5v but i would not rely on that. Generally reverse voltage will kill all electronics unless they are specifically protected against it.
For the LEDs I would use 1k to 10k ohm resistors.  This is giving still enough current to see them light up. Using 330ohms just takes more current and makes the leds extremely bright (3mA is enough).
For testing whether something simple is working, like a shiftregister, flipflop, or logic gate, I would not use a microcontroller at all. You can just use a couple of switches attached to the CLK and LATCH pins, with a slide switch attached to the DATA pin to select 1 or 0 input bit. This eliminates one point where stuff can go wrong.
Whether or not you put in a bypass cap will not make a difference if your supply is sufficiently capable and stable. I use the charger of my broken laptop that can deliver 5v at up to 2.5amps. In this setup I don't need any bypassing, although it's still best practise to include it.
Adding LEDs to the serial IN, latch, and shift clock, and serial output may also help nail down the problem.
Also make sure you don't have dodgy cables. If any of the wires is broken or has microscopic internal breaks this can lead to misbehaviour and is very difficult to find.
One thing I did when I tried if my chips worked was to first use a known good chip from a colleague to confirm the circuit was ok.
Depending on where you take your power from, adding a power LED is usually a good idea as well. If you power everything from a powerbank you may find that some of them just shutoff the outputs if there is less than a certain threshold current flowing out.  This can leads to effects like "the circuit worked for 30 seconds and then died. After disconnecting and waiting a couple of seconds and repluging the power it works again..."  For this reason I include a power LED in just about every project of mine.

Your answer seems to be getting some down votes. Perhaps if you took the trouble to properly construct English sentences that would help? Sentences start with a capital letter, and the word "I" is capitalized. This isn't a mobile phone message.

Really? That seems unduly harsh to down vote an answer because it is not punctuated and does not start sentences with capitals correctly. I also could not see that as a reason in the help center https://arduino.stackexchange.com/help/privileges/vote-down . Now if it were the English literature SO community, I would tend to agree. It is a shame that people are not required to give a reason for the down vote... I to have received several on the arduino site and often have no clue why.

This is a good discussion on troubleshooting best practice (especially e.g. the point about testing with switches instead of microcontroller code).  I've made the grammatical edits, and removed some of the unnecessarily provocative phrases ("stupid idea", etc.)

The only way i found to make this circuit to work
is by putting  8 pullup resistors (1k) from vcc
to each of the output pins of the 74hc595 whithout
them no leds light up ever.

One omission I see is that you don't have a bypass capacitor across Vcc and Gnd of the 74HC595. Without it you would have inconsistent operation.
But if you had the power reversed on the chip then that will be the major problem and I'm sure the chip is damaged.
What I would do is put leds on the clock, data, and latch lines. And then make your delay very long, 1 second, so that you can see what the lines are doing. Just to confirm that you are getting the output that you expect. But first put a bypass cap across the chip.
Also double check that your leds are in the right way.

I'm quite a newb in the electronics field, may I ask what am I supposed to do, in a step-by-step fashion? I followed the guide I got with the kit and it didn't have any capacitors involved. The LEDs are the right way, I tried each one of them out before and they all light up.


text:
Is Arduino's USB communication protocol the same as USB modems use?
An Arduino Uno uses for the default USB communication either an FTDI chip in early versions or a microcontroller that emulates/replicates the FTDI chip communication.
Is this type of USB communications the same as the Conexxant CX930xx modems use as well?
What I want to achieve is to emulate the nessesary AT commands using the ATCommand library to replicate the modem's AT command instruction set. The things that I want to emulate are:

The modem USB communication
The subset of AT commands required for enabling/disabling an incomming call with Caller id
Returning a "fake" incoming call with or without CallerId depending on the provided options from the PC via the AT commands

For the last two I can somehow manage. But I don't know whether the existing FTDI chip/USB microcontroller uses the nessesary protocols that modems use as well. I mean would it be enough if I just replace the hardware and vendor ID or do I need to emulate another type of USB communication as well?
The modem that I want to emulate is the: https://support.lenovo.com/us/en/solutions/pd003647-lenovo-usb-modem-overview
What I want to achieve is to fake an incomming call instead of using the actual modem. The reason why is, because I want to provide my own data towards modem-interfacing desktop application that use CallerId. Instead of using the actual modem I would love to have a fake one where I can emulate various scenarios.

What modem are you talking about. They also make modems that are RS232 which would be a bit easier to interface with. I would suggest using a Mega because it has a second serial port, other boards will work as well. Try these links they may have something you may like: https://www.radi.com/modular29.htm or https://www.radi.com/modular51.htm

I am talinkg for this modem https://www.easytechnology.gr/plerophorike-kai-tablet/upologistes/diktuaka/exoteriko-usb-fax-modem-me-anagnorise-kleseon-oem It is a USB one and is used for CallerId applications. I want to emulate it and send to the PC fake incomming calls like a normal modem would do.

to the OS, the arduino looks like a serial port without a connected modem

Commonly USB modems use two layers of communication that are relevant for your issue.

A virtual serial communication device, known as CDC/ACM, Communication Device Class, and Abstract Control Model, respectively.

Modem control protocol, known as Hayes command set, vulgo "AT command set", on top of this.

Both layers are generally independent of each other. You can use the virtual serial communication for any other purpose. And you can transport the Hayes commands and replies over any other communication stream.
Most Arduino compatible devices reveal themselves as CDC/ACM to a PC, you can check this for example on Windows in the Hardware Manager. Therefore, the underlying transport layer exists for you.
But to answer your concrete question: No, the second layer (AT commands) is missing. It is not necessary for the upload process or the serial monitoring.
But you can write a sketch that implements that set of commands you would like use use for your application.

So I need to change the Vendor Id at Uno's Mega 16u2/8U2 and just make it to be seem as any modem I want to and via the sketch on MEGA 328p to emulate the AP command instruction set right;

In the comment above assume that I already have a sketch that emulates the hayes command set.

Yes, that should work. Does the PC application or the PC driver need this specific VID/PID to accept the device? CDC/ACM was meant to be VID/PID independent...

Well some applications that I need to use may require that (eg. during modem detection)


text:
Why modem driver is loaded and used from my linux machine in order to communicate with Arduino?
Once I plugin an arduino to my linux machine the following response is retrieved (via dmesg):
[ 7250.906241] perf: interrupt took too long (2504 > 2500), lowering kernel.perf_event_max_sample_rate to 79750
[ 9517.599165] usb 1-3: new full-speed USB device number 5 using xhci_hcd
[ 9517.749504] usb 1-3: New USB device found, idVendor=2341, idProduct=0043, bcdDevice= 0.01
[ 9517.749510] usb 1-3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[ 9517.749513] usb 1-3: Manufacturer: Arduino (www.arduino.cc)
[ 9517.749516] usb 1-3: SerialNumber: 7533131313335170A061
[ 9517.780753] cdc_acm 1-3:1.0: ttyACM0: USB ACM device
[ 9517.781046] usbcore: registered new interface driver cdc_acm
[ 9517.781047] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

The last line from dmesg caught my attention:
[ 9517.781047] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

Also as far as I remember in order to communicate with arduino my user needs to be into dialout group. Does that mean that a modem communication protocol is used in order to communicate from/to arduino in order to communicate via USB?

linux questions belong at https://unix.stackexchange.com/questions , not here

@jsotola I disagree. While the answer is in the linux domain, the question in and of itself asks whether there is "some modem protocol" happening between PC and Arduino.

The answer to that is one of history.
There was a time when the main purpose of the serial port (RS-232/UART) was to "dial out"; i.e. it had a serial connection to a modem, fax machine or a mainframe attached. Whatever it was, the primary function was to provide a data connection to the outer world, possibly incurring charges on a phone line. So, it is the other way round than you guessed: The computer communicated with the modem using a serial protocol named RS-232 or UART.
Therefore, all serial ports have been secured to not allow access, except for the user group "dialout". This has been retained as default, even for emulated and virtual serial ports -- like, for example, serial port over USB.

So if I want my arduino to emulate a modem would the arduino's (Arduino UNO) typical out of the box USB communication be considered one that also modems use as well?

@DimitriosDesyllas Yes. A "serial connection" is basically just a bidirectional channel to send and receive bytes. What those bytes mean is up to the programs at either end and it is irrelevant whether this connection is a classic serial port, an emulated Serial-over-USB port or anything else. All your modem dialer program needs to know is "the modem is on serial port /dev/ttyS0". The dialer just sends a series of "AT commands" onto the serial line, waits for the modem to connect and acknowledge, then assumes that the same serial line is now connected through to its destination.


text:
Camera on mkr1000 or nodemcu 0.9
My question is: it is possible to connect camera on an Arduino/Genuino mkr1000 or to a NodeMCU 0.9?
If yes which one?
As far as I now ArduCam OV2640 has ported a library for ESP8266 (that is the chip inside the nodemcu)? Where can I find it and how does I plug the camera to the board?
Reading the camera user guide I've found that:

The ArduCAM mini can be used in any platforms like Arduino, [...] as long as they have SPI and I2C interface

Does one of these 2 board have both SPI and I2C interfaces
EDIT: Here I list my personal search with possible interesting results:

Here is a guide of arducam on ESP8266 module ESP-12E (My nodemcu is ESP-12)
Here another guide for ESP8266-12E

I hope that can be useful the wiring scheme to ESP8266-12E
     ArduCAM mini   ->    ESP8266-12E
         CS         ->        D0
        MOSI        ->        D7
        MISC        ->        D6
         SCK        ->        D5
         GND        ->       GND
         VCC        ->       3V3
         SDA        ->        D2
         SCL        ->        D1

Why the downvote?

Because you didn't do any research yourself. The linked MKR1000 site mentions it and figuring it out for the NodeMCU isn't hard either.

@gre_gor I've added also other research. I asked only if it was possible on my board. Everywhere I find only sketches and examples for ESP8266-12E. I cannot be sure if it works or not so I am asking here.
The question was if any cam is working there, my idea was the arducam that I linked. I make the question because it seems possible that the cam works but I've no certainty.
Sorry if I don't know what are those 2 interfaces but from wikipedia I don't understand much.
Tell me what do you want from me to prove that I made researches, I've linked all the stuff that can be useful.

There are a couple of levels of names in your question, so here are how they fit together:
ESP8266 - This is the bare chip found in the wide range of "esp8266"-based boards/modules/etc. The chip itself has no flash storage, no clock/oscillator, and no voltage regulation.
The I/O pins on the ESP8266 bare chip have labels like GPIO0, GPIO1, etc.

Chip outlined in Red is the ESP8266 alone.
So, to be of much use, the chips are often found on other modules along with flash memory, an oscillator, perhaps voltage regulation, a PCB antenna for the wifi portion, etc.
A popular "brand" of such module is the AI-Thinker modules, with names like

ESP-01
ESP-07
ESP-12
ESP-12E
ESP-12F

The different modules have different PCB sizes, but most notably, different numbers of pins from the actual ESP8266 chip brought out to the module's pins.
These often also call the I/O pins names like GPIO0, GPIO1, etc.

These ESP-xx modules, in turn, are often incorporated into larger modules that then add a USB-serial chip, LEDs, etc. One popular line are the NodeMCU series.
These modules provide different names for the I/O pins. NodeMCU in particular uses D0, D1, etc. and these don't correspond to the same numeric suffix as the bare chip. This chart gives the mappings for NodeMCU modules.

ANSWER
Thus, in the web page you linked about the ArduCAM and ESP8266, you can see a chart on the Hardware Connection of the the ArduCAM pins, and equivalent pins for both the NodeMCU-style pin names, and also the AI-Thinker and bare chip pin names.
The ESP-12 and ESP-12E both have the exact same ESP8266 chip inside, and the same amount of flash memory. There is no difference between them as far as connecting to the ArduCAM is concerned. The ESP-12E has a few more pins brought out to the headers than the ESP-12.
So, as long as you have D0, D1, D2, D5, D6, and D7 on a NodeMCU, OR GPIO4, GPIO5, GPIO12, GPIO13, GPIO14, and GPIO16 on the AI-Thinker module, then you can hook up the ArduCAM, as these are all the pins described in the hookup table.

Thank you for the explanation and the answer. This is far better than what I expected!


text:
Triple-click reset option to erase existing program
My Adafruit Feather M0 has two reset options I know of:

single click restarts existing program
double-click listens for an upload for a few seconds, then restarts existing program

Is there another option to have an existing program erased or replaced with something benign like a blinker, e.g.

triple-click erases existing program and listens for upload indefinitely

If not, what is the level of difficulty to modify the standard bootloader to implement this option?
NOTE
The rationale for this option is to recover a bricked board, e.g. with USB port turned off by a low power mode, so the regular software upload doesn't work any longer, at least without some trickery.

Isn't the bootloader open-sourced? Did you look for it?

Which Arduino? Single click of what exactly?

@NickGammon Tripple-click reset in the title, strongly suggest clicking the reset button. Arduinos with USB firmware upload capability.

You still haven't answered "which Arduino?" Is it a secret? In any Arduino the reset button resets it, there is no such thing as double-clicking reset. And certainly not triple-click. Resetting invokes the reset circuitry which makes the processor go through its reset code, clearing all registers and starting the code from the start.

@NickGammon Not a secret. I'm using clones of Zero, but I'm looking for something applicable to more than just a single model. there is no such thing as double-clicking reset - bootloader on my board responds to double-click on reset button differently, perhaps by saving state in NV memory.

how should erasing the old sketch help? double reset is the way to put a 'bricked' Zero in bootloader mode and upload a sketch. it stays in that mode. it doesn't time out.

@Juraj it stays in that mode. it doesn't time out. Mine was timing out in a few seconds. I was using Adafruit Feather M0.

M0 is not Zero. M0 bootloader times out. you can replace the bootloader to Zero bootloader if you have a SWD programmer

I was using Adafruit Feather M0 - you could have mentioned that at the start.

Next time, put that information in the question. That's where it belongs.

Now that we know the board type (Zero) — which took a couple of questions to elicit — it is possible to give a reasonable answer. Had it been a Uno I would have said that no, it doesn't do that, and it would take too much program space to implement it.

Is there another option to have an existing program erased or replaced with something benign ...

No, not that I am aware of, unless the documentation for the Zero says otherwise.

If not, what is the level of difficulty to modify the standard bootloader to implement this option?

Moderate, I would guess.
As for the Zero, with 256 KB of programmable memory it probably could be implemented by changing the bootloader. Any such change will, of course, reduce the amount of memory available for other tasks, but perhaps that isn't as big a deal if you start with 256 KB.
You would have to detect the triple-click somehow, for code running right after reset this could be tricky, but possibly achievable, as you say it has been for double-clicks.
Find the source code for the bootloader, see how it detects double-clicks, make it detect triple clicks, and have your "benign" program stored in the bootloader as a block of data ready to be copied into program memory.
There are a few alternatives you could consider:

If you have a spare pin in your project, make it so that if (say) pin 13 is grounded at startup, do nothing (other than go into a tight loop). This could be done before anything that might make reprogramming hard, like going into low power mode.

Reprogram it using SWD programming (rather than the bootloader). I don't know the exact details for the Zero, as I don't own one, but there must be a way, otherwise you wouldn't be able to put the bootloader onto it in the first place. Judging by what I read elsewhere the Atmel ICE is the device you need to reprogram it in that way.

Judging by what I read here you can access the bootloader by selecting Arduino Zero (programming port) as the board, and Atmel-EDBG as the programmer. Then you could tell the Atmel-EDBG to reprogram the board. My details here are hazy but you could look into that as an option.

I like the idea of using an extra pin for that purpose. Double-click works most of the time, but you have to synchronize your keystrokes and reset.

All Arduino bootloaders for boards with native USB support double reset as a way to activate the bootloader in case the sketch doesn't respond and fails to handle the USB. (The code linked from the Arduino core to your sketch handles the USB for MCU with native USB).
The M0 Arduino bootloader source code is in Arduino SAMD boards support package. Adafruit may use a modified version. The bootloader is strange because avrdude is used to upload over this bootloader and the board reports as ATmega to avrdude.
The M0 bootloader (and the ATmega 32u4 bootloader for Leonardo and Micro) have timeout after double reset. If no upload occurs some seconds after the double reset, they start the sketch.
You want to add a triple reset to replace the sketch which doesn't respond with a save sketch which will handle the USB and allow upload at any time. This would require to change the bootloader source, build the bootloader and use a SWD programmer to burn it (or create a sketch which replaces the bootloader).
Better option is what Arduino did for the Zero and MKR bootloader. The bootloader activated with double reset doesn't timeout with this bootloader and upload is possible anytime after double reset (until next reset or power-cycle).
The original M0 and Zero are almost the same board. One was sold by arduino.org other by arduino.cc. The most important difference is the bootloader.
It is possible to use M0 board as Zero with the Zero bootloader. By replacing the bootloader, you get the double reset without timeout. Other benefits are faster upload with bossac, the bootloader is half the size of the M0 bootloader and the Zero bootloader doesn't reset the internal RTC as the M0 bootloader does.