text:
GPS is not detected on SIM808 module!
I'm trying to get GPS coordinates using my SIM808 module by connecting it with Arduino. When I use this code,
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "gps.h"

//To change pins for Software Serial, use the two lines in GSM.cpp.

//GSM Shield for Arduino
//www.open-electronics.org
//this code is based on the example of Arduino Labs.

//Simple sketch to start a connection as client.

GPSGSM gps;

char lon[15];
char lat[15];
char alt[15];
char time[20];
char vel[15];
char msg1[5];
char msg2[5];

char stat;
char inSerial[20];
int i = 0;
boolean started = false;

void setup() {
  //Serial connection.
  Serial.begin(9600);
  Serial.println("GSM Shield testing.");
  //Start configuration of shield with baudrate.
  //For http uses it is recommended to use 4800 or slower.
  if (gsm.begin(2400)) {
    Serial.println("\nstatus=READY");
    gsm.forceON(); //To ensure that SIM908 is not only in charge mode
    started = true;
  } else Serial.println("\nstatus=IDLE");
  if (started) {
    //GPS attach
    if (gps.attachGPS())
      Serial.println("status=GPSREADY");
    else Serial.println("status=ERROR");
    delay(20000); //Time for fixing
    stat = gps.getStat();
    if (stat == 1)
      Serial.println("NOT FIXED");
    else if (stat == 0)
      Serial.println("GPS OFF");
    else if (stat == 2)
      Serial.println("2D FIXED");
    else if (stat == 3)
      Serial.println("3D FIXED");
    delay(5000);
    //Get data from GPS
    gps.getPar(lon, lat, alt, time, vel);
    Serial.println(lon);
    Serial.println(lat);
    Serial.println(alt);
    Serial.println(time);
    Serial.println(vel);
  }
};

void loop() {
  //Read for new byte on serial hardware, and write them on NewSoftSerial.
  serialhwread();
  //Read for new byte on NewSoftSerial.
  serialswread();
};

void serialhwread() {
  i = 0;
  if (Serial.available() > 0) {
    while (Serial.available() > 0) {
      inSerial[i] = (Serial.read());
      delay(10);
      i++;
    }
    inSerial[i] = '\0';
    if (!strcmp(inSerial, "/END")) {
      Serial.println("_");
      inSerial[0] = 0x1a;
      inSerial[1] = '\0';
      gsm.SimpleWriteln(inSerial);
    }
    //Send a saved AT command using serial port.
    if (!strcmp(inSerial, "TEST")) {
      stat = gps.getStat();
      if (stat == 1)
        Serial.println("NOT FIXED");
      else if (stat == 0)
        Serial.println("GPS OFF");
      else if (stat == 2)
        Serial.println("2D FIXED");
      else if (stat == 3)
        Serial.println("3D FIXED");
    }
    //Read last message saved.
    if (!strcmp(inSerial, "MSG")) {
      Serial.println(msg1);
    } else {
      Serial.println(inSerial);
      gsm.SimpleWriteln(inSerial);
    }
    inSerial[0] = '\0';
  }
}

void serialswread() {
  gsm.SimpleRead();
}

After some time, I get this error on the Serial Monitor of Arduino:
status=ERROR

The connections are as follows:

TX of Module = Pin 2 of Arduino
RX of Module = Pin 3 of Arduino
GND of Module = GND of Arduino
5V of Module = 5V of Arduino

The Arduino is powered by USB connected to my PC.

Yes. SMS and Call functionalities are working fine. I can send messages to my mobile phone.
And what pins are you talking about? I connected GPS antenna only and nothing else.

I've added images of my GSM/GPS module. Please see for yourself. Thanks.

May I also ask what does pin G SDA SCL 1 2 G G 1 2 does?

Those are just breakout pins for the SIM808's I2C peripheral. Not needed here. Do you have a USB-TTL adapter? You can try communicating with the module directly with the serial monitor, to see if it responds to the GPS commands.

No. Unfortunately I don't.

You can use your Arduino as an adapter. Connect the GSM TX to Arduino TX and GSM RX to Arduino RX, GND to GND, 5V to 5V. Connect the Arduino Reset pin to GND. Then open the serial monitor, set it to "Carriage Return" and send "AT".

That is what I've been doing. But there is no RESET pin?

There is a RESET pin close to the 5V pin. Also this is NOT the same as what you've been doing. Read carefully and compare to your present circuit. Note that by Arduino RX and TX, I'm referring to pins 0 and 1 respectively.

I see a RESET button but no RESET PIN?!

Ok. I get it. I thought of something else. But how do I connect them. Do you just want to connect them on the board itself using jumper wire? Also if I connect TX to TX and RX to RX do I need the change the pins names in GSM.cpp file?

Your problem looks similar to mine. It is possible that your module is a GNSS module and therefore doesn't work with standard AT commands, which are used in "gps.h".
First check that the GPS Module receives enough current, at least 5V -- 2A from an external source like a battery.
Then try sending AT commands in the serial monitor to check if your GPS module works properly:
#include <SoftwareSerial.h>
SoftwareSerial SIM808(2,3); //(RX-Pin,TX-Pin)

void setup() {
  Serial.begin(19200);
  SIM808.begin(19200);
}

void loop() {
  if (SIM808.available())
    Serial.write(SIM808.read());
  if (Serial.available())
    SIM808.write(Serial.read());
}

Upload this to the board an then open the serial monitor and send these commands:
AT+CGNSPWR=1

This should return OK.
After that input:
 AT+CGNSINF

This should return OK and your GPS Location in this format:
1,0,<time>,<your latitude>,<your longitude>,..........

If you get the following output:
1,0,19800106001337.000,,,,0.00,0.0,0,,,,,,0,0,,,,,

It means your GPS is not set. Try to put GPS antenna outside your room, on open space.
For more information about GNSS modules go to  http://www.elecrow.com/wiki/images/0/05/SIM800_Series_GNSS_Application_Note_V1.00.pdf


text:
Clearing arduino serial buffer
How to clear the serial buffer of arduino uno?
This is my code to on and off the LED using sms from mobile using gsm module
#include <SoftwareSerial.h>
int Led=7;

SoftwareSerial mySerial(9, 10);

void setup()
{
  pinMode(Led,OUTPUT);
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void loop()
{
  if (mySerial.available()>0)
  {

  }
   switch(mySerial.read())
  {
    case 'a':
           digitalWrite(Led,HIGH);
           delay(10000);
           digitalWrite(Led,LOW);
           delay(100);
           break;

    case 'b' :
           digitalWrite(Led,LOW);
           break;

  }}

problem is whenever i on the module or the connection is restablished it automatically gets even without an sms.I need it to be fully in my control so i need to clear the serial buffer.

If you are receiving unsolicited message (reading junk) then you could extend the bit pattern you are expecting so that there is almost no possibility of you accidentally receiving it.
Rather than 'a' and 'b' as triggers user LED="0" and LED="1".  Doing this makes reading the data much harder, because what you are looking for may start on character 4 of the string you read.  This is what I think you will need to do.

Read each character in turn and store them in a buffer until you have 7.
Is the first character an L.
If it isn't then delete the first character, shuffle the buffer left
one place and load in the next character before returning to step 1.
If it was, check the next character matches the expected.
If it doesn't match delete all character to the left and this one and return to step one.
If you have a matching token then parse it (get the 1 or 0) and do the action.

You can simply clear it by reading it until its empty.
while(Serial.available()){
    Serial.read();
}

There also used to be a
Serial.flush();

to clear the serial. However they changed it to some other functionality. For further details you can look at the arduino reference page on Serial.

source: Stack Exchange

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

sort: votes


text:
Read BLE Characteristic Value in Arduino Uno
I am trying to build a Smart Led project using Arduino Uno, RGB Led, HM-10 BLE module, and Android device.
I am able to connect HM-10 with my android device and read and write characteristic values using Android BlueDroid stack.
But for this project to work I need to check changes in characteristic value in Arduino and process color value and produce output to light up LED.
I thought I could possibly use AT commands (like AT+Name? AT+POWE? AT+CHAR?) parse their result , but I couldn't find any AT command to read characteristic value. If anyone know such working AT commands for HM-10, please answer?
Also, I looked into CurieBLE library from Intel for Arduino. I think the library is to work on an Arduino board which has BLE hardware as a built-in feature. If that's not the case, please help me how can I communicate Arduino and HM-10 using CurieBLE or any other available library?

It sounds like you need to either find the manual for whatever firmware is loaded on your HM10, or else get the TI CC254x SDK and programmer so that you can treat the HM10 as a generic CC254x development board and create your own program for it.

I was able to communicate Arduino UNO and HM-10. Whenever one writes a characteristic on BLE using Android application, the exact bytes are transmitted to Tx/Rx channel to Arduino and can be read using SoftwareSerial Arduino library.
CurieBLE library works on Genuino/Arduino 101 board which has Intel Curie Module.

This doesn't even remotely try to answer "how". It just answers the "what".

I found this site that discusses the HM-10 and they linked to the datasheet which lists all the AT commands. The set/query characteristics AT command is listed as #13 on page 24.
Datasheet link.
"Bluetooth 4.0 with HM-10" tutorial for MIT course "How To Make (almost) Anything"
Hope this helps.

It is helpful to add some information of where the link directs to in case the link ever gets broken or moved.

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


text:
Arduino Uno - External Power not working properly
I am a newbie to Arduino and created my first project. The project is using a Sharp short range sensor and a 7 seg LED board (http://embedded-lab.com/blog/new-version-of-max7219-based-4-digit-serial-seven-segment-led-display/) to count objects.
Everything works fine when on USB power to my computer or if I use a 5v 1A wall adapter with a USB cable. The problem is when I use an external power adapter or use a DC power supply to the Vin. The board powers up and I measured the output voltage on the 5v pin and is measuring around 4.8v.
The Sharp sensor is connected to the A0 Analog in and I see the voltage fluctuate when an object passes, but the LED is not displaying a value when on the external power. The display is connected to GRD, 5v where DIN, CLK, and LOAD pins of the display are connected to pins 7, 6, and 5 as the instructions stated.
I tried two different Arduino boards and several different AC to DC power adapters ranging from 9v to 12v plus used a DC power supply to the Vin and same results.
The code is below and pretty simple (although I am sure there is a lot better way of doing it but this is my first project in C so go easy on me and the function for digits is from a website and not written by me).
If a picture of the project would help I can upload one.
Any ideas or thoughts?
Thanks,
Steve
#include "LedControl.h"
#include <stdio.h>
#include <math.h>

// Arduino Pin 7 to DIN, 6 to Clk, 5 to LOAD, no.of devices is 1
LedControl lc = LedControl(7, 6, 5, 1);
int sensorpin = 0;      // analog pin used to connect the sharp sensor
int val = 0;            // variable to store the values from sensor(initially zero)
int cnt = 1;

void setup()
{
    // Initialize the MAX7219 device
    lc.shutdown(0, false);   // Enable display
    lc.setIntensity(0, 10);  // Set brightness level (0 is min, 15 is max)
    lc.clearDisplay(0);     // Clear display register

}
void loop()
{

    val = analogRead(sensorpin);       // reads the value of the sharp sensor
    if (val >= 650)
    {

    //write values to LED
    if (cnt<=9)
    {
        lc.setDigit(0, 0, cnt, false); // Display 4 to Digit 1-9, " "
    }
    if (cnt >= 10 && cnt <= 99)
    {
        lc.setDigit(0, 0, getDigitFromNum(cnt,0), false); // Display 4 to Digit 1-9, " "
        lc.setDigit(0, 1, getDigitFromNum(cnt, 1), false); // Display 3 to Digit 1-9, " "
    }

    if (cnt >=100)
    {
        lc.setDigit(0, 0, getDigitFromNum(cnt, 0), false); // Display 4 to Digit 1-9, " "
        lc.setDigit(0, 1, getDigitFromNum(cnt, 1), false); // Display 3 to Digit 1-9, " "
        lc.setDigit(0, 2, getDigitFromNum(cnt, 2), false); // Display 2 to Digit 1-9, " "
    }

    delay(400);
    cnt++;

}
}

// Function: getDigitFromNum returns a digit at a given index of a integer.
// Goes from right to left with the starting index of 0.
int getDigitFromNum(int num, int digit) {
    num /= pow(10, digit);
    return num % 10;
}
// Function: getDigitFromDec returns a digit at a given index of a double.
// Goes from left to right with the starting index of 0.
int getDigitFromDec(double dec, int digit) {
    dec *= pow(10, digit);
    return (int)dec % 10;
}
// Function: getDigitFromNum returns the decimal values of a double.
double getDecimals(double dec) {
    return dec - (int)dec;
}

Maybe to much noise or load on the 5V regulator? How much power are you drawing? And what's wrong with just using a USB power supply? They are cheap and easy to find.

And a good clean picture, and schematic always helps.

Thanks for the help.
Added a photo... not sure it shows it real well. Downloading  Fritzing now so schematic to follow. How do I measure how much power I am drawing (remember newb here).
I want to ultimately use battery power. Any recommendations on a battery pack that will connect to the USB Type B port? Also I would like to understand what I am doing wrong or the issue.

Along with Passerby's comments, your stepping on your own brain. Do not over complicate the wheel. Stick with what works and make it more permanent. There is likely nothing wrong with your code or it would not work at all.

Do you have enough of current supply? What if your power supplies are just too low on current - cannot work properly because arduino cannot get enough current to power everything? Just try (if you have) something with 12V and 1A. It should be more than enough, but..at least, give it a try.

Passerby - Still working on the schematic - not sure how to represent the LED display board as it is not a standard part, but thanks for the tip on schematic vs drawing (once complete will upload). I looked into the USB banks and that looks reasonable and will research that, but still want to understand what is up with this. You mentioned noise. I have a few solder joints to connect the sensor and LED display back to the 5v. Could that cause an issue for the regulator? I read where the external jack is connected to a voltage regulator but the USB is not.

Sparky256 - thanks and yeah I have stepped all over my brain on this one. Although new to Arduino and C programming, background is in software and years ago played with electronics (long before Arduino). I didn't see the code as an issue, but a lot of people I notice ask for it. Also with trying multiple boards and power supplies ruled them out. Has me puzzled on this even though I am new to this.

Jakey - One the external wall jack power supplies I tried is a 12v 1A supply. The other one is a 9v 1a supply that came with a kit. I also used a Dr. Meter DC power supply connected to the Vin pin. It only allows the board to draw the max current it can handle. I pushed the voltage up to 12v and the board would only draw around .800 mAh. The power supply of course can push a lot more than that. Both of these produced the same result.

Okay. What if (I know this is not recommended, but) you connect +5V to a 5V pin on arduino? Just give it a try.
On the other hand: Why don't you (in this case) just power your Arduino with phone USB charger? Just plug in usb A -> usb B cable and you're ready to go.

I might not be able to respond as much for the next week because of travel for work. I am thinking it is something with the LED board. I am going to contact the supplier on that and see what they think. Thanks everyone and will update as soon as I can.

Jakey - right now I am powering the device using a USB phone charger and working good. Two things, I want the device to be portable so running off batteries is preferred and secondly would like to understand why it is not working. Is there something special or different you have to do when uploading the code to the device to have it run off of external power?
Not sure what you mean by connecting a +5v to the 5v pin. I thought the one 5v pin was a voltage out?

5V pin is voltage out. But if you connect the 5V power supply to this pin, arduino should turn on. It's not good for 7805, but if you try it for 3 seconds, won't do any harm.
About external voltage: Give it a try of a battery (or socket charger) to a DC connector left of the USB connector (watch the polarity!).
Report results afterwards. It shouldn't be much different, but in this case, we'll just give a kick in the dark.
PS: Just measure the battery/power supply(NOT USB!) voltage for sure. Just to make sure, it gives out as much as supposed to (or at least 7V, but preferable more than 9V).

@Jakey It's not good for 7805, but if you try it for 3 seconds, won't do any harm. You're talking nonsense. First there is no "7805", and second the LDO that is there doesn't give the slightest damn. Power has no concept of "in" or "out" - it only exists. The only possible danger is if you power through 5V and try to draw current from VIN to power things - then it can flow backwards through the regulator. Other than that, powering into 5V is perfectly valid.

The only difference between powering from USB and powering through the barrel jack is the voltage is reduced to 5V through a Low Dropout (LDO) voltage regulator. These are typically a clone of the popular LM1113-50 and vary in current handling capacity from around 500mA up to 1A.
I notice your board is not a genuine Arduino - therefore the components used may be at the cheaper end. So we'll assume a low-grade LDO that only handles 500mA before going into thermal shutdown with good heatsinking. Since there isn't on these boards we shall therefore assume a maximum of 400mA before it gets too hot. Probably somewhat conservative.
So if your entire circuit is drawing more than about 400mA you can expect the regulator to shut down, or at least to reduce the current and/or voltage available.
The fact you're seeing 4.8V rather than 5V could be an indication that there is voltage droop occurring - i.e., the regulator is not able to supply enough current so the voltage drops. This would be accompanied by the regulator getting very hot.
The regulator is the device with 3 pins on the right side and a single tab on the left directly above the barrel jack socket. See how hot that is getting.
As a rule of thumb if you can hold your finger on it without crying for 10 seconds it's not too hot.

Another thing you can do is to reduce your circuit to the bare minimum. Unplug absolutely everything and upload the Blink example sketch. Power that from the external DC and see if the LED blinks for you. If it does then the power supply is working OK. You can then add your peripherals one at a time to see when it fails.
If it doesn't blink then there must be something inherently wrong with the supply.
One possibility is that the LDO is oscillating due to insufficient or incorrect input and output capacitors. This basically means the "5V" voltage it gives out is actually wildly swinging between say 4.5V and 5V or 4.75V and 5.25V, which really confuses the microcontroller. Cheap LDOs are often more sensitive to the capacitors they are paired with and can suffer from this kind of problem.
To diagnose that kind of thing you would really need access to an oscilloscope to analyse the voltage.
If it is oscillating a 10µF ceramic capacitor connected between the lower two pins of the LDO (as orientated in your picture - that is Vout and GND) may cure it. A 1206 surface mount capacitor fits nicely across those pins and is reasonably easy to hand solder. You could also try a through-hole capacitor (ceramic again) between 5V and GND on the power header, but you really want it as close to the LDO as you can get it, so soldered direct to the LDO's pins is best.

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


text:
Connecting 4 servos, 2 motors, hc-05, sr-04 and L293D to Arduino
I am trying to make an obstacle avoiding robot with robotic arm. First, I am from software programming field with no experience in electronics, circuits and Arduino. Using online tutorials so far I am able to blink an led, bluetooth communication between PC and Arduino and sonar range measurement.
After doing a lot of research on internet I have made the following diagram to connect  4 servos, 2 motors, hc-05, sr-04 and L293D to Arduino using "fritzing" software. I have the sketches for running servos and motors but I am not sure the circuit is correct due to the lack of knowledge in electronics. My doubts are,
1) Is 6V supply enough for 4 servos and 2 dc to work?
2) Is the connection between L293D and 2 DC motors correct?
The final robot will look like (I hope!) a "mearm" like robot arm attached on top of an obstacle avoiding robot.

UPDATED:

Can i get the program for this connection?

1) Is 6V supply enough for 4 servos and 2 dc to work?

If the motors are 6V motors then 6V is not only enough, it is what you need. What you should be asking is "Can my power source provide enough current.

2) Is the connection between L293D and 2 DC motors correct?

Not quite. You have only got half your grounds connected up. Also 3,4EN should be connected to Vcc1 not Vcc2.
1A/2A and 3A/4A are the direction/break pins (one high and one low for a direction, both low for break). The EN pins can be (if you wish) used to control the speed with PWM (if you have any spare) - if not then they should be tied to the logic supply voltage, Vcc1, not the power supply voltage, Vcc2, since that can be up to 36V and is way too high for logic inputs like EN.

Thank you for your valuable comments. I have updated the diagram as you said. Can you please check it is correct or not?

Not quite. You seem to have misunderstood the Vcc1/Vcc2 thing. Vcc2 still needs to be connected to your 6V rail, not the 5V one. It was ony 3,4EN that needed to be changed from connecting to Vcc2 to Vcc1.


text:
Arduino LCD Screen
I am newer to arduinos, and could use some help. I have a LCD screen hooked up to an arduino uno. I can get it to display whatever I type in, which is great. But, what i want it to display is a value from an excel spreadsheet. So, it will change depending on what is in that field. Or even better yet, from access. Is this possible? is there code to have the arduino pull information from an existing table? (assuming it is connected via USB, or, eventually, wifi). thanks!

Assuming your Excel spreadsheet or Access table is stored on your PC, you can write a PC program to read the file and send the data serially over the USB connection to the connected Arduino, which can display it on the LCD.
If the file is stored on an SD card instead, and you want the Arduino to access the file directly by reading said SD card (through an Ethernet shield perhaps), you need to make the file format a lot simpler than XLS to ease parsing; CSV is quite simple and suitable for a lot of tasks. The built-in SD library can be employed to read the data from the card, the Arduino parses the data and displays it on the LCD.
In general, I suggest you do more research.

Why I came here =) I have been digging around, and found that exporting data is easy, but importing it is a whole new monster. Would it be easier to code the arduino in a way that it always reads from the same file location, same lines, same file, in lets say txt format. then access or excel just exports to the same place every time in txt format?

@niva5171 Where will the file be located?

It can be anywhere really. I can have access export the file to any location

@niva5171 What I mean is, will the file be on an SD card connected to the Arduino or on your PC? The former will remove the need for a connection to the PC while the latter will remove the burden of storing the files and parsing them.

Sorry, it is on the network drive (So the PC). Right now any computer can access it. Right now through USB, eventually through WIFI

@niva5171 In that case, you should understand that your Arduino sketch has no control over your PC, at least not without some cooperation from your PC's side. You need to write a program for your PC, in some language, that will open the file, parse it and ultimately send the data to be displayed to the Arduino over the serial connection or WiFi. The only task for the Arduino is to listen for data and print whatever it receives to the LCD. The rest is left for your PC program.

@niva5171 Sure. I suggest you explore the CSV format, which is very straightforward and can be used with Excel. Also try Python for the PC program; its easy to get started with a few lines of code and there are a lot of tutorials on using "pySerial".

Great! I will give that a look into, thanks again!

It is not the easiest thing to do especially if you are newer to arduinos but Roberto Valgolio has made an Arduino Excel interface: http://www.robertovalgolio.com/sistemi-programmi/arduino-excel
I have not worked with it yet but it's worth looking into it.

Yeah, ive noticed that really quickly unfortunately, but if I can figure out how to do it, it could be a really cool advancement for my company. thanks for the link!


text:
Audio Input into A0?
I saw a YouTube Video of someone who used an aux cord input into pin A0 on their Arduino to control a strip of LEDs. I have a strip of Adafruit's RGB NeoPixel LEDs, but I'm not sure how to input my audio into pin A0. If there is a way to do this without a separate shield or board, that'd be great because I'm on a tight budget, but if not possible it'll have to do. Also, would it be possible to send this audio to another Arduino via wifi or bluetooth using a different shield? Thanks.

Depending on how loud your audio signal is, you may be able to do it with just one capacitor and two resistors:

If your signal is quite quiet, though, you may need to amplify it using an op-amp. For instance:

That arrangement would double the volume of the audio. It also has the effect of inverting it, so you will need to invert your readings in software.
Also note that both of these methods will give you an AC waveform centred around 2.5V, so silence will be a reading of around 512, and it will go up and down from there. You can sample that audio waveform and do some basic (though quite slow on an Arduino) analysis of it, such as FFT to get the frequency content of the audio - great for visual effects...

Okay. I have these cheapy water speakers. You're suppose to plug the second speaker into the main one via mini usb, but I figured out that if you actually plug the Arduino into it, it has a constant green status led and the RX and TX LEDs glow to the beat of the music. Would it be possible to feed this to the code that was provided in the description of the video I linked in my main post above? I'm not quite sure how to analyze the connection. Since I'm kinda newly, I figured this he'd easier than the method you listed above.

authors: ธัญเทพ มีเรี่ยม


text:
Significant drop in speed between Arduino IDE and Visual Studio?
So, I'm not sure what is causing this, but maybe I'm overlooking something simple. I have a simple program designed to read the analog input at 640 Hz, it looks like this:
int Ch0 = 0;
int count = 0;
unsigned long startTime;
unsigned long currentTime;
bool startedReading = false;

void setup() {
  //set up pin(s)
   pinMode(Ch0, INPUT);

  //begin serial at 115200bps
  Serial.begin(115200);
}

...

//if the current time exceeds the start time by one second, set the start time equal to current time, print the count, set count equal to zero
if (currentTime - startTime >= 1000) {
  startTime = currentTime;
  Serial.println("time");
  count = 0;
}

//read input, delay some microseconds as a means of controlling sampling rate, bring count up by one
//should read somewhere along the lines of 640-ish Hz
analogRead(Ch0);
delayMicroseconds(1230);
Serial.println(count);
count++;

And this all works fine and dandy in the Arduino IDE, I pull up the Serial Monitor, and it prints every number 1-640 and then says time, with good consistency. Yet, when I open up a Visual Studio program and call the command:
EDIT: Added entire data received event method
private: System::Void serialPort1_DataReceived(System::Object^  sender, System::IO::Ports::SerialDataReceivedEventArgs^  e) {
    if (!this->reading) return;
    else
    {
         try
         {
            //get incoming port and read
            SerialPort^ sp = (SerialPort^)sender;
            String^ sInData = sp->ReadLine();
            //parse read data
            double inData = double::Parse(sInData);

            //write data to debugger for testing
            Debug::WriteLine(inData);

            //start populating the "in" array
            AppendIn(inData);
          }
          catch (Exception^ e)
          {
            Debug::WriteLine(e->Message);
          }
    }
}

Aside from the obvious error that occurs when I try to parse the string "time" to indicate when 1 second has elapsed, everything works fine. Except for the fact that the numbers feed into the debugger very slowly. As in, it'll take roughly 4-5 seconds to read through all 640 reads of the count integer and then it throws the time at me. Thus, this leads me to conclude that Arduino is indeed calculating that 1 second has elapsed and then sending that over, but the output is essentially the same, the only difference being that the message takes exactly 1 second to read on the Arduino IDE and over 4 seconds to read in real time in Visual Studio.
Maybe it has something to do with the way I'm reading the data in VS? I have it set up to constantly monitor the stream by calling that read method every as an event when data is received over the serial. No data at all is being lost, it's just very slow...and only in VS. Thanks in advance for any help you can give, but I'm at a bit of a loss.

I have it set up to constantly monitor the stream by calling that read method every as an event when data is received over the serial.

I suspect that is the issue. Waiting for an incoming "serial data available" event and then processing it, is likely to be slow. I would rework how you get serial data. You haven't shown that bit but maybe you can use a larger buffer.

Hmmm, I'm not entirely sure what you mean by "how I get serial data," but I did include the rest of the event if that's what you mean. The method is attached to the OnDataReceived event of a serial port control in a c++ Windows form if that sheds any more light on it also. That said, I took your suggestion and cranked the read buffer size to16384 (4x what it was before), but there weren't any noticeable speed improvements. So it might have something having to do with firing an event 640 times a second. Though, I'll have to see what other way I could read continuously then.

I don't know exactly how the Windows functions work in this case. Can you provide a reference? (link). What I suspect is happening is that the event is called on the first incoming byte, and ReadLine is waiting for an entire line (and timing out after a couple of seconds).

I think you might be right, according to this page, it does read up until the new line character. In the mean time, I'll try messing around with some of the properties referenced on this page.
https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readline(v=vs.110).aspx

Ok, looks like I'll have to double comment because I can only edit comments for 5 minutes, but I went through and disabled the timeout, then tried changing the ReadLine() command to each of the other alternative reads (there were only about 5 or so, so it wasn't too difficult to test them all) and it seems like it's working perfectly now. I seem to be getting the best speed out of ReadExisting(), granted with marginally less accuracy.  It's a little difficult to tell if it's still reading at exactly 640 Hz, but it's very close if it's not. Thanks a ton for the help!


text:
Reduce 5v Trinket Pro to 3.3v?
Apparently these nRF24L01+ modules need 3.3v, but I've only got 5v Trinket Pros that I'm using.
How can I reduce the voltage to the RF transmitter?
Would a voltage regulator work? Specifically looking at this: http://addicore.com/product-p/165.htm

The NRF24L01+ has inputs that are 5V tolerant! So you only need to provide 3.3V on the Vcc pin of the module, which you can do by putting a voltage regulator between it, and the 5V of the Trinket. So there isn't really any need to convert the Trinket to 3.3V.
PS Remember to add some capacitors to the output of the voltage regulator, as the NRF needs a pretty stable 3.3V. Noise in the power lines can cause instability in the operation of the device.

I also had a 5V Pro Trinket on hand and needed to connect one of its 5V output pins to the 3V pairing pin on an Adafruit's EZ-Key HID. I solved it easily for the price of a couple 1/8 watt resistors by including a simple voltage divider in the circuit as a "level shifter" and it works like a charm. In my case it's not serial data but give it a try.
Classic voltage divider equation: V out = V in * R1 / (R1 + R2)

In setup(), set the 5V Pro Trinket digital out pin to be normally LOW when it's not doing anything in the sketch, e.g. if it were pin 8: pinMode(8,OUTPUT); digitalWrite(8, LOW);
Connect this 5V output pin to one end of a 1.8K resistor (the "R1").
Connect the other end of that resistor to both: your 3V module's input pin AND to a 3.3K resistor (the "R2") to ground.
If you have a meter, perhaps before connecting to your module input first double check your circuit at the juncture of the resistors. Actual serial data probably won't produce a reliable reading so temporarily alter your sketch to just take the 5V Pro Trinket pin HIGH. I measured 3.1 V output on mine when the output goes HIGH and it works great with the EZ-Key module.

There are 3.3V Trinkets. Anything you try to do will cost more than buying one.

LM78**, resistors... simple IC and discreet wouldn't cost more.

As said by JayEye: there are 3,3V Trinkets and that is probably the cheapest option.
If you want to pay the extra money, there are special boards for it by addicore: https://www.amazon.com/gp/product/B00VFNZN8K/ref=s9_dcacsd_bhz_bw_c_x_3
third option is to build yourself a small voltage regulating circuit. The regulator that you linked to will do.


text:
Relationship between avrdude's "programmer" and bootloaders
I'm trying to understand the "programmer-id" concept, as specified in -c avrdude's option.
avrdude asks me to choose a "programmer-id" among many it knows of.
Let's say (just as an example) I have a Arduino 2560 to which I connect via USB, and I want to program it using the bootloader.  Then, in this scenario,
is one programmer-id and just one supposed to work?
More in general, one has
1) some particular board (MCU, -p in avrdude)
2) some particular programming method/connection (JTAG, ISP, development board, USB/serial,  etc)
3) (if using bootloader) some particular bootloader code in Flash.
How are these things related with the programmer selection? I guess that some (most?) programmers-ids are specific to some programmer connection/method (AND probably with some hardware family?), and they have nothing to do with the bootloader.  What is the programmer to use for a standard Arduino with bootloader, connected via USB? What more can be said?
Furthermore, the Arduino IDE lets me choose "Upload" and "Upload Using Programmer" (the first works for me, the second doesn't). Why this distinction? Isn't a programmer always used? What does the IDE do, under the hood (does it call avrdude?) when choosing "Upload" ?

If you are using the bootloader, you are not using a programmer. The programmer, when used, is connected to the ICSP pins on the Arduino. The bootloader however expects a well-defined sequence of data from the Arduino through the serial port immediately after reset. The bootloader recognizes that (if received) and reprograms the flash.
If you turn on verbose mode for uploading you will see the programmer type:
-carduino

That is, the Arduino is using the bootloader programming method.
See my post here: What happens when code is uploaded using the bootloader?

Furthermore, the Arduino IDE lets me choose "Upload" and "Upload Using Programmer" (the first works for me, the second doesn't).

Yes, with "Upload Using Programmer" you need a programmer, such as the AVRISP which you would plug into your USB port, and then select that as the type of programmer to use. In this case, your Arduino does not need to be plugged into the USB as the serial port is not used for programming.
Note that some programmers supply Vcc (ie. +5V) to the Arduino and some don't. The AVRISP doesn't.

Furthermore, it seems that that "Optiboot" is a different bootloader than the standard included in the Arduino.

As far as I know, recent Arduino Unos (and probably others) ship with Optiboot. Its main advantage is that it is smaller (only 512 bytes).

More in general, do avrdude need to know the particular bootloader?

I think the smaller boards use STK500 protocol (see links below) and the larger ones (eg. the Mega) use STK500 Version 2. That is because they have a larger address space. So yes, it needs to know the protocol.
When I switched my board type to Mega2560 the "-c" option changed to:
-cwiring

I am guessing from that, the "arduino" is code for "STK500" and "wiring" is code for "STK500 V2".
Protocols

AVR061: STK500 Communication Protocol
AVR068: STK500 Communication Protocol version 2

Thanks! "The bootloader however sends a well-defined... " should be "The bootloader... expects ..."? Furthermore, I see "-cwiring" in my IDE (1.6.9) instead of "-carduino"

Furthermore, it seems that that "Optiboot" is a different bootloader than the standard included in the Arduino. Are they compatible, or should one change the "-c" option ? More in general, do avrdude need to know the particular bootloader?

You are right, it "expects" the protocol. I amended the reply. Your other questions addressed in the amended reply.


text:
Arduino Button interference
With a push button on an Arduino (or Raspberry Pi), instead of wiring a high voltage (5v) through a button and to a pin to read the input, you often want your input pin set to HIGH (high impedance) and wired through a switch to ground to avoid interference like EM waves. My question is what exactly does setting the input pin to HIGH do (besides making it high impedance)? Does it make the circuit less sensitive to EM interference? I like to understand more of the physics behind circuit design.

In Arduino, just setting the pin as input already makes it high impedance.
Writing HIGH on an input pin actually enables its internal pull-up resistor.
This way, the voltage at the pin is always defined (instead of floating when the switch is open).
Just search for "pull-up resistor" if you need more information.
Note that this code:
pinMode(n, INPUT); // set as input, high-impedance
digitalWrite(n, HIGH); // activate the internal pull-up resistor

is equivalent to this (in recent Arduino IDEs):
pinMode(n, INPUT_PULLUP)


text:
Calculate time between 2 data of a sensor
I'm working on a project in my university and I'm having a trouble in calculate time. I have a conveyor and an IR sensor which I use to calculate the maximum and minimum distances of a box when it is moving on the conveyor. Then I want to calculate the time between the max and min distances of box. I have used millis() for timing but it is not accurate.
Here is my code:
int IRpin = 0;
float volts, distance,firstdata;
int k = 0;
float min;
float mang[150];
int m;
void setup() {
Serial.begin(9600);
}

void loop() {
volts = analogRead(IRpin) * 0.0048828125;
distance = 13 * pow(volts, -1.10);
if (distance < 20)
{
Serial.println(distance);
mang[k] = distance;
k++;
}
else
{
if (k > 0)
{
  min = mang[0];
  for (int i = 1; i < k; i++)
  {

    if (min > mang[i])
    {
      min = mang[i];
      m = i;
    }
  }
  firstdata=mang[1];
  }

I store data the sensor send to me in an array. Now I want to calculate the time between firstdata [mang(1)] and [(min)]. I use 0A41SK Sharp IR sensor.
Thank you for your time and sorry for my bad english.

1st - please format your code properly. Most people won't bother looking at it the way it is now. 2nd - I see no millis() or any other timing calls in your code. 3rd - if you only use the mang array for finding the minimal value - you don't need an array at all - just remember the last minimal value (and eventually its time) - this will save you 600 bytes of memory and the corruption caused at the 151st reading of distance < 20. 4th - 'min' is not a good choice for variable name - it is often defined as a macro, which will cause you problems.

millis() not accurate enough? What kind of accuracy do you need?

Ok, yea...Please format this a little better (properly tabbed line spacing and such), and comments would go a long way to understanding this, because chances are people don't want to invest the time to decipher what's going on here without them. I'm not entirely sure what is going on here, but I'll just suggest what I would do in my understanding of the question, which is how to detect what the minimum and maximum value of the distance is and record the time at which each of these moments occurred.
I would have a float value to store the maximum and minimum distance as well as their times, and simply on every iteration of the loop check if the position was greater than the previous maximum distance or shorter than the previous minimum distance. If either of those are true, set the maximum/minimum distance to the current position and set the maximum/minimum distance time to the current time, using millis(). There's no reason I can see, if I'm understanding this correctly for an array to store all the data, it's just taking up memory space from what I see.
Hope this helps a bit, and, if I'm totally off base, again I'll emphasize the utility of comments in readability. Hope this helps and good luck.

I dont care much about code formatting, so i'll just leave you with 'indent' to satisfy the coding snobs that may have been flogged just a bit too hard by their programming teachers.. To the point (one of them) now; You're using int for your measurements against millis(). This will not fly if your measurements exceed 32 seconds, or if the runtime of the sketch exceeds 32 seconds. Please use unsigned long for all variables referencing millis().

I'm not exactly sure what you're trying to achieve with your code but from what i understood is that you're taking distance measurements to see if an object is front of your sensor and then you want to measure the time interval between each object passing by ....right?
Assuming my understanding is correct, what you need to do is first measure the distance to know if an object is there or not, and then if there isnt an object you start a 'timer' until an object appears and then print thy data to Serial Monitor....
//this is a comment...they make code easier to use and understand for you and others .....
int IRpin = 0;
float volts, distance,firstdata;
//don't Know why you need those...
/*int k = 0;
float min;
float mang[150];
int m;*/
boolean Exists;
boolean measured;

int startTime;
int Interval;
void setup() {
Serial.begin(9600);
}

void loop() {
volts = analogRead(IRpin) * 0.0048828125;
distance = 13 * pow(volts, -1.10);
if (distance < 20) //an object is in front of the sensor
{
Serial.println(distance);
Exists = true;//object is present
}
else
{
Exists = false; object isn't present
}

    if (Exists == false) {// no object present

if(measured == false){//to see if the timer already began
    startTime = millis();
    measured = true;// so the code only runs once
    Read = true; //so that we only measure the time when the timer begins
    }}
else
{ if(Read == true){
Interval = millis() - startTime;
measured = false;

Read = false;

Serial.print(Interval);
}}

What I'm trying to do in the last snippet is to make sure that we only measure the time when nothing is present.

Please excuse any errors i might have done.I'm half asleep and in mobile so things look different

authors: 安信8娱乐代理--平台总代


text:
Determine Object Heading
Is there a sensor I could use which would let me know which direction an object is heading/facing? i.e. I have a servo that can rotate 0 to 180 degrees, and I have another sensor on a block. When I turn the block 45 degrees, I want the servo to also turn 45 degrees - I thought I could do this with a compass, but the varying magnetic fields make it impossible. Gyro/acc maybe? Except I don't know how to use that to solve this problem.
So in other words we need to know the block was rotated 45 degrees using a sensor on the block, which tells the servo to rotate 45 degrees.

You can lookup "sensor fusion" (which is a complicated matter) and "MPU6050", which is a cheap board with some hardware support and plenty of examples for it - perhaps it might be what you need.

Great thanks, I think that might work I have used that sensor before for an indoor positioning system / IMU setup -- one question though is there a way to have two separate MPU6050 synchronize orientations? That was the reason for my compass system - both knew which way was north irregardless of when they were turned on so I could use that as a calibration point.

Lookup Magnetometer sensor.

You could use the accelerometer to "synchronize orientation" because gravity always points down, but that will only work if the two sensors rotate on an axis that does not line up with gravity (e.g. they don't rotate around an axis pointed up). Similarly, a magnetometer won't work if the table rotates around the north vector.

Use a gyro, it will give you the angle. Gyros are difficult to find spare, so you should buy an IMU like MPU6050 that contains also an accelerometer.

authors: บันฑิตา อินทร์สุวรรณ์


text:
Detect movements of a person?
I'm working on a Virtual Reality game. I want to detect the position or movement of most of the bones in the human body(e.g. Knees, elbows, shoulders, hands and legs). This person may wear special equipment. How should I detect this?? I also want to get the distances between a certain position(e.g. The Arduino board) and each bone. Any ideas?

google for "arduino kinect" and you will get lots of ideas.

I'm sorry but saying you want to do some massively complex project and then asking for "any ideas" does not fit into the question-and-answer format of this site. Please narrow your question down somewhat.

What you're looking for is called motion capture. If you google it, you'll find a Wikipedia article that can give you a starting point for deciding which of the many available techniques will suit your project. Youtube also has several videos explaining motion capture, and different technologies.

The problem is that the player is not going to be visible

Please elaborate.

The player is going to be in a giant hamster ball, and he wouldn't be visible, so I need to use some kind of suit.

Bigger problem is that we are not a design bureau.  If we were, I doubt we would use Arduino for this in the first place.


text:
Starter Kit for Arduino Cookbook
I have this book here about Arduino. What kind of Kit should I purchase to get started? Would this work?

I'm not yet sure about what I'd like to do with Arduino, so I may prefer a pretty Universal Kit in order to cover a pretty wide range of projects.
Except this, I won't need any advanced stuff, at the moment, as a beginner I may want to understand the fundamentals, so will surely need LEDs, maybe screens, and other basic stuff like that.
Later on I may try to go for Wireless modules, but not at the moment as a beginner.
Any ideas? Hope to have clarified more or less what projects I'm aiming to, yeah the range is wide, but restricted to basic beginner projects.

I'm not yet sure about what I'd like to do with Arduino - Arduinos are a lot of fun, and you can learn a lot from them. However asking for a suitable kit for "I don't know what" is a big ask. I suggest a minimal kit (or just a plain Arduino) and do some of the tutorials. I think this question should be closed as too broad, but I'll leave it to my fellow community members to make that decision.

The advantage to a kit is it includes a lot of stuff. You'll have a big selection of sensors and parts to choose from.
The disadvantage to a kit is it includes a lot of stuff. You'll have bought and paid for a big selection of sensors and parts, some of which you may never use.
Since you linked to Amazon, I assume you are someplace where shopping on line is convenient. In that case I'd start with a small handful parts and let your developing skills and interests guide your future purchases.
A bag of LEDs with resistors included is really basic - start there. I make up a dozen or so of them with a resistor permanently soldered to the cathode (ground) side of the LED (it doesn't matter which side you choose, just be consistent for your own sanity later on!) These are quicker to wire up on a breadboard than using separate LEDs and resistors, and they make a quick and dirty logic-probe ("Is there 5v on this board?", "Is this pin HIGH or LOW?") or output device.
A handful of push-buttons, often called "Tact switches", a few analog thermo sensors (LM34 or LM35 f/ex), and a light sensor, would start you off inexpensively while providing you opportunities to learn how connect these devices, some basic electronic theory, and some programming skills.
By then, you'll have a much better idea what kinds of projects you want to pursue and the parts necessary to build them.

Yeah guess you're right! Bought a very basic kit without an LCD and other stuff, this way I'll save some money and get a separate LCD for just 3€ instead of spending 20€ more for another kit which includes an LCD screen but even lots of other stuff I'm not sure I'll use it, at least at the moment..

The Stack Exchange format is not well suited for opinions.  That said, people are apparently giving the kit good reviews.  And I see hardware that appears to allow for several projects (LED arrays?, motors?, ultrasonic-distance-measurement?, IR-remote-control?, Alpha-numeric-LCD?, 7-segmet-LED-display?, ect).  Which is more than you need for basic Arduino projects.
In general, it would make the most sense to find a kit with a book rather than obtain a book and a kit separately. This is because slight differences between the written material and independently obtained hardware will cause confusion.  This is generally not a problem for experienced embedded developers.
Keep in mind that embedded processor projects are half hardware and half software.  Since the hardware has already been collected, the majority of activity will be in software.  If this paradigm agrees with you, good luck & have fun.

Mmm you have a Kit to suggest?

The end goal for Stack Exchange is to have a list of clear questions with concise answers that can be searched through.  Opinions do not fit into that paradigm. But, no, I have no specific kit to suggest.  Only, for a beginner, to find a kit with a book so it is clear how to proceed.  While there are many standards for electronic parts, there are also many variations.  It sometimes only takes 1 or 2 variations to make a part unusable to the beginner.  That is why I am suggesting  to buy a kit and book together.

I'll add this...  I did not see a servo motor in that kit.   Servo motors are more expensive because they contain a computer-to-motor interface inside.  Most beginning Arduino uses find servo motors fun to work with.  And they are easy to interface (both hardware and software) to an Arduino.  You can easily pick up servo motors that work with Arduinos independently of buying an Arduno kit.


text:
How to connect an Arduino with SIM300 and a seperate GPS module?
I am trying to connect an Arduino with SIM300 and GPS module to upload data directly into a database on my localhost using GPRS of the SIM inserted. I am not able to interface the separate GPS and GSM modules. Kindly help in this regard.

If you give more details , that would be helpful. The amount of information you give, it looks like you need a tutorial not an answer.

I am using seperate gps and a gsm module. I am using an A6390 gsm and neo 6m gps module. i want to fetch gps data and uplaod to a local database using gprs through the gsm module

I know I should write this in comment section , but as comment have word limitation and I'm going to give you a idea why this should not be a question and how should you go for your problem, I'm writing it in answer section.Please don't down voted me :p
You miss the point of my comment. This is a forum where you ask about your problem and people try to help you to solve it. It's not a tutorial providing forum. But from you'r question as far as I understand , you want more or less  a full tutorial about your circuit. That's why you are getting down vote.
First you should run your module individually . Here is two YouTube tutorial link for your GPS and GSM modules.
GSM module tutorial
GPS module tutorial
You can look for more tutorials in YouTube and build a besic idea. Then make GSM and GPS module working individually. When individually they work, then add there code and components and run the whole system. This way , it will be easy for you to detect where the problem is. If you'r device fail and you can't find or solve the problem, then ask here.
There is some rules how to ask questions here, follow them. Give total idea about your problem and how far you can debug.If possible, add your code and circuit diagram. Hope we can help you then.

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


text:
Generating PWM using Arduino Uno and Simulink (interfacing) pins 5 and 6. What's the maximum frequency?
I am building a boost converter using a mosfet. The mosfet is driven by PWM generated by an Arduino Uno through Matlab Simulink. In Simulink I am giving 10 KHz pulse width 50%. Practically 10 KHz available at pins 5 and 6. Up to how much frequency can pins 5 and 6 handle?

I think the maximum frequency is 4MHz. I wouldn't use pins 5 and 6, as those use timer0, which is already used by millis and delay. You'd better of using pins 9 and 10 which use timer1.

https://www.arduino.cc/en/Reference/AnalogWrite

Just posting a link isn't very useful. What do you mean?

in the above link it states The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz

The implementation of analogWrite uses 490 and 980 Hz, but that doesn't mean you can't use other speeds. You can use a smaller prescaler for the timer being used.

pin 9 and 10 can handle frequency of 10khz.?

Yes. Though you'd have to tweak some of the registers to get this exact frequency. If the frequency doesn't need to be exact you could just change the default /64 prescaler to e.g /1 to get around 30kHz.

PS the maximum PWM frequency is actually 8MHz.

highest frequency achivable using arduino while serially communicating.?

Still 8MHz.....

How much frequency do you need and how many bits of PWM resolution do you need?

1okhz  is designed for boost converter

See my page about timers. The maximum frequency the hardware can output is 8 MHz if you are running a 16 MHz clock.
10 kHz should be easily achievable if you tweak the hardware registers, as Gerben said.

Up to how much frequency can pins 5 and 6 handle?

here is a way for you to find out:
1) pin 5/6 are OC0A and OC0B -> two output compare pins tied to timer0
2) go to the datasheet and timer0 is a 8-bit timer, with a few pwm modes who top out at 0xff or OCR0A -> useless for your application.
So the theoretical but useless answer is 16Mhz/2, at 1:1 prescaler.
the more practical answer is 16Mhz / 256, at 1:1 prescaler.
with that said, some AVRs (ATtiny25/45/85 for example) can run in asynchronous modes generating incredibly high PWM with very little outside help.
if generating high speed pwm is your thing, check them out instead.


text:
Does IDLE Mode not power down an ATtiny85?
So I'm trying to power down my ATtiny85 to save power, but for some reason the ATtiny doesn't power down when I'm using the default IDLE mode, but when I start using the SLEEP_MODE_PWR_DOWN the ATtiny appears to go to sleep.
I'm testing it by calling a checkPower() method that blinks an LED after the sleepNow() method. In other words, if the ATtiny goes to sleep then the checkPower() method should not be reached and the LED should not blink. Here is the code:
void loop()
{
  doStuff();
  sleepNow();
  checkPower();
}

void sleepNow()
{
    // Choose our preferred sleep mode:
    set_sleep_mode(SLEEP_MODE_IDLE);
    // Set sleep enable (SE) bit:
    sleep_enable();
    // Put the device to sleep:
    sleep_mode();
    // Upon waking up, sketch continues from this point.
    sleep_disable();
}

void checkArrays()
{
  for(i = 0; i < 15; i++)
  {
     digitalWrite(1, HIGH);
     delay(1000);
     digitalWrite(1, LOW);
     delay(1000);
  }
}

Any idea why my LED would continue to blink when using the IDLE mode but no the PWR_DOWN mode?

In IDLE mode the timers still run. Arduino uses timer0 for millis. So when timer0 overflows the ATTiny will wake up and call the ISR.
So the ATTiny will go to 'sleep' but wake up a number of microseconds later.

So what can I use besides IDLE? If I try PWR_DOWN I won't be able to use an interrupt to wake the microprocessor. Is there an alternatice. Also how long does IDLE make the ATtiny sleep?

You can wake from power down using either a pin change interrupt or a watchdog timer interrupt.

@IsabelAlphonse: IDLE is fine. You just have to check, whenever you wake up, if there is job to do. If not, just go back to sleep.

As bigjosh said, pin change and watchdog timer interrupts will wake the processor from power-down. See my page about power - not specifically about the Attiny85, but the same processor family.


text:
Detecting distance moved by accelerometer?
I have an accelerometer connected to an Arduino Uno board, is there a way I can detect the distance it this accelerometer moved on each of the 3 axis?

No, not with any meaningful accuracy, as has been previously explained each of the many times this has been asked on the various stack exchange sites.

Check out the way I calculated the distance traveled by an elevator using the ADXL345. It's not the most accurate or even easy, but I go through the whole process on my blog: https://engineersportal.com/blog/2017/9/25/accelerometer-on-an-elevator Let me know if you have any questions!

This is normally referred to as Dead Reckoning.  The processes of determining position using known values, such as acceleration.
First we have to relate acceleration, velocity and position mathematically.  Velocity is the integral of acceleration with respect to time:

Similarly, position is the integral of velocity with respect to time:

Here is an explanation that should tie this all together.  However, it appears this explanation goes in the reverse order.  That is using derivatives of position to find velocity.  And derivatives of velocity to find acceleration.  Simply put, finding a derivative is the opposite process of finding an integral.
A final note, this all works well on paper.  In reality Dead Reckoning based only on acceleration does not work very well.  For instance, I believe most vehicle GPS systems tend to use steering and speed if Dead Reckoning is to be used for guidance.
Added later...
Found this web site where someone talks specifically about Dead Reckoning using an Arduino. He is simply using the deltas of filtered acceleration readings:
velocity(i) = velocity(i-1) + acceleration (i)
position(i) = position (i-1) + velocity (i)

But goes on to say accumulated errors causes drift and positioning errors.

Comments are not for extended discussion; this conversation has been moved to chat.

Think about it:

Accelerometers measure acceleration.
Acceleration is a change in speed.
Distance travelled is speed multiplied by time.

If you know the starting speed (e.g., stationary) and you know how much you have accelerated between two points in time you can calculate the average speed for that time period - and since you know the time of that time period (one would hope) then you can get an approximation of the distance travelled in that axis.
I say approximation, because you are working with finite time points (quanta) and only looking at the acceleration at those points in time. It's far from perfect, but it can give you a rough ballpark figure. The smaller your quanta the better your accuracy - but it will never be anything more than a guestimation at best.
Now it's just, as they say, a SMOP.

Distance is the double integration of acceleration.

I downvoted this because it suggests you can get "an approximation" or "rough ballpark figure" when in reality you're not going to get anything useful out of this approach. The most important issue is that any inaccuracy in your acceleration measurement is going to blow up massively when you integrate to get position.

@TomvanderZanden I mentioned that it was a guestimation at best...  A guestimation, by the way, is worse than an estimation. An estimation is based on good data - a guestimation is based on guesswork, so is quadruply inaccurate. The link to SMOP is of course supposed to discourage the OP from taking this route since the programming would be outside his ability sphere.

@TomvanderZanden you still get usable figures depending on what precision you expect. And you can increase the quality using other sensors and filtering data. The dead reckoning technique can get extremely complicated, but the accelometric input is the base of most


text:
Issue with IF statement condition
I am using 2 accelerometers connected to an arduino. The code below does not work.
> if((acc1 >= 20 && acc1 <= 40) && (acc2 >= 20 && acc2 <=40)) //If acc1 is between 20 and 40 AND if acc2 is between 20 and 40
>     {
>         digitalWrite(13, HIGH);
>     }

But, the following code does:
> if((acc1 >= 20 && acc1 <= 40)) //If acc1 is between 20 and 40
>     {
>         digitalWrite(13, HIGH);
>     }

Can anyone tell me why please?
Edit with full code:
const int acc1_xPin = 0; //X Pin on acc1
const int acc1_yPin = 1; //Y Pin on acc1
const int acc2_xPin = 2; //X Pin on acc2
const int acc2_yPin = 3; //Y Pin on acc2

int xAcc1_maxVal = 409; //Maximum value for X-axis Acc1
int xAcc1_minVal = 269; //Minimum value for X-axis Acc1
int yAcc1_maxVal = 410; //Maximum value for Y-axis Acc1
int yAcc1_minVal = 270; //Minimum value for Y-axis Acc1

int xAcc2_maxVal = 411; //Maximum value for X-axis Acc2
int xAcc2_minVal = 268; //Minimum value for X-axis Acc2
int yAcc2_maxVal = 402; //Maximum value for Y-axis Acc2
int yAcc2_minVal = 263; //Minimum value for Y-axis Acc2

//Hold Calculated Values
double acc1; //acc1 angle
double acc2; //acc2 angle

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {

  int acc1_xRead = analogRead(acc1_xPin); //acc1 X-axis
  int acc1_yRead = analogRead(acc1_yPin); //acc1 Y-axis
  int acc2_xRead = analogRead(acc2_xPin); //acc2 X-axis
  int acc2_yRead = analogRead(acc2_yPin); //acc2 Y-axis

  //convert read values to degrees -90 to 90 - Needed for atan2
  int acc1_xAng = map(acc1_xRead, xAcc1_minVal, xAcc1_maxVal, -90, 90);
  int acc1_yAng = map(acc1_yRead, yAcc1_minVal, yAcc1_maxVal, -90, 90);
  int acc2_xAng = map(acc2_xRead, xAcc2_minVal, xAcc2_maxVal, -90, 90);
  int acc2_yAng = map(acc2_yRead, yAcc2_minVal, yAcc2_maxVal, -90, 90);

  //Caculate 360deg values like so: atan2(-yAng, -zAng)
  //atan2 outputs the value of -π to π (radians)
  //We are then converting the radians to degrees
  acc1 = RAD_TO_DEG * (atan2(-acc1_yAng, -acc1_xAng) + PI); //acc1 in degrees
  acc2 = RAD_TO_DEG * (atan2(-acc2_yAng, acc2_xAng) + PI); //acc2 in degrees

  if((acc1 >= 20 && acc1 <= 40) && (acc2 >= 20 && acc2 <= 40))
  {
    digitalWrite(13, HIGH);
    Serial.println("HIGH");
  }
  else if ((acc1 >= 41 && acc1 <= 60) && (acc2 >= 41 && acc2 <= 60))
  {
    digitalWrite(13, LOW);
    Serial.println("LOW");
  }

  Serial.print("Acc1: ");
  Serial.print(acc1);
  Serial.print(" Acc2: ");
  Serial.print(acc2);
  delay(1000);

}

I'd really appreciate any input as to way the if statements are not working when I have 2 conditions in them but will work when I have 1 condition.
Edit:
I have corrected the typos in the code. My laptop gave up on me last night so I had to retype the code on a friends laptop, hence the typos and why I didn't post the whole code initially.
The IF statements still don't work as stated above when the 2 conditions are in the IF statements together, but when I only put 1 condition in, it works fine.

Because acc2 is never between 20 and 40 at the same time that acc1 is?

@Majenko That makes no sense. They are 2 separate sensors so why can't they be between 20 and 40 at the same time?

I don't know. Maybe something else in your program, or in your setup, is stopping them being both between 20 and 40 at the same time.

I have also put in code to check their values outside the if statement and they are between those values at the same time. I am not getting any errors when I use either if statement

Please post your entire code and a description or schematic of your setup. At the moment all we can do is wildly stab in the dark which is of no use to anyone.

Why test: acc2 >= 41 && acc2 >= 60 ? Surely testing for >= 60 would do? Because that is also >= 41.

would this work? if ((20<=acc1<=40) && (20<=acc2<=40))

I actually got it working. I added extra brackets to it. Eg: if(((acc1 >= 20) && (acc1 <= 40)) && ((acc2 >= 20) && (acc2 >= 40))) this seems to have worked. Thanks for your help

Excellent. Glad to hear. good luck

I think this is your problem (from the full code snapshot)
(acc2 >= 20 && acc2 >= 40))

I believe it should be (like your first snapshot)
(acc2 >= 20 && acc2 <= 40))

Note that the first is greater than or equal to 40 rather than less than or equal to. Also note you've done this when determining whether or not acc2 is between 41 and 60 in the else if part of that same if statement.
I have no idea why the code differs between your first and third snapshot. Potentially you have spotted this already and failed to update the full code being run?

I have corrected the typos in the code. My laptop gave up on me last night so I had to retype the code on a friends laptop, hence the typos and why I didn't post the whole code initially. The IF statements still don't work as stated above when the 2 conditions are in the IF statements together, but when I only put 1 condition in, it works fine.

Can you tell us what the values of acc1 and acc2 are when you are testing? They aren't negative? Can you also elaborate on what you mean by not working, I assume you just never see the LED on pin 13 be driven high? Maybe put some serial output inside the if statements too to rule out any possible hardware gremlins

When testing if Acc1 and Acc2 are between the values at the same time, I have put in Serial.println("HIGH") and Serial.println("LOW") within the IF statements but they are not coming up on the serial monitor when the 2 conditions are within the IF statements. So if I have (acc1 >= 20 && acc1>= 40) within the If statement it will work but if I have ((acc1 >= 20 && acc1>= 40)&&(acc2 >= 20 && acc2>= 40)) within the statement, the serial monitor just shows the values and 'HIGH' or 'LOW' does not appear even though I can see both acc1 and acc2 are within the values at the same time

The code you have sent in your comment
((acc1 >= 20 && acc1>= 40)&&(acc2 >= 20 && acc2>= 40))
is wrong. This will only execute when both are above 40 not in between the 20 and 40.
Can you update your code in the OP to represent what you are actually running.

Sorry, it should b: ((acc1 >= 20 && acc1<= 40)&&(acc2 >= 20 && acc2<= 40)) and the other one should be (acc1 >= 20 && acc1<= 40). I actually have it correct in the code in the main question.

Your code has the following lines:
acc2 = RAD_TO_DEG * (atan2(-acc1_yAng, -acc1_xAng) + PI); //acc1 in degrees
acc2 = RAD_TO_DEG * (atan2(-acc2_yAng, acc2_xAng) + PI); //acc2 in degrees

If I'm going to believe the comments, the first line should start:
acc1 = ...

That doesn't fully explain: they are between those values at the same time.

Agreed - but it can't help! If acc1 meets the criteria when it isn't even initialised, then the formula could be wrong for both. He might see the arm with those angles, but maybe it comes out negative in the formula or something

It's odd that his full code is nothing like the snippets in the original question. :)

I have corrected the typos in the code. My laptop gave up on me last night so I had to retype the code on a friends laptop, hence the typos and why I didn't post the whole code initially. The IF statements still don't work as stated above when the 2 conditions are in the IF statements together, but when I only put 1 condition in, it works fine.


text:
Calibrating ESC and then using it
i have 30Amp ESC which i can move motor by providing values ,
but i am unable to know what is the minimum and maximum throttle speed of the motor....
how to achieve that level of info through arduino,
although when i calibrate through Open pilot software ,it is able to calibrate and the minimum value is 1500ms ..
Also after calibrating it once , do i need to arm everytime before using ESC in the arduino program through serial input ?

What values? How do you provide them? What ESC? What everything basically...?

Used this code -
/*
Coded by Marjan Olesch
Sketch from Insctructables.com
Open source - do what you want with this code!
*/
#include <Servo.h>

int value = 0; // set values you need to zero

Servo firstESC, secondESC; //Create as much as Servoobject you want. You can controll 2 or more Servos at the same time

void setup() {

  firstESC.attach(9);    // attached to pin 9 I just do this with 1 Servo
  Serial.begin(9600);    // start serial at 9600 baud

}

void loop() {

//First connect your ESC WITHOUT Arming. Then Open Serial and follo Instructions

  firstESC.writeMicroseconds(value);

  if(Serial.available())
    value = Serial.parseInt();    // Parse an Integer from Serial

}

the problem was when i was connecting the battery , it was not making any sounds...it was already calibrated by open pilot GCS so it was not calibrating again... i needed to reset the ESC and then run this program from arduino

If this sketch solved you problem, you should accept the answer; If you tried this and are still stuck, it should put in an edit to your question.


text:
Distance finder technology 0-24inches
Can anyone point me towards whats best for relatively low cost distance measuring in the 0-36" range (or 0 - 1m range) with 1/16"/1mm accuracy.  My initial approach was going to be to hack a laser tape measure, but wanted to know if that was the best in cost vs accuracy.
Essentially looking to measure how close I am to a stationary metal plate.
Thanks for any help.

Most "laser" tape measures are merely a laser pointer strapped to an ultrasound range finder. Ultrasound is by far the simplest and cheapest option though its accuracy can sometimes be a little "iffy".

Your suggestion regarding "most" is an invalid generalization and inaccurate as well. Laser rangefinders use lasers, ultrasonic rangefinders use ultrasound, with perhaps a laser indicator for aiming, but it is necessary only to read the product specifications to determine the method of use.

@fred_dot_u If a "laser tape measure" is cheap enough to be destined for hacking then it's using ultrasound. All the "laser tape measures" I have ever seen at DIY stores, or have ever owned, or have ever used, have been ultrasound. Yes, there are laser based range finders, but they are considerably more expensive and outside the "hackable" price bracket.

http://www.dx.com/p/uni-t-ut390b-45m-laser-distance-meter-178482#.V2q--6IiXQo
Granted, it's out of stock, but fifty-one american dollars is low enough cost to be hacked and it's laser. Fully optical, zero ultrasound. My point was that "most" are not. Some are laser, some are ultrasound. You've added an interesting ambiguity to the equation as well. "Cheap enough" is difficult to pin down. Fifty or one hundred dollars is cheap enough if someone has enough motivation and can make a project work. Two hundred dollars is cheap enough if success is a certainty. All this is opinion, of course.

You will likely find the best accuracy is derived from a laser-based measurement. My Bosch is laser only, no ultrasound component and has 1/16" resolution. For your application, the six inch minimum distance limitation of the Bosch is outside your specifications.
Because laser measurement devices use time versus distance, it's possible you could construct a mirror chamber with front-surface mirrors that would cause the laser to travel six inches before exiting the chamber, overcoming that limitation. The calibration should be straight-forward, as you'd place the chamber flush and adjust your mirror placement until you read the exact expected compensation distance.
You would need only small mirror panes, which would not "break the bank," but if you find a discarded large-screen projection television, the mirror within is front surface and quite large. Front surface mirrors should not have contamination from touching and should be cleaned with care, as you can erode or otherwise degrade the reflective surface.
I found this site:
http://blog.qartis.com/arduino-laser-distance-meter/
which looks promising for a different model of laser rangefinder, although the creator has run into a stumbling block or two.
It would appear that the key is to overcome the minimum distance limitation, perhaps as I suggested above, and interfacing with serial communications of the arduino.
One of the links I pursued involved the creator contacting the technical support of the manufacturer. The support ticket was closed as "resolved," in the manner of advising the user that the warranty was void by opening the case. Yeah, like that matters to makers and hackers!

Thank you very much for this.  I really like the idea of overcoming the limitation by using a mirror chamber. I wonder why most manufacturer's do not.

Consider how much labor you might put into building a mirror chamber, as well as the effort in calibrating/tuning the light path. A manufacturer may not be able to design and build something that works for Joe Consumer, but we maker-folk are pretty resourceful. What cost is your labor when you are creating? For some of the stuff I build, for the fun and experience, it appears that I'm paying people to do this kind of work. But then again, what price is fun?

If you have a 3d printer or access to one, you could design a mirror chamber in which to glue or slide the mirror segments as well as include a compartment for the Arduino, although the image in my alleged mind may not match yours, as I do not know the precise application.


text:
Not able to upload program to "Arduino Due"

I'm not able to upload sketch on Arduino Due, using Programming Port.
Even blink sketch from examples is not working. So tried with blank sketch, I got following messages.

Are you sure that the COM port is precisely set?

If its not you COM port being set wrong or in use by something else then have you tried the old favourite of uninstalling the IDE and reinstalling it, just in case something has got messed up?

Upgrade to 1.6.9. There have been a number of changes in the upload system in the recent versions that have both broken and fixed things.

Go to device manager, and make sure that you can see the change in your com ports when you unplug and plug the Arduino into your computer.
You may also have to follow the instructions here: https://www.arduino.cc/en/Guide/Cores
I will also occasionally find that uploading won't work when I have something external connected to the RX,TX,3.3 and 5V, and GND pins.
It also helps to go to File-Preferences- and enable both options for "Show verbose output during". If you do that and post the output, we might have a better idea as to what is going wrong.

There is no FTDI chip on a due. How will installing the FTDI drivers help?

I didn't even see that he was using a DUE! To the OP- if you're using an IDE that's newer than 1.6.2, you may have to follow the instructions here: https://www.arduino.cc/en/Guide/Cores


text:
Arduino as an automation controller
I am considering using an Arduino as a controller for a water treatment system and would love to hear your opinions. All it has to do is open/close a water gate (by starting/stopping a motor) at predefined times. It would have to...

Be able to connect to a phone using a usb cable. The phone would act as a UI to change settings and water flush times on the Arduino (via a custom app)
Log data which would be easily retrievable
Ideally, be able to connect to a cell network and send/receive packets. I believe there is a shield for this
Consume MINIMAL POWER. All it has to do is flush once every few days, log data, and possibly receive data from shield/usb. It would be running off of a solar panel and battery. In winter it could run out of power.

And thats pretty much it! Can this project be done with an Arduino? I would greatly appreciate any advice and recommendations!

Where's the power for the motor coming from? Staying on the cellphone network 24/7 would consume quite a lot of power (think of your phone and how often you have to charge it). If you have enough power to operate a motor powerful enough to open a gate, there should be some over for the Arduino. See my page about power.

The power for the motor also comes from the the battery(which comes from the solar panel). I'm getting the feeling that power is going to be the limiting factor here... And thank you for that link I feel it will be very helpful!

If there is enough power to run the motor, there is enough power to run the Arduino. If you have a clock chip on board with a lithium cell battery backup (as clock chip boards normally have) then you could survive a few days of insufficient power. When the sun comes out the Arduino can power up, and then decide if it is time to turn on the motor.

Does the arduino do this automatically? Or is this something I will program the avr chip to do?

Do what automatically? Everything it does you need to program it to do.

Does the arduino automatically run on the internal battery when input power is low i mean

I was referring to the clock chip shown in the photo in my answer. Those chips are designed to switch to the clock battery backup if there is not enough power to the chip's Vcc pin. The Arduino however does not have an internal battery.

Have a look at my Temperature and humidity sensor - battery powered. That works from 3 x AA batteries, and has been going for a few years. I think I replaced the batteries once. It keeps track of the time, and logs data to the disk (SD card).

I don't have room to describe the whole project here, but the general idea is that the processor sleeps most of the time (consuming around 6 µA). Now this particular project doesn't turn on a motor, but adding a solid-state relay should be all you need to do that.

Be able to connect to a phone using a usb cable. The phone would act as a UI to change settings and water flush times on the Arduino (via a custom app)

I think this will take a lot of power, keeping the phone active. One possible thing to try would be to power up the phone (eg. using another relay) during a certain "window" of time (eg. 6 pm to 7 pm). Then you would know to try to configure the device during that time.

I was thinking of having an app that people could download, then when they went to the site plug in their phone to the arduino there. It seems like it could be a way to avoid having a display running, except when somebody connects their phone. It would be very power intensive when connected though

If they are going to be onsite anyway, some sort of configuration screen might be easier. Eg. a LCD display to show various options, and a keypad to enter data.

So first of all, if the voltage of your systems is too high, arduino cannot provide that on its own. Arduinos can only provide 5v out with the rail. So you could use a relay shield, an add on board to stack on top of it, or just plain old relays with some soldering. Now, for connectivity, try this thing. http://www.annikken.com/andee/ It is relatively easy to learn, and you can build a decent UI without the need for coding an app. I think you can get them for ~30$. However, I do not know how well the arduino can run with so many shields. For data logging, a few companies make data logging shields, or you can get an external read/write and wire it up. I have a small, probably 3" by 8" solar panel for my arduino and it is quite unreliable even in low power applications. However, if you have a good one, that is cool. Best of luck -Peter

I have not had a chance to play with the battery yet, so I don't know what I will need. I will keep the relay shield in mind. The andee shield looks interesting too I'll check it out!


text:
Average response time of Esp8266 module
I'm planning a project where I'd like to control an RC car with Arduino and an Esp8266 module.
A software running on a computer would read the input from an USB analog controller and send the data to the Esp8266 module through the wifi network, and the Arduino would read this data and send signal to the ports accordingly.
What I'd like to know is: would ping/delay be an issue? Considering a dedicated wifi network for this, so the only devices connected to it would be the computer and the Esp8266 module.
I need to know what is the average response time of the Esp8266 module before I buy it, because if it is too high I'll think of something else since for this project I'd need a reasonably high response time.

we can't say what your "average response time" will be, because it depends on your physical environment and how many other wifi devices you are surrounded by that are on (or close to) the channel you choose. My opinion is, as you are only using the ESP as a serial-to-wifi bridge, there are better devices you can attach to an arduino for radio communication - although this would make the (sending) computer side more complicated

I'm pretty sure it can be made to work.
I have a home server with several devices attached to it, including 2 ESP8266 modules - one at home and one in my office. All devices connect using permanent TCP connection and respond to my custom "ping" requests over that connection. Typical round-trip response times are bellow 50ms and often bellow 10ms. There are occasional "hickups" of 100+ms, but they are rare and could be a result many factors. Note that these 2 ESPs are programmed in Lua, which is not optimal efficiency - I was just lazy and the tasks they do are simple enough to not matter.
Most probably if you start an HTTP server on the ESP and bombard it with HTTP requests every time you move the joystick it would be horribly laggy. But with a plain old TCP connection or even a consistent flow of UDP packets I'm pretty sure you will get good results.
Also, I would ditch the Arduino and use only the ESP - you should have no problem controlling two motors (most probably via motor driver board or chip) and perhaps a servo from the ESP directly. This would eliminate the additional lag of serial communication and parsing the serial data. It would also reduce the cost and size of the project.
Having that said, other solutions, like bluetooth or even RF modules should also work, but you asked whether the ESP can do it - and my answer is yes.

It was a bit tricky since both answers were stating two different things. I'm going to accept yours because the TCP connection hint was a big help. My module is coming this week, so I'm finally going to be able to test it out. Unfortunately bluetooth is out of the question, since I need analog input for the speed control, and bluetooth analog controllers are quite pricey.

I think response time would be a big problem. I used the ESP8266 with a temperature and humidity sensor, complete with a small web server on the ESP8266, and it works fine. But I wouldn't want to control an RC car with it. But if you buy it on ebay from China, it is only a few dollars, so buy one anyway.
Use Bluetooth, either a couple of HC-05 modules, or the Bluetooth Low Energy HM-10 modules. Both can communicate at 115200 baud. The HM-10 modules may be a bit tricky, because some Chinese sellers put a stripped down version of firmware on the module, and forces you to search online how to flash a usable firmware version.

If you use websocket it will have a really good response time.
It is a test about it:
https://www.youtube.com/watch?v=8ISbmQTbjDI
I use it for a quadcopter controller.


text:
Strange RPM Readings on Teensy 3.2
While trying to read RPM from a computer fan using the 4-wire protocol, I am getting strange readings. +12 and GND from the fan are connected to a power supply, and the tachometer to the PIN-0 or a Teensy 3.2.
I wrote code to read the tachometer pulse using the internal pull-up and interrupts. The strange thing happening is that the number of recorded revolutions is increasing as I manually slow the fan using my fingers.
Here is the code :
#include <avr/io.h>
#include <avr/interrupt.h>
#include <elapsedMillis.h>

const int fanPulse = 0;
volatile long half_revolutions;
elapsedMillis timeElapsed;

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

  pinMode(fanPulse, INPUT_PULLUP);
  attachInterrupt(fanPulse, rpm_fun, FALLING);

  half_revolutions = 0;
  // analogWriteFrequency(20, 25000); // Teensy 3.0 pin 3 also changes to 375 kHz
}

void rpm_fun() {
  half_revolutions++;
}

void loop() {
  if (timeElapsed < 1000)
    return;

  Serial.printf("%d revolutions in %d miliseconds\n", half_revolutions / 2, (unsigned long)timeElapsed);

  timeElapsed = 0;
  half_revolutions = 0;
}

Here is the strange output :
0 revolutions in 1000 miliseconds  // Start
0 revolutions in 1000 miliseconds
82 revolutions in 1000 miliseconds
394 revolutions in 1000 miliseconds  // "normal" reading
412 revolutions in 1000 miliseconds
576 revolutions in 1000 miliseconds
456 revolutions in 1000 miliseconds
554 revolutions in 1000 miliseconds
585 revolutions in 1000 miliseconds
799 revolutions in 1000 miliseconds  // Slowing the fan
712 revolutions in 1000 miliseconds
691 revolutions in 1000 miliseconds
683 revolutions in 1000 miliseconds
625 revolutions in 1000 miliseconds
531 revolutions in 1000 miliseconds
239 revolutions in 1000 miliseconds
0 revolutions in 1000 miliseconds
0 revolutions in 1000 miliseconds  // End

I must have misread what you have written.  Why do you think these readings are strange?  I would expect that as you slow the fan the number of revolutions per second goes down and that's what the results seem to say.

Did you connect the ground of the Teensy to the ground of the fan?

Matt, I get around ~450 rpm in normal conditions and around ~650 rpm when slowing down.
@Majenko, No I didn't, I was thinking this might be the issue too. My Teensy is powered through USB and the Fan to an external power adapter, is it safe to connect the two ground?
Andy, the 0 rev cycles are the moment where I manually switched off the external power adapter with a switch.

You have to have the grounds connected, otherwise you are just measuring noise.

@Majenko, make that an official response and you'll get a resolving answer! Thanks to all.

Without the ground of the teensy connected to the ground of the fan all you will be measuring is noise. Ground is required to complete the circuit between the teensy and the fan.