text:
DFPlayer Mini unable to begin
I'm using a ESP32-Wroom-32d Firebeetle V4 board and the DFplayer Mini but
I'm unable to get a signal from the DFPlayer to the ESP.
I checked every connection with a multimeter and see that the player gets 5V and read the incoming signal from the ESP. When I unplug the power and re-plug it to the DFPlayer, I get a signal from the RX pin but that's the only time I get a signal.
I'm using the test program from the site but nothing seems to work.
I always get the "unable to begin" error.
The SD card is inserted and the files are stored correctly. The SD card is also 128 MB so that's also not the issue.
If I connect my speaker it also doesn't help.
I don't know what to check anymore or if my DFPlayer is fried.
I connected the IO3 pin which is the RX pin to the TX pin of the DFPlayer and the TX pin which is IO1 from the ESP to the RX pin of the DFPlayer. I also have a small 2 watt speaker connected to the SPK1 and the SPK2 pin of the DFPlayer. I also tested it without the speaker and still get the same error message and no response from the DFPlayer.
/***************************************************
DFPlayer - A Mini MP3 Player For Arduino
 <https://www.dfrobot.com/index.php?route=product/product&product_id=1121>

 ***************************************************
 This example shows the basic function of library for DFPlayer.

 Created 2016-12-07
 By [Angelo qiao](Angelo.qiao@dfrobot.com)

 GNU Lesser General Public License.
 See <http://www.gnu.org/licenses/> for details.
 All above must be included in any redistribution
 ****************************************************/

/***********Notice and Trouble shooting***************
 1.Connection and Diagram can be found here
 <https://www.dfrobot.com/wiki/index.php/DFPlayer_Mini_SKU:DFR0299#Connection_Diagram>
 2.This code is tested on Arduino Uno, Leonardo, Mega boards.
 ****************************************************/

#include "Arduino.h"
#include "DFRobotDFPlayerMini.h"

DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);

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

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

  if (!myDFPlayer.begin(Serial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }
  Serial.println(F("DFPlayer Mini online."));

  myDFPlayer.volume(10);  //Set volume value. From 0 to 30
  myDFPlayer.play(1);  //Play the first mp3
}

void loop()
{
  static unsigned long timer = millis();

  if (millis() - timer > 3000) {
    timer = millis();
    myDFPlayer.next();  //Play next mp3 every 3 second.
  }

  if (myDFPlayer.available()) {
    printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
  }
}

void printDetail(uint8_t type, int value){
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }
}


text:
Problem while interfacing LCD screen with Arduino
I tried to interface an LCD screen with my Arduino but I have a problem - Nothing is being displayed on my LCD screen:

Here is the code:
#include<LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);  // sets the interfacing pins

void setup()
{
 lcd.begin(16, 2);  // initializes the 16x2 LCD
}

void loop()
{
  lcd.setCursor(0,0);           //sets the cursor at row 0 column 0
  lcd.print("16x2 LCD MODULE"); // prints 16x2 LCD MODULE
  lcd.setCursor(2,1);           //sets the cursor at row 1 column 2
  lcd.print("HELLO WORLD");     // prints HELLO WORLD
}

Probably your background is not set correctly (there is a way to change the contrast).

Contrast looks good in the photo -- one row of all-on blocks indicates an uninitialized display.

Your photo doesn't clearly show where the wires are going. Can you create a schematic showing the wiring setup, or at least a better photo that clearly shows where each wire from the LCD goes to the Arduino?

@josecanuc the uninitialized screens can be seen even if the contrast is set wrong;

In the setup() you have to state what pin the Vo (display contrast pin) on the LCD is connected to. Before the
lcd.begin(16,2)

try
analogWrite(pin Vo is connected to, contrast you want to set the screen to);

An example would be:
analogWrite(6,80);

source: Stack Exchange

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

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

sort: votes


text:
Arduino Nano input voltage
Can I supply an Arduino Nano 5 V 1 A unregulated in pin 27?
It has a PIR sensor, a LDR sensor and switch drive high power MOSFET trigger module connected to it.

Probably not. Pin 27 is the 5V pin. That is the voltage at which the microcontroller runs. It is safer to use the VIN pin with 7.5v, although sometimes 5v is applied to the 5v pin, but that could destroy the voltage regulator. The most dangerous part is the word "unregulated". Does that mean that it can be anything between 4 and 7v? Do not apply that to the 5v pin.

Okay. Thank you!

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


text:
How can I compare two serial port readings on Arduino Mega?
I'm writing some code that compares information from two Arduino Unos by an Arduino Mega 2560. The problem that I'm having is that when I read the information coming in through Serial1 and Serial2 on my if statements, I get both inputs out on my serial monitor for the Mega, but if I try to compare them after I have read them it comes out not working the way it is intended. I don't know if I might be missing some syntax on my code or if I'm doing this wrong but I would appreciate any help I can get.
byte inData;

byte inDataTwo;

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

  while (!Serial)
  {
    ; // wait for serial port to connect. Needed for native USB port only
  }
}

void loop()
{
  if (Serial1.available()>0 )
  {
      inData = Serial1.read();
      Serial.print(char(inData));
  }
  if (Serial2.available()>0)
  {
    inDataTwo = Serial2.read();
    Serial.print(char(inDataTwo));
  }
  if(inData == inDataTwo)
  {
    Serial.print("true");
  }
  else
  {
    Serial.print("False");
  }
}`

can you provide a sample output as well..!?

what do you mean sample output? when i get the information on the arduino mega i get the results from both my arduino unos and i can display them on the screen. im sending letters through a laser and the two arduinos convert the information back to characters and i can display that on the screen. when i connect them to the arduino mega the mega displays both of the same character on the screen. I know is working but when i compare them, the program seem to do not what i want to do

print them in else

can you tell what are you sending on serial terminal?

Also, I see a small character after your last bracket for the loop(). I thought that it was a speck of dirt on my screen, but you actually have a character.

I think your code is implemented wrong in general. Even if it worked "like intended" it would not behave like you might want it to.
The first problem is, that you are polling for bytes that are received asynchronuously. That means that  two byte sequences must not only be equal, they must also be sent "at the same time" if they should pass your comparison test. As the atmega will loop() very fast, there is only very little tolerance in timing.
Secondly, the variables you write received values to are not reset, meaning that once they have the same value they will pass the if statement until another byte has been received. Actually they aren't initialized and therefore will be 0 at the very beginning. So I wonder why you don't get your Serial interface flushed with true. Is this actually the entire code?
As a solution I suggest accumulating received bytes into a buffer and waiting for a soecific termination byte (often /n). If a termination character has been received, perform the comparison on that buffer.


text:
Fan regulator control from Arduino
I'm trying to control my ~230 V fan from the Arduino.
Can anyone say the best possible ways to design a fan regulator that can be controlled by the Arduino using a low cost design.

Use TRIAC Circut. In this you can control the current flow to the FAN

How many relays needed to make 5 level regulator? I think it is not effective design.

Do you want a variable speed controller or single-speed? And is this a 3 phase motor?

Single phase motor and variable speed controller for my home automation.

Relay don't control current that's why is suggested TRIAC

I use Kemo module to regulate a heater. They can regulate an inductive load too. For MCU control they have a digital pot module M150 controlled by PWM. https://www.kemo-electronic.de/en/Light-Sound/Effects/Modules/M012-Power-Control-110-240-V-AC-1200-VA.php

@Juraj Thanks. That's more cost design than the 5 relay circuit which is nearly 250 INR. From Amazon lower cost of this module is 3,800 INR.

I enhanced my answer

To control AC power for inductive load (motor) a Triac is used. The concept is called phase cutting. It works for a resistive load (heater) too.
This module is designed for phase cutting. It contains a zero crossing detector and a Triac. The control is done in MCU. The zero crossing detector is wired to an interrupt pin. The control signal for the Triac is wired to an output pin. In external interrupt function you set a timer interrupt to send a pulse to the Triac after some microseconds. Longer off time results in less power for the motor.

At 50 Hz AC, one pulse is 10 milliseconds. To cut a part of AC wave out, activate the Triac gate for 20 microseconds after 0 to 10 milliseconds. Triac turns self off the AC line at next zero crossing.
Robotdyn has a library for the module.
EDIT:
I bought the Robotdyn AC dimmer module to use it in my AC heater regulation project and I tested it with a incandescent light bulb and a fan. (video on youtube)
The library by Robotdyn works, but it is designed to control many dimmers and uses a timer interrupt every 12 microseconds (yes, micros). The library sets the interrupts over MCU registers.
I wrote an arduino fade-in/out sketch using TimerOne library to demonstrate phase cutting with this module.
#include <TimerOne.h>

const byte INTERRUPT_PIN = 2;
const byte TRIAC_PIN = 4;
const byte TRIAC_PULSE_MICROS = 30;

const int FADE_MAX = 9800;
const int FADE_MIN = 2000;

volatile bool triacOn;
volatile int period = FADE_MIN; // microseconds cut out from AC pulse

int fadeAmount = 10;

void zeroCrossing() {
  triacOn = false; // triac tuns off self at zero crossing
  Timer1.setPeriod(period); // to call triacPulse() after off period
}

void triacPulse() {
  if (triacOn) { // stop pulse
    digitalWrite(TRIAC_PIN, LOW);
    Timer1.stop();
  } else { // start pulse
    digitalWrite(TRIAC_PIN, HIGH);
    triacOn = true;
    Timer1.setPeriod(TRIAC_PULSE_MICROS);
  }
}

void setup() {
  pinMode(TRIAC_PIN, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), zeroCrossing, RISING);
  Timer1.initialize();
  Timer1.attachInterrupt(triacPulse);
}

void loop() {
  period = period + fadeAmount;
  if (period <= FADE_MIN || period >= FADE_MAX) {
    fadeAmount = -fadeAmount;
  }
  delay(25);
}

EDIT 2 version with triac activated by 'pwm' pin
const byte TRIAC_PIN = 9;
const byte ZC_EI_PIN = 2;

unsigned long topMicroseconds = 9700; // 10000 micros is between zero crossings
int prescaler = 8;
byte prescalerBits = _BV(CS11); // 8

void zeroCrossing() {
  TCNT1 = 0; // reset the timer counter
}

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

  attachInterrupt(digitalPinToInterrupt(ZC_EI_PIN), zeroCrossing, RISING);

  pinMode(TRIAC_PIN, OUTPUT);
  uint32_t topPeriod = ((F_CPU / 1000000)* topMicroseconds) / prescaler ;
  ICR1 = topPeriod;
  OCR1A = topPeriod + 1; // full off
  // WGM mode 14 - Fast PWM w/TOP=ICR1
  TCCR1A = _BV(WGM11) | _BV(COM1A0) | _BV(COM1A1);
  TCCR1B = _BV(WGM13) | _BV(WGM12) | prescalerBits;
}

void loop() {
  if (Serial.available()) {
    unsigned long microseconds = Serial.parseInt();
    Serial.find("\n");
    uint32_t period = ((F_CPU / 1000000)* microseconds) / prescaler ;
    OCR1A = period;
  }
}

on SAMD it is possible to setup this to start the timer on external interrupt over event, without an interrupt function. then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals
EDIT 3:
The TriacDimmer library version 1.1.0 for AVR Arduinos available in Library Manager works good with this dimmer. Fun fact: It uses timer1's input capture on pin 8 instead of external interrupt on pin 2 or 3.

the modules and component I linked in comments use this method. they work as 'pwm to phase cutting adapters'

The animated graphic is of rectified AC, does it really get down to a zero crossing to do a shut-off?

@DaveX, not to exact zero crossing but in the scale the animation is right

The waveform in the animation isn't right for AC--there's a sharp 'V' at length/2, it looks rectified, so instead of 50Hz 230Vrms AC, it's showing 100Hz (10ms) pulsed DC.   The robotdyn module uses a triac that won't rectify like that diagram.  It should have the second half of the top diagram flipped around it's X axis and twice the height.

@DaveX, the negative part is mirrored up. I didn't find a better one. I linked the animation from Wikipedia page about phase cutting. now I see SE copied the animation

@juray You properly say that the RobotDyn library raise an interrupt every 12us to control multiple dimmers. But this is just an unoptimized implementation since I have implemented this library https://github.com/fabianoriccardi/dimmable-light which triggers only 2 interrupts per semi-period.

Its not exactly what you are looking for but it will help Arduino-controlled-light-dimmer-The-circuit.
Here is the sample project in which TRIAC is used with arduino for controlling the flow of current to the light. In your case Light or better we can say load is FAN. This will help you in controlling the FAN Speed. Relay only act as switch and it won't control FAN Speed.

Link only answer? We are looking for comprehensive answers that provide some explanation and context. Very short answers cannot do this, so please [edit] your answer to explain why it is right. Additionally, we prefer answers to be self contained where possible. link only answers are frowned upon (as links tend to rot) & will be rendered useless if the linked-to content disappears. If you add more context and detail from the link, it is more likely that people will find your answer useful.

Thanks Vaibhav, My thought is TRIAC's AC phase may affect arduino board which will affect my analog sensor readings in arduino and their is chance to death too :-/.

Now I think I am better clear about what I want to say.

Finally i found it as a product available here
with the thyristor circuit and electrical-contactless servo (PWM or ANALOG input) motor ( to drive the input) will helps to drive the output from 0 to 220V. smooth fan regulator can also do this with servo motor and without any external electrical component requirement . If it is not efficient way with low cost design command or answer your way.  :-).

If your design is more efficient than mine your design is considered as answer. :-). Thanks in advance.

this is for manual regulation. you want to turn that pot with a motor?

@Juraj Thank you. That can be done by arduino PWM input. So we don't need to work for that.

the board I linked in my aliexpress comment looks better. labels and description swapped input/output (like you do: PWM input ?!), but the electronics should work

You are correct Juraj. That will perfectly match to this circuit ♥. But in question I asked to bring it in low cost design. Your answer is highly acceptable rather than cost.  That's why I'm not mentioned my design also correct.

@SivamaniV : If the pot is controlled manually, what is the purpose of arduino here.

@Learner pot is not manually controlled here. Servo motor controls the pot. Arduino triggers servo motor.

@SivamaniV, read my answer, if you visit Stack Exchange again

There is also the issue of isolation here, to keep the controller side from being connected to the mains for reasons of noise and safety.  The previous posters' comments about doing this with triacs or mosfets, and phase angle control are all true.  It is nearly impossible to control the speed of a single phase induction motor.   Anyway, the most elegant solution is to get a 3 phase fan motor and a variable frequency drive with low-voltage DC control input.  Run the pwm output from the Arduino through an opto-isolator (drive the internal led).  Use the DC reference on the speed control to power the output of the opto-isolator.  Run that through an rc lowpass filter to the speed control voltage input.  I think you could get out of this for around 200$US. Check surpluscenter.com.  there are many motors and drives out there.
-Hugh

It depends on the motor.
To quote MarkT from this post:

The simple advice is you can't.  Standard induction motors in domestic appliances cannot
safely be speed-controlled (some can be a little, but its not easy to find out by how much).
Get a DC fan

To quote dc42, from this post:

What sort of motors do the fans have? If they use induction motors,
then you won't be able to control the speed much using phase angle
switching - the speed is tied to the supply frequency. If they are
series-wound motors with brushes, then phase angle switching should
work.
The results you reported when you tried to use the velleman kit
suggests to me that the fans may have induction motors.

For more information, read:

How to control AC 220V fan speed with arduino's PWM output..?? and;
Changes in Dimming Circuitry! and;
Learn about zero-crossing. This might help How stuff works - dimmer switch.
AC Fan Speed Control with Arduino

Thanks Greenonline. But how fan regulators do this. From the blog, if I done with PWM signal with normal fan regulator circuit, the output pulse signal will affect the 50 Hz (Indian standard AC frequency) both home main supply box and connected devices.

Blog? What blog? Link?

that's arduino forum https://forum.arduino.cc/index.php?topic=100899.0 from the joy reply

As this reply to Joy's post states, you need to use zero-crossing detection, which Juraj's answer correctly demonstrates.


text:
SoftwareSerial + Serial.printlen() not working properly
I want to read a SMS message , find it's length and do some "substring();" operation on received SMS. My last two(2) statements do not work . How can I get correct answers? What are correct codes ?
#include <SoftwareSerial.h>
#include <string.h>
#include <ctype.h>
SoftwareSerial mySerial(2,3);

String TelephoneNumberText="";

void setup()
{
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);

  mySerial.begin(9600);
  Serial.begin(9600);
  delay(100);

  mySerial.println("AT+CMGF=1\r");    //Sets the GSM Module in Text Mode
  delay(500);
}

void loop()
{

 while(mySerial.available())
  {
   char s;
   s = mySerial.read();
   TelephoneNumberText = TelephoneNumberText + s;
   }

 Serial.println(TelephoneNumberText);           // this statement works

 Serial.println(TelephoneNumberText.length());  // this statement dose not works

 Serial.println(TelephoneNumberText.substring(0,3));// this statement dose not works

} // end loop

Serial.println(TelephoneNumberText);           // this statement works
Serial.println(TelephoneNumberText.length());  // this statement dose not works
Serial.println(TelephoneNumberText.substring(0,3));// this statement dose not works      /* please tell me correct codes for above two(2) statements */

Are you sure a string like this can be used?
Better anyway to not each time let a dynamic string be created, but use a fixed string e.g.
char TelephoneNumberText[16];

Set the length of the max number, and change other string functions accordingly.

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


text:
What is the definition of these arduino commands, and how do they affect the circuit?
I don't know if I am allowed to ask this question because really I could just look this up on google. The reason I'm asking here is because in google when you look up the definitions for the following commands, they treat you like you have good knowledge of arduino boards work. I however want to be treated as a beginner who just started learning arduino boards.
So I want to know the definitions of the following commands in a way that I could learn and teach new beginners without getting them confused.
So I want to know the clear definitions of these following commands:
analogWrite and also why does it have a limit of 255? what does this 255 mean?
analogRead  and also why does this have a limit of 1023? what does this mean?
digitalWrite and also how does this differ from analogWrite?
digitalRead and also how does this differ from analogRead?
Loop and setup also what is the void before it?
Variables and also how they are declared?
Map and also what does it map and how?
Serial.write and also how does this differs from analogWrite and digitalWrite?
If/else commands and when they should and shouldn't be used?
Like I said, I do not know whether the question is appropriate, but could be helpful to all the beginners learning Arduino.

It strikes me that you need to read some basic "Introduction to C programming" tutorials.

@Majenko Having basic instructions in this site could help too, even if it might not be the first go-to place to learn about arduino's. The answer provided below is clear, short and simple to understand, which is what beginners look towards.

This site is not the place for basic tutorials. There's already plenty of them around if you just google. Most of your questions can be answered by first learning the basics of the C syntax, which seems to be the information you are lacking to make sense of everything else.

"I could just look this up on google". Yes, you could.

I would recommend the Arduino on-line reference and tutorials. Please see https://www.arduino.cc/en/Guide/HomePage and explore the Learning menu.

These are reasonable questions, but Stack Exchange is not designed as a tutorial site. The intention is to ask a specific question (eg. "can I use a mousetrap to catch a rat?") and not a really general question (eg. "Please describe all the ways I can catch rats").

These are a lot of different questions. However, you can find most of the Arduino related answers in the official reference:
Arduino reference Guide
Some other answers:

how to declare variables:

e.g.
int x;

SerialWrite sends data to the serial port/UART, analogWrite and digitalWrite puts a voltage to a pin (simplified).
AnalogWrite is normally used for a value that has a range (like the intensity of a led), digitalWrite for an On/Off state (can also be for a led but just on/off).
if/else commands can be used to make a program make a decision.
e.g.
if (a == 10)
{
    Serial.println("10");
}
else
{
    Serial.println("Not 10");
}

void means 'nothing' ... in principle it means the functions (setup and loop) do not return any value. You can also define functions which return a value, e.g.
int add(int a, int b)
{
    return a + b;
}

Read in any C/C++ manual about the commands, get a beginner programmers handbook.
The limit of a pin, means the value cannot be more than 255 or 1023. This means that the range of the value you can get/set is between 0 and 255 or 1023.
The map command can be used to make a value within the range required.

short, simple, understandable and easy to remember. Thank you. Quick question about something, what do you mean the limit of a "pen"?, what is a 'pen'? is there a reason why they have limits?

@Utsave: you are welcome ... and I meant pin, not pen (I updated the answer). The main reason is that it has to be mapped to a value usable for computers. In practice e.g. a voltage can be anything from 0.00000 to 5.0000 V for example. However, computers use bits/bytes and it is not useful to keep 10 significant digts. With 1024 (0-1023 values) the accuracy is good enough and 1024 is 10 bits (2 to the power 10).


text:
Delay() is not working outside of interrupt
Delay() doesn't work inside ISR routines, but here I have used it in loop and outside interrupt section still Delay is not working, however there isn't any error coming. What is wrong?
int L = 2;
volatile int done0=0;                                //ISR variables
void recordL();                                              //ISR 1

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

pinMode(L,INPUT);
}

void loop() {

interrupts();
attachInterrupt(0,recordL,RISING);
done0=0;

while(!done0)
{
    Serial.println(millis());
}
noInterrupts();

Serial.println("Detected");
delay(5000);
Serial.println("After Delay");
}

void recordL()
{
  Serial.println("in Interrupt0");
  done0=1;
}

What is it for ? Perhaps you don't need interrupts at all. Please don't use a Serial.println in the while-loop, the serial output buffer will get full. Please don't use Serial.println in the interrupt routine, because the Serial library uses interrupts itself. In most cases the attachInterrupt is done only once in the setup function.

Looks like I have made lot of mistakes. I need interrupt because I want to detect sound coming from 2nd IO pin. After attaching interrupt once in Setup, do I need to do interrupts() and nointerrupts() in Loop section?

I prefer to keep the interrupts running and use just variables for interrupt detection. The Arduino Uno can run a small interrupt routine a few thousand times per second. I don't understand the sound signal from a second I/O pin, can you explain that ?

Actually I have 3 sound sensors and sound can come at any time at these sensors (If sound is greater than some threshold then 1 else 0), so it can come simultaneously to all 3 with very small difference in time. I want to measure that exact time when sound has reached sensor. So I am using 2 interrupt pin and 1 simple pin which is waiting for sound in loop.

@LookAlterno That's why I have set 'done0' to 1. You also telling that?

Yes, LookAlterno is telling that. What kind of sound sensors? What kind of timing differences do you want to measure? Perhaps you need to timestamp the trigger moment. The Arduino Leonardo/(Pro)Micro has 5 interrupts. With the EnableInterrupt library, every pin of the Arduino Uno has an interrupt: https://github.com/GreyGnome/EnableInterrupt (although it is a little slower). You probably want to detect the first interrupt, and not the interrupts followed directly after that. Please tell us what your project is about before stepping into the XY-problem trap: http://xyproblem.info/

@Jot thanks for your interest in project. My project is to identify direction of sound and make bot go in that direction with Obstacle avoidance. For deciding direction of sound I am using 3 sound sensors which uses Electret Microphones followed by amplifier and 'Time of Arrival' Principle. First I am doing it for 8 directions only (45 degree to each other). 2 sensors will decide zone horizontally and 3rd one will decide it is coming from front or back.

Is it completely silent and the sound a single loud clap ? Are the microphones 30 cm apart ? Then the delay is 900 µs. That might be possible, but not accurate. The interrupt software overhead is about 5 µs https://gammon.com.au/interrupts Can someone verify my calculations ? To detect someone speaking, you need a lot of processing power or perhaps a DSP and a Arduino can not do that.

I am using just a loud clap to make bot move, not voice of any person. Microphones are 15 cm apart. Yes your calculations are right, delay between sound arrival at different sensors won't be grater than 900 micro seconds if 30 cm apart.

I don't understand how you are measuring when the sound has reached three sensors with only one interrupt. Are you planning to use three interrupts?

I have arduino uno so I am using 2 interrupts and 1 sound sensor is waiting for sound in loop. Actually to simplify issue, I have asked question for just one interrupt. If you say I can share code for 3 sound sensors, however I am working on it, it's not complete yet.

noInterrupts();

Serial.println("Detected");
delay(5000);

delay() won't work with interrupts turned off.

Ok. Is there need to off interrupt ? or detaching it?

If you don't want that interrupt while you are delaying and printing, detach the interrupt.

Delay() function works by using timer interrupts internally. If you disable all interrupts using NoInterrupt function , then how will it work. Using that function is not recommended in code, as it causes unexpected misbehaviors.

Yes got it. I am facing one more issue here, delay is not working when 2 ISR gets executed at same time (delay is in loop section), is that because there are only 2 interrupts in arduino and delay can't find free interrupt and so can't work?

Delay () in loop () doesn't work cz it comes after      nointerrupt() function

This is happening also after removing nointerrupt() (means after keeping interrupt always on).

Only attach interrupt is needed here....not needed in loop() ..only in setup()


text:
Pro Mini Fuse Repair
It looks like I broke my Arduino (Compatible) Pro Mini board using AtmelStudio to change the fuses. I was having trouble with speed and using some basic sketches. For example, the LED blink was on for 2 seconds and off for 2 seconds instead of 1 second. I tried to change the fuses to Ext Clock + 65 ms, and now I can't use the thing at all. Cannot enter programming mode. Any ideas?

Sound like you selected a Pro Mini 16MHz in the IDE, but are actually using a Pro Mini that is running at 8MHz.

Sounds like you broke your fuses.
You may be able to enter programming mode by applying an external clock signal to the clock in pin (use another Arduino to generate it).  If that doesn't work then the only way to fix it is with a "High Voltage Programmer".
Nick Gammon has a very good tutorial here: http://www.gammon.com.au/forum/?id=12898

Also if you managed to get a clock divider activated, you may need to slow down the clock rate of the programmer to something sufficiently slower than the effective internal clock rate.


text:
How much code can an Arduino board run?
I'm getting back up and running with microcontrollers after about 5 years of hibernation time, and I am trying to understand a lot of different things. I have been experimenting with Arduinos for the past few weeks and am having a ton of fun. I'm a software engineer by day and a hardware hacker / manufacturer by night. At my day job, I write scripts and applications that are thousands of lines long and highly complex, using external libraries of thousands more lines of code, etc. These are full-fledge, professional software applications.
So, here is my question. Is the Arduino capable of running full-fledged robotics and other large, complex hardware applications, or is it more of a tinkering, hobbyist tool?
How big of a project can be built using Arduino? Are there memory concerns? Can an Arduino run thousands and thousands of lines of code out of the box, and if not, is there a way to add more memory for larger, more complex projects?

There are several "Arduinos" with memory capacities ranging from slightly less than 32k/2k/16MHz (Flash/RAM/CPUClock) ("Uno") to 512k/96k/84MHz ("Due".)  In addition, there are "mostly compatible" boards that expand that range down to less than 8k/512/8MHz ("Gemma", "Digistump") and up to about 1M/256k/120MHz (TI "EK-TM4C1294XL Launchpad"), and "somewhat compatible" boards with 4G/1G/400MHz (Intel "Edison")
Whether these are sufficient for "full fledged robotics" depends on what you consider that to mean.  Edison is probably the only contender if you wanted to include computer vision, for example, and it probably doesn't do that very well. ("What did you expect at ONLY 1 core at 400MHz?!")
The small Arduinos probably do not support your "very large libraries", either.  For example, while the "Arduino Language" is technically C++, support for the C++ STL is not included due to limitations of the small CPUs used and their run-time environment.
32k of program memory (on the popular Uno) is sufficient for "thousands of lines of code", but I'd think robotics would tend to run toward much more than that.  The small amount of RAM available on most of the flash-based microcontrollers also tends to be a serious limitation when you start looking at standard data-intensive algorithms.  32k/2k disappears quite quickly if you start implementing an extensive user interface, networking, or graphics.  I would say that an Uno-class Arduino is suitable for implementing COMPONENTS of robotics systems (motor drivers, sensor management, etc), but probably not a whole robot.
A good example of large robotics-like software that runs on Arduino-class hardware can probably be found in the 3D Printer space.  "Marlin" firmware runs on an Arduino Mega or equivalent (256k/8k/16MHz) (with RAMPS shield), and there are alternative driver packages that run on smaller and larger arduino-like hardware.  Marlin is about 280k lines of code, according to cloc.
Most Arduino hardware does NOT have expandable memory.  The AVR cpus cannot run code except from their internal Flash, and few of the other boards have any sort of memory bus that could be used for expansion.

(Ahem) The Intel Edison is dual-core @ 500MHz...

Ah; it's the Galileo that is 400MHz...

These days the ESP8266 and ESP32 are more or less arduino compatible and they have huge amounts of RAM and storage. Consider these as well.

No accepted or up-voted answers, eh? I'll try my hand. :)

How big of a project can be built using Arduino?

Depends on the model. You can go from around 4 KB of programmable memory to 256 KB, and then get into the larger models like the Due (512 KB).

Are there memory concerns?

There are always memory concerns, however when you have gigabytes of RAM (like on your PC) you tend to ignore them.
These are microcontrollers, designed for embedded applications. You will find yourself probably wishing you had more of everything (RAM, PROGMEM and EEPROM). However for many applications what they have is absolutely fine.

Can an Arduino run thousands and thousands of lines of code out of the box

Probably not. Consider the Uno with 32 KB of program memory. At from two to four bytes per machine instruction (most are two bytes), you are probably going to fit at most:
32768 / 2 = 16384

... machine instructions. So no, not hundreds of thousands. The larger models, maybe.

and if not, is there a way to add more memory for larger, more complex projects?

The Atmega2560 has expandable RAM, for example here which adds 512 KB of RAM.

How big of a project can be built using Arduino?

I have quite a few around the place here doing their own things. One lets me know if I left the garage door open accidentally. I look upon them as being useful for "helper" applications. I wouldn't try to put my SQL database on one.

The AVR machine instructions are all two-byte long, except for jmp,call, lds and sts, which are 4 bytes each.

Ach, I was thinking of clock cycles, which are what is documented in the main datasheet. Thanks for the correction, I amended my answer.

@NickGammon "There are always memory concerns, however when you have gigabytes of RAM (like on your PC) you tend to ignore them." And alas, today's programmers (whippersnappers the lot of 'em!) have lost that realisation... If they could put a bit more effort in optimisation, they'd halve the size of many programs - if not more!

Well, I wasn't counting myself in that group *grin* - my first computer had 512 bytes of RAM (which was also used for code) so I had to program conservatively. I agree though, that thinking you have unlimited memory, and unlimited speed to spare, can lead to careless programming.

Although Arduino is more of a hobbyist electronics board, it can handle complex projects depending on which board you use. The Mega has 54 input pins, so can handle loads of devices and has much more memory and storage. See the Uno - Mega specs below

The ATmega328 chip found on the Uno has the following amounts of memory:
  Flash  32k bytes (of which .5k is used for the bootloader)
  SRAM   2k bytes
  EEPROM 1k byte
The ATmega2560 in the Mega2560 has larger memory space :
  Flash  256k bytes (of which 8k is used for the bootloader)
  SRAM   8k bytes
  EEPROM 4k byte


text:
Need to set a FAILSAFE in an if else loop
This works but I would like to have a timed failsafe...
If the FLOAT_PIN goes LOW for more than 3 seconds, it will turn SOLENOID_PIN to LOW.
I can't figure out how to incorporate it into my loop. I tried delay() and started playing with millis() but all I keep finding is LED blinking samples...
I'm not very good with C++ - still learning.
const int FLOAT_PIN = 8; // Pin connected to FLOAT switch
const int SOLENOID_PIN = A0; // SOLENOID pin - active-high

void setup() {
  Serial.begin(9600);
  // Since the other end of the FLOAT switch is connected to ground, we need
  // to pull-up the FLOAT switch pin internally.
  pinMode(FLOAT_PIN, INPUT_PULLUP);
  pinMode(SOLENOID_PIN, OUTPUT);
}

void loop() {
  int floatswitch = digitalRead(FLOAT_PIN); // Read the state of the float switch

  if (floatswitch == HIGH) {
    // If the pin reads high, water is OFF.
    Serial.println("Switch closed");
    digitalWrite(SOLENOID_PIN, HIGH); // Turn the SOLENOID on
  } else {
    digitalWrite(SOLENOID_PIN, LOW); // Turn the SOLENOID off
  }
}

use a flag floatFlag.... if floatSwitch == high and floatFlag == false (floatFlag = true; tim = currentTime;) ...... if floatSwitch == low (floatFlag == false) ....... if floatFlag == true and currentTime == tim +3 seconds (turn on valve)

Also asked at: http://forum.arduino.cc/index.php?topic=519688 If you're going to do that then please 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.

This is one of those cases when thinking in terms of a finite state
machine makes the programming quite straightforward. Here I would
use three states:

In the OFF state, the switch is LOW and the solenoid is off
in the ON state, the switch is HIGH and the solenoid is on
in the DELAYING state, the switch is LOW, but the program is
keeping the switch HIGH for three seconds.

The possible transitions are:

OFF → ON when the switch goes HIGH
ON → DELAYING when the switch goes LOW
DELAYING → OFF after three second in this state
DELAYING → ON when the switch goes HIGH.

The last transition is meant to ensure that LOW states of the switch
that last less than three seconds do not turn the solenoid off.
And here is a tentative implementation. Keep your constants and your
setup(), and replace your loop() with this:
const uint32_t DELAY_TIME = 3000;  // time to deay the -> off transition

void loop() {
    static enum {OFF, ON, DELAYING} state;
    static uint32_t start_delay;
    int floatswitch = digitalRead(FLOAT_PIN);

    switch (state) {
        case OFF:
            if (floatswitch == HIGH) {
                Serial.println("Switch closed");
                digitalWrite(SOLENOID_PIN, HIGH); // Turn the SOLENOID on
                state = ON;
            }
            break;
        case ON:
            if (floatswitch == LOW) {
                start_delay = millis();
                state = DELAYING;
            }
            break;
        case DELAYING:
            if (floatswitch == HIGH) {
                state = ON;
            }
            else if (millis() - start_delay >= DELAY_TIME) {
                digitalWrite(SOLENOID_PIN, LOW); // Turn the SOLENOID off
                state = OFF;
            }
            break;
    }
}

think its backwards. Worked but backwards, it's preventing it from turning off for 3 seconds, rather then turning off if its on for more then 3 seconds.

no matter what I do it works one way but not the other... not sure what i did wrong.

@MikeS: I can't understand your comment “it's preventing it from turning off for 3 seconds, rather then turning off if its on for more then 3 seconds”. I wrote this answer to match your question as written. If this is not the behavior you expect, please, edit your question with a more explicit description of your expectations.

your example works, but not as intended. Float goes low, turn on solenoid, Float goes high, turns off solenoid but delays 3 seconds once Float is high. The logic about is right, not sure if your states are written correctly. Can it be written outside the loop that Solenoid can only be high for X seconds (no matter the output of the FLOAT?)

@MikeS: This works exactly as intended – as I intended it to work based on my understanding of your question. I assume you didn't read my last comment, so let me repeat: please, update your question and add an explicit and clear description of the behaviour you expect.


text:
The code is showing a error that "ledpin2 is not declared in the scope"
int ledPin1 = 1;
int ledpin2 = 2;
int ledpin3 = 3;
int ledpin4 = 4;
int ledpin5 = 5;
int ledpin6 = 6;

void setup()
{
  //initialize pins as outputs
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  pinMode(ledPin5, OUTPUT);
  pinMode(ledpin6, OUTPUT);
}

void loop()
{
  digitalWrite(ledPin1, HIGH);
  delay(200);
  digitalWrite(ledPin2, HIGH);
  delay(200);
  digitalWrite(ledPin3, HIGH);
  delay(200);
  digitalWrite(ledPin4, HIGH);
  delay(200);
  digitalWrite(ledPin5, HIGH);
  delay(200);
  digitalWrite(ledpin5, LOW);
  digitalWrite(ledpin4, LOW);
  digitalWrite(ledpin3, LOW);
  digitalWrite(ledpin2, LOW);
  digitalWrite(ledpin1, LOW);
  digitalWrite(ledPin5, HIGH);
  delay(200);
  digitalWrite(ledPin4, HIGH);
  delay(200);
  digitalWrite(ledPin3, HIGH);
  delay(200);
  digitalWrite(ledPin2, HIGH);
  delay(200);
  digitalWrite(ledPin1, HIGH);
  delay(200);
}

I'm voting to close this question as off-topic because it's just a typo.

You mix capitals with non capital characters.
The case of characters in variable names are important, so ledPin2 is a different variable than ledpin2.
Also, never mix similar names (unless it is trivial). Either always use ledpinx or ledPinx, not sometimes the first and sometimes the second version.
camelCasing is normally used for local variables, means the first sub-word starts with a lower case, rest with upper case, thus led-pin will become ledPin.
Pascal case is the other way: that would become LedPin in your case.
For global variables I tend to use PascalCasing, or if it is within one file, prefixed camelCasing with an underscore.

I have corrected your code it was just because you mixed capital and lowercase letters while declaring ledPin. Keep it same everywhere in setup() and loop().
int ledPin1 = 1;
int ledPin2 = 2;
int ledPin3 = 3;
int ledPin4 = 4;
int ledPin5 = 5;
int ledPin6 = 6;

void setup()
{
    //initialize pins as outputs
    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
    pinMode(ledPin4, OUTPUT);
    pinMode(ledPin5, OUTPUT);
    pinMode(ledPin6, OUTPUT);
}

void loop()
{
    digitalWrite(ledPin1, HIGH);
    delay(200);
    digitalWrite(ledPin2, HIGH);
    delay(200);
    digitalWrite(ledPin3, HIGH);
    delay(200);
    digitalWrite(ledPin4, HIGH);
    delay(200);
    digitalWrite(ledPin5, HIGH);
    delay(200);
    digitalWrite(ledPin5, LOW);
    digitalWrite(ledPin4, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin5, HIGH);
    delay(200);
    digitalWrite(ledPin4, HIGH);
    delay(200);
    digitalWrite(ledPin3, HIGH);
    delay(200);
    digitalWrite(ledPin2, HIGH);
    delay(200);
    digitalWrite(ledPin1, HIGH);
    delay(200);
}


text:
Flashing NodeMCU with .ino file?
I'm brand new to the Arduino world. I recently purchased a NodeMCU in order to have it act as a sort of foothold to get into Arduinos as it's something I've always wanted to do. However, it was only after I had received the NodeMCU that I realised that there was no default option in the Arduino IDE to flash to a NodeMCU and soon found out that this is because the NodeMCU is in fact not an Arduino and therefore has its own proprietary flashing software for .bin files. This initially confused me as an outsider as I assumed all devices of that nature must be Arduinos.
I recently came across a Homebridge plugin by affix called homebridge-mcu-lamp which uses a NodeMCU running an HTTP server to control a relay. Interestingly, the script he has included in the repository which he claims to have running on his NodeMCU is a .ino file which really confused me.
My question is: how would I flash a .ino file to a NodeMCU like the one mentioned above as I have no experience with .bin files and would much more value to treat the NodeMCU as an Arduino instead (i.e. programming in C++)?
I understand this may sound like a very simple/dumb question for most of you on this forum but it is something that has had me stumped for days and would really appreciate some guidance on.
I would also find it useful if someone could explain to me the difference between a NodeMCU and an ESP8266 as I see the two words being used interchangeably when referring to the same looking board.
This is what my NodeMCU looks like:

esp8266 is a chip under the metal shield of the esp-12 module. esp-12 module is the board glued to the NodeMcu board

Last question first: The ESP8266 is the main IC on the NodeMCU board.
This is similar to the idea that an ATMega328 is the IC on Arduino Uno.
A normal 'clean' Arduino IDE install can work with an Uno ('flash with an INO'), but not with an ESP8266 based board. For this, you will need the ESP8266 addon for the Arduino IDE, after which, the NodeMCU board is available as an option.
This page documents the ESP8266 addon:
https://github.com/esp8266/Arduino
Long story short, open preferences (File -> Preferences) , under Additional Board Manager URLs, add http://arduino.esp8266.com/stable/package_esp8266com_index.json
Click on Tools>Board>Board Manager (assuming you have Arduino IDE 1.6.4 or later) and search for ESP8266 and install the option that includes NodeMCU.

Thank you so much for your reply, that was exactly what I was looking for! Last question; apart from having to install the ESP8266 adding separately, will everything else work exactly the same as if it was an Arduino board (I.e. will the flashed software work exactly the same without any adjustments? Thank you once again!

Sorry, quick question, which buttons do I need to hold down when flashing from the Arduino IDE to the NodeMCU?

unless the nodeMCU is defective or a prototype, you should not need to hold down any buttons to flash from the arduino IDE

@dandavis Perfect, thank you so much for your help!

@Tom, there might be some subtle differences between how a 'proper' Arduino board like an Uno might behave compared to the NodeMCU, but this will depend on the function or library you are trying to use. Most 'core' Arduino functions should work very closely. The page I linked above is probably the best reference for this sort of thing.

@user85471 Thank you for the information, I've successfully been able to flash my NodeMCU with the method you referred to above so thank you very much! I haven't run into any sort of compatibility problems yet but I'll be sure to refer to the official documentation if I experience any sort of unexpected differences. Thanks! :)


text:
NodeMCU - use flash button as input in loop()
I couldn't find a proper answer on the net so I came here as a last resort.
So I want to use the FLASH button as an input in the loop() method.
Is there a way the check if it's pressed or not?

The Flash button on NodeMCU is connected between io 0 and ground.  You can use it as a button.  Set pinMode(0, INPUT_PULLUP) and you will read io 0 LOW if the button is pressed.
NodeMCU schema
To put the module in flashing mode, first the Flash button must be held and the Reset button pushed, only then should the Flash button be released. Normally, the reset to flashing mode is done automatically by esptool before uploading over USB. This uses the circuit connected to serial RST and DTS lines.

I recommend you EasyButton library, you can use pin 0 (D3) in NodeMCU, if you want use a external button module, you can wire your button between D3 pin and GND.
https://github.com/evert-arias/EasyButton
#include <EasyButton.h>

// Arduino pin where the button is connected to.
#define BUTTON_PIN 0

// Instance of the button.
EasyButton button(BUTTON_PIN);

// Callback function to be called when the button is pressed.
void onPressed() {
    Serial.println("Button has been pressed!");
}

void setup() {
    // Initialize Serial for debuging purposes.
    Serial.begin(115200);
    // Initialize the button.
    button.begin();
    // Add the callback function to be called when the button is pressed.
    button.onPressed(onPressed);
}

void loop() {
    // Continuously read the status of the button.
    button.read();
}

Just to complete the other answers, here is sample Lua code to help you get started
inpin=3 -- Select input pin - GPIO0

function pressed()
    print("PRG Pressed")
end

gpio.mode(inpin,gpio.INT,gpio.PULLUP)
gpio.trig(inpin,"down",pressed)

When you press the "Flash" or "PRG" button "PRG Pressed" is printed. You can perform additional magic in the function.
Above sample code adapted from this blog post
I am using this board from MakerFocus

The top answer only works for me when the Nodemcu is connected via a serial port and the "Serial Monitor" is turned on.  (It was frustrating because it would always work whenever I connect up the serial monitor for debugging and then stop working when I disconnect it to run standalone).   I think this is because the Nodemcu connects GPIO0 and GPIO16 to the UART's RTS and DTR signals.   The buttons only work when those control lines are in the right states and that might not always be the case.   See the third page in the schematic at https://github.com/nodemcu/nodemcu-devkit-v1.0/blob/master/NODEMCU_DEVKIT_V1.0.PDF

I often use it as an input if I need a button input on my boards. After the initial boot sequence it is just another I/O pin.


text:
ssPin, resetPin, updatePin, ps0, ps1, osk - was not declared in this scope
The code below produces the  error:

ssPin was not declared in this scope

This error is repeated for all elements of DDS, i.e. ssPin, resetPin, updatePin, ps0, ps1 and osk
Can anyone spot the problem?
#include <SPI.h>
#include <AD9954.h>
AD9954 DDS(ssPin, resetPin, updatePin, ps0, ps1, osk);

void setup() {
SPI.begin();
SPI.setClockDivider(4);
SPI.setDataMode(SPI_MODE0);
delay(500); // let things get set up...

DDS.initialize(400000000); // initialize DDS with 400 MHz clock

}

void loop() {

 DDS.setFreq(25000000); // set DDS to 25 MHz
  delay(2000);

}

The line:
AD9954 DDS(ssPin, resetPin, updatePin, ps0, ps1, osk);

does not have any content above it which declares that those variables exist. You can declare them like
const uint8_t ssPin, resetPin, updatePin, ps0, ps1, osk;

You'll likely also want to assign values to them, corresponding to the pins being used:
const uint8_t ssPin=4, resetPin=5, updatePin=6, ps0=7, ps1=8, osk=9;

(the actual values should be the pin numbers being used in your particular case.)
The file AD9954.h declares these variable names as private inside the class. They aren't available for use outside the class. The call to DDS(...) is the constructor, where you pass in pin definitions, and the values get assigned to those variables inside the class. But you can pass in literals or other variables in the constructor. You could even declare the same variable names in your main source file, but you can't ever directly access private variables from outside the class.

Thanks. However, when I look through AD9954.h I see that the variables have been declared as private within the AD9954 class but it doesn't seem to pick these up.

Right, they are private to the class. They aren't available for use outside the class. The call to DDS(...) is the constructor, where you pass in pin definitions, and the values get assigned to those variables inside the class. But you can pass in literals or other variables in the constructor. You could even declare the same variable names in your main source file, but you can't ever directly access private variables from outside the class.

Ok, thanks for the very clear explanation, I understand the problem now. I've not done any Arduino work for a while so need to get my brain back in gear. Thanks.

As a final comment on this, the line in question (AD9954 DDS(ssPin, resetPin, updatePin, ps0, ps1, osk);) is used to pass the actual Arduino pin numbers for those pin assignments to the object. In the working version I used the following line: AD9954 DDS(2, 3, 4, 5, 6, 7);


text:
Light Powered Motor Troubles
I'm working on a small car (<1 kg) which will drive when there is light and stop when there isn't. Below is a plan with code drawn up (the only numbers I know for sure are the current gains for the TIP31C transistor and the rated load current of the 6 V motor I'm using). I'm going to map the analog voltages to a digital signal output.
I read that the maximum digital output was 40 mA and also that analogWrite gives a pulse width modulation (PWM) which can be set to 100% (255) [the code: outputval/1], 50% (127) [the code: outputval/2]. I'm concerned with the lack of control I have here over the current. Will Arduino by default draw 7.75 mA maximum if the input signal is high [giving the output signal also as high]? If not, can I control the current in this manner reliably? Also are there anything I should worry about if I added another 6 V motor in parallel? Coding and electrical suggestions greatly welcomed.
TIP31 transistor: http://www.hobbytronics.co.uk/datasheets/TIP31.pdf
6 V dc motor: http://www.kysanelectronics.com/graphics/RF-370CA-22170.pdf
maximum digital output: https://www.arduino.cc/en/Tutorial/DigitalPins
PWM: https://www.arduino.cc/en/Tutorial/PWM

The code:
const int transistorbase = 9;
void setup() {
  //set the base as digital output:
  pinMode(transistorbase, OUTPUT);
}
void loop() {
  //read voltage at divider:
  int inputval=analogRead(A0);
  //map voltage to digital
  int outputval=map(inputval,0,1023,0,255);
  //control transistor:
  analogWrite(transistorbase,outputval);
}

tl;dr
Codewise, how do I control the digital output current to my needs? Am I seeing ghosts?

You should seriously consider using an FET for motor control rather than a bipolar or darlington transistor.  Most Arduion hobbyists use IC-based drivers, but the same concern applies there as it does to discretes - seek FET, avoid bipolar.

I just read up on them. Will that fix my worries about current because it has a stronger response to voltage (seeing as a strong output signal will nearly be 5V for a fast PWM frequency) i.e. it is a device controlled by electric field and not a current requirement? Would this be a suitable FET, I don't think I'll fry it at VGS of 20 V, and assuming the PWM wave gives an average above 2 V above the VGS(th), it'll close when the input signal is weak, right?

https://www.infineon.com/dgdl/irfz44npbf.pdf?fileId=5546d462533600a40153563b3a9f220d

No, the threshold voltage is too high, it will be only barely on when driven by an Arduino.  Most suitable parts are surface mount only but https://cdn-shop.adafruit.com/datasheets/irlb8721pbf.pdf might work to a degree

So the digital output is not nearly 5V? That's what I got from the PWM reading.

An FET's threshold voltage is where it just begins to turn on.  You want something much higher for good performance.  Try to find one with a threshold below 2v.

I would take a simple n-channel MOSFET like this one. At 5V on the gate it can drive up to 8A (so you have plenty of space to connect other motors as long as your power source can handle this) and because it is a MOSFET you don't have to draw much current from the Arduino (only enough to load the gate of the MOSFET). You can also hold the current under the critical value for your motor with a simple resistor (fit for the resulting power dissipation) in series.
Yes, the output of the PWM is 5V - the operation voltage of the Arduino. The whole point in PWM is to use only the digital values (here 0V and 5V) and varying so fast, that slow systems as the motor cannot follow this motion, but summing over the impulses. So the motor gets only very fast kicks. And for a normal motor you don't need fast PWM. This only increases the frequency response from the MOSFET.
The code seems for to me.

That is not a very good MOSFET to use with this, as its threshold voltage is high enough that an Arduino will only barely turn it on.  You want one with a lower threshold voltage so that a ~5v output can turn it more completely on.


text:
Compilation Error in nodeMCU along with oneWire temperature sensor ds18b20, and 2x16 LCD display (not I2C)
I am using nodeMCU along with oneWire temperature sensor ds18b20, and 2x16 LCD display (not I2C). I am using Arduino IDE to program nodeMCU. I am getting a compilation error:
C:\Program Files (x86)\Arduino\libraries\OneWire/OneWire.h:108:2: error: #error "Please define I/O register types here"
#error "Please define I/O register types here"
^
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

What is meant by: "Please define I/O register types here"? Thank you for the help.

Also asked at https://stackoverflow.com/q/46498587

I replaced my old OneWire.h code with this(Click here) code, and it worked amazingly.

It appears you're using an outdated version of the OneWire library that does not support ESP8266. Please follow these instructions to upgrade to the latest release of the library:

Sketch > Include library > Manage libraries...
Wait for the download to finish.
In the "Filter your search..." box, type "onewire".
Click on the "OneWire" entry.
Click the "Update" button.
Wait for the installation to finish.
Click the "Close button.

The recent releases of the OneWire library have support for ESP8266 so this should solve your compilation issue.


text:
Arduino Sketch: NodeMCU compilation error
Every time I try to compile a program written in Arduino IDE 1.8.5 for NodeMCU (LoLIN version v3), I get the following error:
Arduino: 1.8.5 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

C:\Users\sumeetpatil\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-ar: unable to rename 'C:\Users\SUMEET~1\AppData\Local\Temp\arduino_build_831529/arduino.ar'; reason: File exists

exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

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

I have tried reinstalling several times, but I just can't get ahead of this step.

what else does turning on the verbose output say? it might be a lib that's not compat.

Do a full uninstall of Arduino, then delete the Arduino folder and
  Arduino15 (back them up first if you have any sketches in there!!!!),
  as well as any Arduino folders under Temp. Make sure the folders and
  all contents are really gone, reboot and try again if not. Then, do a
  clean install of the IDE.

Cited from here.


text:
Arduino Uno won't upload code and overheats
We are using an Arduino Uno R3 connected via USB to a computer. The main problem is that we can't upload any code to the board. We get this error in the Arduino IDE console:

avrdude: ser_open(): can't open device ".\COM1": The system cannot find the file specified
  Problem uploading to board. Visit http://www.arduino.cc/en/Guide/Troubleshooting#upload

My computer may not recognize the board, the IDE won't find any port (COM) and on the board I got the three LEDs turned on, they don't even blink, they stay turned on as long as I have connected the Arduino to the computer. Apart from that, the Arduino heats too much and too fast. I don't have anything connected to it yet. I've tried resetting the board with its built-in button, I've also tried changing the USB cable, even the computer, different system architecture and OS. I don't to want to mess up the board even more, so I don't know what to do. Could you point out what's the problem with my board?
If you need more information, I will try to post as much as you need to help me out.

The fact that it doesn't blink the LED when plugged in or reset indicates that the bootloader of the main microcontroller no longer works.
The fact that the computer no longer recognizes the board as a serial port means that the USB-to-Serial interface doesn't work.
The fact that it heats up tells you that at least one of the chips on the board is dead.
I'm afraid that you'll have to get yourself a new Arduino.

Yeah, I'm afraid of that too. Anyway I got an Arduino Mega2560 to work with, but I wanted to know if I could do something to save the UNO.

Probably not in a cost-effective way.

See Have I bricked my Arduino Uno? Problems with uploading to board

First of all (with unplugged Uno) visually (and maybe with help of some magnifying glass) check, that really there is nothing stuck there, what should not be (tin ball, pice or wire or such) and that all copper lines on PCB are OK (and not shorted or broken). Also check all chips, resistors etc. are visually clean, good soldered and undamaged. If something looks damaged or burned, the it is probably damaged and should be replaced anyway.
If you connect it (I suggest USB charger, to be sure to not damage computer) and the main chip (MCU) is hot, I think, that it is dead.
If some other chip is hot and MCU not so much, then maybe the MCU is not dead, but something else is broken. (probably the hot part, but maybe also some resistor/capacitor shortcuted)
The way it is now makes it is dead for you anyway, so there is not much to came worse.
I would try to connect it only to USB charger (to not damage expensive computer by bad luck) and measure voltage on various points of the board (from ground). There should be 5V straight at 5V pin, also on the same 5V on ISP head, one pin of USB connector and on all power pins on MCU and the other chip between it and USB (new R3 have some atmega there too).
Take schema for that and try to measure on the right places. Be carefull to not shortcut anything with your voltmeter rod (it is easy to connect two legs with it and it may damage something not damaged yet). You can try to check voltage anywhere safely, on some places there should be 0V, on some 5V, but in default setup (no program working yet) the i/o pins are INPUT on boot, so just High resisteance and no strong voltage on them (you should get probably weak 0V until there is some interference).
If you identify (or thing so) wrong part, you can try to replace it with new one - good training even if you botch it and you risc youst price of the new part. Even the MCU can be changed with good soldering pen and some effort. The schema is simple, but the legs are tiny and many of them.
As it is effectively dead for you now, the worse what can happen is, that you burn the new part too and throw it all away (as you would anyway). The best what can happen is that you repair it and it will work flawlessly.
I build some "arduinos" from the SMD chip and other parts on home made PCBs - all worked well. So If you want some entertainment and practise, it is not bad think to try.
If you do not want risc the price of new MCU, but want the practise, yout take away and thyen resolder the (already broken) MCU - it would not repair it, but you can see for yourself, if you think you are able do similar experiments and if you enjoy it.

I found, that some chineese cheap clones have voltage stabilisers, that can break on shortcut and then do anything (usually the output is then shortcuted to input, so the power goes full where only stabilised 5V should be, but also can shortcut to ground, burn to total resistance, or something random between)
It is usually not good idea have arduino connected to two powersources (like external power source for servos AND USB for programming it) at the same time, as there may be different voltage on both and big currents between in some cases. If you need more power for servos (or something) and USB for serial/programming, then better there should be no direct connection between the external source power and Arduino +5V/+3.3V or any pin - just common ground, everything other separated by at least transistor (base on pin, collector on external source) or so.


text:
My Arduino IDE stuck on uploading
So for a while I get some Arduino IDE problem which I can't solve. When I try to upload any kind of code to my Arduino, Arduino IDE just stay at "Uploading". I tried to use another Arduino but I get the same problem. I used Pro Mini, Nano and Uno but it's the same. Then I decided to upload my code from another PC but I get the same problem and so I can't find where the problem is.
Is the problem in all my Arduinos or in my computers?
Note:
The code which I was uploading, was from Arduino examples.
I am using Windows 10 Pro x64 and in my console I get this error:
 avrdude: stk500_recv(): programmer is not responding
 avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x57

i used all kind of arduinos for example nano mini and uno. Of corse they are chines models but i installed CH340 driver. Аs far as it is concerned to ports i am sure that i use the right ports @abu-ahmed al-khatiri

If you are using a PC then the drivers should work, if it is a Mac then the drivers are notorious for not working correctly. Also, make sure that you are using a data USB cable and not a charging cable.

You tried different PCs and different Arduinos, so the only constant is the Code and the USB cable I guess:

Try another USB cable
Try to upload another code

Do you have the same problem with any code you try to upload?

Such reply (and question) is more suitable as a comment.  It is not an answer.

Why? If he changes the cable and it works, then it is the solution. I once had an connection issue and changing the cable solved it. I'm pretty sure it will fix it :)

Yes, until then, it's not a solution (i.e. answer).  You can reword to make it more of an answer than a comment.

To solve this problem, you should google the error message "avrdude: stk500_recv()".  The web shows countless records where this error comes up.  The message indicates that the serial communication has malfunctioned, but incorrect driver or serial port is not the only way this can happen.
During upload, (1) Have you tried to reset the arduino, (2) ensure that the RX/TX pins are not in use?


text:
Can you help me combining these sensor sketches as one in Arduino
I want to combine these three sketches into one.
RAIN SENSOR:
int rainPin = A0;
int greenLED = 6;
int redLED = 7;
// you can adjust the threshold value
int thresholdValue = 500;

void setup(){
  pinMode(rainPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);
}

void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(rainPin);
  Serial.print(sensorValue);

  if(sensorValue < thresholdValue){
    Serial.println(" - It's wet");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - It's dry");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);
}

LIGHT SENSOR:
int ldrPin = A0;
int greenLED = 6;
int redLED = 7;
// you can adjust the threshold value
int thresholdValue = 500;

void setup(){
  pinMode(ldrPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);
}

void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(ldrPin);
  Serial.print(sensorValue);

  if(sensorValue < thresholdValue){
    Serial.println(" - light");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - dark");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);
}

SMOKE SENSOR:
int smokeD0 = A5;
int greenLed = 11;
int redLed = 12;
// Your threshold value
int sensorThres = 300;

void setup() {
  pinMode(smokeD0, INPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(redLed, OUTPUT);
  digitalWrite(greenLed, LOW);
  digitalWrite(redLed, LOW);
  Serial.begin(9600);
}

void loop() {
  int analogSensor = analogRead(smokeD0);
  Serial.println(analogSensor);

  // Checks if it has reached the threshold value
  if (analogSensor < sensorThres)
  {
    Serial.println(" - Smoke");
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
  }
  else
  {
    Serial.println(" - No Smoke");
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
  }
  delay(100);
}

I want to combine those codes as one with only two outputs:

the greenLED and;
the redLED.

What is your problem with combining them? You haven't asked an actual question

The only issue are the same names for sensorValue, thresholdValue and same pins for red and green led and analog pin A0. All in the first two snippets.

Variable renaming

Rename thresholdValue in the first two sketches to rainSensorThreshold, and lightSensorThreshold respectively, and sensorThres to smokeSensorThreshold in the third sketch.

Rename sensorValue in the first two sketches to rainSensorValue, and lightSensorValue respectively, and analogSensor to smokeSensorValue in the third sketch.

Change the Analog pin
Use A1 (or some other analog input other than A0 or A5) for ldrPin in the second sketch, for example:
int ldrPin = A0;

Consistant LED pins
Use the same pins in the third sketch, as are used in the first two sketches, for the two LEDs and note the change in case:
int greenLed = 11;
int redLed = 12;

to
int greenLED = 6;
int redLED = 7;

Recompile each sketch
To check that the each sketch still works, recompile each one separately.
Combine the code
Finally... Splice the code together appropriately, keeping the three parts separate:

Global variables
setup()
loop()

I've got a problem with this --- int sensorValue = analogRead(rainPin);

Ah, I missed that. I have updated my answer.

Don't forget to upvote :-)


text:
How to use Arduino Pro Mini without Programmer
I'm a software engineer, but I'm not too skilled at understanding hardware design yet. I'm trying to learn how to use an Arduino Pro Mini board without the programmer connected, so I can actually make fun toys, etc. Currently, the software will only run when connected to the programmer (or at a minimum with the SCK pins connected to each other). I have been searching online for days, and I think I need a crystal or resonator hooked up somehow, but I can't figure out how to hook them up (which pins). I bought 5 16 MHz ceramic resonators, and I have them right here with me, but I can't find the answers online how to hook it up and have the board run stand alone. Any ideas? Thank you in advance.

You'll have to program it once, and then it should run whenever it's powered up. They should be able to run on internal 8Mhz clock.

You might be on the wrong track.
You do need a crystal (or not, it depends on), and an Atmel programmer if you want to program an empty chip.
However, all Arduino boards come with a chip pre-programmed with a bootloader.
Then it is rather easy: you need an FTDI cable to connect the board to a PC. Then run Arduino IDE on the PC. (The FTDI cable is actually an USB-to-serial converter.)
The Arduino IDE lets you edit a C like code, complile it to binary, and send it out via the FTDI cable to the serial port (Rx, Tx) of the board. The microcontroller on the board comes with a bootloader. Bootloader is a small program which runs at power up, and will receive the data from the computer and put your program to the microcontroller. Then your program will run on the microcontroller.
So, you don't need an external programmer.

On the other hand, you may consider picking a different Arduino board. Arduino Micro, or Pololu A-star Micro (for half of the price of the Arduino Micro) offers a board with a direct USB connection. All you need is one USB cable.
These boards come with a much better microcontroller (32u4) which has a hardware USB connection (allowing you to make a mouse or a keyboard, and control PC (such as buttonbass.com) from your gadget).

You were right. I was completely on the wrong track. My problem was that the target board wasn't being programmed at all. I started over from the beginning, loaded up Atmel Studio and burned a new bootloader. Eventually I was able to go back to Arduino IDE and program the board. I have now moved beyond this roadblock and on to bigger pastures. Thank you very much. Peace.


text:
Light multiple RGB Led Strips from same 3 RGB PWM outputs
I need to control about 6 RGB Led Strips from an Arduino Board. The problem is that i need 3 PWM outputs for each led strip, but each will have probably the same colors. I was wondering if i could put two strips receiving a signal from the same PWM output, then i would have to use half the PWM outputs but send the same signal for each pair of strips.
The scheme i found is this one:

And what i want is something like this:

Is this possible? What should i modify to make it work?
Thanks in advance.

You have few options:

do as you represented in the drawing: it should work, as I expect the transistors to not load too much the input.
add a logic buffer inbetween the arduino and the driver stage
use other pins from the arduino for driving the additional strips and bitbang the PWM, instead of using the HW blocks

Whether the solution you propose (1) will work or not depends entirely on the max current that each PWM pin can output vs the total load from the 3 transistors it will have to drive.

That was very helpful, i was afraid about this current thing, but apparently each 1 meter uses 20mA, and a pin can output 40mA, so 2 strips would be the perfect amount.

Did you check that 20mA is the Max Value, rather than Typical?
You might have some unpleasant surprise, if you take chances and do not plan for the worst case. Same goes  for the Arduino/Atmega: is 40mA the Min Value or the Typical? You should match Min from the source vs Max from the drain and confirm that they are compatible.

That's true. But the max that the strip uses is 20mA at full bright, and the typical that arduino provides is 40mA. Since i'm never gonna use it at full bright i think it should work.

5v with a 220ohm resistor will result in about 20mA of current. Depending on the gain of the transistors and the amount of current the strips use (i.e. depending on their length) 20mA might not be enough to fully saturate the transistor. In that case the leds won't be as bright, and the transistor will get pretty hot. Using MOSFETs will prevent this problem.


text:
bitRead() gives wrong answer Arduino UNO R3
I am trying to read from a quadrature rotary encoder using an Arduino UNO R3. This is done by connecting the encoder's channel A pin to the Arduino interrupt 0 pin (digital IO pin 2). Inside the interrupt routine I then read the value of channel B (connected to digital IO pin 8) to determine the direction of rotation.
I am able to read the correct value of channel B using the digitalRead() function, but when I use bitRead() it always gives me a 0. As far as I know digital IO pin 8 is mapped to PORTB bit 0, so I am using bitRead(PORTB, 0) to read the bit. I also tried to read all of the other pins, but all of them show 0, except the LED at pin 13, which shows 0s and 1s when it gets toggled (It is also the only pin defined to be an OUTPUT pin, whereas the encoder uses INPUT pins).
Below is my code:
int channelA = 0;
int channelB = 8;
volatile int rotateNumber = 0;
volatile boolean interrupted = false;

void setup() {

    Serial.begin(115200);

    attachInterrupt(channelA, rotate, RISING);
    pinMode(channelB, INPUT);
}

void loop() {
   if(interrupted){
       Serial.println(rotateNumber)
       interrupted = false;
   }
}

void rotate(){
  if(bitRead(PORTB, 0) == 1)
     rotateNumber++;
  else
     rotateNumber--;

  interrupted = true;
}

PORTx is the latched value last written there. The external value is found in PINx.

So I won't be able to use bitRead if my pins are inputs?

You're using bitRead() on the wrong variable.

Oh now I understand, I should just use PINB instead of PORTB. Thanks for the help :)


text:
Stepper motor clock
I am currently using an Adafruit motor shield on my arduino uno for the first time.
The idea is turning the stepper motor with basicly 1RPM. But i just cant do it.
This is the first time working with this setup, and i dont know what to do.
Can you people help me?
i'm using the Arduino Uno with ADAFRUIT motorshield. The steppermotor is 48steps / rev
DATASHEET
The code i have at the moment:
#include <AFMotor.h>

AF_Stepper motor(48, 1);

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

  motor.setSpeed(1);

  motor.step(48, FORWARD, DOUBLE);
  motor.release();
  delay(10);
}

void loop () {
  motor.step(48, FORWARD, DOUBLE);
}

Greetings from Holland.

You'll need to provide more inout if you want to get some useful answers: source code uploaded to your board? Board type? Stepper references with link to datasheet? Power supply? What have you done so far?

When you execute this program, what happens? Nothing at all? Most of the time, when encountering problems with stepper motors, the root cause is the wiring: did you check it twice?

That's not a 48-step stepper. That's one with 64 steps per revolution and with 64 reduction gearing inside. So you end up with 64*64=4096 steps per revolution of the outer shaft. So it's moving 85 times too slow. Hope that helps. Greetings back from the Netherlands.

I wonder if employing a motor with 180 steps which is divisible by 60 would be of any advantage? Here is a reference page which may assist you in evaluating the best component for your design: Introduction to Stepper Motors

But i just cant do it. - can't do what? I don't understand what you are asking. What is your question? How is it wired? What happens when you run the code? I'm going to close this question. Feel free to edit it with new information. Thanks for your understanding and cooperation!

Unsure what you need help with, but this might help:
I believe that the 28BYJ-48 has a lot more steps per rotation, around 4000 I think. I had a few problems myself getting this to work. It also has four steps to cycle through, not 2.
Take a look at this library which has the 28BYJ-48 set to default. CustomStepper

If the stepper gives you 48 steps and an hour has 60, you need to provide 1,25 rounds in one hour given you only move the minute hand. Then with some gearing you should be able to move the hour hand every round there.
So the best way to do this is to is either to move the hand once and then delay 1 minute, 1 minute = 60 seconds x 1000 milliseconds.
You then need to figure out what it requires of the stepper motor to make 1 step, with some stepper motors you need to move forward 1 cycle and then back a half. to make a step. You should find all this in the documentation.
Please provide feedback in the comments below so we can improve the answer.

Most stepper drivers can do microstepping.


text:
tone() and PWM limits
I'm developing an active sonar using Costas arrays and Golomb rulers. I need the Arduino to switch between frequencies very quickly to shorten the length of the ping, both to improve processing and to lessen speed of sound limitations. I also need to know the exact times each frequency will be released from the Arduino so the real time computer can ignore those frequencies.
I'm able to generate the melodies I want using the tone() command, but I couldn't find the time required to change frequencies or the standard deviation of that time. I'm also not sure what the minimum length of PWM is.
So I want to know, what is:

The switching time for changing PWM frequencies
The standard deviation of that switching time
The minimum length PWM pulse that can be generated
The standard deviation of the length of that minimum PWM pulse.

And how might I achieve those minimums?

1,2; You could be able to change the frequency in something like 4 instructions, but tone has quite a bit of overhead. But it should still be pretty fast. Though you could write your own optimize code, setting the prescaler and OCRx registers. 3; Highest frequency is something like half of 16Mhz, so 8Mhz. Maybe even higher using PLL.

The number of instructions does not equal the switcing time... well, maybe if they're assembly instructions, but even then, the hardware has to react to the cpu. And highest frequency doesn't necessarily equal the minimum length PWM, that would be the period; if I can stop generating PWM after less than one wavelength, then the PWM's length is smaller than the wavelength, and same if I have to wait more than one wavelength to stop it.

In PWM, Phase Correct mode you can update the OCRA and OCRB values while it is running. It will buffer those values and only update them and the end on the "cycle". That way no "half-tone" is ever generated. Since you are talking about tone generation I was assuming 50% duty cycle. Or did you mean duty cycle when you said minimum length PWM?

Yeah, 50% duty cycle is correct. So the minimum length of PWM is almost exactly its period?

If you pre-calculate the values you need, and arm an interrupt to change on the next edge, then for anything up to a few hundred KHz you should be able to load the new values into the registers before that count is reached, yielding the fastest frequency change theoretically possible with a rectangular waveform.  It's been a while since I looked at the details, but you may need to pre-load the total count register during the the cycle preceding the one in which you want to change it.  For better results, one would think you would want a sinusoidal synthesizer.


text:
Arduino Uno Wire Transmission Issues
I am developing code to run a word clock and have noticed a slight problem. I am using a DS3231 to keep time, and using the Wire library to communicate with it. I ping the DS3231 every second to get the time and check a few other things. This is all working fine except when the clock loses power. It seems that occasionally upon loss of power to the Arduino, the time that that the DS3231 reports when it regains power, is incorrect.
My thought is that the power is getting cut in the middle of various Wire.read() commands and this is causing the chip to mess up and reset its own time, but I am not sure. The DS3231 has a battery backup attached to it, and that battery has only been plugged in for a month or two, so I don't imagine that is the problem.
I am wondering if anyone has an idea how I can deal with this potential problem, or if there is some way I can clear the Wire library before it starts up again.
I have put some sample code below to give an idea of what I am doing. There is of course much more code, but this is the only relevant part.
#include "Wire.h"
#define kClockAddress 0x68

void readDS3231time(byte * second, byte * minute, byte * hour, byte * dayOfWeek, byte * dayOfMonth, byte * month, byte * year) {
  Wire.beginTransmission(kClockAddress);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(kClockAddress, 7); // request seven bytes of data from DS3231 starting from register 00h
  *second = bcdToDec(Wire.read() & 0x7f);
  *minute = bcdToDec(Wire.read());
  *hour = bcdToDec(Wire.read() & 0x3f);
  *dayOfWeek = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month = bcdToDec(Wire.read());
  *year = bcdToDec(Wire.read());
}

void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte dayOfMonth, byte month, byte year) { // sets time and date data to DS3231
  Wire.beginTransmission(kClockAddress);
  Wire.write(0); // set next input to start at the seconds register
  Wire.write(decToBcd(second)); // set seconds
  Wire.write(decToBcd(minute)); // set minutes
  Wire.write(decToBcd(hour)); // set hours
  Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
  Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
  Wire.write(decToBcd(month)); // set month
  Wire.write(decToBcd(year)); // set year (0 to 99)
  Wire.endTransmission();
}

void setup() {
  // put your setup code here, to run once:
  Wire.begin()
   // DS3231 seconds, minutes, hours, day, date, month, year
   //setDS3231time(0, 36, 10, 2, 21, 12, 15);
}

void loop() {
  // put your main code here, to run repeatedly:
  byte second, minute, hour, dayOfWeek, dayOfMonth, month, year; // retrieve data from DS3231
  readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
  delay(1000);
}

By incorrect, do you mean 01/01/00 01 00:00:00?

@Gerben no, I mean off as in like a few hours or a few days.

That's weird. I'd check the battery voltage. The DS3231 should transition to battery power just fine.

  Wire.requestFrom(kClockAddress, 7); // request seven bytes of data

Just because you request 7 bytes doesn't necessarily mean you get them. I suggest before reading the date and time you set all those variables to something invalid (like 0xFF). Then after reading, if you get 0xFF in any of them, ignore the entire lot.

we are sending a start bit again, when we never sent a stop bit previosuly. ... Does this sound reasonable

Not really, because I2C doesn't have start and stop bits, it has start condition and stop condition which are specific changes to SDA and SCL which don't happen at any other times. See I2C for a description. I would be checking the data for validity, as I said. There is no other way of knowing for sure that a transmission wasn't interrupted. If you request 7 bytes of data, the library tells you that you got 7, even if you did not. However if it cannot even find the target device, it returns 0 as the number of bytes (you aren't testing for that anyway).
The very least you should do is test for a valid connection, eg.
if (Wire.requestFrom(kClockAddress, 7) == 7)
  {
  // read the data
  }

That at least confirms that the clock chip responded in some way. Not checking error returns from function calls, where documented, is not wise.
Similarly when you send your command.
  Wire.endTransmission();

That should be:
if (Wire.endTransmission() != 0)
  {
  // handle error here
  return;
  }

You have no tests in your code for either the sending or receiving to be working. And then you are unconditionally using the resulting time values. That's like opening a file, and reading it, without checking if the file exists.

I think the actual problem came about with the I2C interface with the DS3231. If the power is lost to the device in the middle of an I2C read, it never gets the stop signal or some other signal. Because of this, some bogus data either ends up getting written, or the next time we attempt to start a transmission (upon return of power) we are sending a start bit again, when we never sent a stop bit previosuly. At least this is my running assumption as of right now. Does this sound reasonable, or is there a way to fix that?

See amended answer.


text:
How do I stop a servo motor at the current position when using a serial port? I want it to remain in one position when receiving "0"
I am working on a project where I would like values received from an Xbox Kinect will activate components on my Arduino. Currently, I am trying to get a servo motor to turn on and rotate when the value is "1" and to remain in one position (currently written as 120degrees) when the value is "0". However, I can turn on the motor and initiate rotation just fine, but when I let go of the mouse (and it shows that the value "0" is being sent in Processing and on the Serial Monitor), the motor just keeps spinning. This is my current code:
char val; // Data received from the serial port
#include <Servo.h>
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600);
}

void loop() {
  if (Serial.available())
  { // If data is available to read,
    val = Serial.read(); // read it and store it in val
  }
  if (val == '1') { // If 1 was received
    Serial.print ("1");// turn the LED on
    for (pos = 0; pos <= 120; pos += 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }
    for (pos = 120; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }
  }
  if (val == '0') {
    Serial.print ("0");
    pos = 120;
    myservo.write(pos);
  }
}

The logic of your sketch is to move from 0 to 180 and back when receiving the character '1'. The movement is completed before checking for the next character. Your sketch does not allow stop at the current position during the movement.

Are you sure the mouse is not sending a continuous stream of 1s? If that were the case then, because of buffering, all the 1s will serviced before the servo stops. For example, a sequence of 11111 followed by a 0 will cycle the movement 5 times before it stops and prints the 0.

fairly simple:
switch (serial_received()) {
  case -1: break; //-1=nothing received
  case  0: break; //0 received
  case  1: servo_pos = ...; servo_move2(servo_pos); break; //update servo position
  case  .... //other commands
  default: ...
}

you can fill in the functions with whatever appropriate for your environment.