text:
Capturing avrdude command in IDE
With verbose upload selected the IDE provides the executed avrdude command at the top of the log.
I am interested in copy pasting that avrdude command. However at the end of the upload the command is not available anymore. The IDE only shows some last lines of the log and discard the top part.
Is that log saved anywhere? (I am on ubuntu). Any ideas how I can get that command?

If you run the IDE from a terminal you should get the output to STDOUT in your terminal to do with what you want.

That's the solution. Thanks a lot. I am using arduino | tee cmd.txt to capture it.

Disconnect the arduino from your PC before pressing upload. That way you get less output and it won't overwrite the top lines.

If you run the IDE from a terminal you should get the output to STDOUT in your terminal to do with what you want.


text:
Why is my transistor always transmitting?
I want to use a transistor to turn on and of an electric magnet, I have hooked up a transistor like this:

simulate this circuit – Schematic created using CircuitLab
The blue wire goes to the magnet and the white wire goes to the ground:

Regardless of if the arduino is on or off(I can even unplug port 12 from the arduino, the magnet is still on, the circuit never closes. What do I need to do to make the transistor turn off?

If you detach the base connection to the Arduino, it must close then. If not, you have reversed power source and the internal anti-parallel diode is opened. Or you've already destroyed your transistor.

What is the part number? TIP120? Sounds to me like a transistor with a different pinout.

Don't forget the freewheeling diode across the coil.

Did you make the electromagnet your self?If so some magnets will retain their magnetism for long time making it appear your circuit is not off. If you raplidy switch on or off too quickly may look like its on because it may retain magnetism

@Gerben, yes TIP120, https://cdn-shop.adafruit.com/datasheets/TIP120.pdf .

Looks like you connected it the right way around.

@Gerben Right way around = No need to change?

Sorry for the confusion. I you connected if perfectly. So that can't be the problem.

Darlington transistors are very sensitive; even putting your hand near it can be enough to turn it on. Either tie the base to ground with a large resistor or switch to a MOSFET with its gate tied to ground through same. In either case put a diode backwards across the coil to absorb the energy from the coil when it de-energizes so that the transistor is not damaged.

Could you suggest a good MOSFET-transistor for a 12V magnet?

I would recommend going to the web site of a distributor such as DigiKey or Mouser and using their parametric search tool to find an appropriate device.

@Himmators You dont need to MOSFET it, it  will work with a tip 120 if you build the circuit, using TIP 120, correctly. The darlington is "sensitive" to your hand, which really isnt a problem . Its sensitive because it has high gain- high gain is  useful  for driving something like an electromagnet.

@DatHanBag, thanks! Do you have any idea what might cause the problem?

@Himmators You may have damaged the TIP 120 transistor for some reason- since you need a dioide in the first place-as Edgar wrote above. I would start with a new TIP120 with the diode to protect it,  Tie the base to ground as its says in the answer-this is important. Make sure your circuit is correct. If your base resistor is too low it wont work properly too-so try base resitor values from 10k -maybe as low as 4K will work.

source: Stack Exchange

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

sort: votes


text:
Hold a random number
I am trying to create a code that has at least 6 servos attached and two buttons for a two player game. I want to be able to roll a random number and have it hold that value then when it is that players turn. The program should also take that previous number and add it to the next. It would eventually be adding up all the values of the rolls. This is what I have so far. Any advice would be helpful. Thanks!
#include <Servo.h>

Servo myservo;

int pos = 0;    // variable to store the servo position
int x;
int button = 8;
int BUTTON;
int randomNumber;
int xPrevious;

void setup() {
    pinMode(button, INPUT);
    Serial.begin(9600);
}

void loop() {
  for (x = 2; x <= 7; x += 1) {
    myservo.attach(x);

    for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position

      BUTTON = digitalRead(button);
      if(BUTTON == LOW){
        randomNumber = random(1,7);
        delay(350);
        Serial.println(randomNumber);
      }
    }
    randomNumber += xPrevious;
  }
}

You are redefining the random number wrongly each time with
randomNumber += xPrevious;

this is an error. You need another new variable (initialised at 0) to keep the running totals of all the random "rolls". You should be able to fix your program now you know this. Maybe something like
TotalofTherandomNumbers += xPrevious;

to start off with.
You may also want to add in the after the line
 randomNumber = random(1,7);

a new function, of yours, that takes random value randomNumber  do the action in the game, what ever that is,  depending on if its the first or second player.

Your xPrevious is declared but never given any value.
Is this what you're looking for?
    randomNumber += random(1,7);

Another thing is that you should not assume that randomNumber is initialized to 0. Better assign it a starting value.
    int randomNumber = 0;   // or whatever you want

Lastly, an Arduino int is a 2 bytes signed number. If the game goes on for a long time the variable will roll over at 32,767. Consider making it a unsigned long instead.

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


text:
Having problems compiling this code for NRF24l01 on arduino uno and arduino micro
I have the library RF24 and everything in my arduino library but for some reason it's not compiling.  I don't know why. I posted the code and also the error message that the arduin IDE keeps showing. Please help me figure out whats wrong!
Arduino: 1.6.12 (Windows 7), Board: "Arduino/Genuino Uno"

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::read_register(unsigned char, unsigned char*, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::read_register(unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::write_register(unsigned char, unsigned char const*, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::write_register(unsigned char, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::openReadingPipe(unsigned char, unsigned long long)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setAutoAck(bool)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setAutoAck(unsigned char, bool)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::read_payload(void*, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::flush_rx()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::getDynamicPayloadSize()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::flush_tx()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::get_status()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::available(unsigned char*)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::print_status(unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::print_observe_tx(unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::print_byte_register(char const*, unsigned char, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::print_address_register(char const*, unsigned char, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::RF24(unsigned char, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::RF24(unsigned char, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setChannel(unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setPayloadSize(unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::getPayloadSize()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::stopListening()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::powerDown()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::powerUp()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::write(void const*, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::available()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::read(void*, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::whatHappened(bool&, bool&, bool&)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::openWritingPipe(unsigned long long)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::startListening()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::toggle_features()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::enableDynamicPayloads()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::enableAckPayload()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::writeAckPayload(unsigned char, void const*, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::isAckPayloadAvailable()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::isPVariant()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::testCarrier()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::testRPD()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::getPALevel()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setDataRate(rf24_datarate_e)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::getDataRate()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setCRCLength(rf24_crclength_e)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::getCRCLength()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::printDetails()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::disableCRC()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setRetries(unsigned char, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::begin()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

Multiple libraries were found for "nRF24L01.h"
 Used: C:\Users\Owner\Documents\Arduino\libraries\RF24ArduinoCommunicator-master
 Not used: C:\Users\Owner\Documents\Arduino\libraries\RF24-master
 Not used: C:\Users\Owner\Documents\Arduino\libraries\RF24-master
 Not used: C:\Users\Owner\Documents\Arduino\libraries\RF24-master
 Not used: C:\Users\Owner\Documents\Arduino\libraries\RF24-master
exit status 1
Error compiling for board Arduino/Genuino Uno.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Example I tried to compile:
/*
 Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 version 2 as published by the Free Software Foundation.
 */

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"

//
// Hardware configuration
//

// Set up nRF24L01 radio on SPI bus plus pins 9 & 10

RF24 radio(9,10);

//
// Topology
//

// Radio pipe addresses for the 2 nodes to communicate.
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

//
// Role management
//
// Set up role.  This sketch uses the same software for all the nodes
// in this system.  Doing so greatly simplifies testing.
//

// The various roles supported by this sketch
typedef enum { role_ping_out = 1, role_pong_back } role_e;

// The debug-friendly names of those roles
const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"};

// The role of the current running sketch
role_e role = role_pong_back;

void setup(void)
{
  //
  // Print preamble
  //

  Serial.begin(57600);
  printf_begin();
  printf("\n\rRF24/examples/GettingStarted/\n\r");
  printf("ROLE: %s\n\r",role_friendly_name[role]);
  printf("*** PRESS 'T' to begin transmitting to the other node\n\r");

  //
  // Setup and configure rf radio
  //

  radio.begin();

  // optionally, increase the delay between retries & # of retries
  radio.setRetries(15,15);

  // optionally, reduce the payload size.  seems to
  // improve reliability
  radio.setPayloadSize(8);

  //
  // Open pipes to other nodes for communication
  //

  // This simple sketch opens two pipes for these two nodes to communicate
  // back and forth.
  // Open 'our' pipe for writing
  // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading)

  if ( role == role_ping_out )
  {
    radio.openWritingPipe(pipes[0]);
    radio.openReadingPipe(1,pipes[1]);
  }
  else
  {
    radio.openWritingPipe(pipes[1]);
    radio.openReadingPipe(1,pipes[0]);
  }

  //
  // Start listening
  //

  radio.startListening();

  //
  // Dump the configuration of the rf unit for debugging
  //

  radio.printDetails();
}

void loop(void)
{
  //
  // Ping out role.  Repeatedly send the current time
  //

  if (role == role_ping_out)
  {
    // First, stop listening so we can talk.
    radio.stopListening();

    // Take the time, and send it.  This will block until complete
    unsigned long time = millis();
    printf("Now sending %lu...",time);
    bool ok = radio.write( &time, sizeof(unsigned long) );

    if (ok)
      printf("ok...");
    else
      printf("failed.\n\r");

    // Now, continue listening
    radio.startListening();

    // Wait here until we get a response, or timeout (250ms)
    unsigned long started_waiting_at = millis();
    bool timeout = false;
    while ( ! radio.available() && ! timeout )
      if (millis() - started_waiting_at > 200 )
        timeout = true;

    // Describe the results
    if ( timeout )
    {
      printf("Failed, response timed out.\n\r");
    }
    else
    {
      // Grab the response, compare, and send to debugging spew
      unsigned long got_time;
      radio.read( &got_time, sizeof(unsigned long) );

      // Spew it
      printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time);
    }

    // Try again 1s later
    delay(1000);
  }

  //
  // Pong back role.  Receive each packet, dump it out, and send it back
  //

  if ( role == role_pong_back )
  {
    // if there is data ready
    if ( radio.available() )
    {
      // Dump the payloads until we've gotten everything
      unsigned long got_time;
      bool done = false;
      while (!done)
      {
        // Fetch the payload, and see if this was the last one.
        done = radio.read( &got_time, sizeof(unsigned long) );

        // Spew it
        printf("Got payload %lu...",got_time);

        // Delay just a little bit to let the other unit
        // make the transition to receiver
        delay(20);
      }

      // First, stop listening so we can talk
      radio.stopListening();

      // Send the final one back.
      radio.write( &got_time, sizeof(unsigned long) );
      printf("Sent response.\n\r");

      // Now, resume listening so we catch the next packets.
      radio.startListening();
    }
  }

  //
  // Change roles
  //

  if ( Serial.available() )
  {
    char c = toupper(Serial.read());
    if ( c == 'T' && role == role_pong_back )
    {
      printf("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK\n\r");

      // Become the primary transmitter (ping out)
      role = role_ping_out;
      radio.openWritingPipe(pipes[0]);
      radio.openReadingPipe(1,pipes[1]);
    }
    else if ( c == 'R' && role == role_ping_out )
    {
      printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n\r");

      // Become the primary receiver (pong back)
      role = role_pong_back;
      radio.openWritingPipe(pipes[1]);
      radio.openReadingPipe(1,pipes[0]);
    }
  }
}

You have multiple copies of the library.
Delete the folder located at:
C:\Users\Owner\Documents\Arduino\libraries\RF24ArduinoCommunicator-master

ok I deleted that file now it says "void value not ignore as it out to be" and then the line "done = radio.read( &got_time, sizeof(unsigned long) );" is highlighted. Is there something that I missed?

You can't assign nothing (void) to something (boolean "done"). Use radio.available() instead to see if there's something in the buffer waiting to be read.


text:
Speed of comunication by SI4463 under RH_RF24.h
As in this SO question, I use use a RH_RF24.h to control an SI4463. In RH_RF24, there is not anything about the speed of communication. I need the way to control the speed of communication. Because I want to take high speed of communication when Rssi is strong and slow speed when weak (for reliability).
How should I to do it ?

Brief look at the docs suggest you define the modem config (modulation type and speed) using one/some of these values : http://www.airspayce.com/mikem/arduino/RadioHead/structRH__RF24_1_1ModemConfig.html

@KennetRunner  Thanks. Seemly , I can use setModemRegisters(prop_2003) , or  prop_2004, prop_2005 to set data rate (in fact, I am not sure whether I can do so ). But , I don't know the data rate of them .For example , what is the data rate of prop_2004, how to find it ?  Besides, when I low data rate, whether rate of messy code will become low ?

According to RH_RF24.h setModemRegisters takes a ModemConfig struct.  prop_2003, prop_2004 and prop2005 are part of that struct and it's the value of these 3 bytes that sets the datarate.
Datarate is a 24bit unsigned value (hence the 3 bytes in the struct). prop_2003 is the MSB and prop_2005 the LSB.

prop_2003 default is 0x0F
prop_2004 default is 0x42
prop_2005 default is 0x40

meaning the default data rate is 0x0F4240 ( = 1Mbps)
This application note on the API gives more details (around page 99).

What is the mean of 1Mhz ? It means I can communicate by speed of 1000000 bps ? But I rember the speed of SI4463 is slow. Besides , how to use setModemRegisters ?  For example ,because datarate is a 24bit unsigned value . How to write parameter of setModemRegisters ? Just setModemRegisters(prop_2003, prop_2004,prop_2005)   ?

Or just setModemRegisters(0x0F4240)   ? And could you help me in this question http://arduino.stackexchange.com/questions/31150/how-to-use-setmodemregistersin-rf24 ? Thanks very much.


text:
How to use ESP8266-12E with PCF8574 as an I/O extender
I am using ESP8266-12E with a PCF8574 as an I/O Pins Extender.
There are videos on youtube to use the PCF8574 with an ESP8266-01, but my problem is that I'm unable to analyze the pin connections with an ESP8266-12E.
In the youtube tutorial it is said that the GPIO0 AND GPIO2 will go to the SDA and SLC pins of the PCF8574, but then, in the case of ESP8266-12E, the pins will go to the PCF8547.
Thanks in advance.

What is the link to Arduino UNO as you tagged your question?

sorry , i thought people who knows arduino things might also know this.

The '8C-ESP8266 Interface I2C' document may help, if you have access to it.  It's available on Scribd, which is non-free.  One can see the  first page of '8C-ESP8266 Interface I2C' without a Scribd subscription

@jwpat7 : thanks . only first page , unfortunately cover page is visible in free.

i guess very less people plays with such things o wat!

Found the answer .
The data sheet of ESP8266-12E explains everything.
The pin diagram has the given tags which shows which pins we can use.

Would you mind detailing the answer so that your question can bring benefits to other people having the same question?

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review

@jfpoilpret, he IS the author...

i have added details to the answer.

@DatHa this comment was automatically generated from my delete vote; please don't think I can be so stupid, thanks.

@all : is my way wrong to provide and declare answer. if yes plz guide.

@karmaCoding, it could have a little more detail. You could add a wiring diagram and/or code you used to get it working. In that way, others can easily verify and/or use it.


text:
strtok problem while parsing String
Here is my code. The incoming string is "*CRB12344,Temp25,Humidity55,CC5#"
I am unable to get value of Temp which is 25 and Humidity which is 55 and CC which 5. It only display the value of CR i.e B12344 (in this case). May be issue with strtok function?
String inputString = "";
boolean stringComplete = false, StartCapturing = false;

char inData[50];
char inChar, IncomingWeight;
char IncomingString[50];
const int httpPort = 80;

char *i, *k,*p;
String CardID;
int Temprature, Humidity, TC, CC;
byte SendData = 0;

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

void loop()
{
  serialEvent();

  if (stringComplete)
  {
    inputString.toCharArray(IncomingString, 50);
    Serial.println();
    Serial.println(IncomingString);

    i = strstr(IncomingString, "CR");
    {
      if (i)
      {
        p = i+2;
        CardID = strtok(p, ",");

        Serial.print("Card Number :");
        Serial.print(CardID);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "Temp");
    {
      if (i)
      {
        Temprature = strtoul(i + 4 , NULL, 10);
        Serial.print("Temprature :");
        Serial.print(Temprature);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "Humidity");
    {
      if (i)
      {
        Humidity = strtoul(i + 8 , NULL, 10);
        Serial.print("Humidity :");
        Serial.print(Humidity);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "TC");
    {
      if (i)
      {
        TC = strtoul(i + 2 , NULL, 10);
        Serial.print("Total Count :");
        Serial.print(TC);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "CC");
    {
      if (i)
      {
        CC = strtoul(i + 2 , NULL, 10);
        Serial.print("Current Count :");
        Serial.print(CC);
        Serial.println();

      }
    }

    stringComplete = false;
    inputString = "";
    delay(10);
  }

strtok() is a destructive function. It replaces the token with an end-of-string marker (\0). Thus once used the original string is irevocably lost.
Your first use of strtok() changes the string from:
*CRB12344,Temp25,Humidity55,CC5#\0

to:
*CRB12344\0Temp25,Humidity55,CC5#\0

Thus any future references to InputString only see up to the end-of-string marker:
*CRB12344\0

Instead you should use strtok() in a while loop to slice the string into tokens and examine what the token is:
char *tok = strtok(IncomingString, ",");
while (tok) {
    if (strncmp(tok, "*CR", 3) == 0) { // tok is *CRB1234
        // ... whatever ...
    } else if (strncmp(tok, "Temp", 4) == 0) { // tok is Temp25
        // ... whatever ...
    } else if (strncmp(tok, "Humidity", 8) == 0) { // tok is Humidity55
        // ... whatever ...
    } else if (strncmp(tok, "CC", 2) == 0) { // tok is CC5#
        // ... whatever ...
    }
    tok = strtok(NULL, ","); // Note: NULL, not IncomingString
}

Didn't know this. I understand the mistake now.


text:
Arduino Pro Mini RESET button suddenly stopped working
I am powering my Pro Mini(3.3V version) using an external battery (~6.5V 700mA) . I used to connect it to the RAW and GND pins on my pro mini and everything ran fine.
Today when I powered up my Arduino again, it didn't light up. A quick glance told me that I had connected the battery to the RST and GND pins mistakenly. Quickly pulled them out and put them into place, the Arduino worked perfectly until I discovered that the RESET button is no longer working. Without the RESET button I can't upload anything to my board.
Tried connecting the RST and GND Pins, didn't work.
The board is working fine though, I discovered a new procedure to upload as follows-
NOTE: I use the USB-to-TTL adapter by DSUN (picked up at a local electronics store).

Connect the RX, TX and GND Pins from the adapter to the Pro Mini.
(The green LED on the Pro Mini lights up dimly)
Upload the sketch from the IDE.
As soon as the IDE shows "Uploading", connect the +5V pin from the adapter to RAW pin on Pro Mini. Upload goes fine.

The above procedure is working just fine, and the board as well. But I'd like to have my RESET button back.
So what do I do?

You could probably still use that Arduino in a final project where compilation will only happen once, other wise RIP.

You can buy a Arduino Pro Mini for $2 or less, so I guess it not worth using-It's dead Jim. "Do not grieve, Admiral. It was logical."

What do you do? You replace the chip on the board.
By pumping 6.5V through the RESET pin with no power attached you have irrevocably broken the reset pin inside the chip. Way too much current will have flowed through the internals of the pin leaking its way up to the VCC pin and then back down through the rest of the chip to ground, burning out vital parts of the internal logic of the pin.
It's dead, Jim.
Your "fix" basically relies on the fact that the bootloader runs for any kind of reset - be that a RESET pin reset or a POR (Power-On Reset).

Hmmm so my fix can still get the board running anyways right?

Yep. As long as there is a power-up event (even a brief drop-out of power would do) the bootloader will run.

As if holding the RESET button while uploading wasn't annoying enough. Anyways thanks!


text:
Arduino IDE crash when I connect Blend Micro
I recently bought Blend Micro and I am setting up Arduino IDE to start using it, but after installing the required libraries and the Blend Micro drivers, the IDE suddenly crashes without any visible error whenever I plug the blend micro to my PC. If it is already plugged in, the ide won't even start up. This was not happening before I installed the drivers. I don't know if it's relevant but blend micro was connected to my pc during the drivers installation. I have already looked for a way to solve this on Google without relevant results.
I am using Windows 10 with Arduino IDE 1.6.12
I would really appreciate any help with my problem, thank you in advance.

Reboot the PC, try an other one, try a different USB port, try uninstalling the IDE and reinstalling it...

I have already tried all those 3 things and they did not work...

I count 4 things there...

Yes, I did all 4, the 3 was a typo

The final solution to my problem was to download the latest arduino hourly build. There is probably a bug in the stable version that has been solved in the hourly build.

you should try to run the arduino from the consolle, on windows digit cmd on the search bar and the command promp program should appear.
Well, then you should navigate in out arudiono folder: digit cd "XXX" where XXX is the arduino executable location (something like c:/program files/blabla), you can copy paste it from the folder explorer.
then write arduino_debug.exe and you should see on the terminal the error appear; with that we may find the issue.

arduino_debug.exe may provide more information.

@per1234 fixed, thanks, I use win only to play so im a bit rust on that side xD


text:
Power an arduino on a 12V circuit
I am doing a simple circuit with a 12V power supply to power a 12V LED strip. I'd like to be able to switch ON/OFF the strip with a relay connected to my Arduino. I'd like to know if I can power my Arduino directly from the VIN pin using 12V source. I saw that the Arduino can support up to 12V.
Thank you in advance for the help.

Product page says?

I saw that the arduino can support up to 12V - isn't this your answer?

Not from Vin pin probably. But from the power-in jack.

this question about stripleds has been asked too many times, try reading some answers to learn more about how they work , and power sensitivity from 12 to 14.2V.. see related on right side

Possible duplicate of Controlling 7W 12-14V power LED with Arduino

I just want to know how to wire my arduino to a 12V power supply, the question is not about the led part. I couldn't find a clear answer about that

So now can you update us about which part is still not clear?

As you have noted, many Arduino (and clones) are rated for supply voltage up to 12V. But note that if you use 12V power, the on-board regulator will get rather hot.  Providing decent ventilation and maybe even extra heat sink would be a good idea.

The answer is yes, you can. Since there are no information about which Arduino you are using, Lets assume that you use Arduino uno. Based on the official webpage documentation, the recomended voltage input is ranging from 7 - 12 V. Therefore it is possible.


text:
Arduino IDE in conflict with pyserial for use of serial port in OSX Yosemite
I'm trying to communicate with an Arduino Uno via pyserial using a code that I wrote for Ubuntu. However, when I try to use the same code in OSX Yosemite after identifying the serial port for the case of OSX, it doesn't work. This is the offending line:
In [32]: ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

If I run the above line when the Arduino IDE is not running there is no error message, but the Arduino doesn't do anything (the Arduino IDE Serial Monitor must be open in order for the code to work). However, if I open the Arduino IDE and use the Serial Monitor (which works fine, i.e. it shows data that the Arduino is sending), I get the following error message:
SerialException: [Errno 16] could not open port /dev/cu.usbmodem1421: [Errno 16] Resource busy: '/dev/cu.usbmodem1421'

If I run lsof | grep /dev/cu.usbmodem1421 then I get that the only program using said port is Arduino IDE:
Arduino   2012 germanchaparro   94u     CHR               18,7   0t15249    1285 /dev/cu.usbmodem1421

Clearly OSX is not letting Arduino IDE and pyserial to use the serial port (to which the Arduino UNO is connected) at the same time. I don't know how to fix this, and it's especially frustrating since Ubuntu doesn't put up a fight.
Any ideas?

You need to work out why Python isn't working. There is no reason to need the IDE terminal open unless your code is doing things very wrong.

You're right, I can get pyserial to work without the IDE monitor open, although I'm having a hard time printing out the serial output from the Arduino. It seems it's mostly a matter of giving the code enough time between pyserial r/w instructions. It just baffles me how different (and simpler) pyserial works in Ubuntu.

Ok, I solved it. First I stopped using the IDE serial monitor as Majenko suggested, and focused on getting the Arduino readings within the python code. Besides trying to use the python code and the IDE monitor at the same time (which apparently you can do in Ubuntu but not in OSX), the original problem was that my python code was not clearing the serial buffer in the r/w process. In order to do this, I wrote the following function to be called before and after a serial write:
 ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

 def readarduino(ser):
    did=True
    while ser.inWaiting(): # Check number of characters left in buffer
        if did and ser.inWaiting() < 490: # Select last 500 characters in buffer
            for i in range(6):
                print ser.readline() # Print 6 lines in buffer
            did = False
        ser.readline()  # Clear buffer line by line until ser.inWaiting goes to 0

This ensures that the buffer is clear whenever I am writing to the Arduino.
This solution works for OSX Yosemite and Ubuntu 14.04


text:
How do I output tone() and audioFX board output through a single speaker?
I'm building a BMX start gate controller. It requires a voice sample to be played ("Riders ready, watch the gate!") before playing a series of tones at very specific frequencies and intervals. After the tones are complete, a relay is triggered which drops the start gate.
I'm intending to use one of the header pins with the tone() function to output the tones, and an Adafruit AudioFX board to play the voice sample.
How do I connect both of these to an Adafruit mono amplifier (https://www.adafruit.com/product/2130) ?
Note that only one or the other will be playing at one time.
Can I use a "passive mixer" (which I think is putting a 10kΩ resistor on each input source for the amplifier?)

Yes, a passive mixer would do fine. I would recommend capacitors to remove any DC component too, before you do the mixing. 22uF should do fine.
I will draw a circuit in the morning.


text:
How can I use stepper for specific degree?
I use Arduino and I'm beginner. I use the code below, but I don't understand what stepper.step(num) and STEPS in Stepper stepper(STEPS, 2,3,4,5) are, and I want to use stepper for specific degree and I don't know what I can do. for example if I want to use stepper for 40 degree what are STEP and num?
#include <Stepper.h>

// change this to the number of steps on your motor
#define STEPS 100

// create an instance of the stepper class, specifying
// the number of steps of the motor and the pins it's
// attached to
Stepper stepper(STEPS, 2,3,4,5);

// the previous reading from the analog input
int previous = 0;

void setup()
{
  // set the speed of the motor to 30 RPMs
  stepper.setSpeed(100);
}

void loop()
{
  // get the sensor value
  //int val = analogRead(0);

  // move a number of steps equal to the change in the
  // sensor reading
  //stepper.step(val - previous);
  stepper.step(25);
  delay(1000000);
 // stepper.step(-5);

  // remember the previous value of the sensor
  //previous = val;
}

-----------------------------------------EDIT #2-----------------------------
my stepper is the first one in this link:
https://grahamwideman.wikispaces.com/file/view/28byj48_models_table.jpg/538898220/604x265/28byj48_models_table.jpg
( I think! )
and I don't know what it means?
------------------------------------------EDIT #3----------------------------
Thank you very much, I saw the link.

Step Angle (8-Step sequence: Internal Motor alone): 5.625° (64 steps
  per revolution)

and I run this code for 45deg :
#include <Stepper.h>

#define STEPS_PER_MOTOR_REVOLUTION 32
#define STEPS_PER_OUTPUT_REVOLUTION 32 * 64  //2048
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 2, 3, 4, 5);

int  Steps2Take;

void setup()
{

}

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{

  Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 8.11;
  small_stepper.setSpeed(100);
  small_stepper.step(Steps2Take);
  delay(10000);
}

because I understand each turn has 2048 steps, for example if I want to have 1/2 turn, I have to have num=1024 ( 2048/2). ok, So, for 45deg, it's 1/8 turn so I have to set num=2048/8. but for example for 33 deg what should I do?
I thought num= 33*5.61
so for 45deg I use num=45*5.61
you know we have a lot of floating point and I'm not sure we do it correct. right? I'm a little confused.

stepper.step(num)is used to rotate your motor 'num'-step. i.e. num=25, then calling stepper.step will cause your motor do 25-step.
STEPS is number of steps per revolution for your motor. It will be depending on the motor you used. For more information, you can check here.
You have to check for your motor stepper resolution. Most common motor stepper has 200 steps per revolution, which means 1 step is 360/200 = 1.8 degree. If you try Stepper.step(1), your motor will rotate 1.8 degree.
So in your case, if you already found out the resolution of your motor stepper, just do a simple conversion task:
const float resolution  = xx.xx; // put your step resolution here
int step_degree(float desired_degree){
    return (desired_degree/resolution);}

This can be use by calling
stepper.step(step_degree(40)); //rotate 40 degree.

--EDIT--
You can check this link, since it (perhaps) using same motor stepper (24BYJ48)
Based on 24BYJ48 datasheet, it has 5.625 degree resolution / 64 steps per revolution.

Do you mean 1 step is 360/200 = 1.8deg?

https://grahamwideman.wikispaces.com/file/view/28byj48_models_table.jpg/538898220/604x265/28byj48_models_table.jpg

I sent a link, the firs one is my stepper. but I don't know what they are. Would you please tell me what is my resolution?

I set 200 and I expect with num=1 I have to see 1.8 degree but it wasn't.

Instead of put in comment, it will be better if you put edit your question so others can quickly notice it :)

Thanks , I edit it, but I don't know what is the correct step


text:
Regarding Arduino Mega hardware serial
I have a doubt interfacing with fingerprint module (R305) with the Arduino Mega.
I have been able to interface it to Arduino Uno before but not Arduino Mega so far.
I have used the Mega's hardware Serial1 pins 19 (Rx) and 18 (Tx) pins.
However, I am unable to get output from the module. How do I connect hardware serial and what is a sketch to do this?

Try Pin digital pins 0 (RX) and 1 (TX), as they also should be Serial0 on ArduinoMega (PWM 0 and 1)
see:
https://www.arduino.cc/en/Reference/Serial
The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18 (TX), Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX). To use these pins to communicate with your personal computer, you will need an additional USB-to-serial adaptor, as they are not connected to the Mega's USB-to-serial adaptor. To use them to communicate with an external TTL serial device, connect the TX pin to your device's RX pin, the RX to your device's TX pin, and the ground of your Mega to your device's ground.


text:
Running quartz clock off an arduino
I am trying to run a clock off of an arduino following this site: http://www.cibomahto.com/2008/03/controlling-a-clock-with-an-arduino/comment-page-1/ and I tried to combine it with this to get it to run accurately. https://contractorwolf.com/arduino-pwm-interrupt-clock/
For the project that I want to do I need to slow down the minute hand by 23.9345 (So that it will run on sidereal time)
Now the bare code of the first link with some mods works perfectly, but the delay does not seem to be accurate:
    const int a1  =  8;     //use digital I/O pin 8
    const int a2  =  9;
    const int tick1 = 1000;
    const int tick2 = 50;

    void setup()
    {
    pinMode(a1,OUTPUT);   //set pin 8 to be an output output
    pinMode(a2,OUTPUT);   //set pin 9 to be an output output
    }

    void loop()
    {
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
       delay(tick2);          //delay 1000 milliseconds
       digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
       delay(tick2);          //delay 1000 milliseconds
       digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
    }

For this reason I have tried to merge it with the 1 wire clock project and got
const int a1  =  8;     //use digital I/O pin 8
const int a2  =  9;
const int tick1 = 1000;
const int tick2 = 50;

int cyclesPerSecond = 974;

//pins
int clockInterrupt = 0; //interrupt 0 is pin 2 on UNO
int pwmOut = 6; //pin 6

//timekeeping
int seconds = 0;
int masterClock = 0;//number of square waves

void setup()
{
attachInterrupt(clockInterrupt, clockCounter, RISING);
pinMode(a1,OUTPUT);   //set pin 8 to be an output output
pinMode(a2,OUTPUT);   //set pin 8 to be an output output

Serial.println(pwmOut);
analogWrite(pwmOut, 127); // this starts our PWM 'clock' with a 50% duty cycle//digital pin 10 for analogWrite pwm out
}

void clockCounter() // called by interrupt 0 (pin 2 on the UNO) receiving a rising clock edge PWM
{
masterClock ++; // with each clock rise add 1 to masterclock count
if(masterClock >= cyclesPerSecond*23.9345) // 974hz on pin 6, may be 490Hz if you use pin 9 or 10
{
seconds ++; // after one cycle add 1 second
masterClock = 0; //reset clock counter
}
}

void loop()
{
  if (seconds == 1){
   digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
   delay(tick1);          //delay 1000 milliseconds
   digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
   else if(seconds == 2)
   seconds = 0;
   digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
   delay(tick1);          //delay 1000 milliseconds
   digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
  }
}

However this does not seem to move the second hand properly, so the clock does tick but not strong enough to actually work. Is this a hardware thing or a processor thing? I have no idea why this would not work while the other code does.

Tear out the resonator, put a 32kHz clock crystal in place, and tune the async timer to sidereal time.

The idea of using the Arduino's own PWM as a clock is completely misguided. The author of that instructable does not have a clue what he is talking about. Forget about that and just calibrate your millis() or, for better accuracy, use a proper watch crystal.

tick1 has a way to large value (1000), if it has to wait one second, and the do some other stuff, but it has to do this every second, it will fail. I also miss a way to prevent the first if from being called multiple times.

@EdgarBonet - actually it is you who are mistaken.  The idea is not really to use PWM, but to use the hardware timer behind the PWM, which is a very good idea indeed.

@ChrisStratton: Are we talking about the same instructable? This guy is using a PWM signal from pin 6, which is driven by the same hardware timer as the millis() interrupt. There is no way this can be more accurate than millis() itself, thus the whole technique serves no purpose at all. Ultimately, the accuracy of both millis() and the PWM is limited by the ceramic resonator clocking the Arduino, which is quite poor.

Before something like an Arduino Stack Exchange "Flame War" may
start between Chris Stratton and other I would say there's only "one hardware clock" on an Arduino Uno.

As I said in my comment, the idea of using the Arduino's own PWM as a
clock source is completely misguided. It will be no more accurate than
using millis() or micros(): both these functions and the PWM rely on
the same primary clock source, namely the ceramic resonator clocking the
chip.
Also, you should avoid using delay() for timekeeping. The time it
takes to run around the loop() is the sum of all your delays plus the
time needed to execute the actual instructions, which you do not know
accurately. It is far better to use either millis() or micros().
Here is a tentative sidereal clock code, not tested:
// Pins driving the clock.
const int a1 = 8;
const int a2 = 9;

// Length of one sidereal second in microseconds.
const unsigned long SIDEREAL_SECOND = 997270;

void setup()
{
    pinMode(a1, OUTPUT);
    pinMode(a2, OUTPUT);
}

void tick()
{
    static int activePin = a1;

    // Pulse the pin.
    digitalWrite(activePin, HIGH);
    delay(50);
    digitalWrite(activePin, LOW);

    // Next time use the other pin.
    if (activePin == a1) activePin = a2;
    else activePin = a1;
}

void loop()
{
    static unsigned long last_tick;
    if (micros() - last_tick >= SIDEREAL_SECOND) {
        tick();
        last_tick += SIDEREAL_SECOND;
    }
}

You can tune the speed of the clock by changing the constant
SIDEREAL_SECOND. I set the constant to the actual length of a sidereal
second, in microseconds, but you may find that the clock does not run
exactly at the correct speed. This is because the ceramic resonator
inside the Arduino is not very accurate. You can remove most of the
inaccuracy by calibration: measure how fast or slow it runs and change
the value of SIDEREAL_SECOND to compensate. You will still face some
residual inaccuracy owing to the fact that the resonator's frequency is
not very stable, and is highly temperature-dependent.
If you want to build a clock that has decent accuracy, your best bet is
to use a 32768 Hz quartz crystal, as suggested by Ignacio
Vazquez-Abrams in his comment. I did that on a bare ATmega chip (a
“barebones Arduino”) to make a
24-hour analog wall
clock. You should be
able to easily adapt the code I published in that page to fit your
project.

Thank you for sharing your project. I made a Vetinari Clock using AS2, but mine is running a bit too fast. So I'll give your calibration method a try.

Bad idea, this will fail or at least momentarily misoperate in a little over an hour.  Unless you are going to use very large integers, you cannot use a mechanism which figures time from zero, but must do so incrementally.

@ChrisStratton: You are mistaken. Since micros() rolls over cleanly modulo 2^32, the rollover is not an issue.

I'm not 100% certain of what you are trying to do but I noticed a few bits in the code which don't look right to me.  For instance this function:
void clockCounter() // called by interrupt 0 (pin 2 on the UNO) receiving a rising clock edge PWM
{
  masterClock ++; // with each clock rise add 1 to masterclock count
  if(masterClock >= cyclesPerSecond*23.9345) // 974hz on pin 6, may be 490Hz if you use pin 9 or 10
  {
    seconds ++; // after one cycle add 1 second
    masterClock = 0; //reset clock counter
  }
}

This is causing a part of your inaccuracy.  You are incrementing the integer masterClock variable and then seeing if it is >= to a floating point value, the equals is not necessary and will almost never be true.  If the condition occurs then you increment seconds before setting masterClock to zero, losing any part of a second you had left over.
Looking at what others have said I would be inclined to take a different approach to this project rather than try and fix this code.

Writing another answer because I just had a completely different idea.
A standard option for keeping reasonably accurate time with an Arduino
is to use an RTC module. If possible, choose one based on the DS3231
rather than the DS1307, as the former has builtin temperature
compensation, which makes it significantly more accurate.
The RTC is typically used to provide the time over I2C in a broken-down
form: year, month, day, hour, minute and second. This is not really
convenient for a sidereal clock, as it would require complex conversions
to derive the sidereal time. However, most RTC modules have the option
to output a 32,768 Hz square wave. If you can feed this signal to
the digital pin 5 of your Arduino Uno, then you can use the
Timer/Counter 1 to count the cycles and raise an interrupt every
sidereal second, i.e. every 32,678.53 cycles of the RTC signal.
There is small issue with the above number not being an integer. One
could just round it to the nearest integer, which would make the clock
slow by about 14 ppm, or 1.2 s/day. This may not seem like a
large error, but the DS3231 is capable of much greater accuracy:
±2 ppm from 0°C to +40°C.
An elegant solution is to count the cycles internally using a 32-bit
fixed-point number, with 16 bits for the integer part and 16 bits for
the fractional part. On each timer interrupt, we compute what value the
timer should have on the next interrupt (variable next_count below),
simply by adding 32,678.53 to the previous value. Then we use the
integer part of the result (16 most significant bits) to program the
next interrupt. This way the interrupts will be spaced by either 32,678
or 32,679 signal periods, with the average being exactly the value we
need. This provides very high granularity, as our time unit is now
effectively 2−31 s ≈ 0.466 ns.
In the code below, the first three functions are left empty, as “an
exercise for the reader”. Or rather because they are dependent on the
specifics of the hardware setup. I am only showing the logic of using
the Timer 1 for getting an interrupt every sidereal second.
/*
 * RTC-based sidereal clock.
 *
 * Configure the RTC to output a 32,768 Hz square wave.
 * Feed this square wave to pin T1 = PD5 = digital 5.
 */

#include <avr/sleep.h>

static void setup_rtc()
{
    // Configure the RTC to output a 32,768 Hz square wave.
}

static void setup_clock_pins()
{
    // Configure the pins for driving the clock.
}

static void tick()
{
    // Advance the clock by one second.
}

/*
 * For better granularity, time is counted in units of 2^-16 cycles of
 * the 32768 Hz square wave (~ 0.47 ns), as a 32-bit unsigned integer.
 * Timer 1 holds the 16 most significant bits.
 */
const uint32_t SI_SECOND       = 32768UL << 16;
const uint32_t SIDEREAL_SECOND = 0.99726958 * SI_SECOND;

// Interrupt fired every sidereal second.
ISR(TIMER1_COMPA_vect)
{
    static uint32_t next_count;
    next_count += SIDEREAL_SECOND;
    OCR1A = next_count >> 16;  // use the 16 most significant bits
    tick();
}

void setup()
{
    // Configure Timer 1.
    TCCR1A = 0;            // normal counting mode
    TCCR1B = _BV(CS10)     // count rising edges of T1
           | _BV(CS11)     // ditto
           | _BV(CS12);    // ditto
    TIMSK1 = _BV(OCIE1A);  // enable COMPA interrupt

    // Enable pullup on T1 = PD5.
    PORTD |= _BV(PD5);

    setup_rtc();
    setup_clock_pins();
}

void loop()
{
    sleep_mode();
}


text:
Problem understanding code
This is a segment of an Arduino sketch, that I am trying to understand.
I know that the purpose of the entire code is to control 2 stepper motors linked to their respective drivers which are linked to a Mega 2560, but since I am new to Arduino, I am having problems with some functions.
This is a segment of the code. I am having problems with some statements such as unsigned short FLG = 0; and I cannot make out at all the timer interrupts part.
What does it all mean?
/* The “define” function is NOT A PROGRAMMING STATEMENT. Actually it sets up a macro which causes a text replace to occur before code is compiled. The pre-processor of the IDE will replace the variables such as “stp” to the integer value 22 in the following subsequent sections like the “void setup” function and the “loop” function if they are called. This function helps reduce RAM usage. */

#define stp 22
#define dir 23
#define stp2 26
#define dir2 27
#define EN  24
#define dir_ 25

int i, j, t, X = 0, Y = 0, Z = 0;
// here, the integer is creating variables such as i, j, t
//and also assigning values to some of them such as X, Y and Z.

unsigned short FLG = 0;

unsigned int Speed1 = 0, Speed2 = 0; // creating variables assigning initial values; due to unsinged only positive

int ser_1[3];

int po(int, int);

void setup() {     // You define how your Arduino will be used and set up any pins and communications you will be using. This will run first and only once.

  Serial.begin(9600); // begin the data transmission between Arduino and pc at speed of 9600 bits per sec
  delay(500); // stop for 500 milliseconds

  Serial.println(“hi”); // this will print the word “hi” on the serial monitor window on pc via serial port

  pinMode(stp, OUTPUT); // tells arduino to use digital Pin 22 to output electricity
  pinMode(dir, OUTPUT); // tells arduino to use digital Pin 23 to output electricity
  pinMode(stp2, OUTPUT); // tells arduino to use digital Pin 26 to output electricity
  pinMode(dir2, OUTPUT); // tells arduino to use digital Pin 27 to output electricity
  pinMode(EN, OUTPUT); // tells arduino to use digital Pin 24 to output electricity

  noInterrupts(); // to prevent disruption of timing of codes, disables some functions in the background

  /* To use timers, the built-in timer registers on the AVR chip that store timer settings need to be configured.  There are a number of registers per timer.  Two of these registers –the Timer/Counter Control Registers- hold setup values, and are called TCCRxA and TCCRxB, where x is the timer number (TCCR1A and TCCR1B, etc.).   Each register holds 8 bits, and each bit stores a configuration value. */

  TCCR1A = 0x80; //
  TCCR1B = 0x0A; // Enable reset on compare match, 1:8 clock. don’t understand
  OCR1AH = 0x9C;
  OCR1AL = 0x3F;
  TIMSK1 = (1 << OCIE1A); // enable timer compare interrupt
  interrupts();
}
ISR(TIMER1_COMPA_vect)   // timer compare interrupt service routine
{
  res();
}
void loop(){

if(Serial.available())
 {
  ser_1[i] = Serial.read();
  char ch = Serial.read();
if(ch==’S’)
   { i=0;
     X=0;
     while(1)
{
  if (Serial.available() > 0)
     {
      ser_1[i]=Serial.read();
      ser_1[i]=ser_1[i]-48;
      X=X+(ser_1[i]*(po(10,i)));
      i++;
     if(i==3)
       {
        FLG++;
        break;
        }
      }
    }
}

if (ch==’A’)
  { i=0;
    Y=0;
     while(1)
     {
        if (Serial.available() > 0)
      {
      ser_1[i]=Serial.read();
      ser_1[i]=ser_1[i]-48;
      Y=Y+(ser_1[i]*(po(10,i)));
       i++;
      if (i==3)
          {
           FLG++;
           break;
           }
          }
        }
      }

     if(FLG==2)
    {
      Speed1=X;
      Speed2=Y;
      digitalWrite(EN,LOW);
        delay(100);
      StepForwardDefault();
        delay(1000);
      StepForwardDefault2();
         delay(1000);
      ReverseStepDefault2();
      ReverseStepDefault();
      delay(1000);
      digitalWrite(EN,HIGH);
      delay(1000);
      }
      else
      Serial.println(“sequence is stop”);
}
 /*****************po******************/

int po(int num, int pow)
{ int result=1;
  if(pow==0)
  return 1;
  else
 {
  for(int f=1;f<=pow;f++)
    {
  result=result*num;
    }
 return result;
 }
}

/************ MOTOR 1 Function *****************/

void ReverseStepDefault()
{
  Serial.println(“motor a reverse”);
  Serial.println(“Moving in reverse at default step mode.”);
digitalWrite(dir_, HIGH); // Pull direction pin high to move in “reverse”
digitalWrite(dir, LOW);
delay(100);
for(int x=1; x<200; x++) // Loop the stepping enough times for motion to be visible
{
  digitalWrite(stp, HIGH); //Trigger one step
  delay(305-X);
  digitalWrite(stp, LOW);  // Pull step pin low so it can be triggered again3
  delay(305-X);
  }
}

/************ MOTOR 2 Function *****************/

void ReverseStepDefault2()
{
  Serial.println(“Moving b reverse”);
  digitalWrite(dir_, HIGH); // Pull direction pin high to move in “reverse”
  digitalWrite(dir2, LOW);
  delay(100);
  for(int x =1; x<200; x++) // Loop the stepping enough times for motion to be visible
  {
   digitalWrite(stp2,HIGH); // Trigger one step
   delay(305-Y);
   digitalWrite(stp2,LOW); // Pull step pin low so it can be triggered again3
   delay(305-Y);
   }
}

void StepForwardDefault2()
{
   Serial.println(“motor b forward”);
   digitalWrite(dir_,HIGH); // Pull direction pin high to move in “reverse”
   digitalWrite(dir2,HIGH);
   delay(100);
   for(int x=1; x<200; x++) // Loop the forward stepping enough times for motion to be visible

{
  digitalWrite(stp2,HIGH); // Trigger one step forward
  delay(305-Y);
  digitalWrite(stp2,LOW); // Pull step pin low so it can be triggered again
  delay(305-Y);
    }
}

void res()
 {
   if(Serial.available())
  {
   ser_1[i]=Serial.read();
   char ch = Serial.read();
   if(ch ==’T’)
      {
       FLG=0;
       Serial.println(“stop is pressed”);
      }
   }
}

It will be better if you also explain about what you are trying to achieve.

You need to be more specific.What aspect of the line of code don't you understand? What other lines of code are you having trouble with?

this is C code and you need to look into declaring variables and functions in C to understand the syntax

unsigned, short, int etc are variable types, words with the format name(..., ...) are functions, int ser_1[3]; is an array of size 3, #define is not called a "function" and is more like automated copy-paste; for instance, #define stp 22 replaces all the instances of the word "stp" by the number "22" when compiling

I am having problems with some statements such as
  "unsigned short FLG = 0;"

This is the C and C++ syntax for declaring a variable. The statement
means “Let FLG be an unsigned short integer and let it's initial value
be zero”. An unsigned short can hold any integer value between 0 and
65535 inclusive.
The Arduino language reference documents the types
short and
unsigned int but,
for a mysterious reason, it does not document unsigned short.

I cannot make out at all the timer interrupts part.

Nobody can unless they know the internals of the AVR timers, which are
non trivial but are well covered in the
datasheet.
It's a thick document, but you only need to study chapters 14:
Interrupts and 17: 16-bit Timer/Counter (Timer/Counter 1, 3, 4, and
5).
I recommend you first read the Timers and counters
tutorial by Nick Gammon, then go to the
datasheet for the most authoritative information.
Edit: Just a comment... I find the program you have posted to be
written with poor programming style. More specifically, the section
setting the Timer 1 registers would be better written as follows:
TCCR1A = bit(COM1A1);  // set OC1A to LOW on compare match
TCCR1B = bit(WGM12)    // CTC mode, TOP = OCR1A
       | bit(CS11);    // clock at F_CPU / 8
OCR1A  = 40000 - 1;    // period = 40000 prescaled clock cycles
TIMSK1 = bit(OCIE1A);  // enable COMPA interrupt

It is still obscure if you don't know the timer, but using explicit bit
names instead of pure numbers makes things a lot easier when you refer
to the datasheet. Also, there is no point in setting each byte of
OCR1A in a different statement: it only makes things harder to read.

Hi, I have edited the question and added the entire code. Could you kindly have a look and suggest improvements?

Actually, I am trying to control two stepper motors. One motor is connected to a crank slider mechanism and the other to a belt-pulley mechanism. So when the motors are going to operate, the respective mechanisms will create a compression-elongation and twisting force on the test material. I have a picture here : https://drive.google.com/open?id=0B7174vajmpNUXzcycVQ2clRVZms

@AyanPaul: Lots of issues: overlong lines, inconsistent indenting, missing } at the end of loop(), missing definition of StepForwardDefault(), use of non-ASCII quotes ‘’“” instead of '", two Serial.read() following a single Serial.available(), storage of incoming serial bytes in an array that is never used, three almost identical functions that should be factored into a single one, tons of useless comments that only paraphrase the code, missing comments for the things that are really non obvious (e.g. the meaning of all the global variables)...

I'm assuming you don't mean "all" when you ask "what does it all mean?"
I also assume that the comments are from you - in which case you've done reasonably well!
/* The “define” function is NOT A PROGRAMMING STATEMENT... */

True, #define isn't a programming statement that produces code: it's a way of defining a symbol that you can use in the rest of the code, both for explanation purposes and ease of changing: without having to search for all copies of 22 - and then decide if this particular 22 is for that pin or not.
unsigned short FLG=0;

int is 16 bits in the Arduino, but in some systems it's 32 (and in others 64). short is (practically) always 16 bits regardless of system, so many programmers use short when they know they definitely want a 16-bit integer. unsigned merely means that it can never go negative - which allows the variable to hold higher values (0 to 65,535 instead of -32,768 to 32,767).
int ser_1[3];

This is an array of 3 ints called ser_1, which can be accessed as ser_1[0], ser_1[1] and ser_1[2]. In C, all arrays start at 0. Why use an array? It makes it possible to use another variabe to say which ser_1 you want: e.g. ser_1[i]. If i is 2, you get the last one.
int po(int,int);

This says that there will be a function called po that takes two int values, processes them, and returns an int result.
noInterrupts(); // to prevent disruption of timing of codes, disables some functions in the background

Pretty much. An interrupt can happen at any time: the CPU will stop executing the main program, execute the interrupt code, then resume where it left off in the main program. Sometimes that's a bad thing! If the interrupt code is going to change something that this code needs to stay the same (or vice versa!), then Bad Things can happen. To prevent that, you can turn off interrupts temporarily with this function, and turn them on again later with interrupts() (which you'll see below).
/* To use timers, the built-in timer registers on the AVR chip that store timer settings need to be configured.  There are a number of registers per timer.  Two of these registers –the Timer/Counter Control Registers- hold setup values, and are called TCCRxA and TCCRxB, where x is the timer number (TCCR1A and TCCR1B, etc.).   Each register holds 8 bits, and each bit stores a configuration value. */

 TCCR1A = 0x80; //
 TCCR1B = 0x0A; // Enable reset on compare match, 1:8 clock. don’t understand

OK, this is complicated:

By default, a timer simply counts from 0 to 65,535 (maximum 16 bit value), then resets and starts again.
How quickly? One 'tick' is the system clock, so very quickly! But you can "pre-scale" that with a divisor. In this case, they're using a divisor of 8, so the timer will "tick" an eighth as fast.
You can configure the timer to interrupt when it resets, so that special code will execute on a timed basis.
You can also tell it that if at any time it hits a certain number to also interrupt (Compare Match) - that's two different interrupts.
You can also tell it that when it hits that Compare number, to reset back to 0 and start counting again. That means that the timer will interrupt more often.

OCR1AH = 0x9C;
OCR1AL = 0x3F;
These stand for "Output Compare Register 1A High" and "Output Compare Register 1A Low" - a 16 bit value that is 0x9C3F (37839 decimal). If you divide the system clock by that number, (and a further 8 for the pre-scaler), you'll find out how often it interrupts.
interrupts();

This turns on interrupts again.
ISR(TIMER1_COMPA_vect)   // timer compare interrupt service routine
{
res();
}

This is the code that executes every timer interrupt. I don't know what res() does.

Hi, I have edited the question and added the entire code. Could you kindly have a look and suggest improvements?

Here is some explanation :
TCCR1A = 0x80; //OC1 will cleared on compare match
TCCR1B = 0x0A; //Turn on CTC mode --> it means the interrupt counter will reset to 0, and causing the interrupt happen again and again.
               //Divide clock 1:8 (prescaler)
OCR1AH = 0x9C;
OCR1AL = 0x3F; //compare value = 0x9C3F = 39999
TIMSK1 = (1<<OCIE1A); // the micro will jump to the Output Compare A Interrupt vetor upon compare match.

Overall, this setup will make your program do whatever you put in the Interrupt Service Routine ISR(TIMER1_COMPA_vect){...do whatever here...}
The interrupt interval is =

(OCR1A+1) × prescaler ÷ F_CPU
(39999+1) × 8 ÷ 16.000.000 = 0.02 sec

as for res(); and unsigned short FLG; I dont know what that is, since its probably your own creation (not from arduino libs)
You can found more detailed explanation here and here

The interval is (OCR1A+1) × prescaler ÷ F_CPU = 2 ms.

@EdgarBonet - Did you mean 20 ms or 2 ms? The calculation, with the numbers supplied, gives 20ms.

@Greenonline: My mistake: I typed 3999 instead of 39999 in my calculator. The correct value is indeed 20 ms.


text:
L298N vs Motor Shield R3
I'm new to Arduino and need some clarification on motor drivers.
I was wondering if I can use a L298N instead of the Motor Shield R3, I hope not to be comapring apples to oranges, the doc of the Motor Shield R3 say "The Arduino Motor Shield is based on the L298"  and more or less I see similar projects (Robot cars) using both but as mention I don't if I can use one or the other as "replacement".
(L298N)

(Motor Shield R3):

There are many pages, both here and on electronics.stackexchange.com which explain that all boards based on the very old L298 and L293 are best avoided in favor of newer FET drivers, especially if you are using battery power.  If you already have one you can give it a try, but it would be a waste of money to buy one.

Yes.  The shield is easier to user, but the breakout board you've shown uses the same chip.  I'd suspect that the breakout board, which has a much bigger heat sink, can handle larger motors, though.  You'll need to put wires from PWM and digital pins to the breakout board you're showing, but it's not super challenging to use those.  I've used extremely similar boards in the past, as well as shields, and both work great.  How big are your motors?  If they're WAY too big (the breakout board can only handle 2 amps IIRC) then you'll need something else anyway.

Actually, all L298 based boards should be avoided, especially in something battery powered, as they are obsolete and very lossy.  Choose something based on an FET bridge IC instead, or for larger motors a bridge made of discrete FETs.

OP's question related to whether the two boards are interchangeable.  For many applications the readily available motor shields, or possible the shield that OP already happens to own, are sufficient.  I still have a lot of L298 boards lying around from old projects, I'm not going to throw them out and buy new things if I'm happy with their performance.

The problem is that the losses mean you need an extra cell in your battery pack just to heat up the driver chip.  That might be okay if you have a 12v pack and a motor that really wants a bit less, but it's a disaster whenever someone tries to do something with a lower voltage pack, and wasteful in any event.  So no, "work great" is not really a helpful statement.  Essentially the only reason these horrible parts remain in circulation is inertia and popular lack of understanding of how bad they are.

But they're not bad, they're just not optimal.  They actually do work fine.  If OP is running this from an adaptor, for example, and doesn't care about efficiency, and already has some of these things lying around there is absolutely no reason not to use them.  When OP wants to optimize for power use, then I do agree that better options are available.  But that's not what OP was asking


text:
Sound Recognition
I'm looking to recognize a particular sound using arduino uno.
I need to recognize a clap sequence to trigger a relay.
Having given it some thought i need it to be continuous listening mode with out any trigger such as a button press. The background will be quiet.
Is the arduino uno powerful enough to do this and how will i get stated on this? Any help is appreciated.
Note i need to do this entirely onthe Uno itself and not on PC like How do I listen for a sound that matches a pre-recorded sound?
I am thinking i will prerecord the sound and compare with a live sample, is this feasible?

If it's just a clap sound and the background is quiet, then really all you'd need is to sense how loud the sound is.  This can be done using an analog comparator interrupt (this is present on the chip itself but not on the Arduino library).  If all the uno is doing is measuring the sound and maybe setting an output pin when it's loud, then just poll the analogs attached to your microphone and trigger the condition when the output is loud enough.  You'd probably need to amplify the microphone if you haven't already, but yes, the uno can handle that.
Edit: if it's a clapping sequence, then it can still do it.  Again, just measure the time between loud and quiet, don't worry about what the sound is (that is, you don't need to worry about exactly recording and analyzing the sound, you just need to know when it's loud and when it's quiet)

How would it work if work if there  was a clap and another loud sound like a clap (but not a clap)?

It wouldn't, unfortunately.  My answer above really just deals with the case where the only thing that happens is a clap.  Otherwise yes, you'd have to properly identify the sound, which is more complex

If you make a piece of code that detects a short, high volume. It will work better than just a high volume. You could also do two claps (high volume bursts) with an expected time between them. This will filter occasional high volume sounds.

Adding to Michaels answer above which only works for some cases (and  it wont work perfectly even with a sequence of claps). To make it work in more cases you would need to store more information about the clap noise- as Michael points out in his comment above "properly identify" the clap- to make the identification more accurate. There are various ways to do this- you could compare it with live recording as you wrote in your question. I suggest tyou try neural networks to do such a comparision I. I would say you would need a two layer neural network with say a sample of different claps for training it-(its probably quicker to train it not with arduino).
Here is a library for neural networks for arduino
http://robotics.hobbizine.com/arduinoann.html
that you may use. Or you can implement you own neural network. Its well known that sound recognition can be used to analyse sounds.
The built in ADC of Arduino can probably be used to  record and good enough for something like a clap in your case-though it cant be used for high quality sound recordings.

I have not tested it but there is an example for the ArduinoSound library which especially detects claps.
https://github.com/arduino-libraries/ArduinoSound/tree/master/examples/ClapDetector
/*
 This example reads audio data from an Invensense's ICS43432 I2S microphone
 breakout board, and uses the input to detect clapping sounds. An LED is
 togggled when a clapp is detected.

 Circuit:
 * Arduino/Genuino Zero, MKRZero or MKR1000 board
 * ICS43432:
   * GND connected GND
   * 3.3V connected 3.3V (Zero) or VCC (MKR1000, MKRZero)
   * WS connected to pin 0 (Zero) or pin 3 (MKR1000, MKRZero)
   * CLK connected to pin 1 (Zero) or pin 2 (MKR1000, MKRZero)
   * SD connected to pin 9 (Zero) or pin A6 (MKR1000, MKRZero)

 created 18 November 2016
 by Sandeep Mistry
 */

#include <ArduinoSound.h>

// the LED pin to use as output
const int ledPin = LED_BUILTIN;

// the amplitude threshold for a clap to be detected
const int amplitudeDeltaThreshold = 100000000;

// create an amplitude analyzer to be used with the I2S input
AmplitudeAnalyzer amplitudeAnalyzer;

// variable to keep track of last amplitude
int lastAmplitude = 0;

void setup() {
  // setup the serial
  Serial.begin(9600);

  // configure the LED pin as an output
  pinMode(ledPin, OUTPUT);

  // setup the I2S audio input for 44.1 kHz with 32-bits per sample
  if (!AudioInI2S.begin(44100, 32)) {
    Serial.println("Failed to initialize I2S input!");
    while (1); // do nothing
  }

  // configure the I2S input as the input for the amplitude analyzer
  if (!amplitudeAnalyzer.input(AudioInI2S)) {
    Serial.println("Failed to set amplitude analyzer input!");
    while (1); // do nothing
  }
}

void loop() {
  // check if a new analysis is available
  if (amplitudeAnalyzer.available()) {
    // read the new amplitude
    int amplitude = amplitudeAnalyzer.read();

    // find the difference between the new amplitude and the last
    int delta = amplitude - lastAmplitude;

    // check if the difference is larger than the threshold
    if (delta > amplitudeDeltaThreshold) {
      // a clap was detected
      Serial.println("clap detected");

      // toggle the LED
      digitalWrite(ledPin, !digitalRead(ledPin));

      // delay a bit to debounce
      delay(100);
    }

    // update the last amplitude with the new amplitude
    lastAmplitude = amplitude;
  }
}

The question is tagged “arduino-uno”, which is a board ArduinoSound does not support.

authors: Борис Павленко

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


text:
Faster output of Serial.print() data coming from TSL1402R sensor
I am reading a TSL1402R with an Arduino Mega2560.  The code is based on the sketch from the arduino playground here:http://playground.arduino.cc/Main/TSL1402R
The application is a digital caliper for moving strands of filament.  I would like to have the scan rate as fast as possible.  I am making my own filament and need some means of quality control.
I am reading the analog values of each photodiode (256) of the sensor to an array.  I find an average value of 25 reads for each of the diodes and place that in another array.  I then I compare the averaged values for each of the 256 diodes and assign them into 3 groups: dark1, dark2 and dark3 I then count the assigned values and get a total. +1/4 for dark1, 1/2 for dark2 and 1 for dark3.  This figure represents the width of a piece of filament casting the shadow on the sensor.(dark1 is partially blocked photodiode, dark2 is 1/2 blocked, dark3 is fully blocked)
I am looking at the clock pin on the sensor with a scope.  When I output data with serialprint at (any speed) 115200  The program speed slows down considerably.  When I change the program to serialprint only if the previous value changes, it gets even slower.  If I serialprint every time through the loop, the buffer fills and the values are not accurate.
I get accurate data from my program.  What is the most efficient way to get it out and into a usable form? By way of form I mean to have the data saved so I can see the size deviation of the filament I am producing.  It would also be great if I could visualize the data in real time and make adjustments during the extrusion process.
I have been researching this for weeks, tweaking the program and trying different ideas based on responses to questions similar to mine.
My background is industrial electrical systems, not programming.  This is my first attempt at something like this.  Any advice would be greatly appreciated.
Thanks to all in advance,
Dave Stewart, aka bigstew123
#include <EEPROM.h>
#include <TimerOne.h>
#define NPIXELS 255  // No. of pixels in array

// Define various ADC prescaler:
const unsigned char PS_32 = (1 << ADPS2) | (1 << ADPS0);
const unsigned char PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

const byte PWMDAC1pin = 11; // PWM DAC, only pins 9 and 10 are allowed
const byte period = 128; // for 10 bit DAC

const int LEDpin = 8;
const int CLKpin = 3;    // <-- Arduino pin delivering the clock pulses to      pin 3 (CLK) of the TSL1401
const int SIpin = 4;     // <-- Arduino pin delivering the SI (serial-input) pulse to pin 2 of the TSL1401
const int AOpin = 1;    // <-- Arduino pin connected to pin 4 (analog output 1)of the TSL1401

unsigned int intArray[NPIXELS]; // <-- the array where the readout of the photodiodes is stored, as integers

int nAggr = 5;        // image averaging count per one scan. should not exceed 10
int timer = 5;        // value output averaging counter
int sensor_value = 0;
int sensor_value_1 = 0;
int sensor_value_2 = 0;
int sensor_value_3 = 0;
float sensor_value_mapped = 0;
float dark_pixels_1 = 0;
float dark_pixels_2 = 0;
float dark_pixels_3 = 0;
float dark_pixels_total = 0;
float dark_pixels_avg = 0;
float width_mm = 0;
float width_mm_old = 0;

// default filament width
double lowpassValue = 1.75;
double lowpassFactor = 0.5;

double calibFactor =  15.75; // (default pixel per mm = 15.748 for 400dpi     sensor

boolean debugMessage = false;
boolean doCalibration = false;

int timerCounter = 0;
double timerValue = 0;

void setup() {
// To set up the ADC, first remove bits set by Arduino library, then choose
// a prescaler: PS_16, PS_32, PS_64 or PS_128:
    ADCSRA &= ~PS_128;
    ADCSRA |= PS_32; // <-- Using PS_32 makes a single ADC conversion take ~30 us
    pinMode(PWMDAC1pin, OUTPUT);
// Timer1.initialize(period);
    Timer1.initialize(40);
// Next, assert default setting:
    analogReference(DEFAULT);

// Set all IO pins low:
    for (int i = 0; i < 14; i++) {
        digitalWrite(i, LOW);
    }

    pinMode(LEDpin, OUTPUT);
    initSensor();
    Serial.begin(115200);
//Serial.begin(9600);
}

void loop() {
    Timer1.pwm(PWMDAC1pin, (dark_pixels_avg));
    sensor_value = 750; //this is the 0-1023 value for the light/dark threshold
    sensor_value_mapped = sensor_value;
    sensor_value_1 = sensor_value_mapped;
    sensor_value_2 = sensor_value_mapped * 75 / 100;//this is 3/4/
    sensor_value_3 = sensor_value_mapped * 65 / 100; //this is 1/2
    delay(50);
    scanSensor();
    MATH();
    delay(50);
    /*
     *   testing code here: if the value is different, serial print with 100 delay, if the value is unchanged, update at 1000
     *   this is code I used to try to plot the values to a python script running on a raspberry pi 2b
     *   with this setup, the program slows and the scan rate is so slow I miss deviations in the filament.
     *
     if
     (width_mm != width_mm_old)
     {
     Serial.println (width_mm, 4);
     delay(100);

     }
     else
     {Serial.println (width_mm_old, 4);
     delay(1000);

     }
     */
// every scan, print the width
    Serial.println(width_mm, 4);

// Command processor
    if (Serial.available() > 0) {
        char incomingByte = Serial.read();

        switch (incomingByte) {
            case 'd':    // Debugging message toggle
                debugMessage = !debugMessage;
                break;

            case 'c':    // Calibration
                doCalibration = true;
                break;

            case 'h':
                //helpMessage();
                array_value();
                break;
        }
    }

    if (debugMessage) {
        //   Serial.print("Number of dark pixels       ");
        //   Serial.println(dark_pixels);
        // delay(300);
        Serial.print("Dark pixel average          ");
        Serial.println(dark_pixels_avg, 4);
        Serial.print("Dark pixel 1                ");
        Serial.println(dark_pixels_1);
        Serial.print("Dark pixel 2                ");
        Serial.println(dark_pixels_2);
        Serial.print("Dark pixel 3                ");
        Serial.println(dark_pixels_3);
        Serial.print("dark_pixels_total             ");
        Serial.println(dark_pixels_total);
        Serial.print("filament width in mm       ");
        Serial.println(width_mm, 4);
        //  Serial.print ("sensor pot value          ");
        // Serial.println (sensor_value);
        //  Serial.print ("sensor value mapped        ");
        //   Serial.println (sensor_value_mapped);
        delay(200);
        //  Serial.print("Raw:\t");
//    printDouble(lowpassValue, 4);
//   Serial.print("\t(mm)=\t");
//    printDouble(mmValue, 3);
//   Serial.println();
//Serial.println(intArray[i]);//////////////////////////////////////////
//Serial.print(";");
    }

    width_mm_old = width_mm;
}

void initSensor() {
// Initialize two Arduino pins as digital output:
    pinMode(CLKpin, OUTPUT);
    pinMode(SIpin, OUTPUT);

// Clock out any existing SI pulse through the ccd register:
    for (int i = 0; i < NPIXELS + 4; i++) {
        ClockPulse();
    }

// Create a new SI pulse and clock out that same SI pulse through the sensor register:
    digitalWrite(SIpin, HIGH);
    delayMicroseconds(1);
    digitalWrite(CLKpin, HIGH);
    delayMicroseconds(1);
    digitalWrite(SIpin, LOW);
    delayMicroseconds(1);
    digitalWrite(CLKpin, LOW);

    for (int i = 0; i < NPIXELS + 4; i++) {
        ClockPulse();
    }
}

void scanSensor() {
    // Stop the ongoing integration of light quanta from each photodiode by  clocking in a
    // SI pulse:
    // Create a new SI pulse and clock out that same SI pulse through the sensor register:
    digitalWrite(SIpin, HIGH);
    delayMicroseconds(1);
    digitalWrite(CLKpin, HIGH);
    delayMicroseconds(1);
    digitalWrite(SIpin, LOW);
    delayMicroseconds(1);
    digitalWrite(CLKpin, LOW);

    // Next, a new measuring cycle is starting once 18 clock pulses have passed. At
    // that time, the photodiodes are once again active. We clock out the SI pulse through
    // the NPIXELS bit register in order to be ready to halt the ongoing measurement at our will
    // (by clocking in a new SI pulse):
    for (int i = 0; i < NPIXELS + 4; i++) {
        if (i == 18) {
            // Now the photodiodes goes active..
            // An external trigger can be placed here
        }

        ClockPulse();
    }

    // The integration time of the current program / measurement cycle is ~2ms. If a larger time
// of integration is wanted, uncomment the next line:
//delay(1);
// Stop the ongoing integration of light quanta from each photodiode by clocking in a SI pulse
// into the sensors register:
// Create a new SI pulse and clock out that same SI pulse through the sensor register:
    digitalWrite(SIpin, HIGH);
    delayMicroseconds(1);
    digitalWrite(CLKpin, HIGH);
    delayMicroseconds(1);
    digitalWrite(SIpin, LOW);
    delayMicroseconds(1);
    digitalWrite(CLKpin, LOW);

// Next, read all 256 pixels in parallell. Store the result in the array. Each clock pulse
// causes a new pixel to expose its value on the two outputs:
    for (int i = 0; i < NPIXELS; i++) {
        delayMicroseconds(2);// <-- We add a delay to stabilize the AO output from the sensor
        intArray[i] = analogRead(AOpin);    //(AOpin);
        ClockPulse();
    }
}
//here we have a sensor value that is an integer number between 0 and 1023 to represent the value of the pixels read in intArray[]
//  the number varies, so really dark pixels are set at 75, medium at 100, and light at 125....  of course, this will be a % and scaled
//so when the operator adjusts the sensitivity, each value will adjust accordingly.
// each function only counts the pixels in its range so there is no overlapp
//for a sensor value of 200, sensor value 1 will be 200, value 2 will be 150 and value 3 will be 100
////////////////////////////////////////really dark///////////////////

void MATH() {
    int x = 0;
    int y0 = 0;
    int y1 = 0;
    int y2 = 0;
    int y3 = 0;
    float dpa = 0;

    for (int i = 0; i < NPIXELS; i++) {
        x = intArray[i];

        if (x <= sensor_value_1 && x >= sensor_value_2 && x >=  sensor_value_3) { //less than 200, but greater than 150 and 100
            y1 = y1 + 1;   //////////////////////////////////////not very dark/////////////////////////
        }

        if (x <= sensor_value_1 && x <= sensor_value_2 && x >= sensor_value_3) { //less than 200, less than 150, but more than 100
            y2 = y2 + 1;   //////////////////////////////////////medium dark////////////////////////
        }

        if (x <= sensor_value_1 && x <= sensor_value_2 && x <= sensor_value_3) { //less than 200 or 150 or 100 (really dark pixel(low intArray value)
            y3 = y3 + 1;   //////////////////////////////////////very dark/////////////////////////
        }
    }

    dark_pixels_1 = y1 * 25 / 100; ///1/4 of a count for each pixel
    dark_pixels_2 = y2 * 50 / 100; // half a count for each pixel
    dark_pixels_3 = y3; // full count for each pixel
/////////////////////////add up the totals///////////////////////////////
    dark_pixels_total = dark_pixels_3 + dark_pixels_2 + dark_pixels_1;

    for (int q = 0; q < 25; q++) {
        dpa  += dark_pixels_total;
    }

    dark_pixels_avg = dpa / 25;
    float k = 0;
    k =  map(dark_pixels_avg, 50, 97, 157, 313); //map the values to a known     width and convert to mm
    width_mm = k / 100;
    //
    //   Serial.print("Number of dark pixels       ");
    //   Serial.println(dark_pixels);
    // delay(300);
    //Serial.print("Dark pixel average          ");
    // Serial.println(dark_pixels_avg);
    // Serial.print("Dark pixel 1                ");
    // Serial.println(dark_pixels_1);
    // Serial.print("Dark pixel 2                ");
    //  Serial.println(dark_pixels_2);
    //  Serial.print("Dark pixel 3                ");
    //  Serial.println(dark_pixels_3);
    //  Serial.print("dark_pixels_avg             ");
    //  Serial.println(dark_pixels_avg);
    //  Serial.print ("filament width in mm       ");
    //  Serial.println (width_mm, 4);
    //   Serial.print ("sensor pot value          ");
    //   Serial.println (sensor_value);
    //   Serial.print ("sensor value mapped        ");
//    Serial.println (sensor_value_mapped);
//    delay(200);
}

// This function generates an outgoing clock pulse from the Arduino digital pin 'CLKpin'. This clock
// pulse is fed into pin 3 of the linear sensor:
void ClockPulse() {
    delayMicroseconds(1);
    digitalWrite(CLKpin, HIGH);
    digitalWrite(CLKpin, LOW);
}

void array_value() {
    for (int i = 0; i < NPIXELS; i++) {
        Serial.print("ARRAY VALUE");
        Serial.print(i);
        Serial.print("\t");
        Serial.println(intArray[i]);
    }
}

Unfortunately this is not answerable without details of the program.  Either you are keeping the serial port busy, and that is the limitation, or you have another part of the program which is necessarily time consuming, or you have a program mistake which makes something take far longer than it should.

I posted the code.  Not pretty, I see now there are remnants of things I have tried and since removed.  I hope you can make some sense of it.  Thanks for your efforts.

How often do you need this loop to run? At a quick and dirty count of the output (230 characters or so), at 115200 baud (11520 char/sec), the output needs 20 ms, meaning the loop can't run any faster than 50 hz or it will be held up waiting for the the output buffer to clear. You could gain some speed by formatting your (currently 6) output values into a single line, comma-separated, and without the text labels. But ultimately you need to calculate what rate you need and adjust the output quantity and speed to be compatible.

I am trying to check filament diameter as it is wound from a master spool onto a standard 2.2kg spool.  I have the sensor enclosed in a box with a line laser diode aimed at it.  When the filament blocks the laser, the photodiodes on the sensor drop their analog output value to about 20% of the fully illuminated value.  It takes 256 analog reads to complete a full scan of the diodes on the sensor.  Sometimes there are defects in my filament that are about an inch long.  I would like to capture the defect while winding the filament as fast as possible.

My previous best guess was that I was reading about 5 complete scans per second.  At 50 feet per minute spool rate, that is 600 inches per minute or 10 inches per second going past the sensor.  If I only read 5 scans per second, that is one scan for every two inches of filament.  A deviation caused a blob about 1.75 inches long at 4mm diameter (target is 2.85mm filament diameter).   My setup missed the blob, and that is what has prompted me to post here and try and sort it out.     The Serial.print lines are for debugging, I only output the width_mm value.

From what you are describing, your delay calls would be the cause. Or are they just part of the debugging and it runs slow even without them?

After spending some more time doing research, I have come to realize that the arduino platform is not capable of the performance I was hoping for with regard to the rate of ADC sampling.  I have purchased a BeagleBone Black and plan to use it in place of the arduino.  Thank you to everyone who commented.