text:
Microphone Data on Arduino to Wav File on RaspPi
Working on an Arduino + Raspberry Pi project and hoping that this question fits into this category. I'm recording audio using a MEMS microphone on the Arduino and transmitting it over to the Pi to store in a playable file (WAV).
What I currently have setup is TCP transmission from the Arduino to the RaspPi. This part is fine and dandy for the purpose of seeing the data transmission that I am looking for.
Where my issue lies, is the audio data being recorded on the Arduino.
At the moment, I see data from my analogRead() function displaying like the following:
2035
2046
2030
2031
2044
2038
2034
2031
2034
2019
2028
2030
2024
2032
2028

My question is, what does this mean? How would I translate this, preferably on the Pi, as usable data that I can store in a WAV file?
Any libraries or hints/clues that can steer me in the right direction would be great.

That's probably not going to work, or at least not well especially if you need to record at decent quality or for more than a fraction of a second without skipping.  Network interfaces introduce substantial packetization latency, and the Arduino doesn't really have enough memory to store data until it can be sent, plus its ADC is fairly marginal for audio quality sampling to begin with.  If you want to stick the with Arduino you may do better with high baud rate serial since that is streaming rather than buffered, but really an Arduino is not the right choice here.

It's difficult to answer this without seeing any code, but I will take a wild guess and assume you are not using any sort of FFT processing on the input. You could try looking into this library. Alternately, people seem to have good luck with this one too.

This is not a meaningful answer to the question asked.  There is no reason to do an FFT as the goal is a .wav file, ie, linear PCM data in the time domain.  Nor is an Arduino fast enough to do a continuous FFT of audio without throwing away the vast majority of the collected information - so even if a frequency domain representation (or alternately filtering in the frequency domain and transformation back) were desired, it would appropriately be done on the pi, not the Arduino.


text:
BLE Mate 2 bluetooth module to Arduino Uno without FTDI SmartBasic
So I'm trying to hook up this BLE breakout board to an Arduino Uno. SparkFun has a hookup guide which seems to be great for someone who has an FTDI SmartBasic that is mentioned in the article. I don't have the SmartBasic board, and would like to see if this is possible without it.
I have hooked up the board to my Uno with the following pinouts:
GRN -> Reset
RXI -> RX (tried with TX as well)
TXI -> TX (tried with RX as well)
VIN -> Tried 5V and 3.3V
CTS -> GND
BLK -> (No Connection)

I use their example code they have provided, uploaded without the RX and TX pins hooked up because, from what I notice, you cannot upload a program through the USB serial when these ports are in use. So after I upload the program through USB, I power the board with a battery and connect the RX and TX pins to the BLE board.
Has anyone either successfully hooked these up without the use of a SmartBasic? I'm a programmer by trade so I do my best to understand this side of the spectrum.

So I found out what I was doing wrong, and want to smack myself for it -.-
The answer was to simply hook up the BLK connection (which I guess is also ground) to a GND pin on the Arduino Uno.
Hope this ends up helping someone out.

source: Stack Exchange

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

sort: votes


text:
Can't send AT comands to ESP8266 on any baud rate
I have problem with baud rate. I have changed baud rate of esp from 115200 to 9600 with AT command AT+CIOBAUD. And everything worked fine until I wanted to change it back and executed command AT+CIOBAUD115200, after which everything I send trough arduino IDE serial monitor to ESP I get gibberish. I have tried all baud rated available in serial monitor but got nothing. Wiring stayed the same.
TX -> arduino RX
RX -> arduino TX
GND -> GND
CH_PD -> 3,3V
VCC -> 3,3V

I thought that if I can flash ESP firmware it will get back all default parameters, hence I tried flow these steps (link) but I stopped when executed esptool.py --port /dev/ttyACM0 erase_flash which got me
esptool.py v1.3
Connecting...................

A fatal error occurred: Failed to connect to ESP8266: Invalid head of packet ('\x00')

In some forums is said that to get rid of error I need to change baud rate, but nothings works for me.
Please advise how can I fix this problem.

GPIO0 has to be connected to ground to enable programming mode.

Yes, during the flashing GPO0 was connected to ground.

authors: Денис Овечкин

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


text:
Data transmission Serial to TCP
I am trying to send numeric data using ESP8266 to local network python server. Before that I am collecting data from sensors using Arduino UNO and then send it to ESP using hardware serial.
ESP8266 code:
#include <ESP8266WiFi.h>

const char* ssid     = "ssid";
const char* password = "pass";

const char* host = "192.168.1.103";

String serial_data;

WiFiClient client;

void setup() {
  Serial.begin(115200);
  delay(5000);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

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

   delay(5000);

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections

  const int port = 8888;
  if (!client.connect(host, port))
  {
    Serial.println("connection failed");
    return;
  }

}

void loop() {

  delay(200);

  while(Serial.available() <= 0)
  {
    //wait for arduino serial data
  }

  if(Serial.available()>0)
  {
    // This will send data to client via TCP
    Serial.println("Sent..");
    serial_data = String(Serial.read());
    client.print(serial_data);
  }
}

Python Server code:
import socket
import sys
from thread import *
from peewee import *

db = SqliteDatabase("data.db")

class post(Model):
    timestamp = DateTimeField()
    current = TextField()

    class Meta:
        database = db

#connecting to database
def initialize_db():
    db.connect()
    db.create_tables([post], safe = True)

initialize_db()

HOST = '192.168.1.103'
PORT = 8888 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

s.listen(10)
print 'Socket now listening'

#keep talking with the client
#Function for handling connections. This will be used to create threads
def clientthread(conn):
    #Sending message to connected client
    conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string

    #infinite loop so that function do not terminate and thread do not end.
    while True:

        #Receiving from client
        data = conn.recv(1024)
        print data

        #send data to database
        post.create(
            current = data
        )

        reply = 'OK ->' + data
        if not data:
            break

        conn.sendall(reply)

    #came out of loop
    conn.close()

#keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])

    start_new_thread(clientthread ,(conn,))

s.close()

After powering up ESP it successfully connects to server and then simulating arduino esp serial communication I am using serial monitor to send some numbers. Before I send anything server outputs number 240:
Connected with 192.168.1.100:26137
240

Then I am sending number 1 but on server terminal I get numbers 49 and 13. Sending numbers some 2 - 3 times and no more data are outputted to server terminal. Should I parse data received from serial to some form I can transmit it via TCP or data should be processed on server side?

The numbers are ASCII Codes (here is a chart from the Arduino website). 49 is the number 1, and 13 is a carriage return ('\n'). There should be a setting in the bottom right corner of Serial Monitor to change line ending, this should be set to "no line ending." If it is, than client.print() must be adding the carriage return, so you will need to remove it in Python. If you are only sending integers, replace
serial_data = String(Serial.read());

with:
serial_data = String(Serial.parseInt());

In the Python code I suggest adding a print statement to check if the connection is closed after
#came out of loop
    conn.close()

Thank you. But can you also explain why after sending number 1 to server it prints 3 times these values 49 and 13 but after I can send anything and server receives nothing?

Is the connection being closed, or is it just not receiving anything?


text:
ESP8266 problem with recieved data trasmission via TCP
I am having small project where I want to read couple of analog inputs from Arduino UNO, send it via software serial to ESP8266-01 and from that to python server using TCP.
Data is sent to ESP using this code on Arduino UNO
#include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX
    int pin = 5;

    void setup() {
      mySerial.begin(9600);
      delay(20000);
    }
    void loop() {
      delay(1000);
      int data = analogRead(pin);
      mySerial.println(data);
    }

Code on ESP is bellow
void loop() {
    while(Serial.available()>0){
    char data = Serial.read();
    client.print(data);
    }
}

When data is sent to Python server, it prints it out but data is sent in two seperate parts, so it always looks like this
9
59

, but number sent from arduino is just 959!
Python server code snipet:
while True:

        #Receiving from client
        data = conn.recv(1024)

        print data

        #send data to database
        post.create(
            current = str(data)
        )

         if not data:
            break

So the question is, why data sent to server is separated in two parts? Maybe it have to do something with how data is reading from serial on esp?

Suspect the problem to be with the python code. We'd need a complete minimal verifiable example of it.

Python server code can be found in link

read() in a loop to a buffer, then print() all in once go; the extra read delay might be hampering you

You assume all 5 bytes of 959\r\n are received by the server at the same time. The data is sent byte after byte, based on the client.print(data) in the ESP code and assuming the underlying library doesn't buffer bytes before transmitting, so there's no way they'll arrive at the server simultaneously. Most likely, your first pass with conn.recv(1024) grabs the first byte 9 and times out. And then on the second pass, the others (at least 2) arrive and are read. The newline between the packets is typical Python 2 print behaviour.
What you need to do is parse the data at the server. Basically read data till you get CRLF i.e. \r\n, which is a good enough delimiter and you're sending it already anyways, and then use that to know when to write to your database.


text:
Applause reactivity
I'm making a pretty basic light circuit and I'd like to have it react to applause or laughter, but NOT during regular speech, amplified over speakers.
I'm wondering if anyone has already made a function for this that I could use in this design!
Your help is greatly appreciated! Thanks for being awesome people who help educate, assist, and elevate others in their creative journeys. You're the best!
Ryan

Hi Ryan, welcome.  I can see why you asked this question on here, but I think you would get a better response if the question was asked on the Electronics Exchange forum because its something someone may have done on a none Arduino platform that you could port.  If you agree then flag the question for moderator attention and ask them to move it.  (Don't cross-post, its like poking a wasps nest!)

You could try the following:  get a sound frequency specific to the applause, convert it with an analog signal and filter it with an Inductor/RC type circuit whose output goes into Arduino for further processing.

Not really an applause detector, but I have written a sound meter
program you could use as a starting point for your own project. It is
available here: Arduino sound meter. It works as follows:

the analog input is read at a constant rate of about 9600 samples per
second, which is normally fine for telephone quality audio processing
the DC offset from the microphone is removed
the readings are squared in order to get the instantaneous sound
intensity; note that this is not immediately usable, as it fluctuates
furiously
this is run through a first order low-pass filter with a time constant
of 26.6 ms in order to get a usable sound intensity reading
the readings are decimated to keep only one every 26.6 ms
they are sent to the PC through the serial port.

The program does not use the analogRead() function, because it is
really not suited for this kind of real-time sampling. Instead, it
directly accesses the ADC, it configures it in the so called “free
running mode” and uses the ADC interrupt to retrieve the samples. This
limits the portability of the program, which has been written for an
Arduino Uno.
If you want to make an applause detector form this, I suggest the
following approach:

Use the program as is, to record and plot the sound intensity as a
function of time.
Test various types of sounds: applause, laughter, speech, noise...
Look carefully at the plots and try to see how the sounds you want to
detect are different from those you do not want: high peaks? short
peaks? fast rise times? You will have to make up some criteria to
tell them apart. This is the most difficult part, as it will require
some creativity.
Write some code to apply your criteria. Keep in mind that your code
will ultimately have to run in real time, i.e. process one intensity
sample at a time. It will not have the whole record to start with.
Test your code on your computer, on the data previously recorded.
Debug, fine-tune... until you are happy with your detection
algorithm.
Modify my sound-meter program: remove the last statement
(transmitting the data to the host computer) and replace it with your
detection code.

Good luck!

This looks pretty great. I think I can work with this. I'm going to plug it in and see what kinds of values I get. From there I may have an output signal trigger an Arduino Nano running the code for the Neopixels. Touching interrupts in a program running Neopixels can be a bit problematic. Neopixels require very specific timing and sometimes interrupts can disrupt that signal, as I've found out the hard way. This isn't a bad thing though. One development of our project is that we may be putting it onto multiple boards. We could have a Nano for each independent board. This would work splendidly

I'm attempting to recreate the "Sound Sensor Example" project (http://www.arduino.org/learning/tutorials/boards-tutorials/sound-sensor-example), which does use analogRead to detect sound, and operates with a 100 millisecond delay (i.e. 10 Hz sampling). Is this approach totally flawed, or just not suited to detailed analysis of sound waves?

@yoyo: At this rate, you can only reliably sample signals slower than 5 Hz, and you will only get one or two samples out of a clap. Those samples will essentially be random numbers between offset − amplitude and offset + amplitude. Only when they are in the high part of the range will they be identified as a clap. You can probably expect to detect most of the claps, but do not expect the detection to be reliable.

@EdgarBonet thanks for the info. I used the analogRead technique to pretty reliably detect and count claps, but I look forward to using interrupts for more detailed sound analysis.


text:
DC Motor Pinning the Ada Fruit Moto Shield with the Mega2560 R3
I picked up an AdaFruit Motor Shield V2.3 .  The example on the site shows how to code the DC Motor connection
// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2)

What I'm unclear about is how to connect the shield to the mega board.  Which pin on the shield should connect to which pin on the board in order for Motor 1 to run at that speed?

Well because an Arduino Mega2560 is pretty much and UNO with a longer rear end, try seeing the UNO in the MEGA if that makes any sense. Then just put the shield in like a normal shield that you would put on a UNO. Most UNO shields are compatible with MEGAs. Then you just use your shield like if it was on an UNO.


text:
Object Array using Inheritance
I would like to create an array of a generic type so I can use multiple sensors and make my code as extensible as possible.
/*
  Planning for good design. Agent library
  should be able to use more than one sensor.

  The agent's constructor will accept a vector
  of sensors.
*/
class Sensor
{
 public:
  Sensor(){};
};

My implementation class
#include "Arduino.h"

class UltraSonicSensor: public Sensor {
 public:
  /*
    Constructors
   */
  UltraSonicSensor(){};
  UltraSonicSensor(int pin){
    pin_ = pin;
  };
  int Sense(){ return 20;};
  /*
    Measure Distance
   */
  float DistanceMeasure(void);
 private:
  /*
    Class only suppports Metric
   */
  float microseconds_to_centimeters(void);
  int pin_;
  long duration_;
};

#endif // SROBOT_SENSORS_ULTRASONIC_H_

I have tried many, many variations of this code but always the same error
Sensor *sensors[2];

UltraSonicSensor uSensor;
sensors[0] = &uSensor;

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

void loop(){
  Serial.println("starting...");
  delay(1000);
  Serial.println("ok");
//  delay(2000);
//  for (int i = 0; i < sensors.size(); i++) {
////    sensors[i].Sense();
//  }
}

The error is always a variation of
main:10: error: 'sensors' does not name a type
 sensors[0] = &uSensor;
 ^
exit status 1
'sensors' does not name a type

I also used the code for a small replacement vector class but also the same error

You have to do it inside of function:
Sensor *sensors[2];

UltraSonicSensor uSensor;

void setup(){
  Serial.begin(9600);
  sensors[0] = &uSensor;
}

Or directly:
UltraSonicSensor uSensor;

Sensor *sensors[] = {&uSensor};

Don't forget to make method Sense() virtual in the base class and in the inherited classes. Otherwise you'll have to also find out the type of the object and typecast it to correct class pointer before it's use.
class Sensor
{
  public:
    virtual int Sense() = 0; // pure virtual base class
};

// and inherited class:

class UltraSonicSensor: public Sensor {
  public:
    // ...

    // Prototype must be exactly the same, by using override
    // is ensured it actually overrides something from the parent class.
    virtual int Sense() override {
        // ...
    }
    // ...
}

Also the last versions of Arduino IDE supports C++11 standard so you can use range based for loop:
for (Sensor * sensor : sensors) {
    int val = sensor->Sense();
    // ...
}

excellent! Thank you very much the clarification.  Tried it just now and it works

Based on the answer from @KIIV and the Vector class, the below code compiles successfully
#include "Vector.h"
#include "Sensor.h"
#include "UltraSonicSensor.h"
#include "LaserSensor.h"

Vector<Sensor*> sensors;
UltraSonicSensor uSensor;
LaserSensor lSensor;

void setup(){
  sensors.push_back(&uSensor);
  sensors.push_back(&lSensor);
}

void loop(){
  Serial.println("starting...");
  delay(1000);
  for (int i = 0; i < sensors.size(); i++) {
    int val = sensors[i]->Sense();
    // ...
  }
}


text:
ESP8266 TCP connection WiFiClient issue
I am using ESP8266 01 board to send some data via TCP to server on local network. My code is:
#include <ESP8266WiFi.h>

const char* ssid     = "ssid";
const char* password = "pas";

const char* host = "192.168.1.103";

void setup() {
  Serial.begin(115200);
  delay(10);

  // Wifi connection

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

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

   delay(5000);

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int port = 8888;
  if (!client.connect(host, port))
  {
    Serial.println("connection failed");
    return;
  }

}

void loop() {

  while(Serial.available() == 0)
  {
    //wait for arduino serial data
  }

   while(Serial.available())
  {
    // send data to server
    client.print(Serial.read());
  }
}

After chacking code in Arduino IDE I am getting error message:
In function 'void loop()':
espwifitcp1:57: error: 'client' was not declared in this scope
     client.print(Serial.read());
     ^
exit status 1
'client' was not declared in this scope

It appears that if I declare WiFiClient client; inside setup() function it can't be accessed outside it. Do I correctly understand the problem? I have tried to declare object outside setup() and loop() functions but it got even more errors. Any suggestions?

You have declared WiFiClient client; in the scope of setup() only. Move it's declaration to the global scope by placing it above the declaration of void setup()

Or write WiFiClient instead of WifiClient X_X

in the header include WifiClient.h

ESP8266WiFi.h includes WiFiClient.h

authors: игорь теплов

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


text:
Multiple shift registers, 16 bit numbers
Currently working on understanding shift registers and traing to display binary number from 65535 to 0 on a 16 LED's.  Below you can see schematics I am using.

The code I am using is
int latchPin = 8;
int clockPin = 12;
int dataPin = 11;
int numberToDisplay=65535;

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {

    digitalWrite(latchPin, LOW);

    shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay);

    digitalWrite(latchPin, HIGH);
    delay(500);
  }

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 16; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (15 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

Problem is when I change numberToDisplay from 0 to 225, everything works and LEDs are lighted correspondingly (if numberToDisplay=225 all red lights are on). But if numbers are bigger than 225 everything just stops working and nothing lights up.
Thank you in advance

Send an array, then you can handle multiple chips. I have examples on my page about the 595 chip.

Your problem is entirely that you declare val to be uint8_t, instead of uint16_t. You are truncating your data to 8 bits before displaying it. One other note, the 74HC595 has a maximum total drive current of 50mA. Your circuit will draw around 90mA for each of the 74HC595's if all of the LEDs are on. You may want to change the resistors to something bigger (510 Ohm, for example) to avoid this problem. Of course that will make the LEDs dimmer, so it's a tradeoff. Here's your project in 123D Circuits. You can simulate it in the browser and look at the code running in the Arduino there.

I agree with Gerben. But Byte datatype will not help you, since Byte type is an unsigned 8-bit type (the same as uint8_t). Why don't you try this header:
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint16_t val)

Or follow Gerbens idea, just using out of the box shiftOut routine. It shifts 8-bit variables, so you shouldn't need to re-implement the routine.
Regards.

notice the uint8_t val. You are truncating the 16-bit number back to 8 bit.
One way of fixing this is to split the 16-bit number before calling shiftOut.
shiftOut(dataPin, clockPin, MSBFIRST, highByte(numberToDisplay));
shiftOut(dataPin, clockPin, MSBFIRST, lowByte(numberToDisplay));

Great, havent thought about it. Maybe I could change uint8_t val to byte val in this way there could be any lenght of bits, or it don't work that way?

uint8_t val byte are identical (at least in AVR-C), so that won't help.


text:
Serial LED control
Hell0!
I run in small problem. I am try to control LED's by serial port.So I am expect to send "1" and two LED's will start to blink or send "0" and only one LED is constantly lighted up. At first I thought that do-wile will work, Arduino will run do loop while value sent by serial port is "1" or "0". However at first I sent "0" and one LED are lighted, after I send "1" and two LED's are blinking. But when I send "0" again, LED's keeps blinking. What should I change in my code?
const int ledPin2=2;
const int ledPin3=3;
const int ledPin4=4;

void setup()
{

  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);

 Serial.begin(9600);
}

void loop()
{
  while (Serial.available()==0);

  int serialVal = Serial.read()-'0';

  do
   {
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4,HIGH);
    } while(serialVal==0);

  do
    {
      digitalWrite(ledPin4,LOW);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, LOW);

      delay(100);

      digitalWrite(ledPin3, HIGH);
      digitalWrite(ledPin2, LOW);

      delay(100);

  }while (serialVal==1);
};

I don't think you understand how your code is being executed. I would recommend trying the following.
const int ledPin2=2;
const int ledPin3=3;
const int ledPin4=4;
int serialVal;

void setup()
{

  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);

 Serial.begin(9600);
}

void loop()
{
  // If data is available, then read it!
  if (serial.available() > 0)
  {
      serialVal = serial.read()-'0';
  }

  // If serial val is 1, turn on LEd4, turn off Led3
  if (serialVal == '1')
  {
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4,HIGH);
  }

  // If serial val is 0,
  // turn on LED2. Turn off Led3
  // delay for 100ms
  // turn of LED2, turn on LED3
  // delay for 100 ms
  if (serialVal == '0')
  {
      digitalWrite(ledPin4,LOW);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, LOW);

      delay(100);

      digitalWrite(ledPin3, HIGH);
      digitalWrite(ledPin2, LOW);

      delay(100);
  }

}

The reason why your code doesn't work, is once you are within a do while loop, you will not be allowed to exit until the condition is met. If you are not scanning for more serial values within that do while, you will get stuck there forever.
Another reason why you might be confused, is how digitalWirte operates. There is no need to loop over a digitalWrite, as the pin will stay HIGH, or LOW until you change its state. Once you digitalWrite(HIGH) that pin will stay high until it is told to go LOW.

Okay, I just tried your code. If 1 sent by serial then LED3 will light up (HIGH) and will continue to stay on HIGH. After I sent 0 and LED1 lights up and after delay 100ms LED1 turns off and LED2 turns on, but that is all it is not continuing to repeat blinking. Is it possible to loop within last IF statement of your code, so blinking will continue?

That is because serial.available() is a blocking method, when you nest it into a while statement This means that it will not continue in the code until a serial value has been received.
Try this code https://gist.github.com/ericellb/12d7337396f6646ef3f8

If you need anything else, id be glad to help.

This is a good answer, but be careful of your wording. "you will not be allowed to exit until the contition is met", implies break statements don't exist. "serial.available() is a blocking method, when you nest in a while statement", serial.available() does not becoming a blocking method in a while loop, the loop is blocking because of its return value.

Good points BrettAM.

Obviously, the code shown at the moment in this answer will get 3 compile errors (“error: 'serialVal' was not declared in this scope”), at lines 18, 24, and 35.


text:
Motor running slowly when connected to digital pins, but fine with 5V pins
I am trying to connect a Dagu DG01D motor to my Arduino Uno. First I tried connecting the black wire to GND and the red wire to digital pin 7. My code:
void setup() {
  pinMode(7, OUTPUT);
  digitalWrite(7, HIGH);
}

void loop() {
}

When I connected the motor, it wouldn't turn, but would rotate a little when turned in one direction. However, when I connected the red wire to 3.3V or 5V, the motor turned quickly as expected. Why didn't writing HIGH to pin 7 work?
I already verified that I can connect and run code on the Arduino by turning on the LED by replacing pin 7 with 13. I also tried running the same code on a SparkFun RedBoard, with similar results.

An Arduino pin can only supply an absolute maximum of 40mA of current (20mA is recommended). As Ignacio said, your motor requires around 190mA. Use a transistor, to increase the current capability.

No Load Current: 190mA (250mA MAX)

You're not getting that out of a ATmega328P GPIO. Use a driver instead.


text:
How avoid TCP packet fragmentation?
I'm using an Arduino Uno with an Ethernet Shield and the arduino.cc Ethernet library for a custom TCP-based message-exchanging chat-like protocol. Specifically I'm using the Client class with its print()
and println() methods. It works.
But on each single print() or println() call a whole TCP packet is sent. Also if just one byte is printed, a whole TCP packet is sent over the IP layer. I mean there's a lot of TCP packets with very few data inside. In other words there's a big overhead.
For example take this message that my Arduino successfully sends and my server successfully receives:
i-am EEEEEEEE-EEEEEEEE-EEEEEEEE-EEEEEEEE\r\n

The code is the following:
stream.print("i-am");
stream.print(' ');
for (byte i = 0 ; i < SERIAL_CODE_LENGTH ; i++){
  if (  i % 4 == 0 && i != 0 ){
    stream.print('-');
  }
  if (serialCode[i] < 16){
    stream.print('0');
  }
  stream.print(serialCode[i], HEX);
}
stream.println();

All that EE are hexadecimal byte values from an array and they are fine. But I can see from Wireshark that those 42 bytes (that could be fit in a single packet) are sent in 22 TCP packets (one for each print call in my code)!
How can I avoid this fragmentation? Is there a way to use an hardware or software buffer to group data before to send (Nagle's algorithm)?
With other SDKs the data are buffered by default and they're sent when the buffer is full or when an explicit "push" or "flush" call occurs. I checked Client flush method and it looks to be a different beast...

Use a better Ethernet library.

Any suggestions for a better library, @IgnacioVazquez-Abrams?

It is possible to write an ethernet library that buffers directly in the W5100 and uses an efficient SPI interleaving algorithm for transfer. Please see the Cosa W5100/W5200 device drivers for example. https://github.com/mikaelpatel/Cosa/blob/master/libraries/W5100/W5100.hh

To be honest, at the point I'm now with the sketch quite finished, I'm already thinking to replace those stream.print() with a sort of bufferredPrint() and to finalise them with bufferFlush(). But I still ask to myself if there is a better and feasible way to use the hardware buffer of the Ethernet shield and to do not upset the entire sketch.

Have a look at the example sketch CosaShellTelnetServer; https://github.com/mikaelpatel/Cosa-Shell/blob/master/examples/CosaShellTelnetServer/CosaShellTelnetServer.ino You can use this to check the performance difference.

Finally I managed to derive the EthernetClient class to override the write method and to add a sendNow method. In this way I still can:

Use any print method version simply by inheritance;
Pass the BufferedEthernetClient objects to function taking generalized Stream references (functions that can be used also with Serial, Wire, SD...).

Code
#define BUFFER_SIZE 64

class BufferedEthernetClient : public EthernetClient {
  public:
    BufferedEthernetClient();
    virtual size_t write(const uint8_t *buf, size_t size);
    virtual void sendNow();
  private:
    byte buffer[BUFFER_SIZE];
    byte bufferCount;
};

BufferedEthernetClient::BufferedEthernetClient(){
  bufferCount = 0;
}

size_t BufferedEthernetClient::write(const uint8_t *buf, size_t size){
  for (size_t i = 0; i < size; i++){
    buffer[bufferCount] = *(buf + i);
    bufferCount++;
    if (bufferCount >= BUFFER_SIZE){
      sendNow();
    }
  }
  return size;
}

void BufferedEthernetClient::sendNow(){
  if (bufferCount){
    bufferCount -= EthernetClient::write(buffer, bufferCount);
  }
}

Example
I use it in this way:
void printSerialCode(Stream & stream){
  for (byte i = 0 ; i < SERIAL_CODE_LENGTH ; i++){
    if (  i % 4 == 0 && i != 0 ){
      stream.print('-');
    }
    if (serialCode[i] < 16){
      stream.print("0");
    }
    stream.print(serialCode[i], HEX);
  }
}

BufferedEthernetClient client;
...
client.print("i-am");
client.print(' ');
printSerialCode(client);
client.println();
client.sendNow();

I suspect its stream.print() that is causing the problem.  Write the data into a string and then use a SINGLE call to stream.print() to send the data.  It looks like it is trying to send it as soon as possible to prevent delays and this is what is causing fragmentation..

Yes indeed. Anyway I prefer a byte buffer so I do not fear to send zeros (C-style string terminator). I posted my final solution in my answer.

Instead of this, you can join strings into one string by separating with a sign (i.e."-") and then split it into array elements

This is just a duplicate of Code Gorilla's answer from a year and a half earlier.


text:
What are the advantages of "Arduino compatible" boards
There are countless boards called "Arduino compatible board". Some of them have specialized hardware features such as WiFi, SD card readers etc., but most of them seem like plain Arduino copies to me.
Sure, they are a bit cheaper, but for me the price difference doesn't make me favor the money I'd safe over the potential issues I have yet to discover.
Question: What are the benefits (or disadvantages) of Arduino compatible boards (the ones without the "extras") in general? Do you know an Arduino compatible board that you would recommend for some extraordinary features?

Arduino compatible means that you would be able to use the boards directly with the Arduino IDE and you can use most of the libraries and examples that come for the official Arduino Boards.
The official Arduino boards comes with a standard set of features that are infinitely expandable, but sometimes you have constraints for a project and you need a board that you can easily adapt to a project, the compatible boards come handy in those place. For example, you can use Ardupilot to control UAV's and has a lot of sensors on it with a very small form factor but you can still code it with the Arduino IDE, you can use Femtoduino (which is an arduino board the size of a coin) for very small projects.
Another simple reason for using the compatible boards is that a lot times they are cheaper than the official Arduino Boards (see Sparkfun Redboard)
You should be able to use any Arduino compatible boards without any problems but it would be better to go with a reputable supplier rather than a supplier in China to ensure that you get a good board that works without any problems.

While Arduino is an open source system, "Arduino" is a trademarked name and may only legally be used for products from the Arduino's originators or licensed suppliers. Arduino are quite clear about this requirement - see here - Logo and here Trademark
and here What makes an Arduino board an Arduino? and FAQ
As a result, compatible microcontroller boards are legally required to NOT identify themselves as being "Arduinos", so the term "Arduino compatible" is about the most that even an Arduino-identical clone can claim.

As karan notes, some Chinese sourced Arduino compatibles "have issues".
however, I have had no problems at all with Arduino compatibles manufactured and supplied by this Chinese supplier. As well as the basic devices they sell various interface boards (shields) and related equipment. Prices are astoundingly low, free postage is included in many cases (about 2 to 3 weeks delivery time to New Zealand) or you can pay for courier delivery. I buy Nano or Pro-Mini compatibles devices  - usually in batches of 10. As you will see -  Nano compatible costs $US3 each in 10's. Pro Mini compatible is currently $US1.68 each in 10's. !!!
Uno compatible here is $3.80 in 10s.  The voltage requlator may be a different type than than on 'real' Arduinos (but work OK) and versions with a USB-serial bridge IC use a non FTDI IC and you need to source and load the correct (freely available) drivers.
NB: (1) I have NO commercial connection with this company except as a very happy customer.
(2) I'd expect you to have no problems with these or other products from them but I of course have  no responsibility for what they sell.


text:
How to wire up 4-digit 7-segment display?
I have an Arduino Mega and the CL5642BH, a 4-digit 7-segment display. I found very helpful code here, but I don't understand how to wire it up on the breadboard.
The display has 12 pins: 6 on the top and 6 on the bottom. First I guess I need to find out which one is GND.
Then (see the link) there is this code:
int digit1 = 11; //PWM Display pin 1
int digit2 = 10; //PWM Display pin 2
int digit3 = 9; //PWM Display pin 6
int digit4 = 6; //PWM Display pin 8

int segA = A1; //Display pin 14
int segB = 3; //Display pin 16
int segC = 4; //Display pin 13
int segD = 5; //Display pin 3
int segE = A0; //Display pin 5
int segF = 7; //Display pin 11
int segG = 8; //Display pin 15

It's 11 pins, that's the correct amount so far. But how do I wire it up? The pins on the display are in no way labeled.
Note: I'm a software developer, but as far as electronics go, I'm still a beginner.

Datasheet where?

Here: http://www.robotshop.com/media/files/pdf/datasheet-com-09483.pdf, but I don't know how to read it. Also the datasheet shows 8 pins in a row, meaning 16 total pins instead of 12, for whatever reason...

The first thing you do is ask Google for a datasheet.  It tells you: http://www.robotshop.com/media/files/pdf/datasheet-com-09483.pdf
Then you can read the datasheet and find the pin diagram:

That tells you that it is a Common Anode LED display - which means that for each digit all the Anodes (positive pins) of the LEDs are wired together.
Further, all the cathode (negative) pins of the LEDs for the same segments across the digits are connected (that is the cathode for segment A on digit 1 is connected to the cathode for segment A on digit 2, digit 3 and digit 4, etc).
From that you can then infer that you need to provide current for each digit in turn through its common anode pin, and sink current from the segments you want to have lit for the digit that is currently having its current sourced.
The diagram also shows you which pin on the display is for what function - the common anodes are pins 9, 10, 12 and 13, with pin 11 the common anode for the extra dots.
The datasheet also tells you which pin is pin 1 - in this case the one in the bottom left when you have the display facing you and the numbers the right way up.  The pins count anti-clockwise from there, so 2 is to its right and 13 is above it.

By the sounds of it though you may not have the same display as in that datasheet.  If your display lacks the extra dots then it may not have the LEDs on pin 11, and pin 12-13 may be moved down one, so you have 4 commons on 9, 10, 11 and 12 with no pin 13.
So the four digit select pins in your program are wired to pins 9, 10, 12 and 13, and the segment select pins connect to pins 1, 2, 3, 4, 5, 6, and 7.  Don't forget the resistors on all the segment pins to limit the LED current or you will damage the Arduino.
You can do some manual testing of the display by using two wires and a resistor (say 1KΩ).  Connect the resistor to +5V, and one wire to the other end of the resistor.  The other wire you connect to ground.
You then take the loose ends of the wires and try probing pins.  Start with the 5V wire touching pin 9 and connect the other one in turn to pins 1-8 to see if the first digit's segments light up.  Repeat with the 5V wire on pins 10-12.
Edit:
If this (http://mklec.com/displays/7-segment-4-digit-12-pin-common-anode-display) is indeed the same display as yours you can ignore the numbers I mention above and work from the pin numbers on that page.  The same principle applies though, just the pin numberings are different.

This clears things up a lot. And I also found a wiring description. Unfortunately it's in German, but here it is anyway: http://ecotronics.ch.honorius.sui-inter.net/wordpress/2013/multiplexed-4-digit-7-segment-led-display-mit-arduino-ansteuern/

@bytecode77 Don't follow his wiring instructions, they are wrong.  He has 4 resistors, one on each anode.  You need 8 resistors (7 without DP), one on each cathode.

Oh... Well, I'm very confused by now. Do you have some sort of idiot's guide to wiring this display?

@bytecode77 Wires from IO pins to anodes.  Resistor on each cathode. Each resistor to IO pin.

What? Look, I'm really a beginner in electronics. I have trouble with the simplest things. Do you have some sort of guide?

@bytecode77 A guide for connecting a wire between an IO pin and your LED display?

For instance, I don't know which pins are cathode and which are annode.

@bytecode77 Then read my answer. It tells you which pins are which, and how to work that out from the diagrams in the datasheet.

As page 2 of the datasheet shows, there are 5 anode pins (4 digit and 1 aux) and 8 cathode pins (7 segments and 1 DP). Connect the digit lines to the digit anodes and the segment lines to resistors connected to the segment cathodes. The location of pin 1 is shown on the top right of page 2, and as always they go counter clockwise from there. Segments are lit by putting the anode high and the cathode low.

But why does the data sheet show 16 pins when I only have 12?

Probably because that's not the correct datasheet.

@bytecode77: This would appear to be more accurate. The same principles apply, just the numbers differ.

From the datasheet found by Ignacio Vazquez-Abrams:

Now one segment will light up if there is a positive (eg. 5 V) on the anode, and a negative (eg. ground) on the cathode. You need a resistor (eg. 330 ohm) to protect the LED and the output pin.

Hopefully it is clear from the original question which Arduino pins go to which LED pins.

Then the code which I presume you found will have to multiplex the display. That is, it will ground (send LOW) to the appropriate cathode pins for the number of segments it needs to light up (all of them, for example, for the number 8, except the decimal point). And then it will raise to 5 V (send HIGH) to DIG 1. That will make some segments on digit 1 light up. Then it repeats that for digits 2 to 4, fast enough that they will all appear to be on at once.

Apply the pin 1, 2, 3 with 5v from Audrino passing through the resistors. Apply low voltage to pin-a to light up the led, so on so forth.
You can use the multi-meter to confirm the common pins and led pin.
For example touch the pin1 with (+) and pin-a with (-) of the multimeter.
If the pins are correct, led pin-a will light up.
Picture Reference:http://www.circuitstoday.com/voltmeter-using-arduino


text:
How can I play audio from an SD card?
What is the best / simplest way to play audio files from an SD card?
I'm currently working on a sound board, where each button plays a different sound. But I have yet to find the right combination of shields / hardware to do this efficiently.
Is there a shield that supports this directly (SD card -> speaker)? Note that I also need additional pinheads for my buttons to connect to. I think I will be using the Arduino Mega for that purpose.

If all you need is button → sound then you don't need an Arduino at all. There are modules that do exactly that natively.

Are there? I haven't found any yet. Can you point me to one?

https://www.sparkfun.com/search/products?term=trigger

I don't think this will work, because I have 48 sounds and I don't have one button for each sound, but rather one row and one column of buttons that need to be pressed one & then the other...

There are several audio products/shields.  Because you mention "speakers", the first one listed can come with an on-board amplifier to drive speakers directly.  Most shields just give line-out to drive a pre-amp.

Adafruit Music maker shield plays MP3/WAV/OGG from microSD http://www.adafruit.com/products/1788
Adafruit Wave shield plays WAV files on SD card http://www.adafruit.com/products/94
SparkFun MP3 trigger board supports 256 tracks and a serial protocol for running individual tracks. https://www.sparkfun.com/products/11029
SparkFun MP3 shield board plays MP3/WAV/OGG https://www.sparkfun.com/products/10628

Can any of these be triggered with 48 different sounds on button click?

The shields and devices mentioned are for audio playback.  They don't in general handle buttons or inputs (although the SparkFun trigger above handles a smaller number).  Instead, you'd want to handle the inputs with some other method on the arduino (poll your row/column inputs) and then calculate what audio file to play.  Communicate that to the device and it plays.

If you can rig your device to print one of the numbers "1" through "48" based on inputs, getting it to instead play audio with one of the above would be pretty easy.

#include <SD.h>                      // need to include the SD library
//#define SD_ChipSelectPin 53  //example uses hardware SS pin 53 on Mega2560
#define SD_ChipSelectPin 10  //using digital pin 4 on arduino nano 328
#include <TMRpcm.h>           //  also need to include this library...

TMRpcm tmrpcm;   // create an object for use in this sketch
char mychar;

void setup(){

  tmrpcm.speakerPin = 9; //11 on Mega, 9 on Uno, Nano, etc

  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can      be initialized:
    Serial.println("SD fail");
    return;   // don't do anything more if not
     }
  tmrpcm.play("beware.wav"); //the sound file "music" will play each time the arduino powers up, or is reset
}

void loop(){

  if(Serial.available()){
    mychar = Serial.read();

    if(mychar == 'o'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("helpyou.wav");
} else if(mychar == 'r'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("chortle.wav");
} else if(mychar == 'q'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("helpyou.wav");
} else if(mychar == 'p'){
  tmrpcm.play("beware.wav");
}
else if(mychar == 'w'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("impresiv.wav");
}
else if(mychar == 't'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("seekyoda.wav");
}
else if(mychar == 'y'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("sensefear.wav");
}
else if(mychar == 'u'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("strongami.wav");
}
else if(mychar == 'i'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("whyhere.wav");
}
  }

}

This code should be helpful. Make sure you have a SD card reader. You must also hookup the card reader:
3.3v goes to 3.3v on the Arduino UNO (for power)
GND goes to Ground on Arduino UNO
D0 goes to pin 12 on Arduino UNO
D1 goes to pin 11 on Arduino UNO
CLK goes to pin 13 on Arduino UNO
D3 goes to pin 10 on Arduino UNO
Lastly, download an arduino library so it can play audio files.
https://github.com/TMRh20/TMRpcm

Finding code is easy, but the question is more focused on the right hardware.


text:
Programmed device causes issues between computer and ISP
I'm using a Digispark, which is basically an attiny85 packaged with a few other things, as an ISP to program attiny85's. The Digispark is loaded with Littlewire and recognized as an USBtinySPI device on the computer. The target attiny85 to be programmed is stacked on top of the Digispark. All pins are connected 1-to-1, 2-to-2, etc. Programming is done from the Arduino IDE. The tutorial I followed can be found here...
http://digistump.com/wiki/digispark/tutorials/programming
The Digispark uses port 3 (USB-) and port 4 (USB+) to communicate with the computer. There are series resistors and shunt zener diodes on both USB connections. The Digispark schematic can be seen here...
https://s3.amazonaws.com/digispark/DigisparkSchematicFinal.pdf
I have been happily programming attiny85's with this setup, but recently hit a snag. On the target chip, if port 3 or 4 produce an output, the computer will no longer recognize the programmer. The computer will immediately connect to the programmer once the target chip is removed from it's socket. The target chip must be messing up communication between the computer and the programmer.
Curious if I was missing something, I compared my setup with Sparkfun's Tiny AVR Programmer. It seems like a more robust programmer. I thought it might have extra components or something, but it's almost identical. It uses an attiny84 with pins directly connected to an attiny85.
After lots of random guesses, I added series 2.2kohm resistors on ports 3 and 4 between the target attiny85 and the programmer. This solves the problem, but seems like a workaround.
Am I missing something? It seems like a programmer should be able to work without worrying about what the pins on the target device are doing. I assumed poorly, that was the purpose behind the RESET pin. Is there a better solution?

With  the Tiny AVR programmer, the D+ and D- lines are connected to there own input pins on the ATtiny84, see below:

This means that the pins from the target chip do not interfere with the function of these.
Whereas the digistump board has the outputs of the USB connected to pin 3 and 4, these pins are also connected to pin 3 and 4 of the target, as you know,

This means that as soon as you have your outputs active on 3 and 4 these interrupt the function of the USB lines.
By adding the 2.2k you are increasing the resistance before the Zener regulator circuit(thus decreasing the effect of the voltage from the target on these lines) and allowing the main tiny to have 'control' over the bus lines.
This is actual done on the SPI buses as well when a ISP is programming a target, while the target has other SPI chips on the bus, you add series resistors on the SPI bus, as seen below:

The R is usually between 1k - 4k7ohm. So you method is not a workaround, but normal procedure.
Another method to use instead of the resistor would be to cut the traces on the target board for pins 3 and 4, thus preventing it from going back onto the USB line. This is as I see no need to have control over the USB lines from the target.

Am I missing something? It seems like a programmer should be able to work without worrying about what the pins on the target device are doing. I assumed poorly, that was the purpose behind the RESET pin. Is there a better solution?

The programmer only toggles reset when programming, and once the target is flashed with your firmware that uses the same lines as USB and the PC then does not recognize the programmer because of this, the programmer won't be able to issue a RESET to the target, as

the PC can't issue it,
the programmer won't know to do that on its own.

I like your idea of just cutting the traces or adding jumpers. The target chip only needs MOSI, MISO, SCK, and RESET, correct? So, ports 3 & 4 aren't even needed.

@curtis - yes only those four(MOSI, MISO, SCK, RST) are used the other two aren't, it would be nice to have the others if one ever wanted, I was thinking of solder jumpers( cut trace, expose a bit of copper on each), that would be possible if there is space as I don't think a standard jumper would fit.

The target board/socket is connected to the digispark with stackable headers, like an arduino. I'll probably just bend the male pins out that I don't want connected. Sweet, this has been bugging me and it makes sense now. I'd upvote your answer, but can't with only 3 rep.


text:
Battery Status notifier
I am new to Arduino, and I am aware that unlike Raspberry Pi you do not have a full blown OS with many custom applications running concurrently.
I plan to start an Arduino project with an Arduino NANO that will need to be portable, and include batteries. How may I get the battery status information without disrupting the rest of the functionality?

What do you mean "without disrupting the rest of the functionality"?

@AndrewPaes Well. I am new to Arduino, so I dont know if I can run more than one scripts concurrently

Use analogRead to measure the voltage on the battery. You might have to use the internal 1.1V reference to get a good reading.
Don't write any blocking code and the processes won't interfere with each other. That means no long for or while loops waiting for something to complete and absolutely no delay.

To read the battery voltage using the 1.1V reference, you need to put the battery voltage through a resistor divider, to lower the voltage to between 0V and 1.1V. To prevent these resistors from draining the battery too hard, you need to select an appropriate high value. High enough, to not drain the battery to fast, low enough to not get influenced by the sample-and-hold capacitor and the input impedance of the ADC. Adding a small capacitor will also help with high value resistors.

Or, if the battery is powering the ATMega directly you just read the 1.1v reference using the battery as the ADC reference then calculate what the battery voltage must be to give the reading you got for the 1.1v reference.


text:
Is it possible to hookup two ultrasonic sensors to one Arduino Uno unit?
I found a couple of projects using Ultrasonic Distance sensor with Arduino Uno. Is there a way to connect two or more sensors on the same Arduino Uno?

Yes there is. What have you tried? What have you had problems with?

Please help us help you by providing your code showing your efforts.

Well I actually I did not try it yet it's just that I had worries that it might not by feasible so I did not buy any hardware and made the bad decision to ask a question here without trying anything :)

It is possible. Just ping then one after another, or both at the same time.

Yes, it is certainly possible.  There are a few things you need to be aware of:
1)  The Arduino UNO is 5V by design.  Many sensors (not all, but many) are 3.3V devices.  So connecting them to a 5V pin could damage them.  Since you seem to be just starting out, I'd recommend sticking with 5V tolerant sensors.
2)  The Arduino UNO only has so many pins available....obviously.  Different sensors require different amount of pins to 'work'.  For example, a temperature sensor might work with the SPI interface.  Another sensor might require 8 pins.  So if you start running out of pins, you need to think about other challenges like using shift registers, multiplexers, etc.
3)  Don't be afraid to experiment.  I suggest buying a genuine Arduino UNO to support the project.  Maybe buy some cheap Chinese ones to experiment on...in case you fry on of those.
In theory, the sky's the limit when it comes to "how many".  In real life, if you start going over a handful, dozen, etc. then you might want to rethink your design.

You make some useful general points, but Stack Exchange is really about specifics - a specific question, and an answer which specifically addresses it.  Very little of what you have said applies to the actual question asked.

@ChrisStratton you have a point but I guess my question was also too broad

@ChrisStratton people come to Stack Exchange via searching or directly.  Looking for answers.  Sometimes the questions are broad like this one Sometimes they are very specific.  It seems that every day I see more and more examples of people scolding new users, beginners and amateurs.  Many times S.E. is the first response to a Google search.  Yet, when beginners ask, they are told to "Google it" and get down-voted and closed.  I understand that S.E. is about specific questions.  This question seemed specific enough for me. Google brings people here and they are punished, where should they go?

The problem isn't so much the question, as that you didn't answer it.  Very little in your response is even applicable to the actual question, vs some other ones not asked.

I guess I read the question as "is it possible".  My mistake.  But I still stand by my remarks.  Point is, many people come to S.E. looking for generic answers to their generic questions and, apparently, S.E. isn't a place for that.


text:
Does serial speed affect performance of other tasks?
I have explored Google and the Arduino site and this site and cannot find a mention of this, so my guess is that serial is handled by a separate component to the core processing and so different serial communication rates will not affect code performance.
Is this correct?
Where can I find information about how serial passing is handled? For instance, when I call Serial.prinlnt("test"), how does that get to the serial line?

It depends. Serial data is received into, or sent from, buffers (one for sending and one for receiving). If you have a processor with 1024 bytes of RAM or more, then the buffer size is 64 bytes, otherwise it is 16 bytes. (See the HardwareSerial.h file in your distribution).
If the buffer fills up when sending, it will block (that is, the code will wait for the buffer to empty). If it fill up when receiving the extra bytes will be discarded.
If the buffer does not fill up, then the baud rate will not affect performance. That is because data is sent, or received, by an interrupt service routine, in the background.
As a rule of thumb, you can expect data to be sent or received at the baud rate divided by 10. That is because each byte is 8 bits, plus a start and a stop bit (10 bits in total).
So, for example, at 9600 baud you can send 960 characters per second. If you are sending something simple, like a temperature which is 20 bytes, every second, then the baud rate won't affect performance at all. If you are trying to send thousands of bytes per second, it will affect performance, because the Serial.println will probably block once the buffer fills up.

For instance, when I call Serial.prinlnt("test"), how does that get to the serial line?

If the buffer is not full, then "t" "e" "s" "t" are copied into the buffer, and the code returns immediately. If the buffer is full then it waits for it to become not-full.
As an efficiency measure, if you are sending a single byte, and the buffer is empty, then the byte is placed in the hardware register immediately (saving a small amount of time). In this case, if the buffer was empty, "t" would be sent immediately, and "est" would be sent afterwards, as a "byte has been sent" interrupt is raised.1
This is described in the code comments:
size_t HardwareSerial::write(uint8_t c)
{
  _written = true;
  // If the buffer and the data register is empty, just write the byte
  // to the data register and be done. This shortcut helps
  // significantly improve the effective datarate at high (>
  // 500kbit/s) bitrates, where interrupt overhead becomes a slowdown.
  if (_tx_buffer_head == _tx_buffer_tail && bit_is_set(*_ucsra, UDRE0)) {
    *_udr = c;
    sbi(*_ucsra, TXC0);
    return 1;
  }
  tx_buffer_index_t i = (_tx_buffer_head + 1) % SERIAL_TX_BUFFER_SIZE;

  // If the output buffer is full, there's nothing for it other than to
  // wait for the interrupt handler to empty it a bit
  while (i == _tx_buffer_tail) {
    if (bit_is_clear(SREG, SREG_I)) {
      // Interrupts are disabled, so we'll have to poll the data
      // register empty flag ourselves. If it is set, pretend an
      // interrupt has happened and call the handler to free up
      // space for us.
      if(bit_is_set(*_ucsra, UDRE0))
    _tx_udr_empty_irq();
    } else {
      // nop, the interrupt handler will free up space for us
    }
  }

  _tx_buffer[_tx_buffer_head] = c;
  _tx_buffer_head = i;

  sbi(*_ucsrb, UDRIE0);

  return 1;
}

Notice that the byte is not placed in the buffer at all if it is empty, and nothing is being sent.

For more information see my question and answer about serial processing.

Strictly speaking, after discussing this in the comments with Majenko, the interrupt that is raised is really that the hardware "send" buffer is empty. When the send buffer empties then the interrupt is called so that the interrupt code can put a new byte into it.

As an efficiency measure, if you are sending a single byte, and the buffer is empty, then the byte is placed in the hardware register immediately (saving a small amount of time). - actually that's not for the sake of efficiency - that's done so that a TX interrupt can be raised - otherwise you put stuff in the buffer and the TX interrupt never triggers (because there is nothing in the TX FIFO to send) and so the buffer never empties. You need that first manual entry in the TX FIFO to start the ball rolling.

That's not what the comments in the code say (see amended answer). However I agree that a side-effect is that if you go to write another byte, you now know there will be an interrupt from writing the first one. Although I'm wondering now if there could be a race condition. If the code fails that first test (ie. something is being sent) but the sending completes, and the interrupt is processed before the byte is put into the buffer, then that byte may not be sent.

Nah. It enables the Data Register Empty interrupt at the end of write() which, if the transmit buffer is empty triggers the ISR to fill it. If it has triggered during the first if and the buffer has been filled with the last byte in the ring buffer the IF will fail, it will fall through to placing the byte into the ring buffer, and the next time the interrupt fires it will be picked up. If it was the last time the interrupt would fire (empty ring buffer) then the interrupt is re-enabled anyway and fires because the TX buffer is empty.

I'm used to chips with a proper multi-level hardware FIFO, so there's no messing with these silly ring buffers anyway...

Ah, OK, I was looking at the specs for the wrong flag (TXCIEn). What you say makes sense.

However that contradicts what you said before: otherwise you put stuff in the buffer and the TX interrupt never triggers. You agree that the TX complete interrupt is not the important one, but rather it is the TX buffer empty one? I just checked with a test program. There is no TX complete interrupt handler generated. The only thing it is interested in is the TX buffer being empty. Thus your statement that "the buffer never empties" because the "TX interrupt never triggers" is not correct.

Yeah, you can ignore my first bit. I am too used to a different UART system.

No, it affects code performance always. For how much is dependent on used data types, baudrate, tx buffer size.
Data types:

AVR doesn't have hardware floating point operation support. Software support is super slow, so if you want to print some floats, it will be affecting performance a lot (but it's same as just using it).
There is no integer division either (except for bit shifts/rotates which is division by powers of two). So printing bytes, integers, longs in DEC base takes some performance.

Baud rate settings and transmit buffer size:
Sending data over Serial is limited by its speed (baud rate). So if you use common 9600 baud rate you'll be limited by this speed. If you're sending data at higher rate. Transmit buffer gets filled and next write into Serial will be blocked until another character from buffer is sent.


text:
Is there an alternative to soldering to connect boards?
I know that shields are usually soldered to headers so they can be attached to the board with the Arduino. I have a tremor, which makes soldering impossible. Are there ways of connecting PCBs without soldering?
If a concrete example would be helpful, I would like to connect the Adafruit WINC1500 WiFi Shield to a SparkFun RedBoard.

Sparkfun has a lot of sensor boards that use their Qwiic Connect System. Those you can just plug in, and even chain together, with their cables with JST connectors.
Adafruit has their Flora like of products. Mostly tailored to wearables, but with their large connector pads, you can easily connect the board to the sensors wit alligator clips.

It seems to be standard for header pins to not be soldered in, but added separately, in breakouts and shields. You could go to a local maker-space. Those people tend to be more than happy to help solder in a few headers.

Yes, there are ways. There is a system called "Press Fit" where the pins have a bulge in one end of them. This grips the inside of the holes in place of soldering.
A number of companies make them, such as TE Connectivity and Positronic.
Of course, these depend on the holes being just the right size, and finding the right connectors could be tricky... so... your mileage may vary.
But nothing is better than getting someone to solder the pins for you. You could teach one of your younger relatives to solder, for example...

Interesting. I hadn't heard of Press Fit. Thanks for teaching me something new. (voted)

Thank you! I probably will have someone do the soldering for me, but I want to understand the full solution space.

Boards with headers can be connected using jumper wires or hookup wire. If there are no headers then I don't think you will be able to get a reliable connection without soldering.
The RedBoard you linked to uses headers, so you should be able to use jumpers with it, but I suspect you are out of luck with the WiFi shield. You'll probably either need to find a version that is built using headers or ask/hire somebody to solder headers onto it for you.
As for the center portion of the shield you should probably just skip that part and use a breadboard, which uses jumpers or hook-up wires.

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


text:
How can I stop someone from hacking in to my Arduino via Bluetooth?
I am using an HC-05 bluetooth Module. How can I stop someone from pairing with my device by brute forcing the key? Failing that, and if someone does pair with my device, is there a way to authenticate the user? I was thinking of salted hash with a shared secret key. Is there anything better?

Are you thinking that a device could repeatedly try and pair with you by submitting different keys over and over?   I'm not sure about the spec of bluetooth nor maximum allowable key size ... but I'm guessing that you can set a key to be at least 8 bytes in length ... which makes a brute force attack on your device no more or less likely than a brute force attack on any other password protected environment.

Why is your device always accepting pair requests?

@Kolban HC-05 does not take any more than 4 numbers. http://www.tec.reutlingen-university.de/uploads/media/DatenblattHC-05_BT-Modul.pdf

@IgnacioVazquez-Abrams It does not. But with just 10000 pins, it is not hard to brute force. Should I add an application layer security? Nonce / salting / hashing etc?

... But if you're not accepting pair requests then they could try 1000000000 pins and still not get in. Because you're not pairing.

@IgnacioVazquez-Abrams How do I disable pairing on an HC-05?

@LordLoh. what is your end application? Are you really sure that someone will/would want to hijack your device? If so, probably bluetooth is not the most advisable protocol (because the hijacker can just leave the device paired and you won't be able to access it again). Anyway you can't stop someone from connecting, but if there are security issues and you must use bt then encrypt the communication..

Configure your Bluetooth module to AT Command Mode
Then use AT+PIN Command to change the default PAIRING PIN of the Bluetooth Module.
Visit this link for more information about how to configure bluetooth to AT Mode

The question was not how to change the PIN, but whether on not to trust the link layer security? For my application.

In case someone else asks the same question in the future, here's the answer...
Technically speaking, the Arduino cannot be hacked for the simple reason that it doesn't have an Operating System like other devices such as the Raspberry Pi, BeagleBone, Rock64 etc. So in as much as someone might be able to bruteforce the HC-05 pin and get access, there's pretty much nothing else they can do past that point, so my advice to you is that don't stress over it. However I would suggest adding a few security measures to your HC-05 Bluetooth module:

Change the default pin (0000 or 1234) to something else.
Lock the module to connect only to a specific device via the MAC Address and the AT+BIND command.

Cheers!


text:
What is the function of the XBee / USB switch on an XBee shield?
I recently bought an XBee shield (this). The shield has a switch that seems to switch between USB/XBee. However, there is no USB port. What exactly is the switch supposed to do?

it looks like the switch connects / disconnects the XBee to the hardware serial port. And must be disconnected to program the board.

In case someone does ask the same question in the future, this is the explanation for the USB/XBee switch functionality on the XBee Pro Shield V3
The switch serves to connect/disconnect the XBee Pro shield v3 to the Hardware TX->1 & RX<-0 Lines of the Arduino. Moving the switch to the USB side, allows you to disconnect the XBee Pro shield v3 from the hardware serial lines and upload code to your Arduino. If the switch is on the XBee side, this allows your XBee Pro shield v3 to use the TX->1 and RX<-0 lines of the Arduino and if you want to upload code to your Arduino, you would have to remove the shield otherwise it would result in an error trying to upload code.

The Xbee shield has aswitch labled Xbee/USB. This determines how the Xbee's serial communication connects to the serial communication between the microcontroller (ATmega8 or ATmega168 or Atmega328) and FTDI USB-toserial chip on the Arduino board.
In the Xbee position the Xbee module is connected to the RX pin of the microcontroller; and DIN is connected to TX. Note that the RX and TX pins of the microcontroller are still connected to the TX and RX pins (respectively) of the FTDI
chip - data sent from the microcontroller will be transmitted to the computer via USB as well as being sent wirelessly by the Xbee module. The microcontroller, however, will only be able to receive data from the Xbee module, not over USB from the computer.
In the USB position, the DOUT pin the Xbee module is connected to the RX pin of the FTDI chip, and DIN on the Xbee module is connected to the TX pin of the FTDI chip. This means that the Xbee module can communicate directly with the computer -
however, IMPORTANT this only works if the microcontroller has been removed from the Arduino board. If the microcontroller is left in the Arduino board, it will be able to talk to the computer normally via USB, but neither the computer nor the microcontroller will be able to talk to the Xbee module.
THANKS TO RS-COMPONENTS FOR THE DETAILS!!!!!

Better to check connection with tester. I think it switches connection to bluetooth module directly to your PC (with usb serial converter which is on arduino board)  or with arduino microcontroller.

I imagine that the switch has the same functionality as the "serial select" switch on the official Arduino Wireless Shield for XBee modules. Therefore the explanations on the switch settings given there (http://www.arduino.cc/en/Main/ArduinoWirelessShield) probably apply also to your board.

That link doesn't work anymore... "Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline." (from https://stackoverflow.com/help/how-to-answer)


text:
How do I use the additional serial ports on an Arduino UNO R3 clone?

I bought this Arduino clone over eBay. It seems to have an extra SPI and serial ports. How do I use these?

Even without extra ports, you can use multiple devices on a single SPI or I2C port anyway by their chip select lines / device addresses respectively.

UNO means ATmega328. It has always only one serial and one I2C port regardless of how many connectors (or solder pads) it is hooked to. They are just parallel outputs to ATmega pins:

D0 - TX
D1 - RX
A5 - SCL
A4 - SDA
Extra pads are just for user convenience, for easier wiring.

Those are not additional I2C and UART ports, those are additional connectors connected to the normal peripherals. They are used in exactly the same manner as the normal connector.


text:
Can an Arduino Pro Mini interface with a full-sized WiFi shield?
We have an Arduino Pro Mini on a breadboard connected to a 9V battery and a sensor, reading data. We also have a full-sized Adafruit WINC1500 WiFi Shield with PCB Antenna. I would like to know if they can be connected and, if so, how.
I understand that a shield is usually stacked on a similarly sized board, but can we place the shield on the breadboard with the Mini and use jumper wire to connect the necessary pins so the Mini can use the WiFi (actually, we want to write to the SD card on the WiFi shield)? If so, how would we know which pins are used, and would we need to provide additional power? Or is connecting a Mini to a full-sized shield a ridiculous idea?

I would like to know if they can be connected and, if so, how.

Yes.

but can we place the shield on the breadboard

No, the pins are misaligned and won't plug in.

and use jumper wire to connect the necessary pins so the Mini can use the WiFi

Yes - connect the jumper wires directly to the WiFi shield pins.

If so, how would we know which pins are used,

Read the manual or schematic for your WiFi shield. It probably uses the SPI pins plus a few more.

and would we need to provide additional power?

It will need a power connection, yes - though "extra" power? Not sure what you mean.

Thanks. By extra power, I meant would I need an additional power source or if the shield could share the 9V battery with the mini.

@EllenSpertus Throw your 9V battery away. It's useless, so don't even start to use it. Use an AA or AAA battery pack.


text:
How do I use two PulseIn() functions simultaneously in Arduino?
I want to connect multiple Ultrasonic sensors to my Arduino board. For that, I need multiple pulseIn() functions to work at the same time. How can I do that?

You can't. pulseIn() is a blocking function that waits for a pulse to arrive before returning.
Instead you will either have to use interrupts or (where available) Input Capture peripherals.
However, using multiple ultrasonic sensors at the same may not make sense. Unless you take great care with your physical design you will get interference between the two.  Echoes from one bouncing around will trigger the other.  For this reason it is normal to not trigger both at once, but to use them sequentially, in which case pulseIn() is still perfectly fine to use.


text:
BASCOM-AVR stk500_2_ReceiveMessage(): timeout: -1
Arduino Uno R3
Windows 10
Bascom AVR
The ON is alright.
The LED flickers now and then.
The RX and TX flickers when I press the program button on Bascom but then disappears almost immediately.
Hello. I have been having this trouble since yesterday. It always appears whenever I click the program button on Bascom. I feel so stupid having to Restart my PC and checking the Device Manager again and again. I am still new to this.
The COM Port is correct and everything else matches. I do not know how to solve this. Please help, I have already watched tutorials but they all assume you have great background in programming which I don't.
So I hope you can use easy terms.
Thank you.

I know next to nothing about Bascom, but Arduino Uno R3 does not use an STK500v2 bootloader.  It uses one that avrdude refers to as "arduino", basically a modified STK500(v1) protocol.  The arduinoisp.ino sketch also implements stk500v1.  So if you're using UNO "as a programmer", that is with arduinoisp.ino, it would also not be STK500v2.  STK500v2 has been used in some of the larger arduino "Mega" boards.
So if you have a choice of programmer, it would be "arduino" or perhaps "stk500(v1)" at 115200 baud.  If you are choosing an arduino board, it sounds like you have an Arduino Mega type board selected rather than the UNO.  If you are using arduinoisp.ino sketch, it would be stk500v1 at 19200 baud.

Have you tried a different USB cable?
I was having trouble flashing and the cable turned out to be the issue.


text:
Vibration sensor for arduino
I need vibration sensor for my project. I have found many sensors similar to this one. But it seems, that this sensor outputs only zeros for "non-hit" state and ones for "hit state". And I need something that can output levels of vibration, not only presence/abscense.
So is there any high-resolution vibration sensor for arduino?
Thank you!

The search term you are looking for is: "Accelerometer".  A common one is the ADXL345

Using the sensor, you can write the software that checks the amount of on's per second, effectively giving you the frequency of the vibration.

But are you looking to get the amplitude? (Intensity of the vibration)

Sounds like a dedicated Arduino would be necessary to gather this information and process it, then send it to another for the ultimate utilization.

I assume the OP wants the frequency of the vibration, which an accelerometer such as the ADXL345 won't give.
I have two workarounds: if the expected vibration frequency is low, say, under 100Hz, use instead an on/off vibration sensor (adafruit has them for under a dollar) and count the number of transitions. If it's more, how about a microphone and a band-pass filter?

That would seem to require that the Arduino has nothing else to do but count pulses.  Maybe one could do that part of the job then feed the results to another.

The MPU-6050 is a very low-price 3 axis gyroscope and accelerometer with both SPI and I2C interface options.
I found mine here:  https://smile.amazon.com/gp/product/B00KKR9ORI

EDIT:  Removed statement that it is accurate enough for this, based on comment.

The MPU-6050 is horrible for detecting vibrating motion. It is so innacurate! This module shouldn't be used for the purpose of the person's project.

Message received.  Thank you for handling this as a comment.  I added an edit to this effect.


text:
Arduino freezing with OLED display
I have a 0.96" OLED display hooked up to my Arduino Mega via SPI. I installed the Adafruit library and GFX library. I can run through the little graphical demo from Adafruit just fine as well as display static text with no problem.
However, I am trying to put together a project I thought would be simple and straight forward. I am trying to use a DHT22 to collect temperature and humidity and then display it on the OLED. The problem I am running into is that the Arduino freezes after an indeterminate amount of time. The most it has been able to run is about 6 minutes.
Here is the code I am using:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>

#define DHTPIN 7
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

// If using software SPI (the default case):
#define OLED_MOSI   8
#define OLED_CLK   9
#define OLED_DC    10
#define OLED_CS    11
#define OLED_RESET 12
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

#define LOGO16_GLCD_HEIGHT 16
#define LOGO16_GLCD_WIDTH  16

#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

long previousMillis = 0;
long interval = 5000;

    String temperature;
    String humidity;

void setup(){
  dht.begin();

  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);

  // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
  display.begin(SSD1306_SWITCHCAPVCC);

  display.clearDisplay();

  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0,0);

  display.println(" Madgayrah");
  display.display();
  while(millis()<2000);
}

void loop() {

  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;

    float h = dht.readHumidity();
    float f = dht.readTemperature(true);

    if(isnan(h) || isnan(f)){
      int x = 6;
      String dashes = "";
      for(int y=1; y<=x; y++){
        dashes += "-";
      }
      temperature = humidity = dashes;
    }else{
      temperature = String(f)+(char)248;
      humidity = String(h)+"%";
    }

    display.clearDisplay();
    display.setTextColor(WHITE);
    display.setCursor(0,0);

    display.setTextSize(1);
    display.println(String(previousMillis/1000));
    display.println("");

    display.println("Temperature:");
    display.setTextSize(2);
    display.println(temperature);

    display.setTextSize(1);
    display.println("Humidity:");
    display.setTextSize(2);
    display.println(humidity);

    display.display();
  }
}

In my attempt at debugging I discovered that NOT printing out the temperature and humidity variables allows the program to run indefinitely. However, for some reason turning on either one of those lines and printing out that variable leads to the issue of the Arduino freezing.
ADDITIONAL INFORMATION:
I am using a 12 volt external power supply hooked up to the barrel of the Mega. The Mega is providing 5 volts and ground to a bread board which powers/grounds both the OLED and the DHT22.
Any ideas as to what could be causing the freezing issue on what "should be" a simple and straightforward project? Thanks.

How much current does the OLED pull?  It may be too much to pull through the Arduino.  It may need it's own power.

having a problem where even with watchdog the device never recovers until i unplug the LCD

Because your program uses various String objects in several different sizes, there's a good chance that heap memory (in RAM) is getting fragmented to the point that String allocation begins to fail, or begins to allocate on top of stack variables.  (Typically, heap and stack work toward each other, from opposite ends of memory that is free after static variables are allocated.)
For example, the code for(int y=1; y<=x; y++){ dashes += "-"; } with x=6 creates half a dozen String objects, all of different lengths.
To avoid this problem, you could carefully release each heap allocated object when done with it, or more effectively, could avoid using String objects, which actually aren't needed in this program.
For example, instead of display.println(String(previousMillis/1000)); say display.println(previousMillis/1000); and instead of building dashes a character at a time before using it, just say "------" in place of dashes.

I had exact same problem and james's answer helped me realize the problem is related to heap memory.
In addition to what he has already commended, I found here that you should also wrap all your constant strings in F() function.
For example instead of
display.println(" Madgayrah");

You write
display.println(F(" Madgayrah"));

This will store the string in the flash memory instead of SRAM.
Also if you only use OLED display for printing text, I strongly recommend the more lightweight SSD1306Ascii library
It output text to oled display without buffering which causes slight flickering but massively reduce the amount of memory required to drive the OLED.
Another helpful tip is to use arduino's watchdog. Basically after you enable that you need to constantly call wdt_reset(); function and if you failed to call it for certain amount of seconds, arduino will automatically reset.


text:
Can't burn arduino bootloader to atmega8a with usbasp
I want to burn the arduino bootloader with arduino IDE, but I cant get it done. And here  is my circuit:
I have marked the way I connect the ISP port and the chip.

I choose Arduino NG/older as the board and Atmega8 as the processor, but when I start to burn the bootloader to the chip the LED on the usbasp just blink once and an error was given:
Arduino:1.6.5 Hourly Build 2015/05/15 06:16 (Windows 7), 板："Arduino NG or older, ATmega8"

avrdude: warning: cannot set sck period. please check for usbasp firmware update.

avrdude: error: programm enable: target doesn't answer. 1

烧录引导程序出错。

avrdude: initialization failed, rc=-1

         Double check connections and try again, or use -F to override

         this check.

What should go wrong? I have check the connection many times and replace a chip as well, and I even add a 12M crystal(with 22pF caps) but things still keep the same.
EDIT
I do the flowing things as advise:

short the jp3 jumper of the usbasp to make a slow commiuncation. And remove the crystal.
I just found the way I connect the isp port might be wrong. so I changed it as flowing

And my actually circuit is like this:

But got no luck, things still the same :-(

Did you set the SLOW SCK jumper on the USBasp Programmer? Completely new ATMegas use the internal RC-Oscillator at a frequency of 8MHz, but the divide clock by 8 fuse is set too. That means that (before burning the fuses) the AVR is running at a clock frequency of 1MHz and the standard SCK clockrate of the USBasp is too high for this clock frequency. Therefore, you need to set the SLOW SCK jumper to get a lower SCK clockrate.

You forgot the Pull Up resistor for Reset.
Using 12Mhz crystal is not a good idea because the Atmega8 config probably uses 8Mhz or 16Mhz, and the fuses which are burned during the bootloader process (yes, they burn fuses first, and THEN load the bootloader) will not expect there to be a 12Mhz crystal, so any further communication can fail because of this too.

USBasp actively drives the reset line, and ISP doesn't require the bootloader to run.


text:
Will 5V 2A current input to the power port kill my Arduino?
I want to power my Arduino with a mobile charger, the out put is 5V 2A, will it kill my Arduino? And what's the max input current as power source?

No, and whatever the device requires at any one moment in time.

"I want to power my arduino with mobile charger the out put is 5v 2apms will it kill my arduino?"
No! It won't. Even tough the reason has been already explained in this other post, I want to add something.
First of all, your question is really common among the ones who, like you (and me), have little/none electrical/electronic knowledge: if you ask such a question, it means you lack the "basic". This is perfectly ok, as we're here to learn "Arduino"... and this (typically) means we're here as the first step towards the electronic world. This is the very reason why I'm writing this answer. So... back to your question....
You're missing a key point, here: the maximum current that your power supply can provide.... is a maximum! And this does NOT means that such a maximum will be given always, and regardless of the devices connected to it!
In other words:

if you have a device that requires a very little amount of current to properly operate (as an example, this DHT22 sensor, requires as little as 2.5mA, or 0.0025 A) and connect it to your 2A power supply, what will happen is that along the wire from your power-supply to the DHT22 will flow only 0.0025 A of current;
if you have 100 (one hundred) DHT22 connected in some exoterical network/schematic, each one requiring 2.5mA of current, in order to power the all of them, concurrently, you need 2.5mA * 100 = 0,25A (or 250mA), that means that again, your power-supply, will be more than enough (to power the all of them, concurrently);
if you have 1000 (one thousand) DHT22, than you'll need 2,5A (or 2500 mA) and... if you need to power the all of them, concurrently, and if you need to stick with your power-supply (capable of "only" 2A)... you'll have problems, as your power supply will not be able to provide the amount of current required by your equipments (Which kind of problems you'll encounter is a matter for a different question!)

To be more specific:

a common/base Arduino MEGA, without any external component connected, requires around 170mA of current;
an common/base ethernet shield, requires 180mA of current;

So, if you plug your 2A power-supply to the USB socket of a MEGA which has an Ethernet shield mounted on its top, than your power-supply will have no problem at all in powering such two devices (as they jointly requires 350mA of current).

you'll be able to power up to 6 of those MEGA+EthShield, as 6 x 350 = 1900mA, which is lower than 2A. Anyway, it's common practice to not require the maximum! It's good-style to not exceed 75/80% of the maximum, as sometimes, based on the quality of your power-supply, some "strange" things start happening when reaching the top!

In the above discussion we talked about "current", without taking into account the "voltage". Anyway, "voltage" is another key-point as "voltage" and "current" are strongly related.
In your OP you mentioned "mobile charger ... 5V" so I bet that you've an USB power-supply, rated at 2A/5V.
People starting playing with Arduino, should use such 5V power-supply to power Arduino trough the USB socket: it has been designed exactly to be connected to a 5V power source, being it an ad-hoc power-supply (with an USB termination) or an USB cable connected to a computer. As for this last case (a computer), please note that:

as for the USB2 specification, every USB2 "host" should be able to provide at least up to 500mA of current at 5V;
as for the USB3 specification, every USB3 "host" should be able to provide at least up to 900mA of current at 5V;

So, supposing you have an USB2 port on your PC and that you connect an USB "simple hub" (an hub without an explicit power-socket) to such port, you can connect only one MEGA+EthShield as this will require 350mA (of the 500mA available). If you have an USB3 port, you can connect 2 of them (and you can also try with three... but with unexpected results).
As for voltage, please note that you can power a tipical Arduino (eg: UNO or MEGA) also via a barrel-jack, providing a voltage inline with what specified by official documentation:

[...]
  The board can operate on an external supply of 6 to 20 volts. If
  supplied with less than 7V, however, [...] the board may become unstable. If using more than 12V,
  the voltage regulator may overheat and damage the board. The
  recommended range is 7 to 12 volts.
  [...]

The above statement introduce the "voltage regulator". This is another key-component that you should be familiar quite soon. At a very high-level, think to the "voltage regulator" as a magic box that:

from one side (the external world) receive a not-so-stable-and-clean current, flowing in the range 7V-12V;
apply some "magic" to such a current and bring it down _to_a_very_precise_ 5V flow;
provide the resulting 5V potential to the "internal world" of Arduino.

In other words, the voltage-regulator is responsable for providing the exact/constant 5V required by Arduino components, by relying on some "unstable" external current.
You might wonder how is possible to "lower" a 12V "input" to a 5V "output". I really don't know (and, actually, I don't care!). Anyway, a fundamental concept to be kept in mind is that such a reduction will produce "heat"! And the more you lower... the more heat it will produce! And the more current you'll "transform", the more "heat" it will produce! ...and if such heat will not be dissipated properly, chances are high that... something will stop working quite soon!
Having said all the above, please note that I'm well aware that lots of other concepts should have been discussed/introduced and that I have done some big oversimplification in the above description. Anyway, I really think that.... should someone had told me those concepts when I did my first steps in Arduino, my experience would have been shorter (...and easier). Nevertheless... don't blame me if you'll discover that those above will result mostly useless once you'll get slightly expert :-)


text:
combination of arduino uno and mega?
I am new to Arduino. Can I combine Arduino UNO and MEGA in 1 project? Arduino UNO is for audio output and MEGA for LCD display. If I am wrong, is there any ideas how do combine both LCD display and audio output in one microcontroller?

When you want to transport 8 people to a festival you can either use two cars and have 4 in each car, or you can get a minibus and have everyone together in one vehicle. It's often simpler to get a minibus, though hiring one may be outside your budget, so two cars is quite often the norm. The tricky part is to set up some form of communication between the drivers so they can both get to the same place at the same time and find each other.
It is exactly the same with microcontrollers (which the Arduino basically is). You can use one big powerful microcontroller to do everything, or you can split your task between a number of smaller microcontrollers. The tricky part is setting up some form of communication between them so that they can all coordinate what they are doing. Bigger microcontrollers can be more expensive though, and if you already have a couple of Arduinos at your disposal then connecting them together and sharing out different parts of your project to them is a good way of going.
Communicating between the Arduinos can be done in a number of ways, depending on how many Arduinos you are connecting, what kind of data there is going between them, etc. One common method which is well documented is to use I2C (Wire.h) to communicate. This is often chosen because it uses just two wires. For higher speed communication SPI is a good choice, but it requires more pins (4 for bi-directional communication). Of course, you can also connect them together using the UARTs, but on the smaller chips (such as the ATMega328P you get on the Arduino Uno) you only get one UART and that is used for programming, so using that for other things gets tricky.

I think you can manage to find a display that uses only a few pins, like Adafruit 2.2 TFT which has a 3-pins SPI communication.
Then you have a lot of pins left to connect for example an audio shield.
I think this could be done on a single Arduino, you'll just have to find an Arduino board compatible with both audio and video systems you choose.
I only wonder if the audio playing would be suffering from screen refresh if both communications are in SPI.


text:
Arduino UNO and TB67H303HG Ic driver: Wiring question
I would like to control the TB67H303HG (a full bridge driver IC for DC motor
adopting MOS in output transistor) with my Arduino UNO.
This is its datasheet.
I was thinking to connect:

PIN 3 INPUT to Arduino Digital Output 13 and set it to LOW to use the direct PWM mode
PIN 5 Vref to 24VDC
PIN 6 Vcc to 24VDC
PIN 7 STBY to Arduino pin 8
PIN 8 IN1 to Arduino Pin 12
PIN 9 IN2 to Arduino Pin 11
PIN 16 OUT1A and 12 OUT1B in parallel to the Motor
PIN 14 OUT2A and 10 OUT2B in parallel to the Motor
PIN 13 and 17 to GND
PIN 20 Vcc to 24VDC
PIN 22 PWM to Arduino PWM 10

I do not know if I'm wrong, but I think I should use IN1 and IN2 to select the motor spin rotation and the Pin 12 PWM to change the velocity by setting the Arduino pin 10 with the PWM output from 0 to 255. Is it correct?
Can you tell me if the wiring is correct?
Thank you a lot!

The Vref potential should not be 24V. As mentionned in the datasheet:
Vref = 0.3V to 1.95V depending on what you want.

sorry for the mistake, you are right! Thank you for the correction! Do you think the other considerations are OK?

Maybe the pin 23 is to connect with a resistor of 51kOhms ? For the clock


text:
srd-05vdc-sl-c and coil operating time
I'm using Arduino UNO to control an imatic relay board with 16 relays model srd-05vdc-sl-c.
I use all the relays to control some linear actuators and everything is working fine.
My only question is: are the coils used for these relays for continuous use? I mean, can I continue to give power to some coils for more than 30 minutes? Or will they be destroyed?
Should I write a specific Arduino routine to power off all the coils when not used, or can I leave them powered for 30 or more minutes?
I checked the relays and they do not overheat.

You can leave them energized for more than 30 minutes. My 16 year old car with 250,000 km still has the original fuel pump relay. I can't imagine how many hours of continuous use it received over this period of time. The relay in my car is not the same make / model as the relays you are using, so you should check with the manufacture to see if there is a "service lifetime" specification.