text:
analogRead() takes >400 us on Arduino Zero but ~100 us on Uno, why?
I've been trying to figure out why the analogRead() function takes about four times as long on an Arduino Zero than on an Uno, when the Zero has a faster clock than the Uno.  Arduinos website says that it should take around 100 microseconds, and it does on the Uno, but it takes a little over 400 microseconds on the Zero. To time it, I've been setting a digital pin high immediately before the function call and low immediately after and measuring the period on a digital osscilloscope.  I'm just trying to test analogRead, so I'm not doing anything else in this code.  I've tried putting the ADC in freerun mode, and it trims ~15 us off of the ~415 us it currently takes.  I've also used the on-chip debugger to look at the disassembly, and the line that takes too long is always the line waiting for the conversion to complete.  I was also wondering if other ARM-based Arduinos (like the Zero) take over 100 us.  Thanks!
int   sensorPin = A1;
int      ledPin = 11;
int sensorValue = 0;

void setup() {
  analogReadResolution(12);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  digitalWrite(ledPin,HIGH);
  sensorValue = analogRead(sensorPin);
  digitalWrite(ledPin,LOW);
}

Do you have a code used for these measures?

Sorry, meant to post this the first time.
 `int sensorPin = A1;
 int ledPin = 11;
 int sensorValue = 0;

 void setup() {
     analogReadResolution(12);
     pinMode(ledPin, OUTPUT);
 }

 void loop() {
     digitalWrite(ledPin,HIGH);
     sensorValue = analogRead(sensorPin);
     digitalWrite(ledPin,LOW);
 }`

You might consult the data sheets for the two MCUs particularly the number of peripheral clocks to perform a conversion in a given mode and see if what you are measuring seems consistent.

@hiitsali, thank you for mentioning this. I suppose there is no solution for this yet ? I did some tests with the Arduino functions and the Arduino M0 is 3 to 7 times faster. The pinMode() takes 2µs, that is only 2 times faster. The analogRead() takes 422µs which is 4 times slower. I don't want to use interrupts for the ADC, so I have to keep in mind that it is very slow when using the average with many samples.

Arduino is universal platform, lot of wrappers to hide real hardware and it is slow. For example digital write is about 100times slower than direct access to hardware.
For example for AVR Mega328p based Arduino analogRead looks like (without macros):
int analogRead(uint8_t pin)
{
    uint8_t low, high;

    if (pin >= 14) pin -= 14; // allow for channel or pin numbers

    // set the analog reference (high two bits of ADMUX) and select the
    // channel (low 4 bits).  this also sets ADLAR (left-adjust result)
    // to 0 (the default).
    ADMUX = (analog_reference << 6) | (pin & 0x07);

    // start the conversion
    sbi(ADCSRA, ADSC);

    // ADSC is cleared when the conversion finishes
    while (bit_is_set(ADCSRA, ADSC));

    // we have to read ADCL first; doing so locks both ADCL
    // and ADCH until ADCH is read.  reading ADCL second would
    // cause the results of each conversion to be discarded,
    // as ADCL and ADCH would be locked when it completed.
    low  = ADCL;
    high = ADCH;

    // combine the two bytes
    return (high << 8) | low;
}

There are no extra function calls, no much extra actions and ADC is enabled in the startup code (as most of hw).
On the other side there is ARM based arduino with SAM3X8E:
uint32_t analogRead(uint32_t ulPin)
{
    uint32_t ulValue = 0;
    uint32_t ulChannel;

    if (ulPin < A0)
      ulPin += A0;

    ulChannel = g_APinDescription[ulPin].ulADCChannelNumber ;

    static uint32_t latestSelectedChannel = -1;
    switch ( g_APinDescription[ulPin].ulAnalogChannel )
    {
        // Handling ADC 12 bits channels
        case ADC0 :
        case ADC1 :
        case ADC2 :
        case ADC3 :
        case ADC4 :
        case ADC5 :
        case ADC6 :
        case ADC7 :
        case ADC8 :
        case ADC9 :
        case ADC10 :
        case ADC11 :

            // Enable the corresponding channel
            if (adc_get_channel_status(ADC, ulChannel) != 1) {
                adc_enable_channel( ADC, ulChannel );
                if ( latestSelectedChannel != (uint32_t)-1 && ulChannel != latestSelectedChannel)
                    adc_disable_channel( ADC, latestSelectedChannel );
                latestSelectedChannel = ulChannel;
                g_pinStatus[ulPin] = (g_pinStatus[ulPin] & 0xF0) | PIN_STATUS_ANALOG;
            }

            // Start the ADC
            adc_start( ADC );

            // Wait for end of conversion
            while ((adc_get_status(ADC) & ADC_ISR_DRDY) != ADC_ISR_DRDY)
                ;

            // Read the value
            ulValue = adc_get_latest_value(ADC);
            ulValue = mapResolution(ulValue, ADC_RESOLUTION, _readResolution);

            break;

        // Compiler could yell because we don't handle DAC pins
        default :
            ulValue=0;
            break;
    }

    return ulValue;
}

As you can see there is little bit more actions to do single measure using HAL (Hardware Abstraction Level) so you have another level of abstraction here.
If you want faster actions, you can access hw directly, or use HAL and skip unnecessary steps. It would be much faster then.

Thanks, I've actually tried this already.  It shaves off some time, but it's still slower than the time cited by the datasheet (100 microseconds) on the Zero.  On the Uno this helps get it under that, but I don't understand why the baseline time of the Zero is so much longer.  I've spent quite a while looking at the C files and the disassembly.  On the zero, in the disassembly, it's always the line that's waiting for the flag indicating that the conversion is done that takes a long time

@hiitsali abviously the waiting for the result would take more time as the setting up (if done efficiently). Is the problem that you'll have to wait, or that it simply takes too long? You can try setting the ADC to do less samples and/or lower accuracy, that may improve speed. Otherwise, you can implement an interrupt when ADC is complete, so you're not waiting for the ADC (it's not faster, but more efficient).

Code abstraction is not the issue for something already relatively slow like that.  Rather the issue would be the actual time required for a conversion with the configured ADC clock and mode.


text:
Atmega328p clock and safe operation zone
im not used to write in english but i hope you guys can understand. I have some doubts about using the arduino pro mini 3v3@8Mhz

I know its possible to change the clock to 1 MHz with the fuses easily by setting CKDIV8 to '0'. But i dont understand if its possible to divide the internal 8 MHz clock to intermediate values like 4 MHz and 2 MHz.
I know i can divide the clock with program running. The problem is i would like to run the arduino with a voltage less than 2,4V and arduino will start at 8MHz(out of safe operation area) for later change the clock to 4MHz(inside of safe operation area). Is there another way by software to always be in the safe zone ?

Just let CKDIV8 set (it just sets system clock prescaler to /8). And you can set different system clock prescaler later.
For changing system clock prescaler you need:
#include <avr/power.h>

And:
clock_prescale_set(clock_div_2); // possible values are clock_div_1 ... clock_div_256

Just don't forget that millis, delays and basically everything based on F_CPU might be slower/faster when prescaler gets changed.

source: Stack Exchange

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

sort: votes


text:
creating object of another class when initializing an object of a class
Here's what I want to achieve:
I'm building a class for controlling step motors. In that class I want to have a method called "init". In that method I'd like to create an object of class Tone, which I'll need to control a motor.
BUT I want to have seperate Tone class object for every object of my class that I create. How can I do it?
So, for exmaple, if I have:
myClass newmotor1;
memotor1.init();

After executing these two lines, I'd like to have my object newmotor1 (which I have, because I just created it) AND an object of class Tone, which I'll use.

Why do you want to create it in the init function? Why not just have one in the class already?

But I want to have seperate Tone objects for each object of my class

And? What difference does that make?

To be honest, I'm not sure what you mean. I'm actually new to classes, objects and all that stuff. Could you explan?

You use a class just like any other variable. Just use it in your class like any other variable.

I think I understand now, that's a good idea. I've been learning C# recently for my work, I wonder if it could be done in C# too (I'm not talking Arduino at all now, I'm just curious if similiar thing could be applied to C# program)

No idea. I have never used that inferior language ;)

Oh come on, I think it's quite good.

You don't need to "create" anything. Just have an object in your class:
class Tone {
    public:
        void dosomething() {
            // Whatever is in here
        }
};

class MyMotor {
    public:
        Tone tone;
        void init() {
            // Nothing much else to do in here now.
        }
};

You then:
MyMotor newmotor1;

And you can access:
newmotor1.tone.dosomething();

That's a perfect solution. Thanks Majenko!

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


text:
can i configure 2 (XBee series 2) modules using one explorer
Can I configure 2 XBEE modules one then another using 1 XBEE Explorer, or I MUST do this configuration operation for them at the same time and I need 2 Explorer modules?

You only need one.
In order to communicate in Point To Point, you must configure each xbee to belong to the same NetworkID (PAN ID). XBees can only communicate with each other if they have the same network ID. Configure one, switch the xbee then configure the other (see here)
There are more advanced configurations that you can use (check this tutorial for extended information).

thank you, it's the same if i'll do star or mesh right?.                  I have another question can I send information from 2 sources to one destination .. or xbee is only for broadcasting?

I've never tested it, but yes it is possible according to manual in multicast(see page 74 example 4). Just remember that star must have only one coordinator. take a look here also: http://jeffbelback.me/projects/2014/09/17/XbeeDeviceTypes/

thanks again.  I have another new question, I was test the communicating of the 2 XBEEs series 2, and I connected one to the computer and the other to the arduino... but while running a code to send hello world msg from arduino, it doesn't appear in the XBee XTC console.. what should I do?

You don't see anything? Have you set the same PAN ID right? Correct baudrates also?


text:
Doorbell for someone with hearing issues
I have an Arduino Uno with the basic kit, not very good at coding it however.
How could I make a doorbell that lights up an LED instead of making a noise?
I'm trying to make a doorbell for someone with hearing issues.
A simple LED lighting up would be more than enough. Would I need a wifi shield if it's not close enough to be hard wired?
Thanks

I know you are keen on using your Arduino.  But simpler solutions abound.  For instance, if the door bell already works at a lower then main voltage it might be easier to determine the feasibility of connecting a low voltage lamp to the door bell.
However, I can see a situation that an Arduino can fit very nicely into:
Events: 1) The door bell rings. 2) The Arduino senses this and starts turning on and off a room light at about 5 second intervals. 3) This can last until someone notices and resets the Arduino.  4) If no one is home to reset the Arduino, the Arduino stops turning on and off the room light after a minute passes (12 flashes).
There are 2 tricky bits that may need explaining.  The first is how to sense the door bell.  If mechanical you could use a micro switch:

That way you don't need to worry about isolating the Arduino from what is likely a strong electrically noisy solenoid.  The other tricky bit is controlling a room light.  I would suggest using a COTS remote controllable light switch (I just did a search and there are loads of them in every price range) and hack the (battery powered) remote control into the Arduino.

If you must do wireless, you can get by with a 433MHz rx+tx module. Be sure to align both antennas either vertically or horizontally. These modules kind of need two MCUs though, but clones are cheap. Personally I would add a small switch underneath the doorbell button, but separate from its circuitry. Debounce it. On the receiving end you need a good set of LEDs - iphone has a very annoying but attention-grabbing light pulse for people hard of hearing. You can see it on youtube. I would copy that pulse timing and intensity as closely as possible, thus infringing on Apple's no doubt copyrighted+patented 'technology'. Be a pirate, arrr!


text:
Arduino: Reading PPM values from MQ-131 Ozone sensor
I have this sensor MQ131 by sainsmart: https://www.amazon.co.uk/gp/product/B00NL8XIQG/ref=ox_sc_act_title_1?ie=UTF8&psc=1&smid=A3DRI1TTHCTDIG
All I can read is the analog value which does not reflect the gas concentration. Any Arduino code for that to read the ppm concentration?
How long does the sensor needs to be preheated?

First you need t make it burn for 24hrs mini (48 advised). Just plug it and wait. Then for calibration you need a reference atmosphere free of NOx, CL2 and O3. In this reference atmosphere you should get an output value of 0.
I don't know this model you bought exactly, but most of these gas sensors mounted on a PCB have a mini eeprom so the output is the actual PPM concentration. Note that these sensors are not able to tell you how much of which gas is detected, but only a ppm concentration (you then have to guess which one is in the air). If you have several of these gas in the air, you will not be able to tell their concentration with such a sensor.

Can yuou suggest anyone that can give directly the ppm values instead of just struggling with the interfacing of this model I got from Amazon? @Vincent

this model is giving the ppm after calibration, but the ppm of all these gases together. For example if you have 100ppm CL2 and 200ppm O3, you'll read 300ppm on your arduino. If you want a sensor which will give you the ppm of only one gas, it will cost you much much more.

According to the picture, the sensor is a Winsen MQ131 low concentration (black bakelite version). You can have additional information on the sensor in the datasheet.
Your sensor is mounted on a PCB with some features like converting values (analog to digital), controlling the heater, maybe providing I2C bus... Without any additional information, it's difficult to give guidance on your module (the Amazon link doesn't mention any datasheet for the module).
In order to use your sensor, you can connect it directly on the sensor and pilot it by yourself. You can find some code on GitHub (for inspiration or fork).

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


text:
Problems with Powering Led Project Through Vin Pin
I am working on lighting some WS2812 Leds with a nodemcu form hiLetgo. The project works when it is powered from the usb that is on the board, but as soon as it is powered from the barrel jack, the leds will only light up to the last color that they were set, ignoring code. A schematic and code are included for reference.
#include <ESP8266WiFi.h>
#include <Adafruit_NeoPixel.h>

// Which pin on the ESP8266 is connected to the NeoPixels?
#define PIN            D8

// How many NeoPixels are attached to the ESP8266?
#define NUMPIXELS      30

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int delayval = 10; // delay for half a second
int x, y, z;

void setup() {
  // put your setup code here, to run once:
  pixels.begin(); // This initializes the NeoPixel library.
  x = 0;
  y = 0;
  z = 0;
}

void loop() {
  // put your main code here, to run repeatedly:
   for(int i=0;i<NUMPIXELS;i++){
    x = (x+1)%256;
    // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255

    pixels.setPixelColor(i, pixels.Color(x,y,z)); // Moderately bright green color.

    pixels.show(); // This sends the updated pixel color to the hardware.

    delay(delayval); // Delay for a period of time (in milliseconds).

  }
  y= (y+1)%256;

}

can you confirm that the code is actually running when powered from  barrel jack

I have tested it with other code that shows that the code runs when powered form the barrel jack.

What voltage are you providing through the barrel jack?

5v according to the power brick, but according to my multi it's more like 5.2 - 5.3v. Also, it is rated at 3a.

First: What is the purpose of that resistor you have in there? It serves no purpose as far as I can see, and would only cause problems anyway. Lose it.
Second: You have logic voltage level problems:

You are supplying 5.2V to the LEDs.
The ESP8266 is a 3.3V device.
The ESP8266 outputs 3.3V as a logic HIGH.
The WS2812 accepts 0.7Vdd as logic HIGH (as stated in the datasheet).
0.7 × 5.2 = 3.64v

Ergo, the LEDs aren't seeing the logic HIGH signal as logic HIGH because it is too low a voltage.
Add to that the voltage drop across the resistor and your logic HIGH voltage will be even less.
So:

Lose the pointless resistor
Either reduce the supply voltage to the LEDs or increase the output HIGH voltage level with a logic level shifter circuit (3.3v -> 5v).

According to Sparkfun (https://learn.sparkfun.com/tutorials/ws2812-breakout-hookup-guide) it is important to use the resistor to protect the data pin.

@user3242816 They're talking gibberish. Protect it from what?!

My assumption was from excessive current draw, but I'm relatively new to the hardware side of electronics.

The only effect you would see from that resistor is a slight voltage drop and a low-pass filter formed with the input capacitance of the data pin that limits the maximum frequency you could use. There is nothing to draw excess current, since there is no fan-out, only a 1:1 connection from a low-impedance output to a high impedance input.

Interesting. I gave bypassing the resistor with a piece of wire a shot and now it works. Thank you for your advice!


text:
Changing Uid Using MFRC522 Via Arduino Error
Well, I' ve just bought and recieved a MFRC522 rfıd module and done to much research on it. After watching several videos, I sorted out a library for using this module via arduino.
You can click the first link below to be navigated to Miguel Balboa' s github page including the library that I mentioned and example codes written by him using that library. Though I' ve downloaded the zip file, ran such codes as dumpInfo, read and write, unfortunetely I couldn' t made "changeUid" example work. U can reach this example code via the link below as well. My connection is true, I' m sure bout' that  If anybody had faced this kind of problem or knows the solution, their answers will be enough satisfying for me I guess... (By the way, error was this sentance: Are you sure this is a uid changeable card -I was sure, my card was a Mifare 1K card- failure, the card responded as NAK)
link: https://github.com/miguelbalboa/rfid

Search for UID changeable card. The kit included this RFID reader just had a normal RFID card and keychain. You will probably have to buy it yourself. I bought it from aliexpress but I don' t remember which seller. Good Luck! (I mean who read this...)


text:
How can I reduce the redundancy of this code, so one function can perform the task of printing on Serial and Softserial?
void Multi_print (String str)
{
  Serial.print(str);
  mySerial.print(str);
 }

void Multi_println (String str)
{
 Serial.println(str);
 mySerial.println(str);
}

void Multi_parse_int (int value)
 {
    Serial.print(value);
    mySerial.print(value);
 }

I can't tell what your goal is: One function to replace all three? The same three functions but printing on any one Serial instead of on both ones? Or something else?

Just send your data to a tee: this is a type of pipe fitting where you
push the data through one end and it goes out through the other two
ends. As it happens, both Serial and Softserial (and almost anything
that can print()) inherit from the virtual Print class. You can
implement a tee as a Print that outputs to two Prints:
class Tee : public Print
{
public:
    Tee(Print &_p1, Print &_p2)
    : p1(_p1), p2(_p2)
    {}

    size_t write(uint8_t c)
    {
        size_t count1 = p1.write(c);
        size_t count2 = p2.write(c);
        return min(count1, count2);
    }
private:
    Print &p1, &p2;
};

The write(uint8_t) is the only method you really need to implement to
have a working Print. Then, all the print() and println() methods
will work.
Example usage:
Tee dualSerial(Serial, mySerial);
dualSerial.print("The answer is ");
dualSerial.println(42);

Note that parseInt() will not work, as it is not a method from
Print. But if you think twice, you will realize that parseInt() on a
pair of channels just does not make sense.

Very nice solution to the question as asked. :)

LOL, while Edgar was busy answering your question, I posted a github implementation called NeoTee which will tee any number of streams.  I have occasionally wanted such a class (attached at the end).  He has explained the approach nicely.
One quirk of the Arduino Print and Stream classes is that the flush method is in Stream, not Print.  So to provide that method in the NeoTee class requires deriving from Stream.  But Stream requires that you implement read, available and peek.  Although available can return the sum of the characters available on all Streams, the usefulness of read and peek is functional, but dubious.  ;-)
One example sketch is available in the library.  For your sketch, you would declare something like this:
Stream *streams[2] = { &Serial, &mySerial };
NeoTee tee( streams, sizeof(streams)/sizeof(streams[0]) );

And used thusly:
tee.print( '!' ); // prints one character to both
tee.print( 123.45 ); // prints a floating-point number on both

NeoTee implementation:
#ifndef _NEOTEE_H_
#define _NEOTEE_H_

//------------------------------------------------------
// NeoTee
// Copyright (C) 2016, SlashDevin
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//

#include <Stream.h>

// This library is like the UNIX "tee" command, which splits an output stream
// into two streams, but with N branches.  On the Arduino, an output stream is
// instance of the Arduino Print class, and the flush method is in Stream.
//
// Simply declare your own array of streams:
//
//     Stream *streams[2];
//
// Pass the array and its size in to the NeoTee constructor:
//
//     NeoTee tee( streams, sizeof(streams)/sizeof(streams[0]) );
//
// Any Stream operation on "tee" will be duplicated on all Streams in the array.
//
//     tee.println( F("This is sent to all Stream instances in the array.") );
//
// Because there is no base class with "begin" and "end" methods, you
//   must call those explicitly on the individual Streams (e.g., Serial.begin)

class NeoTee : public Stream
{
  Stream **Streams;
  uint8_t  NumStreams;

public:

  NeoTee( Stream **streams, uint8_t numStreams )
    {
      Streams    = streams;
      NumStreams = numStreams;
    }

  virtual void flush()
    {
      for (uint8_t i=0; i<NumStreams; i++)
        Streams[i]->flush();
    }

  virtual size_t write(uint8_t c)
    {
      size_t minWritten = 0;
      for (uint8_t i=0; i<NumStreams; i++) {
        size_t written = Streams[i]->write( c );
        if ((i == 0) || (minWritten > written))
          minWritten = written;
      }
      return minWritten;
    }

  using Stream::write; // make the other overloads visible

  virtual int available()
    {
      int total = 0;
      for (uint8_t i=0; i<NumStreams; i++)
        total += Streams[i]->available();
      return total;
    }

  virtual int read()
    {
      for (uint8_t i=0; i<NumStreams; i++)
        if (Streams[i]->available())
          return Streams[i]->read();
      return -1;
    }

  virtual int peek()
    {
      for (uint8_t i=0; i<NumStreams; i++)
        if (Streams[i]->available())
          return Streams[i]->peek();
      return -1;
    }

};

#endif

Very nice solution to the more general problem. :)


text:
How do I Read and Write data from a USB stick?
Hello I have an Arduino Uno and I salvaged a USB port from an old computer. The USB port has 4 pins on it and it accepts USB sticks. I was wondering if it is possible to connect it to my Arduino so my Arduino can load data from files on the USB. I don't want to go out and buy a shield but I don't mind using libraries. Is it possible to read and write data from a USB stick with Arduino?

Usb OTG mass storage library. Good luck

Requires an USB Host Shield. The UNO can only work as device otherwise. Talking to a stick requires host role.

The Uno does not have any USB host or OTG capabilities on its own, and bit banging it is not easy. A USB Host shield, or a better microcontroller is needed.

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


text:
Why does servo library conflict with irremote?
I am building an Arduino Mega robot. I am planning to use IRremote.h library for it. I am using multiple libraries in my code and I do not know which timers are taken. I always get errors when compiling because I am using the wrong timer. Here are the libraries I am using:
#include <LiquidCrystal.h>
#include <Wire.h>
#include <RTClib.h>
#include <Servo.h>
#include <IRremote.h>

I get this error message when compiling:
libraries\IRremote\IRremote.cpp.o: In function `__vector_42':

C:\Users\Lyuba\Desktop\Nick\Arduino\libraries\IRremote/IRremote.cpp:339: multiple definition of `__vector_42'

libraries\Servo\avr\Servo.cpp.o:C:\Users\Lyuba\Desktop\Nick\Arduino\libraries\Servo\src\avr/Servo.cpp:95: first defined here

c:/users/lyuba/desktop/nick/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

Here is the code in the library where I can change the timers:
// Arduino Mega
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  //#define IR_USE_TIMER1   // tx = pin 11
  //#define IR_USE_TIMER2     // tx = pin 9
 // #define IR_USE_TIMER3   // tx = pin 5
  #define IR_USE_TIMER4   // tx = pin 6
  //#define IR_USE_TIMER5   // tx = pin 46

What can I do to use irremote library? Looking at the error message, the servo library conflicts with irremote. How can I fix this?

... Did you try another timer ?

@Joe I tried all of them. If I stop using tone() in my code, one of the timer works. But I want to use tone as well.

Usual problem is trying to use the same counter for both. For example arduino pins 6,7,8 are on TC4 and if you try to use IR on pin 6 and servo on 7 or 8, it won't work. You can't use pwms on these pins with servo either (it is possible to do it directly in registers, but in arduino framework it might get bad behavior)


text:
Receive sms on android phone without GSM module
I have done a simple project which measures CO gas in air.Now I want that sensor will measure the level of CO gas and sms will be received on android phone when the area is under danger zone.How to receive sms on android phone without GSM module?

You can do it with the power of prayer, or wishful thinking, or some kind of module. Take your pick.

There are exactly two ways of sending an SMS. Both of which require more than "just" an Arduino.

Directly using GSM - for which you NEED a GSM shield
Indirectly using an Internet Gateway - for which you NEED some form of internet connection.

Since you have an aversion to 1, 2 is your only option. So you require some extra hardware (unless you have an Arduino with built in WiFi or Ethernet) to connect your Arduino to the internet. Then you have to pay an SMS gateway provider to allow you to send SMS messages through them, and implement their API in the Arduino.
Also you need an internet connection available wherever the Arduino happens to be.
All in all a lot of work and you're really no better off than using a GSM shield.

He might not have GSM reception at the location of measurment. (Basement maybe)? But in order to send SMS message you will have to use GSM network sooner or later. From price perspective I would have to agree that WiFi shield will cost you back the same amount of money as GSM shield.

Alternative from price perspective:
Assuming that you have internet at the location of sensor (WiFi or cable) you can buy a RaspberryPi (revision 3 has already integrated WiFi and bluetooth). Using python code you can than send SMS message using some free SMS service provider if there are any in your country using their API.
If SMS notificaion is not critical, you can use RaspberryPi to send an email or some other sort of notification. Heck you can even create a Twitter profile for your sensor and call it Mr.Sensor and then post tweets with sensor values. Possibilities are endless, it all depends on your use case and available infrastructure.
I hope you will find something that will satisfy your needs :)


text:
How to volunteer for arduino projects?
I have master in electronics and IT. I know various microcontrollers programming in c. I want to volunteer myself to learn for arduino Projects especially for low Level Drivers etc. Can somebody suggest me Websites or way ?

You want to do what? Help other people, or get help from other people? It's unclear what you are asking for.

The Arduino paradigm is based on abstracting the hardware to a few simple function calls.  So many drivers appear simple to the end user (end programmer).
Most go here for a list of libraries (which have already been written) and how to use them.  I believe these libraries are distributed with the Arduino SDK.  To learn more about writing libraries go here. I am not aware of any formal method of submitting Arduino libraries.  If I wanted to find out more I would go here and participate in the forum.  However, using the forums search, I found this specific (several years old) post where it says:

You can add a page to the Playground section:
  http://playground.arduino.cc/ You might start by adding your website
  with Arduino code to the index of the playground, perhaps a page in
  the Playground section is not needed. The index can contain links to
  websites, to the Arduino forum or to a page in the Playground section.
You can not change or add to the reference or official libraries.

Most of the libraries to read sensors like as Dallas/Maxim 1Wire products, or to interface to RF-, WiFi-, and other radios are user-contributed and maintained, and most, if not all, of them are community maintained and on github.
Update:

Is there any official repository for arduino libraries where someone
  can contribute and submit patches?

"Official": I don't think so, at least I don't know of one if there is, but I am also just learning my way around the open sources.
But you'll probably find most of the libraries in github, and they are usually there to share development. They aren't generally grouped as "Arduino", but by each author's github username.
So the best approach is probably to identify the library in your "libraries" folder that you want to update, and its author's name which is usually in the source-code header comments. And, if you get lucky, a URL to the github project. Otherwise go to github and search for the library, using the author's name or a quick comparison of some the source code to be sure you've really found the same library.
(As I am a user & beneficiary of open source code, you have my sincere thanks for choosing to do this! I haven't gotten that far yet; I hope to, soon.)

can I contribute ? Is there any official repository for arduino libraries where someone can contribute and submit patches?


text:
Real Time Clock Module Reset
I just had a pretty simple question about the RTC Clock Modules, more specifically the DS3231 RTC. Once calibrated and running on my Arduino if I were to unplug it and plug it back in, will the time and everything reset and require another calibration, or will it work like a computer that, even when reset, retains the correct time and date. Thanks!

It depends if your module has a battery backup or not. A bare chip, by itself, will loose everything. That's why many breakout boards will have a small lithium cell on them to retain everything when the power is removed.

So it will be attatched to a breadboard and then attatched to the Arduino. If the main power supply to the Arduino, which is a external 5V battery source, you are saying it would be wise to also have another backup source just in case?

Like I said, it depends on your module. If you are building it from components, then yes you should provide a battery backup - like it shows you in the datasheet.

This is the module I will be using

That is what you have? Do you know what that big round silver thing is in the picture?

Brilliant. Sorry, long day. Thanks for the help.


text:
Can anyone recommend a breadboard for the new Arduino 101?
I just got an Arduino 101 board. I was told that it's practically the same as the UNO. But have no experience using the UNO and I've only done super simple things on the 101 board without using a bread board.
What I want to do is have 2 servos connect to the board. I've only connected one servo without using a breadboard. I've looked on Instructables.com and other places that connect at least 2 to up most 12 servos. They all use different breadboards without specify if the brand, model, or if size even matters. I don't know how breadboards work and which holes I plug the wires into. Furthermore, I haven't found any videos on people working on the 101 board.
Next, I'm not sure if the servos will share the same volt port. There's only 3V and 5V on my Arduino 101 board. If they all need 5V, I'm not sure how to make both servos share. I don't know how they will share the same ground port as well. I know for sure, they will have their own analog port.
A list of recommendations would be nice. Thanks.

Although you will find tutorials which unwisely do so, you really should not power servos from any sort of Arduino.  Servos are nasty motor loads, which should have their own supply that is not an Arduino or the computer that is connected to.  They they need a common ground with the Arduino and signal from it.

I personally prefer the big breadboards that have two sets of terminals for power at the top. The tiny boards tend to get claustrophobic for me. Should have bought one big to begin with instead of the ones that are supercompact. Good for tiny (chinese) fingers though ... I just unravelled a mystery.

@user400344 however (probably) unintentional Good for tiny (chinese) fingers though sounds a little racist (depending on how you view it).

@junerockwell Sparkfun has a pretty neat tutorial on breadboards (https://learn.sparkfun.com/tutorials/how-to-use-a-breadboard). But as Chris Stratton suggest, it's highly advised to separate power lines from control lines.

It's only a matter of personal preference. I am quite happy with the standard 830-point layout, but there are many larger and nicer models.

A breadboard is nothing but a way to attach multiple wires to the same pins. There are many different kinds as can be seen in these images. There's no right or wrong when it comes to breadboards, as long as you have enough pins to prototype you should be good to go.

I agree to "A breadboard is nothing but a way to attach multiple wires to the same pins.", but just one recommendation for the breadboard. Don't buy the ones without the rails for voltage and ground, they are useful.

authors: Кузьма Феськов


text:
Arduino SPI - MOSI not writing any data but clock works
I am trying to iterate over an int array and writing those values to a chip. Here is my code.
#include <SPI.h>

int sine[] = {0x7fc ,0x868 ,0x8d4 ,0x93c ,0x9a8 ,0xa10 ,0xa78 ,0xadc
,0xb3c ,0xba0 ,0xbfc ,0xc58 ,0xcb0 ,0xd04 ,0xd58 ,0xda4 ,0xdf0 ,0xe34 ,0xe74
,0xeb0 ,0xee8 ,0xf1c ,0xf4c ,0xf74 ,0xf98 ,0xfb8 ,0xfd0 ,0xfe4 ,0xff0 ,0xff8
,0xffc ,0xff8 ,0xff0 ,0xfe4 ,0xfd0 ,0xfb8 ,0xf98 ,0xf74 ,0xf4c ,0xf1c ,0xee8
,0xeb0 ,0xe74 ,0xe34 ,0xdf0 ,0xda4 ,0xd58 ,0xd04 ,0xcb0 ,0xc58 ,0xbfc ,0xba0
,0xb3c ,0xadc ,0xa78 ,0xa10 ,0x9a8 ,0x93c ,0x8d4 ,0x868 ,0x7fc ,0x794 ,0x728
,0x6bc ,0x654 ,0x5ec ,0x584 ,0x520 ,0x4bc ,0x45c ,0x400 ,0x3a4 ,0x34c ,0x2f4
,0x2a4 ,0x258 ,0x20c ,0x1c8 ,0x188 ,0x148 ,0x110 ,0xe0 ,0xb0 ,0x88 ,0x64 ,0x44
,0x2c ,0x18 ,0xc ,0x0 ,0x0 ,0x0 ,0xc ,0x18 ,0x2c ,0x44 ,0x64 ,0x88 ,0xb0 ,0xe0
,0x110 ,0x148 ,0x188 ,0x1c8 ,0x20c ,0x258 ,0x2a4 ,0x2f4 ,0x34c ,0x3a4 ,0x400
,0x45c ,0x4bc ,0x520 ,0x584 ,0x5ec ,0x654 ,0x6bc ,0x728 ,0x794};

#define samples 120

const int cs = 9;

int counter = 0;

const int chipSelectPin = 10;

void setup()
{
  pinMode(cs,OUTPUT);
  pinMode(chipSelectPin, OUTPUT);

 SPI.beginTransaction(SPISettings(20000,LSBFIRST,SPI_MODE3));
}

void loop()
{

  digitalWrite(cs,LOW);

  SPI.transfer(sine[counter]);

  digitalWrite(cs,HIGH);

  counter += 1;

  if(counter >= samples)
  {
    counter = 0;
  }

}

Very simple, I am using an Arduino nano and according to this reference the clock pin is 13 and MOSI is 11. I am seeing the clock signal for pin 13 but pin 11 is inactive.

You need to use SPI.begin() before the beginTransaction().
The documentation is not 100% clear but beginTransaction does not replace SPI.Begin to setup the SPI hardware.
Documentation not very clear: https://www.arduino.cc/en/Reference/SPIbeginTransaction

In addition to @Talk2's answer SPI.transfer(...) transfers one byte of data. Your array is made of int which means each entry is 2 bytes long.
Instead you should use SPI.transfer16(...) to transfer 16-bit values.

This is something I also wanted to address thank you for pointing it out.


text:
Using multiple RTC libraries in one program
There are multiple RTC libraries available, can I load several RTC libraries into my code and then use the functions I like from each one?  Will there be some conflict if for example I include DS1307.h   and RTCLib.h and other RTCXXXX.h libraries as well?

I think that in case of the RTCs it might actually work, but it's not advised, and may introduce some really weird problems.

Thanks guys, the real issue is that the functions available from just one RTC library are often lacking. I haven't found a "super" RTC library that incorporates the best ideas of the many libraries out there. I don't feel like writing or editing a library so I'll just convert my sketch to deal with the present best of breed.

If you want to load multiple RTC libraries I guess you are connecting to multiple RTCs.
If they use the same interface to communicate, i.e. I2C there is a possibility you will initialise the bus multiple times.
You should be OK with the functions not clashing, because they are within classes, but its possible some of the referenced structures/ classes my clash.  You might be able to resolve this by namespacing the libraries.
An alternative might be to write your own library that handles all of the RTCs that you are interested in.  This will force you to consider what each RTC requires and identify problems.
At the end of the day I agree with what Gerben is saying.  Don't do it unless you really have to.

can I load several RTC libraries into my code and then use the functions I like from each one?

It will depend on the libraries. Most likely they had some persistent variables, global to the routines, that help information exchange. If only some of the routines are used and others not, values in those variables may not be consistent.

Will there be some conflict

That will depend on the way those libraries are implemented. No way of telling without seeing the code.
The point of doing this is a little bit suspect. It is not clear to me why you would want to have more than 1 RTC in an environment. If you are thinking about giving your program the option to function with multiple RTCs (but using one RTC at any given time), you can use either macro (at compile time) or wrap the RTCs in a logic layer (at run time).
For example, you can have a rtc_init() to reset different RTCs; and rtc_read() to return the time from the rtc. rtc_read() can be implemented based on which RTC is detected during initialization...


text:
how to make led fade on and blink while wav file plays
To clarify I'm extremely new to this and I'm using an Arduino Uno with a wave shield. My circuit works as intended but I haven't learned enough of the code to know what to do to make it do exactly what I want.
Right now the following code makes the sound play on button press but the led sequence doesn't at all. If I move root.rewind(); play(root); to after the last digitalWrite then the led sequence runs but the audio doesn't play until the led sequence ends. I'm out to make the audio play while the led sequence runs. Any suggestions?
if (state == 1) {
    root.rewind();
    play(root);
    for (i = 0; i < 255; i++) { // loop from 0 to 254 (fade in)
        analogWrite(LED,i);     // set the LED brightness
        delay(15);              // wait 15ms because analogWrite
                                // is instantaneous and we would
                                // not see any change
    }
    analogWrite(LED, HIGH);     // turns the LED on
    delay(300);                 // waits for a second
    analogWrite(LED, LOW);      // turns the LED off
    delay(100);                 // waits for a second
    analogWrite(LED, HIGH);     // turns the LED on
    delay(300);                 // waits for a second
    analogWrite(LED, LOW);      // turns the LED off
    delay(100);                 // waits for a second

    digitalWrite(RESET, LOW);
}

analogWrite(LED, HIGH); is equivalent to analogWrite(LED, 1);

@gre_gor in the code I provided its an i not a one if that's what your referring to.

As this can not be your entire sketch we can only guess that you are using some sort of SDCard music playing Arduino shield and library.
An application can not call the delay() function if the application is trying to accomplish more than one task.  Calls to delay() block the processor from doing anything other than waiting for the delay to time out.
In order to (appear to) do multiple tasks, run a loop with no calls to the delay() function.  Instead call the millis() function checking if enough time has elapsed to call the LED function or the sound function.  In neither function should you call the delay() function!  If you did not write the function (for example you are using a library) you may need to edit the code in the library to ensure it is following the no-calls-to-delay()-function rule!
In general terms, this is referred to as a state machine.  In this case, the state machine is driven by the amount of elapsed time as reported by the call to the millis() function.

Thanks, that works perfectly. Still learning the vocab with this thing, which is why I was blissfully unaware of the millis function. And yes I'm using an adafruit wave shield to play audio from an sd card. I didn't include all that code because the majority of it is one of adafruit example codes to get it working. Thanks again, cheers


text:
USB connector between Arduino and a lever (switch)
I am not sure an Arduino forum is the right place to ask this question, but since I'm using Arduino here I thought it would be a good starting point. I am trying to connect a lever (you can think of it as a switch, when it's pressed it's ON, and otherwise it's OFF) to an Arduino via a USB connector. My setup worked perfectly fine when I connected the lever directly to the Arduino, but via the USB it doesn't work. Since I already built and invested in USB connectors I would like to solve this issue, or at least understand what I am doing wrong in here.
I've attached a photo to demonstrate the wiring. Note that it works if I bypass this USB connection. I'm trying to understand why this doesn't work via a USB.

to clarify, you're using a USB connector, but not for a USB connection? perfectly valid thing to do, just check if the female to female doesn't "cross" the grn/yellow connections

As there is not really a legitimate role for USB female to female cables, any you find should be considered highly suspect.  It is quite possible they do not connect all of the pins through, or do not connect them in the way you believe they should be connected.  And generally speaking, using USB connectors for a different purpose is a bad idea - it is just asking for confusion.

Thank you both. Yes, I'm using a USB connector, but not for a USB connection. I guess the problem is indeed the female to female connector. I agree this was a bad idea, but I'm already invested in this solution as I made 16 Arduino boards following this schematic. I can re-wire everything and try different connectors, but it would be great if I could make this work without spending more money on different connectors.

@ChrisStratton I have a female to female USB A cable here. It has a perfectly legitimate role. It came with my oscilloscope and is used for connecting the USB A socket on the front to a USB A socket on a PC. The oscope then switches its OTG to Device mode and the PC sees it.

That is not a legitimate use in the eyes of the USB spec, hence the cable was not supposed to exist.  I've had needs like that too, and sourcing a solution can be hard - when you are shopping for something that isn't supposed to exist, you run into vendors that sell creative fiction.  A working cable certainly can be made, but it's not necessarily what you will get when you buy.

@ChrisStratton What's male and what's female on USB? They're very much hermaphroditic. They're the Bangkok Chick-Boy of connectors.

I'd suggest using a multimeter to figure out what's connected to what after hooking up the complete wiring scheme; there aren't that many options and you should be able to figure out what's connected to what soon enough. On a more philosophical note, it's only a bad idea if the alternatives weren't worse.

I support this answer. If you use a multimeter you can test which pins of the USB connection are linked. I've used USB cables in the past for several installations as well, i.e. for sound or to control NeoPixels. It works quite good, but you have to make sure all the things are wired properly.


text:
SD Card Info Unexpected
So I have just begun testing my Wireless SD Shield from Arduino with my Arduino UNO. Upon running my the basic CardInfo sketch, it uploads and displays data, but far more than expected. The SD Card is entirely empty, as in, if I plug it into my computer, there are no files on it. However, this is the Serial Monitor Output I receive:

The reason I have included screenshots rather than copy and pasting the output, is that if I try and copy and paste, it does not copy all of the Files Found on the card, it only copies the first 8 lines.
Any help would be greatly, appreciated!
This code does not compile for me and gives me an avrdude error which I believe is due in some part to the above pictures:
//Program by Jeremy Blum
//www.jeremyblum.com
//SD Card Demonstration
//Based on Example by Tom Igoe

#include <SD.h>

//Set by default for the SD Card Library
//MOSI = Pin 11
//MISO = Pin 12
//SCLK = PIN 13
//We always need to set the CS Pin
int CS_pin = 4;

void setup()
{
  Serial.begin(9600);
  Serial.println("Initializing Card");
  //CS Pin is an output
  pinMode(CS_pin, OUTPUT);

  if (!SD.begin(CS_pin))
  {
      Serial.println("Card Failure");
      return;
  }
  Serial.println("Card Ready");

}

void loop()
{
  String dataString = "Hello";

  //Open a file to write to
  //Only one file can be open at a time

  File dataFile = SD.open("log.txt", FILE_WRITE);
  if (dataFile)
  {
    dataFile.println(dataString);
    dataFile.close();
    Serial.println(dataString);
  }
  else
  {
    Serial.println("Couldn't open log file");
  }
  delay(5000);
}

Whereas, this code does:
#include <SD.h>         //SD Card Library
#include <Wire.h>       //I2C Library
#include <DallasTemperature.h>
#include <OneWire.h>

OneWire oneWire(2); // initiate pin connected to DS18B20
DallasTemperature sensors(&oneWire); // pass oneWire as parameter to Dallas Temp. library

//SPI SD Card Pins
  //MOSI = Pin 11
  //MISO = Pin 12
  //SCLK = PIN 13
  int CS_pin = 4;
//  int pow_pin = 8;

//Light Sensor Pins
  int light_pin = 0;

float refresh_rate = 500;  //Dataloger Refresh Rate
float id = 0;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  sensors.begin(); // initiate the sensors on the DS18B20
  Serial.println("Initializing Card");
  //CS Pin is an output
  pinMode(CS_pin, OUTPUT);

//  //SD Card will Draw Power from Pin 8, so set it high
//  pinMode(pow_pin, OUTPUT);
//  digitalWrite(pow_pin, HIGH);

  //Initialize Card
  if (!SD.begin(CS_pin))
  {
      Serial.println("Card Failure");
      return;
  }
  Serial.println("Card Ready");

  //Write Log File Header
  File logFile = SD.open("LOG.csv", FILE_WRITE);
  if (logFile)
  {
    logFile.println(", , , ,"); //Just a leading blank line, incase there was previous data
    String header = "ID, Light, Temp";
    logFile.println(header);
    logFile.close();
    Serial.println(header);
  }
  else
  {
    Serial.println("Couldn't open log file");
  }

}

void loop()
{
  //Check Light Level
  int light_level = analogRead(light_pin); //Write the value of the photoresistor to the serial monitor.

  //Read Temperature
  sensors.requestTemperatures(); // request the temperatures from the DS18B20, does not actually do anything simple sets it up
  float currentTemp; // initialize variable to store and hold current temperature readings
  currentTemp = sensors.getTempCByIndex(0); // go and get temperature in Celcius for the first temp probe, temperature probe 0 (could have more than one sensor here if wanted)

  Serial.print("Temperature = ");
  Serial.print(currentTemp); // prints actual temperature and starts new line
  Serial.print(" Celcius ");
  /* Serial.print((char)223); print degree symbol in LCD format */
//  Serial.println("C");

  //Create Data string for storing to SD card
  //We will use CSV Format
  String dataString = String(id) + ", " + String(light_level) + ", " + String(currentTemp);

  //Open a file to write to
  //Only one file can be open at a time
  File logFile = SD.open("LOG.csv", FILE_WRITE);
  if (logFile)
  {
    logFile.println(dataString);
    logFile.close();
    Serial.println(dataString);
  }
  else
  {
    Serial.println("Couldn't open log file");
  }

  //Increment ID number
  id++;

  delay(refresh_rate);
}

Both sketches are quite different, so I reccomend just looking at the intial void setup() part of each if you want to read through them.

Simply seeing an empty card on your computer, does not mean it's empty. Turn on 'Show hidden files' in Windows.
Besides that, many of these files are written to the SD card to make it usable. Without them the card is either corrupted or formatted.

Joy of tech... It's full file table, with old, deleted entries appearing as current files. You can nuke it with a quick or slow format, but the problem will return later. I don't know this shield, but there must be some problem with the code - it really shouldn't show deleted entries. Try another library, or google for problems with your current lib.

Not sure about quick format - but in any case, it shouldn't show old FAT. Please post your findings, I have some microsd modules in the mail.

So I ended up leaving it be, and simply ran a different sketch and it seems to be working fine so far. I believe it may have been some hidden files instaled by my Mac when I first tried to use it, and so hopefully it will not be an issue in the future.

mac's "hidden" files are prefixed with "." (dotfiles), that's not your bug.

hmm, then not sure why it seems to have worked?

can you post your broken and working code seperately?

Yup. I will add it as an edit to the above post.

They are Mac's OS X "Spotlight" hidden indexing files.  This answer shows how to turn it off.


text:
Arduino Micro Cannot get Interrupt 6 work on PIN 7
After finding out about the situation with pin7 from this tutorial:
https://forum.sparkfun.com/viewtopic.php?f=32&t=35847
    void setup(){

    EICRB |= (1<<ISC60)|(0<<ISC61); // sets the interrupt type for EICRB (INT6).
                                  // EICRA sets interrupt type for INT0...3

    /*
    ISCn0  ISCn1   Where n is the interrupt. 0 for 0, etc
      0      0   Triggers on low level
      1      0   Triggers on edge
      0      1   Triggers on falling edge
      1      1   Triggers on rising edge
    */
EIMSK |= (1<<INT6); // activates the interrupt. 6 for 6, etc

void loop(){
//do other things here
}

ISR(INT6_vect) {
  // interrupt code goes here
  }

I have set:
EICRB |= (0<<ISC60)|(0<<ISC61);

Because I need it to be triggered on LOW.
I could still not get it work on the micro. IF I use the pin as regular input pin I can clearly see LOW/HIGHs on pin 7 with digitalread.
I have a sensor attached there which goes LOW in case it is triggered.
I wonder if anybody knows what else can I try to get it work. I already hardwired everything in my circuit board, there are no more free interrupts and no way to change them.

ORing with 0 does nothing.

And did you define an ISR?

I've used following code and loopback from pin 8 to pin 7:
// loopback:  pin 8 -> pin 7

void setup() {
  pinMode(7, INPUT_PULLUP);
  pinMode(8, OUTPUT);
  pinMode(LED_BUILTIN_TX, OUTPUT); // to see pin 8 logic level on TX led
  pinMode(LED_BUILTIN, OUTPUT); // toggled by ISR

  EICRB |= _BV(ISC60);  // Triggers on edge
  EIMSK |= _BV(INT6);   // activates the interrupt
}

ISR(INT6_vect) {
  PINC = _BV(PC7);  // toggle led 13 (@ PC7)
}

void loop() {
  digitalWrite(8, HIGH);
  digitalWrite(LED_BUILTIN_TX, HIGH);

  delay(500);
  digitalWrite(8, LOW);
  digitalWrite(LED_BUILTIN_TX, LOW);
  delay(500);

}

And it works perfectly. Only problem I can imagine is to figure out correctly which pin is really 7 as label is on the right side of pin (not under nor left).


text:
Cheapest way to change digital output source
Powering at 5 volts, atmega328 output ~4.7 volts. I need to output between 12 and 24 volts @ 2 amp. I'm currently using relay but they are costly. Is there a way to do it with transistors or any thing cheaper?
Thanks

Yes, but it depends on WHAT you are powering.

Something like a mosfet.

As @Gerben said in the comments, I would also recommend an N-channel MOSFET.  OnSemi has a great application note on how to determine what type of MOSFET you would need based on your given load requirements and how to use it as a switch.  You can find that app note here.
The basic idea is to provide an enable signal from your atmega328 to the gate of the MOSFET to drive it into saturation or to turn it off.  You would connect your 12/24V supply to the drain of the MOSFET and connect your load to the source of the MOSFET.  The basic circuit can be seen in the application note.
Hope that helps!


text:
Is it possible to connect a camera to an arduino?
I working on a project that requires a small camera to be covering a (insect) nest entrance. The video needs to be transmitted to a computer to be processed. I am interfacing with Java using the RXTX library and will then be tracking objects using OpenCV.
This is the camera
My question is, it it possible to connect this camera to an Arduino (Uno or Yun) and transmit the data back to a computer?

Why don't you get a camera that connects directly to the PC?

@Gerben i don't think the insects will slow a PC near there nest.

I'd just go with a raspberry pi, and usb-webcam of the pi-camera-module. Then you could even run the OpenCV on the Pi itself. Having and Arduino, some camera, some kind of networking shield will quickly become expensive. PS what do you mean by the word slow?

Thanks. Ideally, the connection between the computer and the camera would be wireless. Would this be possible with the pi camera? The other option, is to scrap the Arduino and use a wireless transmitter and receiver set

Yes. Check out ArduCam. Do a google search. http://www.arducam.com

Thank you. I'm a bit confused about the Arducam. Am I able to just use the library with the camera that I specified or do I need to purchase the Arducam camera? Also, would I need the shield?

I didn't mean shield, I meant the board that they are using for the camera, but I think that it is just an Uno

I picked up one of these Arducam Mini Module Camera Shield 5 Megapixels OV5642 Camera Module for Arduino UNO Mega2560 Board https://www.amazon.com/dp/B013JUKZ48/ref=cm_sw_r_cp_api_wlbKxbSN0G2KK You find cheaper ones on eBay b


text:
Yikes! Invalid device signature. Fail to burn bootloader and read fuses
I know this problem is kinda common but I had to post it anyway.
Before anything, I would like to inform you guys that I changed the fuse of my Arduino Pro 3v3 @ 8MHz to allow 1.8 V brownout and also programmed CKDIV8 AND CLKOUT. In other words, the fuse configuration is this: E:FE, H:DA, L:3F.
The programmer is the Arduino 2009 running as ISP programmer. The target is Arduino Pro Mini 3V3 @ 8Mhz.
I also used a 0.1uF cap between reset and ground in the Arduino programmer.
After a good time using the Arduino Pro without problems, some random problems began to appear when I tried to upload a program with the programmer (Arduino as ISP). So I tried to burn the bootloader again and the following message appeared ""avrdude: Yikes! Invalid device signature."
The same occurs when I try to communicate with avrdude using this command "avrdude -c arduino -p m328p -P COM3 -b 19200 -v".
Some tests I did:

Continuity test directly at uC pins between those signals: SCK, MISO, MOSI, (/SS - /RESET). No problem good connection.
Verified the clock in XTAL1 and XTAL2. No problem 8MHz.
Verified the clock in CKOUT (Arduino Pro pin 2) and measured 1MHz.
I also tried to delay the avrdude using -B5, B10 and another values. With a quick search on Google some people are saying that those delays don't work with the Arduino as ISP.
I used some sketches for slow clocks, which I don't remember, and no luck.
External power and no luck again.

What am I missing? Do I need to change something to communicate with Arduino Pro running at 1MHz?

If you are burning the bootloader through the IDE it won't expect the CKDIV8 fuse to be set.
I have a bootloader programmer which you could use to reprogram the bootloader. You just need another Arduino (eg. Uno, Mega) and connect 6 wires between each of them like this:

The sketch for programming the bootloader is available on Github:
https://github.com/nickgammon/arduino_sketches
You want the one in the "Atmega_Board_Programmer" subdirectory.


text:
Why does Serial.print print out the wrong thing?
I am using a flame sensor. I am reading the state and then printing it. Here is my code:
void loop(){
 flameState = digitalRead(flamePin);//variables already defined and are global
existsFire();//calls the void
delay(1000);
}

void existsFire(){

Serial.println("Flame: " + flameState);

}

Before, this printed out the right thing. Today, it was printing out "lame:". The "F" and the flameState were missing. I changed it to:
void existsFire(){

Serial.print("Flame: ");
Serial.println(flameState);

}

Everything worked fine. Is there a problem with my Arduino Mega. What do I need to do to fix this?

You've stumbled across the difference in the C++ language between a String and an "array of characters". What you gave Serial.println() was an array of characters:
Serial.println("Flame: "...);

and then tried to add a number to it.
Serial.println("Flame: " + flameState);

If it had have been a String, then what you typed would have been fine:
String flame = "Flame: ";
Serial.println(flame + flameState);

Adding (literally +) a number to a String adds characters to the String to represent the number. Unfortunately you didn't start with a String, you started with an array of characters:
"Flame: "

Adding a number to THAT changes where the array starts. flameState must have been 1, and "Flame: " + 1 would have been "lame :" - as you found out!
The version that worked did so through a little bit of magic:
Serial.print("Flame: ");
Serial.println(flameState);

The first line called a version of print() that accepted an array of characters and printed each of them out. The second line called a different version of println() that accepted a number and printed out its representation as a series of characters (digits) - followed by a new line (the ln part of the name).


text:
Shift Register w/ Internal Pullups?
Is there a chip that is just a parallel in / serial out shift register but with integrated internal pullups?
I could use a full-blown I/O expander but I really just need more momentary button inputs. I don't need outputs and I would rather not bother adding resistors or with writing commands to initialize the chip.

Have you considered using a button matrix instead?

No but unfortunately that doesn't really help me. Not unless there were a chip that automatically handled the decoding and output serial.

You say "more", which presumes that you're already handling some. Just change how they're being handled.

Probably doesn't exist. http://forum.arduino.cc/index.php?topic=162710.0

Logic integrated circuits such as shift registers normally do not contain pull up resistors on their input(s).  This is because they are normally connected to a totem pole driver.  Such a driver eliminates the need to avoid floating inputs.
Also, pull up resistors require current when the input is driven toward the opposite power rail.  Even though adding internal pull up resistors may not change the overall behavior of the chip, designers will avoid parts if they unnecessarily add to the over all power demand.
Based on your comments and your question, consider an old ps/2 keyboard. It is essentially a switch matrix with a built in decoder chip which may fullfill your requirements. The chip scans the switch matrix, debounces the switches and converts button presses & button releases into a serial stream of data.
Added later...
Here is a description about connecting a ps/2 keyboard to an Arduino.  Included are schematics, code examples and supporting library.
(USB keyboards are not well suited for this purpose as they require a USB Host.  As most Arduinos do not have this, a USB Host shield is required.)

I think you mean debounces... ;)

That's funny!  I should never answer a technical question on a tablet.  I'll change it. Thanks.

I guessed you had. Mine tried to change it in exactly the same way. Android?


text:
SD test is taking long answer when it fails
I am working on an Arduino application that logs sensors values into SD files. It is essential that the SD is inserted and working when a test is started, thus I need to check the presence of the SD regularly (every 2 seconds or so) to prevent launching a test without SD inserted by the user.
When I run the following code, it runs very fast when the SD test succeeds (<10ms), but it takes more than 2000ms when the test fails. Is there another test I could run that does not takes 2 seconds to indicate that the SD is not inserted (or not working)? All my buttons are frozen and they do not trigger any action while checking if no SD is inserted.
Here is my code (both loops have the same issue):
#define csSD   53
#include <SD.h>

Sd2Card card;

void setup() {
  Serial.begin(57600);
  bool SDOK = SD.begin(csSD);
  if(SDOK) {
    Serial.println("SD.Begin Setup OK");
  } else {
    Serial.println("SD.Begin Setup Fail");
  }
}

unsigned long t;
//void loop() {
//  t=millis();
//  if(SD.begin(csSD)){ // SD.Begin test runs fast when there is a SD, even though it return true when you try to begin SD a second time
//    Serial.print("SD.Begin loop OK : ");
//  }else {
//    Serial.print("SD.Begin loop Fail : ");
//  }
//  Serial.println(String(millis()-t)+"ms");
//  delay(500);
//}

void loop() {
  t=millis();
  if(card.init(SPI_HALF_SPEED, csSD)) {
    // card.init test returns true as it should (when SD is present and working), but runs fast only when SD is working
    Serial.print("card.init loop OK : ");
  } else {
    Serial.print("SD.Begin loop Fail : ");
  }
  Serial.println(String(millis()-t)+"ms");
  delay(500);
}

Many SD card sockets have a presence detect switch, of course something in the socket which activates that is not necessarily a functional SD card.

What if you attempt to read from a card if it's not inserted. Maybe this can return the state of the SD card faster.

The SD library builds on the sdfatlib library, in which SD_INIT_TIMEOUT is defined as 2000 ms, which gives your 2 second timeout. You could try lowering that number to get a faster response, although that may run the risk of timing out even when a card is present.
Four different timeout periods are defined in the sdfatlib source:
/** init timeout ms */
uint16_t const SD_INIT_TIMEOUT = 2000;
/** erase timeout ms */
uint16_t const SD_ERASE_TIMEOUT = 10000;
/** read timeout ms */
uint16_t const SD_READ_TIMEOUT = 300;
/** write time out ms */
uint16_t const SD_WRITE_TIMEOUT = 600;

The 300 ms read timeout is faster, as @Paul suggests in his comment, so you could just use a card read as the test rather than an initialisation, or try setting the init timeout to 300 instead. A read test would be simpler, as it doesn't involve modifying library files. It might not cope with a re-inserted card, though - I suspect that requires reinitialisation each time.
Note: the version of sdfatlib included with the SDlib in my Arduino install appears rather older than the current version. The included version defines the timeouts in Sd2Card.h, while the latest has is in SdInfo.h. The snippet above is from the older, included code.

You could always try this very simple sketch. I have never measured how quick it runs, but it is pretty quick.
Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

Just make sure to change 4 in !SD.begin(4) to whatever your ChipSelect pin happens to be for your component.
Furthermore, you could add a return statement after your "initilization fails" loop because that will immediately stop the program, after all you do not want to run it if the SD card is not reading data! And last thing, it may be a little overkill to check the SD card after initial initilization, after all, it will be highly unlikely for an error to occur once everything is working fine unless you mess with the SD card alot while it is running, which I am sure you won't.

This sketch is not working as I would like it to : if placed in setup, it works fine, but as soon as it is run a second time, it returns false.
See : http://arduino.stackexchange.com/questions/3850/sd-begin-fails-second-time
Also, when no SD is inserted, this test takes 2000 to 2300ms on my device.

Have you tried removing the verification from the loop itslef. Like I mentioned before, you should not need to verify the SD card every time you run through the loop, that is a bit overkill.

If you perform the check out of the loop, it would work.
However, in my application, I need to check the SD regularly as the Arduino board will be embedded into a package and will not be able to reset if not by shutting down the power of the whole machine. Also, the user will want to remove the SD to transfer the file onto the computer while the board is on. I would like to prevent a test start if no SD is detected. Thus, I would prefer regular checks on the SD.

If you will have interaction with the SD Card while it is reading, you could potentially have the SD Card detection happen once every 30 seconds or so to prevent from constant button freezing. Or, you could have a manual check at the push of a button or input from the Serial Monitor, so that will allow you to check the SD at you disgression.


text:
Is it possible to use a USB camera with Arduino?
It is necessary to recognize the motion and record video live.
Update
Save enough on your memory card.
PS
Maybe I'll repeat the question, but I am not guided in English.
Sorry for my English.

An Arduino is not a powerful processor and can not do much image processing.  I doubt that there is a USB camera that could be connected to the Arduino.
There are a range of OVO cameras that can connect to the Arduino, but I don't think you will be able to record live video on an Arduino with these, where would you store the file for starters?
There is a PIXY camera system, this has its own microprocessor and interfaces with an Arduino.  It can record video and do object recognition.
http://charmedlabs.com/default/pixy-cmucam5/
Hope that helps.

It looks interesting)) How to get/buy it?

Found http://charmedlabs.com/default/where-to-order-pixy/


text:
How to get readings on serial monitor in every 10s?
I am doing my final year project and here I am attaching the code I am using. According to the code, I will get the sensor output in serial monitor. But I want to get reading once n 10ms. Since serial monitor can't work with that resolution, I need to save the reading in an array and then output the array in serial monitor or any other way. Please help me in modifying the code.
The code is as follows:
/*
   The circuit:
  * VCC connection of the sensor attached to +5V
  * GND connection of the sensor attached to ground
  * TRIG connection of the sensor attached to digital pin 2
  * ECHO connection of the sensor attached to digital pin 4
 */

const int trigPin = 2;
const int echoPin = 4;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop()
{
  long duration, cm;

  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  cm = microsecondsToCentimeters(duration);

  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(100);
}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}

At 9600 bps there should be no problem sending up to 9 bytes every 10 ms.

There is one fundamental error with your code that I feel I should point out - one that I see time and time again.
The basic structure of your code is:

Forever:

Send a ping
Wait for the pong
Print the result
Delay for 100ms (or whatever time you choose)

And you expect to get a result every (delay) milliseconds.
However, you won't.  What you will actually get is a result every so often, where that time is defined as 100ms + the time to send and receive a ping.
So if it takes 11.6ms (200cm, the limit of most pin sensors) to receive the pong, then you also delay for 100ms, you're going to end up with 111.6ms between each print. It's even worse if the pong never arrives back - then pulseIn() will wait for up to a second before returning. You can, of course, reduce that to say 15ms by adding the timeout parameter as per the manual
When you reduce your printing delay to just 10ms you actually run the risk of delaying for more than double the time you expect to (21.6ms instead of 10ms).
Instead you need to use millis() to check to see if it is time to print something so that it doesn't matter how long the pong took to arrive, as long as that never exceeds the amount of time you want between prints, otherwise it's going to get delayed regardless.

Yeah it shouldn't be an issue, remember delay(time) is a millisecond command, so if you want to get a reading every 10ms, simply put delay(10), and not delay(100). Like the comment above mentions, you should have no problem with a 9600 baud rate serial monitor link showing data every 10ms.
Also, I would highly reccomend checking out the NewPing library (https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home)
which is an update library for the ultrasonic distance sensor which I assume you are using based off your code. With that, you can send up to 30 "pings" per second, so if the above solution doesn't fix it for you, this definitely should.


text:
Engine Speed Control Observation
I am using an Arduino Mega to control the speed of an internal combustion engine.
The speed is sensed via a Variable Reluctance Sensor (VRS) on the crankshaft. This signal is then converted into a 5V square wave which is feed into Interupt 2 (Pin 21) on the Arduino.
The flywheel of the engine, onto which the VRS is sensing has one tooth. Therefore one square wave blip (from 5v to 0V) as it is passing it and then back up to 5v. The interupt that this is attached to increases a counter by 1. The time taken for the counter to reach 20 is recorded. I want to use this speed reading value in a PID algorithm which then in turn actuates a servo.
This methodology was sucessfully used in a very similar engine with a 22 toothed flywheel but is not working on this engine with 1 tooth.
The problem is the speed reading - the values that I am recording for the time taken for 20 revs ( in micro seconds), and displayed on the serial terminal is wrong and I do not know why. The numbers printed are all mulitples of one another e.g. 440960,551200,661440,771680 which all divide into one another with an even fraction. The correct reading here is 661440, this has been verified with observation of the square wave input through and oscilloscope.
I cannot find why!
I have attached the code here

Why are you using an interrupt instead of Input Capture?

Are you suggesting using PulseIn?

Your methodology there is somewhat flawed. Not only will you never see that Counter1 >= 20 (since you immediately set it to 0 before returning the count), but if you never get a pulse (engine is stalled) you'll never reach 20 pulses anyway.
A better method is to reverse everything and instead of timing how long it takes to get 20 pulses, count the number of pulses you get in a pre-defined time period.
Your interrupt remains the same, counting each pulse as it arrives, but you then sit and watch the clock (using millis()) and when a certain (to be decided by you) time has elapsed (the sample time) you record the pulse count and reset it to 0. You then have a number of rotations per time period.
If you set that time period to be 1 second (the simplest) then you immediately have the number of rotations per second.
void loop() {
    static uint32_t ts = millis();
    uint32_t pulses;

    if (millis() - ts >= 1000) {
        ts += 1000;
        uint8_t sr = SREG;
        noInterrupts();
        pulses = Counter1;
        Counter1 = 0;
        SREG = sr;
        Serial.print(pulses);
        Serial.println(" revolutions per second");
    }
}

Decreasing the sample time means you can respond faster, but you are working with smaller numbers and hence less accuracy. For instance, setting it to 100ms instead of 1 second you need to multiply your count by 10 to get the current pulses per second. It all depends on how fast your engine runs as to what a good sample time would be.


text:
Xbee not activate on arduino micro
I have 2 nodes: one is a PC+arduino mega+xbee the other one is arduino micro+xbee.
The 2 xbees are communicating fine, I have tested this with 2 separate arduinos.
My problem is that when the second xbee hooked up to the micro it seems it does not try to send or receive data from the serial lines.
It is connected to the first RX/TX pins in proper order (RX->Tx, Tx->Rx) on the micro.
This is obvious for me because if I start my program's setup section on the ardu with:
void setup()

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

The whole main program won't be running because the serial just never gets ready only if I plug my PC in.
When I try to send data from the PC->micro through xbee I see the Xbee receives it (led goes on the board) but nothing happens on the micro.
The micro right now is set to periodically send some debug data through the serial, I don't get that back either otherwise I would see the serial TX led on the micro blinking that it is sending the data. It only works when the PC is connected through USB.
Do I need some additional code for the xbee or is it require a hardware modification? I use a 5V-3V ttl converter as an extra hardware.

From the Arduino site: Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data using the ATmega32U4 hardware serial capability. Note that on the Micro, the Serial class refers to USB (CDC) communication; for TTL serial on pins 0 and 1, use the Serial1 class.

It is probably because you are using the only Serial to communicate to both the devices - your PC and XBee. At any instant, you can communicate to only one device. So you might need an extra serial to get you go.
And, may be due to this conflict you can see TX led blinking. May be it's communicating with anyone of them, and the other one is receiving garbage.

From your description, it kind of hard to figure out which arduino doesn't react. Maybe a picture would help.
If it is the arduino that is connected to the PC then the problem is that the serial connection is already used to talk to te PC and therefore can't be used to talk to the XBee. you'll need to use one of the other serial connections on the atmega (serial1, 2 or 3)
Mind you that you don't need a microcontroller to connect an XBee to the PC. A simple UART to USB converter is enough.


text:
Using Arduino libraries with ARM based microcontroller
A week ago I started messing with LoRa. I got my STM32L151 IM880A kit.
Company that provided SX1272 LoRa modem chip (used in kit), provided some libraries, but lots of functionalities are still not implemented and is still not suitable for use in multi P2P aplications.
After googling I came across Libelium company which used SX1272 chip in their products design and they provided useful set of libraries that provides lots of functionalities and also implements some sort of LoRa frame protocol stack ideal for use in P2P applications.
The problem is that I'm using STM32 in my project and Libelium libraries are written for Arduino. So I was wondering if there is a smart way to port Arduino libraries so I could use them in my STM32 Keil projects, since the libraries seems huge.
Tips, hints, links would be appreciated (I don't have experience in using Arduino and I'm not familiar with Arduino library structure).

Are you familiar with stm32/ARM cortex programming instead?

You can use Arduino software on an STM32: http://jeelabs.org/book/1545d/

I don't want to use Arduino, I just want to know if it is possible to port libraries and in what measure is it convenient.

@Ivan47 well "is it possible to port if it runs natively?": yes. "Is it easy to port": depends. Since you say you feel confident enough in doing Cortex programming: the library really isn't that big. Just port over these C++ methods you need. It'll be mainly a replacement of C++ with C (assuming you're not doing C++ on a cortex-m deliberately), and usage of CMSIS/STM32lib instead of things like arduino's "SPI" class.

Notice that the Libelium library you linked is licensed under the GNU LGPL 2.1. While this probably (IANAL) won't restrict your cross-usage of it, you definitely need to check about license compatibility if you produce a product with that code.

Okay, now I want to spare myself of pain of porting/debuging. I was wondering if there is stack available, that works on LoRa radio layer (does not implement LoRaWAN), that will allow me to assign some sort of ID/NODE_ADDR to each node and be able to establish connection between them, so P2P comm ?

Every time I work on a project I use arduino libraries and port them to my micro controller.
I used sublime text editor with multiple selection and editing(ctrl-d). Then I copy the arduino code to both sublime and my uC IDE then compile it in the IDE, scroll up to the first undefined function and add its definition to the code or modify it using sublime multiple editing and selecting (like digital read and write was in my opinion useless). After that update the file in your IDE and compile again.
You would do that till you have finished and it would take some time.

So I was wondering if there is a smart way to port Arduino libraries so I could use them in my STM32 Keil projects, since the libraries seems huge.

Yes. the STM32 port of arduino uses GCC, which isn't that different MDK or ADS - I have ported quite a few from back and forth from GCC <-> MDK, and one from GCC to ADS. If the code is well written, in many times all you need to do is to change the isr-related code pieces (a few names) and hit the recompile.


text:
Array deletion problem
I am a bit confused about how memory works in Arduino.  I have created an integer array like so:
int* arr = new int[3] {1, 2, 3};

When I go to delete it:
delete[] arr;

The first element is deleted, and all the remaining ones are still  present and accessible.
Serial.println(arr[0]); // prints 0
Serial.println(arr[1]); // prints 2
Serial.println(arr[2]); // prints 3

First of all: it is not a good idea to do dynamic memory maagement in embedded systems (in casu arduino)
Secondly freeing memory means: marking the memory as available. It does not mean "setting the memory to 0"
because ar still points to the same locaton in memory it is "normal" that it also still reads the old values. Only -according to the C CP0P0 pàrogramming rules- you should not do so. Reading will not cause problems but writing will very likely.

It is not a good idea to use dynamic memory in such a small devices in general.
And delete doesn't mean setting values to something at all. It's just returning allocated memory back ("to system" is not correct term here as there is no system).
You should try to use objects with some action in constructor and destructor (like printing values).
For example:
class test {
public:
  test(int _i):i{_i} { Serial.print("test:"); Serial.println(i); }
  ~test() { Serial.print("~test:"); Serial.println(i); }
  int i;
};

void setup() {
  Serial.begin(57600);
  test * arr = new test[3] {4,6,9};
  delete[] arr;

}

void loop() {
}

prints:
test:4
test:6
test:9
~test:9
~test:6
~test:4

Deleting newed memory only informs the system that you are no longer using it and releasing it for re-assignment. The pointer still points to memory containing your array but that memory is no longer reserved for you. You could, in theory, go on using it, but another new might well reassign it for another use and the data that was in it would likely get over-written.
It would be good form to zero your pointer (arr = (int *)0;). It accomplishes several things:

Your code clearly reminds you that the pointer is no longer usable;
Your code clearly informs the next reader that the pointer is no longer usable;
An attempt to use the pointer is quite likely to fail immediately (depends on the envrionment's ability to trap attempted accesses to location 0). The alternative is your code may work anyway - until someday that memory actually does get re-assigned and suddenly, code that has worked "forever", breaks, and in a non-obvious way. Save yourself or the guy or gal who follows you some grief, and make it a habit to zero your pointers once they are no longer valid.

Note that arr = 0; is sufficient - you do not need to add (int*). 0 is defined for pointers.


text:
Bizarre transistor behavior and voltage with DC motor in simple circuit
I started a new motor related project recently with a new Arduino Uno, beginning with several tutorial circuits included in the Vilros Arduino guide. The circuit in question is #10, a simple DC motor circuit with a transistor switch (https://i.stack.imgur.com/KLC0K.jpg). The Arduino is being powered for the moment via USB.
The circuit, completed according to the diagram/common sense, does not work. The voltage across the transistor base is clearly not sufficient to activate the switch with the motor in the circuit. 5V (more like 4.6V) from Pin 13 is running across a 330 ohm resistor to the transistor base, but there is no current between the collector and the base. Bypassing the collector/base gap with a piece of metal will complete the circuit and activate the motor.
For some reason, the transistor will switch properly when the motor is replaced by a simple LED. AND, switching the cable from Pin 13 to the +5V out is enough to activate the transistor switch. I was under the impression that the transistor should only require .7V above the common grounded element.
But, even more bizarrely, with a cable running from +5V to the transistor base (through a resistor), a voltmeter across the DC motor is reading a potential difference of anywhere from 9V to 1702V (see https://i.stack.imgur.com/mwFKp.jpg, yes, with 4 digits). The multimeter is otherwise working normally, so I don't see a good explanation. Is the Arduino pin just incapable of providing sufficient current/voltage to activate the transistor, or am I missing something obvious. And does anyone have some idea why the voltmeter is reading so high and fluctuating so wildly? It is curious that the Arduino disconnects from the PC whenever the circuit is completed with the motor in it, so the Arduino likely is overdrawing from the USB.
The transistor included was not the one listed, but a common MPS2222A.
Thanks

There is nothing wrong with the circuit (although drawn in a bizarre method). Your understanding of how a transistor works is mistaken - forget voltage - transistors are controlled by current.
Most likely you have connected the transistor incorrectly.
The voltage reading is due to back EMF. If you used an analog meter it would give the reading you expect.
In all likelihood you have damaged the transistor.

Thank you. I have some background in physics, but none at all in circuit/semiconductor theory, although I'm learning. The voltage reading makes sense. A damaged transistor does seem likely, although I've replaced the transistor twice with an identical one to no avail. Curiously, the transistor works properly if I wire the transistor base to the 5V out instead of an Arduino pin. Is it possible that the pins can't provide sufficient current across the (possibly damaged) transistor while the 5V out can? Thanks again.

@JacobAustin The Arduino can supply 20mA, but with a 330Ω should put 15mA into the base (you can measure this by putting the meter in series on a mA range). This should be more than sufficient to saturate the transistor and be able to switch its 600mA current. If it isn't turning it on you have a wiring error (most likely reversed C E) or damage. The transistor does seem to be reversed in the image.

Okay. Thanks again. Curiously, I was able to attach a 9V battery to the Arduino and everything worked fine. It's possible that I damaged the USB by drawing too much current, and that was limiting the current supplied by the Arduino across the transistor.

According to second image transistor seems to be connected in oposite direction (switched Collector with Emitter). It means common collector configuration is used instead common emitter and it's usually not enough to drive motor. And C-E can handle only about 10V Max (more or less, depends on transistor) even if it could handle much more in oposite direction.
See link for more details:

Common Base Configuration   –   has Voltage Gain but no Current Gain.
Common Emitter Configuration   –   has both Current and Voltage Gain.
Common Collector Configuration   –   has Current Gain but no Voltage Gain.

I've just tested this circuit an it must be powered by power jack. USB is not strong enough.

The transistor that came with the diagram was itself reversed. Emitter-base-collector, instead of collector-base-emitter. I have also tried reversing the transistor to no avail.

@JacobAustin that's true for 2N2222 and PN2222 but for P2N2222 is schematic correct. SparkFun Inventors Kit contains P2N2222.

The kit contained the wrong transistor. It was an MPS2222A transistor. However, attaching a 9V battery seems to have solved my problem. Probably an issue with current draw from the board.


text:
Difficulty with shifting data
Im trying to shift LEDs using 595 register. Using SN74HC595N registers. Im using 4 of the registers as i got alots of LEDs to shift. My code for shifting doesn't seem working.. i can shift some with 2 registers but not 4 registers
// include the library code:
#include <LiquidCrystal.h>
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 RTC;

// initialize the library with the numbers of the interface pins
// RS-12, E-13, D4-8, D5-9, D6-10, D7-11
LiquidCrystal lcd(12, 13, 8, 9, 10, 11);

int row[]={8,9,10,11};// Digital output connect directly to all rows
int col[] = {A0,A1,A2}; // Analog input with 10K pull-up to 5V.
int i,j; // Two counter variables to count inside for loop
int col_scan; // Variable to hold value of scanned columns

//Pin connected to ST_CP of 74HC595
int latchPin = 3;
//Pin connected to SH_CP of 74HC595
int clockPin = 4;
////Pin connected to DS of 74HC595
int dataPin = 5;

//holder for infromation you're going to pass to shifting function
byte data = 0;
byte data1 = 0x55;
byte data2 = 0xAA;

void setup()
{
  Wire.begin();
  RTC.begin();
  Serial.begin(9600);
  for(i=0;i<=3;i++)
  {
    pinMode(row[i],OUTPUT);
    //pinMode(col[i],INPUT);
    //digitalWrite(col[i],HIGH);
  }

  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Medicine Box");

  //set pins to output because they are addressed in the main loop
  pinMode(latchPin, OUTPUT);

  if (! RTC.isrunning())
  {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }

  for (i=0;i<=4; i++)
  {
    digitalWrite(latchPin, 0);
    shiftOut(dataPin, clockPin, data1);
    shiftOut(dataPin, clockPin, data1);
    digitalWrite(latchPin, 1);
    delay(500);
    digitalWrite(latchPin, 0);
    shiftOut(dataPin, clockPin, data2);
    shiftOut(dataPin, clockPin, data2);
    digitalWrite(latchPin, 1);
    delay(500);
  }
}

void loop()
{

  DateTime now = RTC.now();
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  //lcd.print(millis() / 1000);
  //Serial.println(now);
  //Serial.print("    ");
   /*   Serial.print(now.day(), DEC);
      Serial.print('/');
      Serial.print(now.month(), DEC);
      Serial.print('/');
      Serial.print(now.year(), DEC);
      Serial.print(' ');
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.println(" ");*/

      lcd.print(now.day(), DEC);
      lcd.print('/');
      lcd.print(now.month(), DEC);
      lcd.print('/');
      lcd.print(now.year()-2000, DEC);
      lcd.print(' ');
      if (now.hour()<10)
        lcd.print('0');
      lcd.print(now.hour(), DEC);
      lcd.print(':');
      if (now.minute()<10)
        lcd.print('0');
      lcd.print(now.minute(), DEC);
      lcd.print(':');
      if (now.second()<10)
        lcd.print('0');
      lcd.print(now.second(), DEC);
      //lcd.println(" ");

  for(i=0; i<=3; i++)
  {
    digitalWrite(row[0],HIGH);
    digitalWrite(row[1],HIGH);
    digitalWrite(row[2],HIGH);
    digitalWrite(row[3],HIGH);
    digitalWrite(row[i],LOW);

    for(j=0; j<=2; j++)
    {
      col_scan=analogRead(col[j]);
      if(col_scan < 1000)
      {
        while(analogRead(col[j])< 1000);
        keypress(i,j);
      }
    }
  }
  digitalWrite(latchPin, 0);
  shiftOut(dataPin, clockPin, data1);
  shiftOut(dataPin, clockPin, data1);
  digitalWrite(latchPin, 1);
}

void keypress(int i, int j)
{
  if(i==0&&j==0)
    Serial.println("1");
  else if(i==0&&j==1)
    Serial.println("2");
  else if(i==0&&j==2)
    Serial.println("3");
  else if(i==0&&j==3)
    Serial.println("A");
  else if(i==1&&j==0)
    Serial.println("4");
  else if(i==1&&j==1)
    Serial.println("5");
  else if(i==1&&j==2)
    Serial.println("6");
  else if(i==1&&j==3)
    Serial.println("B");
  else if(i==2&&j==0)
    Serial.println("7");
  else if(i==2&&j==1)
    Serial.println("8");
  else if(i==2&&j==2)
    Serial.println("9");
  else if(i==2&&j==3)
    Serial.println("C");
  else if(i==3&&j==0)
    Serial.println("*");
  else if(i==3&&j==1)
    Serial.println("0");
  else if(i==3&&j==2)
    Serial.println("#");
  else if(i==3&&j==3)
    Serial.println("D");
}

// the heart of the program
void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
  // This shifts 8 bits out MSB first,
  //on the rising edge of the clock,
  //clock idles low

  //internal function setup
  int i=0;
  int pinState;
  pinMode(myClockPin, OUTPUT);
  pinMode(myDataPin, OUTPUT);

  //clear everything out just in case to
  //prepare shift register for bit shifting
  digitalWrite(myDataPin, 0);
  digitalWrite(myClockPin, 0);

  //for each bit in the byte myDataOut�
  //NOTICE THAT WE ARE COUNTING DOWN in our for loop
  //This means that %00000001 or "1" will go through such
  //that it will be pin Q0 that lights.
  for (i=7; i>=0; i--)  {
    digitalWrite(myClockPin, 0);

    //if the value passed to myDataOut and a bitmask result
    // true then... so if we are at i=6 and our value is
    // %11010100 it would the code compares it to %01000000
    // and proceeds to set pinState to 1.
    if ( myDataOut & (1<<i) ) {
      pinState= 1;
    }
    else {
      pinState= 0;
    }

    //Sets the pin to HIGH or LOW depending on pinState
    digitalWrite(myDataPin, pinState);
    //register shifts bits on upstroke of clock pin
    digitalWrite(myClockPin, 1);
    //zero the data pin after shift to prevent bleed through
    digitalWrite(myDataPin, 0);
  }

  //stop shifting
  digitalWrite(myClockPin, 0);
}

My code for shifting doesn't seem working. - this is not a helpful description. What happens? Too many LEDs light up? Too few? They change randomly? The program stops doing anything? "Not working" can mean anything. Try ringing your local garage and saying your car is "not working" - they will soon start asking you if you are having trouble starting it, steering it, if the radio is working, if the tyres are flat, etc.

Why implement your own shiftOut, when it already exists and is more efficient than yours, besides? Theres no need to 'zero out' the data pin after raising the clock HIGH; how do you even know that the register has read the bit you just sent? Read about 'Hold time'.

Your code looks unnecessarily convoluted for merely sending data to a shift register. You can use the SPI hardware for that.
For example:
#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

void loop ()
{
  digitalWrite (LATCH, LOW);
  SPI.transfer (0xAB);
  SPI.transfer (0xCD);
  SPI.transfer (0xEF);
  SPI.transfer (0x42);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop

You have to use the SPI hardware pins for this to work. On a Uno these are:

Chip pin 14 (DS) goes to MOSI  (D11)
Chip pin 11 (SH) goes to SCK   (D13)
Chip pin 12 (ST) goes to SS    (D10)  (or any other pin by changing LATCH)

Example wiring:

More details on my page about the 595 chip.


text:
Should I control each of the four robot wheel separately or wire two from each side together?
I am making a remote controlled Arduino robot. I has 4 DC motors for wheels. I have 2 motor drivers available that control two dc motors each. I was wondering what the downsides are of wiring 2 dc motors together. The DC motors are 6v and the maximum current per channel of my motor driver is 1.2A which should be plenty for the motors. The motor driver that I am using can be found here. Each motor is getting controlled using a PWM signal. The DC motors are controlled separately.

what sort of motor controllers? do they amplify a PWM signal or do they interface over SPI or something else. When you say that each motor controller can control two motors, do you mean that two motors on one controller will always drive the same (as if you Y'd the cables, which would be a good choice, if you want a tank-drive operation) or does each controller control two motors on individual channels?

I added some more info into the question. Each driver controls 2 DC motors individually in both direction and using PWM for speed. @KissMeKimmi

it looks like you have two channels on each controller, so you have some options here. but first I'm going to talk a bit about your motors. If you have a spec sheet for them you can gather most of this info through that, but it doesn't hurt to do some experimentation. A motor will draw max current when it is stalled (is trying to drive but it can't), and you can determine this "stall current" with a multimeter or from the spec sheet. when you're driving the robot, this can occur when you drive up to a wall and try to push through the wall (hint, no robot this size will damage a well built wall) but likely the driver will reach a wall and stop driving (unless she can't see the robot while driving, idk). the lowest current it will draw (aside from zero when it can't...) is it's "free speed" current, this is when it's spinning as fast as it can with no load on it. while you're driving the robot you can expect the current to be between these numbers, if you want to get super fancy (and you want to equip your robot to do this) you could log the instantaneous current every 10ms or however often (this can be useful if you want to diagnose faults, but again its a small robot)... so if you have two motors in parallel (which you want to do because in series one will drive harder than the other), then the current drawn by each will add, so you can double it for two motors.
anyways, here's a few options for the motor configuration:
if two of your motors in parallel draw less than continuous 1.2 amps, you could use a single controller for one robot, controlling left wheels on channel 0 and right on channel 1.
if your motors draw more than that in parallel, you will have to use two channels per side, however you could Y the PWM lines between the motor controller and the arduino
if you are using something like omni wheels and want control over every single wheel, obviously you will want one channel per wheel...