text:
Writing "theremin" outputs to a MIDI file on an SD card
I am making a musical instrument (theremin simulator). I want there to be a "record" capability which stores the volume and note the user is playing, into a MIDI file. Note this doesn't actually record audio, just data for the frequency and volume at a certain point in time.
So far I've done some research and have found how to play MIDI files (which is useful and I plan to take this on as well) and read/write to SD cards. However I haven't found a source which allows me to create and produce MIDI files.
How should I accomplish this feature?
Specs:

I am using an Arduino Nano, I have an Uno too if needed
The SD card is a 64GB micro SD, inserted into an SD adapter, with header pins soldered onto it. (I am too cheap to buy an actual shield)
It was previously XCSD, I formatted it to FAT32 to be compatible with Arduino

Also: I am recording from a self built replica of a theremin, which is basically two ultrasonic sensor readings for volume and pitch. Is this "too basic" for a MIDI file type? (Edit: I guess this is too advanced)
EDIT: This project has been abandoned because of no good way to play between semitones (i.e. at specific frequencies), which is what I need for my theremin. Although there is the pitch bend functionality, the amount of pitch bend translates to different frequency changes based on the receiver.
Instead, I will create my own custom file to achieve the record/playback, because using the pitch bend + note method using MIDI is just too much work and it won't be compatible with other devices anyway.
Nick Gammon's answer is really thorough for those who only need to record/play specific tones and semitones in MIDI format.
Thanks

Learn the syntax of a properly constructed MIDI file and write the Arduino sketch to create the file on an SDCard.  This may be easier said than done as I suspect an artist seldom plays a musical phrase the exact same way twice.

@st2000 Why would it matter if they play it differently another time? Record what they actually played. What they might play another time is irrelevant.

Which Arduino do you have in mind? There are quite a few these days.

You are correct @MarkSmith.  WRT MIDI recordings, I always want to commit the recording to sheet music.  As such, I'm constantly thinking in terms of "what is a quarter note". Similar to your auto's GPS snapping you to the nearest road despite your actual location.  If that is not needed here - they you are correct - just record what is played and play it back.

Updated the question with specifications.

I just want to record whatever is being played.

@st2000 I tried to learn the syntax by downloading a MIDI file from online, and reading them with a text editor. The text wasn't even letters so I just gave up on that.

If anyone has done it before, I guess I can take the time to read about MIDI syntax. If the music is simple, is it possible to do it with no encoded characters?

I did it before, and it is not complicated at all. Only thing that took me some time to understand is the way how the "time" is encoded in midi files. Take a look here, someone was building simple midi file from scratch in hex editor

If you don't have a SD card interface then I hope you are using level shifters for the data lines. Like this: http://www.gammon.com.au/images/Arduino/Micro_SD_breakout.png The chip on the right does the level shifting.

@NickGammon What exactly does level shifting do? I am using SPI interface for communication, and resistors in voltage regulators to drop it to 3.3V. I basically made it from this: https://nathan.chantrell.net/20111128/diy-micro-sd-shield-for-arduino/

Level shifting is catering for (say) running a 3.3V device from a 5V device. Your resistors, acting as voltage dividers, will reduce the 5V down to 3.3V. That device is relying upon the Arduino recognising 3.3V as HIGH which is slightly an edge case (the minimum for HIGH is 3V if you are running at 5V). A proper level shifter actually shifts 3.3V up to 5V, and 5V down to 3.3V depending on which way the signal is travelling. You can buy them fairly cheaply, or make them: http://www.hobbytronics.co.uk/mosfet-voltage-level-converter

Thank you for the explanation, I will look into this as well, although what I have seems sufficient for the time being.

The short answer would be "yes, it is possible". There are lots of gadgets around that record MIDI. They would have microprocessors in them, and they would have something like an SD card, which itself is like EEPROM in concept.
You may possibly have problems with storing the notes in RAM, and then writing them to the SD card fast enough not to lose some. Knowing the rate at which notes would arrive, the speed of the SD card, and the type of Arduino would help to answer if your specific case was likely to work.
I wrote a sketch that reads MIDI which shows that it is certainly possible to receive MIDI data and display it. Video of it running is here.
I don't personally know the format of MIDI files, but it is well documented.
(Edit) I do now - see further down.
Writing to SD cards is well documented. Making your idea work would be a case of taking stuff (like my code to decode MIDI), code to write to SD cards, and knowing the correct format.

(Edited to add)
See Standard MIDI-File Format Spec. 1.1 for an example of producing MIDI data. Also see The MIDI File Format and the Standard MIDI File (SMF) Format
Your basic technique would need to be (as suggested by gabonator):

Write a header chunk to the file, for example:
  4D 54 68 64   // MThd
  00 00 00 06   // chunk length
  00 00         // format 0
  00 01         // one track
  00 60         // 96 pulses per quarter-note

Write a track chunk to the file (the length will be updated later)
  4D 54 72 6B   // MTrk
  00 00 00 00   // <-- length to be updated later

Write instrument configurations (with time delta values of zero), as an example from that page:
  00  FF 58 04  04 02 18 08  // 4 bytes; 4/4 time; 24 MIDI clocks/click,
                             // 8 32nd notes/ 24 MIDI clocks
                             // (24 MIDI clocks = 1 crotchet = 1 beat)
  00  FF 51 03  07 A1 20     // 3 bytes: 500,000 µsec/ quarter note
                             // = 120 beats/minute (500000 in hex is 0x07A120)
  00  C0 05                  // Ch.1 Program Change 5 = GM
                             // Patch 6 = Electric Piano 2

When the player plays something, subtract the time that s/he last did something from the time now. This will give you the delta time.

Convert the time difference to ticks. From the header line above we have 96 pulses per quarter note (PPQ), and 500,000 µs (500 ms) per quarter note. Thus one second would be two quarter notes (2 beats per second, and therefore 120 beats per minute) and one second is therefore 192 ticks). Therefore the number of ticks, based on the time difference in milliseconds, would be:
  unsigned long ticks = (time_difference * 192) / 1000

Output the delta time as a variable length number, where the high order bit is set for each byte, as necessary, until what is left is <= 0x7F. The page above gives sample code for that. For example, for a delta time of 199 ticks:
  Decimal time of 199 ticks -> 0xC7
  0xC7 -> 0b11000111
  Since that exceeds 127, split into two bytes:

  10000001  (the high order bits)
   ^^^^^^^  <- high order bits (the MSB must be one)
  01000111  (the low-order 7 bits)
   ^^^^^^^  <- low order bits (the MSB must be zero)

  Result is 0x81 0x47

Longer times may require even more bytes.
Something like this should do it (adapted from the linked page). Just change the Serial.write line to output to your disk file.
  void WriteVarLen (unsigned long value)
    {
    unsigned long buffer;

    buffer = value & 0x7f;
    while ((value >>= 7) > 0)
      {
      buffer <<= 8;
      buffer |= 0x80;
      buffer |= value & 0x7f;
      }

    while (true)
      {
      Serial.write (buffer & 0xFF);
      if (buffer & 0x80)
        buffer >>= 8;
      else
        break;
      }
    }   // end of WriteVarLen

Follow the delta time immediately by the "note on" or "note off" byte (depending on whether they started or stopped playing a note). For example, "note on" for channel 1 would be 0x90 because 0x9n is a note on command and n is the channel number, zero relative. A "note off" for channel 1 would be 0x80.

Follow the "note on" or "note off" by the note number (in other words, which note was just played or released) - one byte.
  Octave #  Note Numbers in decimal
            C   C#  D   D#  E   F   F#  G   G#  A   A#  B
  -1         0   1   2   3   4   5   6   7   8   9  10  11
  0         12  13  14  15  16  17  18  19  20  21  22  23
  1         24  25  26  27  28  29  30  31  32  33  34  35
  2         36  37  38  39  40  41  42  43  44  45  46  47
  3         48  49  50  51  52  53  54  55  56  57  58  59
  4         60  61  62  63  64  65  66  67  68  69  70  71
  5         72  73  74  75  76  77  78  79  80  81  82  83
  6         84  85  86  87  88  89  90  91  92  93  94  95
  7         96  97  98  99 100 101 102 103 104 105 106 107
  8        108 109 110 111 112 113 114 115 116 117 118 119
  9        120 121 122 123 124 125 126 127

Typically middle C is considered to be C4 (C in the 4th octave), however apparently that can vary between devices.

Then output the velocity (one byte). A velocity of (decimal) 32 would be soft, 64 would be medium, 96 would be loud. The range for velocities is 0 to 127.

Repeat the above (except for writing the chunks and the configuration) until the player decides to stop playing.

Write an "end of track" marker:
  00  FF 2F 00    // Delta time zero, end of track

Then seek back to the start of the file + where the length bytes are (18 bytes into the file by the looks of it) and update the length bytes (4 bytes).

Example of producing a MIDI file
This example code writes out a MIDI file. As an input device I used a 16-key keypad like this:

The columns were connected to pins 0, 1, 2, 3 of the Arduino Uno, and the rows to pins 4, 5, 6, 7. This makes the ribbon cable from the keypad keep the pins in a natural order. If you use different pins just change the keys array in the sketch.
The library for keypads that I used is available at https://github.com/nickgammon/Keypad_Matrix
This particular library supports n-key rollover and key-down and key-up events. That is particularly useful for music, because it lets you hold multiple keys down at once, and the appropriate events will be generated. Obviously you need a key-down event to generate "note on" and a key-up event to generate "note-off".
I laid out the keys like this:
C     C#    D     D#
E     F     F#    G
G#    A     A#    B
Down  Soft  Up    Record

There is a "recording" LED connected to A0 which lights up when you start recording (by pressing the Record button).

Press the Record button again to stop recording and finalize the file. It is important to stop recording properly and not just power off the device, because the length of the file needs to be written near the start.

Press (and hold) Down alongside with another note to play an octave lower. Press (and hold) Up alongside with another note to play an octave higher.

Press (and hold) Soft alongside with another note to play at a softer velocity.

Using a keypad matrix is logical, because most keyboard devices would use a matrix, to reduce the number of wires you have to run.
Note that the matrix needs diodes wired for each switch as described here because otherwise if you press 3 or more keys at once you will get "ghost" keys.
In my case I opened up the commercial keypad and soldered in the diodes.

I also used a Micro-SD breakout adapter, connected to the SPI pins of the Arduino, like this:

The SDFat library was an archived one that I keep here: http://gammon.com.au/Arduino/SdFat-master.zip (2.2 Mb)
Unzip that file, and from within the folders inside it, copy the SdFat folder into your "libraries" folder (which is under your Arduino sketchbook folder - not inside the Arduino application folder). Then restart the Arduino IDE.
The code definitely compiles with that (with a handful of warnings). The later library from https://github.com/greiman/SdFat may be an improvement but I haven't tested that.

To keep track of file numbers I used the EEPROMAnything library, a copy of which can be found at http://gammon.com.au/Arduino/EEPROMAnything.zip
Each time you start a new recording it adds one to the file number, which wraps around to 0000 once it reaches 9999.

If there is an error initializing the file system (eg. no SD card) then the LED blinks slowly. If the file can't be created the LED blinks rapidly.

You can choose a MIDI instrument by changing the line:
const byte PATCH_NUMBER = 4;   // electric piano 1

Code
/*
 Sketch to write to a MIDI file from an instrument.
 Author: Nick Gammon
 Date:   10th May 2018

 Copyright 2018 Nick Gammon.

 PERMISSION TO DISTRIBUTE

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 and associated documentation files (the "Software"), to deal in the Software without restriction,
 including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
 subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 LIMITATION OF LIABILITY

 The software is provided "as is", without warranty of any kind, express or implied,
 including but not limited to the warranties of merchantability, fitness for a particular
 purpose and noninfringement. In no event shall the authors or copyright holders be liable
 for any claim, damages or other liability, whether in an action of contract,
 tort or otherwise, arising from, out of or in connection with the software
 or the use or other dealings in the software.

*/

#include <Keypad_Matrix.h>
#include <SdFat.h>
#include <EEPROM.h>
#include <EEPROMAnything.h>

// For MIDI numbers see: http://www.pjb.com.au/muscript/gm.html
const byte PATCH_NUMBER = 4;   // electric piano 1

const byte RECORDING_LED = A0;

// bottom row changes things
const char DOWN_OCTAVE  = '-';
const char SOFT         = 's';
const char UP_OCTAVE    = '+';
const char RECORD       = 'r';

// how the keypad has its keys laid out
// capital letters are for sharps
const byte ROWS = 4;
const byte COLS = 4;
const char keys[ROWS][COLS] = {
  {'c', 'C', 'd', 'D'},
  {'e', 'f', 'F', 'g'},
  {'G', 'a', 'A', 'b'},
  {DOWN_OCTAVE, SOFT, UP_OCTAVE, RECORD},  // - = down octave, s = soft, + = up octave, r = start/stop record
};

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

// Create the Keypad
Keypad_Matrix kpd = Keypad_Matrix( makeKeymap (keys), rowPins, colPins, ROWS, COLS );

// file system object
SdFat sd;
const byte chipSelect = SS;

// the current file we are recording to
SdFile myFile;
// are we recording right now?
bool recording = false;

const byte MIDI_META_EVENT = 0xFF;
const byte MIDI_SET_TEMPO  = 0x51;
const byte MIDI_TIME_SIGNATURE = 0x58;
const byte MIDI_END_OF_TRACK = 0x2F;
const byte MIDI_PROGRAM_CHANGE = 0xC0;
const byte MIDI_NOTE_ON = 0x90;   // channel 1
const byte MIDI_NOTE_OFF = 0x80;  // channel 1

struct
  {
  char magic [4]; // MThd
  uint32_t length;
  uint16_t format;
  uint16_t tracks;
  uint16_t PPQ;    // pulses per quarter note
  } chunkHeader;

struct
  {
  char magic [4]; // MTrk
  uint32_t length;
  } trackHeader;

unsigned long trackHeaderPosition;
unsigned long timeLastAction;
int           nextFileNumber;

uint32_t changeEndianness32(uint32_t val)
{
  return (val << 24) |
        ((val <<  8) & 0x00ff0000) |
        ((val >>  8) & 0x0000ff00) |
        ((val >> 24) & 0x000000ff);
} // end of changeEndianness32

uint16_t changeEndianness16(uint16_t val)
{
  return (val << 8) | ((val >> 8) & 0x00ff);
} // end of changeEndianness16

void showError (const int delayTime)
  {
  while (true)
    {
    digitalWrite (RECORDING_LED, HIGH);
    delay (delayTime);
    digitalWrite (RECORDING_LED, LOW);
    delay (delayTime);
    }

  } // end of showError

void startRecording ()
  {
  EEPROM_readAnything (0, nextFileNumber);
  if (nextFileNumber > 9999 || nextFileNumber < 0)
    nextFileNumber = 0;

  char name[15];
  sprintf (name, "SONG%04d.MID", nextFileNumber++);

  // open the file for writing
  if (!myFile.open(name, O_WRITE | O_CREAT | O_TRUNC))
    showError (100);  // fast flash - never returns

  // update EEPROM for next time
  EEPROM_writeAnything (0, nextFileNumber);

  recording = true;
  digitalWrite (RECORDING_LED, HIGH);
  memcpy (chunkHeader.magic, "MThd", sizeof (chunkHeader.magic));
  chunkHeader.length = changeEndianness32 (
                       sizeof (chunkHeader.format) +
                       sizeof (chunkHeader.tracks) +
                       sizeof (chunkHeader.PPQ));

  chunkHeader.format = changeEndianness16 (0);
  chunkHeader.tracks = changeEndianness16 (1);
  chunkHeader.PPQ = changeEndianness16 (96);
  myFile.write (&chunkHeader, sizeof (chunkHeader));
  memcpy (trackHeader.magic, "MTrk", sizeof (trackHeader.magic));
  trackHeader.length = 0;   // to be filled in later
  trackHeaderPosition = myFile.curPosition ();
  myFile.write (&trackHeader, sizeof (trackHeader));

  struct
    {
    byte deltaTime = 0;
    byte metaCode [2] = { MIDI_META_EVENT, MIDI_TIME_SIGNATURE };
    byte length = 4;
    byte sig [2] = { 4, 2 };  // 4/4 time (denominator of 2 is 2^2)
    byte clocksPerClick = 24;  // MIDI clocks/click
    byte clocksPerBeat  = 8;
    }  timeSignature;

 struct
    {
    byte deltaTime = 0;
    byte metaCode [2] = { MIDI_META_EVENT, MIDI_SET_TEMPO };
    byte length = 3;
    byte usPerQuarterNote [3] = { 0x07, 0xA1, 0x20 };  // that is: 500000 µs per beat
    }  tempo;

 struct
    {
    byte deltaTime = 0;
    byte message =   MIDI_PROGRAM_CHANGE;
    byte patchNumber = PATCH_NUMBER;
    }  programChange;

  myFile.write (&timeSignature, sizeof timeSignature);
  myFile.write (&tempo, sizeof tempo);
  myFile.write (&programChange, sizeof programChange);
  timeLastAction = millis ();
  } // end of startRecording

void stopRecording ()
  {
  struct
    {
    byte deltaTime = 0;
    byte metaCode [2] = { MIDI_META_EVENT, MIDI_END_OF_TRACK };
    byte length = 0;
    }  endOfTrack;

  // write out "end of track" message
  myFile.write (&endOfTrack, sizeof endOfTrack);
  // find where we are
  unsigned long finalPosition = myFile.curPosition ();
  // go back to where the track header is
  myFile.seekSet (trackHeaderPosition);
  // work out how long the data was (excluding the headers)
  trackHeader.length = changeEndianness32 (finalPosition - trackHeaderPosition - sizeof (trackHeader));
  // update the file length
  myFile.write (&trackHeader, sizeof (trackHeader));

  myFile.close ();
  // ensure flushed to disk
  myFile.SdBaseFile::sync();

  // no longer recording, turn off recording LED
  recording = false;
  digitalWrite (RECORDING_LED, LOW);
  } // end of stopRecording

void writeVarLen(unsigned long value)
{
  unsigned long buffer;

  buffer = value & 0x7f;
  while ((value >>= 7) > 0)
  {
    buffer <<= 8;
    buffer |= 0x80;
    buffer |= value & 0x7f;
  } // end of while

  while (true)
  {
    myFile.write ((byte) (buffer & 0xFF));
    if (buffer & 0x80)
      buffer >>= 8;
    else
      break;
  } // end of while

}   // end of writeVarLen

// turn the keypad code into a note number
byte codeToNote (const char which)
{
  char notes [] = "cCdDefFgGaAb";
  char * pos = strchr (notes, which);
  if (pos == NULL)
    return 0;
  return pos - notes + 60;  // start at middle C (C4)
} // end of codeToNote

// do a note on or note off
void doNoteAction (const char which, const byte action)
{
  // we need to work out how many milliseconds have elapsed
  unsigned long now = millis ();
  unsigned long deltaTime = now - timeLastAction;
  // remember when we did this
  timeLastAction = now;
  // write out the delta time
  writeVarLen ((deltaTime * 192) / 1000);

  // note information
  struct
    {
    byte noteOn;
    byte whichNote;
    byte velocity;
    } playNote;

  playNote.noteOn = action;
  playNote.whichNote = codeToNote (which);
  if (kpd.isKeyDown (DOWN_OCTAVE))
    playNote.whichNote -= 12;  // one octave down
  else if (kpd.isKeyDown (UP_OCTAVE))
    playNote.whichNote += 12;  // one octave up

  playNote.velocity = 64;      // medium velocity
  if (kpd.isKeyDown (SOFT))
    playNote.velocity = 32;    // softer

  myFile.write (&playNote, sizeof (playNote));
} // end of doNoteAction

void startPlaying (const char which)
  {
  doNoteAction (which, MIDI_NOTE_ON);
  } // end of startPlaying

void stopPlaying (const char which)
  {
  doNoteAction (which, MIDI_NOTE_OFF);
  } // end of stopPlaying

void keyDown (const char which)
  {
  switch (which)
    {
    case 'c':
    case 'C':
    case 'd':
    case 'D':
    case 'e':
    case 'f':
    case 'F':
    case 'g':
    case 'G':
    case 'a':
    case 'A':
    case 'b':
      startPlaying (which);
      break;

    default:
      break;
    } // end of switch on which key
  } // end of keyDown

void keyUp (const char which)
  {
  switch (which)
    {
    case RECORD:
      if (recording)
        stopRecording ();
      else
        startRecording ();
      break;

    case 'c':
    case 'C':
    case 'd':
    case 'D':
    case 'e':
    case 'f':
    case 'F':
    case 'g':
    case 'G':
    case 'a':
    case 'A':
    case 'b':
      stopPlaying (which);
      break;

    default:
      break;
    } // end of switch on which key
  } // end of keyUp

void setup()
{
  kpd.begin ();
  kpd.setKeyDownHandler (keyDown);
  kpd.setKeyUpHandler   (keyUp);
  pinMode (RECORDING_LED, OUTPUT);

  if (!sd.begin (chipSelect, SPI_HALF_SPEED))
     showError (500);  // never returns

} // end of setup

void loop()
{
  kpd.scan ();
} // end of loop

I am recording from a self built replica of a theremin, which is basically two ultrasonic sensor readings for volume and pitch. Is this "too basic" for a MIDI file type?

It looks like this could be possible by using the MIDI "pitch bend" message. You would need to determine where your note value was (presumably most of the time between the natural notes like C and C#) and then send a bend message or "Pitch Wheel Change" (0xE0 for channel 1) to modify the main note. The main note would need to be updated if you moved more than a couple of semitones away.
See:

https://en.wikipedia.org/wiki/Pitch_wheel
http://sites.uci.edu/camp2014/2014/04/30/managing-midi-pitchbend-messages/

My project doesn't actually have anything connected to a MIDI port; its just reading from/writing to files.

Although what you've done is really cool

Ah, OK. So my answer doesn't really address your question. I got the idea into my head that your device outputs MIDI codes and you wanted to turn them into a disk file.

I've updated my answer to give a lot more detail about how you might do it.

I've updated my answer to give an example of a complete sketch that does this.

Wow. I would've never expected such an elaborate answer. Give me a few days to understand it all. I have limited experience of all this but I will try to see if I can understand it!

Ok so I think I understand how the MIDI syntax works. On a theremin the note would always be on so that byte would always by 0x90, right?

I'm reading about the pitch bending and also trying to figure out how to convert a frequency value to a note + pitchbend... also where would I write the pitchbend byte - after the note number byte?

No, they are two different commands. 0x90 is "note on". There would be no point in sending lots of "note on" unless they were for different notes. And the pitchbend is a separate command. If the pitchbend range was big enough you could just do a single "note on" and then just bend it up or down as your hand moved, but the range might be too small for that. It might just bend up from C to D. I think you might have to experiment with that. Are you planning to play this on another MIDI device, or just play it back on your own theramin?

The ultrasonic sensors aren't very good so the note is constantly fluctuating even if the hand controlling it is not moving. I still want it to be recording those anyway, so why isn't sending lots of "note on"s appropriate? The refresh rate on the ultrasonic sensors are pretty fast, I would guess around 15ms per note.

On the second link you gave me, it says: "The amount of alteration in pitch caused by the pitchbend value is determined by the receiving device". So I guess I will have to experiment to see how much one pitchbend value changes the frequency by, but it probably wont be able to go a few octaves, which was what I was hoping for.

If the pitch bend value translates to different frequency changes based on what type of receiver is playing, then that defeats the purpose of using MIDI to record and playback. I think I might just use some type of custom file format, as it won't be compatible with other instruments anyway...

Yes, well for recording and playing back on your own device, a custom file format would be much simpler. You could basically just record the raw data from the sensors (and a time difference). Then when they go to play it back, make the code think this raw data has just been received and it should reproduce it perfectly.

This answer is pure gold. I just built a pass-through MIDI recorder that sits between a device with midi-out (e.g. a novation launchkey) and device with midi-in (e.g., an ASIO audio interface) so that even if you're not running something that comes with "always-on recording" like FL Studio or Ableton, you won't lose that sweet riff you were noodling on an hour ago. To keep it simple I was writing the data as CSV file rather than as .mid, but thanks to your answer that changes today.

Yes, read the MIDI file format specification. Create a single track midi file and append just note press / release commands / pitch or volume changes and delta times (reverse conversion of delta times to milliseconds is explained here). When you finish recording, just seek to the beginning of the file and update the track length value (total size of the appended buffer of midi commands)


text:
Arduino reduces the laser power
Its important to mention that I'm noob.
I bought 500mw 405nm TTL module laser(5-12 volt) driver circuit. When I supplied laser with 12 volt, it turns on with max power. but when i connects laser TTL module to arduino (pin 11) in order to control turning on & off of laser through GRBL(CNC machine language) command with full power, the output of laser reduces.
"M05 S0" turns off the laser while
"M03 S255" should turns on the laser with full power as it is turning on with direct 12 volt supply, but its not happening.
so how can I make laser turn on with full power with arduino control?
Laser I,m using
https://www.amazon.in/gp/product/B071J2W7V8/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1
Laser driver circuit

What laser? What's your circuit?

Did you set the maximum spindle speed in GRBL to 255? If not, than it is correct, that the laser power goes down. GRBL outputs a simple PWM signal, but that does not mean, that the duty cycle of the PWM output directly translates to the spindle speed set by the S command

I'm voting to close this question as off-topic because it is about a laser power supply, and not about Arduino.  If you want to pursue this project (despite the rather obvious potential hazards) you will need to use other resources to figure out how to make the power supply operate correctly from an approximately 5v logic input, which is what the Arduino can provide as a control signal.

Did you try a simple PWM sketch?

Possible duplicate of How to connect TTL logic laser with arduino?

Also asked at: https://electronics.stackexchange.com/q/364287 and http://forum.arduino.cc/index.php?topic=537202 If you're going to do that then at least be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

It also helps if you post a link to the datasheet.

The first thing I would recommend is to log into your Amazon account and contact the seller. Ask them to send you product documentation.
If the seller is not able to provide any, then you could return the product for a refund or try to figure it out how it works.
According to this document: TTL Laser
TTL modulators emit 100% of their power when a TTL "0" (0 VDC) is input and less than 5% of their power when a TTL "1" (5 VDC) is input.
gre_gor's comment about trying a simple PWM sketch sounds like an excellent place to start.

source: Stack Exchange

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

sort: votes


text:
What happens when I exceed amp limit on Arduino 5v pin?
I'm using an Arduino Uno to power some rgb LEDs.
Each LED takes 20mA (on average).
I have a strand of 400 LEDs.
This should be drawing ~8,000mA.
Arduino Uno has a limit on its 5v pin of 500mA.
**So how many amps is my Arduino outputting? My 8A worth of LEDs are illuminated, just dimly.
Edit:
My Arduino still runs, and the 8,000mA LEDs illuminate, just dimly. I’ve left the setup on for 12 hours, and it all still works.
So it appears the behavior of the Arduino Uno is to limit the amp output of its 5v pin. It does not burn out.
Any explanations for this observed behavior?
Edit 2:
I know how to wire up this setup correctly using power injection. I’m just curious why my Arduino is not burning out as we all expect it to.

You can always make Arduino to control a power MOSFET (or a relay module) that's rated for more that 8A. That way Arduino gives out only several milliamperes.

If the 5V source is the barrel jack, (like from a 7.5V or 9V source), than you may be able to get up to 800mA to 1A from the 5V pin. There is a reverse polarity diode that is rated for 1A. The 5V regulator is only rated for 800mA. It does not have good heatsinking, and will overheat and shut before you see 800mA tho.
USB, well, you may get 500mA from that, if the source doesn't shut down first. If it doesn't, then the 500mA inline fuse should open.
You really need a seperate source for 5V for power to the strands.  Be sure to connect the Gnd from the source to the Arduino Gnd.
What kind of RGB LEDs are you using? WS2812B type LEDs?

If you exceed the amp limit, that can be drawn through (!) the Arduino, some components on the Arduino will be fried (As for most electronic devices. For the Arduino this is practically a short). There is no current limitation there. Which components are fried depends on how you provide the power. If you provide power through the power jack or VIN, the voltage regulator will burn out. If you provide power through USB a diode or the MOSFET will be fried (You can look this up in the Arduino UNOs schematic at this site).
The setup might output a current, that is a bit higher than 500mA, for a short time. But the mentioned components, that are in the currents path, will heat up very quickly and be destroyed. In this short time the LEDs will be very dim, since the Arduino cannot provide a current as big as 8A, not even for a short time.
All great loads have to be powered separately from the Arduino, so that their supply current will not flow through the Arduino. If you are using a powerful USB supply, you have to split the power lines, before giving the voltage to the Arduino. You can connect the USBs 5V pin to the 5V pin of the Arduino and to the LEDs. If you are using a power supply with a higher voltage than possible for your LEDs, you have to buy an extra regulator, that also capable of providing the needed current.
Important note: Since you didn't specify, how you are connecting the RGB LEDs, you also have to take care about the current limit of a single pin. It should not exceed 20mA, 40mA at the absolute maximum. So you cannot drive the LEDs directly. You will need a driver for then anyway. The simplest way is a MOSFET, that is capable of sourcing the corresponding current. It is then controlled by the Arduino, which needs very little current for it.

I thought this too - but I’m drawing far beyond the 5v pins limit, and nothing is fried. The Arduino still works fine after a 12 hour run with an 8A draw.

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


text:
How to switch 12V water pump
I found this pump:
https://www.aliexpress.com/item/Free-Shipping-Ultra-quiet-DC-12V-3M-240L-H-Brushless-Submersible-Water-Pump-High-Qualtiy-mini/32472119699.html
Now, I want to control it from an Arduino.
Is this a good relay to use?
https://www.pololu.com/product/2480?
I want to use a 12v battery for the pump.

You don't need a relay - a simple N-channel MOSFET will do the job. Oh, and don't forget the flyback diode. A pump is just a motor, after all.

You need to check the voltage rating and the current rating of the relay. So in your case, the relay should have a rating of at least 12V DC, and 0.35A of current. Both values are really low, so almost any relay will work. The relay you linked to doesn't have a DC rating, only an AC. But I don't think that's a problem in this case.

@Gerben A general rule of thumb: DC rating is 1/10th - 1/20th of the AC rating. Current remains constant. It's all about arc extinguishing - AC auto-extinguishes at the zero crossing, DC doesn't.

@Majenko thank you. I didn't know about that rule of thumb. I knew it was lower. Since the pump in question is only 350mA,  the 10/5A relay from pololu should work.

I see people are recommending mosfets (which is the best option). Keep reading this if you still want to use relay. There are two kind of relays, mechanical and solid state. Mechanicals are cheap but they can be noisy (they make sound) also they have low life expectancy compared to solid state relays. On the other hand solid state relays are faster with everything else but they are expensive. Also you need to check voltage and max current rates before buying.

Some solid state relays only work on AC, so they won't work in this application.

@Gerben . . There are solid state relays for DC :  http://www.crydom.com/en/products/catalog/e_l_dc.pdf

About the relay, you can buy a low cost relay from aliexpress like the following one or other variant.
https://m.aliexpress.com/item/32392799916.html#autostay
It's well within your desired voltage and current  range and works readily with arduino.

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


text:
Controling pump while displaying moisture value on a LCD at the same time with soil moisture sensor?
I'm new with Arduino (and I'm not very good at English). Recently with Arduino Nano I have tested:

Control water pump based on soil moisture (using relay) (1)
Display soil moiture (in percent) on a Nokia 5110 LCD   (2)

Now I'm combining 2 codes to control water pump while always displaying moisture value (in percent) on LCD. However, after I have uploaded the code an Arduino Nano, the LCD showed nothing.
When I touched the sensor (changed moisture value) the first time, the LCD showed up, but when I touched the sensor the second time (changed moisture value again), the LCD went blank. The relay and pump still work fine, so I think the problem comes from LCD's code.
Here's my code (1):
const int VAL_PROBE = 0;
int RELAY1 = A1;
const int MOISTURE_LEVEL = 250;

void setup()
{
  Serial.begin(9600);
  pinMode (2, INPUT);
  pinMode(A0, INPUT);
  pinMode(RELAY1, OUTPUT);
}

void loop()
{
  int moisture = analogRead(VAL_PROBE);
  Serial.print("Moisture = ");
  Serial.println(moisture);

  if(moisture < MOISTURE_LEVEL)
  {
    digitalWrite(RELAY1,0);           // turn on relay
    Serial.println("Light ON");
  }
  else
  {
    digitalWrite(RELAY1,1);          // turn off relay
    Serial.println("Light OFF");
  }
}

The code (2)(got it from the Internet):
    //////////////////////////////////////////////
   //        Arduino Soil Moisture Sensor      //
  //            with NOKIA 5110 LCD           //
 //           http://www.educ8s.tv           //
//////////////////////////////////////////////

#include <LCD5110_Graph.h> // THE LIBRARY I AM USING IS THIS:  http://www.rinkydinkelectronics.com/library.php?id=47

LCD5110 lcd(8,9,10,12,11);

extern unsigned char BigNumbers[];
extern uint8_t ui[];

int sensorPin = A0;
int sensorValue = 0;
int percent = 0;
String percentString ="0";
int stringLength = 0;

void setup() {
  lcd.InitLCD();
  lcd.setFont(BigNumbers);
  delay(1000);
}

void loop() {
  lcd.clrScr();
  lcd.drawBitmap(0, 0, ui, 84, 48);
  sensorValue = analogRead(sensorPin);
  percent = convertToPercent(sensorValue);
  percentString = String(percent);
  stringLength = percentString.length();
  displayPercent(stringLength);

  lcd.update();
  delay(1000);
}

int convertToPercent(int value)
{
  int percentValue = 0;
  percentValue = map(value, 1023, 350, 0, 100);
  if(percentValue>100)
    percentValue = 100;
  return percentValue;
}

void displayPercent(int length)
{
  switch(length)
  {
    case 1:  lcd.print(percentString,38,19); break;
    case 2:  lcd.print(percentString,24,19); break;
    case 3:  lcd.print(percentString,10,19); break;
    default:  lcd.print(percentString,0,19); break;
  }
}

And my combined code:
const int VAL_PROBE = 0;
int RELAY1 = A1;
const int MOISTURE_LEVEL = 250; // Mức độ ẩm cố định là 250
#include <LCD5110_Graph.h>

LCD5110 lcd(8,9,10,12,11);

extern unsigned char BigNumbers[];
extern uint8_t ui[];

int sensorPin = A0;
int MoistureValue = 0;
int percent = 0;
String percentString ="0";
int stringLength = 0;

void setup()
{
  Serial.begin(9600);//Mở cổng Serial ở mức 9600
  pinMode (2, INPUT);
  pinMode(A0, INPUT);
  pinMode (12, OUTPUT);
  pinMode(RELAY1, OUTPUT);
  lcd.InitLCD();
  lcd.setFont(BigNumbers);
  delay(1000);
}

void loop()
{
  lcd.clrScr();
  lcd.drawBitmap(0, 0, ui, 84, 48); // hiển thị giao diện màn hình
  MoistureValue = analogRead(sensorPin); // đọc giá trị từ cảm biến

  percent = convertToPercent(MoistureValue);
  percentString = String(percent);
  stringLength = percentString.length();
  displayPercent(stringLength);

  lcd.update(); // cập nhật màn hình
  delay(1000); // mỗi 1 giây

  int moisture = analogRead(VAL_PROBE);
  Serial.print("Moisture = ");
  Serial.println(moisture);

  if(moisture < MOISTURE_LEVEL)
  {
    digitalWrite(12,HIGH);
    digitalWrite(RELAY1,0);           // bật relay
    Serial.println("Light ON");
  }
  else
  {
    digitalWrite(12,LOW);
    digitalWrite(RELAY1,1);          // tắt relay
    Serial.println("Light OFF");
  }
}

int convertToPercent(int value) // đổi giá trị cảm biến sang phần trăm
{
  int percentValue = 0;
  percentValue = map(value, 1023, 350, 0, 100);
  if(percentValue>100)
    percentValue = 100;
  return percentValue;
}

void displayPercent(int length) // hiển thị phần trăm ra màn hình
{
  switch(length)
  {
    case 1:  lcd.print(percentString,38,19); break;
    case 2:  lcd.print(percentString,24,19); break;
    case 3:  lcd.print(percentString,10,19); break;
    default:  lcd.print(percentString,0,19); break;
  }
}

Any advice?

include a circuit schematic, preferably fritzing

I think the problem is with
digitalWrite(12,HIGH);

and
digitalWrite(12,LOW);

Pin 12 is used by the LCD. Changing it's output will reset the LCD. I'm not sure why you put it there to begin with, as it wasn't part of any of the two sketches.

Thank you Gerben. Pin 12 I used in code (1) as a led to indicate if the pump was activated. I though I have deleted it in the last code but turn out I deleted it in code (1) instead. That's why you though it wasn't part of any sketches. What a simple mistake haha. I don't have time to check it right now but it must be the answer. I'm going to check it and close this question in few hours later. Btw this website don't have section to add comment for answers? I can only add comment for questions

@LêThànhVinh you just commented on an answer. For your own question, you can edit it

in cases like this where you are combining multiple pieces of code together, a simpler approach would be to rename that:
//set up 1
void setup1(void) {
...
}

//loop 1
void loop1(void) {
...
}

//set up 2
void setup2(void) {
...
}

//loop 2
void loop2(void) {
...
}

...

//combined setup
void setup(void) {
  setup1();
  setup2();
  ...
}

//combined loop
void loop(void) {
  loop1();
  loop2();
  ...
}

that's much easier to track than to manually copy-and-paste them.

authors: علي ود هندسة


text:
Can I use IR Transmitter/Receiver for heart beat detecting?
Specifically, I want to know if the KY-022 module and KY-005 module can be used for heart beat detecting according to this tutorial?
KY-005:

KY-022:

If so, can you please explain to me how can I achieve such thing with respect to the following:
1- Is there any kind of synchronization between transmitter/receiver?
2- How to get a stable analog value from the receiver?
3- The Correlation between Heart beat rate and the obtained values?
providing circuit sketch will be very helpful but not necessary.
Thanks in advance.

If you watch the video and try to work out what you are seeing it should be clear. [No - the transmitter is simply an IR light source.] 2. No need for stability - look for local maxima and minima at frequencies that are "about   right".  An FFT of the signal may be useful but is overkill. 3. Did you watch the video? If so, watch it again. Look at the waveform on the oscilloscope. You are, of course, seeing the heart beat.

Tutorial link broken.

No, you cannot.  The sensor you link to has a circuit which attempts to detect IR light modulated at a specific frequency, and produces a digital output.   For a heartbeat sensor you need an analog output to feed into far more sophisticated signal processing - effectively the built-in processing gets in the way and means you cannot use it for this purpose.
Additionally, sensors of this type typically have an automatic gain control which means that they desensitize when subjected to continuous signal - they are designed for sources like remote controls where the modulation is itself pulsed on an off in small fractions of a second, so they interpret constant modulated light as noise and soon turn off their output.


text:
Why is there a plastic sleeve on my HC-05 bluetooth module
I would like want to know why the bluetooth module has a plastic sleeve covering it?
Is it possible to remove it?

It is to protect it. You should keep it so that the modules lasts longer.
If you remove it, just don't do anything stupid.

To protect it against ham fisted newbies from causing short circuits.
Yes, you can remove it, as long as you're not a ham fisted newbie that is going to cause short circuits.


text:
Error in the arduino code
This is my arduino code for interfacing with an ESP8266:
#include <ESP8266WiFi.h>

int incomingByte;
String value;
char a;
int flag=0;
String valueserial;
int valueint;

const char* ssid     = "NIDHI";
const char* password = "nidhi123";

String data;

void setup() {
  Serial.begin(9600);
  delay(6000);
  data = "";
  valueserial = "";

//
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 //
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);

    Serial.print(".");

  }
  //
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
//
}

void loop() {
  flag = 0;
  delay(5000);
  valueserial = "";
  // Use WiFiClient class to create TCP connections
  WiFiClient client;
String url = "/display.php";

if (Serial.available() > 0){
    while (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();
                valueserial += char(incomingByte);
              }
    if (incomingByte == '\n') {
      Serial.print("Value:");
      Serial.println(valueserial.toInt());
      Serial.print("String: ");
      Serial.println(valueserial);
      // clear the string for new input:
    }
    //valueint = Serial.parseInt();
    data = "?value=" + String(valueserial.toInt());

    url += data;
    delay(100);
    flag = 1;
}

if (client.connect("www.soil.pixub.com",80) && flag==1) { // REPLACE WITH YOUR SERVER ADDRESS
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
    "Host: soil.pixub.com\r\n" +
    "Connection: close\r\n\r\n");
    Serial.println("!!!!DATA POSTED!!!!");
   }

       //valueserial += '\0';
  //valueserial = Serial.read();
//
Serial.println(data);
//
  if (client.connected()) {
    client.stop();  // DISCONNECT FROM THE SERVER
  }
//
  Serial.println();
  Serial.println("closing connection");
//
}

And i am getting the following errors
Arduino: 1.6.12 (Windows 10), Board: "Arduino/Genuino Uno"

In file included from C:\Users\Akshay\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFi.h:33:0,

                 from C:\Users\Akshay\Downloads\esp8266code\esp8266code.ino:3:

C:\Users\Akshay\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFiType.h:26:19: fatal error: queue.h: No such file or directory

 #include <queue.h>

                   ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

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

Please make your post as readable as possible. From what I can read the compiler is telling you there is a header file or library missing.

A comment about personal security.  When copying and pasting from a computer, consider scrubbing the information to remove any personal names.

The ESP8266WiFi library is meant to be used when programming an ESP8266 using the Arduino environment. In Arduino lingo: It's supposed to be used with a ESP8266 Board.
It's -not- meant to be used with a 'Arduino/Genuino Uno' board, which is what you are trying to do. This is why it fails.
What you want to use is the ESP8266wifi library, which is used with a ESP8266 connected to a Arduino, and flashed with AT firmware.
And yes, it's confusing, there are two very similar libraries:

Programming an ESP8266 using Arduino IDE:
ESP8266WiFi: https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFi
Programming an Arduino using Arduino IDE, to communicate with ESP8266 using AT commands:
ESP8266wifi: https://github.com/ekstrand/ESP8266wifi

The file queue.h is either missing or is not in the expected location (correctly installed).  Make sure you have your SDK and Libraries correctly installed and up-to-date.  In an extreme case, you might consider reinstalling both to make sure the build environment is correct.


text:
How to include Vref in thermistor temperature calculation?

simulate this circuit – Schematic created using CircuitLab
This is the code that I'm using to get the temperature:
#define COEFF_A 0.8662984364E-03
#define COEFF_B 2.780704551E-04
#define COEFF_C -0.9395108479E-07

float VRT, Temp;
float Vref = 2.52;

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

void loop() {
  long Resistance;
  VRT = analogRead(A3);
  Resistance = 10000 / ((1023.0 / VRT) - 1);
  Temp = log(Resistance);
  Temp = 1 / (COEFF_A + (COEFF_B * Temp) + (COEFF_C * pow(Temp, 3)));
  Temp += -273.15;
  Serial.println(Temp);
  delay(500);
}

I know that the calculation should be: V = Vref × VRT ÷ 1023 but i don't know how to implant it in this code, any help appreciated.

Update
After Edgar Bonet answer, the edited code is:
#define COEFF_A 0.8662984364E-03
#define COEFF_B 2.780704551E-04
#define COEFF_C -0.9395108479E-07

float VRT, Temp, VR;

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

void loop() {
  long Resistance;
  VRT = analogRead(A3);
  VR = 2.52 * VRT / 1024;
  Resistance = 10000 * VR / (2.52 - VR);
  Temp = log(Resistance);
  Temp = 1 / (COEFF_A + (COEFF_B * Temp) + (COEFF_C * pow(Temp, 3)));
  Temp += -273.15;
  Serial.println(Temp);
  delay(500);
}

But the temperature reading is 2 centigrade less than what it should be, when i remove the analogReference(EXTERNAL); it shows the normal/correct temperature readings.

The formula to get the analog voltage from the ADC reading is:
    V = Vref × reading ÷ 1024
(yes, it's 1024, not 1023). The formula to get the thermistor resistance
from the measured voltage is:
    R = Rref × V ÷ (Vref − V)
where Rref is your 10 kΩ pull-up. You can combine these
two formulas in order to get the resistance directly from the ADC
reading:
    R = Rref × reading ÷ (1024 − reading)
You may notice that, while doing this simplification, Vref
cancels out. It's not an error. The readings you get with this setup are
indeed independent of your reference voltage.

Update 1: After the OP's edit, we now have a completely different
question. The question is now: how come the readings do depend on the
reference voltage that is used, whereas in theory they should not.
The answer lies most likely in the ADC calibration. If high accuracy is
a requirement, the correct formula for the measured voltage is
    V = Vref ×
(reading + Eoff) ÷ (1024 + Egain)
where Eoff and Egain are the offset error and the
gain error respectively. These errors are not knows a priori, and they
are usually neglected when the accuracy requirement is low. The
datasheet only gives constraints on how big these errors can be. The
actual values depend on the specific microcontroller and can somewhat
depend on the reference voltage. The only solution to get rid of these
errors is to calibrate your own ADC. See Response of the Arduino
ADC for an example on how this could be done.

Update 2: If I had to program this in an Arduino, I would rather
simplify the calculations as much as possible before coding:

do not compute the measured analog voltage, nor the resistance, as
they are not needed
compute instead the ratio R/Rref directly from the analog
reading
rewrite the calibration polynomial as a function of
log(R/Rref) instead of log(R) (which actually means
log(R/(1 Ω)))
optimize the evaluation of the polynomial by using
Horner's method.

With these optimizations, we get:
// Coefficients of polynomial fit of log(R/Rref) -> 1/T.
const float c0 = 3.3540165e-3;
const float c1 = 2.5416075e-4;
const float c2 = -2.5959644e-6;
const float c3 = -9.3951087e-8;

// Convert ADC reading to temperature in deg. C.
static float temperature(int reading)
{
    float R_ratio = reading / (1024.0 - reading);  // = R / Rref
    float x = log(R_ratio);
    float inverse_T = c0 + x*(c1 + x*(c2 + x*c3));
    return 1/inverse_T - 273.15;
}

void loop()
{
    int reading = analogRead(A3);
    Serial.println(temperature(reading));
    deay(500);
}

so in this example it should be this: Resistance = 2.52 * VRT / (1024 - VRT);, correct?

No. Your reference resistance is 10 kΩ, not 2.52 Ω.

but the readings is wrong, Resistance = 10000 * VRT / (1024 - VRT); did i missed something? it's like 2C less...

I don't understand your last comment. Please, edit your original question if there is something missing.

when i use your suggested formula Resistance = 10000 * VRT / (1024 - VRT); the temperature is 2 centigrade less than what it should be.

unless i remove the analogReference(EXTERNAL);, that means it don't ignore "cancel" the Vref!

Update your question.

Edited the question.

The article you linked is a piece of gold, thank you.

Note: I formulated this answer on your previous, deleted question.
Whether the voltage increases or decreases with rising temperature depends on your circuit: if you use the ntc with R1 as a pull-down, the voltage will increase on rising temperature. If R1 is a pullup the voltage will fall respectively.
Concerning your calculation: I highly recommend using a look-up table instead. Those are some hard calculations, and at the arduinos resolution you'll be fine with a LUT with about 64 entries. There're tools out there which generate LUTs for a given NTC setup (I personally like this tool).

uh i feel so bad now that i deleted that question while you was answering it! sorry...

the code that i posted in my question does all the calculations, i don't need to re-do it, i just need to add the Vref into the calculation and don't know how... it's a pull-down btw.

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


text:
Flashing ESP8266 ESP-12E/12F
I'm pretty new to Arduino programming and i'm trying to connect this ESP8266 module to my FTDI programmer but constantly getting this error on my ARDUINO IDE:  esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header.
My guess is that its not in flashing mode and that i have to connect GPIO0 to ground or sompthing else.

On my version of this "Adatper" adapter the io pins were not connected. I patched io 0 to the esp-01 like header, to be able to put the ESP in bootloader mode. On the picture you see a paperclip jumper connecting io 0 to ground for flashing mode.
Back then I could leave the jumper connected, because the esp8266 run the sketch after upload. In new versions of esp8266 arduino boards package the esptool hard resets the esp8266 so it returns into flashing mode. This can be changed in platform.txt.
I recommend you to buy an esp8266 dev board with USB (Wemos, NodeMcu and similar)

I connected it like this Check here but i still got same error TRACE +0.101 Timed out waiting for packet header. Any advice ? :S

is the io 0 pin of the esp-12F module connected to the header? on my it was not. do you see the wire soldered to esp-12F pin on my photo?

It's not, since i'm new to this can you explain to me how to connect it to header ?

you see it on my picture

I see soldered wire but I do not know where the other end of the wire is going

I connected wires as on the picture and connected io 0 pin of the esp-12F module to GPO0 on the bottom side of the esp-12 and when i tried to upload the code got this Check here

I added a photo of the bottom side. Do you still have the jumper wire on the header from Ground to io 0?

Thank you alot for your help but i still got this error: link

measure with multi-meter if the soldering and header connection is good

I think connections are good since Arduino IDE at start uploading shows that he read bytes and receives packet but after a while it crashes like on link :S

try it without breadboard

Same result link :/

do you supply 3.3 or 5 V to the adapter?

I supply with 3.3V

the adapter converts 5 V input to 3.3 V for the esp8266. supply 5 V

I't wooorkeed ;) Thaank you alot :)))))))))))

the purpose of the adapter is to convert 5 V power and logic level on RX pin to 3.3 V of the esp-12F


text:
Soft wdt reset error on NodeMCU (ESP8266)
I am getting error on Serial monitor Soft WDT reset. I decoded the error code also and found the following stacktrace.
I am using SIM808 module and DFRobot_sim808 as the library.

0x4010030d: millis at AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/core_esp8266_wiring.c line 180
0x401003b9: __digitalWrite at AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/core_esp8266_wiring_digital.c line 82
0x40202863: sim808_wait_for_resp(char const*, DataType, unsigned int, unsigned int) at Documents\Arduino\libraries\DFRobot_SIM808-master/sim808.cpp line 172
0x402027a4: sim808_send_byte(unsigned char) at Documents\Arduino\libraries\DFRobot_SIM808-master/sim808.cpp line 118
0x402028ce: sim808_check_with_cmd(char const*, char const*, DataType, unsigned int, unsigned int) at Documents\Arduino\libraries\DFRobot_SIM808-master/sim808.cpp line 191
0x402025dc: DFRobot_SIM808::init() at Documents\Arduino\libraries\DFRobot_SIM808-master/DFRobot_sim808.cpp line 63
0x402024c1: setup at G:\Development\ESP8266\SIM Module\sim_module/sim_module.ino line 41 (discriminator 1)
0x40203248: loop_wrapper() at AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/core_esp8266_main.cpp line 122
0x40100e8d: cont_wrapper at AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/cont.S line 81

I tried to find solution for the same everywhere but none found it. But the same code I am trying on arduino it works but not for ESP8266. I dont have long waiting loop(). But still it gives me error.
Below is the code for the same
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

#define PHONE_NUMBER "********"

#define MESSAGE  "hello,world"

#define PIN_TX D1
#define PIN_RX D0

SoftwareSerial mySerial(PIN_RX, PIN_TX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

void setup() {
  delay(1000);
  mySerial.begin(9600);
  Serial.begin(9600);

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB
  }
  while(!sim808.init()) {
      delay(1000);
      Serial.print("Sim808 init error\r\n");
  }
  Serial.println("Sim808 init success");
  Serial.println("Start to send message ...");

  sim808.sendSMS(PHONE_NUMBER,MESSAGE);
}

void loop() {

}

The culpret is the SIM808 library. It's not written to work well with the ESP8266.
The problem lies in this function:
boolean sim808_wait_for_resp(const char* resp, DataType type, unsigned int timeout, unsigned int chartimeout)
{
    int len = strlen(resp);
    int sum = 0;
    unsigned long timerStart, prevChar;    //prevChar is the time when the previous Char has been read.
    timerStart = millis();
    prevChar = 0;
    while(1) {
        if(sim808_check_readable()) {
            char c = serialSIM808->read();
            prevChar = millis();
            sum = (c==resp[sum]) ? sum+1 : 0;
            if(sum == len)break;
        }
        if ((unsigned long) (millis() - timerStart) > timeout * 1000UL) {
            return false;
        }
        //If interchar Timeout => return FALSE. So we can return sooner from this function.
        if (((unsigned long) (millis() - prevChar) > chartimeout) && (prevChar != 0)) {
            return false;
        }

    }
    //If is a CMD, we will finish to read buffer.
    if(type == CMD) sim808_flush_serial();
    return true;
}

It has a loop that can take some time to run, and it doesn't yield() at any point to allow the ESP8266's housekeeping routines to run and "kick the dog".
Adding a call to yield() inside the while(1) loop should cure the problem.

Thank you very much. It worked. Really appreciated. But I am facing I more issue after 10-12 "Sim808 init error" I receive success why is it so why it does not get initialised in first attempt.

Probably waiting to connect to the network. That can take up to a minute sometimes.

Thanks for the reply. Nothing to bother. There was some contact issue between Gnd Pins of both modules.


text:
Will Intel Atom Processor laptops support cloned a Arduino with CH340 driver?
I am planning to buy a low cost and low weight laptop with an Atom Processor.
I only have cloned Arduinos - will the Arduino drivers and IDE work on laptops which come with Atom Processors?

Are you wondering if you could install the Arduino IDE on the laptop?

Yes. Original FTDI chip will work but I am having cloned Arduino with CH340 and i am using Intel I3 which is working fine. Also planning to buy Atom processor based low cost laptop (Z3735F variant). Whether the driver will support the cloned one.

Install the needed drivers and you're done.

The processor in your laptop is irrelevant. It is the operating system you should be thinking about, not the processor.
If the operating system has drivers for the CH340 chip, and Windows does, as you already know since you are using it already, then you already know that the answer is a big fat yes.
The only time you need to worry about if the processor will support something is when you are switching to a completely different archetecture such as ARM.

Thanks. I am planning to buy  http://www.snapdeal.com/product/micromax-canvas-l1161-lapbook-intel/661756382388 which is comes with windows 10


text:
How to subtract micros()?
I am attempting to calculate the time between pulses by comparing the micros() timestamp. I understand that you cannot just simply subtract unsigned longs, but I cannot understand what the alternative for it is.
Below is a simplified version of code. On pin 6 I receive 2ms long pulses every 2ms comparing the times returns "-19728". I'm planning to make the pulses much shorter once I figure out this math problem.
Site note: I'm using pulses to make two Arduinos send simple data via digital pins.
Thanks you.
int pinReceiver = 6;
int val = 0;
int isReceiving = 0;
int pauseLength = 0;
unsigned long timeStart = 0;

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

void loop() {
  noInterrupts();
  val = digitalRead(pinReceiver);

  if(val==HIGH){
    if(isReceiving==0){ //Pulse begins
      isReceiving = 1;
      pauseLength = micros() - timeStart;
      Serial.println(pauseLength);
    }

  } else {
    if(isReceiving==1){ //Pulse ends
      isReceiving = 0;
      timeStart = micros();
    }
  }
  interrupts();
}

The calculation seems correct. Please try to also use unsigned long for pauseLength. That might be your problem

That definitely solved the problem. I assumed that since the difference would be such a short number it could be int. Thank you. I don't know how to mark this as solving answer.

I think its more about that you mixed unsigned and signed types. Tomorrow I will write an answer, that you can accept

what happens if you cast long to int ? ... pauseLength = (int)(micros() - timeStart);

Long to Integer conversion will overflow the value and you'll get values in negative numbers.
Define the pauseLength as unsigned long to make it work.


text:
Arduino GSM Shield NET and STATUS led turn off after a few seconds
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess;     // include a 'true' parameter to enable debugging
GSMScanner scannerNetworks;
GSMModem modemTest;

// Save data variables
String IMEI = "";

// serial monitor result messages
String errortext = "ERROR";

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);

  Serial.println("GSM networks scanner");
  scannerNetworks.begin();

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      notConnected = false;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  // get modem parameters
  // IMEI, modem unique identifier
  Serial.print("Modem IMEI: ");
  IMEI = modemTest.getIMEI();
  IMEI.replace("\n", "");
  if (IMEI != NULL) {
    Serial.println(IMEI);
  }
}

void loop() {
  // scan for existing networks, displays a list of networks
  Serial.println("Scanning available networks. May take some seconds.");
  Serial.println(scannerNetworks.readNetworks());

  // currently connected carrier
  Serial.print("Current carrier: ");
  Serial.println(scannerNetworks.getCurrentCarrier());

  // returns strength and ber
  // signal strength in 0-31 scale. 31 means power > 51dBm
  // BER is the Bit Error Rate. 0-7 scale. 99=not detectable
  Serial.print("Signal Strength: ");
  Serial.print(scannerNetworks.getSignalStrength());
  Serial.println(" [0-31]");
}

Results:
When I run the program, I can see the "GSM networks scanner" message appear on my serial monitor, but it does not display anything else after that. Also, the NET and STATUS LEDs turn off after some few seconds when the program starts running. I already made the minor adjustments necessary for the Arduino Mega, and the power supply is temporarily from the USB port of my laptop connected to the Arduino Mega. I am using a SIM card that has been activated.
I think my program stops at this stage:
  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      notConnected = false;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

P.S. when I run the program without inserting a SIM card, the NET and STATUS LEDs keep on working (NET is blinking, while STATUS remains ON)
I tried this program as well https://www.arduino.cc/en/Guide/ArduinoGSMShield#toc9
and it has the same problem (i.e. stops at the same stage as the previous program)

It would be great if you could format you code properly and describing expected results.

@jsotola I edited the question to make things clearer

SOLUTION:
To solve my GSM shield issue, I connected a 9 V battery to my Arduino as a supply instead of using my Laptop's USB cable (and I also tried a 12 V supply as well). Thankfully, it did work. In the case that that it does not work (after uploading the program), click on the 'restart' button found on the GSM shield. You can find the type of sources that I used to supply my Arduino & GSM shield in the image posted below. IT IS IMPORTANT TO MENTION THAT THE FOLLOWING PROGRAM WAS IMPLEMENTED TO CHECK IF THE GSM SHIELD IS WORKING (I tried the "GSM Networks Scanner" program that I have mentioned in my question initially, but it did not work and it was not necessary anyways. So, I used the 'GSM SMS' code directly and it worked fine)
This is the code that worked out with me:
#include <GSM.h>

#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess; // include a 'true' parameter for debug enabled
GSM_SMS sms;

// char array of the telephone number to send SMS
// change the number 1-212-555-1212 to a number
// you have access to
char remoteNumber[20]= "Replace this text with a mobile number instead";

// char array of the message
char txtMsg[200]="Hello World";

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

  Serial.println("SMS Messages Sender");

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected)
  {
    if(gsmAccess.begin(PINNUMBER)==GSM_READY)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
  sendSMS();
}

void loop()
{
// nothing to see here
}

void sendSMS(){

  Serial.print("Message to mobile number: ");
  Serial.println(remoteNumber);

  // sms text
  Serial.println("SENDING");
  Serial.println();
  Serial.println("Message:");
  Serial.println(txtMsg);

  // send the message
  sms.beginSMS(remoteNumber);
  sms.print(txtMsg);
  sms.endSMS();
  Serial.println("\nCOMPLETE!\n");
}


text:
LCD Display many numbers?
There is no error in the code it already stored 11 numbers in serial print  but the problem I want to input 11 numbers only in keypad That will display 11 numbers also in LCD. But it display many numbers in LCD. Any idea please?

#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
SoftwareSerial mySerial(6, 5);
int table[] = { 0, 0, 0 };
#include <Keypad.h>
#include <Wire.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

char keys[ROWS][COLS] = {
    { '1', '2', '3' },
    { '4', '5', '6' },
    { '7', '8', '9' },
    { '*', '0', '#' }
};
byte rowPins[ROWS] = { 2, 3, 17, 16 }; //connect to the row pinouts of the keypad
byte colPins[COLS] = { 15, 14, 13 }; //connect to the column pinouts of the keypad
int count = 0;
Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
char entryStr[13]; // This can hold up to 4 digits
int i = 0;
//char n1, n2, n3;
//char buf[15]; // i put here***
char n1[11], n2[11], n3[11];
void setup()
{
    Wire.begin();
    Serial.begin(9600);
    Serial.begin(9600);
    lcd.begin(20, 4);
    ask();
}

void loop()
{
    Wire.requestFrom(2, 3); // request 6 bytes from slave device #2 for(int i=0;i<3;i++) {

    int c = Wire.read(); // receive a byte as character
    Serial.print(c);
    table[i] = c;
    Serial.print('\t');
    // print the character } Serial.print('\n'); Serial.print(table[0]); Serial.print('\t'); Serial.print(table1); Serial.print('\t'); Serial.print(table[2]); Serial.print('\n');

    //if(table[0]<=8) //{ //Serial.print("Flame Detected!"); //Serial.println("Level1");
}
void ask()
{

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no1.:");
    lcd.setCursor(0, 1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    GetNumber(n1, sizeof(n1) - 1);;

    Serial.print(n1);

    delay(1);

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no2.:");
    lcd.setCursor(0, 1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    GetNumber(n2, sizeof(n2) - 1);

    Serial.println(n2);
    delay(1);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no3.:");
    lcd.setCursor(0, 1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    GetNumber(n3, sizeof(n3) - 1);

    Serial.println(n3);
    delay(1);
    Serial.println(n1);
    Serial.println(n2);
    Serial.println(n3);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("list of numbers ");
    lcd.setCursor(0, 1);
    lcd.print("will be shown press");
    lcd.setCursor(1, 2);
    lcd.print("reset if wrong");

    delay(7000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Numbers Stored:");
    lcd.setCursor(0, 1);
    lcd.print("no1.:0");
    lcd.print(n1);
    lcd.setCursor(1, 2);
    lcd.print("no2.:0");
    lcd.print(n2);
    lcd.setCursor(2, 3);
    lcd.print("no3.:0");
    lcd.print(n3);
}
void GetNumber(char* result, const int maxLength)
{
    char key = kpd.getKey();
    int i = 0; // how far through buffer we are
    while (key != '#') {
        switch (key) {
        case NO_KEY:
            break;

        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':

            lcd.print(key);
            if (i < maxLength) {
                result[i++] = key;
                result[i] = 0; // terminating null
            }
            break;

        case '*': // backspace
            if (i > 0) {
                i--;
                result[i] = 0; // terminating null
            }

            break;
        }

        key = kpd.getKey();
    }

} // end of GetNumber

what i mean is The number i input in keypad is the same number iin LCD thats right.  But i want only in LCD to display 11 numbers only.

You declared n1 to be 11-char long, which doesn't have room for 11 numbers plus the null terminator. How are you getting 11 correct numbers in the first place is probably random.

Thank you. Can you give me any idea how can i fix it?

If 11 is not enough space for 11 numbers plus a null-terminator, I wonder what would be enough space?


text:
Interfacing Arduino with Python Serial
I am implementing an FIR filter using Arduino. I am using an input signal as an audio signal. The audio signal has a duration of 3 seconds with total samples, 66150. What I am doing is reading this file in python and storing the data in an array. Using Serial, I want to send this sampled data to Arduino serial and process it, then send it back to serial and receive in  Python.
Python Code
import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.io import wavfile # get the api
import serial, time

samplerate, data = wavfile.read("sample.wav")
samples = len(data)
plt.plot(data[:20000])
arduino = serial.Serial('COM4', 9600, timeout=.1)
time.sleep(1) #give the connection a second to settle

for i in range(0,samples):

    arduino.write(data[i])
    time.sleep(1)
    print(arduino.readline())

Arduino Code
  void setup() {

  Serial.begin(9600);
  }
  int i = 0;
  int newdata[10];
  void loop() {
     if(Serial.available() > 0) {
          int data = Serial.read();
          newdata[i] = data;
          Serial.print(newdata[i]);
          i = i+1;
        }
   }

The problem I am facing is that I am stuck at very first step. As a check, I sent 10 samples values at start from Python to arduino using a loop and tried to recover them back to read on Python console. These values were not correct. When I entered a string inside the arduino.write(), it was receiving but when I input a variable inside the arduino.write(), it doesn't print that value after transferring back to python.
I just tried many things like changing to string but I didn't get the desired result. The output for this code is attached. Tomorrow is my submission and I am stuck in this thing. Help will be highly appreciated.

I want just to check whether the value I am writing to arduino from python is correct or not. Firstly I sent string from Python to arduino it was fine. But when i tried variable data, it doesn't catch that value. The very first step is going wrong  so I can not proceed further (for processing stage).

int values or float values which are stored in data array are not being transferred to arduino. So if I can't get proper value of x[n] at a point it will not be useful for implementation of an FIR filter.

I just edited the question with more explanation. Kindly look over it.

first problem. you don't reset i

second problem. you read a byte/character and then print it as int. but print(int) will output the number as text. use Serial.write(data);

I have found a way to tackle this.
Here is my arduino code:
char buf[100];
const double coefficients[28] = {
-0.006416610121367, -0.01179616274682, -0.01212859343535,-0.001491136183145,
 0.0175211951058,  0.03193599126761,   0.0259553014052,-0.004580133449276,
-0.04206485416456, -0.05260424218688,-0.007566809377484,  0.09242896920118,
 0.2100842841173,   0.2894365184419,   0.2894365184419,   0.2100842841173,
 0.09242896920118,-0.007566809377484, -0.05260424218688, -0.04206485416456,
-0.004580133449276,   0.0259553014052,  0.03193599126761,   0.0175211951058,
-0.001491136183145, -0.01212859343535, -0.01179616274682,-0.006416610121367
};

int order_of_filter = 27;
int sample_array[28] = {};
double output_sample = 0;
void setup()
{
  Serial.begin(9600);
  Serial.setTimeout(50000);
}
void loop()
{
  int  sample_in;
  int num_read = Serial.readBytesUntil('\n', buf, 100);
  buf[num_read] = '\0';
  sscanf(buf, "%d", &sample_in);
  for (int i = order_of_filter; i > 0; i--)
  {
    sample_array[i] = sample_array[i-1];
  }

  sample_array[0] = sample_in;

  for(int i = 0; i<=order_of_filter; i++)
  {
    output_sample = output_sample + sample_array[i]*coefficients[i];
  }
  Serial.println(output_sample);
  output_sample = 0;
}

And here is my Python Code:
    import matplotlib.pyplot as plt
  from scipy.fftpack import fft
  from scipy.io import wavfile # get the api
  import serial, time
  import numpy as np
  import sounddevice as sd

  arduino = serial.Serial('COM4', 9600, timeout=1) #COM port depends on the USB port
 time.sleep(3) #time to get connection ready
 # %%

 fs, data = wavfile.read('hfsound.wav')
 samples = len(data)
 #Plot the signal
 plt.plot(data[:samples])
 plt.ylabel("Amplitude")
 plt.xlabel("Time")
 plt.title("Time Domain Response of the Input Signal")
 plt.grid()
 plt.show()
 #Plotting fft
 fft_input = fft(data)
 half_length = int(len(fft_input)/2)
 omega_axis = np.linspace(0, fs/2, half_length)
 fft_n = fft_input[:half_length]
 plt.plot(omega_axis,abs(fft_n))
 plt.xlabel('frequency')
 plt.ylabel('Amplitude')
 plt.title("Frequency Domain Response of the Input Signal")
 plt.grid()
 plt.show()
 # %%

 #Declare an Array of zeros
 outputArray = np.zeros(64000)
 #Sending data to aurdino
 for i in range(samples):
     number = data[i]
     string = str(number).encode(encoding='utf-8') + b'\n'
     arduino.write(string)
     byt = arduino.read_until();
     print(byt.strip())
     outputArray[i] = byt.strip()

 arduino.close()
 # %%

 #Plotting Output waveform
 #Plot the time-domain output signal
 plt.plot(outputArray[:len(outputArray)])
 plt.ylabel("Amplitude")
 plt.xlabel("Time")
 plt.title("Time Domain Response of the Output Signal")
 plt.grid()
 plt.show()

 #Plotting fft of output
 fft_out = fft(outputArray)
 half_length = int(len(fft_out)/2)
 omega_axis = np.linspace(0, fs/2, half_length)
 fft_n = fft_out[:half_length]
 plt.plot(omega_axis,abs(fft_n))
 plt.xlabel('frequency')
 plt.ylabel('Amplitude')
 plt.title("Frequency Domain Response of the Output Signal")
 plt.grid()
 plt.show()
 # %%

 #Playback code
 sd.play(outputArray, fs)
 # %%

    arduino.write(data[i].tobytes())
    time.sleep(.1)
    print(int.from_bytes(arduino.readline(),byteorder='little') )

Is this what you whant?


text:
LED won't turn on and serial monitor won't display values
I am trying to use my Arduino to record some values from a photo-resister. The idea is when a character other than g is read the LED will turn on and 512 values will be recorded.
When I type in a character in the serial monitor whether it is g or not it just says 1 or 0 but doesn't not provide me with the values I need from the photo-resistor. My code is as follows:
int timeOut = 60000;
int pollTime = 0;
int time = 0;
unsigned long startTime = 0;
unsigned long endTime = 0;
int x = 0;
int Vs[512];
int analogPin = 0;

void setup() {
  Serial.begin(9600);
  pinMode(9, OUTPUT);
  while (!waitFor('g', 200, 60e6)) {}
  analogWrite(9, 128);
  startTime = micros();
  for (x = 0; x < 512; x = x + 1)  {
    Vs[x] = (analogRead(analogPin));
  }
  endTime = micros();
  for (int x = 0; x < 512; x = x + 1)  {
    Serial.println(Vs[x]);
  }
  Serial.println(endTime - startTime);
}

void loop() {
}

boolean waitFor(char in, int pollTime, int timeOut)  {
  boolean done = false;
  char charWait;
  time = micros();
  while (time < timeOut)  {
    if (Serial.available())  {
      charWait = Serial.read();
      done = (charWait == in);
      Serial.println(done);
    }
  }
}

Since you never update time, then while (time < timeOut) {...} is an infinite loop.

Like Edgar says, what you need to do is this:
bool waitFor(char in, int pollTime, unsigned long timeOut)
{
  while (micros() < timeOut)
  {
    if (Serial.available())
    {
      if (Serial.read() == in)
      {
        Serial.println("done");
        return true;
      }
    }
    delay(pollTime);
  }
  return false;
}

If it still doesn't run after that then change setup() to this:
void setup()
{
  Serial.begin(9600);
  Serial.println("Initialising...");
  pinMode(9, OUTPUT);
  while (!waitFor('g', 200, 60e6)) {}
  Serial.println("g command received...");
  analogWrite(9, 128);
  Serial.println("About to start...");
  startTime = micros();
  for (x = 0; x < 512; x = x + 1)  {
    Vs[x] = (analogRead(analogPin));
  }
  endTime = micros();
  Serial.println("Finished...");
  for (int x = 0; x < 512; x = x + 1)  {
    Serial.println(Vs[x]);
  }
  Serial.print("The result is : ");
  Serial.println(endTime - startTime);
  Serial.println("All finished.");
}

This still doesn't print anything to the serial monitor.

OK.  Can you alter the setup function as above and report what the last line of output is.  If you get no output at all then check you have the correct serial port.

In the prototype of waitFor(), timeout should be unsigned long: and int can be no bigger than 32767.


text:
Lowering cost of using NRF24L01 radio module for communication between several Arduinos
I have several Arduino Uno's if I am using several NRF24L01 modules to transmit a simple pulse (1 bit of information which can be high or low) between them-from one Arduino to the rest of them. Then I was considering, because the information is one bit of information only can I replace the other receiving NRF24L01 module's with something cheaper (and probably simpler) ?-may something based on like a simple tank LC circuit?-or it maybe another simple circuit instead of the LC one. The intuition for asking the question is because only 1 bit of information (which maybe represented by a string of 1's or another known string X if it makes the decoding simpler)  is transmitted then the receiving circuit maybe simplified somehow -rather than use something like the full circuitry of a NRF24L01 module. Elaborating further on a possible scheme for decoding X may be done by just counting the "marks ratio"-as done "in a marks and spaces style scheme"-e.g. if there are known ratio of 1's, than compared to the usual ratio, then we can consider that to be a high signal received -the number of 1s sent is such that the binary information from the NRF24L01 protocol, that sends X, would not significantly affect the ratio of the 1s. however I don't know how accurate my intuition is here.
So in a nutshell, I want to know if there is a simple circuit that does what I want - an answer may include a custom Arduino sketch suggestion for the transmitter and/or receiver.

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

To receive a signal from an nRF24L01 you either need another nRF24L01 or to reimplement the nRF24L01 in discrete components. That's a big, complex circuit requiring precision components and PCB layout. At 2.4GHz, with GFSK modulation, you need amazing skills to create something that would work reliably - and the cost would be astronomical compared to the cost of an nRF24L01.
Your thought that you are "only sending 1 bit of data" is completely wrong. Yes, you may be providing only 1 bit of data to the library that controls your nRF24L01 - however the nRF24L01 then encapsulates that single bit into a fixed length packet including source and destination addresses, checksums, and even implements a reliable ACK/NACK system for packet retransmission. None of that can be thought of as a "single bit" once it gets out onto the airwaves - so the system that you came up with would have to be able to interpret and handle that entire packet and provide any requested ACK/NACK signals back to the transmitter.
If you want to receive with a simpler system then you need to also transmit with a simpler system. The simplest system is probably the 433MHz PAM systems you find on eBay. You pull the input pin HIGH on the transmitter and the output pin on the receiver goes HIGH. You pull the transmitter pin LOW and the receiver pin goes LOW. (Basically you turn the carrier on and off at one end, and the other end tells you if the carrier is on or off - Pulse Amplitude Modulation [also known as On Off Keying - OOK]).
Coupling that with UART signals it's possible to send actual data, but if all you need is HIGH/LOW signalling then you can drive it direct with any GPIO pin.
They are incredibly crude, and would never pass any kind of emissions testing, but they get the job done at a very low cost.
While it may be possible to create a crude 2.4GHz PAM transmitter and receiver, owing to the broadband spectrum harmonics you would have unless you managed to produce an absolutely pure sine-wave with zero harmonic distortion, the interference it would cause to other devices nearby (such as your WiFi connection) would cause untold problems. No doubt your neighbours would have something to say about that - and maybe FCC / OFCOM / whoever.

I have several Arduino Uno's if I am using several NRF24L01 modules to transmit a simple pulse (1 bit of information which can be high or low) between them-from one Arduino to the rest of them.

Let us assume that the broadcast has to reach all. None of the listeners are allowed to drop messages. How would this be achieved? Each listener would have to acknowledge the message.
Anyway reasoning about the application requirements and communication protocol may help determine if a "cheaper" solution is possible.
IMHO using NRF24L01+ is a cheap solution in this scenario.
Cheers!


text:
Stepper motor with HCSR-04 sensor
I want to make a stepper motor increase and decrease speed working with a HCSR04 sensor. The idea is that if the sensors detects an object the stepper motor is going to decrease, and stop as close as possile to the object.
I have made some code, and it is sorta working..
My current code looks like this:
if (distance > 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(500); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(500); // Wait
}

if (distance > 20 && distance < 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(2000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(2000); // Wait
}

if (distance > 10 && distance < 20)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(10000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(10000); // Wait
}

if (distance > 1 && distance < 10)
{
  //digitalWrite(13,HIGH); // Output high
  //delayMicroseconds(1000); // Wait
  digitalWrite(13,LOW); // Output low
}

But I thought it could be easier, So I made a function:
void velocity()
{
 digitalWrite(13,HIGH); // Output high
 delayMicroseconds(500); // Wait
 digitalWrite(13,LOW); // Output low
 delayMicroseconds(500); // Wait
}

Now my question is: Can I manipulate the delayMicroseconds to change if the distance changes? Is there a formula to do so?
Entire code:
int trigPin = 11;
int echoPin = 10;

void setup()
{
pinMode(trigPin, OUTPUT); //Sensor
pinMode(echoPin, INPUT); //Sensor
pinMode(6,OUTPUT); // Enable
pinMode(13,OUTPUT); // Step
pinMode(12,OUTPUT); // Dir
digitalWrite(6,LOW); // Set Enable low
digitalWrite(5,LOW); // Set Step low
Serial.begin(9600);
}

void loop()
{
//rotateleft();
//Serial.println("ik draai nu exact een rotatie linksom");
//delay(1000);
//rotateright();
//Serial.println("ik draai nu exact een rotatie rechtsom");
//delay(1000);
//velocity();

 //sensor
 long duration, distance;
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(5);
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = (duration/2) / 29.1;
 Serial.print ("cm ");
 Serial.print (distance);

//eigen creatie

if (distance > 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(500); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(500); // Wait
}

if (distance > 20 && distance < 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(2000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(2000); // Wait
}

if (distance > 10 && distance < 20)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(10000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(10000); // Wait
}

if (distance > 1 && distance < 10)
{
  //digitalWrite(13,HIGH); // Output high
  //delayMicroseconds(1000); // Wait
  digitalWrite(13,LOW); // Output low
}

//Own functions
}

void velocity()
{
 digitalWrite(13,HIGH); // Output high
 delayMicroseconds(500); // Wait
 digitalWrite(13,LOW); // Output low
 delayMicroseconds(500); // Wait
}

void rotateleft()
{
 digitalWrite(12,HIGH); // Set Dir high
 for(int x = 0; x < 200; x++) // Loop 200 times
  {
    digitalWrite(13,HIGH); // Output high
    delayMicroseconds(1000); // Wait
    digitalWrite(13,LOW); // Output low
    delayMicroseconds(1000); // Wait
   }
  }
  void rotateright()
  {
   digitalWrite(12,LOW); // Set Dir high
   for(int x = 0; x < 200; x++) // Loop 200 times
   {
     digitalWrite(13,HIGH); // Output high
     delayMicroseconds(1000); // Wait
     digitalWrite(13,LOW); // Output low
     delayMicroseconds(1000); // Wait
   }
 }

You might look into using the constrain() function to establish a distance beyond which you will run at full speed, and then use the map() function to turn that into an inverse relationship between distance and delay.  Beware of possible hesitations while measuring, and the fact that ultrasonic sensors have a minimum distance, so make sure you don't go to full speed when something is closer than the minimum!

Assuming you have a distance variable containing the distance measured from your sonar sensor in cm. You can use that value to adjust the delay times in between your steps.
EDIT Modified code to increase speed when distance increases
int time = 0;
int timeWait = 1000; //interval in milliseconds between each distance reading
int maxDelay = 1000;

void velocity(int speed){
   int trim = 10;
   digitalWrite(13,HIGH); // Output high
   delayMicroseconds(maxDelay - speed*trim); // Wait
   digitalWrite(13,LOW); // Output low
   delayMicroseconds(maxDelay - speed*trim); // Wait
}

int readDistance(){
 //code to read distance
 return distance;
}

void setup(){
time = millis();
}

void loop(){
   if(millis()-time > timeWait){ //only read distance if 1000ms has elapsed since the last reading
     time = millis();
     int distance = readDistance(); //your distance reading code;

   }
   velocity(distance);
}`

EDIT 2
You'll also need something to handle upper and lower limits for delays (i.e. you don't want delayMicroseconds(0) or any negative numbers and  you don't want to include extraneous distance readings)

This looks to increase the delay (ie, move slower) longer distance, which seems to be the opposite of the goal.

I'll edit to subtract from the maximum delay which should increase speed when distance increases.


text:
AC meter By ADC timer interrupt from Nick Gammon
I want to read ADC from the pin A0 and A1. I have written in this code, however.
I took this code came from Nick Gammon
Thank You
//////////////////////////////////////////////////////////////////////////////
this is code
const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

// ADC complete ISR
ISR (ADC_vect)
  {
  if (resultNumber >= MAX_RESULTS)
    ADCSRA = 0;  // turn off ADC
  else
    results [resultNumber++] = ADC;
  }  // end of ADC_vect

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);  // WTF?
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

  // wait for buffer to fill
  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
    Serial.println (results [i]);

  }  // end of setup

void loop () { }

What is the problem??

Just change ADMUX in the ISR.

I want to read from a0 and a1, but the code read from a0 alone.

what  change ADMUX ?

It is unclear what you are asking. Please improve your question.

This is code read ADC from A0  (voltage)  but I want to read ADC from A0 (voltage) and A1 (current )  I need to write code to add, however.

Please stop repeating the question! This question is very badly written, and hard to understand. Repeating does not help! Instead, read How to ask, click on the edit link, and take the time to write properly. You should also link to the Gammon's page from where you copied that code.

I want to read ADC from the pin A0 and A1

In the code you posted the first line is:

const byte adcPin = 0;  // A0

To read from A1 the change is simple:
const byte adcPin = 1;  // A1

i am sorry i come from thailand

Whatever country you are from does not excuse from you posting the same question many, many times.
I suggest you read the datasheet:
ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet
Scroll down to 24.9.1 ADMUX – ADC Multiplexer Selection Register

You can read two analog channels like this:
int first_reading = analogRead(A0);
int second_reading = analogRead(A1);

If this does not fit your purpose, then your question was not asked
properly: rewrite it and clearly state your requirements. Explain why
the simple solution does not work for you.
If this does work for you, then stop (for now) reading advanced
tutorials, like the one where you found your code, and focus on the very
basics: the Arduino examples in the 01.Basics section, then the
03.Analog section.

i want  interrup ADC A0 and A1

i am sorry i come from thailand

I am do Meter Ac.    adcPin A0(measure Voltage) and adcPin A1(measure Current)   Thank You

this code from Nick Gammon read adcPin = A0

constexpr byte  adc_mux_setting = bit(REFS0) | bit(ADLAR); // Left alligment for ADC result, so ADCH contains 8b result.

volatile uint16_t         sum_u = 0;
volatile uint16_t         sum_i = 0;
volatile uint8_t   resultNumber = 0;

// ADC complete ISR
ISR (ADC_vect) {
    if (resultNumber & 1) {
        sum_u += ADCH-(sum_u>>8);                  // 8bit resolution, something like floating average
    } else {
        sum_i += ADCH-(sum_i>>8);                  // 8bit resolution, something like floating average
    }
    ADMUX  = adc_mux_setting | (++resultNumber&1); // Expecting pins A0 and A1 (otherwise offset must be added)

    TIFR1 |= bit(OCF1B);                           // clear the flag otherwise it never starts ADC conversion (not without ISR)
                                                   // it's here because I don't want to ADC starts conversion before switching channel
}

void setup () {
    Serial.begin(115200);
    Serial.println("Start");

    // reset Timer 1
    TCCR1A  = 0;
    TCCR1B  = bit(CS11) | bit(WGM12);              // CTC, prescaler of 8
    TCNT1   = 0;
    //TIMSK1 = bit (OCIE1B);                       // it doesn't work without clearing OCF1B
    OCR1A   = 80;                                  // it never reaches 80 so it never sets interrupt flag
    OCR1B   = 79;                                  // 40 uS - sampling frequency 25kHz for both (15kHz for each)

    ADCSRA  = bit(ADEN)  | bit(ADIE) | bit (ADIF); // turn ADC on, want      interrupt on completion
    ADCSRA |= bit(ADPS2);                          // Prescaler of 16
    ADMUX   = adc_mux_setting;                     // A0 goes first
    ADCSRB  = bit(ADTS0) | bit(ADTS2);             // Timer/Counter1 Compare Match B
    ADCSRA |= bit(ADATE);                          // turn on automatic triggering
}

void loop () {
    if (resultNumber == 0) {                       // print results after 128 measures for both channels
        Serial.print(sum_u);
        Serial.print(' ');
        Serial.println(sum_i);
        while (resultNumber == 0);                 // I want to print it only once per iteration
    }
}


text:
Using an Arduino as a electrical mains switch
How do I make an electrical switch using Arduino, that when it receives signal (wirelessly or through a LAN port) to switch off it disconnects the switch and then again told to turn on turns the switch on?
The main problem I am facing is that I need to give a 5V output to turn off the transmission between two wires having voltage rating of 230V.

Google the phrase "Arduino Relay"

Relays are the only solution which you are looking for.!

You need two shields: a Network (i.e. Ethernet/Wi-Fi/GSM/3G) shield, and (as already mentioned); a Relay shield. Plus, some code to glue the two together. See Ethernet Switching - with Arduino for an example of how to do it.

Depending on the nature of your load and how you need to switch it, the type of electronically controlled switching device you should use will vary.  A cheap mechanical relay module can indeed be a simple solution for low-current devices switched at a no more than moderate rate, but if you have something high current like a heating element, inductive like a large motor, or need to do duty-cycle based control, you will need a different sort of switching element, perhaps TRIAC-based, but likely requiring a fair amount of surrounding circuitry for safety and longevity.

You need to use Relays.  There all kind of relays.
Regular and Solid state ... for controlling a Regular Relay using Arduino you will need a transistor (so you will able to provide the right current to the relay to close a circle)
There are a lot of guides for Arduino and Relays (for example)

As pointed out in the comments, I would need to use something known as a relay with my Arduino.


text:
MPU6050 Measure distance traveled or position
How can I use MPU-6050 with an arduino to measure the distance the robot traveled from it's starting point or just it's current position on the map?
The Robot should be moving in a map same as a 2D array and I need to detect it's position while it is moving and send the data to a station.

You won't - not with any degree of accuracy anyway.
You could attempt "dead reckoning" whereby you estimate the current speed by the acceleration and deceleration over time, and from that get a rough idea about the distance travelled in any one direction, but the accuracy will be so poor and the drift so huge that it would be next to pointless.
Instead you really want to monitor the wheels. Count how many revolutions (or half revolutions, quarter revolutions, whatever accuracy you need) and combine that with the circumference of the wheels to calculate how far you have travelled.