text:
Help with a rather specific implementation of FFT Library?
So, I guess what I'm trying to do here is properly understand the FFT library posted here by Open Music Labs, done in C++. I believe I understand the Fourier transform, but the FFT has some nuance that I'm not quite familiar with. From what I understand, the FFT takes a amplitude vs. time signal and transforms it into its constituent frequencies like a normal Fourier transform, but it only does so at given points that break down the signal into the Arduino's clock speed divided by the number of bins decided on, for the sake of efficiency. Thus each bin actually accounts for a number of frequencies that is also equal to the clock speed divided by bin number. I'm correct so far, right?
So here's my question. I have a very specific application of the FFT that requires reading only frequencies at roughly 0-100 Hz. Everything else I don't need, and I want to know how to achieve such high resolution. I imagine that because the number of bins seems to be capped at around 512, that there must be some sort of way to decrease the clock speed to an exorbitantly low number in order to read these frequencies. How might I go about doing that? Or maybe there is a better way to apply the transform to the data at such low frequencies through some other method outside of FFT?
Second, I'm wondering how performing multiple FFTs simultaneously will affect performance, and if there is some way I can export this data to another program in order to do the heavy lifting regarding data storage, seeing as I imagine performing many FFTs all at once will decimate the available memory on the Arduino itself if all of those values aren't being kept on my computer.
Thanks in advance for any insight you guys might be able to provide

You are mixing things. There is the “Fourier transform” (FT), the “discrete Fourier transform” (DFT) and the “fast Fourier transform” (FFT). DFT is a generalization of FT for finite sets of data points. FFT is an efficient algorithm for computing a DFT when the number of data points is a power of two. The binning is a feature of the DFT arising from the finite nature of your data set, it has nothing to do with efficiency. “0-100 Hz” is a frequency range, not a resolution. What resolution do you need?

As Edgar has mentioned you are confusing things slightly.
First there is your sampling frequency. According to the Shannon-Nyquist theorem that is at a minimum of 2x the maximum frequency in your signal. So that is 2x100 = 200Hz. That's the number of samples per second in your sample set.
Secondly is your sample size, which is directly related to the FFT bucket size. For every two samples you can get one bucket. The more samples you have the more buckets you have, and the higher the resolution each bucket is. But for FFT to work you need a power-of-two sized sample set. That means 2, 4, 8, 16 etc samples.  So 256 samples would give you 128 buckets. That would be a little under 1Hz per bucket.
To make things cleaner though you can back-apply the last calculation to the first and get them to match. 256 samples at 256 samples per second will give you 128 buckets covering 0-128Hz so 1Hz per bucket.  Double that to 512 samples and you get 256 buckets at 0.5Hz per bucket. Double it again and you get double the resolution again.
The main speed issue that you will come across is not the time taken to do the FFT, but the time taken to capture your sample set. 256 samples at 256 samples per secod will, of course, take 1 second to capture. 512 samples will be 2 seconds, etc. Far longer than a decent FFT takes to calculate.

Ok, that makes it a bit clearer. So, if I follow correctly, it seems like taking a half decent fft at such low frequencies is not a practicable option because increasing sampling rate will up the range of sampled frequencies, thus decreasing resolution, but if I leave it where it is at 256, then it would not be sampling fast enough to achieve a real-time readout. So it seems there has to be a better way to achieve the same effect of at least a 1hz resolution, because, as I understand it now, the Fourier transform is inherently limited for this application.


text:
Send HTTP get request from GSM SIM800c and Arduino
I am trying to send Get request from my GSM Module but after connecting to server it is not responding any thing
#include <SoftwareSerial.h>
SoftwareSerial myGsm(2,3);
void setup()
{
myGsm.begin(9600);
Serial.begin(9600);
delay(500);
myGsm.println("AT+CGATT=1");
delay(200);
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR,connection type is GPRS
delay(1000);
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"APN\",\"wap.mobilinkworld.com\"");//setting the APN,2nd parameter empty works for all networks
delay(5000);
printSerialData();
myGsm.println();
myGsm.println("AT+SAPBR=1,1");
delay(10000);
printSerialData();
myGsm.println();
myGsm.println("AT+SAPBR=2,1");
delay(10000);
printSerialData();
myGsm.println("AT+HTTPINIT");
delay(2000);
printSerialData();
myGsm.println("AT+HTTPPARA=\"URL\",\"http://sensor.somee.com/api/Data/GetData?SensorID=1\"");// setting the httppara,
delay(1000);
printSerialData();
myGsm.println();
delay(10000);//the delay is important if the return datas are very large, the time required longer.
printSerialData();
delay(9000);
printSerialData();
delay(1000);
Serial.println("done ");
printSerialData();
}
void loop()
{
}
void printSerialData()
{
while(myGsm.available()!=0)
Serial.write(myGsm.read());
}

and the Out put is
AT+CGATT=1

OK
AT+SAPBR=3,1,"CONTYPE","GPRS"

OK
AT+SAPBR=3,1,"APN","wap.mobilinkworld.com"

OK

AT+SAPBR=1,1

OK

AT+SAPBR=2,1

+SAPBR: 1,1,"10.209.122.68"

OK
AT+HTTPINIT

OK
AT+HTTPPARA="URL","http://sensor.somee.com/api/Data/GetData?Sen
done

Could you solve this problem?

You haven't instructed the module to make a request yet.
With the AT+HTTPPARA command, you are just configuring the request you want to make. In your case, you just specified the URL you want to call.
Next, you have to send
AT+HTTPACTION=1

to make the actual request using the HTTP GET method, and then you can read the HTTP response using
AT+HTTPREAD

Keep in mind that after AT+HTTPACTION you will receive an unsolicited result code in the format
+HTTPACTION: <Method>,<StatusCode>,<DataLen>

this will happen after the module will actually do the request and will have the response.

You should place the code to communicate (which is a recurring task) into the loop (and do this without blocking delay()s. Using delay stops the CPU so whatever comes to the buffer is probably not processed.
Read about the difference of placing code in the setup and the loop in the Arduino basic documentation.Never use delay in communiction scenarios (except for intializing hardware in setup) see example blinkwithoutdelay in ArduinoIDE

Calling webservice in a loop :| ?! What do you mean?

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:
RFID-RC522 not working, red led is on
I am working with RFID-RC522 and Arduino UNO. I have check pin configurations again and again tried different libraries. It is not reading card and red led on RC522 is consistently on.

Here's a picture of the card reader I have. If yours looks identical, then this library should work: https://github.com/ljos/MFRC522

The auth_read_write.ino sketch worked for me. Before you install the library, I recommend removing any other MFRC522 libraries from your arduino/library folder.
The only thing I did differently was used a 74HC4050 running at 3.3V between the Arduino and card reader. Some people claim you can connect the reader directly to the Arduino. I didn't want to take a chance of burning out the card reader so I used the 74HC4050.
Here's how I connected it:
Component markings and connections

|-------------------------------------------|
|   SPI    |  UNO  | 74HC4050  | RFID-RC522 |
|----------|-------|-----------|------------|
| SDA (SS) |  10   |     7     |            |
| SDA (SS) |       |     6     |    SDA     |
| SCK      |  13   |     5     |            |
| SCK      |       |     4     |    SCK     |
| MOSI     |  11   |     3     |            |
| MOSI     |       |     2     |    MOSI    |
| MISO     |  12   |           |    MISO    |
| IRQ      |  N/C  |    N/C    |    N/C     |
| GND      |  GND  | 8,9,11,14 |    GND     |
| RST      |   5   |           |    RST     |
| 3.3V     |       |     1     |    3.3V    |
|-------------------------------------------|

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


text:
Is my Arduino Ethernet Shield broken?
I have an Arduino setup from which I can control my RGB LED strip from my computer using LAN.
It worked like a charm in the start, but after two days, my Ethernet Shield W5100 for Arduino Uno stopped working, and I can't figure out why.
When I connect the Ethernet Shield, the red LED "pwr" is solid red and the "FULLD" flashes orange every second.
The setup:
I have followed an Adafruit guide, connecting the Arduino as such:
On top of the Arduino, I have the Ethernet Shield. All this is powered by an 12V/4A power supply connected to the Arduinos 2.1mm jack.
As I said, this setup worked fine for a few days. While it was on, I noticed the Arduino getting somewhat hot, but some google searches assured me that Arduino Uno can handle high temperatures, so I did not pay any attention to it.
The LED strip is not too long - about 2 meters with about 150 LEDs.
What I have tried:

When I detach the Arduino from my breadboard, the Ethernet Shield
will still not connect
I have tried connecting the Shield to another Power Supply (Computer USB) using another Arduino, but the Shield would still not connect.
I have added a debugging Serial.print message in the Arduino loop function. When using serial monitor, this message is printed over and over again (as if it is stuck in a reset loop)
I have verified for MAC address collisions, even changed the MAC address of the Shield multiple times.

Have I somehow burned the Ethernet Shield? Why won't it work anymore?

I'm sorry to tell you but i think you damaged your board severely that's because you took more energy from the pins than an arduino can handle.
150 LEDs takes way too much power for the arduino to handle as you can see here.
So you likely burnt something on your board and might have to replace it :/
make sure which board is damaged(the arduino itself or the shield) before replacing it.
If the ATmega328P(The chip on the arduino) is damaged then this should be an easy fix.
Instead of what you did, you shoud have powered the LED strip from another power supply(not from the arduino pins) and used the arduino to turn "this power supply" on and off(probably using transistors).

You are right. I should have an external power supply.
The Arduino seems to have survived it with no problems, although it got pretty hot. The ethernet shield however, is dead :(.
Thanks for the answer!


text:
Using multiple timers and avoiding conflicts
I would like to use three timers in CTC mode to launch three Interrupt Service Routines at different frequencies.
In this application I need to use the servo library, millis() and micros() functions.
Timer3 (Working)
Thanks to this question, Timer3 has been set up in the following way:
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count:  @~744 Hz
  OCR3A = 20;
  // turn on CTC mode:
  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  ISR(TIMER3_COMPB_vect)
  {
     cont++;
  }

Timer4
I've tried with this configuration:
cli();          // disable global interrupts
TCCR4A = 0;     // set entire TCCR3A register to 0
TCCR4B = 0;     // same for TCCR3B

// set compare match register to desired timer count: @ ~744 Hz
OCR4A = 20;
// turn on CTC mode:
TCCR4B |= (1 << WGM42);
// Set CS10 and CS12 bits for 1024 prescaler:
TCCR4B |= (1 << CS40) | (1 << CS42);
// enable timer compare interrupt:
TIMSK4 |= (1 << OCIE4B);
//TIMSK4 |= (1 << OCIE4A); same issue
// enable global interrupts:
sei();

ISR(TIMER4_COMPB_vect) //TIMER4_COMPA_vect same issue
{
  cont++;
}

But the compiler returns an error caused by the servo library conflict:

Servo\Servo.cpp.o: In function '__vector_42': C:\Program Files
  (x86)\Arduino\libraries\Servo/Servo.cpp:117: multiple definition of
  '__vector_42' Timer4B_800Hz.cpp.o:C:\Program Files
  (x86)\Arduino/Timer4B_800Hz.ino:49: first defined here c:/program
  files
  (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.3.2/../../../../avr/bin/ld.exe:
  Disabling relaxation: it will not work with multiple definitions

As Gerben suggested in a comment in this question:

They are just hogging all timers. I guess you have to alter the
  library slightly by removing the #define _useTimer3 line, or try
  putting a #undef _useTimer3 right after the include. –  Gerben

I would avoid changing the servo library since motors play a critcal role in the application.
Timer 5 Same issue
Which timers and output compare registers can I use to set up the three ISR correctly?

Whichever you like, as long as you're willing to dump the Servo library and do it by hand.

Is it the only solution? There must be another way to use these timers...

Have you tried the undef suggestion?

Related: Setting the frequency of a timer interrupt

The problem is the Servo library. This library is claiming all the timers, so you can't use them yourself. What I do to fix this is edit the Servo.h (or ServoTimers.h) file.
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
//#define _useTimer5
#define _useTimer1
#define _useTimer3
//#define _useTimer4
//typedef enum { _timer5, _timer1, _timer3, _timer4, _Nbr_16timers }   timer16_Sequence_t;
typedef enum { _timer1, _timer3, _Nbr_16timers } timer16_Sequence_t;

This will remove the 2 timers (4 and 5) for the Mega boards, but you can still attach 24 servo's. If you need more, you should edit this file again.


text:
How to test the sleep / enable function of Stepper Driver?
I am currently using an Arduino Mega 2560 to run this stepper motor driver (Big Easy Driver, ROB-11876 from sparkfun) https://www.sparkfun.com/products/11876.
I am trying to use the sleep or enable function on this chip to decrease the power consumption when I am not using the motor. I have all the rest of the driver working properly (steps, direction etc.) but when I hook up a wire to either the sleep or enable section and send a respective high or low it doesn't appear to do anything. (Chip works as normal, power consumption stays the same).
I have tested to see that the Arduino is outputting correctly and it seems to be. But other than this I'm kinda at a loss on what might be wrong.
Does anyone have any suggestions on why this might be or other things to test to try to narrow down the problem?

Found my answer from Sparkfun - see below

glad you were able to figure it out. When you are able to, please post it as an answer.

Since you should be able to add an answer now, can you add it as an answer?

Just for future reference if anyone needs it I got the following from SparkFun:
On the Big Easy Driver Board, the Step, Dir, Sleep, Reset, and the Microstep pins are all >pulled high with 20kΩ resistors, while Enable is pulled low with the same. So sleep is >disabled (until explicitly enabled) and the stepper is enabled (until explicitly disabled).
For much of the use of this board, there is no real need to adjust these settings, but If you >want to achieve a low-power state you would pull the sleep pin low. This should disable much >of the internal circuitry on the IC. In order to reduce power, Enable should be pulled high >to disable the output FETs.
To test that the sleep function is working on the chip you can just jump it to low (ground). For me it turned out to be an error with the Arduino code rather than the chip. Here is also a good reference about pull-down / pull-up resistors. http://www.bit-101.com/blog/?p=3813


text:
To connect a simple toy circuit and trigger with an arduino?
I have a small circuit from a toy sword that has an LED and a small speaker. It was powered by a couple of small coin cells.
I am trying to figure out how to connect it to my Arduino so I can trigger it.
If I attached the circuit directly to the GND and +3.3V and press the switch in it I get the sound of a sword and flashing LED as desired.
Now I want to somehow get the Arduino to trigger the circuit but am very new to Arduino and quite unsure of how to approach this.
Can anyone advise how best to work with an existing low power circuit that can use the Arduino's power rails but needs the switch integrated?
Sorry for the noob question.

You'll probably want to use a transistor to switch it on/off. You could just use the Arduino's digital pin but they can only supply a limited amount of current. Transistors can work with larger currents. The Arduino switches the transistor and it powers the external circuit.
There are a couple of existing questions that may help you.

How to switch an external circuit with Arduino?
How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino?

jippie's answer in the first link shows an example schematic for hooking up a transistor with a bunch of LEDs but you would replace them with your own circuit:

Thanks for this. I had been looking at this diagram earlier when trying to figure this out. In this diagram do you think I could just use the GND and +3.3V pins as the external circuits power supply?

It looks like the DC current for 3.3 pin is 50mA. If your circuit requires less than that, it should be okay.


text:
DC-DC converter with Arduino not working
I've got a program running on the Arduino that is supposed to turn on and off a pump.  currently, I am outputting the reads of the components that need to be read and it shows when the port (port 13) is supposed to turn on and when it's supposed to turn off.  When I use a multimeter between the port 13 and ground, everything works as expected.
When I start the program and the port is off, I get a reading of 0.03v @20v max (to be more precise, I get 14.0 at 200mV) - Shouldn't this be zero? or is there always going to be some electricity flowing?
When the port is turned on: digitalWrite(airPump, HIGH); (and yes, airPump is set to 13), the voltage reads between 4.0 and 4.51 with spikes down to 3.65 on my multimeter set at 20v max.  is it ever stable? (pictured below)

So, the main question is: I'm supposed to be sending the power from port 13 to a DC-DC converter.  I tested the converter on a separate bread board just by itself.  I used a DC power supply and set it to 4.5v, then ran the power through the vIn, grounded the ground pin and ran the vOut to the multimeter (then to ground with the multimeter) and I got it set to output only 2.5v with a constant 4.5 running into it. (pictured below)

I also tested whether or not changing the voltage input would change the output at all and it seems it does not, from 1.5-15v, the converter stays steady at 2.5v
Now when I do the exact same set up on the arduino with the power from port 13 running into the voltage in on the DC-DC converter, it gives me a reading of 0.01v.  Any idea why this is happening?

I've checked probably over 30 times and rearranged everything just as many, but nothing seems to help.  I can't get a stable 2.5V output from the converter with the arduino...
UPDATE: Below is a simple wiring diagram:

The image shows what it is supposed to do, but for testing purposes I made it so if the rH is higher than average (I just breath on it) then the pump will turn on.

Are you connecting the output pin of the Arduino directly to the input of the DC-DC converter? A circuit diagram will help.

I am (through a breadboard) The output pin 13 goes directly to the DC-DC converter voltage in.  Is there a good, free place to do diagrams with components like these?

@Craig Diagram updated.

The arduino output pin cannot provide enough current to drive the pump. The DC-DC converter is not designed for this use.
You need external power supply with enough current to drive the motor that you switch on and off with the arduino output pin.
Search for "Arduino 3V DC motor control" for examples of how to do this, there are many options.

Or use a high-side load switch.

Hmm, That's strange, when I read the multimeter it shows it's driving enough voltage, though not consistent.  So I will need to use the arduino just to turn a switch on from a power supply to the pump? I will look into this.  Thank you - I will also look into a high-side load switch.


text:
Looking for a protocol, any hints?
I am looking for a multi-purpose wire protocol for Arduino.
Requirements:

Range of at least 500ft (200m)
No shield required
Able to communicate between Arduino and Raspberry Pi
Be able to run "point-to-multipoint"

Are you looking for hardware or software recommendations?

To quote my tag: "Hardware".

What do you mean by "No shield required"? Do you mean no extra electronics on the Arduino?

Yeah, no extra electronics.

So you want hardware, but you don't want electronics?

There is nothing that will work given those constraints.
You only have low power 5V signals on the Arduino which won't handle your distance requirements.
You could look into RS-485 using a shield on the arduino side and a breakout board on the Raspberry Pi.


text:
MySQL Connector/Arduino issues - not connecting
So I was going to make a project with the MySQL Connector/Arduino; a temperature log. I started out by experimenting with the example code from the website linked above. Not once did I manage to actually connect to the server; the mysql_connect() function always returns false. After several hours of intense googling, innumerable irritated noises and more, I decided to ask here on Stack Exchange.
Here is my current code:
#include "SPI.h"
#include "Ethernet.h"
#include "sha1.h"
#include "mysql.h"

byte mac_addr[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x69, 0xAC };
byte ip_addr[] = { 192, 168, 10, 127 };
byte dns_addr[] = { 192, 168, 10, 1 };
byte gateway_addr[] = { 192, 168, 10, 1 };
byte netmask[] = { 255, 255, 255, 0 };
IPAddress server_addr(192, 168, 2, 100);

Connector my_conn; // The Connector/Arduino reference

char user[] = "";
char password[] = ""; //the credentials are correct in my code
char INSERT_SQL[] = "INSERT INTO test_arduino.hello VALUES ('Hello, MySQL!');";

void setup() {
  Serial.begin(115200);
  Ethernet.begin(mac_addr, ip_addr, dns_addr, gateway_addr, netmask);     //Yes, I know this is way more than necessary, but just to play it safe
  delay(1000);
  Serial.print("IP: ");
  Serial.println(Ethernet.localIP()); // debugging
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password)) //connect to database
  {
     delay(500);
     my_conn.cmd_query(INSERT_SQL);
     Serial.println("Query Success!");
  }
  else
    Serial.println("Connection failed.");
}

void loop() {
}

Any help is greatly appreciated.
Rasmus
EDIT: Looks like I'm not even getting through to reaching the server and attempting to log in. I enabled the general query logs, yet I get nothing when trying to connect. Also, I can ping both the Arduino and the MySQL server from this computer. I guess that rules out a faulty shield and network setup.

Can the gateway machine communicate with the server?

Yes, it can. I can also ping it from this computer which is also in the 192.168.10.x net.

Can you ping from the Uno to the server? aka from 192.168.10.127 to 192.168.2.100? Are you sure that port 3306 is not being blocked by the gateway (aka not ping, but login using 'this' computer or similar at 192.168.10.x)?

Sorry for the delay. Port 3306 is not being blocked. I'll start looking into pinging from the Arduino, but it should be the same because the Arduino and my laptop ('this' computer) are in the 192.168.10.x net.

Update: I most certainly can ping the server from the Arduino. I'll start looking at Windows MySQL clients to try it out.

Can you telnet from the Arduino?
telnet  3306
Anything come of that?


text:
Why is this variable giving me always the value of 0?
I am doing a project and here is the code that I am using, but I do not know why the values of duration and sofia is always 0 so the values of distance and monroy are also 0
const int trigPin = 9;
const int echoPin = 10;

const int t = 8;
const int e = 7;

long duration, sofia;
int distance, monroy;
void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  pinMode(t, OUTPUT);
  pinMode (e, INPUT);
  Serial.begin(9600); // Starts the serial communication
}
void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  digitalWrite (t, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  digitalWrite (t, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  digitalWrite (t, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  sofia = pulseIn(e, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2;
  monroy = sofia * 0.034 / 2;
  Serial.print(duration);
  if (distance = 15);
  {
    digitalWrite (3, HIGH);
    delay (5000);
    digitalWrite (3, LOW);
  }

  if ((monroy >= 0) && (monroy <= 5));
  {
    digitalWrite (4, HIGH);
    digitalWrite (5, LOW);
    digitalWrite (6, LOW);
  }
  if ((monroy >= 5.1) && (monroy <= 9));
  {

    digitalWrite (5, HIGH);
    digitalWrite (6, LOW);
  }
  if (monroy >= 9.1);
  {

    digitalWrite (5, LOW);
    digitalWrite (6, HIGH);
  }
}

do you have the Arduino connected to anything?

My Arduino is connected to my laptop

What do you have connected to pins 9 and 10 of your Arduino? You might find this post on our meta site helpful: How to ask a good question for Arduino Stack Exchange

In the 9th and 10th pins I have the echo and trig pins connected. Thanks!

Please do a Serial.print of sofia so we can see what value is being used for the subsequent calculation.

when i write Serial.print(sofia) it always prints 0

It looks like it is timing out after one second, in that case. See: https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/

What is connected to pin 7?

When I formatted your code for readability and then compiled it I got these warnings:
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino: In function 'void loop()':
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:34:20: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
   if (distance = 15);
                    ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:34:21: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if (distance = 15);
                     ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:41:38: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if ((monroy >= 0) && (monroy <= 5));
                                      ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:47:40: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if ((monroy >= 5.1) && (monroy <= 9));
                                        ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:53:21: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if (monroy >= 9.1);

These are important - you should pay attention to them. For example, here:
  if (distance = 15);  // <-- NO SEMICOLON NEEDED HERE!
  {
    digitalWrite (3, HIGH);
    delay (5000);
    digitalWrite (3, LOW);
  }

Putting a semicolon there means that stuff under the if is always executed - the semicolon terminates the scope of the if.

To see the warnings open the Preferences dialog in the IDE GUI and change "Compiler warnings" to "All".

Also:
  if (distance = 15);

This assigns 15 to distance, so distance will always be 15. You mean:
  if (distance == 15)


text:
How to declare a Dynamic Array?
I want to define an unknown size for an array. However, I know that this cannot be done on the arduino. So what other methods do you suggest? I tried using vectors by downloading the library ArduinoSTL, but it doesnt work. (It only prints Serial.println(Signal); once, referring to the code in the pastebin link below)
Here's my code with vectors:
#include <ArduinoSTL.h>
#define sensor1 A0

using namespace std;

int Signal;
int Threshold = 550;

vector<int> startTime;
vector<int> endTime;
unsigned long measureTime;

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

void loop()
{
  //Serial.println(analogRead(sensor1));
  int i = 0;
  measureTime = millis();

  while ((millis() - measureTime) < 10000)
  {
    Signal = analogRead(sensor1);
    Serial.println(Signal);
    if (Signal < Threshold)
    {
      startTime.at(i) = millis();
      Serial.println("1");
    }
    if (Signal > Threshold)
    {
      endTime.at(i) = millis();
      Serial.println("2");
    }
    i++;
  }
}

unknown size? the size of the MCU RAM is known and there are no concurrent programs,  so declare a maximum possible array and you are good to go

The vector is empty after its default constructor. And nothing was ever added into it in your code. So you can't use anything like idexing by vect[index] or method vect.at(index). And as there are no exceptions available, who knows what it does after the out of range call.
You should consider ring buffer instead, using dynamic memory is tricky on such constrained platforms. Even using Arduino's String class is often source of memory fragmentation and out of memory type errors.

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


text:
Arduino won't send serial data if connected with external power supply
I am trying to make a connection between 2 Arduino's with the APC220 rf modules.
void setup() {
    Serial.begin(9600);
}

void loop() {
   int value = 5;
   Serial.println(value);
   delay(1000);
}

I uploaded this code to my Arduino Nano and Uno. I disconnected the rf modules for uploading the code.
I tried to run this program with an external power source (lipo 11.1V 2200mAh).
The Arduino is powered on(power led is on) BUT the tx led doesn't blink.
The only way to make it work is by using the usb and opening the serial monitor on my pc.
I tried to use a 10k resistor between tx and rx (or rx to ground) but the code won't run...
Can someone help me?
Solution : the arduino worked perfect. When you connect the arduino with an exernal power supply the tx and rx lights won't light up, Even when they are transmitting or receiving.

You'll want to add your solution as an answer and select it. Also, the TX and RX LEDs are generally only for the USB connection, which includes the serial monitor.

your Arduino's has to have common ground also.

Is it an official arduino board? Which type?

Solution : The Arduino worked perfectly. When you connect the Arduino with an external power supply the Tx and Rx lights won't light up, Even when they are transmitting or receiving.

I'm adding this as the solution to stop this being re-added as an unsolved problem.

That is correct. The Tx and Rx LEDs are connected to the Atmega16U2 processor, and thus only flash if there is serial comms via USB.

I think tx not activated without available serial connection. What is you rf module and what is the baud rate of RF module. Also can you share connection diagram or a test video. Alternativeliy you can look SoftwareSerial: http://www.arduino.cc/en/Reference/SoftwareSerial

I set the baudrate of both the apc220's to 9600 with rf magic. I don't want to use software serial because I need the storage space of the tx and rx.


text:
Problem uploading program to Atmega 328 microcontroller
I recently bought a Atmel Atmega 328 P-PU microcontroller.I tried uploading a program to it by using the circuitry given in the link.I am using a RS 232 breakout board.Here is the link http://www.arduino.cc/en/Main/Standalone .I am not able to upload programs to it.It says problem uploading to board or avrdude attempt 1 out of 10 failed.What can I do about it?

the uploader is a usb to uart bridge

Did you install the bootloader first?

Additionally, if you wired ATmega pins directly to RS232 levels without level translation, your chip may be damaged.   You can buy a replacement with a bootloader preinstalled at a small premium, or use another Arduino or a programmer or even some other development board to load the bootloader into a good chip.

It is a pre bootloaded chip

You never described the problem.

Which RS232 breakout board are you using and how have your connected it between your PC and the Atmega chip?

The problem has been solved by pressing the reset button at the right time.I must have added a 100nf capacitor there.(between DTR and reset)


text:
Pinout of Arduino 9 Axes Motion Shield
I bought an Arduino 9 Axes Motion Shield without looking at the pinout. I'm worried it won't work with my Adafruit Motor Shield v1.
It seems the 9 axes shield uses I2C, a reset pin and several other pins for the TinkerKit Input, Output and TWI connectors. Does anyone have a list of specific ports used by the shield on the Arduino UNO?
It also seems that my Arduino UNO r1 only has the original analog pins for I2C, while the 9 axes shield uses the new pins next to the digital pins.
update: I asked support from arduino.org on twitter and on their forums, no reply yet and it seems their twitter account has been suspended. Should have bought a Genuino I guess.


text:
How do I use a 3 legged phototransistor?
I have searched the Internet and found the following circuit to use with my phototransistor but it is not working, I can say so because all analog input i get is 1023 even if i have covered it totally, I have include the phototransistor and the diagram can anyone tell why is it not working!
I used this webpage to check my sensor and it works-I used this page
I have used 10kohm resistor.

This is my phototransistor

I have used a 10kohm resistor

What is your infra-red light source?  That PTX won't respond well to ambient light.

halogen lamp and tv remote both @Majenko

Showing just the relevant portion of your image makes it MUCH easier to view

Thanks Russell @RussellMcMahon do You have any idea about this problem, also I got new info when i made the test circuit as said by this webpage - https://learn.adafruit.com/ir-sensor/testing-an-ir-sensor it works fine

That's not a phototransistor. Phototransistors do not have a "supply voltage" or a "work frequency".

It happens to be an IR phototransistor @IgnacioVazquez-Abrams

It may contain a phototransistor, but it is not a phototransistor.

@IgnacioVazquez-Abrams the same phototransistor so called ir sensor is available at adafruit, so it is basically phototransistor which has a peak sensitivity of Infrared spectrum -http://www.adafruit.com/product/157

You can also check the data sheet below and will you pls care to look at my previous question and maybe tell me an answer. Thanks! @IgnacioVazquez-Abrams

I'm okay with people looking at you sideways with big question marks over their heads, so feel free to believe that you have a phototransistor.

Let us continue this discussion in chat.

@IgnacioVazquez-Abrams The website says so and also I use codes for phototransistor and its working is same and is is doing same thing that a phototransistor is supposed to be

First that is not even a photo resistor 2nd you have to put one wire positive and the other negitive and the last one plug it into any other gpio pin

A reasonably generic data sheet is HERE
That is for an AT156 but yours may be an AT138/HT138 based on an ad some years ago from the same seller when they said they had 10,000 for sale.
Basic information here and more in the data sheet.

Following the same guide I am now able to decode my remote signals, though thanks for your effort


text:
How to store values inside an empty array and get the average integer? [UPDATED QUESTION]
Goodafternoon,
I want to read values form a microphone (Adafruit MAX9814) connected to the Analog port A0 from Arduino and store the values that are incoming inside an array.
After the values are stored in the array, I want to read out the values and store the number that is repeated most time in a variable. Is this possible and how to achieve this?
I came up with the following:
const int micPin = A0;
int soundArray[10];

void setup() {

  Serial.begin(9600);
  pinMode(micPin, INPUT);

}

void loop() {

  int micValue = analogRead(micPin);
  Serial.println(micValue, DEC);
  //delay(400);

  for (int i = 0; i > 10; i++) {
    soundArray[i] = micValue;
    Serial.println(soundArray[i]);
  }
  delay(1000);
  Serial.println("End of for loop");

}

The problem now is that a value of the microphone will be repeated 10 times. So I will receive 10 times the number 234 for example. See image.
This is not what I want. I want to get different numbers in the array of that moment.

Hope someone can help me out.
Thanks in advance.

I have a library that does what you want: https://github.com/MajenkoLibraries/Average

Since you do not change micValue, soundArray[i] = micValue is always storing the same number. You probably mean soundArray[i] = analogRead(micPin).

I'm guessing that the code you posted is not copied from your sketch as the for loop will do nothing.  You initialise i to zero then only run the loop whilst i is greater than 10, which it will never be...

The error message is correct. You did not define the size of the array.
You have 3 choices:

Declare it with a constant length
int foo[10];
Declare it and initalize it
int foo[] = {0,1,2,3,4,5,6,7,8,9};
Declare it dynamic as pointer and alloc or realloc the mem by yourself (this is not recommended (realloc) because of possible heap memory fragmentation)
int foo;
int size = 10;
foo = (int)malloc(size * sizeof(int));
free(foo);

As reference:
http://www.arduino.cc/en/pmwiki.php?n=Reference/Array

Ah oke, I understand it. And the third point is to calculate the average?

Add the values together, then divide by the number of values. Simple junior school math.

Maybe I am not asked it right. The values from the analog port will be stored in the array. Then I want to get the number that is repeated most time.. So when I get an array with: (1,2,1,4,5,2,1,3) the number 1 is repeated most type and that one I will store in another variable for example valMost.

Ah, the operation then is called "mode".  My Average library (pointed to above) will do mode() for you.

I will check your code @Majenko. Check also my updated answer so there will be no mistakes!

There are three main sorts of "average" used normally in Maths:

Mean: This is the most common meaning of Average. It is the mathematical average of all the values in the set - the sum of all the values divided by the number of values.
Mode: This is the "most common" value in a set of values.  For the set {1, 2, 3, 4, 3, 5, 3, 1, 7, 3} the "mode" would be 3 since there are more 3's than any other number.
Median: This is the middle value of a set of values.  If there are 5 values and they are sorted into ascending order the "median" would be the third (middle) value.

By your comments it sounds like "mode" is what you are after - the most common number in your set of values.
It's quite easy to work out which is the most common number in a set if you are willing to loop through that set enough times.
I have an Average library that can do it for you.  The main part of the mode() function of that library looks like this:
most = _store[0];
mostcount = 1;
for(pos = 0; pos < _count; pos++) {
    current = _store[pos];
    currentcount = 0;
    for(inner = pos + 1; inner < _count; inner++) {
        if(_store[inner] == current) {
            currentcount++;
        }
    }
    if(currentcount > mostcount) {
        most = current;
        mostcount = currentcount;
    }
    // If we have less array slices left than the current
    // maximum count, then there is no room left to find
    // a bigger count.  We have finished early and we can
    // go home.
    if(_count - pos < mostcount) {
        break;
    }
}
return most;

Basically two loops, one inside the other.  The outer one steps through each number, and the inner one counts the number of times than number appears in the set (actually just from the current outer loop position to the end of the set - no point in counting numbers we've already looked at).  If the count is greater than the current "mode" count then store that as the "mode" count and also store the value as the "mode" value.  Move on to the next number.
To use the Average library it's quite simple:
const int micPin = A0;

// We want to be able to store 10 int values here.
Average <int>sounds(10);

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

void loop() {
    // Push 10 values into the Average buffer.  Any old values will drop
    // off the bottom.
    for (int i = 0; i < 10; i++) {
        sounds.push(analogRead(micPin));
    }
    Serial.print("Mode value is: ");
    Serial.println(sounds.mode());
    delay(1000);
}


text:
Is it possible to use two encoders with Arduino Uno?
I would like to control 2 motors with the Arduino Uno board, which provides only two interrupt pins on digital 2 and 3.
I've set one encoder using these pins, and it works. What do you think about the following approaches:

Timer Interrupt:

Create a Timer Interrupt.
Connect the seconder encoder to an analog pin.
Set an analog read function in the interrupt service routine.
Change the prescaler of the ADC and increase the acquisition time.

PinChangeInt

Use PinChangeInt to capture the pin change interrupt rather than an external interrupt.

This should allow you to use almost any I/O pins on the Uno for the
  encoder.
as Ignacio Vazquez-Abrams suggested here

Just go with the PinChangeInterrupts solution. There are some libraries for it if you want. I don't get the timer or analog read solution.

Just to check the state of the pin as fast and precise as possible but they suggested to check it with a normal digital pin.


text:
SIM900 + GPS Module making http rest calls
I am wondering if its possible to program a board that is developed using SIM900 and GPS module to make http rest calls.
I found this library. My question is, will I need a microcontroller for this ?

I partially agree to Anonymous Penguin's answer.
But if you want go for a deep dive, actually SIM900 / SIM800 GSM modules also have a facility called Embedded AT. Just Google it using "SIM900 Embedded AT". They have a pdf here at the time of writing this.
According to this application note, SIM900 is actually ARM core and using Embedded AT you can utilize most of things you do in External MCU. So if you are thinking of some application, which can be developed into SIM900, Yes you can avoid using external MCU. You can give AT Commands from your application to SIM900 core using API. You even get 1 UART to interface GPS chip with SIM900. If you move to SIM800 family they have more UARTs.
PS: I haven't used it.

My question is, will I need a microcontroller for this ?

Yes. There are certain things that you need a "man in the middle" to control. Without a microcontroller, how will you tell it what site to visit? How often to send the HTTP request? How to format the HTTP request? Is there any other thing you need this to do?
People often hope that they can hook up two complex devices that are almost setup to be slaves (like shields, sensors, and outputs) to a microprocessor. Unless the two were specifically designed to work together (or they use a standard, very specific protocol), your chances of building this without a microchip is like trying to build a skyscraper with popsicle sticks. It's possible, but there are cheaper and much easier/more efficient ways to doing that.
Well, they're both SPI/I2C/UART/USB/Serial! Why not? Well, although we're all humans and we use verbal communication as a protocol, do we all understand each other? Not really... For those protocols, they're designed to have a "master" and a "slave." A master would be powerful and have control over all the slaves. Hooking a GSM and GPS shield together is like hooking two slave devices together. It's not going to work out (unless you're aiming for blue smoke...)
tl;dr: you trying to mix two things that don't mix. Buy an Arduino Nano clone for $8 and have your circuit actually work.

Going by the cost of Arduino, I am getting inclined to go for SIM900 boards.

@Siddharth does the SIM900 have a MCU that you can program?


text:
Reading Ground/Open signal wire combonations to power specific LED's - Can it be done?
This might be a super easy question to answer. I ordered an Arduino Uno anyways for the sole purpose to understand this. Would not mind getting a jump on things before it's here.
I would like to setup the Arduino Uno to be used as a gear indicator for GM transmissions (specifically right now the GM 4l60e). Below is how it currently tells the computer/cluster what gear it's in.
This uses a range switch. Basically it's a combination of 4 wires that are grounded (low) in a specific order, the computer reads it, and displays what gear the transmission is in. There are 4 signal wires - Signal A,B,C, and P. Below is how the range switch signals it:
Park    - A=low,  B=open, C=open, P=low
Reverse - A=low,  B=low,  C=open, P=open
Neutral - A=open, B=low,  C=open, P=low
OverDrv - A=open, B=low,  C=low,  P=open
Drive 3 - A=low,  B=low,  C=low,  P=low
Drive 2 - A=low,  B=open, C=low,  P=open
Drive 1 - A=open, B=open, C=low,  P=low

I am wondering what would be the best way to go about this? The Arduino would be powered on by ignition. Display would be an LED (9-12V) output from the Arduino to each gear on a floor mount shifter. Total of 7 LEDs.
Hopefully this is easy to understand what I am trying to do. Thanks!

Could you clarify what you want the output to be - is it 7 single LEDs, so exactly one will be on at once? Or perhaps you're not asking about the output - just how to read the input..?

Yup, sorry about that.
7 single, different LED's representing a gear would be the output.
The main question being is it possible for the Arduino to intake 4 wires that could be ground or open at any instance and take that info and make an output to power an LED representing the combination (listed above).

First of all, Arduino is a 5V device, as such to drive the 9-12V LED you will need to use one or more transistors (depending on the LEDs type, number and connection, in series or in parallel).
Also, powering the Arduino from a 9-12V is not the best option: Arduino Uno has an onboard voltage regulator, but goes up to 9V maximum and, unless you go for the original one or a reputable manufacturer (Arduino is an open source project) I wouldn't go above 6V, because non-reputable manufacturers tend to use lower specs devices, like regulators which can get too hot when powered with high voltage: consider that the regulator will have to dissipate any excess energy into heat.
Said that, and knowing nothing more than what you said about the transmission you are describing, I assume the status open stands for open collector, meaning that it is not going to draw any current, so the following circuit is what you should use:

simulate this circuit – Schematic created using CircuitLab
The diagram assumes you are using digital pins 5 to 8 of your Arduino in INPUT mode and the Arduino GND is at the same voltage level as the transmission: this might be a big assumption, depending on how you power your Arduino (not from a battery pack, to be clear).
When node A is in open state, the voltage on Arduino pin 5 will be 5V, or HIGH as Arduino reports it. When node A is in low state then the voltage on Arduino pin 5 will be 0V, or LOW in Arduino lingo.
Resistors from R1 to R4 are there to limit current drawn when the gearbox is in state low.
UPDATE: I'm assuming the gearbox shares the same ground and operates at 5V,a s the Arduino does. If that's not he case and the gearbox operates at an higher voltage or does not share the same ground, the circuit will not work and you risk damaging the Arduino and/or the gearbox.
You can find a simulation of the above circuit where you can play with the different pins here.
The same occurs for the other pins, so your code will have to scan the 4 pins for their state and update your display accordingly, like:
#define PIN_A 5
#define PIN_B 6
#define PIN_C 7
#define PIN_P 8

void setup() {
  pinMode(PIN_A, INPUT);
  pinMode(PIN_B, INPUT);
  pinMode(PIN_C, INPUT);
  pinMode(PIN_P, INPUT);
}

#define PARK 0;
#define DRIVE_1 1;
#define DRIVE_2 2;
#define DRIVE_3 3;
#define OVER_DRIVE 4;
#define REVERSE 5;
#define NEUTRAL 99;
#define UNDEFINED 255;

unsigned int gear = UNDEFINED;
void loop() {
    bool A = digitalRead(PIN_A);
    bool B = digitalRead(PIN_B);
    bool C = digitalRead(PIN_C);
    bool P = digitalRead(PIN_P);

    if (!A && B && C && !P) {
      // Park - A=low, B=open, C=open, P=low
      gear = PARK;
    } else if (!A && !B && C && P) {
      // Reverse - A=low, B=low, C=open, P=open
      gear = REVERSE;
    } else if (A && !B && C && !P) {
      // Neutral - A=open, B=low, C=open, P=low
      gear = NEUTRAL;
    } else if (A && !B && !C && P) {
      // OverDrv - A=open, B=low, C=low, P=open
      gear = OVER_DRIVE;
    } else if (!A && !B && !C && !P) {
      // Drive 3 - A=low, B=low, C=low, P=low
      gear = DRIVE_3;
    } else if (!A && B && !C && P) {
      // Drive 2 - A=low, B=open, C=low, P=open
      gear = DRIVE_2;
    } else if (A && B && !C && !P) {
      // Drive 1 - A=open, B=open, C=low, P=low
      gear = DRIVE_1;
    } else {
      // none of the above
      gear = UNDEFINED;
    }
    // update your display here
}

Please note the above code is NOT the most efficient, but I believe it's easier to read and understand than a version using bitwise operations to identify the possible combinations.

Awesome, this really helps! Power source can be changed. The ECU in the vehicle that this is going to be tested in has plenty of 5v references. So if that would be better I can do that. But this really helps. Kudos! I will jump right on it when it gets here and see what we get, thanks again!

Please consider my update and also consider the fact the gearbox and the Arduino must have a common ground for this circuit to work.

Also consider there are more robust solutions than what I've here described and I would NOT advice to use the circuit I've diagrammed above unless you have double checked the gearbox and it's current draw capabilities. Personally I would opto isolate all interactions diagrammed above between the gearbox and the Arduino: voltage spikes are not uncommon in a vehicle electronics.

It is. It is totally separate. I am just using it to show gear indication. The ECU on the vehicle gets all it's info based on the floor shift. It does not use the range switch on the transmission. The range switch was not even being used. I just thought that I would like to have the indicator lights based on what gear the transmission is actually in vs what the sifter "thinks" it's in the way it is currently lit up as. This whole setup is completely separate from the actual vehicle operation. Just for me to see. It's a hotrod setup.

I've updated my answer based on what you have commented here: if both the gearbox and the Arduino operates at 5V then the whole circuit gets simplified and the shared ground will greatly simplify your circuit. All you need are pullup resistors to bring the voltage level HIGH when the gearbox outputs are open.

@Roberto Lo Giacco - Could he use INPUT_PULLUP instead of INPUT in pinMode() to eliminate the need for external resistors?

I wouldn't go above 6V - actually 7.3V would be about the minimum. There is circuitry to switch between the power jack input and the USB input. It is based on a comparator which compares double 3.3V (there is a voltage divider) from the 3.3V regulator to Vin, after the protection diode. So 6V is too low for it to switch to using the power jack. You would need 6.6V plus the voltage drop over the diode, so really 7.3V would be about the minimum. Possibly with no USB input it would take whatever it got, but still ...

If you have a 5V supply that is regulated and filtered you could put that direct into the 5V line of the Uno (and not into the power jack).

@VE7JRO actually no, those resistors act as pullups but they are also limiting the current sink by the gearbox open collector output when it is turned low: without the external resistors it is possible the gearbox creates a short to ground when turned low. Does it make sense?

@NickGammon that's totally right

@Roberto Lo Giacco - The transmission switch is ONLY providing a ground, so the Arduino Uno internal pull up resistor is providing the excess current protection when the input pin is grounded through the switch. The OP is not using the switch with the PCM connected to 12V as shown in this diagram: http://www.truckforum.org/threads/transmission-problems-4l60e.36202/. Please have a look at the "Park/Neutral Position (PNP) Switch" part of the circuit.

@VE7JRO the ground only connection is what I described as open collector, so I was aware of that. When internal pullup resistor is enabled you are actually connecting the Arduino pin to VCC via a 20k resistor so the final circuit would look like http://tinyurl.com/yd6k8xea
So you are right, good catch!


text:
Wemos D1 Mini deep sleep
I am building a very simple battery powered touch button using a Wemos D1 Mini (it is basically an ESP8266) and a capacitive touch sensor (something like this: https://www.az-delivery.de/en/products/touch-sensor-modul-1).
Since it is battery powered, I need to reduce as much as possible to consumption of the Wemos D1 Mini. I learnt that, in order to obtain minimum power consumption, we need to use the deep sleep mode. In order to do that, we need to connect RST to D0 (being D0 the WAKE PIN) and program the device accordingly.
My question is: will the Wemos D1 Mini wake up when the touch button is activated (aka: when PIN D1 is pulled up)?

Could this be the solution? I could use this as a switch to reset the Wemos D1 Mini and program it to send certain instructions when woken up.
https://youtube.com/watch?v=ojcwgxWMAo8

Why not try it to find out?

it will not. deep sleep is complete off. wake-up from deep sleep is a reset.

it would be far better to power the ESP from the button, perhaps though a mosfet. This will enable the button to work for years on the same battery.

@dandavis could you elaborate, please? Seems like an interesting solution

Please do not post further queries as "answers". This isn't a forum. If you want to add more detail to your question, please edit it. I have moved your "answer" into your question.


text:
Connecting Nokia 106 to Arduino
I was wondering if this can be done. I got a Nokia 106 and am trying to make it talk, but the audio jack doesn't seem to cooperate and the Fbus pins are right under the SIM slot, which is right under the battery. Any advice?
Added: It seems that it talks AT commands, since it is a GSM model, but I'm not 100% positive.

Hi, can you give us some information on the communication protocol of the Nokia? It's impossible to tell you if its possible to talk to the Arduino if we don't know how it talks.

@sachleen There's actually not much info out there. The phone was release on August 2013, so there doesn't seem to be much research. I found out about the Fbus here: http://forum.gsmhosting.com/vbb/f148/nokia-105-new-100-working-solution-1731398/

@sachleen Sorry for the difficult question. I'm kinda new to this and I don't want to screw up the cellphone… to much.

Here's the picture of the Nokia FBUS connector from your link:

And here's a (slightly dubious) method of connection from some random web page

which goes on to say

The F-bus protocol uses 115,200bps so we can easily use the Arduino’s serial function to communication with the phone. All you need to is hook up the phones TX to the Arduino’s RX and then use a resistor divider (I choose 330 ohm resistors) to connect the Arduino’s TX to the phones RX as shown above.

That page goes on to show how to use an Arduino to get the phone to send SMS text messages.
Sources:

http://www.insidegadgets.com/2013/01/12/how-to-use-nokia-f-bus-to-send-an-sms-message/
http://forum.gsmhosting.com/vbb/f148/nokia-105-new-100-working-solution-1731398/

Thanks, but the problem is that I'd need to pretty much tear the cellphone apart. I'd rather not kill my phone :/

just trim the actual simcard, so its level with 'microsim insert' back edge. Its what i did on my Nokia 100/GPO 746 project, works fine, wont kill the phone


text:
Stuck making multi, many button, joysticks
I'm stuck, I figured I'd ask here for some help... Note I'm a newb and this is essentially my first Arduino project beyond blink...
I'm creating Virtual cockpit panels for DCS World, using an Arduino Leonardo as an HID device. I'm using three SN74HC165 Shift-In registers for multi-buttons (24) - as it seemed the easiest - and all in all it does work...
So I figured that I'm using only 4 pins on the Leonardo, so why not try to setup 3 of these "shift-in clusters" (12 pins) to appear as 3 separate joysticks?
I got the one working and I got 2 more joysticks showing up in Windows10... now my problem is: how would I setup 2 more "shiftIn Clusters", I've tried many things but I must defer to outside help (cause I really don't know what I'm doing)
Edit to clarify: So each joystick need 3 or 4 shift registers making 24-32 buttons on each joystick
Shift In Lib: https://github.com/…/Ardu…/blob/master/ShiftIn/src/ShiftIn.h
Joy2 Lib: https://github.com/MHeironimus/ArduinoJoystickLibrary
Here's an image of the Layout I want: https://i.sstatic.net/sEtRp.png
... any help would relieve a great headache, Thank for your time
#include <ShiftIn.h>
#include <Joystick.h>

// use <n> shift registers
ShiftIn<3> shift;             // use three shift register

// Create joystick
// TESTING MULTI JOYSTICKS
// 1/3 Works!!!
// 3/3 Appear in Windows
// ????? must add shiftIn sections for 2nd and 3rd joysticks????
// (add pin usage + modify line 77-79 stuff)

#define JOYSTICK_COUNT 3
Joystick_ Joystick[JOYSTICK_COUNT] = {
  Joystick_(0x03, JOYSTICK_TYPE_GAMEPAD, 32, 0, false, false, false, false, false, false, false, false, false, false, false),
  Joystick_(0x04, JOYSTICK_TYPE_GAMEPAD, 32, 0, false, false, false, false, false, false, false, false, false, false, false),
  Joystick_(0x05, JOYSTICK_TYPE_GAMEPAD, 32, 0, false, false, false, false, false, false, false, false, false, false, false),
};

// Set to true to test "Auto Send" mode or false to test "Manual Send" mode.
//const bool testAutoSendMode = true;
const bool testAutoSendMode = false;

const unsigned long gcCycleDelta = 1000;
const unsigned long gcAnalogDelta = 25;
const unsigned long gcButtonDelta = 500;
unsigned long gNextTime = 0;
unsigned int gCurrentStep = 0;
int gJoystickId = 0;

/*
// WORKING SECTION Single Joystick with Shift Reg
Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID, JOYSTICK_TYPE_GAMEPAD,
  32, 0,                        // Button Count, Hat Switch Count
  false, false, false,          // X and Y, but no Z Axis
  false, false, false,          // No Rx, Ry, or Rz
  false, false,                 // No rudder or throttle
  false, false, false);         // No accelerator, brake, or steering
*/

void setup() {

  shift.begin(8, 9, 11, 12);  // set pins of the shift register
//  shift[1].begin(7, 6, 5, 4);  // set pins of the shift register
//  shift[2].begin(3, 2, 1, 0);  // set pins of the shift register

 Joystick[0].begin();
 Joystick[1].begin();
 Joystick[2].begin();
}

void loop() {

  if (shift.update()) {
    for (int i = 0; i < shift.getDataWidth(); i++)
    Joystick[0].setButton(i, shift.state(i));            // just press or release the button
  }
/*if (shift[1].update()) {
    for (int i = 0; i < shift[1].getDataWidth(); i++)
    Joystick[0].setButton(i, shift[1].state(i));            // just press or release the button
  }
if (shift[2].update()) {
    for (int i = 0; i < shift[2].getDataWidth(); i++)
    Joystick[0].setButton(i, shift[2].state(i));            // just press or release the button
  }
  delay(10);
*/
}

Each ShiftIn instance handles just one connection. You need to make multiple instances.
ShiftIn shift1<3>;
ShiftIn shift2<3>;
ShiftIn shift3<3>;

Then you begin each of them:
void setup() {
    shift1.begin(8, 9, 11, 12);
    shift2.begin(7, 6, 5, 4);
    shift3.begin(3, 2, 1, 0);
    ... etc ...
}

Each shiftx is a completely separate entity. You can just repeat your block of code for each shift object:
if (shift1.update()) {
    for (int i = 0; i < shift1.getDataWidth(); i++)
    Joystick[0].setButton(i, shift1.state(i));
}

if (shift2.update()) {
    for (int i = 0; i < shift2.getDataWidth(); i++)
    Joystick[1].setButton(i, shift2.state(i));
}

if (shift3.update()) {
    for (int i = 0; i < shift3.getDataWidth(); i++)
    Joystick[2].setButton(i, shift3.state(i));
}

You could arrange the ShiftIn objects into an array like you do with your Joystick objects and then loop through them, but that is pretty pointless for just three of them.

Thanks for your reply!
I didn't make my question clear, I need at least 24 buttons on each joystick so 3 shift registers on each joystick.. I added a picture

@FedaykinWolf Ah right. I misunderstood. I'll modify my answer.

That was it!!! the first part I din't understand how to start 3 instances (Also I was trying to modify "ShiftIn" and not "Shift"...
Thank you soo much! suddenly my headache is cured.

@FedaykinWolf Another option to save wiring is to connect all of them together to make one ShiftIn shift<9>; and do how I had before.

Thanks again! I was thinking about that option, but I need it a little more modular so I can change cockpit types (F-16, F-18, A-10) quickly, and easily


text:
Multiple Arduinos, same name - Windows 10 Game Controllers
I am making some SimPit panels and SimRacing devices, and I've run into an annoying issue. I have  multiple Arduinos (Leonardos and ProMicros) that show up as the same "Controller Names" (See Image)
EDIT: In the Game Controllers (joy.cpl) windows of Windows 10, where does the name "Arduino Leonardo" come from?, so that I can rename each, so they show up listed as something different like: Leonardo 1, Leonardo 2, Leonardo 3?
I imagine this is a change to the boot-loader and nothing to do with anything via Arduino IDE?
Thank you for your time, and let me know if more info/explanation is needed.

Thank you, edited, where does the name "Arduino Leonardo" come from?

https://github.com/arduino/ArduinoCore-avr/blob/master/boards.txt#L387

That didn't work, it changed the name in "Bus Reported device description" in device manager (https://i.imgur.com/TgIgXBR.png), but not in the joy.cpl "Game Controllers" window
also I purged all USB Serial devices to be sure there was no lingering windows drivers overwriting the changes

Then it may be in the .inf file for the driver in Windows.

So, if that's true, then it'll likely change all the devices using that driver together to the same name?
Not 3 devices using the same inf to 3 unique names?
I'll test ASAP

If it is the case then you'll need to make three distinct devices with unique VID/PID combinations and have three separate drivers for them.

it appears that windows is able to distinguish more than VID/PID of a USB device ... there is mention of VID/PID/REV in the inf files ... REV is the device revision number which is the bcdDevice field in the USB device descriptor ... the bcdDevice field would have to be different in each Leonardo ... the inf file would have to be edited to create a different device name for each REV version

start on the windows side of the problem ... write arduino code that sets the bcdDevice field to some number, such as 4 .... edit the inf file to match VID/PID/REV ... choose REV = 4 ... windows should hopefully detect Leonardo ... next, change REV to 5 ... if windows detects an unknown device, then you have a way to distinguish Leonardos

Thank you both I'm going to try this new path ASAP, I will update when I can

@jsotola why are these comments, instead of an actual answer? This is detailed enough to absolutely justify being its own step by step answer, which can then also be found by searching (both on-site and through google).

Windows is likely assigning the inbox driver to use based on the VID/PID of the USB device.  Take care changing those values, as you may not be able to easily reprogram the devices.
There is a Device Firmware Update (DFU) technique where if a pin is low at startup / USB init, the VID/PID are returned as different values

Meaning I should setup a "board" with the changed VID/PID in arduino IDE?
DFU if you mean the vulgar acronym, I can do that ... I am that ;)

Certainly not the vulgar term. I was referring to Device Firmware Update (DFU).  If you setup the board(s) to use a VID/PID that the inbox joy stick driver recognized, then Windows will recognize the devices as such. The key to this is being able to make sure that you can still get the Arduino IDE to recognize the board as well.  I don't have any leonardo boards, but I have done this with one of the other Arduino boards... though it was some time ago.

Correction:  The project I was thinking of emulated a keyboard not a joy stick

Haha lol DFU is permanently ruined for acronyms, ill never see beyond the vulgar one now.. Thanks for all the info


text:
Asynchronous function calls in Arduino sketch
In an Arduino sketch, is there a way to make asynchronous function calls within the loop? Like listening to requests through http server and process them in a non-blocking way.

If you're not a C++ beginner, then you could take a look at Cosa library (https://github.com/mikaelpatel/Cosa). It is a complete rewrite of Arduino library to make it better: OOP and generally interrupt-driven. I think they support HTTP, but I haven't checked that part yet.

Yes and no. You're kinda vague on what you want to do. I've made this into a few different sections (mainly focused on reading sensor data... it applies to everything but that's the context I'm using):
Threads
AFAIK all Arduinos only have one core (they can do one thing at once). For most Arduino boards, hardware multithreading isn't supported. However, there are ways to implement software multithreading. The approach by AsheeshR wouldn't work well for functions that take a long time to complete (i.e. something in a library that takes a while, or a delay) because it would get jammed up by those instructions, but it would work well for short functions like pinMode(). The Protothreads library listed there might be better at this, but I don't really know.
It'd be hard to orchestrate this with HTTP, especially since you have to make
Delays
A common way for a sketch to stall is the use of a delay. This can be solved by using, in the main loop, a if statement and the millis() function that returns a time (not a clock time, but rather the time since the Arduino started). You could also do a loop within the loop to poll sensor data.
The millis() approach wouldn't work well with things that cause the whole program to stall (i.e. more delays or loops that last a noticeable amount of time). Note that 100ms IIRC is the general maximum time to make a UI not seem laggy.
Interrupts
Interrupts are a great way to keep things almost asynchronous. They run a short piece of code (that you specify) every time a pin state changes. It breaks from the loop(), and goes back where it left off once the "ISR" has been ran. I don't have much time to explain how to do this, but a quick Google search will yield a lot of results.

As far as you example, the threading section would be the most applicable. This topic is pretty vague, so you'll have to experiment with a few things and find something that works.

I just posted some code for a task scheduler on the playground the other day, you may want to take a peek, maybe you can adapt it to your needs.
The Arduino's processor is inherently single-threaded and cannot multi-task. As has been mentioned there are however ways to create the illusion of multi-tasking. Annonomus Penguin hit on those pretty well.
Also check out TimerOne (It's probably better ;)

TimerOne is a bad idea because it works with avr-based arduinos only. For example my Wemos D1 R1 doesn't work

You can definitely make asynchronous code on devices with only one thread. This is what the "static" keyword is for in C. It helps you to setup functions as a "state machine" so that they can run concurrently with other functions.
Let's take a simple function for example. These are just made up functions and not meant to be compiled in any IDE, just to show you the general principles.
char read_bit_sync()
{
    while ( digitalRead(PIN_CLOCK) ) {}
    while ( !digitalRead(PIN_CLOCK) ) {}
    return digitalRead(PIN_DATA);
}

void loop()
{
    char c = read_bit_sync();
    Serial.println(c);
}

In the example code above, we wait for the clock pin to go high and then low again, and then on the falling edge we read the bit and print it to the Serial output in a loop.
The problem is, what if we want to read this pin asynchronously? These "while" loops cause the whole program to freeze until it receives a bit.
The trick is to reimagine our algorithm as one that can be done in many small steps that each can be completed in a very short amount of time, so that the function will need to be called repeatedly until those steps are completed.
int read_bit_async()
{
    static int state = 0;
    int ret;

    switch (state)
    {
        case 0:
            if ( digitalRead(PIN_CLOCK) )
            {
                return -1;
            }
            state++;
            return -1;
        case 1:
            if ( !digitalRead(PIN_CLOCK) )
            {
                return -1;
            }
            state++;
            return -1;
        default:
            ret = digitalRead(PIN_DATA);
            state = 0;
            return ret;
    }
}

void loop()
{
    int c = read_bit_async();
    if (c != -1)
    {
        Serial.println(c);
    }
}

In the example above, the function starts in a "0" state which it will remain in that state until it reads that the clock pin is high. It then transitions into a "1" state which it then will remain in until the clock pin is low. It then transitions to a "2" state which the next time you read it, it will return the bit read, and then reset its internal state to the "0" state.
Now in the main loop, we can call the read_bit_async() every iteration of the loop and it will return -1 when it's still "awaiting" the bit but when it received the bit then we get the actual bit value. The main loop can continue to run and process other code while waiting for the bit to be received.
I've used in this past to, for example, write a library that can read keyboard input from a PS/2 keyboard asynchronously alongside the main program. I've also used it to write a communication protocol that could send bytes of data down a single wire asynchronously, so if you have two wires for upstream and downstream data then the two devices could communicate without blocking the main program loop.
For what you are personally trying to do, let's say you receive an HTTP request and you want to respond to it with an HTTP file, but sending out the whole file is too time consuming. You could have each iteration send out only one byte.
You could also have a "listening", "processing", and "responding" state where at first it is listening for a request, and then if it receives one it switches to the "processing" state where it interprets the request, and then after that it switches to the "responding" state where it produces the output.
Also, the second block of code I wrote is not necessarily the most optimal, for example the last two states can be merged into one, but I prefer to write them this way because I find it to be more clear and easier to follow along with.
If you want to create a non-blocking asynchronous function on a single thread, the easiest way to do it is to reimagine the algorithm you're trying to write as a state machine that can be broken up into many many different tiny parts, where enough iterations of these parts can eventually complete task, and then to implement this.
When I say "tiny" I mean mostly in terms of speed. If a single iteration of the function takes too long, it can noticeably interfere with other asynchronous functions, so you want to make sure each iteration can be done in very little time. If a single iteration takes too long, then you should try to figure out how to break it up into even more states.


text:
AnalogRead always 1023 on Arduino Due?
Just using the Basic Example AnalogReadSerial.
// the setup routine runs once when you press reset:
  void setup()
{
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop()
{
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

I have a basic voltage divider set up between two 10K resistors from 5V to GND. I have verified with a DMM that the DC voltage at pin A0 is 2.5V. Grounding the A0 pin has no effect.
It also seems that enabling either ADC channel 7 (Arduino pin AD0) or enabling every channel, putting the ADC in free-running mode, and deliberately setting it to not sleep has no effect:
ADC->ADC_CHDR = 0;
ADC->ADC_CHER |= 0xFF;
ADC->ADC_MR |= 0b10000000;
ADC->ADC_MR &= 0b11011111;

Also, by running the sketch DigitalInputPullup, I can get the LED on pin 13 to toggle and serial communication to work as I tie the pin to ground, demonstrating that the board is being programmed properly.
I guess I'm just stumped. Should be the simplest thing in the world and it's just not working.
EDIT:
This is my attempt at manually controlling the ADC:
volatile unsigned long value;

void setup()
{
  //ADC setup
  ADC->ADC_WPMR &= 0xFFFE; //disable write protect
  ADC->ADC_CHER = 0b100; //Enable AD2     |
  ADC->ADC_MR &= 0b11111111000000001111111100000000;
  ADC->ADC_MR |= 0b00000000000100100000000000000000; //software trigger, hi res, no sleep, not free running
  ADC->ADC_IER = 0b100; //enable interrupt
  ADC->ADC_IMR = 0b100; //enable interrupt in mask

  ADC->ADC_CR |= 0b10; //start first conversion
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop()
{
  ADC->ADC_CR |= 0b10; //start conversion
  while (!(ADC->ADC_ISR & 0b100)); //wait for conversion to end

  for (int i = 0; i <= 15; i++)
 {
    value = ADC->ADC_CDR[i]; //read conversion data for all channels
    Serial.println(value);
 }

 Serial.println();
 Serial.println();
 Serial.println();

 delay(3000);
}

Just doesn't seem to be doing anything. ADC_CHSR (the ADC channel status register) shows channel 2 and only channel 2 enabled and conversions are starting and completing, yet now the conversion data is always 2048. Here's the serial output of all 15 channels, now in 12 bit mode:
0
0
4095
0
0
0
0
0
0
0
0
0
0
0
0
0

0
0
4095
0
0
0
0
0
0
0
0
0
0
0
0
0

Have you tried the same on another analog input pin?

Yup, I've tried all of them.

I've abandoned all hope and decided that the ADC is just bad.

You need to add this to your setup():
pinMode(A0, INPUT);

...to set the pin for reading.
Since you're reading an input that's already pulled up (in the middle of a voltage divider), that should be all. However, you can turn on the internal pull-up with:
digitalWrite(A0, HIGH);

...while the pin is in input mode.
More details here:
http://arduino.cc/en/Reference/PinMode
http://arduino.cc/en/Tutorial/AnalogInputPins

Could've sworn I needed something like this, but it wasn't in the example or the code on the website. However, it's still outputting only 1023.

Try connecting that pin to ground. If you still get 1023, you might have a damaged chip.

The value remains the same no matter what it is connected to.

It seems like a broken chip.

You could have a short somewhere.

No, you do not need to do analogRead() since the ATmega chips default to low impedance mode (input). Would've been needed if they set it to output, but that wasn't done.

@AnnonomusPenguin: Sorry for the bump, but don't you mean pinMode() and not analogRead() ?

pinMode(), yes :-)

Answer to a 6 years old thread. Hope this will help others :)
Looks like you have been using an external power source and only connected the positive core to the pin. If you had an external power source, did you connect the external power source GND to Arduino GND?

Try to force sensorValue at the beginning of the void loop to zero, put short delay before reading the analogue pin. I tried this and works for me. Unless your prgram will misbehave at zero sensor value at every loop start. The will  No need of initializing A0 as input because they are input by default.

If you have AREF pin pulled out onto the shield board not connected to anything, and you don't declare analogReference in your code (thus keeping it as the default internal 5V), it could still cause you to have the 1023 symptom you are describing. My suggestion: cut the AREF connecting pin, or put a constant 5v onto the AREF line.

Try adding this line in your void setup(), also disconnect AREF pin from any kind of bias,
analogReference(INTERNAL1V1);


text:
rfid_default_keys check with RC522
I just received a RC522 board and since i am new to RFID, I tried out some examples from "Arduino RFID Library for MFRC522". Here's one of them
rfid_default_keys
/*
 * ----------------------------------------------------------------------------
 * This is a MFRC522 library example; see https://github.com/miguelbalboa/rfid
 * for further details and other examples.
 *
 * NOTE: The library file MFRC522.h has a lot of useful info. Please read it.
 *
 * Released into the public domain.
 * ----------------------------------------------------------------------------
 * Example sketch/program which will try the most used default keys listed in
 * https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys to dump the
 * block 0 of a MIFARE RFID card using a RFID-RC522 reader.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

// Number of known default keys (hard-coded)
// NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
#define NR_KNOWN_KEYS   8
// Known keys, see: https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] =  {
    {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
    {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
    {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
    {0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
    {0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
    {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
    {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}  // 00 00 00 00 00 00
};

/*
 * Initialize.
 */
void setup() {
    Serial.begin(9600);         // Initialize serial communications with the PC
    while (!Serial);            // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();                // Init SPI bus
    mfrc522.PCD_Init();         // Init MFRC522 card
    Serial.println(F("Try the most used default keys to print block 0 of a MIFARE PICC."));
}

/*
 * Helper routine to dump a byte array as hex values to Serial.
 */
void dump_byte_array(byte *buffer, byte bufferSize) {
    for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
    }
}

/*
 * Try using the PICC (the tag/card) with the given key to access block 0.
 * On success, it will show the key details, and dump the block data on Serial.
 *
 * @return true when the given key worked, false otherwise.
 */
boolean try_key(MFRC522::MIFARE_Key *key)
{
    boolean result = false;
    byte buffer[18];
    byte block = 0;
    byte status;

    // Serial.println(F("Authenticating using key A..."));
    status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        // Serial.print(F("PCD_Authenticate() failed: "));
        // Serial.println(mfrc522.GetStatusCodeName(status));
        return false;
    }

    // Read block
    byte byteCount = sizeof(buffer);
    status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
    if (status != MFRC522::STATUS_OK) {
        // Serial.print(F("MIFARE_Read() failed: "));
        // Serial.println(mfrc522.GetStatusCodeName(status));
    }
    else {
        // Successful read
        result = true;
        Serial.print(F("Success with key:"));
        dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
        Serial.println();
        // Dump block data
        Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
        dump_byte_array(buffer, 16);
        Serial.println();
    }
    Serial.println();

    mfrc522.PICC_HaltA();       // Halt PICC
    mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD
    return result;
}

/*
 * Main loop.
 */
void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent())
        return;

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial())
        return;

    // Show some details of the PICC (that is: the tag/card)
    Serial.print(F("Card UID:"));
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
    Serial.println();
    Serial.print(F("PICC type: "));
    byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
    Serial.println(mfrc522.PICC_GetTypeName(piccType));

    // Try the known default keys
    MFRC522::MIFARE_Key key;
    for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
        // Copy the known key into the MIFARE_Key structure
        for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
            key.keyByte[i] = knownKeys[k][i];
        }
        // Try the key
        if (try_key(&key)) {
            // Found and reported on the key and block,
            // no need to try other keys for this PICC
            break;
        }
    }
}

So i modified the code to see exactly what is happening there and here is my output:

Everything looks fine, right ?
So i tried to modify it again by adding some more stuff to the knownKeys array
but it looks like that only the first key is used in the actual authentication.
Here's an output for the same card but i moved {0xff, 0xff, 0xff, 0xff, 0xff, 0xff},  // FF FF FF FF FF FF = factory default to the end of that array.

So.. as you can see even if it used the right key, nothing happened.
For the solution i tried few things but without a success. Thanks in advance for answering.

Call:
if ( ! mfrc522.PICC_IsNewCardPresent()) return false;
if ( ! mfrc522.PICC_ReadCardSerial()) return false;

before every re-authenticate.

According to NXPs application note (AN1304) regarding MIFARE CLASSIC cards (page 24/25):

Each time an Authentication operation, a Read operation or a Write operation fails, the MIFARE Classic or MIFARE Plus remains silent and it does not respond anymore to any commands. In this situation in order to continue the NDEF Detection Procedure the MIFARE Classic or MIFARE Plus needs to be re-activated and selected.

PICC_IsNewCardPresent resets modulation parameters and performs RequestA - activates the PICC (Card).
PICC_ReadCardSerial basically just performs Select - with anti-collision algorithm.

In case there are multiple cards present it would be better to manually call mfrc522.PICC_Select(&mfrc522.uid, mfrc522.uid.size * 8), the second argument tells it that you already know all of the bits for UID, thus it will select the same PICC that was selected previously.

Based on some experimenting, I believe the 1st key is skipped for one of two reasons:

If you follow the code flow, in loop(), PICC_IsNewCardPresent() and PICC_ReadCardSerial() called. If a "new" card/tag is present, then try_key() is called which calls PICC_IsNewCardPresent() [and PICC_ReadCardSerial()] again. Since the card/tag is not "new", PICC_IsNewCardPresent() returns false.
   or
It appears that if the correct key is the default of all 0xFF's, then a call to PCD_Authenticate() will fail.

I'm still working a new version of rfid_default_keys to fix the problem.

If called:
if ( ! mfrc522.PICC_IsNewCardPresent()) return false;
if ( ! mfrc522.PICC_ReadCardSerial()) return false;

before every re-authenticate.
You will skip the FIRST item in array knownKeys
so you will never test the default key FF FF FF FF FF FF.


text:
Problem stopping a stepper motor with an endstop
Basically I have created the following code to control my stepper motor:
int pin_enable_motor_x = 38;
int pin_motor_step_x = A0;
int pin_direction_x = A1;
int endstop_x = 3;

void setup() {
  pinMode(pin_enable_motor_x, OUTPUT);
  pinMode(pin_motor_step_x, OUTPUT);
  pinMode(pin_direction_x, OUTPUT);
  pinMode(endstop_x, INPUT);

  digitalWrite(pin_enable_motor_x, LOW);

  for (int i = 0; i < 200000; i++) {
    runMotorSingleStepX(100, false); // runMotorSingleStepX(int delay, boolean direction)
    if (digitalRead(endstop_x) == true) {
      break;
    }
  }
}

void loop() {

}

void runMotorSingleStepX(int wait, boolean value) {
  digitalWrite(pin_direction_x, value);
  digitalWrite(pin_motor_step_x, HIGH);
  delayMicroseconds(wait);
  digitalWrite(pin_motor_step_x, LOW);
  delayMicroseconds(wait);
}

The idea is that the stepper motor will give many single steps until it reaches my mechanical endstop. But what really happens is that it detects true random pulses even when my endstop isn't pressed. So my motor stops before the point it should stop. I'm not sure if it's a common problem and I should be using some tricks to fix this problem.
Does anyone know what could be happening supposing that my electronics circuit is properly settled?

How is this endstop switch wired exactly?

I'm controlling a RAMPS board (http://www.reprap.org/wiki/File:RAMPS1.4schematic.png)... It happens with all endstop min (3,14,18) and max (2,15,19) pins... I believe that it's some kind of noise problem that's possible to treat by software because the Marlin firmware ( the official firmware that runs with the Arduino Mega and RAMPS) works fine.

Try making the endstop mode INPUT_PULLUP

It seems to be a little more stable... But it still stops before the point sometimes.

Try a stronger pull-up, like 10k. Try a capacitor (eg. 0.1 µF) between the switch pin and ground.

Thanks, the extra 10K resistor solved the problem :) ...

Answer based on comments originally under the question
It sounds like the endstop switch may have floating input. Try making the endstop pins INPUT_PULLUP rather than INPUT.

It seems to be a little more stable... But it still stops before the point sometimes.

Try a stronger pull-up, like 10k. Over a long wiring run the inbuilt 50k pull-up may not be strong enough to counter noise in nearby wires.

Thanks, the extra 10K resistor solved the problem :)

Your for() loop is using an int type for the iterator. You are asking it to run for up to 200,000 steps but an int is a 16 bit signed entity (~+/-32,768) so the for() loop will exit well before it reaches your desired count. That may be why you are not reaching the stop while still in the loop.
You may want to use an unsigned long as the type for your loop counter and or use a while() construct in which you incorporate the exit condition.

That's true, thanks ... But actually I wasn't using the 200000 max value. I just put a huge number there to make tests. Even fixing the int value my endstop is still detecting random pulses along the way and stopping before my motor reaches it.


text:
Cannot pass objects of non-trivially-copyable type 'class String' through '...'
I'm attempting to send data from a serial connection to a GSM modem, but having problems.
The string from rx looks like this:
1.0 2.0 3.0 4.0

Here's my code to replace the spaces and then I just want to pass the whole string on, regardless of what's inside (there could be negative values too).
                data_current[data_index++] = ',';
                char received = bike_port.read(); //bike
                char test[32];
                inData += received;
                  if (received == '\n')
                  {
                      String nospace = inData;
                      nospace.replace("\t",",");
                      debug_println("Data: ");
                      debug_println(nospace);
                      inData = ""; // Clear recieved buffer
                      delay(1000);
                  }
                  sprintf(test,32,"%d,%d,%d,%d",(String) nospace);
                //strtok(received, tmp);
                for (int i=0; i<strlen(test); i++) {
                  data_current[data_index++] = test[i];
                }

I have also tried
sprintf(test,32,"%ld,(String) nospace);

What I get now is this error
cannot pass objects of non-trivially-copyable type 'class String' through '...'

Without the sprintf line I can successfully echo the string to debug_println (Serial Monitor).
What am I doing wrong?

Your sprintf() line doesn't seem to make sense. What are you trying to get it to do?

I basically just need 'nospace' to be added to data_current. Maybe I should try
    for (int i=0; i<strlen(nospace); i++) {
              data_current[data_index++] = nospace[i];

The basic problem here is that you're trying to pass a String object to sprintf(). That isn't possible because String is a C++ class, and sprintf() is a C variadic function. The only way to pass a string to it is as a char *.
The rest of your call to sprintf() doesn't seem to make sense either, although I suspect it's not what you actually want here. You'd normally use sprintf() if you want to format several values into a string.
As you've suggested in the comments, adding the contents of nospace to data_current character-at-a-time would be the sensible approach. You could do it something like this:
for (int i = 0; i < nospace.length(); ++i) {
    data_current[data_index++] = nospace[i];
}

Note that strlen() won't work on nospace because it's a String object not a char array.
This is all assuming that there's enough space in data_current though. Without seeing the rest of your code, I can't tell you if it will definitely work or not.

Update:
As an alternative, you could use memcpy() to do a block transfer:
memcpy(data_current + data_index, nospace.c_str(), nospace.length());
data_index += nospace.length();

I'm not sure there's much benefit to doing that though. It's hypothetically more efficient, but it probably won't make a noticeable difference unless your string is moderately long and it's being called very frequently. (It's trading-off the loop overhead against a function-call overhead.)

There should be enough space, if not, I know where to change it. But is there a way to add the whole content of nospace, not a character at a time? Because it then gets sent through GSM. I don't know what the exact character length will be, but I do know the maximum.

@Fid You could use memcpy() in theory, although I don't know how much difference it will really make. I've updated my answer with details anyway.

"But is there a way to add the whole content of nospace, not a character at a time?" Yes and no: Yes, you can express it that way in C++; adding strings translates into concatenation. No, because for most processors, and for AVR's in particular, it ultimately involves a character by character copy. In other words, write it however it reads best to you. It won't make much difference at run time.

Let me get this straight. You want to change:
1.0 2.0 3.0 4.0

to:
1.0,2.0,3.0,4.0

Right?
How about:
  char indata[32] = "1.0 2.0 3.0 4.0";

  int len = strlen (indata);
  for (int i = 0; i < len; i++)
    if (isspace (indata [i]))
      indata [i] = ',';

  Serial.println (indata);   // prints: 1.0,2.0,3.0,4.0

Only problem is that when I change "1.0 2.0 3.0 4.0" to the actual incoming read (bike_port.read()), than I get error ...

In that case, as Jake C said, modify the incoming byte like this:
 char received = bike_port.read(); //bike
 if (isspace (received))
   received = ',';

This works wonderfully. Only problem is that when I change "1.0 2.0 3.0 4.0" to the actual incoming read (bike_port.read()), than I get error "array must be initialized with a brace-enclosed initializer".

As a companion to Nick Gammon's excellent answer, here is a streaming version of that (assuming this is coming in one serial port and out another to the modem).
if (Serial.available()) {
  int inByte = Serial.read();
  if (inByte == ' ')
    Serial1.write(',');
  else
    Serial1.write(inByte);
}


text:
Find number in a reply returned via serial
I am communicating with my GoPro via ESP8266 and GET requests.
One of the replies returns a set of predefined number and what I would like to do is extract the number on position "38". This is what the reply looks like in full:
SEND OK

+IPD,4,163:HTTP/1.1 200 OK
Transfer-Encoding: chunked
Date: Sun, 24 Apr 2016 03:13:40 GMT
Server: Cherokee/1.2.101b150714_bd80061 (UNIX)
Content-type: application/json

OK

+IPD,4,972:3c0
{"status":{
"1":1,"2":1,"3":0,"4":0,"6":0,"8":0,"9":0,"10":0,"11":0,"13":0,"14":0,"15":0,"16":0,"17":1,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"26":0,"27":0,"28":18,"29":"","30":"xxx","31":0,"32":0,"33":0,"34":7933,"35":5039,"36":0,"37":4,"38":0,"39":4,"40":"%10%04%18%03%0D%28","41":0,"42":0,"43":1,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"54":29698976,"55":1,"56":4,"57":1022279,"58":0,"59":0,"60":500,"61":2,"62":0,"63":0,"64":0},
"settings":{"1":0,"2":9,"3":6,"4":1,"5":2,"6":1,"7":1,"8":0,"9":0,"10":0,"11":1,"12":1,"13":1,"14":0,"15":4,"16":0,"17":2,"18":2,"19":2,"20":0,"21":1,"22":2,"23":0,"24":2,"25":0,"26":4,"27":0,"28":2,"29":1,"30":10,"31":0,"32":0,"33":0,"34":1,"35":2,"36":1,"37":2,"38":0,"39":4,"40":0,"41":13,"42":8,"43":0,"44":8,"45":8,"46":0,"47":0,"48":0,"49":0,"50":1,"51":1,"52":0,"53":0,"54":0,"55":1,"56":1,"57":1,"58":1,"59":0,"60":8,"61":1,"62":700000,"63":4,"64":1,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":1}}

0

OK

As you can see, position 38=0 (...,"38":0,...). The number 0 will increment. So I would like to find the string "38": and do something with following numbers until ,.
What is the correct way to grab that number from the serial reply and echo or do something with it?

Are you using an Arduino to see the serial reply ? Or are you directly connected to the ESP8266 via USB?

USB <-> Teensy <-> ESP ~~~~ GoPro

Since you are being returned JSON, you can use the jsoncpp library found here
To split your return to an array. Then you simply retrieve whatever item you want using array index notation.
Here is another helpful post on creating arrays of strings in C++ from JSON.
C++ and JSON

I ended up using https://github.com/bblanchon/ArduinoJson and Serial.find();