text:
Arduino Zero and micro SD card not working
I have an Arduino Zero processor (atsamd21g18a) with a microSD shield connected (check images of schematics)

The point is that I cant make it to work, not with sd.h sketch and not with sdfat.h sketch.
Chip-select for the SD card is A3 or digital pin 17.
sd.h sketch
#include <SPI.h>
#include <SD.h>

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  SerialUSB.begin(9600);
  delay(1000);

 while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  SerialUSB.print("Initializing SD card...");

  if (!SD.begin(A3)) {
    SerialUSB.println("initialization failed!");
    return;
  }
  SerialUSB.println("initialization done.");

  if (SD.exists("example.txt")) {
    SerialUSB.println("example.txt exists.");
  } else {
    SerialUSB.println("example.txt doesn't exist.");
  }

  // open a new file and immediately close it:
  SerialUSB.println("Creating example.txt...");
  myFile = SD.open("example.txt", FILE_WRITE);
  myFile.close();

  // Check to see if the file exists:
  if (SD.exists("example.txt")) {
    SerialUSB.println("example.txt exists.");
  } else {
    SerialUSB.println("example.txt doesn't exist.");
  }

  // delete the file:
  SerialUSB.println("Removing example.txt...");
  //SD.remove("example.txt");

  if (SD.exists("example.txt")) {
    SerialUSB.println("example.txt exists.");
  } else {
    SerialUSB.println("example.txt doesn't exist.");
  }
}

void loop() {
  // nothing happens after setup finishes.
}

sdfat.h code
const int chipSelect = A3;
/*
 SD card read/write

 This example shows how to read and write data to and from an SD card file
 The circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4

 created   Nov 2010
 by David A. Mellis
 updated 2 Dec 2010
 by Tom Igoe
 modified by Bill Greiman 11 Apr 2011
 This example code is in the public domain.

 */
#include <SdFat.h>
SdFat sd;
SdFile myFile;

pinMode(chipSelect, OUTPUT);

void setup() {
  delay(5000);
  SerialUSB.begin(9600);
  SerialUSB.println("Serial start");
  //while (!SerialUSB) {}  // wait for Leonardo
  //SerialUSB.println("Type any character to start");
  //while (SerialUSB.read() <= 0) {}
  delay(1000);  // catch Due reset problem

  // Initialize SdFat or print a detailed error message and halt
  // Use half speed like the native library.
  // change to SPI_FULL_SPEED for more performance.
  if (!sd.begin(chipSelect, SPI_HALF_SPEED)) sd.initErrorHalt();

  // open the file for write at end like the Native SD library
  if (!myFile.open("test.txt", O_RDWR | O_CREAT | O_AT_END)) {
    sd.errorHalt("opening test.txt for write failed");
  }
  // if the file opened okay, write to it:
  SerialUSB.print("Writing to test.txt...");
  myFile.println("testing 1, 2, 3.");

  // close the file:
  myFile.close();
  SerialUSB.println("done.");

  // re-open the file for reading:
  if (!myFile.open("test.txt", O_READ)) {
    sd.errorHalt("opening test.txt for read failed");
  }
  SerialUSB.println("test.txt:");

  // read from the file until there's nothing else in it:
  int data;
  while ((data = myFile.read()) >= 0) SerialUSB.write(data);
  // close the file:
  myFile.close();
}

void loop() {
  // nothing happens after setup
  SerialUSB.println("loop done.");
}

I am not sure if it is a hardware or software issue, but soldering and tracks are good.
Its like the hardware gets frozen, so I cant really see the serial messages. I know its not a serial issue because I can make a simple print serial script and it shows up. I think it might be related with libraries, or maybe some hardware limitation?
Can I use any pin as Chipselect? is digitalpin17 / A3 right?

what do you mean? PA04 is analogpin3 or digitalpin17 on samd21g18a . If you mean the comments on the sketches I use it is because they are examples of arduino and should work on any board as long as you change cs pin, thats why the second says pin4 as cs

Oop, yep, mis-remembered--pinout confirms.

Z1 to Z5 are varistors for overvoltage protection? Why does VDD of the SD card connect to 3.3V via a 1.69kOhm resistor and not directly? Can you check with a logic analyzer whether there is correct activity on the SD card's SPI bus? Also in the sdfat.h example you probably want to replace sd.initErrorHalt(); with { sd.initErrorPrint(); SerialUSB.flush(); } to get the error message.

Yes, z1 to z5 are varistors of 3,3V. I could not make the sd card to work so I ended up checking schematics on google and I copied what I thought could help. thats why I added the varistors and the series resistor on the vdd. I made a previous question about a proper schematic for sd card because everything I see online is actually different, but didnt really get a proper answer. I dont have a logic analyzer, but I have a scope, I will try to see what I get. I will try the change on the sdfat code. I put a tft screen on the spi, and it does work but it has a different CS.

Update here. I managed to get the sd card working. Adding a resitor to the 3,3V pin of the sd card was an absolute mistake beacuse it was making the volttage to drop. So I put a jumper there for now. Another thing was adding a pull up resistor on miso. Also one varistor seemed to be damaged so I removed it. Now the SD card is working fine, but the timestamps funcions of sdfat library make the board freeze. I will try to fix that but apparently it involves edditing the library. Does anyone know how to edit the library for this?


text:
Problem sending data via Bluetooth
I have an HM-11 BT module that I am configuring as a Master/Central and attempting to connecting to a SH-M08 BT slave module.
I can connect to the slave successfully but I cant send data.
I found this code on line. After configuring the HM-11, scanning and printing the found BT modules to serial, it reads commands from the serial port.
From the serial monitor I can send AT+CON[ADDR] and get back OK+CONNA and OK+CONN which indicates that connection was successful.
When I attempt to send anything via the serial connection it does not get received by the slave BT. I am able to used an app on my phone to send data to the slave BT.
This is the code.
SoftwareSerial BTserial(2, 3); // RX, TX

#define baud 9600

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(baud);
  BTserial.begin(baud);

  at("AT"); // check if working, always returns OK
  at("AT+RENEW"); // select master = central
  at("AT+ROLE1"); // select master = centra
  at("AT+RESET"); // actually more a restart than a reset .. needed after ROLE
  at("AT+SHOW1"); // include Bluetooth name in response
  at("AT+SCAN5"); // set discobery time to 5 seconds
  at("AT+IMME1"); // "work immediately", not sure what this does
  //at("AT+FILT0"); // show all BLE devices, not only HM ones
  delay(1000); // wait a bit, NECESSARY!!
  BTserial.print("AT+DISC?"); // here comes the magic
 while(!BTserial.find("OK+DISCS")) Serial.print(".");
   Serial.println("OK+DISCS");
}

void at(char* cmd) {
  BTserial.write(cmd);
  Serial.print(cmd);
  while(!BTserial.find("OK")) Serial.print(".");
  while (BTserial.available()) Serial.write(BTserial.read());
  Serial.println(" .. OK");
}

void loop() // run over and over
{
  if (BTserial.available())
    Serial.write(BTserial.read());
  if (Serial.available())
    BTserial.write(Serial.read());
}

source: Stack Exchange

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

sort: votes


text:
Measuring Amplitude/Frequency of sound
I need to read an analog signal at about 500-1000Hz for at least 5 seconds.
I've a battery powered microphone wired into an analog and ground pin on my arduino and am trying to measure the frequency (and amplitude) of sound coming from a rijke tube
To accurately represent the sound waves I need to take samples with a frequency at least twice that of the sound I'm studying, hence the frequency above. I plan to next do FFT to find the frequencies associated with the sound sample
Having stripped down every other part of my code, I could still only get at the most 107 readings a second, as shown below
#define VOLT_CAL 269
#define CURRENT_CAL 60
unsigned long time;

EnergyMonitor emon1;             // Create an instance

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

  Serial.println("CLEARDATE");
  Serial.println("LABEL, DATE, TIME,Wall Voltage,Wall Current, Mic Voltage, Time Elapsed");
}

void loop()
{
  int sensorValue = analogRead(A4);

   time = millis();

  Serial.print(sensorValue);
  Serial.print(",");
  Serial.println(time); //prints time since program started
}

can anyone tell me what I'm doing wrong/how I can increase the sample rate?
I've also tried to use a for loop to take my readings first, only printing them at the end but also maxed out at only 100 readings a second with the next attempt.
I've read also about preclocking, but the example codes were too complex for me to understand. A starting point in this direction would also be very much appreciated.

Serial prints at 9600 baud slow your loop down

i've tried it with 115200 and even 250000, it didnt get faster

500 samples per second for 5 seconds with 16 bit integer = 5000 byte. The arduino uno has 2000 byte sram. Do you have another arduino board?

no...is it really complex to get maybe 400Hz? it doesn't need to be integers, i just need to read analog

Use a hardware timer, for example https://arduino.stackexchange.com/questions/50045/uniform-timing-when-using-arduino-for-data-acquisition .  Data sampling rates up to 100 kHz are possible!

Also, Arduino UNO can be used but to greatly increase the timing accuracy consider substituting the 16 MHz ceramic resonator for a crystal.

The arduino uno with the normal arduino functions can do 4000 samples per second. When using the registers of the microcontroller a higher sample rate is possible. Set the baudrate to 1000000, use only this in the loop (nothing else): Serial.println(analogRead(A4));

@Jot, there is a problem with your suggestion ..... there is no timing information in the resulting data

@zueses, is there a reason why you are using an arduino for this project?

it's just a starting suggestion from my professor, is it unreliable?

You need to do the engineering part first before doing a project like this. That is calculate possible sample rate, storage size, etc, given the resources. By doing this you can see that the given requirements cannot be met with an Arduino Uno. This might be what your professor actually wants you to do instead of implementing on an Arduino Uno just to find out it was not possible.

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


text:
HC-05 connecting to Arduino
I have been looking through StackExchange, and searching on the web and cannot find an answer to my issue.
Setup:
Arduino Nano 168
HC-05 VERSION:3.0-20170601
I am trying to connect my Android phone to my Nano to control an output. I have found tons of varying examples, but they all basically boil down to MIT App Inventor to create app to connect via BT and send data to the Nano to control.
After many attempts with no results, I attempted the following:

#include <SoftwareSerial.h>

int light=8;
int Received=0;
int light_state =0;

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup(){

  Serial.begin(38400);
  pinMode(light,OUTPUT);
  BTSerial.begin(38400);

}

void loop(){
  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available()) {
    Serial.write(BTSerial.read());
 }

 if(BTSerial.available()>0) {
    Received = BTSerial.read();
 }

if (light_state == 0 && Received == '1') {
    digitalWrite(light,HIGH);
    light_state=1;
    Received=0;
  }
if (light_state ==1 && Received == '1') {
    digitalWrite(light,LOW);
    light_state=0;
    Received=0;
  }
}

So, when I run the MIT app on my phone to connect to the HC-05 the status LED on the HC-05 changes.  Before I connect, the status LED flashes fast.  After I connect, it flashes slow.
I have the serial monitor open on my laptop monitoring the Nano.  The HC-05 connects via pins 10 & 11.  When the phone connects to the HC-05, the data printed on the serial monitor is garbage.
⸮x⸮x⸮⸮x⸮x⸮x⸮⸮xxxxxx⸮x⸮⸮xx⸮⸮xxx⸮⸮
That is what I get.
The app is set to transmit a "1" via BT to the Nano.  When I press the button to send the 1, no data comes across.  But every time I pick the HC-05 and tell the app to connect to the unit, I get that same string of data above.
Thank you in advance for your help.

Seems, that you have a mismatching baud rate. Is the HC-05 really set to 38400 baud? You can try other baudrates to test

I forgot to mention, if I can access the HC-05 and run AT commands to read settings from the HC-05.

@chrisl I checked the baud rate on the HC-05 via the AT commands, but I will double check it tonight.
On the serial monitor, I checked every baud rate, but that was just between the Nano and the laptop.

@chrisl, I checked the settings.  I used AT+UART? and it returned 9600, 0, 0.  I have reset it to 34800, 1, 0.  I looked up the default settings for the Arduino Nano, and it said default is an 8bit word, 1 stop bit, and 0 parity bits.  So I made sure to match this setup.  I will test again shortly.

After getting the rate and bits correct, I do get data through the port.
However, all I get is:  +DISC:SUCCESS

where do you get this?

@chrisl, I got the units from ebay.  However, I have found out that my hardware and Nano code is correct (I setup a software serial port and used a BT terminal program on my phone to send data from the phone to the HC-05 on the software port on the nano, then the nano dumps the data to the hardware serial port to my serial monitor on my laptop).  My issue lies in my App Inventor code somewhere.  That is where I am working on now.

You should add the correct answer and close this question.And then ask another question regarding your app.

This issue has been resolved.  There was an issue with the parity and stop bits.
When setting up for arduino comms, remember, baud rate, 1 stop bit, 0 parity bits.


text:
Looking for some help with an RGB LED animation
I'm working on a project that is running off of a Sparkfun Pro Micro 5V. I'm trying to accomplish a color rainbow cycle animation which will have a function when triggered to fade the rainbow to black and fade-in some white LED. I'm using a Adafruit RGBW Neopixel for this. I'm having trouble getting some code that does this as when I try to trigger my fade-out it's turning off faster than expected due to the way I wrote it. I'm hoping someone can point me to a piece of code or suggest an edit that will help.
Constraints for animation:

Must execute quickly (if at all possible avoid floats or other constructs that take a lot of time; relatively)
Be able to configure a maximum brightness set on initialization (0 - 255)
Must not have any "delay" or "while" loops that are designed to hold the code up.
When triggered by a button press the rainbow should fade to black (i.e. off) and previously off white LED should fade in.
When button pressed a second time white should fade out and rainbow starts or resumes.

I don't really care how the color animation works. It can cycle to/between specified colors or use whatever. To keep it simple what I tried was to have it just cycle RGB values with each 1/3 out of phase. My cycle includes a "dead" time where the color stays off for a part of the loop to keep the colors more distinct so they don't merge into white through color mixing. I specifically didn't use any sort of HSV conversion or sin/cos/whatever to calculate position in the cycle I am because those require a lot of calculation relative to incrementing a number.
Here is the code I wrote for your review. This has some servo control and the button checking and the LED in it. The bit at the very end is to prevent the pixels from updating during the time the servo pulses are being sent which prevents servo jitter due to the neoPixels.

#include <Servo.h>
#include <Adafruit_NeoPixel.h>

#define usToTicks(_us) (( clockCyclesPerMicrosecond()* _us) / 8)

class ColorCycle {
  private: int maxB;
  private: int offH;
  private: int stepD;
  private: int curD;
  private: int rVal;
  private: int gVal;
  private: int bVal;
  private: int wVal;
  private: int rHold;
  private: int gHold;
  private: int bHold;
  private: int wHold;
  private: bool rDir;
  private: bool gDir;
  private: bool bDir;
  private: bool wDir;
  private: bool showWhite;

  public: ColorCycle(int maxBrightness, int offHold, int stepDelay) {
      maxB = maxBrightness;
      offH = offHold;
      rVal = gVal = bVal = wVal = 0;
      rHold = 0;
      gHold = (maxB + offH) * .5;
      bHold = (maxB + offH);
      wHold = 0;
      rDir = gDir = bDir = true;
      wDir = false;
      stepD = stepDelay;
      curD = 0;
    }

    void moveStep() {
      moveSteps(1);
    }

    void moveSteps(int count) {
      if (count == 1) { //going to skip the delay if you are trying to move more than one step intentionally.
        if (curD > 0) {
          curD--;
          return;
        }
        curD = stepD;
      }

      for (int s = 0; s < count; s++) {
        if (showWhite) {
          whiteHold();
          wDir = true;
        } else {
          wDir = false;
        }

        //setting the direction and holds when appropriate
        if (rVal == 0)
          rDir = true;
        if (rVal == maxB) {
          rDir = false;
          rHold = offH;
        }

        if (gVal == 0)
          gDir = true;
        if (gVal == maxB) {
          gDir = false;
          gHold = offH;
        }

        if (bVal == 0)
          bDir = true;
        if (bVal == maxB) {
          bDir = false;
          bHold = offH;
        }

        //stepping the values
        if (rDir && rHold == 0)
          rVal++;
        if (!rDir && rVal > 0)
          rVal--;
        if (rVal == 0 && rHold > 0) {
          rHold--;
        }

        if (gDir && gHold == 0)
          gVal++;
        if (!gDir && gVal > 0)
          gVal--;
        if (gVal == 0 && gHold > 0) {
          gHold--;
        }

        if (bDir && bHold == 0)
          bVal++;
        if (!bDir && bVal > 0)
          bVal--;
        if (bVal == 0 && bHold > 0) {
          bHold--;
        }

        if (wDir && wVal < maxB)
          wVal++;
        if (!wDir && wVal > 0)
          wVal--;
      }
    }

    int getRedValue() {
      return rVal;
    }
    int getGreenValue() {
      return gVal;
    }
    int getBlueValue() {
      return bVal;
    }
    int getWhiteValue() {
      return 0;
    }

    void setShowWhite(bool sw) {
      showWhite = sw;
    }

    void whiteHold() {
      rHold = 5;
      gHold = (maxB + offH) * .5;
      bHold = (maxB + offH);
      rDir = gDir = bDir = false;
    }
};

#define BUTTON_LED_PIN 16
#define BUTTON_SWITCH_PIN 14

Servo lidServo;
int lidServoPosition;
Servo leftServo;
int leftServoPosition;
Servo rightServo;
int rightServoPosition;

#define LID_LED_CONTROL_PIN 3
#define LID_LED_COUNT 8
Adafruit_NeoPixel lidPixel(LID_LED_COUNT, LID_LED_CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
ColorCycle ccLid(50, 50, 10);

#define BASE_LED_CONTROL_PIN 4
#define BASE_LED_COUNT 8
Adafruit_NeoPixel basePixel(BASE_LED_COUNT, BASE_LED_CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
ColorCycle ccBase(50, 50, 10);

void setup() {
  pinMode(BUTTON_LED_PIN, OUTPUT);
  digitalWrite(BUTTON_LED_PIN, LOW);
  pinMode(BUTTON_SWITCH_PIN, INPUT);
  lidServo.attach(5);
  leftServo.attach(6);
  rightServo.attach(9);
  lidPixel.begin();
  lidPixel.show();
  basePixel.begin();
  basePixel.show();

  Serial.begin(9600); //This pipes to the serial monitor
  Serial.println("Starting");
}

void loop() {
  if (digitalRead(BUTTON_SWITCH_PIN) == true)  {
    digitalWrite(BUTTON_LED_PIN, HIGH);
    lidServoPosition = 0;
    leftServoPosition = 0;
    rightServoPosition = 0;
    ccLid.setShowWhite(true);
    ccBase.setShowWhite(true);
  } else {
    digitalWrite(BUTTON_LED_PIN, LOW);
    lidServoPosition = 180;
    leftServoPosition = 180;
    rightServoPosition = 180;
    ccLid.setShowWhite(false);
    ccBase.setShowWhite(false);
  }
  lidServo.write(lidServoPosition);
  leftServo.write(leftServoPosition);
  rightServo.write(rightServoPosition);

  ccLid.moveStep();
  ColorCycle tempCc = ccLid;
  for (int i = 0; i < lidPixel.numPixels(); i++) {
    lidPixel.setPixelColor(i, lidPixel.Color(tempCc.getGreenValue(), tempCc.getRedValue(), tempCc.getBlueValue(), tempCc.getWhiteValue()));
    tempCc.moveSteps(10);
  }

  ccBase.moveStep();
  tempCc = ccBase;
  for (int i = 0; i < lidPixel.numPixels(); i++) {
    basePixel.setPixelColor(i, basePixel.Color(tempCc.getGreenValue(), tempCc.getRedValue(), tempCc.getBlueValue(), tempCc.getWhiteValue()));
    tempCc.moveSteps(10);
  }

  if (TCNT1 > usToTicks(8192)) {
    lidPixel.show();
    basePixel.show();
  };
}

You are updating the LEDs in a timed way through TCNT1, but the setting of the pixels is not part of that, so that will be done very fast. I think, that code should also be timed. Then you only change the values, when you are really updating the colors.

The TCNT1 timer is only used to make sure that the "show" command doesn't execute during a servo update as this would cause servo jitter.

You are writing your code non-blocking, but you don't introduce any way of timing code. This way the calculation of the new color values happens as fast, as the code can run. You can write timed action in a non-blocking way by using the coding style from the BlinkWithoutDelay example, that comes with the Arduino IDE. Then the LED code will only be executed, if the correct time has come. You save a timestamp of the last calculation execution in a global variable  and then check, if enough time since then has passed. Only then you again execute the calculation and update your timestamp.
unsigned long timestamp = 0;
unsigned int interval = 10;

void loop(){
    //--------
    // Omitted the servo code
    //--------
    if(millis() - timestamp > interval){
        timestamp += interval; // update the timestamp to the next value
        //--------
        // Omitted the calcuation and the LED update (show() method)
        //--------
    }
}

Note, that here I used millis(), which will return the number of milliseconds, that passed since the Arduinos startup. I used an interval of 10 milliseconds, so that the LEDs will be updated every 10 milliseconds. You can change this value as you need it (also during the code execution). If you need faster execution, than a few milliseconds, you can use micros() instead of millis(), so that you work with microseconds. Of course, you cannot get faster, than the rest of the code runs.
For further explanation of this principle, you can google it. It has been described numerous times on the web and on this site.


text:
One of the LEDs on my Arduino is very dim
I made a vibration sensor using an Arduino. It is connected to an Android app. When the start button is pressed on the app, a red light LED turns on (stand by), and after 2 - 5 seconds, the red LED turns off and a green LED turns on (meaning the system is ready). The green LED turns off if the sensor detects a vibration. The green LED works perfectly. However, the red LED is always dim. I've tried testing the red LED separately, it works fine. I've tried changing the pin it's connected to, it's still dim. I've included my code below if it helps.
Thanks in advance.
int ledPin = 13;
int ledPin2 = 9;
int EP = 7;
int cal = 500;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(EP, INPUT); //set EP input for measurement
  Serial.begin(9600); //init serial 9600
}

void loop() {
  if (Serial.available()) {
    char c = Serial.read();
    if (c == '1') {
      cal = 100;
    }
    if (c == '2') {
      cal = 200;
    }
    if (c == '3') {
      cal = 300;
    }
    if (c == '4') {
      cal = 400;
    }
    if (c == '5') {
      cal = 500;
    }
    if (c == '6') {
      cal = 600;
    }
    if (c == '7') {
      cal = 700;
    }
    if (c == '8') {
      cal = 800;
    }
    if (c == '9') {
      cal = 900;
    }
    if (c == '0') {
      int randm = random(2, 6);
      int x = randm * 1000;
      digitalWrite(ledPin2, HIGH);
      delay(x);
      unsigned int tm = millis();
      digitalWrite(ledPin, HIGH);
      digitalWrite(ledPin2, LOW);
      while (1) {
        long measurement = TP_init();
        char br = Serial.read();
        if (br == 'x') {
          break;
        }
        if (measurement > cal) {
          digitalWrite(ledPin, LOW);
          unsigned int out = millis() - tm;
          unsigned char i = out;
          Serial.print(out);
          break;
        }
      }
    }
  }
}

long TP_init() {
  delay(0);
  long measurement = pulseIn (EP, HIGH);
  //wait for the pin to get HIGH and returns measurement
  return measurement;
}

try pinMode(ledPin2, OUTPUT)

You need to add this line for the other LED pin:
pinMode(ledPin2, OUTPUT);

You need this same line for the other LED pin:
pinMode(ledPin2, OUTPUT);

This should have been a comment to the other answer; to fix his typo.

@Blair Fonville - If you hover your mouse over the timestamp at the end of Juraj's comment, you notice a "tool tip" popup with the UTC timestamp of that event. If you compare that to the timestamp of CrossRoads answer, you will see that Juraj's comment gave the correct answer before CrossRoads. If anyone deserves credit for the first correct answer, it's Juraj.

Irrelevant. ....

If it would make you feel any better, you could just down-vote my answer. It will only cost you 1 rep.

Crossroads answered only 19 seconds after Juarj's comment. I doubt he had time to read the comment, and type in his own reply, in 19 seconds. Comments under the question are not for answering it. That's why we have answer boxes. Please don't start bickering about this sort of thing. If you like an answer, vote it up, if you dislike it, vote it down, otherwise ignore it, or maybe make a comment explaining why it is wrong.

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


text:
When RFID tag is removed
After rewriting and getting a good grip on what I have got in my sketch so far, I need some assistance.
So in my sketch I can play an MP3 track with a certain tag, but when that tag is removed I can't  start the fading out process.
So for all that helped on previous ones, where I just mashed a lot of code together and hoped for the best, this one should start to have some good foundations to build on.
But I'm stuck on the part that's commented out.
//rfid
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN         9  // reset pin 9
#define SS_PIN          10 // sda pin 10
MFRC522 rfid(SS_PIN, RST_PIN); // Create MFRC522 instance

// = 0001.mp3    8C DE 63 A9   uid's for me to relate to mp3 tracks.
// = 0002.mp3    0A 97 F3 16 /
// = 0003.mp3    3A 5F DE 16

//mp3 player
#include<SoftwareSerial.h>
int mp3Pin[2] = { 5, 4 }; //Rx/Rx

// For the checksum to the mp3
#define startByte 0x7E
#define endByte 0xEF
#define versionByte 0xFF
#define dataLength 0x06
#define infoReq 0x01

SoftwareSerial mp3(mp3Pin[0], mp3Pin[1]); // Rx, Tx

void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin(); // Init SPI bus
  rfid.PCD_Init(); // Init MFRC522
  rfid.PCD_DumpVersionToSerial(); // Print version of RFID

  //Mp3
  mp3.begin(9600); // Init mp3
  delay(1000);
  sendMP3Command(0x3F, 0, 0); // Send request for initialization parameters
  sendMP3Command(0x06, 0, 20); // Vol set to 30
  sendMP3Command(0x07, 0, 0); // EQ = pop
}

void loop() {
  // Look for new cards
  if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial()) {
    //In new card found and new serial
    /*printHex(rfid.uid.uidByte, rfid.uid.size); // Print the Hex uid &
      Serial.println(); // use to get new uids.*/
    {
      String content = "";
      byte letter;
      for (byte i = 0; i < rfid.uid.size; i++) {
        content.concat(String(rfid.uid.uidByte[i] < 0x10 ? " 0" : " "));
        content.concat(String(rfid.uid.uidByte[i], HEX));
      }
      content.toUpperCase();
      if (content.substring(1) == "0A 97 F3 16") {
        //change here the UID of the card/cards that you want to give access
        //Serial.println("hello World");
        Serial.println("0002.mp3");
        sendMP3Command(0x03, 0, 0002); // Play track 0002.mp3
        sendMP3Command(0x19, 0, 0); // Loop track playing
        delay(30);
      }
      /*else !rfid.PICC_IsNewCardPresent();{
        sendMP3Command(0x06, 0, 28); // Reduce vol by 2 and fade out
        delay(30);
        sendMP3Command(0x06, 0, 26);
        delay(30);
        sendMP3Command(0x06, 0, 24);
        delay(30);
        sendMP3Command(0x06, 0, 22);
        delay(30);
        sendMP3Command(0x06, 0, 20);
        delay(30);
        sendMP3Command(0x06, 0, 18);
        delay(30);
        sendMP3Command(0x06, 0, 16);
        delay(30);
        sendMP3Command(0x06, 0, 14);
        delay(30);
        sendMP3Command(0x06, 0, 12);
        delay(30);
        sendMP3Command(0x06, 0, 10);
        delay(30);
        sendMP3Command(0x06, 0, 8);
        delay(30);
        sendMP3Command(0x06, 0, 6);
        delay(30);
        sendMP3Command(0x06, 0, 4);
        delay(30);
        sendMP3Command(0x06, 0, 2);
        delay(30);
        sendMP3Command(0x06, 0, 0);
        //sendMP3Command(0x16, 0, 0); // Stop
        delay(500); // Change value if you want to read cards faster
        }*/
    }
    // Halt PICC
    rfid.PICC_HaltA();
    // Stop encryption on PCD
    rfid.PCD_StopCrypto1();
  }
}

void sendMP3Command(byte Command, byte Param1, byte Param2) {
  // Calculate the checksum
  unsigned int checkSum = -(versionByte + dataLength + Command + infoReq + Param1 + Param2);
  // Construct the command line
  byte commandBuffer[10] = { startByte, versionByte, dataLength, Command, infoReq, Param1, Param2, highByte(checkSum), lowByte(checkSum), endByte };
  for (int cnt = 0; cnt < 10; cnt++) {
    mp3.write(commandBuffer[cnt]);
  } // Delay needed between successive commands delay(30); }
  /*   // Print the Hex uid & use to get new uids.
    void printHex(byte * buffer, byte bufferSize) {
    for (byte i = 0; i < bufferSize; i++) {
      Serial.print(buffer[i] < 0x10 ? " 0" : " ");
      Serial.print(buffer[i], HEX);
    }
    }*/

how is it that you write several for loops and then you write linear code like that commented out code?

Which RFID reader? Which Arduino? Using "programming" as a tag is rather generic. Obviously it is programming.

In general, RFID readers send a message when a card is presented. They don't send a message when a card is moved out of range. Unless you have a fancy reader that tells you that (and in that case it would help to mention the reader type).

Thank you for your quick replies. Sorry, a mfrc522 reader coupled with a nano and a dfplayer MP3. Regards

Basically, you have written this code:
void loop()
{
  // Look for new cards
  if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial())
  {
    {
      // ...
      if (content.substring(1) == "0A 97 F3 16")
      {
        // play
      } else
      {
        // stop
      }
    }
    // ...
  }
}

Try something like this:
bool playing = false;

void loop()
{
  // Look for new cards
  if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial())
  {
    // ...
    if (content.substring(1) == "0A 97 F3 16")
    {
      // play
      playing = true;
    }
    // ...
  }
  if (playing && !anyCardPresent())
  {
    // stop
    playing = false;
  }
}

and for the implementation od anyCardPresent refer to this discussion - if more consecutive calls of PICC_ReadCardSerial fail, you can consider this as card being removed

Thank you gabonator, I will try this when I'm home. I did use some code that could tell when the card was removed but the person who wrote it and myself didn't really understand it or how it worked. I can post it later if that might help. Regards

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


text:
RFID with Adafruit fingerprint together not working in Arduino Uno
I have edited my Ccde and now the issue is both are working but not together.
#include <Key.h>
#include <Keypad.h>
#include <Adafruit_Fingerprint.h>
#include <SD.h>
#include <SPI.h>
#include<SoftwareSerial.h>

SoftwareSerial mySerial(0, 1);
SoftwareSerial mySerials(2, 3);

int read_count = 0, tag_count = 0;
int j = 0, k = 0; // Variabvles to iterate in for loops
char data_temp, RFID_data[12], data_store[12];
boolean disp_control;
char filename[4], fileText[30], names[10];
int atm[5];
uint8_t n, num, p;
char key;
int p1, p2, p3, p4, z;
char fid;

File myFile;
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerials);

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad

Keypad keypads = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup() {
  finger.begin(57600);
  mySerial.begin(9600);
  Serial.begin(9600);

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

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

  Serial.println("Please Place Your Card");

}

void RecieveData()
{

  if (mySerial.available() > 0)
  {
    data_temp = mySerial.read();
    RFID_data[read_count] = data_temp;
    read_count++;
  }
}
void ReadData()
{
  if (read_count == 12) {
    disp_control = true;
    for (j = 0; j < 12; j++) {
      data_store[j] = RFID_data[j];
    }

    int x = 0;
    for (int i = 9; i < 12; i++) {
      filename[x] = data_store[i];
      x++;
    }
    filename[3] = '.';
    filename[4] = 't';
    filename[5] = 'x';
    filename[6] = 't';
    filename[7] = '\0';

    myFile = SD.open(filename, FILE_READ);
    if (myFile) {

      // read from the file until there's nothing else in it:
      while (myFile.available()) {

        for (int i = 0; i < 20; i++) {
          fileText[i] = myFile.read();
        }

        int a, n = 0;
        for (int i = 0; i < 4; i++) {
          atm[a] = fileText[i];
          a++;
        }
        for (int i = 5; fileText[i] != '\0'; i++) {
          names[n] = fileText[i];
          n++;
        }
        fid = fileText[4];

        validate();

        myFile.close();
      }
    } else {
      // if the file didn't open, print an error:
      Serial.println("error opening test.txt");
    }
    read_count = 0;
    tag_count++;

  }
}
void validate() {

  Serial.print("Hello ");
  Serial.print(names);
  Serial.println();
  Serial.println();
  Serial.println();

  pin();

}

void pin() {
  Serial.println("Please Enter Your ATM PIN");

  p1 = keypads.getKey();
  while (p1 == NO_KEY) {
    p1 = keypads.getKey(); //UPDATE VALUE

  }
  Serial.print(p1 - 48);

  p2 = keypads.getKey();
  while (p2 == NO_KEY) {
    p2 = keypads.getKey(); //UPDATE VALUE
  }
  Serial.print(p2 - 48);

  p3 = keypads.getKey(); //UPDATE VALUE
  while (p3 == NO_KEY) {
    p3 = keypads.getKey(); //UPDATE VALUE
  }
  Serial.print(p3 - 48);

  p4 = keypads.getKey(); //UPDATE VALUE
  while (p4 == NO_KEY) {
    p4 = keypads.getKey(); //UPDATE VALUE
  }
  Serial.print(p4 - 48);
  Serial.println();

  if ((p1 == fileText[0]) && (p2 == fileText[1]) && (p3 == fileText[2]) && (p4 == fileText[3])) {
    Serial.println("Please verify Fingerprint");
  }
  else {
    Serial.println("Invalid. Buzzer!!!!");
  }
}
uint8_t getFingerprintID() {
  uint8_t p = finger.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println("No finger detected");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK success!

  p = finger.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    Serial.println("Found a print match!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {
    Serial.println("Did not find a match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  // found a match!
  Serial.print("Found ID #"); Serial.print(finger.fingerID);
  Serial.print(" with confidence of "); Serial.println(finger.confidence);

  return finger.fingerID;
}

int getFingerprintIDez() {

  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;

  Serial.print("Found ID #"); Serial.print(finger.fingerID);
  Serial.print(" with confidence of "); Serial.println(finger.confidence);
  return finger.fingerID;

  // found a match!

  /*z = finger.fingerID;
    if ((fid - 48) == z) {
    Serial.println("Success");
    }
    else {
    Serial.println("Fail");
    }*/
}

void loop() {
  RecieveData();
  ReadData();
  getFingerprintIDez();
  delay(50);
}

If I initialize in this format, then fingerprint works:
mySerial.begin(9600);
  finger.begin(57600);
  Serial.begin(9600);

And if I do it this way, then RFID works:
finger.begin(57600);
  mySerial.begin(9600);
  Serial.begin(9600);

I want both of them to work i.e I first scan the card, then verify the PIN and then it checks the validity of the fingerprint. But the issue is only one of them works at a time. If RFID works, then fingerprint doesn't even blink and if fingerprint works, RFID doesn't read.

Also asked on SO

Why are you using software serial on hardware serial pins?

No surprise there. Your function says:
uint8_t p = finger.getImage();
if (p == FINGERPRINT_OK)
  z = finger.fingerID;

So what happens if p isn't FINGERPRINT_OK? This runs:
  if ((fid - 48) == z) {
    Serial.println("Success");
  }
  else {
    Serial.println("Fail");
  }

So z is uninitialized and so probably 0, fid was assigned some value along the way (and it doesn't seem to be 48). So what you get is the expression in the IF condition evaluates to false, 'Fail' is printed and the function returns.
Neglecting the poor structure of your code, magic numbers and all, you've failed to account for the case where there's no finger on the module. Aside from that, you're not even performing a fingerprint search (as I assume you intend); even when someone places their finger, all you're doing is grabbing the image and then reading the default value of fingerID which I believe is 0xffff -- no template conversion or database search. Bottom line, you need to go back and study the original example, which is well commented with self-explanatory method names, before making any changes and writing your own stuff.


text:
Which EEPROM has a long lifecycle?
I would like to build a box counter for machine, so I'm going to use EEPROM in Arduino to save count. But the lifecycle is limited to 100,000 writes. Please suggest an external EEPROM with a long lifecycle or any other solution.

Lifetime is not limited to 100,000. Lifetime is minimum 100,000. It's guaranteed to be at least 100,000.

See also this question: https://arduino.stackexchange.com/questions/48872/extending-eeprom-life

I would use an ESP8266: it's 1-4MB of SPIFFS storage wear-levels, so storing one counter takes ~1/1,000,000 writes, and you can do 100k+ writes, so that's a lot of counting: 100bln for $2. you can also use the RTC ram of the ESP if you have some power managment.

You can cycle through all the addresses in the EEPROM like a ring buffer.
You'll need to reserve a bit so you can binary search for the head of the buffer during startup.
You can also reduce how often you write in general especially when the count will increment in bursts, try and wait out those bursts instead of writing on every increment.

Wear leveling is the way to go. +1.

Great answer, but if you know of external EEPROM modules, please add that info as well.

The EEPROMs from Microchip have a guaranteed erase count of 1 million. The ones from ST offer 4 million. So it's not hard to find EEPROMs with a higher endurance.
But for a device which writes a lot, a better solution would be a NVRAM, FRAM or EERAM. Those usually come with virtually no limitations to the write cycles but usually are more expensive than EEPROMs but that might very well be worth it compared to the hassle you can get in otherwise.
Adafruit offers SPI and I²C variants for FRAM boards.

If you use something like an SD card, they have internal logic that will move the data around when a call is used up.  This should give you virtually unlimited storage for something as simple as a count.


text:
How to continuously monitor range finder and immediately interrupt code to run a different code in pedestrian traffic lights setup?
I am currently doing part 2: Pedestrian Mode of my project below:

Regular Mode: This is the regular mode of operation. In this mode the
three lights (Red, Yellow and Green LEDs) should operate in the following
order. The Red LED lights for 2 seconds, followed by the Yellow LED for 1
second, the Green LED for 2 seconds and then the Yellow LED again for 1
second. The cycle should repeat until the mode changes.
Pedestrian Mode: This mode uses the SRF05 Ultrasonic Range Finder to
detect the proximity of any object. The lights should operate as defined in
the regular mode UNTIL an object is detected less than 10 cm from the
TLC. The buzzer should then beep and the Yellow LED must blink ON/OFF
(flashing intervals of 0.1 sec) repeatedly 10 times. The buzzer should then
stop beeping and the operation of the lights (not the system) must behave
as it would in the regular mode. The operation stays the same until the
mode changes

My code works, however it waits for the entire regular cycle to finish before sensing a pulse with the ultrasonic range sensor to determine if an object is near or not. Therefore, when I put my hand near the sensor, it has to finish running the regular mode before it detects my hand and switches to pedestrian mode. What I would like is for the range finder to continuously fire the pulse and immediately switch to pedestrian mode when it detects an object less than 10 cm away.
Code below:
int red_light = 12;
int yellow_light = 10;
int green_light = 8;
int ECHOPIN = 3;
int TRIGPIN = 5;
int buzzer = 7;
float distance;

void setup() {
  Serial.begin(9600);
  pinMode(red_light, OUTPUT);
  pinMode(yellow_light, OUTPUT);
  pinMode(green_light, OUTPUT);
  pinMode(ECHOPIN, INPUT);
  pinMode(TRIGPIN, OUTPUT);
  pinMode(buzzer, OUTPUT);
}

void loop() {
  range_finder();
  if (distance < 10) {
    pedestrian_mode();
  } else {
    regular_mode();
  }
}

void regular_mode() {
  digitalWrite(red_light, HIGH);
  delay(2000);
  digitalWrite(red_light, LOW);
  digitalWrite(yellow_light, HIGH);
  delay(1000);
  digitalWrite(yellow_light, LOW);
  digitalWrite(green_light, HIGH);
  delay(2000);
  digitalWrite(green_light, LOW);
  digitalWrite(yellow_light, HIGH);
  delay(1000);
  digitalWrite(yellow_light, LOW);
}

void range_finder() {
  digitalWrite(TRIGPIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGPIN,HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN,LOW);
  distance = pulseIn(ECHOPIN, HIGH);
  // return 0 if no high pulse in 1 sec
  distance = distance/58;
  Serial.print(distance);
  Serial.println("cm");
  delay(200);
}

void pedestrian_mode() {
  digitalWrite(buzzer, HIGH);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
}

Also I have a feeling some parts of my code may be unnecessarily long and could be shortened. If so, I would appreciate any advice and how to do that. Thank you.

   digitalWrite(yellow_light, HIGH);
   delay(100);
   digitalWrite(yellow_light, LOW);
   delay(100);

   digitalWrite(yellow_light, HIGH);
   delay(100);
   digitalWrite(yellow_light, LOW);
   delay(100);

...

You really need to read up on "for" loops. Make a loop that does it 10 times, don't copy and paste 10 times.
As for your other issue, at the very least you could test the proximity sensor after each delay. Read up on millis. Just imagine how you might do it in real life. Would you really delay for two seconds? Or would you check the clock to see if two seconds had elapsed and also check if a pedestrian had arrived?
And better still, replace delay with a loop which tests elapsed time, and also tests the distance sensor.

I'm not writing more specific code because clearly the exercise is for you to learn how to do this. I already know how to do it, and if I just posted the exact answer you wouldn't have learned how to do it.

As a short addition: The BlinkWithoutDelay example in the Arduino IDE is a good starting point for learning this principle

You should use an interrupt pin.
Interrupt pins can operate outside the normal void loop().
So you can have a normal loop going on. If an interrupt pin is triggered - it performs a function immediately.
https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
Or you could consider using a switch case.

However that function should be brief. What the OP seems to want is to switch modes (regular mode to pedestrian mode). It might be better to check for the conditions for a mode change to occur, while a particular mode is in operation.


text:
Code compatibility with Arduino Due
I am currently working on a quadcopter project that involves an MPU6050 accelerometer+gyroscope module, an ultrasonic sensor and control of electronic speed controllers. I have used existing examples and modified them to get raw values of acceleration, yaw pitch and roll angles, and the distance from the ultrasonic. Here is the long code.
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif

MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

const int trigPin = 9;
const int echoPin = 10;

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z] world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3], yprd[3] = {0, 0, 0};

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = {'$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================
volatile bool mpuInterrupt = false;
void dmpDataReady() {
  mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================
int16_t yo = 0, po = 0, ro = 0;
int lv = 1, flag = 0;
const int MPU_addr = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
int32_t AcXo = 0, AcYo = 0, AcZo = 0, prev, curr;
int32_t AcXd = 0, AcYd = 0, AcZd = 0;
int i = 1, flaggl = 0;
int  glc = 0, lv2 = 1;
long duration;
int distance, distanced;
void setup() {

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000);
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif
  Serial.begin(115200);
  // initialize device
  Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);
  // verify connection
  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
  // wait for ready
  Serial.println(F("\nSend any character to begin DMP programming and demo:
                   "));
  while (Serial.available() && Serial.read()); // empty buffer
  while (!Serial.available());                 // wait for data
  while (Serial.available() && Serial.read()); // empty buffer again
  // load and configure the DMP
  Serial.println(F("Initializing DMP..."));
  devStatus = mpu.dmpInitialize();
  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(220);
  mpu.setYGyroOffset(76);
  mpu.setZGyroOffset(-85);
  mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
  // make sure it worked (returns 0 if so)
  if (devStatus == 0) {
    // turn on the DMP, now that it's ready
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

    // enable Arduino interrupt detection
    Serial.println(F("Enabling interrupt detection (Arduino external
                     interrupt 0)..."));
    attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
    mpuIntStatus = mpu.getIntStatus();

    // set our DMP Ready flag so the main loop() function knows it's okay to use it
    Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;

    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
  }

  // configure LED for output
  pinMode(LED_PIN, OUTPUT);
  glc = 0;
  distance = distanced = 0;
}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================
void loop() {
  // if programming failed, don't try to do anything
  if (!dmpReady) return;

  // wait for MPU interrupt or extra packet(s) available
  while (!mpuInterrupt && fifoCount < packetSize) {
  }
  mpuInterrupt = false;
  mpuIntStatus = mpu.getIntStatus();
  // get current FIFO count
  fifoCount = mpu.getFIFOCount();
  // check for overflow (this should never happen unless our code is too inefficient)
  if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
    // reset so we can continue cleanly
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));
    // otherwise, check for DMP data ready interrupt (this should happen frequently)
  } else if (mpuIntStatus & 0x02) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);
    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;
    //#ifdef OUTPUT_READABLE_YAWPITCHROLL
    // display Euler angles in degrees
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    if (millis() > 30000 && flag == 0) {
      if ( flag == 0 && lv  < 21) {
        yo += ypr[0] * 180 / M_PI;
        po += ypr[1] * 180 / M_PI;
        ro += ypr[2] * 180 / M_PI;
        ++lv;
      } else if (flag == 0) {
        flag = 1;
        yo /= 20;
        po /= 20;
        ro /= 20;
      }
    }
    //#endif
    // blink LED to indicate activity
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
    Wire.beginTransmission(MPU_addr);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
    AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C     (ACCEL_XOUT_L)
    AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
    mpu.resetFIFO();
    if (i < 21 && !flaggl) {
      AcXo += AcX;
      AcYo += AcY;
      AcZo += AcZ;
      ++i;
      Serial.println();
      Serial.println("***************************************************************************");
    } else if (!flaggl) {
      flaggl = 1;
      AcXo  = AcXo / 20;
      AcYo = AcYo / 20;
      AcZo = AcZo / 20;
    }
    curr = (AcZ - AcZo / 100);
    if (prev == curr )
      ++glc;
    else {
      glc = 0;
      prev = curr;
    }
    if (glc == 10) {
      Serial.println("lock broken!!!");
      glc = 0;
      loop();
    }
    if (flag == 1 && flaggl == 1) {
      if (lv2 < 21) {
        delayMicroseconds(2);
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);
        duration = pulseIn(echoPin, HIGH);
        distance = duration * 0.034 / 2;
        AcXd += (AcX - AcXo) / 100;
        AcYd += (AcY - AcYo) / 100;
        AcZd += (AcZ - AcZo) / 100;
        yprd[0] += ypr[0] * 180 / M_PI - yo;
        yprd[1] += ypr[1] * 180 / M_PI - po;
        yprd[2] += ypr[2] * 180 / M_PI - ro;
        distanced += distance;
        ++lv2;
      } else {
        AcXd /= 20;
        AcYd /= 20;
        AcZd /= 20;
        yprd[0] /= 20;
        yprd[1] /= 20;
        yprd[2] /= 20;
        distanced /= 20;
        lv2 = 1;
        Serial.print("AcX = ");
        Serial.print(AcXd);
        Serial.print(" | AcY = ");
        Serial.print(AcYd);
        Serial.print(" | AcZ = ");
        Serial.print(AcZd);
        Serial.print(" | yaw = ");
        Serial.print(yprd[0]);
        Serial.print(" | pitch = ");
        Serial.print(yprd[1]);
        Serial.print(" | roll = ");
        Serial.print(yprd[2]);
        Serial.print(" | distance = ");
        Serial.println(distanced);
        AcXd  = 0;
        AcYd = 0;
        AcZd = 0;
        yprd[0] = 0;
        yprd[1] = 0;
        yprd[2] = 0;
        distanced = 0;
      }
    }
  }
}

The code involves offset calculation and displays the averaged instantaneous values. After overcoming the problems of FIFO buffer overflow and some other typical issues, I've managed to get the code running but the the Arduino hangs after sometime (code tested on both Uno and Nano).
Therefore, it seems that maybe I need a higher clock speed. So, I had a look through other Arduino boards and Due seemed to be the solution, as it has a clock speed of 84MHz, compared to Uno's 16 MHz. Therefore, my question is that will the libraries and functions used in this code be compatible with the Due? Also, can the 3.3V operation of the Due, compared to  Uno's 5V, present any problem in interfacing it with other sensors mentioned?

You should probably spend some time looking at existing post-ATmega open source aircraft designs.  The chip from a DUE can probably be made to a work; a lot of incumbent designs use comparable STM32, GigaDevices, and Nuvoton ARM Cortex MCUs... and also some other MCUs and especially MCU/radio chips basically undocumented in the west.

Arduino Due is a dead product, and has been from its birth. It is too powerful to be used just for flashing LEd's.Yes, you can make it work for your project but caveat emptor - do not expect much sympathy from Arduino.

Therefore, my question is that will be the libraries and functions used in this code be compatiable with Due?

The I2Cdev library is made for abstracting the hardware I2C functions to a more user friendly interface for each chip. Since the Arduino Due has hardware TWI (which is basically I2C) the normal Wire library from the Arduino IDE should work with it.

Also, can the 3.3V operation of Due, compared to Uno's 5V present any problem in interfacing it with other sensors mentioned?

You cannot put 5V from your sensor on a 3.3V pin on the Arduino Due, since this would destroy the pins hardware. I don't know how exactly you are using the MPU6050, but this one from Adafruit runs on 3.3V, which would be perfect. If your MPU6050 board only works with 5V maybe you can level shift the lines (but note that I2C would need 2-way level shifting, because SDA is used as output and input).
Also this Article may help you, where they are porting MultiWii to an Arduino Due.

I am working with the ArduinoDue and ArduinoMega2560 boards and I have found that programs that compile with the Mega2560 board don't necessary compile with the Due board.
This is because there is a limited amount of available libraries that are compatible with the Due board.
Try compiling (verifying) your code with the Due options set, you don't need to buy one to try verifying it.


text:
Having an issue running an Arduino sketch
I just got my USB host shield attached to my Arduino Uno, opened the program sketch for USBDESC.ino and I'm getting an error. It says "usbhub.h not found". It won't compile. How did I go wrong?
I am using the Mac version of the Arduino IDE and downloaded the USB host shield Master v 2.0 file directly into /Arduino/java/examples. This was how I have added every previous library download. Please help. Thanks.

is that file in the arduino path? did you search for it?

I don't know how you came up with that location as the right place to put libraries. It is wrong. Oh so very wrong.
Libraries go in ~/Documents/Arduino/libraries as stated in the first hit for "arduino macos libraries" on Google.

ok that worked, but now I just get a garbled output from running the script


text:
L298N motor controller board EN pins

For this device are the enable pins meant to be connected to PWM pins?
If so then how am I able to use this device with an arduino uno?
The uno does not have any pwm pins right?

the pins with ~. https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

The uno pins are 3, 5, 6, 9, 10, 11.
See https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/
Usage:
analogWrite(pin, value);

The people over at How to Mechatronics have a great introduction to this board and using it with an Arduino Uno.
The enable pins are for turning the motors on and off. See the table for the different settings.  But the EN pin is also used for controlling the motor speed.
PWM is used to adjust the speed the motors turn at. Rather than simply turning the enable pin fully “on” (i.e, full speed), PWM is used to adjust the voltage and thereby control the speed the motors turn.
So the short answer is yes, you can connect a PWM signal to the EN pins.  Yes a UNO can produce PWM (as answered by others)


text:
L298 motor controller board

Hello I have 2 questions:
A) do I have to remove any of the plastic casings that I have highlighted in order to make the motors move.
B) What is the purpose of the black plastic casing that I have pointed out?

Remove black casings? The jumper by the Vin and M1 headers is to control the on-board circuitry power—when enabled the on-board circuitry uses the 12V max Vin through a voltage regulator to run the 5V components, when disabled you need to supply a 5V source. The “black cases" on the left and right are protection diodes; if they’re removed bad things happen.

A) do I have to remove any of the plastic casings that I have highlighted in order to make the motors move.

Those aren't "casings", those are diodes. They are part of the circuit and must be left alone.

B) What is the purpose of the black plastic casing that I have pointed out?

That is a "jumper" and is used to connect the +5V pin to the internal 5V regulator so the board can be run from just the 12V input power supply. Remove that if, and only if, you want to supply 5V to the board separately from elsewhere.


text:
fatal error ESP8266WiFi.h: No such file or directory
I want to turn my ESP8266 into an access point so that I can connect directly to it.
I use the following sketch, but when I select
GENERIC module ESP8266 from menu, the libraries ESP8266WiFi.h and ESP8266WebServer.h become available but I was unable to upload the sketch.
Also when I select board as Arduino Uno (Which i have really) and then what to upload then the above two files becomes unavailable and says fatal error no such file... no idea what to do next.
#include <ESP8266wifi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include<WiFi.h>
#include<SoftwareSerial.h>
SoftwareSerial esp(2,3);
IPAddress local_IP(192,168,4,22);
IPAddress gateway(192,168,4,9);
IPAddress subnet(255,255,255,0);
 String ssid="Wisal";
 String pass="12345678";
 ESP8266WebServer server(80);
 boolean isAccessPointCreated=false;
void setup(){
  esp.begin(115200);
  Serial.begin(115200);

  WiFi.mode(WIFI_AP);
  Serial.print("Setting soft-AP configuration ... ");
  Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");

  Serial.print("Setting soft-AP ... ");
  Serial.println(WiFi.softAP("ESPsoftAP_01") ? "Ready" : "Failed!");
  Serial.print("Soft-AP IP address = ");
  Serial.println(WiFi.softAPIP());

}

void loop(){
  while(esp.available()>0){
    char a = esp.read();
      if(a == '\0')
        continue;
      if(a != '\r' && a != '\n' && (a < 32))
        continue;
      Serial.print(a);
   }
}

Are you trying upload to an Uno or an ESP8266? The hardware package and libraries you're referring to are for use directly on an ESP8266, not an Uno using an ESP8266 for WiFi communications.

i upload the sketch to arduino uno and the esp8266 is connected to my arduino uno.

The ESP8266 core for Arduino that you're trying to use is for programming ESP8266 directly. You are trying to program an Uno with an ESP8266 connected to it for use as a WiFi module. For that application the ESP8266 core is of no use. For your application it's most common to run the AT firmware on the ESP8266 and communicate via serial. If you're doing that I recommend the WiFiEsp library:
https://github.com/bportaluri/WiFiEsp
Since you're uploading to the Uno you should have Arduino/Genuino Uno selected in the Tools > Board menu.

You have imported ESP8266wifi.h and not ESP8266WiFi.h

There are two ways to use an ESP8266.
Method 1
You seem to say you are using it as a slave to your UNO.  You program you Uno from the IDE.  The program will have code in it to send 'AT' commands to the ESP and this will make the ESP handle all the WIFI stuff.
Method 2
You remove you Uno and use the ESP as the main processor.  This means you get to program the ESP with C++ like code through the IDE, just as if it was an UNO.  HOWEVER you will need to install the ESP package from the board manager and there are certain limitations.  You also have access to less IO ports, but you can connect the Uno (over serial or I2C) and use it as a slave (which you program through the IDE separately).


text:
12V dc fan motor rpm finding using tacho out
I need an Arduino program to find the RPM of a 12V DC fan motor.
I don't want to control the speed. I only want to find the speed of the motor using tacho out.

https://www.instructables.com/id/Arduino-Frequency-Counter/

How is this related to my question? Sorry i am new to this.. help me.. i wanna know only fan motor rpm

RPM is just frequency. You want to know the frequency of the pulses from the fan. The simplest way is "frequency counting" - counting the number of pulses over a defined time. Frequency = Pulses Per Second.  Pulses Per Second = Revolutions Per Second. Revolutions Per Second * 60 = Revolutions Per Minute.

do you have a fan that has a tachometer output?

Thank you buddy....

@Majenko you should flesh out your answer a little bit and post it as an answer. That way the OP can accept it and we can up-vote it. That link you posted is 90% of the way there.


text:
Water level switches / reed switches and Arduino Uno
How could I estimate the max number of switches that I could connect to an Arduino Uno?
I am questioning if Arduino has enough power to simultaneously operate an X number of switches with no issues.
I am using an external power adapter of 12 volt/2 amps (barrel).
Here is the hardware: https://m.hellasdigital.gr/el/products/tank-pool-water-level-liquid-sensor-float-switch

Count the number of digital-capable IO pins :) It's unclear what problem you're thinking you'll run in to. Are the switches, for example, really far away?

You can use up to (N/2)² switches where N is the number of IO pins you have.

Yes I am trying to find out why under some conditions the sensor does not trigger the Arduino. It is one in the hundreds but it happens often if you think that the sensor is triggered twice every five minutes continuously. The distance is under five metres. I will soon move the power cables away from the signal cables. Right now they are a bit close.

How are they connected? You might want to check out https://arduino.stackexchange.com/q/13072/8583 and similar; 5m isn't far-far, but it's far enough.

Yes indeed I forgot to write that I used 10 k pull up resistors and I do not use the Arduino internal. Maybe I should try the 1 K. Something else that may be relevant while I was reading the article is the fact that all buttons use the same ground cable. Maybe each one should have each own twisted and only at the end I should connect all ground together.

I liked the idea of using opto coupler isolation. First of all I have to put the cables in an order. For instance a separate twisted pair per switch and put them far away from the high voltage cables.

thank you a lot about your input it was very useful.
My source of issues was a faulty sensor. After I changed it things are smooth now.
I separated the power cables from the signal as well that is super important.
Thank you a lot about the valuable input!


text:
how do i make stepper stop if both sensors are LOW ? im using a adafruit l293d motor shield
I've tried this code below but it doesn't stop it just rapidly switch direction that it looks like it's trembling I think because it always reads the void startF/R thats why it's trembling .
I need help on how to completely stop the stepper if it reads both sensor LOW
if (sensLval== LOW || sensRval == LOW){
     steppStop();
}

this is my void loop code below
    void startF()
  {
    motor1.step(10, FORWARD,SINGLE);

  }

    void startR()
  {
    motor1.step(10, BACKWARD,SINGLE);

  }

    void steppStop(){
  motor1.step(0, BACKWARD, SINGLE);

 motor1.step(0, FORWARD, SINGLE);
}

    void loop() {
  sensRval=digitalRead(sensR);

sensLval=digitalRead(sensL);

  if (sensLval == LOW)

{
    startF();
  }

if (sensLval== LOW && sensRval == LOW)

{
     steppStop();
  }

  if (sensRval == LOW)

{
    startR();
  }

}

Isolate your conditions.
You currently check for:

Both sensors LOW at the same time and
Either sensor LOW on its own

If both are low—don't check for either being LOW (which triggers startX.)
if (sensLval == LOW && sensRval == LOW) {
    steppStop();
} else if (sensLval == LOW) {
    startF();
} else if (sensRval == LOW) {
    startR();
}

There may be other considerations as well, but this is enough to get past that issue.

Unrelated, but consistent indentation goes a long way towards code readability and helping others be able to reason about code in general. When posting code it's a good idea to format your code as code, described here and when you are editing the question.

Im sorry bout the format , im still learning but i'll be sure to do well next time. The code works now thanks alot! I ddnt know u could code it  that way. That's cool!


text:
How to programme a button per colour for a neopixel strip?
I am trying to make a particular pixel in a neopixel strip, turn green, red or blue depending which button has been pressed and to stay on until pressed off again (like a toggle), but currently when I press one of the buttons it flashes the correct colour when button is pressed down but isn't acting as a toggle switch and then goes to a white light.

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinke
#endif

#define BUTTON_PIN1  2
#define BUTTON_PIN2  10
#define BUTTON_PIN3  11
#define PIXEL_PIN    6  // Digital pin 6 connected to the NeoPixels.

#define PIXEL_COUNT 13  // Number of NeoPixels

// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800);

boolean oldState1 = HIGH;
boolean newState1 = HIGH;

boolean toggle1 = LOW;

boolean oldState2 = HIGH;
boolean newState2 = HIGH;

boolean toggle2 = LOW;

boolean oldState3 = HIGH;
boolean newState3 = HIGH;

boolean toggle3 = LOW;

void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN1, INPUT_PULLUP);
pinMode(BUTTON_PIN2, INPUT_PULLUP);
pinMode(BUTTON_PIN3, INPUT_PULLUP);
strip.begin(); // Initialize NeoPixel strip object (REQUIRED)
strip.show();  // Initialize all pixels to 'off'
}

void loop() {
updateButtonState1();
updateButtonState2();
updateButtonState3();

}

void updateButtonState1() {

 // Get current button state.
 newState1 = digitalRead(BUTTON_PIN1);

 if ((newState1 == LOW) && (oldState1 == HIGH)) {
 delay(50);
 newState1 = digitalRead(BUTTON_PIN1);
 if (newState1 == LOW) {
   toggle1 = !toggle1;
  }
 }
 oldState1 = newState1;

if (toggle1 == HIGH) {
strip.setPixelColor(2, 245, 15, 15); //electrical/fire hazard (red)
} else {
strip.setPixelColor(2, 0, 0, 0);
}
strip.show(); // Update strip with new contents
}

void updateButtonState2() {

// Get current button state.
 newState2 = digitalRead(BUTTON_PIN2);

if ((newState2 == LOW) && (oldState2 == HIGH)) {
 delay(50);
 newState2 = digitalRead(BUTTON_PIN2);
 if (newState2 == LOW) {
   toggle2 = !toggle2;
   }
  }
 oldState2 = newState2;

  if (toggle2 == HIGH) {
  strip.setPixelColor(2, 13, 50, 190); //Leak (blue)
  } else {
  strip.setPixelColor(2, 0, 0, 0);
  }
 strip.show(); // Update strip with new contents
 }

 void updateButtonState3() {

 // Get current button state.
 newState3 = digitalRead(BUTTON_PIN3);
 if ((newState3 == LOW) && (oldState3 == HIGH)) {
  delay(50);
  newState3 = digitalRead(BUTTON_PIN3);
  if (newState3 == LOW) {
    toggle3 = !toggle3;
  }
 }
 oldState3 = newState3;

 if (toggle3 == HIGH) {
 strip.setPixelColor(2, 58, 233, 65); //bins/recylcing (green)
 } else {
   strip.setPixelColor(2, 0, 0, 0);
  }
  strip.show(); // Update strip with new contents
}

Why do you want/need to use an array?

Is the shown code not working correctly? If so, include a description in your question, how it IS actually behaving and what you expect from it.

You do not really have to use an array for this, though I do agree that it's the cleanest solution.
Here is a simplified version of your code, do mind you'll still have to do the button handling yourself (by setting buttonpressed to 'true' when the button is pressed.
Also, when adding more colors to the array, you'll have to manually adjust 'totalColors'.
void setup() {
  //Color/pixel declarations based on https://learn.adafruit.com/adafruit-neopixel-uberguide/arduino-library-use
  uint32_t magenta = strip.Color(255, 0, 255);
  uint32_t greenishwhite = strip.Color(0, 64, 0, 64);

  //https://www.arduino.cc/reference/en/language/variables/data-types/array/
  uint32_t colors[] = {magenta, greenishwhite};
  unsigned char totalColors = 2;
  unsigned char currentColor = 0;
}

void loop() {
  if (buttonpressed) {
    //Change the "currentColor" index every time the button is pressed, but make it start at 0 when it reached the end.
    currentColor++;
    if (currentColor >= totalColors) {
      currentColor = 0;
    }

    //From the array of colors, pick the one with the index "currentColor" and show it.
    ledstrip.fill( colors[currentColor] , 0, strip.numPixels() - 1);
    ledstrip.show();

    buttonpressed = false; //Reset flag, so this doesn't get executed until next time button is pressed.
  }
}

You should be able to replace the first 3 lines (setting up the array) with a single:
uint32_t colors[] = {strip.Color(255, 0, 255,  strip.Color(0, 64, 0, 64)};

But I had it split up to better show the idea of the array.
Alternatively you could do:
switch(currentColor){
  case 0:
    //Color RED
  break;
  case 1:
    //Color GREEN
  break;
  case 2:
    //Color BLAUW
  break;
}

Thank you so much! Where in the code do I set up the buttonpressed as true ? I thought potentially an array was the best way to do it as after this I would like to set it up so that first in can be input which neopixel to turn on with one set of buttons then which colour (which is the part this code is trying to address)

It doesn't quite matter where you put "buttonPressed" to true. Though preferably before the code where it checks it. You could even swap "buttonPressed" for ”digitalRead(buttonPin)” and put a delay after changing the colours of the pixels (to avoid contact bounce to call do it multiple times for a single press).


text:
HC-05 Bluetooth fails AT+LINK
I'm trying to get a HC-05 connected as master to a Bluetooth ELM327 OBD scanner.
The HC-05 is accepting AT commands, no problem. This is the sequence I use:

AT+RMAAD    (Clear any paired devices)
AT+ORGL     (Set factory defaults)
AT+ROLE=1   (Set role to master)
AT+RESET    (reset needed after role change)

AT+CMODE=0  (allows connection to any device)
AT+INQM=0,5,9   (set inquiry to search for up to 5 devices for 9 seconds)
AT+INIT     (Inits BT)
AT+INQ      (searches for BT devices)

AT+PAIR=1D,A5,68988A,9  (Pairs to the address of the ELM327, timeout in 9 secs)
AT+BIND=1D,A5,68988A    (Binds the address)
AT+CMODE=1      (HC-05 will now only connect with the paired device)
AT+LINK=1D,A5,68988A    (Connect to device)

Everything is fine, until the last step: AT+LINK.
What happens is:
>at+link=1D,A5,68988A
FAIL
+INQ:1D:A5:68988A,1F00,7FFF
OK

So it fails the AT+LINK, then for some reason, it starts inquiry mode.
I saw a guide which had CMODE=1/0 swapped. I have tried both, anyway, doesn't make any difference to the result. I should be in full AT command mode, I connected 3.3v to pin 34. The password for the ELM327 is 1234, and the default password for the HC-05 is 1234.
If I skip the link stage, then re-power the HC-05 in comms mode, then the ELM327 flashes its green LED which means its transmitting. The HC-05 flashes rapidly, then slowly, then rapidly, then slowly, and so on. But I get nothing in the serial monitor, not even garbled text.
This is the OBD reader I have
This is the HC-05 I have
So I don't know what the problem is, I have connected the HC-05 to my phone as a slave, and can send messages to and from it though the serial monitor. So its working. And the ELM327 is working fine when connected to my phone. So both are working fine.
So my guess is, either I'm missing something, like, maybe the outgoing password/pin is set with a different AT Command other than AT+PSWD? Or, maybe this particular HC-05 for some reason isn't capable of master mode? Or maybe the ELM327 I have for some reason will never accept a connection from something other than an android phone?
I just wondered if anyone has some experience with this, and can advise, before I go off and buy another HC-05 and another ELM327. Thanks in advance for any help.
Just for more information, I'm using an ESP32, which I know has bluetooth and I wanted to use it, but I couldn't find how to enter it's AT Commands (at least, not easily), it was just easier to buy a HC-05. So since the ESP32 has 3.3v outputs I don't use a voltage divider. I use the 5V out for the VCC on the HC-05, and I use the 3.3v out to go directly to pin 34. Here's the sketch I use to enter AT Commands:
#include "HardwareSerial.h"
#define RXD2 16                //Arduino pin connected to Tx of HC-05
#define TXD2 17                //Arduino pin connected to Rx of HC-05

HardwareSerial BTSerial(2);

char c=' ';
boolean NL = true;

void setup()
{
  // initialize the 2 serial ports:
  Serial.begin(38400);  //For the arduino to communicate with the PC
  Serial.print("Sketch:   ");   Serial.println(__FILE__);
  Serial.print("Uploaded: ");   Serial.println(__DATE__);
  Serial.println(" ");

  BTSerial.begin(38400, SERIAL_8N1, RXD2, TXD2); //-> HC-05 AT mode baud rate is 38400
  Serial.println("BTserial started at 38400");
  Serial.println(" ");
}

void loop() {

  // Read from the Bluetooth module and send to the Arduino Serial Monitor
  if (BTSerial.available()) {
    c = BTSerial.read();
    Serial.write(c);
   }

  // Read from the Serial Monitor and send to the Bluetooth module
  if (Serial.available()) {
    c = Serial.read();
    BTSerial.write(c);

    // Echo the user input to the main window. The ">" character indicates the user entered text.
    if (NL) { Serial.print(">");  NL = false; }
    Serial.write(c);
    if (c==10) { NL = true; }
  }
}

I have exactly the same problem. Did you find a solution?
I tried to enter the AT-mode by pushing small button and request the status of the device (AT+STATE?). Device status changed from inquaring to connecting. But the module cannot establish a connection with ELM327

Sorry, I didn't find a solution, I emailed the company who made the module, and they said sometimes there are compatibility issues. They couldn't tell me which one would work, theres a few different ones out there. What I ended up doing is using wires, connecting TX/RX on the arduino to the RX/TX on the ELM327, and it works fine.

AT+CMODE=1 (HC-05 will now only connect with the paired device) // tha's wrong, the CMODE that only allow to conect with a device is CMODE=0


text:
Servo PWM Pin seems to be interfering with Wire.onRequest i2C function
A newbie here. I am thinking of interfacing Raspberry Pi with Arduino via I2c to control a few servo motor (as RPi have limited PWM pins). Meaning I would send input from RPi to Arduino to allow to the Arduino to control the servo.
The problem is this: When I was testing the I2C communication alone, it worked fine. The RPI can send a char, and the Arduino Uno can receive and recognize it.
However, when I added in the function to get the Arduino to send PWM signals to the servo, then the program becomes wonky (e.g. when I send over "0x1", the Arduino led should light up, when I send "0x2", the led should turn off. However, once I tried to PWM the servo, it flickers a while and does no light up when I send the signals, and the servo just vibrate a bit, instead of turning to intended position).
And the funny thing is, the code runs (meaning the LED turns on/off accordingly) as long as I do not plug in the servo's signal pin to the Arduino.
What am I missing? Why does the PWM seems to interfere with the I2C, and is there a way to get around this?
My code is below, do pardon me if anything is unclear, I will be more than happy to clarify.
Thanks guys!

#include <Wire.h>
#include <Servo.h>

Servo myservo_1; // create servo object to control lift servo
Servo myservo_2; // create servo object to control entry servo
Servo myservo_3; // create servo object to control exit servo
// twelve servo objects can be created on most boards

int statusLED = 0;
int statusServo = 0;
int pos;

const int ledPin = 13; // onboard LED
const int servo_1 = 3;
const int servo_2 = 5;
const int servo_3 = 9;

static_assert(LOW == 0, "Expecting LOW to be 0");

void setup() {
  Wire.begin(0x8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent);   // register event
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);     // turn LED off

  myservo_1.attach(servo_1);  // attaches the servo on pin 3 to the servo object
  myservo_2.attach(servo_2);  // attaches the servo on pin 5 to the servo object
  myservo_3.attach(servo_3);  // attaches the servo on pin 9 to the servo object

  //Serial.begin(9600);
}

void loop() {

  if (statusServo == 1){
    myservo_1.write(90);
    delay(15);
  }

  else if (statusServo == 2){
    myservo_1.write(0);
    delay(15);
  }

  else {
    myservo_1.write(45);
    delay(15);
  }

}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {

  int c;

  while (Wire.available()) { // loop through all but the last
    c = Wire.read(); // receive byte as a character
  }

  //Serial.println(c);

    if (c == 0x1){
          digitalWrite(ledPin, HIGH); // turn it on
          statusServo = 1;

    }

    else if (c == 0x2){
          digitalWrite(ledPin, LOW); // turn it on
          statusServo = 2;
    }

}

current draw? underpowered?

Make sure, that the servo gets enough power. Also don't power it through the arduino. Instead connect the power source directly to the servo

Hi. I am powering the servo using 4x AA Battery (6V), so it doubt its a power issue. Also, according to my code, the interrupt function should turn the LED on/off cleanly, depending on the byte sent. However, the LED flickers instead when I send a single byte, so I am quite perplexed.

I see you have a Serial print inside the ISR, thats currently commented out. Have you confirmed, that you are receiving the correct data? The symptoms really look like a power issue. Servos can draw much power. Is the Arduino powered from another source (for example USB)? If it's also connected to the same battery pack: how is it connected? Vin normally needs a nit more than 6V max to correctly output 5V


text:
What is the sizeof() Arduino's built in HIGH and LOW?
This might be a stupid question to ask but I'm curious. I decided to test this myself and I got a value of 2 for both HIGH and LOW, why would it output 2?

In Arduino AVR Boards, HIGH and LOW are currently macros:
https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/Arduino.h#L40-L41
#define HIGH 0x1
#define LOW  0x0

This means that sizeof(HIGH) is equivalent to sizeof(0x1). 0x1 is an integer constant. The default type of integer constants is int. On an 8 bit microcontroller like the ATmega2560 used by your Arduino Mega, an int is 16 bits.
That is why sizeof(HIGH) returns 2 (16 bits / 8 bits/byte = 2 bytes).


text:
Uploading my code gets an error : permission denied on Ubuntu 16.04
I have faced this problem for few years ago and I solved it on Ubuntu 14.04 but I don't know why my solution doesn't work right now on Ubuntu 16.04
The Error :

avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied

I'm using the same solution from The guide
Here what I've done :

ls -l /dev/ttyACM*
   from the result : The owner is "root" and the group with access is " dialout
  Then I applied

  sudo usermod -a -G dialout UserName
  sudo chmod a+rw /dev/ttyACM0  Finally logged out and logged in .

After all should be worked but  I still have the same Error , it doesn't work at all , I removed the software and re-installed it didn't work as well

sudo apt-get remove modemmanager

Are you sure with ttyACM0? My Arduinos always show up as ttyUSB0

@chrisl Yes I'm sure . Any help ?

@Majenko still ! , didn't solve it

@chrisl Real Arduinos with an ATMega for the USB use CDC/ACM, so appear as ttyACMx. Clones that use other chips, or ancient Arduinos with an FT232 appear as ttyUSBx.

Did you install the snap app of the Arduino IDE? This is known to not work properly in many cases.

@oh.dae.su No I have never installed it !

Re-check the permissions on the device node now you have logged out etc. Some useful commands: stat /dev/ttyACM0 - check the first "Access:" line.  sudo fuser /dev/ttyACM0 - list processes that are using the device node.

@Majenko When I try to see " sudo fuser ... " that shows " Specified filename /dev/ttyACM0 does not exist. " What does it mean ?

Is the board plugged in at the time you run the command?

@Majenko Yes it is, I unplugged it and plugged back again to try then run the command but the command show nothing actually just press Enter then I got nothing " no result " , and the error still on Arduino software

If it returns nothing then nothing is locking the device. That's good. How about the first Access: line from the stat command?

@Majenko That return " (0660/crw-rw----)  Uid: ( 1001/     moh)   Gid: ( 1001/     moh) "
Note : moh is the user , and it's already member of dialout "the group with access" , what do you think ?

How about if you type echo foo > /dev/ttyACM0 - does that return anything?

Finally ! I got it , it works now ! Thank you so much , appreciate your help

What did you do to make it work?


text:
IR module sensor query for Line Follwer Robot

Are the IR sensors used in Line following Robot and Obstacle avoidance Robot with Arduino UNO different ? If yes , where do we buy these parts online ? I used the following sensor in my Line Follower and am not getting result as it’s detecting obstacle instead of black line .

The sensor you have used is fine. There is a potentiometer on the sensor PCB that is used for the range. For the line following robot you would want the range small, between 1-4cm. However, for the obstacle avoidance robot you would want to set this for a much larger range, say 10-45cm.
To make an effective line following robot you need at least 2-3 sensors.
Here is one using 2 LEDs either side of the line:

And here is a 3 sensor robot:

Notice that one LED stays on the line.
And finally a 5 sensor robot:

The following websites have good step by step guides where they explain the various techniques:

https://www.learnrobotics.org/blog/how-to-build-a-mobile-robot-using-arduino-part-4/
https://circuitdigest.com/microcontroller-projects/line-follower-robot-using-arduino
http://www.robotc.net/wikiarchive/Tutorials/Arduino_Projects/Mobile_Robotics/VEX/Using_the_line_tracker_to_follow_a_line

When I made my line following robot I used 2 of the following sensor:

These sensors were great as they pointed in towards each other, making a focal point. You can do this to your sensor by bending the LEDs slightly towards each other.

For obstacle detection you would usually use a different IR sensor, yes. The IR sensors usually used for line following only work at a very short range (typically <1cm). For a robot detecting obstacles you want a sensor that detects an obstacle further away, say at a 30-60 cm distance, so the robot can evade the obstacle before it runs into it.
Common IR sensors for obstacle detection look like this:

The IR sensor you showed probably send a 0V or 5V, true or false value to a digital input of your arduino. The IR distance sensor shown above sends an analogue value (range 0-5v) to an analogue input of an arduino. They come in different ranges. Ranges go from ± 10 cm to ±5m (rough indication).
But personally I prefer to use the common HC-SR04 ultrasonic distance sensor instead of infrared ones. They have a larger usable range, a less noisy signal and detect more different types of objects. That's my personal experience from side-by-side comparison.

I'm reluctant to mention online shops on where to buy them. They're very common sensors.


text:
Parsing using the ArduinoJson library
I am trying to parse JSON using the ArduinoJson library. The problem is that I can’t parse www.read() because it’s declared as a char. I think www.read() needs to be a string? How can I convert www.read() into a format that jsonBufffer.parseObject() can understand? Please excuse any lack of terminology. I am new to using JSON.
When I run the code I get to the point where it prints "-------------------------------------” then it does nothing.
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include "utility/debug.h"
#include <ArduinoJson.h>

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,
ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
SPI_CLOCK_DIVIDER); // you can change this clock speed

#define WLAN_SSID       "WLAN_SSID_HERE" // cannot be longer than 32    characters!
#define WLAN_PASS       "WLAN_PASS_HERE"
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

#define IDLE_TIMEOUT_MS  300000      // Amount of time to wait (in milliseconds) with no data
// received before closing the connection.  If you know the server
// you're accessing is quick to respond, you can reduce this value.

// What page to grab!
#define WEBSITE      "wefeel.csiro.au"
#define WEBPAGE      "/api/emotions/primary/totals"

StaticJsonBuffer<200> jsonBuffer;

uint32_t ip;

void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  /* Initialise the module */
  Serial.println(F("\nInitializing..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }

  Serial.print(F("\nAttempting to connect to "));
  Serial.println(WLAN_SSID);
   if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /* Display the IP address DNS, Gateway, etc. */
//  while (! displayConnectionDetails()) {
 //    delay(1000);
//  }

  ip = 0;
  // Try looking up the website's IP address
  Serial.print(WEBSITE);
  Serial.print(F(" -> "));
  while (ip == 0) {
    if (! cc3000.getHostByName(WEBSITE, &ip)) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
   }

  cc3000.printIPdotsRev(ip);

}

void loop(void)
{
  char c;
  Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 80);
  delay(300);
  if (www.connected()) {
    www.fastrprint(F("GET "));
    www.fastrprint(WEBPAGE);
    www.fastrprint(F(" HTTP/1.1\r\n"));
    www.fastrprint(F("Host: "));
    www.fastrprint(WEBSITE);
    www.fastrprint(F("\r\n"));
    www.fastrprint(F("\r\n"));
    www.println();
  }
  else {
    Serial.println(F("Connection failed"));
    return;
  }

  Serial.println(F("-------------------------------------"));

  unsigned long lastRead = millis();
  while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    //Serial.print(www.available());
    while (www.available()) {

      //Serial.print(c);
      //char json[] = www.read();
    }
  }
  c = www.read();
  Serial.print(c);
 JsonObject& root = jsonBuffer.parseObject((char*)c);
 if (!root.success()) {
    Serial.println("parseObject() failed");
    return;
    }

  long love = root["love"];
  long other = root["other"];
  long sadness = root["sadness"];
  long anger = root["anger"];
  long joy = root["joy"];
  long surprise = root["surprise"];
  long fear = root["fear"];

  Serial.println(love);
  Serial.println(other);
  Serial.println(sadness);
  Serial.println(anger);
  Serial.println(joy);
  Serial.println(surprise);
  Serial.println(fear);

  www.stop();
  delay(100);
  www.close();
  delay(200);
 }

First you never setup the HTTP header with "Content-Type: application/json", so the data return might not be in json as you want. Secondly, you need to create a buffer to store the response back from the server within the while(www.available()) { buffer[i++]=www.read(); } (i.e. read the data char by char and store in the buffer), then you can parse the return data in the buffer with JsonObject& root=jsonBuffer.parseObject(buffer);.

There are two read methods. One that returns a single character (or error), and one that populates a buffer; you want the latter, with method signature int read(char* buf, size_t len) or some such. Read the source.
When allocating the json buffer in StaticJsonBuffer<200> jsonBuffer;
, make sure your expected json data fit in 200 bytes.

Thank you for responding to my problem. I'm assuming you would use  jsonBuffer as uint8_t *buf but what value do I use for size_t len?

no, jsonBuffer has to still be a StaticJsonBuffer. It's what you read() into that should change. Something along the lines of:
char buf[256];
size_t n_read = www.read(buf, 255);
buf[n_read] = '\0';

You need the third line because parseObject expects a nul-terminated string.

I really appreciate your help. I think Im following you but am still unclear what I need to do next. Im thinking it is calling jsonBuffer.ParseObject but I was thinking that I would have it parse n_read which seems to be incorrect? What variable should I perform the parse on?


text:
How to interface DS1801 digital resistor with Arduino DUE SPI interface? What clock rate so use?
I am trying to program a digital resistor and set it's wiper resistance. The general circuit looks a little like this where "pot" represents the Maxim DS1801 digital resistor and DUE is, of-course the 3.3v Arduino DUE.
POT       DUE
CLk ----> SCK
D    ----> MOSI
RST ----> CS (ChipSelect) (PIN10)

Now so far, I have sucessfully been able to interface with the DS1801, but I am having issues determining how to properly set the wiper resistance values. The DS1801 datasheet says the it accepts a 16bit input and from application example online it looks like the values range from 0 to 64. Here is my code:
// include the SPI library:
#include <SPI.h>

// set pin 10 as the slave select for the digital pot:
const int slaveSelectPin = 10;
int mute = 64;
int loud = 63;
int soft = 0;

void setup() {
  // set the slaveSelectPin as an output:
  pinMode (slaveSelectPin, OUTPUT);
  // initialize SPI:
  SPI.setBitOrder(LSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(slaveSelectPin,SPI_CLOCK_DIV8);
  SPI.begin();
  delay(10);
   digitalPotWrite(mute, mute);
}

void loop() {

  // Raise the volume from off to loud
for(int i = 0; i <= 63; i++){
  digitalPotWrite(i, i);
  delay(5);
    }
  }

void digitalPotWrite(int left, int right) {
  // take the SS pin low to select the chip:
  digitalWrite(slaveSelectPin, HIGH);
  //  send in the address and value via SPI:
  SPI.transfer(left);
  SPI.transfer(right);
  // take the SS pin high to de-select the chip:
  digitalWrite(slaveSelectPin, LOW);
}

I THINK my issue lies with setting the clock rate for the DS1801. The data sheet say the chip runs at 10MHz which is why I wrote
SPI.setClockDivider(slaveSelectPin,SPI_CLOCK_DIV8);

to divide the 84MHz default speed down to 10MHz.
Anyone have suggestions on why my code is not working??? At the moment, I have LED's connected to chip with series resistors to limit current below 2mA. The resistors just blink randomly with the code posted above.

10MHz is too high to have flapping around in the breeze. Show your circuit setup.

I'm not exactly sure what you mean by that? lol   ... Okay, I'll go snap a picture of the circuit and update my post. Why would 10MHz be too high if that's what it says in the datasheet? I don't doubt you, I'm just wondering thats all!   :)

Poor wiring can turn a 10MHz signal into a dog's breakfast, so extra care must be taken when routing such.

Alright, I threw up some pictures, hopefully you can make that out.... essentially, blue is the bit line (D - MOSI), white is the 10MHz clock, and green is Chip Select (or RESET as the datasheet calls it)

Well, it turns out that apparently my issue was not having the AGND pin hooked up. In addition to that, I was trying to switch the wiper resistance value too quickly. By putting at least a 10ms delay between calls, it works much better.
Also, it does seem to work even at 10MHz just fine...

There is no way in hell you're going to get a 10MHz signal down that line. Shorten it to 3 inches total maximum and reduce the clock rate to 2MHz or lower. It is possible to get a 10MHz signal through, but you'd need to switch to twisted pair wiring and proper termination to even begin to have a chance to get it to work.