text:
Robot beeping when power set to 0
I am working on an Arduino Uno robot project for college, I have modified my robot to beep and light up when he bumps into a wall or reverses, my robot works fine except for one very annoying problem, when my robots power is switched to 0 to turn him off he starts to beep as though he is bumping and I have no idea why!
My code:
#include <Servo.h>                           // Include servo library

Servo servoLeft;                             // Declare left and right servos
Servo servoRight;

byte wLeftOld;                               // Previous loop whisker values
byte wRightOld;
byte counter;                                // For counting alternate corners

void setup()                                 // Built-in initialization block
{
  pinMode(7, INPUT);                         // Set right whisker pin to input
  pinMode(5, INPUT);                         // Set left whisker pin to input
  pinMode(8, OUTPUT);                        // Left LED indicator -> output
  pinMode(2, OUTPUT);                        // Right LED indicator -> output

  tone(4, 3000, 1000);                       // Play tone for 1 second
  delay(1000);                               // Delay to finish tone

  servoLeft.attach(13);                      // Attach left signal to pin 13
  servoRight.attach(12);                     // Attach right signal to pin 12

  wLeftOld = 0;                              // Init. previous whisker states
  wRightOld = 1;
  counter = 0;                               // Initialize counter to 0
}

void loop()                                  // Main loop auto-repeats
{

  // Corner Escape

  byte wLeft = digitalRead(5);               // Copy right result to wLeft
  byte wRight = digitalRead(7);              // Copy left result to wRight

  if(wLeft != wRight)                        // One whisker pressed? (Output on the left is not the same as the right)
  {                                          // Alternate from last time?
  tone(4, 3000, 1000);                       // Beep for 1 second as we hit the wall (BK)
    if ((wLeft != wLeftOld) && (wRight != wRightOld))
    {
      counter++;                             // Increase count by one
      wLeftOld = wLeft;                      // Record current for next rep
      wRightOld = wRight;
      if(counter == 4)                       // Stuck in a corner?
      {
        wLeft = 0;                           // Set up for U-turn
        wRight = 0;
        counter = 0;                         // Clear alternate corner count
      }
    }
    else                                     // Not alternate from last time
    {
      counter = 0;                           // Clear alternate corner count
    }
  }

  // Whisker Navigation
  if((wLeft == 0) && (wRight == 0))          // If both whiskers contact
  {
    bump();                                  // Call bump function
    backward(1000);                          // Back up 1 second
    reverseBeep();                           // Call reverseBeep function
    turnLeft(800);                           // Turn left about 120 degrees
  }
  else if(wLeft == 0)                        // If only left whisker contact
  {
    bump();                                  // Call bump function
    backward(1000);                          // Back up 1 second
    reverseBeep();                           // Call reverseBeep function
    turnRight(400);                          // Turn right about 60 degrees
  }
  else if(wRight == 0)                       // If only right whisker contact
  {
    bump();                                  // Call bump function
    backward(1000);                          // Back up 1 second
    reverseBeep();                           // Call reverseBeep function
    turnLeft(400);                           // Turn left about 60 degrees
  }
  else                                       // Otherwise, no whisker contact
  {
    forward(20);                             // Forward 1/50 of a second
  }
}

void forward(int time)                       // Forward function
{
  servoLeft.writeMicroseconds(1700);         // Left wheel counterclockwise
  servoRight.writeMicroseconds(1300);        // Right wheel clockwise
  delay(time);                               // Maneuver for time ms
}

void turnLeft(int time)                      // Left turn function
{
  servoLeft.writeMicroseconds(1300);         // Left wheel clockwise
  servoRight.writeMicroseconds(1300);        // Right wheel clockwise
  delay(time);                               // Maneuver for time ms
}

void turnRight(int time)                     // Right turn function
{
  servoLeft.writeMicroseconds(1700);         // Left wheel counterclockwise
  servoRight.writeMicroseconds(1700);        // Right wheel counterclockwise
  delay(time);                               // Maneuver for time ms
}

void backward(int time)                      // Backward function
{
  servoLeft.writeMicroseconds(1300);         // Left wheel clockwise
  servoRight.writeMicroseconds(1700);        // Right wheel counterclockwise
  delay(time);                               // Maneuver for time ms
}

void bump()                                  // Light and sound code for when the robot bumps a wall (BK)
{

  tone(4, 3000, 1000);                       // Play tone for 1 second
  digitalWrite(8, HIGH);                     // Left LED on
  digitalWrite(8, LOW);                      // Left LED off

}

void reverseBeep()                           // Light and sound code for when the robot reverses(BK)
{

      for (int i = 0; i < 3; i++)
      {

        digitalWrite(8, HIGH); // Left LED on
        tone(4, 1600, 400);                     // Beep (Pin 4, 1600Khz tone for 400ms) (BK)
        digitalWrite(8, LOW); // Left LED off

      }

}

I am using this breadboard setup
http://learn.parallax.com/tutorials/robot/shield-bot/robotics-board-education-shield-arduino/chapter-5-tactile-navigation-6
The custom functions bump() and reverseBeep()are my custom functions to control the bumping and reversing beep and LED light up.
Does anyone know why he beeps when the power switch is set to 0?

Can you share your schematic too?

Probably electrical schema would be useful too. Servos and motors need high current to move decently fast, while Arduino does not need so much for "just live". If you have there large capacitors, or if the robot is moving when powered off and so turns motors to dynamos temporaly, then it is possible, that even with switch OFF the Arduino have enought power to live for a moment and at the same time the whiskers go donw as if pressed, so it works like it bumped.

I have edited my question now to include the relevant breadboard diagram.

Please avoid linking to your code on pastebin as the current configuration will remove your code in less than one month, making your question and any answers just plain useless at that time. Rather copy your code here in your question.

Code is very large, over 100 lines.

100 lines is nothing. 10,000,000 is very large.

I see no power switch on that diagram. We need your actual setup, not someone else's sketch that is vaguely similar in a few ways. How exactly do you "set the power switch to 0"?

I am following the tutorial, that is the tutorial, that is what I am told to do, the Arduino Uno board has a power switch directly built in http://learn.parallax.com/tutorials/robot/shield-bot/robotics-board-education-shield-arduino/chapter-3-assemble-and-test-12

Do you have the Arduino wired over USB? You can try logging the whisker statusses and if your bot wants to go left/right. Though your code seems sane and I think it's something electrically.

It does the same thing if wired or on USB, I probably should have tested another robot, it isn't a big deal it is just a little annoying.

bill it as a feature, not a bug.

By beeping I assume you mean a 1 second been with no flash from the LED.
The only place in you code that can happen is when the whiskers are not equal.  I think the whiskers are powered by the shield you have turned off, in which case I suspect they are floating.  Is it possible to power these direct from the board, bypassing the off switch?
The easiest way to fix it would be to allow the processor to know when the Off switch is on and off.  Wire the 5V from the shield to the Arduino via a resistor of ???Ohms and read that pin before doing anything in loop().


text:
Arduino Zero: Enable RTTI
I need dynamic casts for my project, I'm getting:
error: 'dynamic_cast' not permitted with -fno-rtti

It appears that RTTI (run-time type information) is disabled with the fno-rtti compiler flag.
How do I change this?

We'll need to see your code in order to help.

Welcome to Arduino SE.  Be sure to take the tour at https://arduino.stackexchange.com/

It apparently is true that “RTTI (run-time type information) is disabled with the fno-rtti compiler flag”; however, looking at compiler.c.flags and compiler.cpp.flags in platform.txt, no fno-rtti compiler flag is set, suggesting that gcc sets it by default.
One way to turn off fno-rtti is adding a -frtti flag into the appropriate flags string in platform.txt.  As a side effect, this will affect all sketches subsequently compiled, rather than only those that need dynamic casts.
Note, on a microcontroller, a more-appropriate way to deal with the problem is getting rid of the need for dynamic casts, via function overloading.
Edit 1: On Linux, typical file paths to platform.txt are like /opt/arduino-1.6.3/hardware/arduino/avr/platform.txt or /opt/arduino-1.8.0/hardware/arduino/avr/platform.txt.  I don't know the location on OSX.  However, a command like locate *avr/platform.txt should reveal its location.  (If locate is a new install on your system, first run updatedb, which may take a while.)

Do you know where the platform.txt file is on OS X? Perfect answer, thanks!

@CodySmith, see Edit 1

This does not entirely solve the problem for those wishing to use rtti. This does not enable the linker to complete the compile of a simple sketch with dynamic_cast in it. What are the steps to get that aspect working. (I know there are people who say it shouldn’t be done, but I’m curious and have some ideas I’d like to test). I have drawn a blank as to how to complete this process. (Sorry this should have been a comment)

source: Stack Exchange

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

sort: votes


text:
Why is my boards.txt file not being found?
I'm using the ino command line tool for the first time. When attempting to build my first sketch I run:
ino build in the project directory.
I get the following error:
Searching for Board description file (boards.txt) ... FAILED
Board description file (boards.txt) not found. Searched in following places:
  - /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino
  - /usr/local/share/arduino/hardware/arduino
  - /usr/share/arduino/hardware/arduino

What's going wrong here?
I've found an open issue here: https://github.com/amperka/ino/issues/240
But I'm wondering if anyone has a workaround.

I got a hack to work  (macOS) by symlinking the files to where ino expected them to be.  But now I'm running into this issue: https://github.com/amperka/ino/issues/149
FWIW:
cd /Applications/Arduino.app/Contents/Resources;
ln -s Java ../Java;
cd /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino;
ln -s boards.txt avr/boards.txt;

Did it for me as far as finding boards.txt goes.
Still Broken otherwise. (Not marking as answer)

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


text:
How to connect arduino with local network
I am trying to connect Arduino with local network. This will act as a web server, client would be android mobile app or web browser. These are on same local network.
Do I need Ethernet Shield or ESP8266 to make Arduino accessible with local network IP ? Is there any way to connect without Ethernet Shield ?

To connect to a network you need a network interface.  This could be an Ethernet interface, a Wifi interface or something that supports TCP/IP.  The easiest way of doing this is with ether an Ethernet 'shield' of a WIFI 'shield'.
In either case there are a range of options, from full shields to smaller boards that connect via jumper wires.  One important consideration is the longer the wires the more chance for signal degradation and loss of comms.  So direct plug in boards are probably better.
Probably the easiest way to do it is to use a ESP8266-??, but using an ESP as a network interface is like only using your PC for email.  The ESP is faster and has more memory than the Arduino, so it would be better to program that as the web-server and get the Arduino to feed it the data.
You could use Bluetooth, radio, etc, but that's just making life hard for yourself.
You could also look at the Arduinos that have networking built in.

If I deploy my web services code on IBM Bluemix or AWS then Can ESP8266 communicate with those servers ?

If they support raw TCP/IP communications yes.  If they support HTTP, REST or SOAP, yes.  If they need web-sockets, maybe if you can find a WS library for the ESP8266.

Thanks. Do you have any links which can help me to connect Arduino with ESP8266 on network ?

@Williams - The best place to look is the examples that come with the ESP extensions for the IDE.  Go to board manager, download the ESP stuff and have a look.

If you get yourself a board with an ESP8266 (say, Wemos D1, NodeMCU etc) this will allow you to do what you require and connect wirelessly to a local network. You can do this either with the Arduino using the ESP8266 as a shield or alternatively you can use the 8266 board on its own (it's a more powerful MCU than the Arduino!!)
Hope this helps.

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


text:
Where to connect shield in USB power supply for Arduino?
I'm making a 5 volt portable regulated power supply (using LM7805 regulator IC) for Arduino UNO. I'm planning to use a USB connector as its output socket, this way I can just plug it into the Arduino to power it.
My problem is where do I connect the USB sockets's shield? (Not an Arduino shield - I am talking about the USB cable's shield).

As far as I know it should be connected to the ground if it is a host device - can we consider the power supply as a host device?

Welcome to Arduino SE.  Please take a moment and take the tour at https://arduino.stackexchange.com/Tour

I don't see how it's too technical to be here. (FYI It's also named Electrical Engineering not Electronics Exchange) The question belonging there is also questionable, they usually push questions like these back here.

@Code Gorilla Thanks for the edit and advice, I'll try Electronic Exchange too.

SDsolar, Avamander Thanks for showing interest in my post.

@CodeGorilla I'm well aware of that. It just won't survive there and if you find it off-topic, use the close flags to indicate that.

In response to the "off topic" close flag; This is a perfectly acceptable question and falls within the "power" and "USB" Arduino Stack Exchange tags.

A similar question has been asked in the Electrical Engineering Stack Exchange: EMI/ESD protection for USB interface?

As for the SHIELD connection, you are correct - it is the metal casing of the connector and the braided shield of the USB cable that connects so it, which is likely referenced to protective Earth somewhere on the PC side of things. For EMI reasons it should not be directly tied to the GND signal connection, but should be connected through some impedance. I've seen both parallel resistor / capacitor (as you've shown) and ferrite bead connections between them. --Adam Lawrence

A good technical explanation was written by Ali Chen in his answer to this question:

Ali Chen's Answer to Structure of a USB 2.0 connector

In the answer, Ali recommends using a 330 ohm resistor in parallel to a 0.1uF capacitor between the digital ground and the protective earth (shield).

simulate this circuit – Schematic created using CircuitLab

If the supply for the Shield is 5V, then you can use one of the 5V lines on the Arduino to power the Shield, plus a common ground of course.

This isn't about Arduino shields, please read my question again. But thanks for trying to be helpful.

No probs, but upon reading your question again, to me it doesn't make sense. I am not clear on what you're asking, John!

Thanks for the comment. The shield I'm talking about here is the shield of the USB socket (a metallic cover surrounds the female USB connector) which I'm going to use at the 5v power supply side (as its output socket).

Aha, I think what caused the confusion is the use of the word 'shield'.  You're probably aware that 'shields', in the Arduino sense, are accompanying boards that sometimes fit atop the Arduino and provide additional functionality.

Read My First Comment!

I did. It was confusing. No need to be rude!


text:
Arduino powered car not running when touching ground
I hacked a cheap car I connected both motors to L298N Dual H-Bridge Motor Controller and all things are working good. Motors are running fast. But when I put the car on the ground to run. It runs so slow. I am using 4.5V for L298N.
What can I do to run it fast on ground?
I have tried PWM but it does not work.
What can be the causes of this?

Some measurements could help understand the issue.

What are you using to provide the 4.5volt?

The car's default battery back. It has space for 3 1.5V batteries. I am using that.

It cannot draw enough current I suppose. When wheels are free-spinning, the load on motor is very small. When you put it on ground, the load increases, and it is slow because there is not enough current to drive the load

Yep more power is always the answer :)

The question is. How car was actually running with 4.5V batteries before i hacked it?
Was that power enough to run the car without motor driver and arduino?
Can you kindly explain this?

If you are powering stuff directly from Arduino, problems will arise due to fact that Arduino pins have limited current output. I suggest you create a driver circuit, with transistors and external power source. Transistor is for external source control.

I powered it with 9V battery. It does not work. When I was using 3 1.5V batteries, the voltage of the motor was 1.8V but when I powered it with 9V battery, it was 1.8V again. And it does not move on the ground.


text:
Standalone atmega328
I have a transistor tester with 16x2 LCD running a plug-in at328 with an 8Mhz xtal. I would like to use this hardware for another purpose.
My first idea was to replace the crystal with a 16Mhz one, write a program on my Uno and swap the AT328.
Is this the only way? I also have an USB adapter. Reading/saving the code now on it is of secondary interest.

Does the transistor tester have an ICSP header?

To be able to program the chip, by plugging it in the socket of an UNO, it should have the Arduino bootloader. Which is most likely not the case. You can however use the uno running the Arduino-as-ISP sketch to program the bare atmega328.

Why replace the crystal? Just add or find a 8MHz entry.

there's a "hack" for the IDE that lets you run one without a crystal at 8MHz...


text:
Can you pass the entries of a strut array to a int array? if so how?
typedef struct {
  uint8_t  pitch;
}LearnNote;

#define  MAX_NOTE  500

LearnNote  Noteseq[MAX_NOTE];

int learnindex=0;
void loop() {
 MIDI.read();
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity){
Noteseq[learnindex].pitch=pitch;
learnindex++;
}

You are misusing the title. You are not supposed to squeeze your question there. Instead you should give a brief description of your Problem. Beside that in your particular case you can only cast your array from LearnNote to uint8_t. You need to loop over all entries and copy them one-by-one into an int-array.

Its not very clear what you are asking, but I think you are saying can you do this
uint8_t anArray[MAX_NOTE];
anArray = Noteseq.pitch;

In general the answer is no.  However in this specific case off the top of my head I think you probably can (maybe).  You have a struct which only contains bytes.  The compiler will probably pack the sequentially so you will effectively have a contiguous sequence of bytes which you would be able to copy to the byte array by doing:
memcpy (anArray, Noteseq, MAX_NOTE);  // THIS IS BAD PRACTICE!

You can only do this in this case because the types are both 8bit numbers.  Its not a good idea to do this copy between an array of structs and a POD type array is just asking for trouble.
Instead use a function to do it.
int* CopyPitch (LearnNote* source, int* destination, int count)
{
    for (int i = 0; i < count; ++i)
    {
        destination[i] = source[i].pitch;
    }
}

(You should really check for null pointers and stuff, but its just an example)


text:
comparing the entries of two arrays
i am trying to compare the elements of two arrays before the code goes on to the next sequence. The elements of note[x] are filled with the note values of a song. and i want to be able to input values from a midi controller into learn[x]. how can i compare array learn[ ]  to array note[ ] before the showsequence(); is incremented?
 const int x = 100;
    int note[x];
    int learn[x];
    int largestindex = 0;
    int learnindex=0;
    void showsequence();
    void readsequnce();
    const int PLAY = 1;
    const int TRYAGIN = 2;
    int state=0;

 void loop() {
     if (state == PLAY) {
        showsequence();
        readsequnce();
      }
      else if (state == TRYAGIN) {
        incorrect();
       }
     MIDI.read();
    }
    void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
    learn[learnindex]=pitch;
     learnindex++;
    }

 void showsequence() {
      //Add a new index to the end of the songseq
      SongSeq[largestindex];
      largestindex++;
      //loop through the songseq
      for (int index = 0; index < largestindex; index++) {
        SongSeq[index]();
      }
    }

      void readsequnce() {
      static uint16_t nextkey;
      bool mademistake = false;
       nextkey=0;
       learnindex=0;

       if (array_cmp(learn, note, largestindex, largestindex) == true){
               // do this if they are equal
               lcd.setCursor(16, 2);
        lcd.print("True");
         }else{
               // do this if they are different
               lcd.setCursor(16, 2);
        lcd.print("False");
         }
    }

 boolean array_cmp(int *a, int *b, int len_a, int len_b){
         int n;

         // if their lengths are different, return false
         if (len_a != len_b) return false;

         // test each element to be the same. if not, return false
         for (n=0;n<len_a;n++) if (a[n]!=b[n]) return false;

         //ok, if we have not returned yet, they are equal :)
         return true;
    }

It depends what sort of comparison you want to do.  If you want to see if note[x] == learn[x] then that's what you do.
If you want to see if all the notes match all of learn then you'll need to put the comparison in a loop.
for (int n = 0; n < MAX_NOTE && note[n] == learn[n]; ++n)
{
    // Empty loop
}

If you want to see if the first n notes match the current note and the proceeding n notes then its a bit more complex, but its just a loop.
int n = 0;
for (int l = currentPos;
(l > (currentPos - 10)) && (note[n] == learn[l]);
 l--, n++)
{
    // Empty loop
}

If it is something else you want, please can you try and describe it in idiot proof terms so I can understand it.

i want to compare note[x] == learn[x] but then once the compare is matches to compare note[x] == learn[x] (x going from 0->1) increasing  by 1 every time the match is correct

Then use the bottom example, but int n = x, int l = x and l++.  You will have to be careful about n and l exceeding the maximum index of the array/data, so add two extra conditions into the third line && n < maxData && l < maxData  (Need to set maxData to something sensible.

Start by assuming they match. Loop over each element pair, compare them, and set a flag when you find a pair that don't match.
bool they_match = true; // assume they match
for ( int i = 0; i < x; i++ ) { // for each note/learn element
  if ( note[i] != learn[i] ) { // check if they don't match
    they_match = false; // they don't mach, so set flag
    break; // stop looping
  }
}

At the end they_match will be true if note[] and learn[] match, or false if they don't.
I would suggest you learn how control structures work.
https://www.cs.fsu.edu/~myers/c++/notes/control1.html
https://www.cs.fsu.edu/~myers/c++/notes/control2.html


text:
Is there a manometer available to use with Arduino?
I used an analog manometer in a plumb system. I would like to actually track information about water pressure across an entire building on different points and record all this information to analyze changes on pressure. I was wondering if there is a manometer that can be used with arduino. Or if there is some other homemade solution?
If there is any electronic sensor with an analog output that would be enough.

There are intrusive ones, i.e. you need to cut the pipes.  I can't say I have seen one that you could just wrap around the pipe, but the should exist.  I doubt you find one specifically for Arduinos, but you should be able to get one that the Arduino can talk to, look for I2C, SPI or One wire interfaces.  If you can get the datasheet it should be simple enough to write your own library for it.  Looking for libraries is another way of identifying a suitable part.

@CodeGorilla Yeah I was planning to cut the pipe, I already used an analog one cutting the pipe. Thanks for the advice, I will start looking for I2C and SPI One wire interfaces.

glue a neodymium magnet to the analog meter's needle, then mount a hall-effect sensor on the side of the meter and read it's value to determine pressure. you could also go optical.

I think the problem is not the way to connect a manometer but the choice od the manometer. I work on project for Firefighters and my main problem is to find flow meters able to measure flow between 0 and 1000 liters per minutes, and manoter for pressure up to 25 bars and so on.

Bruno, there are a number of sensors available, try an Ebay search, to do what you want.  However, you need to determine what pressure range you are looking at.  As you mention manometer I assume you are working in the mBar range but to me that would be at odds with the pressure typically seen in whole building systems.  An Ebay search on 'Pressure transducers' will yield a good range of devices, likely to be primarily industrial types and some using wheatstone bridge type outputs.  you may need an op-amp circuit to buffer / amplify the output signal but virtually all sensors can be interfaced to an Arduino with the correct conditioning cicuitry.  As you are aware to measure pressure all sensors will need to be invasive into the pipework.

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


text:
waiting for a set number of inputs in an array to be reached
How do i have code wait for an x number of inputs be reached in an array before doing anything else?
int largestindex = 0;
int learnindex=0;

    void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
    learn[learnindex]=pitch;
     learnindex++;
    }

    while(learn[largestindex]==0){
          MIDI.read();
          if (learn[largestindex]!=0){
           break;
              }

Can you provide some example code of what you have so far?

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.  Also link to whatever MIDI library you use.  Does MIDI.read(); affect any of the variables mentioned in the snippet?

If the call to MIDI.read() is a blocking call (it stays in there until it has a value) then you are pretty close:
const int NumberOfInputs (42);
for (int index = 0; index < NumberOfInputs; ++index)
{
    MIDI.read();
}

You can simplify you handler by post incrementing the learnindex counter as you use it.  (Post increment will happen after the value has been 'used')
void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
    learn[learnindex++] = pitch;
}

When you increment a variable on its own line its usually better to pre increment it, because you aren't using the value and it might result in quicker execution.  However remember you are increasing the value before using it, so if you use it as above you end up accessing the array element one higher than you intended to!
int learnIndex = 0;
++learnindex;            // Pre-increment it to 1
learn[learnIndex++] = 1; // Set element 1 to 1.
learn[++learnIndex] = 3; // Set element 3 to 3.


text:
Arduino: wrong digitalRead results from a pullup pin
A button connects GND to PIN where PIN is any digital pin.
I want to catch the moment the button is pressed, so I wrote the following code:
void setup () {
    pinMode (PIN, INPUT_PULLUP);
    Serial.begin (9600);
}

void loop () {
    static bool wasDown = false;
    bool isDown = digitalRead (PIN) == LOW;
    Serial.println (isDown);
    if (isDown && !wasDown) Serial.println ("down!");
    wasDown = isDown;
}

While the button is not pressed, everything goes as expected: the output is all zeroes. But when I press it, the following pattern appears:
0
0
0
0
<Some other zeroes, about 10 total>
1
down!
<the same number of zeroes>
1
down!
0
...

Is it some schematic flaw?

We have no idea about the hardware involved, but you might want to read about debouncing.

It is definitely not the case, as the pattern is very regular and stable for a long period

Also looks like a debouncing problem to me. Could your button have a repeatable bouncing behaviour?

What happens when you keep the button pressed down - do you see a constant stream of '1'? Can you give us the reference of your button used? @PlasmaHH is most likely right and you might be suffering from debouncing issues.

8 buttons connected to different pins could not, I think

@HervéGrabas no, when I press the button, I see the pattern presented in the question text: N zeroes - one - N zeroes - one - ...

Schematics and/or picture of setup could help.

Perhaps try and repeat the experiment with an external resistor?

@JorenVaes For some reason an external resistor helped... Thanks!

What output are you expecting/wanting to see?

@Mazaryk All ones when the button is pressed, all zeroes when it's not. Serial just prints the button state continuously. Anyway, the issue was solved by downloading the sketch into another board


text:
How to code Arduino to follow schedule
I'm working on my system and I have to make arduino repeat such action or block of code if its the set time .. I'm using DS3231 module to track date and time .Example If I set the time in 6:00 AM and when the arduino reads the module and it turns out that its already 6:00 AM the arduino will now execute some action or the block of code .. sorry for my english ..

Could you use the TimeAlarms Library ? https://www.pjrc.com/teensy/td_libs_TimeAlarms.html

Check out how the DS3231 Alarm functions work.  They will interrupt even a delay() statement.  At the appointed time the specified function is called.
This same question was answered here:
How to set Alarms on the DS3231 easily?
For another way to see how to set this up, let me refer you to this article:
Build Programmable Time-based Switches Using a Real Time Clock
The code can be downloaded Here

This example shows a simple way of conditionally processing an event at a given time of day, once per day. The example allows 59 seconds of accuracy but in reality if the Arduino is free to read the time this will happen almost exactly at 6.00am.
You need to declare and populate currentTime and currentDate by reading the DS3231. This example assumes the currentTime is in millis.
unsigned long action1_LastDoneDate;
unsigned long TIME_600AM = 21600000; // millis 6.00 am = 6*60*60*1000
unsigned long TIME_601AM = 21660000; // millis 6.01 am

void setup()
{
 action1_LastDoneDate=0L;
}

void loop()
{
 //make sure we have not processed today
 if (action1_LastDoneDate != currentDate)
 {
   //make sure the time is within range
   if (currentTime>=TIME_600AM && currentTime<TIME_601AM)
   {
     //save off the current date so we don't try do process this alarm again
     action1LastDoneDate = currentDate;
     //now do the 6am stuff
   }
 }
}

Thanks for the quick reply .. I will try this and give you update , Thank you :D


text:
GPS autonomous robot
I am working on a GPS autonomous robot using Arduino, HMC5883 compass, Adafruit GPS module and I have managed to sort of complete the coding for it and I tried compiling / verifying it and I get an error. It would be helpful if anyone could assist help me find out what I am doing wrong in my code as I have spent 2 days looking for what I have done wrong and if someone could suggest a better way of writing my code or even improving it here code I appreciate it. HERE IS MY CODE http://textuploader.com/drhfa
Error:
GPS_move_:468: error: unterminated argument list invoking macro "radians"

I assume the problem is with this line: Wire.send("A);

it's not that I just corrected it and it still comes up with the error-@gre_gor

There's numerous missing semicolons...

Also you seem to have a missing close bracket at differencelongitude = radians((longitudeWaypoint2 - (longitudeWaypoint1)); (or an excess open bracket)

And a colon instead of a semicolon here: turn_left():

Using autoformat helps to highlight where these kind of problems are since the formatter can't format it right if there are errors like this.

Please post the code.  the linked location says the post has expired..   Suggest posting the code as part of your question (indent all code 4 spaces, so it will be displayed as code.

I cannot compile because there are libraries missing. However, after auto-formatting the code I have this list of problems:

Many lines lack semicolons at the end (check your variable definitions near the top of the code)
You have an extra bracket in one of your radians() calls (the one that is giving the error I guess): differencelongitude = radians((longitudeWaypoint2 - (longitudeWaypoint1));
There is an unterminated string literal: Wire.send("A);
You have a colon instead of a semicolon: turn_left():

There may be more but as I cannot even begin to compile I cannot find them easily - also there may be similar errors in any included files you have created.


text:
String array glitch
For a project, I was asked to design a presentation on Arduino. I now have run into the problem of my code suddenly stopping. It worked fine one day, I entered a new item in the array, it stopped working. It looked like I was being returned all newlines insteaed of debug info. Can anyone help?
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

int slide = 0;
const int slideNum = 13;
const String data[] = {
  "What is Arduino?\nArduino is a board\nthat can be used to\neasily program",
  "that can be used to\neasily program\ncomplex behaviors.",
  "Purpose\nMoney\nEase of Use",
  "How are they\ncontrolled?\nIDE, C++, Library\n",
  "Commonly Used\nCommands\ndiditalWrite();\ndidgitalRead();",
  "Commands\ndiditalWrite();\ndidgitalRead();\npinMode();",
  "diditalWrite();\ndidgitalRead();\npinMode();\nanalogWrite();",
  "didgitalRead();\npinMode();\nanalogWrite();\nanalogRead();",
  "Arduino Types\nUno\nMega 2560\nLeonardo",
  "Uno\nMega 2560\nLeonardo\nNano",
  "Mega 2560\nLeonardo\nNano\nMini",
  "Leonardo\nNano\nMini\nEthernet",
  "Nano\nMini\nEthernet\nBluetooth",
  "THE END"};

//Addr: 0x3F, 20 chars & 4 lines
LiquidCrystal_I2C lcd(0x27,20,4);

void setup()
{
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Send Newlne to start");
  Serial.begin(9600);
}
void loop()
{
  while (Serial.available() <= 0){
  }
  Serial.println("Current: " + String(slide));
  while (Serial.available() != 0){
    Serial.read();
  }
  next();
  if (slide == slideNum){
    for(;;){
    }
  }
}

void next(){
  String local = data[slide];
  String current[4];
  for (int i = 0; i != 4; i++){
    current[i] = local.substring(0, local.indexOf("\n"));
    local.replace(local.substring(0, local.indexOf("\n")), "");
    current[i].trim();
    local.trim();
    Serial.print("i=" + String(i) + ", current=" + current[i]);
    Serial.println(", local="+local);
  }
  lcd.clear();
  for (int i = 0; i != 4; i++){
    Serial.println(current[i]);
    lcd.setCursor(0,i);
    lcd.print(current[i]);
  }
  //lcd.print(data[slide]);
  slide += 1;
  Serial.println("New: " + String(slide));
}

Ouch, your poor poor heap...

Change const String to const char *.

@TisteAndii Provide that as an answer, it does work.

I edited the question to format the code; the HTML tags you put around the code didn't work.  The text in questions and answers on SE sites use Markdown Syntax, a sort of bastardized HTML.  ¶ You should fix those silly misspellings (extra d, or d instead of g, in "diditalWrite" and "didgitalRead" [sic]

You should really use PROGMEM to force the strings to remain in Flash. Oh, and never use String for anything, ever.

@JamesWaldby-jwpat7 Oops.

Since you haven't provided all of your code, I can't say for sure exactly what caused your problem except that Arduino String operations employ dynamic allocation a lot. This will cause heap fragmentation, which is especially bad on a chip like the ATmega328 with little RAM and subsequently cause weird issues like you're getting. I would guess that initializing the String members of the array takes up a lot of heap space while fragmenting it and when you added one more string, you ended up with a stack-meets-heap situation at some point in loop().
You're a lot better off with an array of compact strings using an array of pointers to char i.e. const char * array[] = ... since the strings are literals and so already known at compile time.

Thanks! Honestly, I copied all of my code, don't know why it didn't paste.


text:
home automation - What's a compact way to control a light switch with Arduino without interacting with high voltage?
To be clear, this question is not about physically wiring into the light switch to control the lights - simply pressing on the switch from the outside. I apologize in advance if my electrical vocabulary isn't up to par - I'm very new to this.
I have been developing an Android app that allows me to control Particle Photon boards over the internet, and I have already installed a board that turns my computer on and off. However, I am researching ways to automate the lights (ceiling lights, not lamps) without interacting with high voltage. I have not been able to find any good information.
Does anybody have any advice?

Other than with X10?

Welcome to Arduino Stack Exchange.  Be sure to take the tour at https://arduino.stackexchange.com/Tour

Get those RF wall switches. Then connect a RF transmitted to your photon. The protocol for most name brand switches have already been reverse engineered.

you can glue an LED controlled by an MCU into the sensor hole of a dusk to dawn sensor. these are available in socket and outlet shapes, are UL certified, and require no messy wiring. I've been able to switch an outlet model by duct-taping an ESP8266's built-in LED against the window; can it get any simpler?
Here's a working example's parts, exploded for easy identification.

You can spot an inline socket-to-outlet adapter, a dusk-to-dawn sensor, a bulb, a cheap nodeMCU ESP8266 devboard, a short micro usb cable, a USB wall wort, and an RGB LED module attached to dupont wires. I'm wiling to bet anyone here can figure out how these pieces fit together to make a $10 "smart bulb". You can get most of these parts at the local home center, and everything shown on amazon/ebay.
Of course you won't get a lot of respect from EEs, but you will get the job done quickly and safely, and the opto-isolated controls work with any platform. I have cheaper/smaller build i've moved onto, but i still have several of these switch builds in-place for years and they work great.
I would recommend getting a dusk-to-dawn switch that is labeled as being compatible with LED bulbs; they tend to use a lower-"bleed" IGBT instead of the older/cheaper diac/triac combo which causes some low-energy bulbs to flicker when off.

I have built a 'switch-flip' controller that just attach to the regular light switch. The controller has both RFM69 radio and Bluetooth module in it so it can use iPhone (iOS app only for now) to control the switch on/off.

Walmart and others sell battery-operated units that can flip switches to turn lights off or on. Example: AutoChron Wireless Light Switch Timer, as seen in following picture.

You could buy one of these (for about $25) then hack into it and attach wires to the On and Off buttons to allow an Arduino to simulate presses of those buttons.  The unit would move the switch handle accordingly.

A clumsy way would be to use a servo motor connected to the mechanics of the switch, somehow.  Or in a dimmer, replace the rotating knob with the output of a servo, thus simulating it turning.  Not sure if that's what you were after.


text:
Transistor amplifier to drive speaker using Arduino PWM
I have been working on a project lately which uses Arduino to play a wav file from SD card. I am using TMRPCM library which made the job very easy. But the problem is that the output sound in the speaker is very low. I am using the below single transistor circuit with my Arduino to drive 1.2W / 8ohm speaker

But the Audio output is barely audible. And i have tried many speakers with different wattage but same result.
I am wondering that is there is something wrong with the Wav file i have used for my project. It is 16000Hz/ 8 bit unsigned PCM coded. So in a nutshell my questions are
1) How can i improve the sound obtained from my speaker by making modifications in the transistor amplifier circuit?
2) Was the less audible sound is due to the Wav file i have used?
Kindly help me out, thanks in advance.

I had some success using an LM386 audio amplifier after an CRC band-pass filter (to remove the DC and the PWM frequency). It's a very common and cheap (less than $1) amplifier specifically designed to drive a speaker. See the datasheet for the proper wiring.

Can you play the WAV file on your PC?  Is it quiet on there?  Can you play another WAV file, or use another audio source?

Hi @EdgarBonet , I have tried hooking up with a LM386 based amplifier but very little improvement. May be i will try with the CRC filter before feeding it to transistor. Am not quite whether its quiet in PC i would say its fine. Other wav files are less audible as well. However i have tried default Arduino melody tones which sounds pretty good with the same setup

you need to at least block the dc component with an rc filter. edit: basically, what Majenko has shown.

Ditto with @Edgar.  There are Arduino LM386-based amplifier modules available for peanuts.  They can drive a decent speaker.

Your amplifier arrangement is fundamentally flawed. At the moment you are "tickling" the top end of the electromagnet in the speaker - that is, you are energising it when the Arduino outputs a HIGH, and leaving it energised to de-energise by itself when the Arduino outputs a LOW.  Coupled with that the fact that a PCM file outputs PWM with a carrier frequency much higher than a tone() function (and ideally above human hearing frequencies) you end up with almost nothing happening on the speaker.
The classic Class A amplifier has a different arrangement:

simulate this circuit – Schematic created using CircuitLab
With that arrangement the transistor and R1 form a simple RTL inverter. Size R1 to give the output current you need for your speaker (lower resistor = more power = more heat = bigger transistor as well). R3 and C2 remove the high frequency switching from the PWM (you could also replace R3 with a suitable inductor if you want less losses from the resistor). C1 removes the DC offset from the signal to give the full swing to the speaker and prevent excess clipping and heating.
It's not an efficient design by any means. A better "first stage" (replacing R1 and Q1) would be a high drive output logic gate (one of the CD4000 series, since it can run from 12V). I have seen AND gates used before - this also gives the benefit that you can use the second input to the AND gate as a MUTE signal. The rest (R3, C1, C2) remains the same.
The advantage of using a logic chip instead of the RTL arrangement is that it gives a more efficient "Push-Pull" output which can deliver much more current with far less heat losses.
Instead of the speaker you could connect an audio power amplifier to the output of C1 to then drive a more powerful speaker. In this case you can most likely remove the first stage (Q1/R1/R2) and drive the RC filter directly from the Arduino.

Thanks for the circuit. Tried it but no luck the sound has even dropped. Double checked to make sure i have hooked up everything correctly. Also the transistor is heating up, any idea why this is happening?

The transistor is heating up because it's a tiny little 2N2222. If you look in a real audio amplifier you will see TO220 style transistors and big heat sinks. Using PCM audio on an Arduino is pretty silly anyway. You should invest in a proper audio shield, or a more powerful MCU that can do real audio.

Hi, I'm curious whether I should be able to hear the difference in sound quality between the Class A amplifier and the circuit given by the OP?  Wiring them both, couldn't tell the difference, but the OP circuit generated the same "loudness" at 11mA which the Class A amplifier took 110mA.  The OP circuit seems 10x lower power for comparable loudness.  (I couldn't tell the difference in sound quality, using an 8R, 3W speaker, at 5V playing Jesu by Bach on an Arduino)

You might try an audio transformer in the circuit, following a low-pass filter to smooth the PCM signal.  Here's a picture of suitable inexpensive transformers (from alexnld.com; but similar transformers are available on Ebay etc.):

The effect of the transformer in the circuit is transforming the high voltage, high impedance output of the transistor driving circuit to the low voltage, low impedance needed at the speaker.  The impedance ratio of the transformers in the picture is 1300 Ω to 8 Ω.

"It is 16000Hz"
That's pretty high frequency. Is your hearing good enough for that? Many folks couldn't hear it.

First, do not get fooled by some that answer that 16kHz is a pretty high, nearly unhearable frequency. You're talking about sampling rate here. Then 16khz is pretty low end (although maybe on the edge of what's possible with the microcontroller, I don't know that off the top).
I would recommend introducing a negative supply rail to majenko's design as you can not expect a circuit to output negative voltages (i.e the negative halfwaves of an audio signal) without a negative supply...
As others already pointed out the transistor you use is a pretty poor choice. There is a transistor selection guide available here.
It has an audio section, take a look at that!


text:
Calculating with millis()
The following code works fine until I turn the if (tijd - action >= 500) into if (tijd - action >= 1000)
I wonder why this fails.
If I just loop and print the tijd - action it has no problem with it and runs well beyond 1000.
The Logic Analyzer on the software serial only returns '255' when it fails, I also wonder what that means.
The core I use is this one
The chip I use is an ATtiny85
I run this using the Arduino IDE 1.8.2
[update]
with "start"
Sketch uses 3070 bytes (37%) of program storage space. Maximum is 8192 bytes.
Global variables use 146 bytes (28%) of dynamic memory, leaving 366 bytes for local variables. Maximum is 512 bytes.

with "starting"
Sketch uses 3072 bytes (37%) of program storage space. Maximum is 8192 bytes.
Global variables use 148 bytes (28%) of dynamic memory, leaving 364 bytes for local variables. Maximum is 512 bytes.

script
#include <SoftwareSerial.h>
#include <avr/sleep.h>
#include <avr/wdt.h>

#define TX_PIN 4
#define RX_PIN -1

#ifndef cbi
  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

SoftwareSerial mySerial(RX_PIN, TX_PIN);

unsigned long tijd;
unsigned long action = 0;

volatile boolean f_wdt = 1;
ISR(WDT_vect) {
  f_wdt=1;
}

void system_sleep() {
  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out
  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

void setup_watchdog(int ii) {
  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

void setup() {
  mySerial.begin(2400);
  mySerial.print("Starting..");
  setup_watchdog(8);
  pinMode(0, OUTPUT);
}

int zie = 0;

void loop() {
  if (f_wdt==1) {
    digitalWrite(0, HIGH);
    tijd = millis();
    mySerial.print(".");
    mySerial.print(tijd - action);
    zie+=1;
    if (tijd - action >= 500) { // fails when set to 1000
      digitalWrite(0, LOW);
      action = tijd;
      mySerial.print("z");
      mySerial.print(zie);
      mySerial.print(".");
      system_sleep();
    }
  }
}

Which ATtiny are you using?

the ATtiny85 is what I use

Try Serial.println(tijd) before your comparison. See how many ms it takes till it gets to comparison. maybe it is bigger than 500, but lower than 1000

You mean printing millis() before comparison right, because tijd is fixed at the start..

It looks like there is nothing wrong with your code, which means its not easy to see.  Is it possible to reduce the problem just to its bare essentials and have a loop that prints something every second?

To get to the comparison it takes ~24ms. I expect the Watchdog Timer to interfere with this code, that is why it's not a clear small sample.

@Thijs - Sorry I didn't mean "you need a minimal repeatable example", I meant is it possible to reproduce the problem with just the simple loop, no watchdog, etc.  Unless you think its the watchdog causing this issue.

Does the watch dog reset millis()?  Does the watch dog re-initialise the variables, i.e. action?  I suspect yes, no.  So is it possible action = 500 and (tijd - action)  = 500 and it doesn't run long enough for millis to go past 1499?

You will not be believe this; if I change the string "Starting.." to "Start" it will run fine! This probably has something to do with filling up the RAM of the Tiny, right?

if I change the string "Starting.." to "Start" it will run fine! This probably has something to do with filling up the RAM of the Tiny, right?

That symptom does suggest RAM overflow, in spite of the relatively low RAM use (28%) reported during compilation.
To reduce memory use slightly more, you can move the string "Starting.." to PROGMEM by changing from line 1 below to line 2.
  mySerial.print("Starting..");     // line 1
  mySerial.print(F("Starting.."));  // line 2

To save another handful of RAM bytes, change lines like mySerial.print("."); and mySerial.print("z"); to mySerial.print('.'); and mySerial.print('z');.  That is, you are printing single-character strings; each string has a null terminating byte; instead just print single characters.
References and discussion of the F() macro include 1, 2, 3, 4, 5 and also see  How do I squeeze code to fit onto an ATTiny.  Also, there are some really compact software serial libraries targeted for ATtinies, which may save hundreds of bytes of flash and dozens of bytes of RAM.

I'm not going to disagree but I'd be interested to understand why its happening at such a low threshold.  (unless the values reported are [rubbish])

Adding the F already does the trick. I would like to know why this is a solution. I still have a library to add to this code, I will probably run into the same trouble again..

@CodeGorilla, that I don't know, which is why I say  “does suggest RAM overflow” instead of proving it.  I've seen somewhat larger ATtiny85 programs, and don't know what's wrong here.  Answers to  How do I squeeze code to fit onto an ATTiny might suggest an approach

@Thijs, I added some F() links, but as noted I don't know what's wrong.  Perhaps read the assembly code looking for surprises.


text:
Making MCUs Arduino Compatiable
I have recently just built a custom arduino using the schematics found on their website. As awesome as this little processor is, I need more power. I have been thinking of making my own MCU, but wanted to know if it is possible to make them compatible with the arduino software. It would be very nice to not have to rewrite my existing programs.
If so, how would I go about doing that? If this is not a possibility (or just not a good idea for any reason), which language should I learn to start programming these upper level MCUs.
If I do have to start using a different language, what kind of software do I use to upload the code to these processors? And do they have the common features like Serial Monitor and Serial Plotter like the Arduino IDE does.

Are you talking about making your own MCU or your own devboard? The former requires a lot more work.

Have a look at the Teensy boards: https://www.pjrc.com/

There are several "Arduino compatible" boards with ARM core mcu, over at mbed.org (note: my employer makes one of them, the MAX32600MBED.)

What do you mean by "power"? Actual electrical power, i.e. "more watts" or more computational power, i.e. "more MIPS" (or "more MHz's")? It is not clear from your question.

There's already arduino compatible 32-bit microcontroller boards (ARM,MIPS,X86 ....) - see the wikipedia "List of Arduino boards and compatible systems"

You are speaking of porting. The arduino environment is built around a set of libraries and commands that are designed to abstract the low level access to a simpler high level language. In order to make arduino code work on a new microcontroller, you would have to rewrite and recreate the libraries using the low level access of your target microcontroller.
For example, Energia is a port of the Arduino libraries to the Texas Instruments MSP430 line of microcontrollers. Since not all features are the same, some code does not just drop in directly but additional code or libraries could be added to fix that. Even the Arduino IDE, the program used to write code and program the arduino was ported.
It would not be a trivial thing to port an entire library base.

As to your other questions, you would code your new microcontroller in any language it's programmer and compiler can use. Likely C or C++. Arduinos are typically programmed in C++. You should look into the manufacturer of your MCU to find out what software to use, and what libraries they offer. They likely do not offer something like the serial monitor right out of the box.

...but no porting is necessary, if one chooses a more potent MCU for which a port already exists.

The Arduino IDE supports a whole list of micros:
http://forum.arduino.cc/index.php?topic=145065.0
Some of those have a lot more power than the others. But to answer your question, no you cannot say take an ARM and use the Arduino IDE with it. It all comes down to your compiler and environment. At work we use ARm based processors and Keil uVision to program and Flip to program them. At my previous job we used Freescale Kinetis micros with CodeWarrior to flash and write the software. It all depends on what you decide to go with to fit your application, but it all boils down to it's all C or assembly if you decide to go that way.

OTOH, you could take existing ARM support for Arduino and modify it appropriately for your specific chip.

That's a very outdated list. Better is https://github.com/arduino/Arduino/wiki/Unofficial-list-of-3rd-party-boards-support-urls in addition to the product page: https://www.arduino.cc/en/Main/Products. If you look at those pages you will see there is support for ARM based boards made by Arduino as well as 3rd party ARM boards so your statement is wrong. Arduino is not only AVR! Of course there may be a significant amount of work to add support for an ARM that is not currently supported but it's certainly possible.


text:
Diorama Controller Part 2 - Need More Outputs
For background see my original post.  I've decided to not to use batteries and have it wired up with wall power.
I wish to use the Arduino Pro Mini 5V as the controller for my diorama project.  I have five completed buildings which will all have LEDs (with only two wired up so far).  The two currently wired buildings have multiple "zones/rooms" that can have its LEDs activated separately.
Building 1 is a saloon with rooms above.  It has a total of 7 zones/rooms.
Building 2 is a store with a doctor's office above and rooms in the back of each.  It has 4 rooms.
With this setup, I am able to use the software to simulate people coming and going within the rooms.  It's pretty neat.
However, I'm currently at 11 outputs out of the Mini.  I'm running out of pins.  How can I have more outputs?

I think I understood what you want. If you want to control more LED's with less pins, consider using a shift register. For example, sn74hc595 could increase your digital outputs drastically. It has 8 bits, so you can have 2^8 combinations of outputs with it! For example, 0000 0001 is something, and 0000 0010 is something else, and so on. Check it out! I hope this helps :)
https://learn.sparkfun.com/tutorials/shift-registers - Basic knowledge about shift registers
http://www.bc-robotics.com/datasheets/sn74hc595.pdf
Other shift registers are great as well

This looks like it might solve my problem.  Let me completely read it before marking this as the correct answer.

Will I be able to use Pulse Width Modulation with a shift register?

I have never used them in that way, here is an article, perhaps you find your answer there http://forum.arduino.cc/index.php?topic=8183.0

Very cool.  Looks like I'll be buying some more parts and trying some stuff out.


text:
Two TH02 Sensors to Grove Base Shield V2
We are trying to connect two TH02 (Grove - Temperature&Humidity Sensor (High-Accuracy & Mini))  sensors to Grove Base Shield V2 that is connected to Arduino Wifi Uno.
We connected the each sensor alone to I2C of the Base shield and it is working just fine, but when we connect two, we cannot get simultaneous readings.
We are new to Arduino and we are trying ti figure out if these two sensors can be connected to I2C even if they have the same address.
Please tell if we need to provide more information. Thanks!

It looks like they have a fixed I2C address so, if I understand correctly, unfortunately you cannot address them individually if they're both on the same bus. Perhaps there's a way to multiplex the bus...

Get i2CScanner to confirm what mark has said (he is usually right).  This just scans the I2C bus and tell you what addresses respond to it.  (Its a useful Arduino program to have to hand anyway).  You can get chips that create a second I2C bus, can't remember the make or model, but they are out there.

I have done, and the TH02 sensor's address is 0x40. Is there a way we can connect one of the sensor to D2 or D4?


text:
Port manipulation in Arduino using byte value
I'm trying to write PORTB and PORTD in ATmega328P using byte system like this,
    //  PD7  PD6  PD5  PD4  PD3  PD2  PD1  PD0
    //  N     N    N    N    N    U    U    U
    //  7     6    5    4    3    2    1    0
    //======================================
    //  PB7  PB6  PB5  PB4  PB3  PB2  PB1  PB0
    //  X     X    1    1    1    1    1    1
    //  C     C    13   12   11   10   9    8
    //======================================
    //C-Crystal Pins/U-Un used/N-Used/X-unknown value

    byte pins[] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};

    //uint16_t style1=1365; //10101010101
    //uint16_t style2=682;  //01010101010

    void setup() {
      for (int i = 0; i < 11; i++) {
        pinMode(pins[i],OUTPUT);
        PORTD=B00000000;
        PORTB=B00000000;
      }

    }

    void loop() {
      PORTD=B10101000;
      PORTB=B00101010;
      delay(1000);
      PORTD=B01010000;
      PORTB=B00010101;

    }

According to this , Port value should be swapped.
But, It's still remaining given value of the code before delay()
What is the problem in this code?

What is the problem in this code?

No problem, it does change the bits of port D and B from 0B10101000 and 0B00101010 to 0B01010000 and 0B00010101 respectively.
However, microseconds later loop() runs again and changes them back to  0B10101000 and 0B00101010 for a full second.
To better see what's happening, add a second delay(1000); statement, placing it just before the closing brace.

Ops,,,I really know about that.But,I have forgot that.,Im  very mad. Thank you.


text:
Problem with SIM800L GSM module and servo
I have a SIM800L GSM module like in this link, .
.
The problem is when I connect the GSM to my Arduino Uno the GSM turns on for a while and then turns off. I tried to connect it with a 9-volt battery and an LM7805 voltage regulator, but I have the same problem. Attached to the Arduino are an LM35 temperature sensor, two LEDs, a buzzer, an LCD, a GSM module, a gas sensor and a servo.
The other problem is with the servo. I tested the servo and it works fine but when the servo stops moving, it starts to shake. I do not know what the problem is.

9V batteries are useless. They are only any good at powering smoke alarms. Use a proper power supply or better batteries (6xAA or 2S Lithium Ion).

But I used LM7805 with battery to drop the voltage down! so you recomnded to me to use one of these,(6xAA or 2S Lithium Ion).?

You "drop the voltage down" by throwing away about half of it as heat. The current remains minuscule since the battery can't provide much (which is where your problem lies). You either need a source that can provide more current (6xAA or 2S Li-Ion) or a switching regulator that can convert the excess voltage into current.

Hi Majenko.. i used 6xAA but it is still did not work i donot know why, if u know other way to produce 3.5v and 2A let me know because i think my problem in the current .

Look for a 5v UBEC from somewhere like hobbyking.

You SIM800 module will pull 2Amps when its transmitting.  If your servo is also trying to overcome the inertia at the start of a movement it will pull 4+ times its normal running current.
A 9 volt battery will let you pull a couple of hundred milliamps.  So when the GSM transmits you system will shutdown.
You need a proper power supply or a battery pack that can put out these levels of peak current (3+Amps)

What did you mean by battery back ? And if i got it how can i connect it and connect it to what? I'm afriade of u because i did not understand it.

A battery pack, like 4xAA batteries or 2x3.7vLipo, etc.  You are going to power source that can deliver a peak current of 3Amps or more at 5V.  To start with it will be cheaper to use a plug in power source, once you have verified that your system works you can try and find a "battery pack" that will deliver the current you need.


text:
3x3 LED Matrix with less pins
I'm building an audio cable tester/soldering station.  XLR cables have 3 pins and they can be wired in a few ways depending on what you want to do.  The basic cable is connected 1 for 1 and I want to make a system to verify if each pin is connected to the good ones on the other connector.
Picture the male and female connectors side by side.  The 3 pins on the male connectors will be connected to 3 digital outputs and the 3 pins on the female connector will be connected to 3 digital inputs.  That way, I can turn one of the outputs High and check my 3 inputs to see where that pin on the male connector is wired on the female connector.  Then I can walk the remaining outputs and find out how the rest of the cable is wired.
That part is all good, I can output the wiring via the Serial.print() command and the result is good.  The thing is that I would like to show the result with LEDs.  It brings me up to 9 LEDs in a 3x3 matrix.  I can use 9 outputs to show the result, but it seem like there could be a much better way.
The two solutions I see are the following:

Buying addressable LEDs and interface them with my Uno
Use 6 outputs, one for each row and one for each column.  Each row represents one pin on the male connector, each row represents one pin on the female connector.  So while I walk my 3 pins I can turn on the corresponding row and columns, then turn off that row and go to the next one, turn on the corresponding columns, etc.  I feel like this would work, but I'm wondering if the LEDs will flicker or if the refresh will be fast enough not to be noticeable.

What would you suggest?  Am I on the wrong track with solution #2?  Is there another way that does not require that many outputs?  I'm already up to 12 IO pins taken with #2 and 15 with #1.  It seem like a lot for such a simple build...

Option #2 can definitely work, it is based on a widely adopted side effect of human vision called Persistence Of Vision, abbreviated with POV, which is used in Television, LED cubes and many other display devices.
You SHOULD notice no flickering if you manage to keep a refresh rate above 24 FPS (Frames Per Seconds or full refreshes), but not all human being are the same, that's why we tend to aim at 60 or 100 FPS to ensure flickering is not perceivable by anybody.
What you WILL notice though is a reduced brightness as each LED will be turned on only for a fraction of time.
So, naming your pins as COL1 to COL3 and ROW1 to ROW3, you can refer to the following schematic:

simulate this circuit – Schematic created using CircuitLab
You can further extend your option #2 by using an external IC, commonly referred as LED drivers: not something you need unless you get short of outputs.

Thanks a lot for that.  The LED driver shouldn't become necessary with this project, but I'll keep it in mind for future stuff.  I already ordered a few adressable LEDs just to play with them eventually, but in that case, I don't need RGB anyway.

It might be most cost- and time-effective to use an SPI-interfaced MAX7219-based 8x8 LED module.  These cost a couple of dollars.  Typically they include an 8x8 array of single-color LED chips, mounted under a cover.  The MAX7219 handles LED multiplexing and allows software control of brightness as well as resistor control.
To represent 9 items in a 3x3 arrangement, you could use 4 LEDs per item, so that rows 1 and 2; 4 and 5; 7 and 8 represent rows of items, with LED rows 3 and 6 remaining blank; and similarly for the columns.
Note, with four output lines you can control 12 LEDs, multiplexed via “charlieplexing”.  But the time and cost of setting that up probably would be somewhat more than just using a MAX7219 module.

I might expand my project eventually to do other connectors (some of them have 8 pins to check) so if I get there I'll get the 8x8 led matrix.  I've read about charlieplexing already, but being pretty new to electronics I got a bit lost.  I've been coding for a long time, so that part is not hard at all for me.  The rest is still a work in progress, but it's very exciting!


text:
serial.write if condition
I am trying to do a simple serial communication control via sending a char and using it as an if condition, the arduino part is below
char incomingchar;
void setup() {
    Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
//        Serial.write("g"); // does not work when I explicitly write here either as opposed to through python.
}

void loop() {
    if (Serial.available()) {
            // read the incoming char:
            incomingchar = Serial.read();
               if (incomingchar=="g"){
              Serial.println("hello world!");}
              else{
              Serial.println(incomingchar);
    }
}
}

And here is the Python code:
import serial;
ser=serial.Serial('COM3',9600,timeout=1)
ser.write(b'g')

When I run this, the python program returns a '1', and so does the arduino program in the serial monitor.
Note, if I directly set Serial.write('g'), it simply types out 'g' in the monitor and does nothing else from the loop.

With Char types you want to use the single-quote mark instead of double quotes.

Welcome to Arduino Stack Exchange.  Be sure to take the tour at https://arduino.stackexchange.com

I think @Mazaryk's answer is correct, but may a comment regarding your comment: the reason writing "g" to serial in your setup doesn't work is because that would be written to the output wire, and you're reading from the input wire.

hi Mark, thanks for your insight, could you explain a little more about output wire? I thought what I was doing was sending the 'g' to the arduino, what is the way to 'input' to the arduino then?

You declare incomingchar as a char. In your if you compare that char to a string (double quotes) incomingchar=="g". I think you want to compare it to a char (single quotes) like this:
if ( incomingchar == 'g' ) {
  // do something
}

Hi Mazaryk, I made the change, it works now (albeit in a different paradigm where serial monitor or Arduino IDE is not open) I think the issue was also that python can't access the port if you have arduino or serial monitor open, so it was preventing me from really testing it. If someone knows how to get over that, would be much appreciated.


text:
NodeMCU powered with battery and use WiFi
I'm running a project with a nodeMCU DevKit and my project runs smooth if I run it connected through the usb wire to the computer.
I need to run my project using battery and I tried with a ICR14500 battery (3.7V and 700mAh). I connected the battery to the Vin pin but the NodeMCU doesn't send the data to the cloud.
When I run it with the battery I have detected some random behaviour, some times the led on the ESP8622 is blinking continiously and the total board power consumption is around 130mA!
Any idea what can be happening?

connect it to the 3V pin to bypass the LDO on VIN. A 3.7v  Vcc is ok: barely within spec...

This is a good approach, I will try this. My project is ported from another implemented with a D1Mini and I have realised that the LDO in the D1Mini is the TR9013 which has a voltage dropout maximum of 250mV. On the contrary the LDO on the NodeMCU is the NCP1117 and it has a output dropout around 0.9V at 100mA.

@dandavis a full lithium battery is 4.2 Volt. I think this is far out of spec.

You  need to use a voltage regulator with a lower dropout.

@Gerben:  touche; I forgot 3.7!=3.7. a hybrid buck+boost set to 3.3 and connected to "3V" would be ideal in this precarious situation; minimal heat, forgiving input voltage (ex: 3.8-12).

In order to reduce the voltage to 3V maybe a diode could be added to drop the battery voltage from 3.7 to 3V

Or use a zenner diode to clamp the voltage to within spec.

I'm voting to close this question as off-topic because it is about the ESP8266 hardware but about neither Arduino hardware nor Arduino-based development on alternate hardware.

It seem to be a problem with onboard regulator such as AMS1117.
ESP are really sensitive to power instability.
For every of my project i need to put capacitor on alimentation to prevent bugs.
I think you dont have enougth voltage to work properly with your regulated input.
To correct this issue you should put two battery to get 7.5 volt on the regulated input.
Another solution is using 3.3v input to pass trought the regulator.

Yes!! this is what was happening!

If your battery is fully charged it’ll supply abount 4.2V.
The ESP should be able to handle up to 4.7V fine (according to this forum post), except that it’ll draw more current. So there’s no immediate need to go through the regulator.
If you’re battery-powering and want to use deep sleep, also consider using a different regulator with a lower quiescent current (e.g. MCP1702), otherwise the AMS1117 is already drawing at least 4mA.
Blinking and non-operation of the ESP is a sign for errors during boot, e.g. causing boot loops, typically caused by unstable power-supply, e.g. insufficient voltage or that the power supply cannot fulfill the peak current requirements (abount 200mA for the ESP).
My suggestion to be failsafe: just connect two batteries is series (7.4V nominal) and go through a 3.3V regulator.

ESP8266 require 3.3v input.  Some boards require 5V (from USB) and have regulators on.  How do you know that supplying 3.7v to Vin will work?
As to the high power consumption I would suspect it might be the WIFI transmitting.

The NodeMCU have a regulator built in (the NCP1117) and It has a minimum input voltage of 3.5V. Anyway I'm going to try with another battery because it could be voltage drop when the ESP8266 tries to communicate through WiFi

@rdiaz82: all my nodeMCUs have an AMS117, which wants 4.75v min. less==instability

I am sure my NodeMCU requires 5V power, not 3.7V, and the high power consumption is related to Wifi - a notoriously high user of power!
This is why many battery driven ESP8266 related projects contain sleep mode stuff, to attempt to significantly reduce power consumption.

For the deep sleep problem maybe you should try with lower time value such as 10 second for example. For me it's a problem with the duration .
I've never seen this kind of problem on my project but try with lower value and tell me what you got !

Yes! 15 minutes in production, in test I'm using 1 minute xD

Why have you added a second answer, when you could have edited and updated your existing answer?

The vin pin will work with anything above 5v as it goes via ams1117 to drop it to 3.3, to provide 3.3v directly connect to pin which says 3v directly on nodemcu lolin board

It's actually not 5v, though 5v is sufficient; but the point you are making has already been made several times.  How does your answer improve on those of nearly three months ago?


text:
Why Liquid crystal display doesn't give output in code below?
I've been working on project for children showing the codes used by atc transponder. I've used a keypad and a 16×2 display , where user types a 4 digit code and display shows condition related to the code
E.g. typing 7500 on keypad will show hijack on display
What has went wrong??
My code is ------
    #include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(8, 9, 10, 11, 12, 13);//RS,EN,D4,D5,D6,D7
#include <Keypad.h>//header for keypad commands enabling
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Three columns
// Define the Keymap
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'#','0','*','D'}
};
// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = { 0, 1, 2, 3 };
// Connect keypad COL0, COL1 and COL2 to these Arduino pins.
byte colPins[COLS] = { 4, 5, 6, 7 };
//  Create the Keypad
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

char inputArray[4]; //array to gather user keypad presses
char Vfr[4] = {'1','2','0','0'}; //array to hold keypad password
char Gliders[4] = {'1','2','0','2'};
char Hijack[4] = {'7','5','0','0'};
char Comfail[4] = {'7','6','0','0'};
char Emerg[4] = {'7','7','0','0'};
char Mic[4] = {'7','7','7','7'};

int i = 0;
int state = 1;

void setup()
{
  for(int k=8;k<14;k++)
  {
    pinMode(k,OUTPUT);//pins 8-14 are enabled as output
  }
  lcd.begin(16, 2);//initializing LCD
}

void loop()
{
while (state = 1);
{
 lcd.setCursor(0, 0);

 char key = kpd.getKey();

 //if a key is presseds
   if(key)
     {

     inputArray[i] = key; //store entry into array
     i++;
     lcd.clear(); //print keypad character entry to serial port

     if (key=='C');
       {
         lcd.setCursor(0, 1);
         lcd.print("Reset");
         i=0; //reset i
       }

     if (i == 4) //if 4 presses have been made
       {
         {

         //match input array to password array

           if (inputArray[0] == Vfr[0] &&
           inputArray[1] == Vfr[1] &&
           inputArray[2] == Vfr[2] &&
           inputArray[3] == Vfr[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("VFR");
              }
         }

         {

         //match input array to password array

           if (inputArray[0] == Gliders[0] &&
           inputArray[1] == Gliders[1] &&
           inputArray[2] == Gliders[2] &&
           inputArray[3] == Gliders[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("GLIDERS");
              }
         }

         {

         //match input array to password array

           if (inputArray[0] == Hijack[0] &&
           inputArray[1] == Hijack[1] &&
           inputArray[2] == Hijack[2] &&
           inputArray[3] == Hijack[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("HIJACK");
              }
         }

         {

         //match input array to password array

           if (inputArray[0] == Comfail[0] &&
           inputArray[1] == Comfail[1] &&
           inputArray[2] == Comfail[2] &&
           inputArray[3] == Comfail[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("COMMFAIL");
              }
         }

         {

         //match input array to password array

           if (inputArray[0] == Emerg[0] &&
           inputArray[1] == Emerg[1] &&
           inputArray[2] == Emerg[2] &&
           inputArray[3] == Emerg[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("EMERGENCY!");
              }
         }

         {

         //match input array to password array

           if (inputArray[0] == Emerg[0] &&
           inputArray[1] == Emerg[1] &&
           inputArray[2] == Emerg[2] &&
           inputArray[3] == Emerg[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("EMERGENCY!");
              }
         }

         {

         //match input array to password array

           if (inputArray[0] == Mic[0] &&
           inputArray[1] == Mic[1] &&
           inputArray[2] == Mic[2] &&
           inputArray[3] == Mic[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("MILITARY IC");
              }
         }
       }
}
lcd.print(key);
}
}

while (state = 1);

This line is a loop that will go around forever so long as you can set the variable state to 1.  What you mean is:
while (state == 1)

You don't need semicolons at the end of conditionals, here is another:
 if (key=='C');

If you fix those two bugs, you'll get a lot further.

Thank you I tried  and now display seems to give some output but it's some weird character

The keys I'm typing on keypad are appearing on same cursor position ?????

You aren't incrementing the cursor position manually so have you initialised the LCD so it increments the cursor position?

How can I do it?

You'll need to read the command from the manual for your display, you haven't stated the make and model, so  can't help.  They are usually very easy to find.  Or lcd.setCursor(0,x++);

should I define x as int? From 0 to 16 right??

I tried-- for (int x=0; x<17;x++) lcd.setCursor(0,x++); and it did the same except changed my cursor position to (0,1) and still numbers are being typed on same position

I guess it has to do something with my array?


text:
Arduino nano clone problem with interrupt on falling edge on pin 2
I've s 1Hz square wave coming from a DS1307 SQW/OUT pin going into pin2 on the Nano that is set up as input with internal pullup enabled.
I've set up the interrupt on falling edge but I can't get the ISR to execute every second (it's not executing at all). If I wire up a button normally open to ground pin2 and I press and hold it down I can get the ISR to execute.
Where's the problem:

Is the DS1307 not grounding fast enough for the falling edge logic to
pick it up ?
Is the internal pullup resistance on pin2 too high for the square
wave to be picked up (tension on pin2 is never high enough to trigger
a falling/rising edge event) ?
Is 1Hz too fast for the internal falling/rising edge logic to trigger the
event ?
Have I done something else wrong ?
Is it a problem on the clone only ?

This is a snippet of the code to get an idea of what I'm trying to do:

    void rtc_setCG(byte val);
    const byte rtc_id = 0x68; //DS1307 i2c id: 0x68h, 104 dec, 150 octal, 1101000b
    pinMode(2, INPUT_PULLUP);
    attachInterrupt (digitalPinToInterrupt(2), rtcout_int, FALLING);
void rtcout_int ()
{ char buf[5] = "    ";
  time_t now;
  struct tm *ts;

  wdt_reset();
  noInterrupts();
  epoque++; //this is a global volatile unsigned long variable that holds the number of seconds since the arduino epoque
  interrupts();
}
void rtc_setCG(byte val)
{ Wire.beginTransmission(rtc_id);
  Wire.write((byte)0x07);
  Wire.write(val);
  Wire.endTransmission();
}
ISR (TIMER1_COMPA_vect)
{ byte nsecond;
  nsecond=(byte)((millis()/1000) % 60);
  if ( nsecond != second )
  { second=nsecond;
    epoque++;
    minute=(byte)((epoque / 60) % 60);
    hour=(byte)(((epoque / 3600) + timezone) % 24);
  }
}
rtc_setCG(0x10); //this is how I set up the ds1307 to do 1hz on the SQW/OUT

I've put a speaker on the SQW/OUT and I can hear it click so the DS1307 is set up right for what I'm trying to do but I can't get the ISR to execute on the falling edge. I tried plying with rising edge or change but made no difference.

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

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets. Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem. Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant. Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem

The full code and or snippets  is not possible because I've since then worked around the problem by using the 1Hz from the RTC to do other stuff.


text:
WDT and RadioHead with delay()
The core I use is this one
The chip I use is an ATtiny85
I run this using the Arduino IDE 1.8.2
RadioHead ASK library (slimmed down)
What I want to do is:

deep sleep
wake up every minute
turn on sensor
take measurement
transmit data
back to sleep

This works when I test it seperatly, where it goes awry is when I combine RadioHead with WDT and then try to use a delay. This always hangs.
Probably a timer issue, I am looking for a work around.
I need the delay because I need to start the sensor, wait .5 sec and then take a measurement. Maybe I should give the ATtiny85 just some job to keep it busy for 0.5 sec?
This is working code, when I uncomment //  driver.init(); it will fail.
// RadioHead ASK
#include <RH_ASK.h>

// Sleep
#include <avr/sleep.h>
#include <avr/wdt.h>

#ifndef cbi
  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

// Absolute reference PB to overcome inter-IDE issues
#define T_PIN 1 // transmission
#define L_PIN 3 // optional LED pin
#define S1 A2
#define S2 A1
#define BAUD 2000

// Baud rate, receiver, transmitter
RH_ASK driver(BAUD, 9, T_PIN); // pin 9 is non existent

// Watchdog
volatile boolean f_wdt = 1;

ISR(WDT_vect) {
  f_wdt=1;
}

// Sleep
void system_sleep() {
  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out
  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

// Setup for Watchdog
void setup_watchdog(int ii) {
  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

void setup() {
//  driver.init();
  setup_watchdog(8);
}

void loop()
{
  if (f_wdt==1) {
    pinMode(0, OUTPUT);
    digitalWrite(0, HIGH);
    delay(500);
    digitalWrite(0, LOW);
    delay(500);
    system_sleep();
  }
}

The instruction bb|= (1<<WDCE) looks wrong: in the timed sequence, you are always writing this bit to one. The datasheet says (emphasis mine): “2. Within the next four clock cycles, in the same operation, write the WDE and WDP bits as desired, but with the WDCE bit cleared”. I would do something like cli(); WDTCR = _BV(WDCE) | _BV(WDE); WDTCR = _BV(WDIE) | _BV(WDP3); sei();.

I do not understand this part of the code well enough to understand your suggestion.  I need to read up on it.

The RH_ASK library uses timer0, which is also used for millis and delay.
Quick workaround is to use the standard AVR delay instead.
#include <util/delay.h>

...

_delay_ms(500)

This point needs to be made in big bold red letters in the RadioHead documentation.  Many hours were spent {wasted?} trying to debug the issue. +1


text:
Syntax for declaring more than one serial pins of Arduino mega?
How can I declare multiple serial ports for Arduino Mega as it has been in the example below?
#include <SoftwareSerial.h>
SoftwareSerial mySerial(18,19); // RX, TX  //how this syntax can be modified for multiple Rx module?

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

void loop(){
   Serial.write(45);    // send a byte with the value 45

   int bytesSent = Serial.write(â€œhelloâ€); //send the string â€œhelloâ€ and return the length of the string.
}

The Mega has four UARTs. Why are you using SoftwareSerial?

@IgnacioVazquez-Abrams..... But how i can access four Softwareserial for Arduino mega?like syntax for single serial port is as,                 SoftwareSerial mySerial(18,19); // RX, TX

@Code Gorilla    But how i can access four Softwareserial for Arduino mega?like syntax for single serial port is as, SoftwareSerial mySerial(18,19); // RX, TX – Hafeez Ahmad Fii Zue 2 mins ago    edit

If you mean the built in serial ports then just user the other objects that are pre-declared as per:
https://www.arduino.cc/en/Serial/Begin

From the official docs on serial:

The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18 (TX), Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX).

Which means, you use Serial1 for serial on pins 19 and 18 instead of Serial:
void setup(){
   Serial1.begin(9600);
}

void loop(){
   Serial1.write(45);    // send a byte with the value 45

   int bytesSent = Serial1.write("hello"); //send the string "hello" and return the length of the string.
}

what will be the syntax for serial two and three if it is "SoftwareSerial mySerial(18,19)" for serial 1

Isn't is obvious? Did you read the quoted text?

how can we access more than two Softwareserial?

Why do you need software serials if you have 4 hardware serials?

can i share you the complete code so that you can amend it easily?  i need yours email id?


text:
Arduino serial port implementation
It might be an obvious answer to this, but I can't find it via a quick google search. To give my question a bit of more context, I'm writing an application which simulates a communication with Arduino via serial port, therefore I need to know how it is implemented internally.
From my previous experience with micro-controllers, the serial port is normally presented in micro-controller as two separate queues, one for TX and another for RX. For transmit out of MC, my software writes a byte to the end of transmit queue, and MC hardware reads byte from the beginning of the queue, converts it to bits, and toggles the pin to transmit data/parity/stop bits. And it keep doing that until queue is exhausted. The opposite happens for receive queue.
Am I right in assuming that Arduino has similar implementation with two separate queues? In particular, I want to read and write to serial port simultaneously.

It depends on which Arduino and which serial port you are talking about. It can be a raw UART (TX and RX pins), an UART tunneled through USB by another chip (e.g. in the Uno communicating with the host computer), or a completely virtual UART seen through USB (e.g. in the Leonardo).

but to answer the question, there are two separate buffers, the arduino can only read or write at a time, but the hardware side can be treated as being full duplex with separate buffers.

The AVR UART has a simple one step hardware queue for both the RX and the TX. The hardware has a register for the parallel to serial conversion and a queue register to allow write/read while a transmit/receive is in progress. The Arduino HardwareSerial class adds a software queue (32 or 64 bytes). These buffers are used to feed the hardware queues on interrupts from the UART hardware module.

Please do not cross-post the same question on different Stack Exchange sites. See Is cross-posting a question on multiple Stack Exchange sites permitted if the question is on-topic for each site?.

Yes. Arduino has two buffers. See the HardwareSerial.h and HardwareSerial.cpp

I have a lengthy post about Arduino serial communications: How does serial communications work on the Arduino?
In short, the hardware (on an Atmega328 like on the Uno) has a two-byte receive queue (so you can be putting one byte into memory while the next byte is being received). It has a one-byte send queue.
Lengthier queues are implemented in software using interrupts to move data from the RAM queues in/out of the hardware queues.


text:
Switch to drive Arduino and optocoupler
At the moment I have a switch that connects to a digital pin on an Arduino as per the schematic below.  (Obviously there is an pull-up resistor on the pin).

simulate this circuit – Schematic created using CircuitLab
I now want this switch to also connect to another Arduino via an optocoupler. Is it as simple as just adding the optocoupler between the switch and ground with the necessary resistor for it?

Is it as simple as just adding the optocoupler between the switch and ground with the necessary resistor for it?

Probably not, because of two issues.  First, adding circuit elements between the switch and ground raises the voltage the pin will see when the switch is closed, which might keep a switch closure from registering as a low pin voltage.  For example, with Vcc=5V, table 30.2 DC Characteristics in the Rev. 8271J 11/2015 ATmega328P datasheet shows the guaranteed maximum input low voltage as 0.3 Vcc and the guaranteed minimum input high voltage as 0.6 Vcc; that is, 1.5 V and 3 V if Vcc=5V.  If the voltage drop across the optocoupler is between 1.5 and 3 V then the pin might register high or low with no guarantee which.
Second, if the pullup is large, not enough current will flow to trigger the optocoupler.  For example, at Vcc=5V if the internal pullup is used and the optocoupler drops two volts, I/O Pin Pull-up Resistor Current will be about 80 μA, too little to trigger a typical optocoupler.  (See figure  35-17, ATmega328P: I/O Pin Pull-up Resistor Current vs. Input Voltage (Vcc = 5V) in datasheet.)
What you might do instead is use two optocoupler channels in parallel or series, one for each of the Arduinos.  The switch lets current pass through an appropriate resistor or resistors and the optocoupler inputs;  optocoupler outputs go to  Arduino inputs.
Or, tie one side of the switch to +5V and the other to a resistor in series with an optocoupler input.  Connect the first Arduino's input pin to the low side of the switch.  I think that input will register low when the switch is open.  It will register high when the switch is closed.


text:
Arduino Zero - Stepper control (interrupt)?
I have a stepper controller board that I need to pulse every 40 uS or so.
I also have I2C sensors and Serial writes to preform.
Currently I run an update call in a tight loop, but the I2C sensors and Serial writes cause considerable delays which makes the motors stutter and come to a halt.
I would like to use an ISR to call the motor update method periodically.
However I cannot for the life of me figure this timer stuff out.
Here's my current attempt:

void TC4_Handler() {
  Stepper::updateAll();
}

void setup() {

  // Timer stuff
  // Set up the generic clock (GCLK4) used to clock timers
  REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                    GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                     GCLK_GENCTRL_GENEN |         // Enable GCLK4
                     GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                     GCLK_GENCTRL_ID(4);          // Select GCLK4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  // Feed GCLK4 to TC4 and TC5
  REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                     GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                     GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_TC4_COUNT16_CC0 = 0x000F;                      // Set the TC4 CC0 register as the TOP value in match frequency mode
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

  //NVIC_DisableIRQ(TC4_IRQn);
  //NVIC_ClearPendingIRQ(TC4_IRQn);
  NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
  NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

  REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
  REG_TC4_INTENSET = TC_INTENSET_OVF;             // Enable TC4 interrupts
  // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

  REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV1024 |   // Set prescaler to 1024, 48MHz/1024 = 46.875kHz
                   TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                   TC_CTRLA_ENABLE;               // Enable TC4
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization
  // ...
}

As Stepper::updateAll(); isn't shown I don't know what it does.  For accurate timing it would make sense to use hardware-operated output-compare output pins like TIOAx and TIOBx, instead of running some code to drive the pins when an interrupt occurs.
If you need to control several wires per motor – such that a pulse on a single output line isn't enough – you might consider using a 74HC595 (or other shift register) to transfer the bits.  Thus, each time an output compare occurs, the  TIOAx and TIOBx line would pulse the ST_CLK (store-clock) line of the SR, to transfer bits from the shift chain flipflops to the output flipflops; then, at its leisure the interrupt routine can shift the next set of bits out to the '595, ready to be transferred at the correct moment, when the next output compare occurs.
During stepper acceleration or deceleration, the timer count-limit would also need to be updated within the ISR.

I'm using this driver https://www.pololu.com/product/2975, all Stepper::updateAll() does is to check if the step pin needs to be pulsed.

In that case, you should use a TIOAx or TIOBx line to pulse the A4988, and should calculate timer count-limits for the ISR to set.  In other words, don't “check if the step pin needs to be pulsed” – which amounts to trying to run the stepper using polling, which is a bad idea – but instead calculate when the step pin needs to be pulsed, set timer accordingly, and have the timer pulse the A4988.