text:
How do I make the letters on my Arduino LED matrix scroll faster?
////*************************************************************************
////----------------1.开发环境:Arduino IDE or Visual Studio 2010----------------
////----------------2.使用开发板型号：Arduino UNO          ----------------
////----------------3.单片机使用晶振：16M                   ----------------
////----------------4.店铺名称：大学生电子商铺/小强电子设计  ----------------
////----------------5.淘宝网址：Ilovemcu.taobao.com       ----------------
////----------------        52dpj.taobao.com                ----------------
////----------------6.作者：神秘藏宝室              ----------------
////***********************************************************************

#include <Arduino.h>

//IO配置
#define LEDARRAY_D 5
#define LEDARRAY_C 6
#define LEDARRAY_B 7
#define LEDARRAY_A 8
#define LEDARRAY_G 9
#define LEDARRAY_DI 10
#define LEDARRAY_CLK 11
#define LEDARRAY_LAT 12

#define led 13

#define Display_Num_Word 2              //液晶能显示的汉字个数

unsigned char Display_Buffer[8];
unsigned char Display_Swap_Buffer[Display_Num_Word][32]={0};                    //显示缓冲区
bool Shift_Bit = 0;
bool Flag_Shift = 0;
unsigned char Timer0_Count = 0;
unsigned char temp = 0x80;
unsigned char Shift_Count = 0;
unsigned char Display_Word_Count = 0;

#define Num_Of_Word 33
const unsigned char Word[Num_Of_Word][32] =
{
0xFF,0xFF,0xFF,0x07,0xBB,0xBB,0xBB,0x87,0xBB,0xBD,0xBD,0xBD,0xBB,0x07,0xFF,0xFF,/*"B",0*/
0xFF,0xFF,0xFF,0xC7,0xBB,0x7D,0x7D,0x7D,0x7D,0x7D,0x7D,0x7D,0xBB,0xC7,0xFF,0xFF,/*"O"*/
0xFF,0xFF,0xFF,0x83,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0x83,0xFF,0xFF,/*"I",0*/
0xFF,0xFF,0xFF,0x1F,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0x01,0xFF,0xFF,
0xFF,0xFF,0xFF,0xC1,0xBD,0xBD,0xBF,0xDF,0xE7,0xFB,0xFD,0xBD,0xBD,0x83,0xFF,0xFF,/*"S"*/
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0xEF,0xEF,0xE7,0xD7,0xD7,0xDB,0xC3,0xBB,0xBD,0xBD,0x18,0xFF,0xFF,/*"A",0*/
0xFF,0xFF,0xFF,0x03,0xBD,0xBD,0xBD,0x83,0xB7,0xB7,0xBB,0xBB,0xBD,0x1C,0xFF,0xFF,/*"R",0*/
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0x81,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0xEF,0xEF,0xE7,0xD7,0xD7,0xDB,0xC3,0xBB,0xBD,0xBD,0x18,0xFF,0xFF,/*"A",0*/
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0x83,0xBD,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBD,0x83,0xFF,0xFF,
0xFF,0xFF,0xFF,0x1F,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0x01,0xFF,0xFF,
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0x81,0xFF,0xFF,
0xFF,0xFF,0xFF,0xEF,0xEF,0xE7,0xD7,0xD7,0xDB,0xC3,0xBB,0xBD,0xBD,0x18,0xFF,0xFF,/*"A",0*/
0xFF,0xFF,0xFF,0x03,0xBD,0xBD,0xBD,0x83,0xB7,0xB7,0xBB,0xBB,0xBD,0x1C,0xFF,0xFF,/*"R",0*/
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0xC1,0xBD,0xBD,0xBF,0xDF,0xE7,0xFB,0xFD,0xBD,0xBD,0x83,0xFF,0xFF,/*"S"*/
0xFF,0xFF,0xFF,0x83,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0x83,0xFF,0xFF,/*"I",0*/
0xFF,0xFF,0xFF,0xC3,0xBB,0xBB,0x7F,0x7F,0x7F,0x71,0x7B,0xBB,0xBB,0xC7,0xFF,0xFF,/*"G",0*/
0xFF,0xFF,0xFF,0xBF,0x83,0xBD,0xBD,0xBD,0xBD,0xBD,0xBD,0xBD,0xBD,0xBD,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0xC7,0xBB,0x7D,0x7D,0x7D,0x7D,0x7D,0x7D,0x7D,0xBB,0xC7,0xFF,0xFF,/*"O"*/
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0x01,0x6D,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xC7,0xFF,0xFF,/*"T",0*/
0xFF,0xFF,0xFF,0x18,0xBD,0xBD,0xBD,0xBD,0x81,0xBD,0xBD,0xBD,0xBD,0x18,0xFF,0xFF,/*"H",0*/
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0x81,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0x07,0xBB,0xBB,0xBB,0x87,0xBB,0xBD,0xBD,0xBD,0xBB,0x07,0xFF,0xFF,/*"B",0*/
0xFF,0xFF,0xFF,0x1F,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0x01,0xFF,0xFF,
0xFF,0xFF,0xFF,0xEF,0xEF,0xE7,0xD7,0xD7,0xDB,0xC3,0xBB,0xBD,0xBD,0x18,0xFF,0xFF,/*"A",0*/
0xFF,0xFF,0xFF,0x83,0xBD,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBD,0x83,0xFF,0xFF,
0xFF,0xFF,0xFF,0xBE,0xBD,0xBB,0xB7,0xB7,0xBB,0xBB,0xBD,0xBD,0xBE,0xBE,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0x07,0xBB,0xBD,0xBD,0xBD,0xBD,0xBD,0xBD,0xBD,0xBB,0x07,0xFF,0xFF,/*"D",0*/
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0x81,0xFF,0xFF,
0xFF,0xFF,0xFF,0xEF,0xEF,0xE7,0xD7,0xD7,0xDB,0xC3,0xBB,0xBD,0xBD,0x18,0xFF,0xFF,/*"A",0*/
0xFF,0xFF,0xFF,0x01,0x6D,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xC7,0xFF,0xFF,/*"T",0*/
0xFF,0xFF,0xFF,0x18,0xBD,0xBD,0xBD,0xBD,0x81,0xBD,0xBD,0xBD,0xBD,0x18,0xFF,0xFF,/*"H",0*/
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0xDF,0xD7,0xB7,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xBE,0xBD,0xBB,0xB7,0xB7,0xBB,0xBB,0xBD,0xBD,0xBE,0xBE,0xFF,0xFF,
0xFF,0xFF,0xFF,0x83,0xBD,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBD,0x83,0xFF,0xFF,
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0x81,0xFF,0xFF,
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xFF,0xFF,
0xFF,0xFF,0xFF,0x1F,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0x01,0xFF,0xFF,
};
void setup()
{
    pinMode(LEDARRAY_D, OUTPUT);
    pinMode(LEDARRAY_C, OUTPUT);
    pinMode(LEDARRAY_B, OUTPUT);
    pinMode(LEDARRAY_A, OUTPUT);
    pinMode(LEDARRAY_G, OUTPUT);
    pinMode(LEDARRAY_DI, OUTPUT);
    pinMode(LEDARRAY_CLK, OUTPUT);
    pinMode(LEDARRAY_LAT, OUTPUT);

    Clear_Display();
}

void loop()
{
    unsigned int i;
    for(i = 0;i<30;i++)
    {
        Display(Display_Swap_Buffer);
    }
    Display_Word_Count = Shift_Count/16;                //计算当前显示第几个字
    Calc_Shift();

    Shift_Count++;

    if(Shift_Count == (Num_Of_Word+Display_Num_Word)*16 )               //移动次数
    {
        Shift_Count = 0;
    }
}

//************************************************************
//清空缓冲区
//************************************************************
void Clear_Display()
{
    unsigned char i,j;
    for(j = 0 ; j < Display_Num_Word; j++)
    {
        for(i = 0 ; i < 32 ;i++)
        {
            Display_Swap_Buffer[j][i] = 0xff;               //0=显示  1=不显示
        }
    }
}

//************************************************************
//计算移动数据，存在在缓冲器
//************************************************************
void Calc_Shift()
{
    unsigned char i;

    for(i = 0;i < 16;i++)
    {
        if((Display_Swap_Buffer[0][16+i]&0x80) == 0)                                    //每行第一个字节移位
        {
            Display_Swap_Buffer[0][i] = (Display_Swap_Buffer[0][i] << 1)&0xfe;          //最低位清零
        }
        else
        {
            Display_Swap_Buffer[0][i] = (Display_Swap_Buffer[0][i] << 1)|0x01;          //最低位置一
        }

        if((Display_Swap_Buffer[1][i]&0x80) == 0)                                   //每行第二个字节移位
        {
            Display_Swap_Buffer[0][16+i] = (Display_Swap_Buffer[0][16+i] << 1)&0xfe;            //最低位清零
        }
        else
        {
            Display_Swap_Buffer[0][16+i] = (Display_Swap_Buffer[0][16+i] << 1)|0x01;            //最低位置一
        }

        if((Display_Swap_Buffer[1][16+i]&0x80) == 0)                                    //每行第三个字节移位
        {
            Display_Swap_Buffer[1][i] = (Display_Swap_Buffer[1][i] << 1)&0xfe;          //最低位清零
        }
        else
        {
            Display_Swap_Buffer[1][i] = (Display_Swap_Buffer[1][i] << 1)|0x01;          //最低位置一
        }

        if(Shift_Count%16 < 8 && Display_Word_Count < Num_Of_Word)
        {
            Shift_Bit = Word[Display_Word_Count][i]&temp;
        }
        else if(Shift_Count%16 < 16 && Display_Word_Count < Num_Of_Word)
        {
            Shift_Bit = Word[Display_Word_Count][16+i]&temp;
        }
        else
        {
            Shift_Bit = 1;                      //把字移出缓冲区
        }

        if( Shift_Bit == 0)                                                     //后8位移位
        {
            Display_Swap_Buffer[1][16+i] = (Display_Swap_Buffer[1][16+i] << 1)&0xfe;        //最低位清零
        }
        else
        {
            Shift_Bit = 1;
            Display_Swap_Buffer[1][16+i] = (Display_Swap_Buffer[1][16+i] << 1)|0x01;        //最低位置一
        }

    }
    temp = (temp>>1)&0x7f;
    if(temp == 0x00)
    {
        temp = 0x80;
    }
}
//************************************************************
//num为字数  dat[][32]为字模的名称
//*************************************************************
void Display(const unsigned char dat[][32])
{
    unsigned char i;

    for( i = 0 ; i < 16 ; i++ )
    {
        digitalWrite(LEDARRAY_G, HIGH);     //更新数据时候关闭显示。等更新完数据，打开138显示行。防止重影。

        Display_Buffer[0] = dat[0][i];
        Display_Buffer[1] = dat[0][i+16];
        Display_Buffer[2] = dat[1][i];
        Display_Buffer[3] = dat[1][i+16];

    Display_Buffer[4] = dat[2][i];
    Display_Buffer[5] = dat[2][i+16];
    Display_Buffer[6] = dat[3][i];
    Display_Buffer[7] = dat[3][i+16];

    Send(Display_Buffer[7]);
    Send(Display_Buffer[6]);
    Send(Display_Buffer[5]);
    Send(Display_Buffer[4]);

        Send(Display_Buffer[3]);
        Send(Display_Buffer[2]);
        Send(Display_Buffer[1]);
        Send(Display_Buffer[0]);

        digitalWrite(LEDARRAY_LAT, HIGH);                   //锁存数据
        delayMicroseconds(0.1);

        digitalWrite(LEDARRAY_LAT, LOW);
        delayMicroseconds(0.1);

        Scan_Line(i);                       //选择第i行

        digitalWrite(LEDARRAY_G, LOW);

        delayMicroseconds(100);;        //延时一段时间，让LED亮起来。
    }
}

//****************************************************
//扫描某一行
//****************************************************
void Scan_Line( unsigned char m)
{
    switch(m)
    {
        case 0:
            digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, LOW);
            break;
        case 1:
            digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, HIGH);
            break;
        case 2:
            digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, LOW);
            break;
        case 3:
            digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, HIGH);
            break;
        case 4:
            digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, LOW);
            break;
        case 5:
            digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, HIGH);
            break;
        case 6:
            digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, LOW);
            break;
        case 7:
            digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, HIGH);
            break;
        case 8:
            digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, LOW);
            break;
        case 9:
            digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, HIGH);
            break;
        case 10:
            digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, LOW);
            break;
        case 11:
            digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, HIGH);
            break;
        case 12:
            digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, LOW);
            break;
        case 13:
            digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, HIGH);
            break;
        case 14:
            digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, LOW);
            break;
        case 15:
            digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, HIGH);
            break;
        default : break;
    }
}

//****************************************************
//发送数据
//****************************************************
void Send( unsigned char dat)
{
    unsigned char i;
    digitalWrite(LEDARRAY_CLK, LOW);
    delayMicroseconds(0);;
    digitalWrite(LEDARRAY_LAT, LOW);
    delayMicroseconds(0);;

    for( i = 0 ; i < 8 ; i++ )
    {
        if( dat&0x01 )
        {
            digitalWrite(LEDARRAY_DI, HIGH);
        }
        else
        {
            digitalWrite(LEDARRAY_DI, LOW);
        }

        digitalWrite(LEDARRAY_CLK, HIGH);               //上升沿发送数据
            delayMicroseconds(0);;
        digitalWrite(LEDARRAY_CLK, LOW);
            delayMicroseconds(0);;
        dat >>= 1;

    }
}

reduce any delays as much as practicable - if you've reduced them as far as you can, then you have achieved the maximum speed your code allows - if this isn't fast enough, then use a faster MCU, or perhaps your code can be written better, but this is unknown as the code is almost unreadable as it stands

Start by measuring the update time (microseconds). After that you may consider optimizations, for instance, faster digitalWrite, direct port access, SPI, etc.

You have 30x loop calling Display() that inside a 16X loop calls eight Send() that inside an 8x loop makes three digital writes each taking at least 2us to complete. At a minimum, only digitalWrite takes 180ms in one pass.
Use SPI if possible or search Google for "arduino speed up digitalWrite" , here is a good article on this.
Also unrolling the 8x loop inside Send() like this can spare some ms:
   if( dat&0x01 ) digitalWrite(LEDARRAY_DI, HIGH);
   else digitalWrite(LEDARRAY_DI, LOW);
   digitalWrite(LEDARRAY_CLK, HIGH);               //上升沿发送数据
   delayMicroseconds(0);;
   digitalWrite(LEDARRAY_CLK, LOW);
   delayMicroseconds(0);
   if( dat&0x02 ) digitalWrite(LEDARRAY_DI, HIGH);
   else digitalWrite(LEDARRAY_DI, LOW);
   digitalWrite(LEDARRAY_CLK, HIGH);               //上升沿发送数据
   delayMicroseconds(0);;
   digitalWrite(LEDARRAY_CLK, LOW);
   delayMicroseconds(0);
   ........
   if( dat&0x80 ) digitalWrite(LEDARRAY_DI, HIGH);
   else digitalWrite(LEDARRAY_DI, LOW);
   digitalWrite(LEDARRAY_CLK, HIGH);               //上升沿发送数据
   delayMicroseconds(0);;
   digitalWrite(LEDARRAY_CLK, LOW);
   delayMicroseconds(0);

These lines
    digitalWrite(LEDARRAY_LAT, HIGH);                   //锁存数据
    delayMicroseconds(0.1);

    digitalWrite(LEDARRAY_LAT, LOW);
    delayMicroseconds(0.1);

    Scan_Line(i);                       //选择第i行

    digitalWrite(LEDARRAY_G, LOW);

    delayMicroseconds(100);;        //延时一段时间，让LED亮起来。

Reduce the time in the last one.
I don't think delayMicroseconds(0.1); does anything, nor does delayMicroseconds(0); found elsewhere.
I see individual pins being controlled
#define LEDARRAY_D 5
#define LEDARRAY_C 6
#define LEDARRAY_B 7
#define LEDARRAY_A 8
#define LEDARRAY_G 9
#define LEDARRAY_DI 10
#define LEDARRAY_CLK 11
#define LEDARRAY_LAT 12

You don't say what the hardware is, but I bet you replace writing individual pins with blasting data out serially to a shift register with 8 MHz SPI clock as a way speed things up. Or if you had a '1284P or '2560 board, then you could do port writes also.


text:
Generating random pattern on startup
I'm trying to get an arduino to generate a random pattern in a neopixel grid every time you restart it. But I only get the same number sequence generated each time. What I'm doing wrong?
Here's the sequence that keeps happening: 1110 0000 1101 0011
Here's the code I have so far:
/* ========================== INCLUDES ================================= */
#include "RGB.h"

#include <Adafruit_NeoPixel.h>
#include <Adafruit_NeoMatrix.h>
#include <Adafruit_GFX.h>
#ifndef PSTR
 #define PSTR // Make Arduino Due happy
#endif

/* ========================== NEOPIXELS SETTINGS ================================= */
#define NEOPIN 6
#define MATRIX_W 4
#define MATRIX_H 4

Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(MATRIX_W, MATRIX_H, NEOPIN,
  NEO_MATRIX_BOTTOM + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS + NEO_MATRIX_ZIGZAG,
  NEO_GRB + NEO_KHZ800);

/* ========================== BOARD / GRID STUFF ================================= */

/* coordinates for a 4 x 4 grid
00,10,20,30
01,11,21,31
02,12,22,32
03,13,23,33,
04,14,24,34
*/

int land[4][4] = {};

/* ========================== SETUP AND LOOP ================================= */

void setup(){

  Serial.begin(9600);

  matrix.begin();
  matrix.setBrightness(60);
  matrix.fillScreen(matrix.Color(off.r,off.g,off.b));
  crossFade(off, white, 50, 5);
  drawLand();
}

void loop(){
  matrix.show();
}

/* ========================== FUNCTIONS ================================= */

  void drawLand() {
  for(int row = 0; row < MATRIX_W; row++) {
    for(int column = 0; column < MATRIX_H; column++) {

     land[row][column] = random(0,2);

     Serial.println(land[row][column]);
     if(land[row][column] == 1) {
       matrix.drawPixel(column, row, matrix.Color(red.r,red.g,red.b));
     }
   }
  }
}

It's because an machine running the same program on the same data will calculate the same result. rand() is a pseudo-random generator for that reason. With the same starting value it will create the same sequence of numbers. The only way to get different outputs is to provide different inputs: You have to start rand with a different value each run. You can set initialize rand() by supplying an unsigned int to randomSeed(). But it still needs to be different from run to run for you get different outputs from those runs.
Some devices do this by reading a real-time clock on startup and hashing the result in some way. Another method is to ask the user to press a button or a key and using the response time (and possibly the key, if it's a keyboard) to generate the seed. Counting non-repeating events, like electrical noise or background radiation is another way.
But bottom line: you need different inputs to get different outputs.

I just figured out I needed randomSeed to help it along 5 minutes after posting this. It ain't perfect, but randomSeed(analogRead(A0)); does the trick well.

put a short segment of wire onto the analog pin to increase the max noise value.

Re: previous comments.  You can use a product, sum, and modulus/LSB of analogRead's to make it unpredictable and give somewhat equally probable outcomes.  The timing of multiple analogRead's could potentially affect the randomness.

randomSeed(analogRead(A0)); does the trick well

Better yet, use the lsb of analogreads to seed the random number generator. No repeat patterns any more.

source: Stack Exchange

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

sort: votes


text:
Issue with Embedded Coder Target for Arduino
I am using the embedded coder target for arduino following this: (http://www.mathworks.com/matlabcentral/fileexchange/30277-embedded-coder-target-for-arduino). I am having problem while running the myarduino_blink.slx demo.
My MATLAB version is R2015a, and I am using an Arduino Uno. I ran the file setup_custom_target_arduino.m after changing the relevant directory listing and the arduino version in the m file, and I got the output of Arduino on COM 3, which was correct.
After this, I checked the Simulink Library Browser and I had the Custom C/C++ Target Arduino Library will all its modules. Now when I simulate the model, I get the following error:
Error in S-function 'myarduino_blink/Digital Output':
S-Function 'sfunar_digitalOutput' does not exist
Kindly help me out, what could I have done wrong?

... I think you forgot the error...

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


text:
Ruby and Arduino over Serial
I'm trying to send data over serial and pick it up in a ruby script. I'm using the serialport gem (https://rubygems.org/gems/serialport) as stated in the Arduino docs (http://playground.arduino.cc/Interfacing/Ruby).
My question is, I'm trying to print out some gyroscope data, particularly the x, y, and z. This is what my arduino sketch looks like:
void setup() {
  Serial.begin(9600);
  // ... do some gyro stuff here
}

void loop() {
  gyro.read();

  Serial.print((int)gyro.g.x);
  Serial.print(" ");
  Serial.print((int)gyro.g.y);
  Serial.print(" ");
  Serial.print((int)gyro.g.z);

  delay(500);
}

My ruby script is pretty straight forward as well:
require "serialport"
port_str = "/dev/tty.usbmodemfa141"
baud_rate = 9600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE

sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
while true do
  message = sp.gets
  if message
    message.chomp!

    puts message
  end
end

However, the output that I get is choppy. What I mean by that is that the numbers don't come out as a single line as I intend:
52 9
5
250
 -28
 85
25
9 -5
1 69

Even if I replace it with "Hello World", it'll come out as:
He
llo
Wor
ld

or similar.
Any ideas why? Thanks in advance for any help.

Just use Serial.println() after printing all x y z.

Hey, thanks for replying. I think theres a little confusion as to what the problem is. I've edited the original question to show what the output I'm getting is now. It seems to be printing out on different lines.

The problem is then on your ruby code, as the Arduino program looks OK here.

Is your gyro project publicly available (e.g. on GitHub)?

Firstly, let's look into documentation for Ruby IO#gets:

Reads the next "line" from the I/O stream; lines are separated by sep ...

Secondly, look into documentation for Arduino Serial.print:

Prints data to the serial port as human-readable ASCII text ...

Finally, you don't print new line char \n in your "arduino sketch" above.
I recommend you to use Serial.println in the last line from your sketch:
void setup() {
  Serial.begin(9600);
  // ... do some gyro stuff here
}

void loop() {
  gyro.read();

  Serial.print((int)gyro.g.x);
  Serial.print(" ");
  Serial.print((int)gyro.g.y);
  Serial.print(" ");
  Serial.println((int)gyro.g.z);

  delay(500);
}

Yes Arduino code is fine although your should use println() as a terminator.
I think you should read the message into a tmpMessage var. If tmpMessage is empty then break out the loop otherwise concatenate tmpMessage into the message var.
Then print the message var after the loop when no more data arrives.
It must be ruby inserting the line breaks when you use puts

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


text:
Calculating Angles from MPU6050
I've been playing with a GY521 breakout recently with the MPU6050 chip on it, though i've hit a bit of a problem that I can't quite work out
I know when I rotated the board I rotated ~90 degrees about the Y axis, and using the sensitivity numbers from the datasheet (131) and integrating i've managed to get something that looks believable from the gyroscope, but am having problems with the accelerometer.
From a number of sources, this being one of them, I've managed to get the three equations seen on here, however when I apply them to either the raw or scaled data (as they're scalers is shouldn't make a difference?) I get a set of data that varies from 0 to 90, but only on the X and Z axes, while nothing happens to the Y.
Updated to include code:
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"

MPU6050 accelgyro;

int16_t ax, ay, az, gx, gy, gz;

double timeStep, time, timePrev;
double arx, ary, arz, grx, gry, grz, gsx, gsy, gsz, rx, ry, rz;

int i;
double gyroScale = 131;

void setup() {

  Wire.begin();
  Serial.begin(9600);
  accelgyro.initialize();

  time = millis();

  i = 1;

}

void loop() {

  // set up time for integration
  timePrev = time;
  time = millis();
  timeStep = (time - timePrev) / 1000; // time-step in s

  // collect readings
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  // apply gyro scale from datasheet
  gsx = gx/gyroScale;   gsy = gy/gyroScale;   gsz = gz/gyroScale;

  // calculate accelerometer angles
  arx = (180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
  ary = (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));
  arz = (180/3.141592) * atan(sqrt(square(ay) + square(ax)) / az);

  // set initial values equal to accel values
  if (i == 1) {
    grx = arx;
    gry = ary;
    grz = arz;
  }
  // integrate to find the gyro angle
  else{
    grx = grx + (timeStep * gsx);
    gry = gry + (timeStep * gsy);
    grz = grz + (timeStep * gsz);
  }

  // apply filter
  rx = (0.1 * arx) + (0.9 * grx);
  ry = (0.1 * ary) + (0.9 * gry);
  rz = (0.1 * arz) + (0.9 * grz);

  // print result
  Serial.print(i);   Serial.print("\t");
  Serial.print(timePrev);   Serial.print("\t");
  Serial.print(time);   Serial.print("\t");
  Serial.print(timeStep, 5);   Serial.print("\t\t");
  Serial.print(ax);   Serial.print("\t");
  Serial.print(ay);   Serial.print("\t");
  Serial.print(az);   Serial.print("\t\t");
  Serial.print(gx);   Serial.print("\t");
  Serial.print(gy);   Serial.print("\t");
  Serial.print(gz);   Serial.print("\t\t");
  Serial.print(arx);   Serial.print("\t");
  Serial.print(ary);   Serial.print("\t");
  Serial.print(arz);   Serial.print("\t\t");
  Serial.print(grx);   Serial.print("\t");
  Serial.print(gry);   Serial.print("\t");
  Serial.print(grz);   Serial.print("\t\t");
  Serial.print(rx);   Serial.print("\t");
  Serial.print(ry);   Serial.print("\t");
  Serial.println(rz);

  i = i + 1;
  delay(50);

}

Results:

Strikes me as a little odd, as I was expecting only a rotational change in Y.  Any suggestions?

could you post those code samples?

If I understand your question, the main issues are that the axis don't match up, and z from the accel is not accurate?
with respect to the axis: just swap the values. Rotation math is self-consistent and "correct" in many different permutations. What makes it correct is the set of equations, not any single equation; So, copying equations from one reference frame to another will yield incorrect results even if they were correct originally.
your link addresses this difference:

"Interpreting the diagram at left is a little tricky, since the tilt
  of the X-axis actually shows rotation around the Y-axis, and the
  angling of the Y-axis shows (negative) rotation around the X-axis."

  ary = -(180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
  arx =  (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));

should work better for you
On the second point: accelerometers can't measure yaw, the "z" equation can safely be ignored. that isn't yaw it calculates. Calculating z from the gyro alone should fix your second issue.
Other considerations:

The gyroscope tracking can be made more accurate by using the midpoint rule in your integration
Your code is not integrating the gyroscope's signal with the best estimate of its last position (rx, ry, rz), instead it integrates the gyro with separate numbers (grx, gry, grz). In effect information from the accelerometer is discarded each loop and gyro drift is not corrected for.
Thanks for including those graphs with your code samples =] rotation math is extremely tricky, and graphs help a lot

Thanks BrettM!  I originally had the gyroscope using  the rx, ry and rz values but changed it at some point while playing with the accelerometer numbers,  thanks for reminding me to change it back,  I'd forgotten.  I was also planning to update to using the midpoint,  but had shortened it being a bit lazy.  Thanks again for helping me sort out my original question!


text:
What can I do if I run out of Flash memory or SRAM?
According to the Arduino documentation, the ATmega328 has 32KB of Flash memory for the bootloader + uploaded sketch, and only 2KB SRAM for runtime data. The ATmega2560 has quite a bit more, totalling 256KB and 8KB respectively.
In either case, those limits seem rather small, especially when compared to similarly sized consumer devices, such as smartphones.
What can you do if you run out? E.g. if your sketch is too big, or you need to process a lot of data (such as strings) at runtime? Is there any way to expand the Flash or SRAM?

Try using some variable optimization. Some different variable are discussed here

Use proper scopes for your variables if not already doing so, the compiler will optimize RAM usage for you when variables are unused.

You might actually use a Teensy 3.2 (with Teensyduino Software), which would be comparable to an Arduino. Given that you're running out of RAM/PROGMEM it would mean that you're also likely that what you're trying to do is pushing your Arduino. A Teensy 3.2 is not that much more expensive. but has: 32bit, 72MHz (wtf!?) 256KB FLASH and 64KB RAM and 3x UART. Not more program memory as the ATmega2560, but the RAM and speed increase should suffice.

Optimisation
Low-level programming for embedded systems is quite different from programming for general purpose devices, such as computers and cell phones. Efficiency (in terms of speed and space) is far more important because resources are at a premium. That means the very first thing to do if you run out of space is to look at what parts of your code you can optimise.
In terms of reducing program space (Flash) usage, the code size can be quite difficult to optimise if you're inexperienced, or if you're more used to programming for desktop computers which don't tend to need that skill. Unfortunately, there's no 'magic bullet' approach which will work for all situations, although it helps if you consider seriously what your sketch really needs to have. If a feature isn't needed, take it out.
Sometimes it's also helpful to identify where multiple parts of your code are the same (or very similar). You may be able to condense them into reusable functions which can be called from multiple places. However, be aware that sometimes trying to make code too reusable actually ends up making it more verbose. It's a tricky balance to strike that tends to come with practice. Spending some time looking at how code changes affect the compiler output can help.
Runtime data (SRAM) optimisation tends to be a bit easier when you're used to it. A very common pitfall for beginner programmers is using too much global data. Anything declared at global scope will exist for the entire lifetime of the sketch, and that isn't always necessary. If a variable is only used inside one function, and it doesn't need to persist between calls, then make it a local variable. If a value needs to be shared between functions, consider if you can pass it as a parameter instead of making it global. That way you'll only use SRAM for those variables when you actually need it.
Another killer for SRAM usage is text processing (e.g. using the String class). Generally speaking, you should avoid doing String operations if possible. They are massive memory hogs. For example, if you're outputting lots of text to serial, use multiple calls to Serial.print() instead of using string concatenation. Also try to reduce the number of string literals in your code if possible.
Avoid recursion if possible as well. Each time a recursive call is made, it takes the stack a level deeper. Refactor your recursive functions to be iterative instead.
Use EEPROM
EEPROM is used for long-term storage of things that only change occasionally. If you need to use large lists or look-up tables of fixed data, then consider storing it in EEPROM in advance, and only pulling out what you need when necessary.
Obviously EEPROM is quite limited in size and speed though, and has a limited number of write cycles. It's not a great solution to data limitations, but it might be enough to ease the burden on Flash or SRAM. It's also quite possible to interface with similar external storage, such as an SD card.
Expansion
If you've exhausted all other options, then expansion may be a possibility. Unfortunately, expanding Flash memory to increase program space isn't possible. However, it is possible to expand SRAM. This means you may be able to refactor your sketch to reduce code size at the expense of increasing data size.
Getting more SRAM is actually fairly straightforward. One option is to use one or more 23K256 chips. They are accessed via SPI, and there is the SpiRAM library to help you use them. Just beware that they operate at 3.3V not 5V!
If you're using the Mega, you could alternatively get SRAM expansion shields from Lagrangian Point or Rugged Circuits.

You can also store constant data in program memory, rather then SRAM, if you have SRAM space issues and free program memory. See here or here

Another great alternative to EEPROM is an SD card. It does take up a few IO ports but if you do need a large chunk of space for, say map data or similar, it can be easy to swap out and edit with a custom program on a PC.

People should not be encouraged to use SPI SRAMs or RAM expansions, if they are running low on memory. That's just a waste of money. Choosing a bigger MCU would be cheaper. Beside, the performance could be very poor.
One should first make a ballpark estimation: if the estimated RAM usage is too close to the limit, then you're choosing the wrong board/microcontroller/development platform.
Sure, good usage (storing strings in flash) and optimization (avoiding using some libraries) can be true game changers. However at this point I see no benefits of using the Arduino Software platform.

When you upload your code to your Arduino, say an Uno for example, it'll tell you how many bytes it uses up out of the 32K available. That's how much flash memory you have (think computer hard disk). While your program is running, it's using whats called SRAM, and there is much less of that available.
Sometimes you'll notice your program behaving oddly at a point that you haven't even touched in a while. It could be that your most recent changes cause it to run out of memory (SRAM). Here are a few tips on how to free up some SRAM.
Storing strings in Flash instead of SRAM.
One of the most common things I've seen is the chip running out of memory because there are too many long strings.
Use the F() function when using strings so they are stored in Flash instead of SRAM, since you have much more of that available.
Serial.println(F("This string will be stored in flash memory"));

Use the right data types
You can save a byte by switching from an int (2 bytes) to a byte (1 byte). An unsigned byte will give you 0-255 so if you have numbers that don't go higher than 255, save a byte!
How do I know I'm running out of memory?
Usually you'll observe your program behaving strangely and wonder what went wrong... You didn't change anything in the code near the point where it's messing up, so what gives? It's running out of memory.
There are a couple of functions to tell you how much available memory you have.
Available Memory

Do you know if the F() thing is an Arduino specific function or is it in the AVR libraries? You could consider to mention PROGMEM const ... too.

Also you can use bit structures to further reduce space used by your variables 5eg if you deal with lots of boolean).

In addition to what others have said (on which I fully agree), I would advise to read this adafruit article about memory; it's well written, explains a lot of things about memory and provide hints on how to optimize it.
At the end of the read, I think you would get a quite complete answer to your question.
To sum it up, you have 2 possible optimization targets (depending on where you memory problems are located):

Flash (ie Program Memory); for this, you can:

remove dead code (e.g. any code that is included but not used) and unused variables (that one also helps with SRAM)
factor out duplicated code
remove the bootloader altogether (you can gain between 0.5K for a UNO and 2 or 4K for other Arduino models); this has some downsides though

SRAM (ie stack, heap and static data); for this you can:

remove unused variables
optimize the size of each variable (eg don't use long -4 bytes- if you need only int -2 bytes)
use the right scope for your variables (and prefer stack to static data when possible)
reduce buffers size to the strict minimum
move constant data to PROGMEM (ie your static data will stay in Flash memory and won't get copied to SRAM at program start); that also applies to constant strings for which you can use F() macro)
avoid dynamic allocation if it is not absolutely necessary; you will avoid a fragmented heap that may not shrink even after freeing memory

An additional approach to reduce SRAM usage is also described (but seldom used, because it is a bit heavy when coding and not very efficient), it consists in using EEPROM to store data built by your program, but not used until later when some conditions occur, when data can be loaded back from EEPROM.

Removing dead code-- the compiler is really good about handling this for you- it won't make any difference if you have lots of code that's not ever called. If you accidentally call code that you don't need, then that's different, of course.

There are two things to do if you run out of storage:

Somehow "optimize" your code so it needs less storage; or at least uses less of the particular kind of storage that you ran out of (and uses more of the kind of storage that you still have plenty of). Or,
Add more storage.

There are lots of tips online on how to do the first (and for the vast majority of things people do with the Arduino, the build-in storage is more than enough after "optimizing").
So I'll focus on the second:
There are 3 things that use up flash or SRAM; each one needs a slightly different approach to adding storage:

variable storage: it is possible to expand SRAM, as sachleen has already pointed out.
SRAM, FRAM, and NVSRAM are all appropriate for rapidly-changing variables.
(While in principle you could use flash to store variables, then you have to worry about flash wear-out).
SPI (a serial protocol) is the easiest to connect to the Arduino.
The SpiRAM library works with the Microchip 23K256 serial SRAM chip.
The Ramtron FM25W256 serial FRAM chip (now owned by Cypress) also uses SPI.
The Cypress CY14B101 NVSRAM also uses SPI.
Etc.
constant data that needs to still be there the next time the power comes on: this is almost as simple as expanding SRAM. There are many external EEPROM, FRAM, NVSRAM, and FLASH storage devices available.
Currently the lowest cost per MB are SD flash cards (which can accessed via SPI).
The Ramtron FM25W256 (see above), the Cypress CY14B101 (see above), etc. can also store constant data.
Many expansion shields include a SD card slot,
and several libraries and tutorials support reading and writing to (flash) SD cards.
(We can't use SRAM for this, because SRAM forgets everything when the power goes out).
executable code: Unfortunately, expanding an Arduino's Flash memory to increase program space isn't possible. However, a programmer can always refactor a sketch to reduce code size at the expense of increasing data size and making it run slightly slower. (In theory, you could go so far as translate your entire sketch into some interpreted language, store that version of your sketch on a SD card, and then write a interpreter for that language that runs on the Arduino to fetch and execute instructions from the SD card -- Forth on Arduino, a BASIC interpreter, a Tom Napier Picaro interpreter, some application-specific language, etc.).


text:
Corrupted output from HC-05 Bluetooth module
I have arduino Pro Mini 3.3V version with hc-05 module connected to 3.3V/GND and RXI/TX0 pins. I am then using my android phone to connect to the module. It shows up and pairs fine. Then I use BlueTerm app to view the output. I am seeing output that is occasionally as expected but mostly partially corrupted (characters replaced with random characters).
I am using 9600 baud rate and trasmitting the following:
void serialTransmit(int data){
  // send to raspberry pi or other device(s).
  Serial.print("Serial Transmit: ");
  Serial.println(data); // this is hard coded as "12" for testing
}

I tried switching rx/tx pins around but got same corrupt output. Tried changing baud rate but then it wouldn't transmit anything at all and default rate is 9600 so that was expected.
What could be the cause?

Does it show up as expected when using a computer? Also, I've seen some models with 38400 baud

I don't have bluetooth on any of my pc's yet, could try a tablet but should it matter if it's android or another OS? ebay listing does say 9600 baud rate but will try 38400 later.

Tablet should be fine, just to double check the reading. Could you also try setting the parity bit/etc. on BlueTerm?

Not seeing any such option in BlueTerm or other 3 apps I tried. It does seem odd that I get about 10 lines correctly at the beginning and only then it starts to corrupt.

That's weird...

It's strange that you should get anything at all in one of the  rx/tx configurations. Try changing the test string and confirm that what the few "good" transmissions really are true.

First thing to try:
Connect a 2.2k - 10k resistor from the arduino RX pin (the hc-05 tx pin) to ground.
If that didn't work, I recommend getting everything into a known state and eliminating some complexity. So, first let's remove the Android software from the equation.  And second, let's put the module into a known baud rate.
To do this wire up the arduino and module like this:
Notice that the Key pin is connected to 3.3v.  That will ensure the module is at 38400 baud on power up.
Connect the arduino to your computer with the FTDI cable.  Upload the following sketch:
/* Serial Loop */

#include <SoftwareSerial.h>

#define rxPin 8
#define txPin 9

SoftwareSerial mySerial(rxPin, txPin); // RX, TX
char myChar ;

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

  mySerial.begin(38400);
  mySerial.println("AT");
}

void loop() {
  while (mySerial.available()) {
    myChar = mySerial.read();
    Serial.print(myChar);
  }

  while (Serial.available()) {
    myChar = Serial.read();
    Serial.print(myChar); //echo
    mySerial.print(myChar);
  }
}

With the sketch now uploaded and running, open the Arduino serial console and enter these AT commands. The serial console baud rate should be set to 9600 and line endings should be "Both NL & CR"
AT+ORGL //back to factory settings
AT+ROLE=0 //slave role - transparent serial bridge
AT+UART=9600,0,0 //default baud rate
AT+INIT //init module

You should get "OK" back from the module after each command. If you've gotten this far, we know the module is working fine and we know what baud rate it will default to now.
Hook the module back up the way you had it before.  Make sure 3.3v is disconnected from key pin and make sure you have added the pulldown resistor on the RX line. Cycle the power to the module. The module should start up running 9600 baud, slave mode. Delete the module from the Android pairing list and re-pair it.  The name probably will have changed.  Hopefully it works correctly now.
Cheers

I tried 4.7k resistor but it didn't make a noticeable difference, I assume there's no point in trying different resistor values? Also my module is bale, and has no voltage regulator, does your diagram apply to this situation since the module is rated at at 3.3V. Will need to wait until I receive my new soldering iron to change connections, clamping cables to the module is tedious :)

I think I saw 2.2k recommended, but tried it and worked with 10k.  The diagram applies except ignore the 5v line.  You take 3.3v from the mini pro vcc pin to the BT module VCC and Key pin (pin 34).

Until your soldering iron comes in, try using software serial instead of hardware serial. just move rx and tx on the arduino from 0 and 1 to some other digital pins.  See my code as an example.

If your wires are just clamped(alligator clips?) onto the module, you may just have a loose connection.

I tried software serial but couldn't get any output, will try to get it to work tomorrow. It's not even alligator clips, it's a small hand clamp that's pushing the wires against the contacts on one side :) Connections seem solid though...

Ok, so now I have a new module with breakout board. Connecting is easy now and I have tried connecting it like in your diagram. What I get as output instead of OK is some gibberish. The length seems to change depending on the input length. This is what it looks like: xÿx0þàø (input was AT+ORGL). The corruption is different now in that there is nothing discernible at all. Any ideas?

It sounds like there is a baud rate mismatch somewhere. What settings are you using where? Are you running the same sketch I posted?  Are you using the arduino serial console?

Yes, I am using latest arduino software and the Serial console that come with it. I pasted the same code you posted in a new sketch. What else could I try?

what baud rate setting are you using in BlueTerm?

I tried again on a new breadboard and it worked this time, I think it was interference from another unused device connected to the same pin as serial pins. Not sure what it was last time. Thanks for your help!

I have the same problem with arduino pro mini and HC-06, only change the baud rate of your BTserial port... try diferent baud rates in my case:
Serial.begin(9600);
Serial.println("AT");

BTSerial.begin(2400);
BTSerial.println("AT");

Works fine, it happens because the arduino try to "understand" the module, but if the module speaks other leanguage, the arduino will never understand the command.
like me... sorry for my bad english. se ya.

Add the module as software serial then add these lines to setup() these line tell us the Bluetooth to turn into data mode:
bluetooth.begin(115200);
bluetooth.print("$$$");
delay(100);
bluetooth.println("U,9600,N");
bluetooth.begin(9600);


text:
Why do some pins have a different PWM frequency?
According to the Arduino reference for analogWrite(), the PWM frequency on most pins is ~490 Hz. However, it's ~980 Hz for pins 5 and 6 on the Uno, and for pins 3 and 11 on the Leonardo.
Why are these different? Is it a deliberate design feature, or is it somehow dictated by the hardware?

Those aren't the only frequencies available for the PWM signals. However, they are the frequencies as determined by the applied prescaler (which you can readily change as detailed below).
Each of the 3 pairs of PWM pins is tied to one timer, each of which has its own base frequency, as follows:

Pins 5 and 6 are paired on timer0, with base frequency of 62500Hz
Pins 9 and 10 are paired on timer1, with base frequency of 31250Hz
Pins 3 and 11 are paired on timer2, with base frequency of 31250Hz

Then each set of pins have a number of prescaler values that can be chosen, that will divide the base frequency of that pair of pins. The prescaler values available are:

Pins 5 and 6 have prescaler values of 1, 8, 64, 256, and 1024
Pins 9 and 10 have prescaler values of 1, 8, 64, 256, and 1024
Pins 3 and 11 have prescaler values of 1, 8, 32, 64, 128, 256, and 1024

The different combinations yield different frequencies in a given PWM pin. Notice that timer 2 (tied to pins 3 and 11) have more prescaler values available, resulting in more frequencies available.
Now, why timer 2 is different, that's a separate question.
Edit: Here's a list of possible PWM frequencies per pin (from this article):

For pins 6 and 5 (OC0A and OC0B):

If TCCR0B = xxxxx001, frequency is 64kHz
If TCCR0B = xxxxx010, frequency is 8 kHz
If TCCR0B = xxxxx011, frequency is 1kHz (this is the default from the Diecimila bootloader)
If TCCR0B = xxxxx100, frequency is 250Hz
If TCCR0B = xxxxx101, frequency is 62.5 Hz

For pins 9, 10, 11 and 3 (OC1A, OC1B, OC2A, OC2B):

If TCCRnB = xxxxx001, frequency is 32kHz
If TCCRnB = xxxxx010, frequency is 4 kHz
If TCCRnB = xxxxx011, frequency is 500Hz (this is the default from the Diecimila bootloader)
If TCCRnB = xxxxx100, frequency is 125Hz
If TCCRnB = xxxxx101, frequency is 31.25 Hz

TCCRnB is where you set the prescaler bits for timer n, replacing n by 0, 1 or 2, depending on the timer you want to set. If you are still unsure about bitwise operations, read this bit math tutorial.
My sources:

http://playground.arduino.cc/Code/PwmFrequency
http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM
http://arduino.cc/en/Tutorial/PWM
http://arduino-info.wikispaces.com/Arduino-PWM-Frequency

Note that there seems to be divergence in those sources about whether pins 9 and 10 have the same behavior as 5 and 6 or 3 and 11, but you get the idea anyway. I'm reading the datashet to try and figure out which is correct, or whether this is a difference between boards.

What ATmega does this answer refer to? I didn't check, but I bet it slightly differs per controller.

@jippie Good point! The sources refer to ATmega168 and 328.

@jippie Just to clarify, in my answer, the pin numbers refer to how they are assigner on the Uno board (pin 1 means Digital Pin 1, or D1, for example), not the IC (ATmega328 pin 1 is reset).

I believe those details change too with boards, Uno, Duemilanove, Mega, ...

@jippie Definitely, yes.

This answer is simply wrong. The timers use the same prescaler setting. The only difference is timer 1 and 2 are set to phase-correct PWM, while timer 0 is set to fast PWM, doubling the frequency.

I am not aware of the design considerations, but if you check the datasheet for the microcontroller on your Arduino, you will notice that PWM pins are grouped together and per group connected to a timer. The speed at which this timer is increased varies by the configured prescaler. If you change the prescaler for a certain timer, you change the PWM frequency for the related PWM pins. I believe some timers double for other purposes like the millis(); function. If you change the prescaler for that timer, values returned by millis() will be off by the same factor.
You can calculate the setting for the prescaler as follows:
$$\text{prescaler} = \dfrac{f_{CPU}}{PWMresolution × f_{PWM}} = \dfrac{16\text{MHz}}{256×490} \approx 128$$

prescaler = f[CPU]/(PWMresolution×f[PWM]) = 16000000/(256×490) = approx 128.

Check the datasheet and you'll find that 128 is indeed one of the prescaler values you can select.

Boy, do we miss MathJax or what? I hope we get it enabled after the beta.

@Ricardo I have a MathJax button in my browser ;o)   http://meta.arduino.stackexchange.com/questions/13/is-there-an-easy-way-to-enter-formulas-in-questions/51#51


text:
What are the SVG pins for on the SainSmart Uno clone?
I bought a SainSmart clone board which is compatible with the Arduino Uno R3. Alongside each of the standard IO pins, there is a row of 3 additional pins (male). They are arranged in columns, marked S, V, and G.
They can be seen on this image:

Most of them are immediately above the SainSmart and UNO logos. The SVG pins corresponding to the analog pins can be seen immediately below the microprocessor.
What are these pins for? Is this a standard format for some applications, or is it something unique to the SainSmart?

SVG = Signal, Voltage, Ground.
The Signal pin will carry the actual output, which may be high or low at any given time. It's basically just a male version of the corresponding standard GPIO pin. The Voltage pin will always be high (which can be 5v or 3.3v on this board, depending on the output level switch). The Ground pin is exactly what the name suggests -- it's connected to the board's ground.
This obviously means there is a lot of duplication. Why have two signal pins? And why bother having so many Voltage and Ground pins if they're all the same anyway?
The reason is simply convenience.
If you have a standalone external component (such as a motor), you would normally have to run 3 separate wires to it. With the regularly-spaced SVG pins on the board, you can instead use a 3-way cable with a suitable female header block. You can run that to an equivalent set of 3 pins on the external component. That means you are able to attach/detach the component by plugging/unplugging (effectively) a single cable.
I don't think the SVG idea is a 'standard' as such, largely because (in this form) it's only really of benefit to people who are experimenting or prototyping (as opposed to designing a more permanent system). It seems to be fairly popular among hobbyists and enthusiasts though. You just need to watch out for components which may put their equivalent SVG pins in a different order.

Servos usually have the same pinout so I guess the other benefit is that you can easily plug them in. http://www.imagesco.com/servo/connectors.jpg

Great point. I'd meant to mention servos, but obviously forgot!

This is also useful for plugging potentiometer to analog pins. If you plug the external pot pins to V & G and the middle pin to S, then you have an instant voltage divider.

I should point out that it appears the V pin in this configuration is not powerful enough to drive a standard servo.  This is unfortunate, because it is really convenient to plug a servo directly into this header.  It seems to work at first, but eventually the board will go into an unresponsive state, presumably because it can't drive that much current, or the voltage is fluctuating.  I'm not exactly sure why, but driving the servo off of the Arduino header 5v pin seems to work just fine.  Kind of a bummer.

It's not really a good idea to power a servo of of any pin on an Arduino, as those would either have too high a voltage or be sourced from the logic regulator, and as servos are notoriously power hungry and electrically noise, it is preferable that they not share the same regulator as logic.


text:
How to really shrink a sketch
I want to make a sketch that is as small as possible, for test purposes. The problem is, when i compile the BareMinimum sketch (with an empty setup and loop), i get 466 bytes for the Uno and a whopping 4,242 for the Leonardo. Is there any way to write your own code that has no extra functions (namely Timer0 for millis() and delay()). I would also like to be able to disable the keyboard/mouse functions for the Leonardo.

Shouldn't this be tagged leonardo and not uno (and focus on one board)? These are separate questions.

I'm just pointing out that a blank compiled sketch is large for a lot of boards, especially the native USB based ones

I would also like to be able to disable the keyboard/mouse functions for the Leonardo. is the second question.

You should be able to create your own board definition with a custom boards.txt file as per https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification. As I see there are several usb features in the leonardo's definition. I would hope that the compiles inclusion of the 4K is based off of these flags and not the processor type.
Where the boards.txt would use the upload, bootloader sections from the Leonardo and the build from the uno.
This is all assuming the core library build does not use processor specific flags to include USB functions.
If you get such working. post back, I am sure others would be interested in such.

I recently ran into this 4K used limitation on a library demo that actually maxed out the UNO and had to put in a
#if !defined(__AVR_ATmega32U4__)
...

around a large chunk of extra features in the sketch to fit on the Leonardo.
I had assume (wrong) that this 4K was because I still included Serial.print which when over the USB's CDC on the Leo. But I see after a memory dump of an empty sketch they are still there.
C:\Users\mflaga\AppData\Local\Temp\build8958339595868119500.tmp>avr-objdump -d sketch_feb13a.cpp.elf > sketch_feb13a.cpp.elf.lst

Which makes sense. As the Leonardo still requires the USB-CDC client (the 4K) as to detect the 1200 Baud connect from AVR-DUDE as to stroke the remote reboot.

Hence making a custom boards.txt without USB in the build, also needs to have
leonardo.upload.use_1200bps_touch=true

removed.
Once loaded on the target, this would require the upload to be synchronized with a manual reset of the target. As the ability to remote reboot is lost.

updated as to why 4K is still compiled in, even if Serial.print is omitted.

I recently wanted to do exactly this. Since there is no nice way to do so, I wound up writing a patch for the Stino sublime-text arduino plugin to do exactly this. It's subsequently been accepted, so it should be in any up-to-date Stino installs.
This adds a new option to Stino:

Using this mode produces compilation results like the following:
For a Uno:

Binary sketch size: 172 bytes (of a 32256 byte maximum, 0.53 percent).
  Estimated memory use: 0 bytes (of a 1024 byte maximum, 0.00 percent).

For a leonardo

Binary sketch size: 240 bytes (of a 28672 byte maximum, 0.84 percent).
  Estimated memory use: 0 bytes (of a 2560 byte maximum, 0.00 percent).

Actually programming the leonardo with the above compiled output is probably a bad idea, as it might break the auto-reset functionality, but you could, if you wanted. Hat-tip to mpflaga for noting this in his answer.
Note that the memory reports are actually incorrect, but that's a separate issue.
The code used for the above is:
int main()
{
    while (1)
    {

    }
}

Some notes:

You ain't writing a "Sketch" anymore, not that you ever actually do write a sketch. You write programs. Period. I don't care what the Arduino wackos want to say, they don't get to redefine terms.
All interrupt management is manual. This means no milis() or similar.
You can still use the arduino serial libraries and so forth, if you want. You do have to #include <Arduino.h>.
You define main. You don't ever return from main. If you want setup stuff, it goes before the while (1).

@jfpoilpret You call that an IDE? More like notepad with macros...

@Ron-E I don't call it an IDE, Arduino IDE is its name, so I just used its name, even though it is not worth that name.

@FakeName Bad language isn't permitted on Stack Exchange sites (see: http://stackoverflow.com/help/behavior). I've edited it out in this case, but please try to refrain from using expletives on this site in future. Thanks.

Although it depends on your sketch, you can somewhat decrease the size by reusing code with methods.
Take this code:
int led = 13;
int val;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  val = digitalRead(10);
}

1,322 bytes on Arduino Uno. Now let's shrink it a bit:
int led = 13;
int val;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  for(uint8_t i = 0; i < 8; i++) {
    blink(HIGH);
    blink(LOW);
  }
  val = digitalRead(10);
}

void blink(uint8_t state) {
  digitalWrite(led, state);   // turn the LED to the right state
  delay(1000);                // wait for a second
}

1,194 bytes. That's about a 10% decrease!
Anyway, although it doesn't greatly shrink a sketch, it sometimes can be the easiest route when you are two bytes over the limit, or just want to make a more compact sketch to begin with without loosing any functionality. It's not for every situation, but I find it useful sometimes.

Generally, if you pull code out into functions, the compiler will do the hard work and get the rest right for you.

@Cybergibbons Can you define that [for users that aren't familiar with that]?

If you break out code into a function and it isn't efficient, generally the compiler will in-line it for you. However, a compiler will never break code out into functions. Therefore, it's nearly always better to write  more functions.

Using direct port access, the size is decreased to 646 bytes. Using only avr-libc (no Arduino core), it gets down to 220 bytes.

@annonomus penguin, sure we can
Although the code compiles into 1180 bytes flash + 13 bytes RAM for an uno on my computer, we can improve on it :) so golf challenge accepted and also a few usefull tips since we are in the business of learning.
Step 1: decrease variable requirements.
Using an int for a led port seems a bit overkill, we certainly don't have 65535 addressable IO ports on the arduino :) So we change it to a byte just for the fun of it. We will change it over to a #define later on, but to show the impact of using too large variable types.
byte led = 13;
int val;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  blink();
  val = digitalRead(10);
}

void blink() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

Compiles into 1172 bytes + 13 byte RAM. This saves 8 bytes of flash due to fewer needed operations for the byte instead of a integer. I would expect 12 bytes of ram, but okay. Not that much, but every byte saved is good.
Step 2: change over variable into defines when it makes sense.
For example, the led byte is not needed, the pin won't unsolder itself.
#define LED 13
int val;

void setup() {
  pinMode(LED, OUTPUT);
}

void loop() {
  blink();
  val = digitalRead(10);
}

void blink() {
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

Compiles into 1142 bytesflash + 11 bytes ram. Already 38 bytes saved. This is due to fewer register operations needed to fetch the int value. Also we saved 2 bytes from RAM. (still wondering why the byte didn't compile into 1 less byte of ram.....)
Step 3: optimize code.
I see 2 delays. I wonder if i change it to 1 delay it would save space, but i have to figure out the value of the LED pin and toggle (invert) it. We can do that with digitalRead(), but will it save space?
#define LED 13
int val;
void setup() {
  pinMode(LED, OUTPUT);
}
void loop() {
  blink();
  val = digitalRead(10);
}
void blink() {
  digitalWrite(LED, !digitalRead(LED));   // toggle the led based on read value
  delay(1000);               // wait for a second and spare yourself the other delay
}

Compiles into 1134 bytes + 11 bytes ram. Yay! another 8 bytes. That makes a total of 46 bytes and 2 fewer lines of code.
Also another general tip on decreasing codesize. Don't use the String class. It's HUGE, learn how to deal with char arrays, strcpy(), strcmp(). If all you have are some basic string operations, the usage of the String class is mostly just wasting space on both flash and RAM.


text:
Sending MPU6050 data over serial to Java/C# Program
I am using a MPU6050 Accelerometer/Gyro breakout (GY-521) to retrieve data and send it to a java program. I have tried several ways, but I couldn't find a way to send the float values calculated from the Arduino over Serial. Could you please let me know a good way of serial communication with Arduino and a Java Program? Thanks in advance.
UPDATE:
Thank you for your comments and replies. What I have tried is the I2Cdev library code. I could work with it without any issue. Code is in this link. I also could run the processing code to get a visual output. But the problem I have i that I'm not able to send the accelerometer and gyro data to a Java/C# program and process it from there. I tried sending an array of FIFO bytes from the Arduino and convert it from the C# code and processing code, but it didn't give me correct results. Now what i did was, just to send a string of values and receive it from the C# program. But I don't know whether it's good method. I would be glad if you could help me in this. Thanks again.
Arduino
#ifdef OUTPUT_TEAPOT
        // display quaternion values in InvenSense Teapot demo format:
        teapotPacket[2] = fifoBuffer[0];
        teapotPacket[3] = fifoBuffer[1];
        teapotPacket[4] = fifoBuffer[4];
        teapotPacket[5] = fifoBuffer[5];
        teapotPacket[6] = fifoBuffer[8];
        teapotPacket[7] = fifoBuffer[9];
        teapotPacket[8] = fifoBuffer[12];
        teapotPacket[9] = fifoBuffer[13];
        Serial.write(teapotPacket, 14); //Serial.write(buf, len)
        teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
    #endif

    #ifdef OUTPUT_ACCEL_STR_RAW
        mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

        String accelGyroRaw = "STX,";
        accelGyroRaw += ax;
        accelGyroRaw += ',';
        accelGyroRaw += ay;
        accelGyroRaw += ',';
        accelGyroRaw += az;
        accelGyroRaw += ',';
        accelGyroRaw += gx;
        accelGyroRaw += ',';
        accelGyroRaw += gy;
        accelGyroRaw += ',';
        accelGyroRaw += gz;
        accelGyroRaw += ',';
        accelGyroRaw += "ETX";

        Serial.println(accelGyroRaw);

    #endif

C# Code
class Program
{
    static SerialPort port = new SerialPort("COM7", 115200);
    //static int serialCount = 0;
    //static int aligned = 0;
    //static char[] teapotPacket = new char[14];
    //static float[] q = new float[4];

    static void Main(string[] args)
    {

        Console.WriteLine("****** Serial Console Read ********");
        port.Open();
        port.DataReceived += port_DataReceived;

        Console.Read();
    }

    static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {

        string s = port.ReadLine();
        string[] accelGyroVals = s.Split(',');
        string[] accl = new string[3];
        string[] gyro = new string[3];

        if (accelGyroVals[0] == "STX" && accelGyroVals[accelGyroVals.Length - 1] == "ETX\r")
        {
            accl[0] = accelGyroVals[1];
            accl[1] = accelGyroVals[2];
            accl[2] = accelGyroVals[3];

            gyro[0] = accelGyroVals[4];
            gyro[1] = accelGyroVals[5];
            gyro[2] = accelGyroVals[6];

            Console.WriteLine("a : " + accl[0] + " , " + accl[1] + " , " + accl[2] + "\t g : " + gyro[0] + " , " + gyro[1] + " , " + gyro[2]);
        }

    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        if (port.IsOpen)
        {
            port.Close();
        }
    }
}

Sorry for this for lengthy code and if my question is unclear. It's my first time to work with an IMU. Thank you.

What have you tried so far? Is your problem related to Arduino side or Java side? Can you post some code you have tried until now?

Java and C# are similar, but not the same, so you need to be clear about which you are actually using.  In C# you can use == to compare String contents, but in Java that operator will only compare object instances and you must use the .equals() method to compare contents of Strings.  Given the non-capitalization of "string" it appears your posted code is actually C#, but the "==" will subtly fail if you try to make trivial changes to build and run it as java.

Chirs, Thanks a lot for your comments. You are correct. But what I am actually stuck in is the sending packets from serial to a java program / C# program and use the data packets in some meaningful manner. Anyway thanks for the help Chris.

If your question was about a previous attempt to communicate floats in binary, that can indeed be tricky as the binary encoding of floating point values can easily be different between platforms/languages.  You'd either need to transmit a standard form supported by both, or for simplicity sake use a textual encoding.  The latter might have 3x overhead, but has the huge advantage of making your data easily monitorable with a terminal program during debug.

You may find RXTX java library helpful.
You can format the data (float as calculated at Arduino side) in any mannner that you desire. RXTX library will send the data. It will then up to the Java program (non Arduino side, like PC, etc.) how to interpret the data and extract the values.
http://playground.arduino.cc/interfacing/java
Hope this helps

Thanks a lot for your answer John. I'll give it a try. Thanks a lot.

The RXTX is very standard. In fact, the Arduino IDE (on PC side) itself is written in Java, and it can communicate to the serial port (COMxx: port via USB on PC side) via the RXTX Java library (to the Arduino MCU hardware board via the USB power/download cable).


text:
MCP23017: 16x2 LCD showing black boxes
I've researched a lot but I couldn't find a solution to my problem, which is that after properly following all steps from this Website: http://www.danielealberti.it/2014/02/collegamento-diplay-lcd-ad-arduino-via.html
and after using the Library LIQUIDTWI2:
(https://drive.google.com/file/d/0BwSP1-P3E2UJY1loYWtWQVRWNlU/edit?usp=sharing)
for I2C connections, the LCD keeps displaying black boxes on the top row.
I'm pretty sure that I have wired (as shown in the tutorial linked above) and programmed everything correctly but I'm still getting the black boxes. Is the problem related with the MCP23017 pin expander or with something else?
I'm using an Arduino UNO

Have you wired up the contrast adjustment pot? If contrast is wrong you can see black boxes.

No pin 3 is not connected with a POT. I connected pin 3 of the LCD right to the ground and I dont think that it is a problem with the contrast

@NickGammon is contrast is set wrong, either no boxes appear (too low), or boxes appear on both the top and the bottom row (too high).

CrazyBacon did not say specifically that there were no black boxes on the bottom row.

after properly following all steps - photo perhaps?

Quite often such situation occurs when the display does not reset properly (the reset from the IDE does not necessarily reset the display!).
So, once the sktech has been uploaded to the board, I would first try to do a reset on the Uno board (using the RESET button). If that doesn't do the trick, I would recommend to make the contrast adjustable (all my LDC displays showed "black boxes in the upper row" on delivery and I had to ajust the contrast).
If that also has not the desired effect, there is no alternative to debugging your code. Without the code itself, we cannot guess what might be wrong.

Thanks. For some reason after resetting the Arduino and attaching a POT to the LCD it started working


text:
sketch uploading give error?
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x20
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x20

See Have I bricked my Arduino Uno? Problems with uploading to board - your "question" is very light on detail.

Most often this message indicates that you should select another board type in the Arduino IDE under Tools menu. Have you tried that?

This Instructables post has a list of potential causes for this error. Is this a new board? What board are you using? Is it a genuine Arduino board or a clone? Have you been able to upload to the board previously?

I have selected right com port. Previously i had uploaded sketches and that worked find. Now it giving me issue.

I am using clone arduino

@user3883017 What is your hardware setup? Do you have any wires connected to the RX pin?

Arduino UNO. No Just one LED to pin 13 and ground

avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
Copyright (c) 2007-2009 Joerg Wunsch
     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM7
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200

Have you changed the atmega328 chip? If you have the new one may not have a bootloader or it may have one for a different board. Select every board option. Duemillemova maybe?
If you still have no luck, you might have over written your bootloader. Try burning the bootloader again. Instructables shows you how.


text:
uno + ethernet sheild(wiznet) + dh22 temp humidity sensor + viewing data online
i am new to arduino and have no experience with programming
i have an uno r3 board, a wiznet ethernet sheild, and dh22 temp and humidity sensor.
  I would like to have it update plot.ly to view the data.

error returned on monitor is ...
POST /clientresp HTTP/1.1
Host: plot.ly:80
User-Agent: Arduino/0.6.0
Content-Length: 340

version=2.3&origin=plot&platform=arduino&un=jozef.jones&key=tgcio4brx1&args=[{"y": [], "x": [], "type": "scatter", "stream": {"token": "ke1f6fwqas", "maxpoints": 100}}, {"y": [], "x": [], "type": "scatter", "stream": {"token": "k5lmga9qrl", "maxpoints": 100}}]&kwargs={"fileopt": "overwrite", "filename": "filename", "world_readable": true}
... Sent message, waiting for plotly's response...
HTTP/1.1 200 OK
Content-Type: application/json
Date: Sun, 17 Jan 2016 16:22:32 GMT
Server: nginx/1.8.0
Set-Cookie: csrftoken=WknqVtPqjTYvlTyoKSC5QehqDgmt7Qp7; expires=Tue, 17-Jan-2017 16:22:32 GMT; Max-Age=31622400; Path=/; secure
Set-Cookie: anoncsrf=2UDFDiQhQq1zf5MIMaoRJ0ayaqs7g58R; expires=Mon, 18-Jan-2016 16:22:32 GMT; httponly; Max-Age=86400; Path=/
Vary: Accept-Encoding
Vary: Cookie
X-Frame-Options: SAMEORIGIN
Content-Length: 138
Connection: keep-alive

{"url": "", "message": "", "warning": "", "filename": "", "error": "Missing required POST parameters: platform un key origin args kwargs"}

code is
#include <SPI.h>
#include <Ethernet.h>
#include "plotly_streaming_ethernet.h"
#include "DHT.h"

#define nTraces 2

char *tokens[nTraces] = {"ke1f6fwqas", "k5lmga9qrl"};
// arguments: username, api key, streaming token, filename
plotly graph("jozef.jones", "tgcio4brx1", tokens, "filename", nTraces);

// DHT Sensor Setup
#define DHTPIN 2 // We have connected the DHT to Digital Pin 2
#define DHTTYPE DHT22 // This is the type of DHT Sensor (Change it to DHT11 if you're using that model)
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT object

byte mac[] = { 0x00, 0xAA, 0xBB, 0x00, 0x00, 0xCC };
byte my_ip[] = { 192, 168, 1, 117 }; // google will tell you: "public ip address"

void startEthernet(){
    Serial.println("... Initializing ethernet");
    if(Ethernet.begin(mac) == 0){
        Serial.println("... Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, my_ip);
    }
    Serial.println("... Done initializing ethernet");
    delay(1000);
}

void setup() {
  graph.maxpoints = 100;
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  startEthernet();

  bool success;
  success = graph.init();
  if(!success){while(true){}}
  graph.openStream();
  dht.begin();
}

float h, t;

void loop() {
      h = dht.readHumidity();
      t = dht.readTemperature();
      graph.plot(millis(), t, tokens[0]);
      graph.plot(millis(), h, tokens[1]);
}

Seems to be a more common problem (http://community.plot.ly/t/arduino-streaming-data-issue-missing-required-post-parameters/304). You should encode the values of args and kwargs. But that didn't fix the error message when I tried it myself.


text:
Get 25 kHz PWM on a 16 MHz Arduino
I am trying to output a 25 kHz software PWM on at least four pins simultaneously with variable duty cycles on each pin individualy.
I've got all the actual PWM outputs via internal timers 2x8 1x16 with variable duty cycles and am looking for a way to output a 25 kHz PWM on the four pins (any pins) via an external timer if necessary. How can I do that?

The three available timers on a 328 give you six PWM outputs via their A and B compare outputs, with the only limitation being that the two outputs of the same timer have to have the same period (but can have different duty cycles). So as far as I can see, you don't need to do anything special.

Look into using one of the AVR chips that have more PWM outputs. For example, AT90PWM81 which includes six hardware PWM outputs.

I was tinking that chip might even run arduino code.

AT90PWM216 has a UART, that might make for easier PC interfacing.

void setup()
{
    // Set the main system clock to 8 MHz.
    noInterrupts();
    CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
    CLKPR = _BV(CLKPS0);  // divide frequency by 2
    interrupts();

    // Configure Timer 0 for phase correct PWM @ 25 kHz.
    TCCR0A = 0;           // undo the configuration done by...
    TCCR0B = 0;           // ...the Arduino core library
    TCNT0  = 0;           // reset timer
    TCCR0A = _BV(COM0B1)  // non-inverted PWM on ch. B
        | _BV(WGM00);  // mode 5: ph. correct PWM, TOP = OCR0A
    TCCR0B = _BV(WGM02)   // ditto
        | _BV(CS00);   // prescaler = 1
    OCR0A  = 160;         // TOP = 160

    // Same for Timer 1.
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1  = 0;
    TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
        | _BV(COM1B1)  // same on ch. B
        | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
    TCCR1B = _BV(WGM13)   // ditto
        | _BV(CS10);   // prescaler = 1
    ICR1   = 160;

    // Same for Timer 2.
    TCCR2A = 0;
    TCCR2B = 0;
    TCNT2  = 0;
    TCCR2A = _BV(COM2B1)  // non-inverted PWM on ch. B
        | _BV(WGM20);  // mode 5: ph. correct PWM, TOP = OCR2A
    TCCR2B = _BV(WGM22)   // ditto
        | _BV(CS20);   // prescaler = 1
    OCR2A  = 160;
}

void loop()
{
    analogWrite( 3,   1);  // duty cycle = 1/160
    analogWrite( 5,  53);  // ~ 1/3
    analogWrite( 9, 107);  // ~ 2/3
    analogWrite(10, 159);  // 159/160
}


text:
Why do I get negative voltages for a PWM waveform?
I used my Arduino Uno's pin 3 to generate a PWM output. The code is:
void setup() {
  // Put your setup code here, to run once:
}

void loop() {
  analogWrite(3, 180);
}

I connected the output directly with a oscilloscope.
And the output waveform is shown below:

I found it's weird that the minimum voltage is negative! And with the duty cycle increasing, both the maximum voltage and minimum voltage decrease.
Why does it behave in such a way?

Oh my god! It's due to the setting of the oscilloscope. I reset it and now it's  works normally.

But I still don't know which setting is not right...Can you guys help me?

There is no need to have the analogWrite call in loop() - it only needs to be called once (the hardware automatically generates the PWM signal - no software is involved). It can and should be moved to setup().

At first you had the scope AC (Alternating Current) coupled.  Then you switched it to DC (Direct Current) coupled.
AC coupling is used to remove the DC component of a signal.  It places a large capacitor between the probe and the internal amplifier.  This is used, for instance, if you want to see a small signal with a large DC offset.  But it can also attenuate and / or alter signals that are low in frequency.
When a PWM signal is AC coupled to an oscilloscope, an interesting phenomenon occurs.  As the duty cycle goes from a minimum (almost always off) to a maximum (almost always on) the DC component of the PWM signal changes.  Since the DC component is blocked by the AC coupling, the PWM signal appears to move lower on the screen as the duty cycle increases.
DC coupling is where there is no coupling capacitor between the probe and the internal amplifier.  Everything comes through.  For digital electronics where the signal travels a small distance from 0 to 5 volts or from 0 to 3.3 volts, this is the best way to use the scope.

Incidentally - you see how the top and bottom of the waveform are sloping down and up slightly? This is indicative of the charging and discharging of the AC coupling capacitor by the low frequency component of the waveform.


text:
Recover from wrong Wi-Fi password on Arduino Yún
I'm trying to customize my Arduino Yún to work as an access-point (or hotspot) for providing services to clients directly connected and, alternatively, to work as a client on a wireless network for downloading resources from the Internet.
The access to such a wireless network is gained after the user submits a network SSID and password in the web control panel provided by Yún.
How can I recover from a user submitting a wrong password? At the moment the Yún stays stuck without any connection, and thus is unreachable via SSH to attempt any recover.

Perhaps if you posted your code, we could help.

At the end I came out with a button connected to one of the digital input pins and a sketch that, using the bridge to communicate with the "Linux part" of Yún, restores original values in the configuration files and reboots the whole controller.
After the reboot completes the Arduino Yún is accessible again through the Wi-Fi network "Arduino Yun xxxxxxxxxx".

The simplest option is to provide a serial console interface which will either give full access to the OS (pipe through Console) or a menu driven interface that sends instructions to the main chip (through Bridge).
The user would then connect to the USB interface and use a terminal program to access the configuration in whatever way you have chosen.  This could either be via options within your installed sketch, or by uploading a special sketch through the USB connection.

The fact is that the Arduino board will be in a box, and the only channel available will be the wi-fi. I basically would like to replicate the behaviour described in [link] (https://www.arduino.cc/en/Main/ArduinoBoardYun?from=Products.ArduinoYUN) , for the WLAN RST button pressed for more than 5 seconds.

You could always solder wires from the switch to your Arduino such that if after 15 mins you are still not connected to the net. Reset the WiFi by pulling that pin low ( I think)


text:
C# and Arduino problem with serial port
I would like to establish a communication between my C# program and my Arduino Duemilanove. I tried lot of different tutorials, but none of them were the same, and I'm a little bit confused.
Actually my code is:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace InterfaceArduinoWindowsFOrm {
  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      serialPort1.PortName = "COM3";
      serialPort1.BaudRate = 9600;
      serialPort1.Open();
    }

    private void pictureBox1_Click(object sender, EventArgs e) {
    }

    private void tabPage2_Click(object sender, EventArgs e) {
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
    }

    private void toolTip1_Popup(object sender, PopupEventArgs e) {
    }

    private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) {
      Console.WriteLine("test");
    }

    private void button1_Click_1(object sender, EventArgs e) {
      serialPort1.Write("5");
      Console.WriteLine(serialPort1.IsOpen);
    }
  }
}

Arduino:
/* Sweep
  by BARRAGAN <http://barraganstudio.com>
  This example code is in the public domain.
  modified 8 Nov 2013
  by Scott Fitzgerald
  http://arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // Create servo object to control a servo.
// Twelve servo objects can be created on most boards.
int pos = 0;
int message = 0; // This will hold one byte of the serial message
                 // variable to store the servo position.

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

void loop() {
  if (Serial.available()) {

    // Check to see if there is a new message
    message = Serial.read();

    // Put the serial input into the message
    Serial.print(message);

    if (message == '5') {
      Serial.print("test");
      for(pos = 0; pos <= 180; pos += 1) {
        // Goes from 0 degrees to 180 degrees
        // in steps of 1 degree

        myservo.write(pos);
        // Tell servo to go to position in variable 'pos'

        delay(15);
        // Waits 15 ms for the servo to reach the position
      }

      for(pos = 180; pos>=0; pos-=1) {
        // Goes from 180 degrees to 0 degrees

        myservo.write(pos);
        // Tell servo to go to position in variable 'pos'

        delay(15);
        // Waits 15 ms for the servo to reach the position
      }
    }
  }
}

The problem is, when I click my button, nothing happens, but obviously if I remove the if statement, the servo motor code works.

Did you make sure that the C# button event is fired, and that the Serial connection is established properly? Also, what happens if you open the Arduino COM terminal and press 5?

Hum yea , i tested with some console writte and Button work , what do you mean by : press 5?

I mean that, in your C# code, you just send "5" to the serial port. As part of the debugging - pin pointing where the problem lays - did you use the Arduino Serial console to send "5" the same way you send it from C#, and made sure it works there? Because if sending "5" from the Serial console in the Arduino IDE doesn't work, the C# way won't work either.

I follow lot of tutoriel covering this , the code is really similar as mine , but , when I try to use the serial monitor , and I try to fire button event , it say that Com3 is already in use and unauthorized ... 5 is only a message id to call the arduino IF statement ....

Yes, I get that 5 is the trigger. What I'm trying to understand is whether that trigger works or not. You cannot use Arduino IDE Serial Monitor while running your C# code since the Arduino COM port can interface only one serial port at a time. Try using the Arduino IDE Serial Monitor after closing the C# serial port and not in parallel to it.

Ok , but how to make sure if my arduino trigger is activated

As I suggested; do not run the C# app, only use the Arduino IDE Serial Console to send '5' and examine the results.

A ok ! But how to send 5 from serial monitor , just input 5 on the input text ?

Yes. If you do that, do you get the desired result?

I can confirm you this in arround 1 hour

Since you are sending from the Arduino the received serial data back to the C# application (Serial.print(message);), I would advise to check what you receive on the C# side.
Register to the DataReceived event of the SerialPort as so:
serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

And add an event handler:
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort port = (SerialPort)sender;
    string data= port.ReadExisting();
    // check here what data you received, if any
}

This way you could confirm that the Arduino gets the data properly from the C# side to begin with. Next step would be to understand if this if statement treats the data properly:
if (message == '5')

But starting from examination of what you get from the C# side will help you decide where exactly is the problem.

EDIT : NeverMind I missundarstood your post i'm sorry, But i acctualy don't understand your answer, do you mean that I try to send from Arduino to C# because, Me I want to do the opposite...

Yes, I mean that you try send from Arduino to C# (you are already doing that) and see what you get. This will help you understand where is the problem.

Ok so i Will try if i understand to directly send from arduino to c#

You are already doing it... the line "Serial.print(message);" sending the message back to the C# code. Just see what you get from the C# side as I explained.

Hooo yea it was a test code , but I forget to read from C# I'm sorry if I didn't understand but it's because I forget this line ...

any progress with this?

Tomorow , i CAN continue working on this ,i had´nt GOT the time until now , tomorrow I can tell you if it's working

Ok , i test right now what you said about serialDataReceivedEvent with a  DataReceivedHandler method : { /---what you write --/ Console.WriteLine("received data "+ data); }  I connected the arduino with USB cable and launched the C# program , but obviously I don't compile my program at the same time as it say that COM3 port is already in use ... So, I received some data but it seems encrypted , for example : "Z?" Or "J?"   I will try other message stay tuned,      Edit : apparently message seems to work , yea. I successful receive data from my arduino to my C# program ! Now lt go arduino part!


text:
I²C between ATTiny85 (8MHz) and Arduino Uno
I keep receiving the following error in myATTiny85-Slave code below:

sketch_mar12a.ino: In function 'void setup()':
sketch_mar12a:19: error: 'class USI_TWI_S' has no member named 'onRequest'

I have downloaded TinyWireS and TinyWireS.h clearly has a public function onRequest. I opened the .ZIP file (downloaded from https://github.com/rambo/TinyWire) and drag-dropped TinyWireS folder into the Arduino libraries folder. This is how I install ALL libraries.
I am using Arduino 1.0.6
What am I doing wrong?
ATTiny85-Slave Code:
#include "TinyWireS.h"                  // wrapper class for I2C slave routines
#define I2C_SLAVE_ADDR  0x26            // i2c slave address (38)

byte t=10;

void setup()
{
   TinyWireS.begin(I2C_SLAVE_ADDR);      // init I2C Slave mode
   TinyWireS.onRequest(requestEvent);
}

void loop()
{
}

void requestEvent()
{
   TinyWireS.send(t);
}

Arduino Uno-Master Code:
 #include <Wire.h>
 #define I2C_SLAVE_ADDR  0x26            // i2c slave address (38)

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

 void loop()
 {
      byte num;

     // read 1 byte, from address 0x26
     Wire.requestFrom(I2C_SLAVE_ADDR, 1);

     while(Wire.available()) {
          num = Wire.read();
     }

     Serial.print("num = ");
     Serial.println(num,DEC);
 }

How did you install the library?

I opened the .ZIP file (downloaded from https://github.com/rambo/TinyWire) and drag-dropped TinyWireS folder into the Arduino libraries folder. This is how I install ALL libraries.

you may need to include: TinyWireS_stop_check();
in your loop

I was able to compile your code "ATTiny85-Slave Code" without problems.
You can try to extract the contents of the ZIP archive (i.e. the library) directly to the directory where your sketch is stored. #include "TinyWireS.h" should then pick up that version.
You should also switch on verbose output for the compilation to have a look at the directory in which the code is compiled. Here you would find (at least in my older Arduino IDE version) copies of the included files. (/tmp/build... on Linux systems.) You can then make sure the proper version of the files is used.
You can also search your drives for other copies of TinyWireS.h.

Which version of Arduino IDE are you using? What board did you select?

I am using Arduino IDE 1.0. It compiles with any board selection... Note that I did not install the Tiny hardware specs, but did a small hack in usiTwiSlace.c, declaring all missing symbols as ints.


text:
Can I use an arduino as a ground short?
I have a little personal project involving an Arduino Uno and an amp board from Sure Electronics. The amp has contacts for a mute function that involves shorting the contact to ground. I would like to control this muting with the Arduino which I was planning to do with a relay. However I think I might be complicating things and I thought it might be possible to do it directly with the pins.
Can I use the Arduino to directly short a circuit to ground? Or would I need something more complicated to be safe?

@FuaZe - no, that is extremely incorrect.  The limit for a given signal is at least 10 times lower!   And there is a maximum voltage, too.

"For 328P, the max current rating is 400mA for the TQFP package" - http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations
"DC Current per I/O Pin: 40.0 mA"
How stupid, I took the max current rating for the complete package... per pin it indeed is ~40mA.
Also, ofcourse it shouldn't surpass the arduino voltage limits (5V?)
I'll delete my comment before anyone will burn his/her arduino because of it :)

Depends on the voltage that is on that mute pin. If it's below 5 volt, you could use the arduino pin. You can measure the voltage using a multimeter.
If it's more than 5v you can use a NPN transistor and resistor combination.
Current isn't a problem with these kinds of "settings" pins, as there is just a pull-up resistor that by default (unconnected) sets the pin to HIGH. By connecting the pin to ground you set the pin to LOW.

I would recommend an optical coupler: http://en.wikipedia.org/wiki/Solid-state_relay, which will let the Arduino survive even in case of severe overvoltage in the amp. They also come in 2 or 4 per package, so this could control also the power of the amp, in a small footprint. Example: http://www.ebay.com/itm/6N136-Highspeed-Transistor-Optocoupler-DIP-8-/251561136534?pt=LH_DefaultDomain_0&hash=item3a92365196

I missed the product link in the question. The SD pin is pulled up to the voltage applied to the amp (page 20 datasheet). The voltage for the amp is 8-24 volts. So you can connect the pin directly. And optocoupler is a bit overkill with these low voltages. Solid state relays are uber-overkill.

I can't see how much current the amp board will sink into the Arduino so like FuaZe I would recommend using your Arduino to drive an external component that you know can take the current.  This isn't really complicating the design too much, use an NPN transistor, with the P connected to the Arduino and just write High to the pin when you want to apply the mute.  If you blow the transistor then its going to cost you a few pence for a new one, if you blow your Arduino you are down £20!

Don't forget to add a resistor between the base (P) and the Arduino pin, or you will definitely blow your Arduino, regardless of the amp board.


text:
Using arduino uno as a battery charger timer
My question is, can I use a Arduino as a battery charger timer, I have a 3.7 v 1200 mah lithium battery that I have been charging with a 4.2 450 ma charger for quite some time, I normally just use gator clamps to connect the leads to charge it, but today I was charging it and forgot about it and let it over charge. I don't want to ruin the life of the battery or possible have it blow up, so I got the idea of using my Arduino as a timer so it will shut off when it is done (or close to done).  My plan was to connect a transistor to it and have the Arduino running to the base pin to control when it will turn on or off and add a diode for both feedback and voltage droppage. I am aware that I will have to add a resistor/diode, so its not charging at around 6 volts.
But I want to know if I can run a program through my Arduino that will have it charge for say 2 hours?  If anyone knows if the uno is capable of doing this please let me know.
Also will I be able to connect a standard phone charger which I believe is 5 volts 2 amp to power my arduino?
Thank you for ur replies, if there is a program please link it
P.S. If anyone would like to know more information or would like to me fix any information please just comment and I will have it fixed shortly.

But I want to know if I can run a program threw my ardino that will have it charge for say: 2 hours.? Yes you can use the Uno to make a battery charger timer circuit. And also, will I be able to connect a standard phone charger witch I believe is 5 volts 2 amp to power my arduino? Yes, if its 5v regulated DC psu, and has the same barrel socket (uses 2 wires) and same has polarity. Next question?

Please get a proper charger! Lithium batteries are pretty specific about the way you charge them, or they can catch fire.

Yes I know they r sensitive when charging, but I believe this charger was preveiwlesly used to charge a lithium battery.

What are "ur replies" and how do I make them?

I mwnt comments

This might be a little off topic but it still a part of the same project, is there a way that I can have my ardino uno automatically shut off when the batteries r fully charged? I was thinking something like using a analog to read the input voltage from the battery and when the input voltage hots a sertain voltage it just end the program

Can you use an Uno to switch something on and off?  Yes.
Should you?  No.
In this case you are talking about controlling something that if it is not controlled could have serious safety implications.  Are you confident enough in you ability to code not to get this wrong?  What if the hardware fails, the Uno freezes?
Yes you could do it, but I think you would be better off buying a tried and tested COTS solution.

As others have already said, you could time the charge, but your idea has some major flaws;
First, since you can more easily read voltages than you can keep track of time, you should stop the charge once a certain voltage is reached, so you could also charge other batteries or half charged ones.
MORE IMPORTANTLY,
Lipos always need fairly complex charging circuits (compared to other rechargeable types). This is an area you should read up on extensively before tinkering, since LoPo's respond explosively to mistakes.
A good starting tutorial;
 http://learn.adafruit.com/li-ion-and-lipoly-batteries/overview
I would suggest using a commercial charger, so that you are sure to be protected from over charge, over voltages, shorts, and fires, and will stop charging when the battery is charged. This one should also have a connector so you can connect it to your phone charger, and costs 0.90$.
http://www.electrodragon.com/product/tp4056-lithium-battery-charging-board-1a/
Please note this is a reference, you should find more economic offerts.