text:
Arduino: Read frequency of input from audio jack
I want to trigger an arduino from a sound from an audio jack from a mobile phone. The audio is a 1 Khz sound that the mobile will play. I want to avoid accidental triggering of the audio by testing for specifically that frequency.
I've found several tutorials using analog read, but the output is not in hertz.
How do i get the output in Hertz?
int incomingAudio;

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

void loop(){
  incomingAudio = analogRead(A0);//read voltage at A0
  incomingAudio = (incomingAudio+1)/4 - 1;//scale from 10 bit (0-1023) to 8 bit (0-255)
  if (incomingAudio<0){//deal with negative numbers
    incomingAudio = 0;
  }
  PORTD = incomingAudio;
  Serial.println(PORTD);

}

Edgar Bonets Program is ingeneous, but the power fluctuations tested with a tone at 1000 kHz (square wave Signal) are quite high. A factor of three using LOG_TAU = 6. May be, some improvement is possible.

@ChristianRempel: Testing with synthetic data shows the reported power fluctuates within a factor 2.2 with a square input and a factor 1.2 with a sinusoidal input.

You can measure a single "pure" frequency by counting the number of times that the pin changes, by using the inbuilt timers. Here is a sketch from my page about timers that accomplishes that:
// Timer and Counter example
// Author: Nick Gammon
// Date: 17th January 2012

// Input: Pin D5

// these are checked for in the main program
volatile unsigned long timerCounts;
volatile boolean counterReady;

// internal to counting routine
unsigned long overflowCount;
unsigned int timerTicks;
unsigned int timerPeriod;

void startCounting (unsigned int ms)
  {
  counterReady = false;         // time not up yet
  timerPeriod = ms;             // how many 1 ms counts to do
  timerTicks = 0;               // reset interrupt counter
  overflowCount = 0;            // no overflows yet

  // reset Timer 1 and Timer 2
  TCCR1A = 0;
  TCCR1B = 0;
  TCCR2A = 0;
  TCCR2B = 0;

  // Timer 1 - counts events on pin D5
  TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

  // Timer 2 - gives us our 1 ms counting interval
  // 16 MHz clock (62.5 ns per tick) - prescaled by 128
  //  counter increments every 8 µs.
  // So we count 125 of them, giving exactly 1000 µs (1 ms)
  TCCR2A = bit (WGM21) ;   // CTC mode
  OCR2A  = 124;            // count up to 125  (zero relative!!!!)

  // Timer 2 - interrupt on match (ie. every 1 ms)
  TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

  TCNT1 = 0;      // Both counters to zero
  TCNT2 = 0;

  // Reset prescalers
  GTCCR = bit (PSRASY);        // reset prescaler now
  // start Timer 2
  TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
  // start Timer 1
  // External clock source on T1 pin (D5). Clock on rising edge.
  TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
  }  // end of startCounting

ISR (TIMER1_OVF_vect)
  {
  ++overflowCount;               // count number of Counter1 overflows
  }  // end of TIMER1_OVF_vect

//******************************************************************
//  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
//  16Mhz / 128 / 125 = 1000 Hz

ISR (TIMER2_COMPA_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  // see if we have reached timing period
  if (++timerTicks < timerPeriod)
    return;  // not yet

  // if just missed an overflow
  if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
    overflowCopy++;

  // end of gate time, measurement ready

  TCCR1A = 0;    // stop timer 1
  TCCR1B = 0;

  TCCR2A = 0;    // stop timer 2
  TCCR2B = 0;

  TIMSK1 = 0;    // disable Timer1 Interrupt
  TIMSK2 = 0;    // disable Timer2 Interrupt

  // calculate total count
  timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
  counterReady = true;              // set global flag for end count period
  }  // end of TIMER2_COMPA_vect

void setup ()
  {
  Serial.begin(115200);
  Serial.println("Frequency Counter");
  } // end of setup

void loop ()
  {
  // stop Timer 0 interrupts from throwing the count out
  byte oldTCCR0A = TCCR0A;
  byte oldTCCR0B = TCCR0B;
  TCCR0A = 0;    // stop timer 0
  TCCR0B = 0;

  startCounting (500);  // how many ms to count for

  while (!counterReady)
     { }  // loop until count over

  // adjust counts by counting interval to give frequency in Hz
  float frq = (timerCounts *  1000.0) / timerPeriod;

  Serial.print ("Frequency: ");
  Serial.print ((unsigned long) frq);
  Serial.println (" Hz.");

  // restart timer 0
  TCCR0A = oldTCCR0A;
  TCCR0B = oldTCCR0B;

  // let serial stuff finish
  delay(200);
  }   // end of loop

Feeding in a 1 kHz sine wave (from 0V to 5V) I get this output:
Frequency Counter
Frequency: 1000 Hz.
Frequency: 1002 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1002 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.

There is the occasional mis-reading but it looks accurate enough. You might sample a few times, and if you get something between 990 and 1010, five times, you might consider that a match.
You will need to make sure that the input is in the range for triggering the input circuitry of the Arduino. It should be around 4 to 5V, and not higher than 5V (for a high). It also should not go negative.
Something like this will protect the input pin:

Warning - audio from an audio jack will be AC and it will go negative. Make sure you use a suitable input protection.

Amplification
After looking at Wikipedia - Line level it seems likely that the output from your phone will not be high enough (around 700 mV probably). Therefore a simple transistor amplifier will probably be required to raise it to a level that can be detected.
Inspired by this post on Electronics Stack Exchange, I made up a simple amplifier:

Testing out with around 500mV peak-to-peak input indicates that it successfully amplified it to 0 to 5V DC:

Alternative method with analog comparator
Based on suggestions by Chris Stratton, there is another way of doing this.
You can use the analog comparator to detect an analog signal passing a threshold, like this:

I have set up the voltage divider to trigger at 0.265V, so that a 500 mV signal should provide an acceptable triggering range.
As for the sketch, at these frequencies we can do something simpler than what I posted before:
volatile bool counting;
volatile unsigned long count;

ISR (ANALOG_COMP_vect)
  {
  if (counting)
    count++;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

unsigned long startTime;

void loop ()
  {

  if (!counting)
    {
    startTime = micros ();
    count = 0;
    counting = true;
    }
  else
    {
    // is a second up? (1000000 microseconds)
    if (micros () - startTime >= 1000000)
      {
      counting = false;
      Serial.print (count);
      Serial.println (F(" Hz."));
      }  // end of a second being up

    }  // end of if

  }  // end of loop

You don't need an amplifier, if you are going to do single-tresholding detection anyway, the ATmega has an analog comparator usable by the timer.  What you did miss is the DC blocking capacitor in your first circuit.  Choose one that makes the impedance high (especially in combination with any resistor) enough to use the internal protection diodes, rather than trying to find an external one that creates the right limitation.

@ChrisStratton :  Yes, good idea. I've edited with an alternative method along the lines of what you suggested.

I'm afraid you still don't quite have it. The diode remains a distraction and you need to bias to your threshold, which would ordinarily be placed somewhere more like half the operating voltage.

Well, @ChrisStratton, I would be pleased if you would post an answer explaining your solution in detail. Just saying that I have it wrong isn't helping me or anyone else, like the OP.

you need to bias to your threshold - I was assuming that the incoming signal was around 700mV (Line Level) - and indeed that worked in my test. Feel free to post other figures.

Nice description and quick prototyping!  I totally missed that the signal did not have any other background noise, it's just the 1kHz tone.

How to do this on a Attiny85? Code does not compile. I want to use an old phone with touchscreen that uses a (local) webpage as button interface and connected via audio to the Attiny85. Each button produces a sound (wave) at different Hz to be unique and to identify which button is pressed. Came along this article because there are not much articles about using (an old phone's) audio as interface to interact with a hardware project. It doesn't sound impossible, like your example describes. Possible to do this on Attiny? Will be great.

If your signal is a pure 1 kHz tone, then you should use Nick
Gammon's counting method, as it is the most straight-forward solution.
If, however, you are picking the signal through a microphone, chances
are you will also get some background noise, and this can make the
counting method unreliable.
In such a case, you will have to use some kind of digital filter to
extract the desired signal from the noise. I would recommend using
homodyne detection,
which is both simple and very robust against wide-spectrum noise: let
f = 1 kHz be the frequency you want to detect, and t
be the current time, then

compute cos(2 π f t ) and sin(2 π f t ): these two periodic signals,
in quadrature to one another, are called “the local oscillator”
multiply your signal independently by the above cos() and sin()
low-pass filter the two products, which gives you the
I and Q demodulated signals
compute the instantaneous power = I2 + Q2.

You know the phone is ringing when this power goes above some
experimentally-determined threshold.
I know all this sounds like heavy math, but it need not be:

All the computations are amenable to efficient fixed-point
implementations, and you can do the math in parallel with the
analog-to-digital conversion.
The scheme works even with crude approximations of the sin() and cos()
functions. Even square waves (sin() and cos() being always +1 or −1)
work quite decently.
The low-pass filter can be implemented as an
exponential moving
average,
which is only a bit shift, an add and a subtract.

I can try to write some sample code, but I would go through the trouble
only if there is interest. If your signal is so clean that Nick Gammon's
method works reliably, there probably is no point.

EDIT: I wrote a program to demonstrate this approach, just for the
fun. It's available as a GitHub gist:
homodyne.ino.
I am not copying the whole program here, just adding some explanations:
The first thing is to take care of the sampling frequency. Whenever one
wants to do signal processing, it is very desirable to sample at a fixed
and known frequency. This is next to impossible to achieve by looping
over analogRead(), because the CPU time needed to go through the loop
is hard to predict, as it can be influenced by interrupts and by
conditional branches. analogRead() is also highly inefficient, as it
locks the CPU in a busy loop while it waits for the analog-to-digital
converter (ADC) to do its job.
The solution is to put the ADC in the so called "free running mode". In
this mode, it starts a conversion as soon as the previous one is
finished, which gives a very steady sampling rate of 9.615 kHz (one
sample every 104 µs). The samples are handled by an interrupt
service routine called ISR(ADC_vect) which gets triggered every time a
sample is ready. This is also where all the signal processing is done.
Below is a detailed explanation of every line of code in the ISR:
int8_t sample = ADCH - 128;

Reading the ADC result is the first thing to do in the ISR. Since we do
not need the full 10 bit resolution, the ADC was configured to
left-adjust its result. Then we get an 8-bit result by just reading the
high byte of the ADC data register. We subtract 128 to remove the DC
offset and get a signed number in the range [−128 .. +127].
Next, we update the phase of our local oscillator:
static uint16_t phase;
phase += PHASE_INC;

We need not worry about possible overflows: since the phase is kept in
units of 1/216 cycles, the increment automatically works
modulo one cycle. The phase increment should theoretically be 6815.744,
which is rounded to 6816. This makes the local oscillator fast by
0.0376 Hz, which is negligible given the accuracy of the Arduino
clock. The phase could be kept in an 8-bit variable, but the rounding
error would then make the oscillator fast by 14 Hz, which can be
borderline unacceptable.
Next we need to build two square waves in quadrature, which will be used
as rough approximations of sin() and cos(). But since the most
significant bit of the phase is on during half of the cycle, it can be
used as one of our square waves. The other wave is obtained in a similar
way, after adding 1/4 cycle to the phase. So here is how we multiply our
sample by the square waves:
int8_t x = sample;
if (((phase>>8) + 0x00) & 0x80) x = -1 - x;
int8_t y = sample;
if (((phase>>8) + 0x40) & 0x80) y = -1 - y;

The expression phase>>8 is only meant to hint the compiler that it
needs only to consider the most significant byte of the phase. This
should normally not be needed, but I noticed that, without this hint,
gcc generates suboptimal code. The -1 in the above lines are for
avoiding a possible overflow.
Next comes the low-pass filter:
signal_I += x - (signal_I >> LOG_TAU);
signal_Q += y - (signal_Q >> LOG_TAU);

Where signal_I and signal_Q are volatile int16_t globals, and
LOG_TAU is 6. This filters with a time constant

τ = 64 × 104 µs = 6.656 ms

which translates to a −3 dB bandwidth of

Δf = 1/(2πτ) = 23.9 Hz.

which is fairly narrow for a 1 kHz signal. The significance of τ is
that, once the tone starts, it takes the filter about
2.3 τ ≈ 15 ms to reach 90% of its final output. Both
τ and Δf can be changed by simply changing LOG_TAU.
This ISR takes about 176 CPU cycles (11 µs, including the
4 cycles needed to put the CPU in interrupt mode) every
1664 cycles (104 µs). This amounts to about 10.6% of the
available CPU power. And since everything is done inside the ISR, the
program is free to do whatever else needs to be done while the data
acquisition and digital filtering happens in the background.
I tested the program by sending it a sine wave of 4.36 V
peak-to-peak amplitude. The reported power fluctuated quite a bit, but
here are the approximate average readings as a function of the input
frequency:
frequency  |  power
-----------+-------
   929 Hz  |   480
   976 Hz  |  2400
  1005 Hz  |  4600
  1028 Hz  |  2700
  1079 Hz  |   480


text:
Burning servos like crazy, what am I doing wrong?
For some reason my servos keep burning out.
My code is simple, if condition, rotate to 0 degrees, else rotate to 180.
However, what that does to the motor is keep it in a constant struggle to stay in rotation 0 or 180, when there is no movement in between. Sure enough, leave it running for 1 hour, the motor burns out.
if (!strcmp("1",output)){
    myservo.write(0);
}
else {
    myservo.write(180);
}

Is there something like myservo.release or something? I presuming i need to get the servo in to position, then release it so it doesnt try to stay in position.
Please help, i've burned through 4-5 of them so far, it's not fun :(

Servo's are meant to keep their position; if you could "release" the torque you won't have a "fixed" position, since when shut down the motor does not generate the torque to keep it still. You can try to reduce the speed of the servo, but if the problem arises when you leave it still then probably you just have to consider changing servo brand..

Are you sure these servos can run all the way to 0 and 180 degrees? (If they are running against their end stops it might cause problems.) Also what voltage are they rated for, and what power are you using?

What are your servos doing, or trying to do? If they are not driving anything they should hold position with very little current. If they are holding against a load, they take current to maintain position; more load = more current. Seeking an unachievable position (beyond their, or the mechanical system's stops) is a worst-case.

First steps: Burned motors are most often the result of two things, incorrect wiring or using the wrong voltage input to the motor for power. Make sure your voltage source matches the specs on the servos and that your wiring is correct.

Some servos are actually not able to do full 0..180 rotation - or to rephrase it better, the standard 0.5ms and 1.5ms pulse will force them to a position which can not be reached. Therefore the motor keeps on rotating in a constant struggle.

change 0 to something like 20, and 180 to something like 150
check that the motor has stopped once reaching 20 or 150. I.e. it does not produce any sound, and if you touch the motor body it is not producing any vibration (so no constant stuggle)

Most servo has a range of 90deg, so the safe range is from 45 to 135 (which correspond to a pulse from 1000 to 2000ms)

Actually, I found it is not etched into stone. I have a couple of micro servos, which accept pulses of 0..180 degrees (0.5/1,5ms), still make a rotation of only 90 degrees because of difference in gears. I would say that we control the pulse width - and the servo react in some way :) I agree that it is a little oversimplification expecting that myservo.write(35) will move to 35.000 degrees.

Yes there are exception, but most use the "standard" pulse, because that is what come out from most radiocontroller

I can fully agree, @lesto! However standards are obeyed pretty liberally by many Chinese manufacturers as I have found, especially with TowerPro servos. (They are great price to value ratio, but do have the same problems what the OP mentioned.)

Ensure your voltage source matches the motors specs and that your wiring to the arduino or driver shield is correct and try the code I've posted which has worked for me to test servos.
#include <Servo.h>  // servo library
// You can control a maximum of twelve servos on the Uno
// using this library. (Other servo libraries may let you
// control more). Note that this library disables PWM on
// pins 9 and 10!

Servo servo1;  // servo control object

void setup()
{
  //  Attach the servo1 object to digital pin 4.
  servo1.attach(4);
}

void loop()
{
  int position;
  // Change position at full speed:

  servo1.write(90);    // Tell servo to go to 90 degrees
  delay(1000);         // Pause to get it time to move
  servo1.write(180);   // Tell servo to go to 180 degrees
  delay(1000);         // Pause to get it time to move
  servo1.write(0);     // Tell servo to go to 0 degrees
  delay(1000);         // Pause to get it time to move

  // Change position at a slower speed:
  // Tell servo to go to 180 degrees, stepping by two degrees

  for(position = 0; position < 180; position += 2)
  {
    servo1.write(position);  // Move to next position
    delay(20);               // Short pause to allow it to move
  }

  // Tell servo to go to 0 degrees, stepping by one degree

  for(position = 180; position >= 0; position -= 1)
  {
    servo1.write(position);  // Move to next position
    delay(20);               // Short pause to allow it to move
  }
}

I wanted to answer my own question:
I had purchased some really cheap servos from AliExpress. These are not good. They burn out really fast, which has been confirmed by some friends of mine that had purchased the same servos.
The voltage was correct, it was 5V. When using more quality servos that cost $15 I did not see any of these issues.
Do your self a favor. Do not get servos from AliExpress. Get them from DFRobot or some other more reputable website.

source: Stack Exchange

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

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

sort: votes


text:
Processing Serial data
I have a PM10 sensor that I'd like to get the values from.
Here's the official documentation from the sensor:

I've looked as serial communication, but how do i process byte by byte of information if it's coming in byte at a time?
I'm looking at this example:
void setup() {
  Serial.begin(9600);
  Serial.println("<Arduino is ready>");
}

void loop() {
  recvOneChar();
  showNewData();
}

void recvOneChar() {
  if (Serial.available() > 0) {
    receivedChar = Serial.read();
    newData = true;
  }
}

void showNewData() {
  if (newData == true) {
    Serial.print("This just in ... ");
    Serial.println(receivedChar);
    newData = false;
  }
}

Ideally, i'd like to get the PM2 and PM10 values and print them out.

The proper method of receiving this kind of data is to use a sliding window. That is you visualise the stream of bytes as just that - a stream of bytes (think letters on paper tape).  You then have a conceptual "window" on that data which is the width of the packet (10 bytes in this case).  As the data passes behind the window you see just 10 bytes of it. When that 10 bytes is in the "right" format (that is, it starts with 0xAA, ends with 0xAB and the checksum is valid) then you have a valid packet and can read the values from it.
The simplest method of implementing that is with a 10-byte array. As a byte arrives on the serial port you shuffle all the bytes down the array to make room for the new byte at the top of the array.  Once 10 bytes have arrived that first byte should now have made its way to the bottom of the array.
For instance:
uint8_t window[10];

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

void loop() {
    if (Serial.available()) {
        // Slide the window
        for (uint8_t i = 0; i < 9; i++) {
            window[i] = window[i + 1];
        }
        // Add the new character
        window[9] = Serial.read();

        // Output the current window data for debugging
        dumpWin();

        // Check the framing characters
        if ((window[0] == 0xAA) && (window[9] == 0xAC)) {
            // Calculate the checksum
            uint8_t cs = 0;
            for (uint8_t i = 2; i < 8; i++) {
                cs += window[i];
            }
            // If the checksum matches...
            if (cs == window[8]) {
                // ...we have a valid packet!
            }
        }
    }
}

void dumpWin() {
    for (int i = 0; i < 10; i++) {
        Serial.print(window[i], HEX);
        Serial.print(" ");
    }
    Serial.println();
}

Getting the data out of the valid packet is now a case of combining bytes into 16-bit integers then dividing them into floats.  For instance the PM2.5 would be:
uint16_t pm25i = (window[3] << 8) | window[2];
float pm25 = (float)pm25i / 10.0;

The PM10 would be the same but with window[5] and window[4] of course.

Since you can't really use the hardware UART for both communication with your sensor and communication with the PC you may want to investigate the use of SoftwareSerial instead of the hardware UART pins for communicating with the sensor.

Amazing stuff! Great work!

However, i'm having an issue, it never reached the IF condition, so i did some debugging:
Serial.print(window[0]);
Serial.print("=");
Serial.print(window[9]);
Serial.println();
And it's returning some weird results:
0=170
0=192
0=85
0=1
0=115
0=1
Shouldnt the first number be a byte? Shouldnt the second one be static as well? Why is the second number changing for each row?

You might be better off dumping the whole window each time. I'll add a little function to do that.

@R0b0tn1k By the way, 170 is 0xAA - the first number in the = will change to 170 when it finally reaches the bottom of the window (10 characters have been received).

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


text:
Error compiling Arduino
I've just installed the last version of Arduino 1.6.7 plug my Arduino SmartEverything (http://www.smarteverything.it/) to OS X 10.11.2, try to compile this project: https://github.com/nicolsc/sigfox-weather-station/blob/master/sigfox_smart_weather.ino But i got this error
/Applications/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware "/Applications/Arduino.app/Contents/Java/hardware" -hardware "/Users/nunito/Library/Arduino15/packages" -tools "/Applications/Arduino.app/Contents/Java/tools-builder" -tools "/Applications/Arduino.app/Contents/Java/hardware/tools/avr" -tools "/Users/nunito/Library/Arduino15/packages" -built-in-libraries "/Applications/Arduino.app/Contents/Java/libraries" -libraries "/Users/nunito/Documents/Arduino/libraries" -fqbn=AMEL:samd:AMEL_SmartEverything_native -vid-pid=0X2341_0XE002 -ide-version=10607 -build-path "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/arduino_50d3a89dbbfb2b67c903ba23d4913431/sketch_jan21c.ino"
/Applications/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware "/Applications/Arduino.app/Contents/Java/hardware" -hardware "/Users/nunito/Library/Arduino15/packages" -tools "/Applications/Arduino.app/Contents/Java/tools-builder" -tools "/Applications/Arduino.app/Contents/Java/hardware/tools/avr" -tools "/Users/nunito/Library/Arduino15/packages" -built-in-libraries "/Applications/Arduino.app/Contents/Java/libraries" -libraries "/Users/nunito/Documents/Arduino/libraries" -fqbn=AMEL:samd:AMEL_SmartEverything_native -vid-pid=0X2341_0XE002 -ide-version=10607 -build-path "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp" -warnings=none -prefs=build.warn_data_percentage=75 -verbose "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/arduino_50d3a89dbbfb2b67c903ba23d4913431/sketch_jan21c.ino"
Build options changed, rebuilding all
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/dev/null"
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/dev/null"
""   -w -x c++ -E -CC -DF_CPU=48000000L -DARDUINO=10607 -DARDUINO_SAMD_SMARTEVERYTHING -DARDUINO_ARCH_SAMD  -D__SAMD21J18A__        "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/cores/arduino" "-I/Users/nunito/Library/Arduino15/packages/AMEL/hardware/samd/1.1.0/variants/AMEL_SmartEverything" "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/sketch/sketch_jan21c.ino.cpp" -o "/var/folders/52/_nghc_ms7p52tqr5zdbwvj240000gn/T/build50d3a89dbbfb2b67c903ba23d4913431.tmp/preproc/ctags_target_for_gcc_minus_e.cpp"
exec: "-w": executable file not found in $PATH
Error compiling.

Your installation is broken.

I've reinstalled Arduino with the same problem

You must reinstall the Board. That is where the problem is. The board build settings are not read correctly. The compiler setting is missing.

I guess I can't do it through the USB

What has USB got to do with the board and compiler definition installation?  Just delete and reinstall the whole thing, not just the IDE. Delete all the boards and reinstall them.

I 've reinstalled with the same result :-(

Reinstalled the IDE, or reinstalled the boards / compilers etc packages?

Please avoid posting duplicate questions on multiple SE sites

Install Arduino SAMD Boards (32-bits ARM Cortex-M0+) board (using "Tools" -> "Board" -> "Boards Manager" menu).
Just search for "SAMD" in the search bar, choose the latest version and install.

Are you saying this fixed the problem?

yes !!!   indeed, this fixed the problem


text:
Converting TinkerKit to native Arduino pins
Over the years, I have acquired many TinkerKit modules for my Arduino Uno. My only issue is that I need to find a way to code using the native syntax, and not the less-powerful TinkerKit variation. To do this, I need to know if TinkerKit maps its 3-pin connector to the Arduino Board's pins (ex: 1, 3, 5). If it does, what are the mappings?
Thanks in advance!

The TinkerKit Sensor Shield helps understand the mapping. There is also the TinkerKit Header File with symbol mapping.


text:
TCCR1A and TCCR2A on Leonardo
I'm trying to use the TTS library for Arduino on an Arduino Micro board, which is based on the Leonardo. When I try to compile my sketch I get some errors;
/libraries/TTS/TTS.cpp: In function 'void soundOff()':
/libraries/TTS/TTS.cpp:355: error: 'TCCR2A' was not declared in this scope
/libraries/TTS/TTS.cpp:355: error: 'COM2B1' was not declared in this scope
/libraries/TTS/TTS.cpp: In function 'void soundOn()':
/libraries/TTS/TTS.cpp:382: error: 'TCCR2A' was not declared in this scope
/libraries/TTS/TTS.cpp:382: error: 'COM2B1' was not declared in this scope
/libraries/TTS/TTS.cpp:382: error: 'WGM20' was not declared in this scope
/libraries/TTS/TTS.cpp:383: error: 'TCCR2B' was not declared in this scope
/libraries/TTS/TTS.cpp:383: error: 'CS20' was not declared in this scope
/libraries/TTS/TTS.cpp:383: error: 'WGM22' was not declared in this scope
/libraries/TTS/TTS.cpp:384: error: 'OCR2B' was not declared in this scope
/libraries/TTS/TTS.cpp:385: error: 'TCNT2' was not declared in this scope
/libraries/TTS/TTS.cpp: In function 'void sound(byte)':
/libraries/TTS/TTS.cpp:424: error: 'OCR2B' was not declared in this scope
/libraries/TTS/TTS.cpp:425: error: 'TCNT2' was not declared in this scope

Googling revealed that the Leonardo uses different timers. And other things I don't understand! But I couldn't piece together an answer beyond that.
What are the correct constants to use for Leonardo boards, and is there a way I can update the library to work across both?

The hilarious part is that the Arduino libraries provide MCU-independent ways to do all that and this code completely ignores all of them.

@IgnacioVazquez-Abrams Great news! Do you have a link on how to use that feature of the library, or an example please?

This "library" is written specifically for the ATMega328 (not the ATmega32u4 inside the Leonardo).  You should be able to port it. Not hard, but not also a task for a beginner.

Eh. I just noticed that it uses parameters not controlled by the basic libraries. You'd need to find a more fully-featured PWM library for it. But barring that conditional compilation would be the way to go.

Do you have to use a Micro? Your code will probably work on a Uno (or some other ATmega328 based board). To check, select Uno under the Tools->Board menu and then try to compile it.

Apparently the library in the OP's link has been updated to support the Leonardo, so this problem should now be solved.

This is the Leonardo patch in case its useful to anyone https://github.com/jscrane/TTS/pull/6/commits/d84cbd2eb39e513e62b4f33a55ccfad412f5aec8


text:
Explanation for micros function
I was trying to understand the working of micros() function internally and I had a look at the function in Arduino.h
This is the code:
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;

    cli();
    m = timer0_overflow_count;
 #if defined(TCNT0)
    t = TCNT0;
 #elif defined(TCNT0L)
    t = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

#ifdef TIFR0
        if ((TIFR0 & _BV(TOV0)) && (t & 255))
        m++;
#else
        if ((TIFR & _BV(TOV0)) && (t & 255))
        m++;
#endif

    SREG = oldSREG;

    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

Can someone please explain me what this line is doing :
  if ((TIFR0 & _BV(TOV0)) && (t & 255))
   m++;

If the timer 0 has overflowed (TIFR0 & _BV(TOV0)) and there is at least a count of 1 in the timer count register (t & 255) then increment the local copy of the overflow count.
That overflow count is used later on to add an upper 8 bits to what is basically an 8 bit counter to turn it into a 16 bit one ((m << 8) + t).

can you please explain me "timer0_overflow_count" too?

It's the current count of timer overflows - it's incremented in an interrupt routine elsewhere.

Since at the start of this function interrupts have been disabled by the cli() function it is possible that the timer TCNT0 has overflowed yet this event has not been processed and included in the value of timer0_overflow_count that has been read into m. Therefore the line that you are asking about is checking for this condition and incrementing the local copy m if necessary before using it to calculate the number of microseconds since startup.


text:
Is this a fake pulse sensor?
A couple of days ago, I purchased a pulse sensor online for a project. Before actually doing anything with it, I wanted to capture and view its analogue waveform output. One while placing my finger on it and one when in the default state, so that I can see the trend or difference in the two waveforms. But when I captured the output, it seems like there is not much difference. Just some random noise I guess. Also, I checked the company website who may have made this one and it all looks good to me.

The image below shows the waveform captured when no finger is placed on the sensor.

The image below shows the waveform captured when my index finger is placed on the sensor.

This is my setup for the sensor for measuring pulses.

This image shows the face of the sensor.

I need some insights from folks here regarding this sensor. Is it showing some junk output? or my understanding is wrong and there's a better way to figure this out/ work with this sensor.

I'm voting to close this question as off-topic because it is not in any way about Arduino, and because even for an SE site where the subject matter could be on topic, the question fails to state details of the measurement taken.

What is a pulse sensor? I don't see what this question has to do with Arduinos.

The second trace looks like a pulse to me. With that kind of sensor you don't get the PQRST traces of an ECG - just a slight bump when you get a pulse.

Ok, that means this sensor does work. I am connecting the output of this sensor to a 24 (~18 ENOB) bit ADC and getting the digital data. What would be the right approach to accurately capturing these bumps using the digital samples while being able to differentiate it from other junk?.

Low pass filter it to remove the random spikes, and then look for the change in signal level through a threshold, maybe with some hysteresis.

To design a low pass digital filter, I need to know the cut off frequency, how do I know that?

You don't need that level of detail. The difference in frequency between signal and noise is big enough that simple averaging of samples is enough.


text:
Connecting TCD1304 with Arduino
I'm working on a project, where I will have 2 red light beams, where one will be constantly turned on while the other will be turned on and off continuously with frequency about 100 hz.
I need to detect, on which side is the blinking beam and show it on the output (something such as if the blinking beam is on the left, turn green LED on; if it's on the right side, turn on the red LED). Each beam is big as 3mm circle.
I bought 3pcs (in case if I burn 2 of them :D) of Toshiba TCD1304 sensors(datasheet), which have 3684 elements in a row. I want to connect the sensor with Arduino, but I really don't know how I would even start this project. I've found some schematics, but it's either for some other model or is for different kind of a project(reading different colors over the field). Either way, none of them is useful for me.
It will look something like that at the end (the blue circle will be also red, but it's striped to show, it's the blinking one).

The TCD1304's minimum OS-datarate is 200 kHz. Quite a lot more than what the arduino is capable of. You should look to faster processors or to a different sensor. The TSL1401 seems to be popular with the arduino-community.
If you /need/ the TCD1304, then an arduino due will probably be able to do it, but I'm guessing you'll have to drop the arduino-IDE to achieve the full speed of the ADC.
Here's how I've done it with a STM32F4 processor:
https://tcd1304.wordpress.com/


text:
How to use IRremote library with atmega8a
A few days ago I tested  a circuit on a  breadboard based on a ATmega8a with 1 MHz internal oscilator. It sould turn on and off a relay based on a IR code that is received and if it matches the programmed in the EEPROM it shoud enable or disable the relay. Now I developed a PCB and soldered everything together but now it isn't working. On an Arduino Nano it is working ok.
#include <IRremote.h>
#include <EEPROM.h>

int RECV_PIN = 11;
int RELAY_PIN = 4;
int setpin = 3;
unsigned long work_at;
unsigned long adres;
unsigned long irbuffer;
IRrecv irrecv(RECV_PIN);
decode_results results;

void dump(decode_results *results) {

    if(digitalRead(setpin) == 0){
      work_at = results->value;
      Serial.println(work_at, HEX);
    }
    irbuffer = results->value;

}

void eeprom_writer(){
  if (irrecv.decode(&results)) {
    if(digitalRead(setpin) == 0 && work_at != 0){
      EEPROM.put(0, work_at); //put walue
      Serial.println(work_at, HEX);
      adres = work_at;
      Serial.println(adres, HEX);
      delay(1000); //wait
   }
  }
}
void setup()
{
  EEPROM.get(0, adres);
  pinMode(setpin, INPUT_PULLUP);
  pinMode(RELAY_PIN, OUTPUT);
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

int on = 0;
unsigned long last = millis();

void loop() {
  if (irrecv.decode(&results)) {
    // If it's been at least 1/4 second since the last
    // IR received, toggle the relay
  //  if(&results == adres){
      dump(&results);
      if (millis() - last > 250) {
        on = !on;
        if(on == true && adres == irbuffer){
          delay(5000);
          digitalWrite(RELAY_PIN, on ? HIGH : LOW);
          dump(&results);
        }else if(on != true  && adres == irbuffer){
          digitalWrite(RELAY_PIN, on ? HIGH : LOW);
          dump(&results);
          delay(5000);
        }
      }
    //}
//    Serial.println(dump(&results));
//    Serial.println(count, DEC);

    eeprom_writer();
    last = millis();
    irrecv.resume(); // Receive the next value
  }
}

@LookAlterno I soldered it ti the pcb and used dip connectors to conect the iscp uart relay and the ir module.

Maybe I should use a pin that supports PWM

Changing the internal oscillator to 8MHz helped.


text:
What are the components of a Xively HTTP PUT request to send to my SIM800 GPRS module?
I have an Elecrow GPRS shield which I want to use to post temperatures from 3 x DS18B20s to Xively. The example code is a mystery to me. You can find in full at this link: http://www.elecrow.com/wiki/index.php?title=GPRS/GSM_Shield_v1.0#A_Simple_Source_Code_Example
The relevant function is here:
///send2Pachube()///
///this function is to send the sensor data to the pachube, you can see the new value in the pachube after execute this function///
void Send2Pachube()
{
mySerial.println("AT+CGATT?");
delay(100);

ShowSerialData();

mySerial.println("AT+CSTT=\"CMNET\"");//start task and setting the APN,
delay(1000);

ShowSerialData();

mySerial.println("AT+CIICR");//bring up wireless connection
delay(300);

ShowSerialData();

mySerial.println("AT+CIFSR");//get local IP adress
delay(2000);

ShowSerialData();

mySerial.println("AT+CIPSPRT=0");
delay(3000);

ShowSerialData();

mySerial.println("AT+CIPSTART=\"tcp\",\"api.cosm.com\",\"8081\"");//start up the connection
delay(2000);

ShowSerialData();

mySerial.println("AT+CIPSEND");//begin send data to remote server
delay(4000);
ShowSerialData();
String humidity = "1031";//these 4 line code are imitate the real sensor data, because the demo did't add other sensor, so using 4 string variable to replace.
String moisture = "1242";//you can replace these four variable to the real sensor data in your project
String temperature = "30";//
String barometer = "60.56";//
mySerial.print("\"method\": \"put\",\"resource\": \"/feeds/43634/\",\"params\"");//here is the feed you apply from pachube
delay(500);
ShowSerialData();
mySerial.print(": ,\"headers\": \"X-PachubeApiKey\":");//in here, you should replace your pachubeapikey
delay(500);
ShowSerialData();
mySerial.print(" \"_cXwr5LE8qW4a296O-cDwOUvfddFer5pGmaRigPsiO0");//pachubeapikey
delay(500);
ShowSerialData();
mySerial.print("jEB9OjK-W6vej56j9ItaSlIac-hgbQjxExuveD95yc8BttXc");//pachubeapikey
delay(500);
ShowSerialData();
mySerial.print("Z7_seZqLVjeCOmNbEXUva45t6FL8AxOcuNSsQS\",\"body\":");
delay(500);
ShowSerialData();
mySerial.print(" \"version\": \"1.0.0\",\"datastreams\": ");
delay(500);
ShowSerialData();
mySerial.println("[\"id\": \"01\",\"current_value\": \"" + barometer + "\",");
delay(500);
ShowSerialData();
mySerial.println("\"id\": \"02\",\"current_value\": \"" + humidity + "\",");
delay(500);
ShowSerialData();
mySerial.println("\"id\": \"03\",\"current_value\": \"" + moisture + "\",");
delay(500);
ShowSerialData();
mySerial.println("\"id\": \"04\",\"current_value\": \"" + temperature + "\"],\"token\": \"lee\"");

delay(500);
ShowSerialData();

mySerial.println((char)26);//sending
delay(5000);//waitting for reply, important! the time is base on the condition of internet
mySerial.println();

ShowSerialData();

mySerial.println("AT+CIPCLOSE");//close the connection
delay(100);
ShowSerialData();

}
void ShowSerialData()
{
while(mySerial.available()!=0)
Serial.write(mySerial.read());
}

Note that although this is called "send2Pachube" it uses the Cosm API, which still works.
The section following the line
mySerial.println("AT+CIPSEND");

is where the HTTP gets formulated. I've assembled the string in the example code and it looks odd. The API key goes on about four times longer than it should. I'm not sure what all those colons are doing in there, are they a String operator? Can anyone give me an example of an HTTP PUT request for Cosm or Xively that illustrates how this string should be assembled?
Thanks

I've got a working solution to this issue. Here's the values you can edit and the function:
String FEED = "YOUR_FEED";
String KEY = "YOUR_API_KEY";
String DATASTREAM1 = "YOUR_DATASTREAM1_NAME";
Int VALUE1 = YOUR_VALUE1;
String DATASTREAM2 = "YOUR_DATASTREAM2_NAME";
Int VALUE2 = YOUR_VALUE2;

void send2Cosm()
{
mySerial.println("AT+CGATT?");
delay(100);
ShowSerialData();
mySerial.println("AT+CSTT=\"CMNET\"");//start task and setting the APN,
delay(1000);
ShowSerialData();
mySerial.println("AT+CIICR");//bring up wireless connection
delay(300);
ShowSerialData();
mySerial.println("AT+CIFSR");//get local IP adress
delay(2000);
ShowSerialData();
mySerial.println("AT+CIPSPRT=0");
delay(3000);
ShowSerialData();
mySerial.println("AT+CIPSTART=\"tcp\",\"api.cosm.com\",\"8081\"");//start up the connection
delay(2000);
ShowSerialData();
mySerial.println("AT+CIPSEND");//begin send data to remote server
delay(4000);
ShowSerialData();

mySerial.print("{\"method\": \"put\",\"resource\": \"/feeds/" + FEED + "/\",\"params\"");
delay(500);
ShowSerialData();
mySerial.print(": {},\"headers\": {\"X-ApiKey\":");
delay(500);
ShowSerialData();
mySerial.print("\"" + KEY + "\"},\"body\":");
delay(500);
ShowSerialData();
mySerial.print(" {\"version\": \"1.0.0\",\"datastreams\":");
delay(500);
ShowSerialData();
mySerial.print("[{\"id\": \"" + DATASTREAM1 + "\",\"current_value\": \"");
mySerial.print(VALUE1);
delay(500);
ShowSerialData();
mySerial.print("\"},{\"id\": \"" + DATASTREAM2 + "\",\"current_value\": \"");
mySerial.print(VALUE2);
delay(500);
ShowSerialData();
mySerial.println("\"}]}}");
delay(500);
ShowSerialData();

mySerial.println((char)26); //sending = ctrl+z
delay(5000);//waitting for reply, important! the time is base on the condition of internet
mySerial.println();

ShowSerialData();

mySerial.println("AT+CIPCLOSE");//close the connection
delay(100);
ShowSerialData();

}

void ShowSerialData()
{
while(mySerial.available()!=0)
Serial.write(mySerial.read());
}

To answer part of my question: no, the colons aren't a String operator, they're part of the HTML. Here's an example of the formed URL that gets sent:
{"method": "put","resource": "/feeds/YOUR_FEED/","params": {},"headers": {"X-ApiKey":"YOUR_API"},"body": {"version": "1.0.0","datastreams":[{"id": "DATASTREAM1","current_value": "VALUE1"},{"id": "DATASTREAM2","current_value": "VALUE2"}]}}

This code updates my feed but after several hours the updates stop. I'm still troubleshooting this new problem so I'm not 100% sure that this code is good. I will post back if the problem's in here.


text:
Mini Voice Recorder for Arduino
I am trying to find a small voice recorder that I can use with my Arduino Micro, and I found this. It is exactly what I am looking for, but it is now a retired product. I googled ISD1932, but many other sites are out of stock or not selling it anymore. Is there something of this size that does the same things, and why is it retired?

ISD 1820 voice recorder module for arduino. Or ISD series or ISD 1700 series voice recorder module. Which I think you can still buy these. Will work  with 8bit CPU. Or can be interfaced to 8 bit CPU. You could use multiple modules to increase recording times. I can give you more of an answer if you tell me more about your problem. ISD4004 IC can record for 8 minutes.

This was perfect!

FYI, these ISD chips sample audio and store a variable charge on a single flash like cell. They do not convert a sample to a numerical value. There is no data to be read from the chips nor (AFAIK) is there an opportunity to write data to play back to the chips. AFAIK, for us common people, each ISD chip needs to have its recording entered individually. Think of it like duplicating cassette tapes. Think about this when considering how to go about building your project.

I  think the OP was asking can he get a chip on a breakout board -or something that can be interfaced to an 8 bit arduino-rather  than an IC chip.

Yes, agreed.  I debated on answering or commenting.  But this is the Arduino bit of stackexchange and I thought the information useful not just for the OP but for others exploring using the same chip.

It's retired because there is no market for it any more. Modern microcontrollers are more than powerful enough to handle simple audio without the need for external chips like that.
Some can even do full blown multi-channel HD audio with just the addition of a CODEC chip (that's a fancy name for a DAC to you and me).
Even a lowly 8-bit Arduino can play audio directly (though at low quality) through PWM from an SD card.

@Manjenko Thank you. That helped me understand why it is retired. But is there a substitution for it that would work with this?

Yes, it's called don't use that, use something better. Maybe a Teensy 3.1 or something like that...?

Please don't be rude. Also, I already bought that because I thought people on StackExchange could help me.

I'm not being rude. I'm being serious. 8 bitters have a role, but that role is not working with audio. Teensy's are very similar in design and price but have much more power and are more suited to audio work.

Dat Han Bag's answer worked.


text:
ESP-NOW: Master and Slave at the same time
I am interested to use ESP-NOW as a means to transmit data between two ESP32's back and forth, - each ESP receives and sends data, taking turns. The example library provides an example sketch for Slave and one for Master, which allows for one-directional data flow. However, I would like to use ESP-NOW for two-way communication. Is it possible to combine both of these sketches to allow the data to flow in both directions at the same time?

I'm assuming two ESP's won't be able to send data at the same exact time, so the best approach to start, I think, would be to wait until a packet has been received before sending one from the other end. Here's a snippet of code which I tried to use, but failed:

void setup()
{
  Serial.begin(115200);
  WiFi.mode(WIFI_MODE_APSTA);
  // configure device AP mode
  configDeviceAP();
  // This is the mac address of the Slave in AP Mode
  Serial.print("AP MAC: ");
  Serial.println(WiFi.softAPmacAddress());
  Serial.print("STA MAC: ");
  Serial.println(WiFi.macAddress());
  // Init ESPNow with a fallback logic
  InitESPNow();
  // Once ESPNow is successfully Init, we will register for recv CB to
  // get recv packer info.
  esp_now_register_recv_cb(OnDataRecv);
  esp_now_register_send_cb(OnDataSent);
}

unsigned long nextManage;

void loop()
{
  // In the loop we scan for slave
  ScanForSlave();
  // If Slave is found, it would be populate in `slave` variable
  // We will check if `slave` is defined and then we proceed further
  if (slave.channel == CHANNEL2)
  { // check if slave channel is defined
    // `slave` is defined
    // Add slave as peer if it has not been added already
    bool isPaired = manageSlave();
    nextManage = millis() + 10000;
    while (isPaired)
    {
      if (packetRecieved)
      {
        packetRecieved = false;
        // Send data to device
        sendData();
      }

      unsigned long t = millis();
      if (t > nextManage)
      {
        nextManage = t + 10000;
        // pair success or already paired
        isPaired = manageSlave();
      }
    }
    Serial.println("Slave pair failed!");
  }
}

"ESPNow" is part of the ESP IDF. You can read more here: https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/network/esp_now.html - it's not Arduino functionality, but something that is closed source and custom to ESP32.

@Majenko I see. Then the one I made on espressif forum would be more applicable I guess. I will keep this one up for a while just in case. Thanks

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


text:
Using Arduino as Keylogger
Is it possible to use arduino uno r3 as USB keylogger by connecting the usb male pin to CPU and keybord cable to female USB pin of arduino.
So that the keystrokes are stored in EEPROM. Without using an external storage modules or other components?
I am new to arduino, even suggestions are appreciated.
Thanks in advance.

It might help if you explained what you are trying to do.  Are you trying to capture passwords?  Repeat tests?

Yes it possible to to implement USB host in software but you need a few extra components, which are a few resistors
and a USB socket. What youre trying to do is make arduino a USB host for keyboard-some folks
have nearly done  this. I give a link be low. to a USB host  implemented in software for ATMEGA32 I see the source code is there-which you may
try and modify for your uses–they give a driver for mouse-and say the keyboard host (youre interested in)  is is possible
and easy (but not done). ATMEGA32 is similar to AMTMEGA 8 (used in older arduino).

Only a few componenets are used in the solution there-and its cheapers than a USB host shield-the software is there as a zip file -this is a suggestion for starting point-you need to modify software for you own use- see
https://courses.cit.cornell.edu/ee476/FinalProjects/s2007/blh36_cdl28_dct23/blh36_cdl28_dct23/

But for emjulating a keyboard on arduino-there's different ways to do it on arduino-it been done

Of course if you can manage to do the above  you would have good bragging rights-becuase no one made a cheap USB host (for keyboard)  for arduino/arduino library  -instead most people use USB host shield (costing about ten dollars or more)-it would save money of course. Its not as difficult as it looks.

arduino works at 16mhz pushed to maximum speed- that USB solution there  works on 15Mhz arduino-which means is can to do a low speed USB device such as a keyboard

Since you asked for USB (rather than a USB keyobard that also emulates PS2 with a passive adapter -which they dont all do) -I am assuming you have only a USB keyboard in mind -I gave a suggested answer only for USB.. I suggest try that. If you get stuck or have any further question then ask on here.  USB acting as PS2 keyboard or  PS2 keyboard can also be done and the answer has been fully fleshed out.

USB-host is hard if not impossible to implement on an UNO.
Though I believe most USB keyboards support PS2 as well (normally done with a USB-to-PS2 plug). So you should be able to talk to the keyboard using the PS2 protocol, which is a lot easier. There are libraries to do this for you.
Next you could use V-USB to emulate a keyboard to the PC. For that USB connection you need to add some resistors and zener diodes, to stay withing the usb specification. This is all explained on the V-USB website.
Using a different Arduino that has real USB support might be a better option. Also the UNO is rather large, so not that easy to hide.

It is highly unlikely using an arduino uno r3.
USB Device: (To emulate a HID (Human Interface Device) Keyboard):
While there are Arduino libraries for emulating a keyboard, these will not work with the Uno R3.  Instead, to make a Uno R3 act like a USB Keyboard Device, you need to reprogram the 2nd processor on the board and switch it from a USB Serial Device to a USB Keyboard Device.  This is talked about in this stackexchange question.
USB Host (to talk to a USB Keyboard):
I do not believe there are any software solutions for emulating a USB Host on most Arduinos. Certainly not a Uno R3.  A USB Host is a very complex software & hardware device. Instead, most Arduino projects use a USB Host Shield for this purpose.

Down voting with out a comment is not that unusual.  However, it does make it difficult to improve the answer.  Why do you think some of these answers are not correct?

No, it's not. Or not with any degree of ease. The best you could hope for would be to intercept the USB data and try and decode it, but that really is beyond the ability of a lowly Arduino.
I have thousands of dollars worth of equipment aimed at doing that kind of thing - it's not a simple task.

Then is there any possibility to do this?

If you use some device that can sample a signal in the high tens of megahertz (which an Arduino has no hope of doing) then you may be able to capture a waveform and decode it. Not with an Arduino though.

What are those device which can sample the signal. can you name them

Microcontrollers that run in the hundreds of megahertz. FPGAs. CPLDs (maybe). I use a TotalPhase Beagle 480.


text:
Is it possible to extract a hex file via UART from an Arduino?
Right now I am tinkering on my 3D printer that has an Arduino mega as a brain. I need to update the Marlin firmware but in case of an error I want to create an backup of the firmware. And because it is assembled using a shield on top have no access to the ICSP interface. And I was curious if you can extract all the flash and EEPROM via USB (UART). If yes than what software should I use to do that.

AVRDUDE which is used by the IDE to send the content of HEX file from your computer, as a feature letting it to get back the data of the flash, in order to compare and see if data are correct.
For a UNO try:
avrdude -patmega328p -carduino -P/dev/cu.usbmodemFD121 -b115200 -U flash:r:"flash.bin":r

I think it would not be very hard to change that for a Mega.
It works fine. I have use that a lot to debut my "Android Updater" which allow the user of my board to update the code themselves.
PS: Just for info, you'll not get back the HEX file as in the flash, you have only some "pieces" of the HEX file.

When this works, you will in fact get back the contents of the flash. If you have doubts about it, do the process multiple times and diff the result, then examine the actual addresses capture in the hex file.

If you send the code via ISP using the .ino.hex from the Arduino IDE, rather than the ino.with_bootloader.hex, the result is that you will have the code but no more the bootloader. So in this case, you are not able to get back the data using AVRDUDE, of course.

Well, yes, but that has little to do with the question.  If you write with the bootloader and the board is properly configured, you won't loose the bootloader.

Not only is readback supported, avrdude depends on it in order to perform the default verify operation.

It looks like my other answer was completely wrong, so I've deleted it.

Yes, you can read back the flash using the USB interface, as Chris Stratton pointed out, and Peter mentioned in his answer.
The bootloader includes a "verify" action, which means it can be used to read the flash. If you connect up the USB cable to your Atmega2560 you can read the flash back by using a command similar to this:
/usr/local/bin/arduino-1.6.9/hardware/tools/avr/bin/avrdude  `# where avrdude is`  \
-patmega2560     `# chip type: atmega2560` \
-cstk500v2       `# protocol: stk500 v2` \
-P/dev/ttyACM2   `# what serial (hardware) port the board appears on` \
-b115200         `# baud rate` \
-U flash:r:"flash.hex":i   `# save flash as "flash.hex", in Intel format` \
-C /usr/local/bin/arduino-1.6.9/hardware/tools/avr/etc/avrdude.conf  # config file for avrdude

This was done under Linux, with the command in "bash" format, which means the comments look a little strange, as I had to do that to put a comment on each line.
I've put comments on each line to show what each parameter means.
If you happen to have avrdude in your path, or are in the directory where it is installed, the brief form of the command would be:
avrdude -patmega2560 -cstk500v2 -P/dev/ttyACM2 -b115200 -U flash:r:"flash.hex":i -C avrdude.conf

You will probably (almost certainly) have to change the path to where avrdude is, and where the configuration file for avrdude is. You will also need to find out the serial port that the board is on, which you can find out from the Arduino IDE (the Port menu will show you the possibilities).

As Chris Stratton suggests, do this a few times (change the file name of course) and compare the files (eg. using "diff"). If they are all the same then you can be reasonably confident that you have got good copies.

Yes, though it's not a "verify" action of the bootloader, it is explicitly a page read action.  It is avrdude which uses that generic capability to accomplish a verify.


text:
How do software interfaces compare to hardware interfaces in therms of speed and reliability?
The Arduino core includes numerous software interfaces mimicking the hardware interfaces provided by the chip and even extending beyond. My question is, if in a project I can either use software or hardware protocol, what would be the difference in stability, speed and versatility? Is there a reason why hardware interfaces are preferred? Because anyways the protocol is handled by the CPU or am I mistaking something?

the peripherals can work autonomous, involving the CPU over an interrupt only if needed. for example if you start a PWM the CPU is not involved in pulses generation. if you use external interrupt on pin, CPU is not involved in monitoring the pin.

In your question you ask about all communication interfaces in general, so the answer will be as general as your question.
Hardware interfaces should always be preferred to software interfaces, though there are situations, where it is a better or needed to use a software interface due to limited resources.

Because anyways the protocol is handled by the CPU

That is mostly wrong. The communication protocol is done by the hardware in most cases, if you use hardware interfaces. Serial (UART) for example automatically sends out the byte, that is placed in the hardware buffer, with the set configuration. It does not rely on any software for that. The same goes for SPI or I2C. The protocol of the interface is handled via hardware.
Though at least for Arduino Core/library users there is more to it, that get's handled automatically. Since the interface hardware is limited, the software have to take care of the resulting or needed data. For example: All the interfaces mentioned above use a 1 byte buffer for the data. The software must read or write this data, so that the hardware can work. If you don't read the byte of data, that was received by the Serial interface, it might get overwritten by the next byte. The hardware cannot provide a buffer, that is generally big enough, since the manufacturer cannot know, how long the transmissions will be. So the interfaces get a 1 byte buffer and the software has to do the rest. For this reason all the libraries use a bigger buffer in their software, that gets filled, when the hardware sends a corresponding interrupt.
So: Hardware interfaces implement the basic interface protocol (how the bits get transmitted) in hardware, thus the software only has to provide and read the byte data. The stability, speed and versatility is only determined by how the manufacturer build the hardware of that interface. This limit is clearly specified in the datasheet and does not change with the code.
For software interfaces, everything is done in software. This also involves monitoring and setting the corresponding pins with the correct timing. In the best case the software can utilize general hardware functions like a pin interrupt, but if it cannot do this, it has to constantly monitor (poll) the pins to receive something. Software interfaces are often called "bit banged", because the software manually pushes out each individual bit with the exact needed timing. That is a tedious task, which often blocks the execution of other code, since the timing often is critical. Especially the timing introduces limits, since doing things in software often involves many clock cycles more, than it could be done by dedicated hardware (consider all the code to poll a pin and the multiple if statements to react to specific situations). For example: When you write data with SoftwareSerial the call to the write function will block, because is manually pushes out bit after bit. Or with SPI: With hardware SPI you can go to incredible clock speeds in the MHz range. You won't every get near that with software, because the software simply cannot run this fast.
Note, that depending on the actual hardware of the used chip, a library may need to implement parts of the protocol in software. For example this is the case for using I2C on an ATtiny85, which does not have full I2C hardware support. Instead the USI (Universal Serial Interface) can be used to implement some functions of the protocol in hardware and the rest in software.
TL;DR

Hardware interfaces lift the heavy duty of handling the low level protocol (transmitting the bits by the needed standard) (which can be rather complex) from the software
The Software then only handles the byte data, not it's transmission
Translating complex protocols from dedicated hardware to software (bit banging the data through simple pins) imposes great limits on speed and reliability.

Using a hardware interface takes a lot of load from the CPU. Let's take an asynchronous serial interface for example.
With the UART built-in hardware you'll get parallel-serial conversion and back done in hardware. The CPU "just" needs to store the data to be sent in a register. The receiving part is handled completely by the hardware and the CPU "just" needs to look at the "received" flag before reading the data. Or it sets up an interrupt as callback.
If you use a software interface the CPU needs to convert the parallel data to serial with several instructions and, really important, needs to maintain a certain timing. For receiving this might be even harder because of the asynchronous nature of the protocol. A timer might be usable to clock the communication, for example by an interrupt, but this puts a lot of load on the CPU. Certain conditions might make this usage impossible, too.
Now you might think about the issues you mentioned:
Stability: If done correctly both approaches are equally stable, meant as reliable function. If you have more tasks to be done you might not be able to meet the requirements. This comes "earlier" with software interfaces than with hardware interfaces due to the higher load.
Speed: Hardware interfaces can be faster than software interfaces because the hardware is commonly clocked faster than what is possible by software which needs multiple instructions for one step. But speed is always a relative issue. There are libraries implementing USB1.1 via software, and the USB1.1 protocol is both fast and really complex.
Versatility: Software interfaces are more versatile because hardware interfaces are limited in their capabilities. If a hardware interface can't do what you need there is no way to make it do this. Software can do "anything" as long as the CPU has enough time and resources for this.
Hardware interfaces are preferred because they are simpler to use and commonly don't put hard requirements on your software architecture.

Re “Stability”: Note that software interfaces sometimes cut corners to simplify the implementation. A software UART will typically take a single sample of RX per bit, whereas the hardware UART would take at least three samples and do a majority vote. It is also not uncommon for a software UART to not check the stop bit, and for a software I2C to not support clock stretching. A hardware port also tends to deliver more consistent timings than a software one.

@EdgarBonet That's what I meant by "If done correctly..." ;-) A hardware UART might start the reception on the leading edge of the start bit, or use a clock of in example 16x. This may be realized in software by edge interrupts and a highly clocked timer interrupt, which is not purely software to be honest.


text:
Arduino and reading from multiple USB connections
I'm sending up a high-altitude balloon with an onboard Mighty Ohm Geiger Counter and some other sensors, all of which will be managed by an R Pi B+. I'll collect and store the data with the R Pi; all of that's fine.
In order to track and recover it, I'm using the HABDuino shield on an Arduino. It uses the APRS system and sends back short messages, giving the altitude, internal temp, my callsign, and coordinates. I'd like to add the Geiger counter's data to that, but I'll need to get it from the R Pi.
Currently, I'm using an FTDI Friend to connect the Gieger counter to the R Pi, and getting the data from the serial port. I see here that I can connect the Arduino and Pi vai USB, but... since there's already a USB connection to the Gieger counter, will there be a conflict? Is that something that I can work around?
Thanks for the help!

What is the point of having multiple connections to the same arduino? Just choose one, or the other.

Have you tried using a hub?

There would be two USB connections to the PI, rather than the Arduino. I can't use just the Pi because I need the hardware (it's an Arduino shield) for the tracking, and I can't use just the Arduino because the tracking shield takes up all of the resources.

What sort of hub?

Ummm... USB hub?

I'm voting to close this question as off-topic because this is about the Pi, not the Arduino.

Note you can also connect the Arduino to the pi's hardware serial UART, though if you are running your Arduino at 5v you will need level translation.

The FTDI should be showing up as /dev/ttyUSB0 on the Pi.
If you connect an Arduino as well it will show up as /dev/ttyACM0.
If you don't have enough USB sockets then just add a USB hub.


text:
What is Reverse Current through an Arduino?
Can someone explain (in a non-wiki technical way) what reverse current is through an Arduino ? Cheers y'all

It's current flowing "the wrong way".
The electronics inside the main chip are designed such that the + side (Vcc) must be at a significantly higher voltage than the - side (GND).  By significantly I mean 2.1-5.5V higher.
Because of that it is expected that the current will flow through the components in one direction (or in a couple of pre-determined directions depending on settings).  Any situation which causes a reversal of that current through the internals is bad, and as called "reverse current".
It could be caused by something as simple as connecting a power supply backwards, or more technical things like the "Back EMF" from an inductive load (motor, relay, etc) entering a pin that is an output and flowing backwards up to Vcc, or "Back Powering" where the chip is not powered but some external device connected to it is powered, and it "leeches" power backwards through IO pins to power the chip.
All of those situations are bad and should be avoided.

Many thanks for getting back. Other then checking my connections/jumpers are the right way round...how do I "spot the signs", test & prevent a reverse current in a circuit b4 "frying" my chips in the Arduino ?

Make sure all inductive loads have flyback diodes, and ensure that external circuitry is never powered without the Arduino powered.

Adding resistor between the arduino, and signals that might have a higher voltage than that of the arduino. This will help prevent to much current going through the clamping diodes (and break) inside the arduino chip. I can't find the specific value for the clamping diodes but I thinks it's around 1-2mA max.


text:
PIR motion sensor stuck in a loop
I've bought an HC-SR501-compliant PIR motion sensor (like this one) and connected it to a Teensy 3.1. The circuit seems fine, and the LED lights up. However, when nothing is moving in front of it, the sensor keeps reporting HIGH and LOW in suspiciously constant intervals. The monitor reads like this (numbers in milliseconds)
motion detected  4113
motion stopped   7234
motion detected  4114
motion stopped   7274
motion detected  4113
motion stopped   7204
motion detected  4111
motion stopped   7184

When it detects movement, it stays on the triggered position for longer, but even then goes back to predetermined intervals, e.g.
motion detected   4113
motion stopped   17204
motion detected   4111
motion stopped   41754
motion detected   4113

This is the sketch (as found on Adafruit):
int ledPin   = 13;              // choose the pin for the LED
int inputPin = 1;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val      = 0;               // variable for reading the pin status

unsigned long lastTime = millis();

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input

  Serial.begin(9600);
}

void loop(){
  unsigned long currentTime = millis();

  val = digitalRead(inputPin);   // read input value
  if (val == HIGH) {             // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    if (pirState == LOW) {

      // we have just turned on
      Serial.print("motion detected ");
      Serial.println(currentTime - lastTime);

      // We only want to print on the output change, not state
      pirState = HIGH;

      // Save time for measurement
      lastTime = currentTime;
    }
  } else {
    digitalWrite(ledPin, LOW); // turn LED OFF
    if (pirState == HIGH){

      // we have just turned off
      Serial.print("motion stopped ");
      Serial.println(currentTime - lastTime);

      // We only want to print on the output change, not state
      pirState = LOW;

      // Save time for measurement
      lastTime = currentTime;
    }
  }
}

Could this be a faulty device? I'm thinking about getting a new one for testing. While I can compensate for the gaps when triggered, I can't think of a way to make sure that it's not actually being triggered by this weird internal interval.

Try powering the PIR motion sensor with a higher voltage.  I get the same problem you're seeing when powering it with the 3.3v output of an Adafruit Huzzah ESP-12, but it works just fine when I power it with the 5v USB power.

From the Adafruit page:  "Runs on 5V-12V power (if you need to run it off of 3V you can do that by bypassing the regulator, but that means doing a bit of soldering)."  So powering it from the Teensy's 3.3V may be the problem.


text:
MicroSD interfering with ISP programming
I have a microSD connected to an Arduino and I can't program it over ISP without removing the SD card. Does anybody know how to prevent the SD card from interfering with the ISP programming?
Details:
This is the microSD breakout: https://www.adafruit.com/products/254
I'm using an ATMEGA328P at 3.3V 8MHz.
I'm not using a bootloader and, for several reasons, I can't use the serial port for programming.
Thanks!

Have you tried putting a 10k resistor from CS to +3.3V? What pin is CS tied to?

Because the SD card is an SPI device it shares the same pins as the ISP interface. The only way to not have the SD card interfere with the ISP is to not have the SD card connected.
As you have seen, that can be achieved by removing the card.
It can also be achieved by adding a tri-state buffer between the MCU and the card so the MCU only connects the card to the SPI bus when it is ready to use it - under default operation the card is disconnected.

Would you then need to disable the tristate buffer before programming the MCU?

The buffer would, if you wired it right, default to off when the MCU stops actively setting it to on.

This sounds great! Thanks for the tip. (Do you have any recommendations for what buffer I should use?)

You can also use the buffer as your level shifter as an added bonus. Look in the 74hc series for a quad tristate noninverting buffer.

You should not need to disconnect the card - provided programming is being done at a compatible voltage level, inactivating the card's chip select should be sufficient.  SPI devices are, after all, designed to share the SCK, MOSI, and MISO signals, and so should not drive MISO when they are not slave selected.

@ChrisStratton there are two flaws in that argument... 1: most cheap card shields lack a pull up on CS, so while you are programming the CS is floating. 2: SD cards aren't 100% SPI compatible. They have times where the CS is held high while being clocked. They are notorious for not always playing well with other devices on the bus - care has to be taken with them.

The poster isn't using a shield, but a PCB wired to something that appears to not be a complete Arduino, adding a resistor (at the wiring interface if nowhere else) is trivial (though it would be with a shield as well).  Many SPI devices can continue operation after the select returns high, that's quite different than their driving MISO when it has never, or at least not recently, been low.  What could make things tricky would be if the existing sketch kicks off an SPI operation that then gets interrupted by entering programming mode.  But your "the only way" opener seems inaccurate.

@ChrisStratton Yes, many (most) SPI devices keep running with CS raised. No other SPI devices require the clock to be run with CS raised. This is a fundamental difference between SD cards and true SPI devices that is known to cause problems in the field. And then of course you have the fuzziness of what constitutes the SD card SPI interface, implemented differently by different mfrs with many cheap Chinese mfrs cutting corners, etc. I have seen some SD cards that even never tri-state their MISO pin. As a general rule of thumb I always put SD cards on their own dedicated SPI channel.

That's useful detail - your answer would be a lot better if its actual body included this explanation of why you recommend handling an SD card uniquely, as opposed to as an ordinary SPI device.

I had the exact same problem, also using Arduino (Atmega 328P). I have an sd card module with a different layout, but also with a level shifter. My circuit is running at 5V (which is appropriate when using a level shifter).

To resolve the issue I just installed a pullup resistor (10k) on my own board to the chip select line of the sd module, which keeps the sd card unselected while programming the MCU. Now it works.

There seems to be no pullup integrated into the module. Hence the CS is low during programming (without the pullup), the sd card thinks it should answer the SPI commands, and so interferes with the communication to the MCU, which is why programming over an ISP fails.


text:
WiFiClient.connect() does fail all the time (ESP8266 Core for Arduino)
I have one ESP(1) opening an AP and running a server on it. The other ESP(2) is running a client on it and is connecting to the AP and after that trying to connect to the host server. The connection to the AP does succeed but the connection to the host always fails and I cannot figure out what the problem is here. Testing the server via netcat and packetsender works fine. Connecting to it via telnet fails because the connections gets closed by the "foreign host".
Server Sketch
#include <ESP8266WiFi.h>

const char* ssid = "artex11";
const char* pw = "getmenow11";
WiFiServer server(80);
WiFiClient client;

void setup() {
  Serial.begin(115200);
  //setup AP
  WiFi.softAP(ssid, pw);
  Serial.println("AP started at: ");
  Serial.print(WiFi.softAPIP());
  server.begin();
  Serial.println("Server started...");
}

void loop() {
  client = server.available();

  if(client){
    Serial.println("Client connected!");
    Serial.print("HasClient: ");
    Serial.println(server.hasClient());
    char message = client.read();
    Serial.printf("Message: %c\n", message);
  }
}

Client Sketch
#include <ESP8266WiFi.h>

const char* ssid = "artex11";
const char* pw = "getmenow11";
const char* host = "192.168.4.1";
const int port = 80;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, pw);
  Serial.println("Connecting to AP");
  while(WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
   }
  Serial.println(" connected");
}

void loop() {
  WiFiClient client;
  Serial.println("Connecting to host");
  if(!client.connect(host, port)){
    Serial.println("...connection failed!");
    Serial.println("Retrying in 5 seconds...");
    delay(5000);
    return;
  }
  client.print("A");
  Serial.println("...TCP message fired!");
  delay(2000);
}

In your Client sketch you are setting the IP address of your host to "192.168.4.1", but in your Server sketch you never set an IP address, so how do you expect the connection to be established?
There are multiple libraries for ESP8266, without clarifying which one you are using there is not much we can do about this...

This is the default IP. As I said connecting to this IP through telnet, netcat and packetsender works but no from the client ESP

And as I said, without knowing which library you are using we cannot help because in the library I was opening to solve your issue the default IP is 192.168.0.1.

The library is #include <ESP8266WiFi.h> isnt that visible through the sketch code? I'm gonna try to not rely on a default IP mybe that works.

That is an header file, not a library. The same header file is defined in at least 11 libraries I was able to find online...

https://github.com/esp8266/Arduino sorry this lib

The problem was this missing piece
WiFi.mode(WIFI_STA);
If omitted  it seems the WiFi is starting in Station & AP mode - so I was able to connect to the other AP but not to connect to the host because of reasons.

If the server has a default IP address of 192.168.0.1 and the client has an IP address of 192.168.4.1 my guess is they won't be able to talk because you are using a 24 bit mask.
The subnet mask defines the number of bits that makes up the subnet, so if you were using the two addresses above and had a mask of 255.255.255.0 or 24 bits then the subnets you were using would be 192.168.0 and 192.168.4.  To cross subnets you need some form of routing process (usually a router, switch that can route, etc).
So you need to either change the mask or, stick both devices on the same subnet.
(Don't rely on defaults, when they change your code breaks)

your reasoning is correct and possibly applicable, I'm commenting here just because you inverted the IP addresses of client and server... In the client firmware he is opening a connection toward192.168.4.1, so that's the expected server address... Also I don't think he ever sets the client address to 192.168.0.1, that was a statement from me, but I was probably looking at the wrong lib.

@RobertoLoGiacco - I wasn't awake, I've only just started work, I have to get 3 hours in before I can read :)

authors: ชิณท์ณภัทร ผลจันทร์


text:
how to get an unofficial WiFi Shield to work?
I just bought these two WiFi Shields -> http://www.ebay.de/itm/262525969091?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT
As they arrived I put one of them onto my Arduino Uno R3 and tried if my LED test sketch still works. It did.
After that I tried this WiFi tutorial (https://www.arduino.cc/en/Tutorial/ConnectWithWPA) to play around with the WiFi API a little bit. Sadly it prints to the serial monitor "WiFi shield not present" which tells me I missed something when setting up the shield.
I just thought the WiFi shield will be already usable without wiring anything. Surely that might be naive somehow, but hey I'm still a noob ;)
Can you guys tell me or simply point out a tutorial where it tells me what wiring I have to do to at least get pass this "WiFi shield not present" check?
Then I just realized that I do not have the "real" Arduino WiFi Shield and therefore the origin WiFi lib won't work for me according to this thread: http://forum.arduino.cc/index.php?topic=371362.0
Sadly I did not received any documenation on how to get this thing to work now. I found A LOT of threads about the "WiFi shield not present" error but none of them solved my specific problem with the shields I bought.

Somewhere it should say this: It is really really difficult to implement enough of the TCP/IP stack on an Uno to handle talking over the Ethernet.  In other words, the shield is doing almost all the work.  As such, if you don't have any documentation, using this Ethernet shield will be difficult.  That said, it looks like this shield is using an ESP8266 which IS widely documented. And if you search around, can even find people creating Arduino / ESP8266 software.


text:
Rfid is not working
I am making a rfid card cognition code to find out what id does my card have.
I used rfid-rc522 module. And I set the pins like this picture.

I'm using a genuine Arduino uno. and my code is this:
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN   9                            // reset핀은 9번으로 설정
#define SS_PIN    10                           // SS핀은 10번으로 설정
                                               // SS핀은 데이터를 주고받는 역할의 핀( SS = Slave Selector )

MFRC522 mfrc(SS_PIN, RST_PIN);                 // MFR522를 이용하기 위해 mfrc객체를 생성해 줍니다.

void setup(){
  Serial.begin(9600);                         // 시리얼 통신, 속도는 9600
  SPI.begin();                                // SPI 초기화
                                              // (SPI : 하나의 마스터와 다수의 SLAVE(종속적인 역활)간의 통신 방식)
  mfrc.PCD_Init();
}

void loop(){
  if ( !mfrc.PICC_IsNewCardPresent() || !mfrc.PICC_ReadCardSerial() ) {
                                               // 태그 접촉이 되지 않았을때 또는 ID가 읽혀지지 않았을때
    delay(500);                                // 0.5초 딜레이
    return;                                    // return
  }

  Serial.print("Card UID:");                  // 태그의 ID출력

  for (byte i = 0; i < 4; i++) {               // 태그의 ID출력하는 반복문.태그의 ID사이즈(4)까지
    Serial.print(mfrc.uid.uidByte[i]);        // mfrc.uid.uidByte[0] ~ mfrc.uid.uidByte[3]까지 출력
    Serial.print(" ");                        // id 사이의 간격 출력
  }
  Serial.println();
}

And I used library rfid-master which is in the github
So, when I try to get the card to the reader see video, it doesn't work like the video. What is the problem?

Can you read the key fob using the DumpInfo.ino sketch that came with the library?

This would be a good question if you explained a little more on what you expect to happen and what exactly isn't working.


text:
Arduino only supports 140 LEDs
I've a problem with an Arduino Uno board. It only supports 140 LEDs using the FastLED library. Any LED which is higher than that number can't be turned on or off using FastLED.
Is this related to the board, the library or any other  circumstances? And help or advice would be appreciated.

Did you read this https://github.com/FastLED/FastLED/issues/288

Maybe your code or inadequate power supply? We need more info.

Depending on how fast you need to go, the apa102-arduino library by Pololu doesn't seem to have a hard limit on their LED capacity.  They say the refresh rate goes down after 60 LEDs, but don't say anything about the maximum amount of LEDs you can have.
https://github.com/pololu/apa102-arduino
The max I'm doing at a time is only a string of 48, so I haven't checked how many it can update at once.  I am, however, running a total of 180 LEDs with this library, over 5 separate "channels".
To make it even a tiny bit harder, I'm doing it with a Nano.
This library has a "slow" and "fast" way to update the LEDs.  So far, the "slow" way is faster than the BlueTooth connection I'm sending data over to update the LEDs.
They state that the "fast" method is something like 20x faster than the "slow" way, but takes a little more in-depth programming.  Since the "slow" way works for me, so far, I haven't bothered trying the "fast" way.
Other option:
Talking with a friend at my local maker space, he said that it could be due to the speed of your board vs the timing of your LEDs. If your board isn't running fast enough, it can prevent the LEDs from being updated correctly after a certain amount of LEDs.
He was also saying that if you don't have enough available memory, it can affect how many LEDs you can update.
Seeing as you have an Arduino Uno, you shouldn't have a problem with speed or memory. Without knowing what else you are running on your Arduino (code, sensors, GPS, other shields, etc.), it's hard to say what could be holding you back.
My friend's son uses the FastLED library, so I'm going off other-than-first hand knowledge here.


text:
Help with multi function momentary buttons
I'm using the PunchThrough Bean and trying to build a two button project that has multiple functions. The idea is the user can press button 1 or button 2 for either short or long presses, or they can press both buttons simultaneously for a short or long press. This would give the user up to 6 different functions. Below is my code. I can get button 1 or button 2 press to work, but can't get pressing both to work. Also, I can't figure out how to have a function depending on how long a button sequence was pushed. Any help would be greatly appreciated.
const int btn0 = 2;
const int btn1 = 3;

void setup() {
  Bean.enableWakeOnConnect(true);
  Bean.enablePairingPin(true);
  BeanHid.enable();
  pinMode(btn0, INPUT_PULLUP);
  pinMode(btn1, INPUT_PULLUP);
}

void loop() {
  bool connected = Bean.getConnectionState();
  pinMode(btn0, INPUT_PULLUP);
  pinMode(btn1, INPUT_PULLUP);

  if (connected) {
    int btn0State = digitalRead(btn0);
    int btn1State = digitalRead(btn1);

    if ((btn0State == LOW) && (btn1State == HIGH)) {
      Bean.setLed(255, 0, 0);
      Serial.print("up");
      BeanHid.sendKey(KEY_UP_ARROW);
      Bean.sleep(500);
      Bean.setLed(0, 0, 0);
    }

    if ((btn1State == LOW) && (btn0State == HIGH)) {
      Bean.setLed(0, 255, 0);
      Serial.print("down");
      BeanHid.sendKey(KEY_DOWN_ARROW);
      Bean.sleep(500);
      Bean.setLed(0, 0, 0);
    }

    if ((btn1State == LOW) && (btn0State == LOW)) {
      Bean.setLed(0, 0, 255);
      Serial.print("right");
      BeanHid.sendKey(KEY_RIGHT_ARROW);
      Bean.sleep(500);
      Bean.setLed(0, 0, 0);
    }

  }
}

Don't act immediately when a button gets pressed, instead when a button is pushed all you do is set the timestamp on that button and set a flag.
Then when it is released or the time elapsed is large enough do the appropriate thing.
void loop(){
    int btn1State = digitalRead(btn1);
    static bool button1 = false;
    static unsigned long time1 = 0;

    if (btn0State == LOW && !button1) {
        button1 = true;
        time1 = millis();
    }

    if (btn0State == LOW && button1) {
        if(millis() - time1  > SHORT){
            //do long action
            time1 = millis(); //reset timer
        }
    }

    if (btn0State == HIGH && button1) {
        button1 = false;
        //do short action
    }

}

That would cause bad user experience. When a button has both a “short press” and a “long press” action, user expectation is that the “long press” action happens as soon as the press reaches the required duration, not when the button is released. Otherwise it would be, for the user, hard to know how long is long enough.

@EdgarBonet fixed the answer


text:
Arduino Obstacle Avoidance (Problem)
I am having a problem. I designed obstacle robot with ultrasonic sensor. But the problem i'm facing is one that no one discussed ever. I kept on searching it on internet and found no solution for it. So, i decided to ask it here:
Firstly, I used one ultrasonic sensor to avoid obstacle alongwith servo motor using newping library. But it failed badly due to an elevation of the sensor so it doesn't detect any lower height object.
Second time, i used three ultrasonic sensors to check for the side's obstacles and front obstacle as well. In most of the cases what no one ever showed in video there are some places and times when it get stuck (due to design and even sonar limitation).
What i want to do is to add some features to the code that can detect stuck motor or stopped robot at one place. Once detected this condition it moves backward and turn the other way if again stuck then move backward and turn the other way.
I hope i could make you understand the problem i'm facing. I'll appreciate the solution and it may help others to find solution for it. I don't know how to attach the code here (it may create mess for the reader). So, please tell me if i need to send or attach here. Thanks.!

you could add bump sensors(switches) so that it it bumps into an object, it can back up and turn the right way(depending on which sensor is hit).   Think about humans, how do we get around if we cant see?

hint: a robot will get stuck in some places because it always reacts the same way to a particular sensor input


text:
Arduino creating delay function
I am trying to make my own delay function. Briefly mydelay function is calling toggled function every secs seconds. The code is not well written, i know (this is the first version). But i am just trying to get it work properly. Then i will refactor it. But i have some unexpected bugs. First time the loop in x function is working properly. It is printing "I am in while" for 1 second and then it prints "Im ending mydelay" which is the behaviour i want. But after finishing the loop in x. The second time when it loops. It enters the mydelay function (that is ok). But then it is not printing "I am in while" at all. It just prints "Im ending mydelay" which is not good.
Here is the code:
#include <Arduino.h>
int led = 7;
void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  x();
  Serial.println("Im ending main loop");
}

void x() {
  for (int i = 0; i <= 10; i++) {
    mydelay(led, 0, 1);
    mydelay(led, 1, 1);
  }
}

void mydelay(int pin, int hol, int secs) {
  int starttime = millis();
  while ((millis() - starttime) <= (secs * 1000)) Serial.println("I am in while");
  toggled(pin, hol);
  Serial.println("Im ending mydelay");
}

void toggled(int pin, int hol) {
  digitalWrite(led, hol);
}

starttime should be unsigned long. 2) it is a bad idea to Serial.println() inside a tight loop: you will fill the output buffer and be slowed down by the prints.

You already asked this exact question on Stackoverflow.

As mentioned in the comments, your main problem is you declare starttime as an int. This is a signed value with a range of -32,768 to 32,767. You will quickly overflow - in about 32 seconds.
The solution is to use an unsigned long which has a range of 0 to 4,294,967,295.

Yeah,actually i asked the exactly the same question on stackoverflow.And got my answer.But anyways i appreciate the answer.

Btw,Isnt range of int on arduino 65536-1 ?

@MuhamedCicak That would be for unsigned int. Without specifying unsigned you get a signed int.

True... I forgot that,i am pretty new to C so yea.I am reading this K&R Book.I dont know if you know it.

You can try something along these lines:
void verboseDelay(unsigned long ms)
{
    unsigned long now = millis();
    Serial.print(F("delaying"));
    unsigned long start = now, lastPrintTime = now;
    do {
        now = millis();
        if (now - lastPrintTime >= 20) {
            Serial.write('.');
            lastPrintTime += 20;
        }
    } while (now - start < ms);
    Serial.println();
}

The trick is to used unsigned long for all the time-related variables,
and also to avoid printing too fast.