text:
Arduino Uno- Analog serial monitor not reading values over 174
I am simultaneously using a LEGO sound sensor in pin A5 and a RadioShack Tricolor LED Strip (Product #2760339) in pin A0.
The sound sensor alone works as expected (producing values based on volume) running only code to read the value and output to the serial monitor. However when I upload the program to use the LED strip, read the sensor value and output to the serial monitor, the sensor value caps at 174.
The program given to run the LED strip can be found at http://blog.radioshack.com/2013/06/tricolor-led-strip/
The code I added to this was pulled mostly directly from the AnalogInOutSerial example provided by Arduino.
Here is the full code;
/***************************************************************************/
//            Hardware: RadioShack Tricolor LED Strip
//            Arduino IDE: Arduino-1.0
//            Date:      April 17, 2013
//            Copyright© 2013 RadioShack Corporation
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, see <http://www.gnu.org/licenses/>
//
/*****************************************************************************/

#include <avr/pgmspace.h>

// ******** DEBUG ==== should auto config to adapt different mother board *********
//#define DATA_1 (PORTF |=  0X01)    // DATA 1    // for ATMEGA
//#define DATA_0 (PORTF &=  0XFE)    // DATA 0    // for ATMEGA
//#define STRIP_PINOUT DDRF=0xFF  // for ATMEGA
#define DATA_1 (PORTC |=  0X01)    // DATA 1    // for UNO
#define DATA_0 (PORTC &=  0XFE)    // DATA 0    // for UNO
#define STRIP_PINOUT (DDRC=0xFF)    // for UNO

PROGMEM const unsigned long rainbow_full[5][10]={
  {0xff0000,0x00ff00,0x0000ff,0xffff00,0xff00ff,0xffffff,0xff6622,0xff0000,0xff0000,0xff0000},

};
PROGMEM const unsigned long off[1][10] = {
   {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red1[1][10] = {
   {0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red2[1][10] = {
   {0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red3[1][10] = {
   {0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red4[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red5[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red6[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red7[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red8[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000},
};
PROGMEM const unsigned long red9[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000},
};
PROGMEM const unsigned long redfull[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000},
};

/*PROGMEM const unsigned long pattern_test_blue[10][10]={
  {0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00},
};

PROGMEM const unsigned long pattern_test_green[10][10]={
  {0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff},
};

PROGMEM const unsigned long pattern_test_white[10][10]={
  {0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff},
};

PROGMEM const unsigned long pattern_test_comet1[][10]={
  {0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff},
};

PROGMEM const unsigned long pattern_test_comet2[][10]={
  {0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000},
  {0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000},
  {0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000},
  {0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000},
  {0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff},
  {0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000},
  {0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000},
  {0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000},
  {0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000},
  {0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff},
};

PROGMEM const unsigned long pattern_test_comet3[][10]={
  {0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff},
  {0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x444444},
  {0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0xffffff,0x444444,0x111111},
  {0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0xffffff,0x444444,0x111111,0x000000},
  {0x000000,0x000000,0x111111,0x444444,0xffffff,0xffffff,0x444444,0x111111,0x000000,0x000000},
  {0x000000,0x000000,0x111111,0x444444,0xffffff,0xffffff,0x444444,0x111111,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0xffffff,0x444444,0x444444,0xffffff,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0xffffff,0x444444,0x111111,0x111111,0x444444,0xffffff,0x000000,0x000000},
  {0x000000,0xffffff,0x444444,0x111111,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000},
  {0xffffff,0x444444,0x111111,0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff},
};

PROGMEM const unsigned long pattern_test_rainbow[10][10]={
  {0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000},
  {0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000},
  {0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000},
  {0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff},
  {0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff},
  {0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff},
  {0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00},
  {0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00},
  {0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00},
  {0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000},
};

*/

// ***********************************************************************************************************
// *
// *                            Power Up Init.
// *
// *
// ***********************************************************************************************************

int sensorvalue = 0;
int outputvalue = 0;
void setup() {

  STRIP_PINOUT;        // set output pin - DEBUG: should auto detect which mother board for use

  reset_strip();
  Serial.begin(9600);
  //noInterrupts();

}

// ***********************************************************************************************************
// *
// *                            Main Loop
// *
// *
// ***********************************************************************************************************
void loop()
{

    sensorvalue = analogRead(A5);
    outputvalue = map(sensorvalue, 0, 174, 0, 18);
    if(outputvalue == 0){
      send_1M_pattern(off, 1, 20);
    }

    else if(outputvalue > 0 && outputvalue <= 3){
      send_1M_pattern(red1, 1, 20);
    }
    else if(outputvalue > 3 && outputvalue <= 5){
      send_1M_pattern(red2, 1, 20);
    }
    else if(outputvalue > 5 && outputvalue <= 7){
      send_1M_pattern(red3, 1, 20);
    }
    else if(outputvalue > 7 && outputvalue <= 9){
      send_1M_pattern(red4, 1, 20);
    }

    else if(outputvalue > 9 && outputvalue <= 11){
      send_1M_pattern(red5, 1, 20);
    }

    else if(outputvalue > 11 && outputvalue <= 13){
      send_1M_pattern(red6, 1, 20);
    }

    else if(outputvalue > 13 && outputvalue <= 16){
      send_1M_pattern(red9, 1, 20);
    }

    else if(outputvalue > 16){
      send_1M_pattern(rainbow_full, 1, 20);
    }
    Serial.print("sensor = " );
    Serial.print(sensorvalue);
    Serial.print("\t output = ");
    Serial.println(outputvalue);

    delay(2);

  /*
    frame++;
    if(frame<=10) LEDSTRIP_PATTERN_0();
    if(10<frame<=20) LEDSTRIP_PATTERN_0();
    if(20<frame<=30) LEDSTRIP_PATTERN_0();
    if(frame>30) frame=1;
   */
  //delay(1);
}

/*******************************************************************************
 * Function Name  : send_1M_pattern
 * Description    : Transmit pattern to whole 1 meter strip
 *
 * Input          : pointer to ROM pattern; pattern length; frame rate
 *
 * Output         : None
 * Return         : None
 *******************************************************************************/
void send_1M_pattern(const unsigned long data[][10], int pattern_no, int frame_rate)
{
  int i=0;
  int j=0;
  uint32_t temp_data;

  for (i=0;i<pattern_no;i++)
  {
    noInterrupts();
    for (j=0;j<10;j++)
    {
      temp_data=pgm_read_dword_near(&data[i][j]);
      send_strip(temp_data);
    }
    interrupts();

    delay(frame_rate);

  }

}

/*******************************************************************************
 * Function Name  : send_strip
 * Description    : Transmit 24 pulse to LED strip
 *
 * Input          : 24-bit data for the strip
 *
 * Output         : None
 * Return         : None
 *******************************************************************************/
void send_strip(uint32_t data)
{
  int i;
  unsigned long j=0x800000;

  for (i=0;i<24;i++)
  {
    if (data & j)
    {
      DATA_1;
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");

/*----------------------------*/
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
/*----------------------------*/
      DATA_0;
    }
    else
    {
      DATA_1;
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      DATA_0;
/*----------------------------*/
       __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
/*----------------------------*/
    }

    j>>=1;
  }

}

/*******************************************************************************
 * Function Name  : reset_strip
 * Description    : Send reset pulse to reset all color of the strip
 *
 * Input          : None
 *
 * Output         : None
 * Return         : None
 *******************************************************************************/
void    reset_strip()
{
  DATA_0;
  delayMicroseconds(20);
}

Please include your code here. While one may say "code came from such-and-such", it is possible that interactions between various pieces of code can cause complications.

I have included the code.

So you're saying that just performing the analogRead() on the audio sensor alone without the rest of the code gives results from 0 to 1023? Is this regardless of whether or not the other electronics is in place?

Correct, I have discovered that the sensor reading is independent on the other electronics plugged in, yet is is dependent on the statement STRIP_PINOUT; in the setup function. If that statement is excluded from the code, the sensor reads normally, but the LED strip does not work.

To be clear, when I say the sensor reads normally, I am getting values around 0 with no sound, and no more than 500 with music playing as loud as my ears can handle, with no visible cap.

A5 is PC5. Your code sets it as an output. Since you only need A0 (PC0) to be an output:
#define STRIP_PINOUT (DDRC = _BV(PC0))

Uno pin mappings

I can see why this example code skips the usual Arduino I/O abstraction for its direct assembly bit-banging, but it is unfortunate as it makes their code hard to combine with anything else written in terms of Arduino pin names.

I am particularly amused by the repeated __asm__("nop\n\t"); lines. I suppose they didn't know about _delay_us() et alia.

This probably gives them finer control, particularly for very short intervals.  Likely the code was tuned for maximum performance shifting data to the strip, with a scope against the data sheet, or possibly by reducing to the point of failure and then backing off.

It also locks it to a single CPU clock speed, versus using the adaptive delay macros found in AVR Libc.


text:
Maplin Bluetooth Shield for Arduino - BAUD rate
I am currently using a Bluetooth shield which i bought from maplin, see: http://www.maplin.co.uk/p/bluetooth-shield-for-arduino-n97dg.
I have got it to work perfectly on the default 38400 BAUD , but cannot get it working at any other baud rate. I am currently just modifying the base code (here) given with the device where AT commands are used to configure the module.
I have tried setting the BAUD to say 115200 and then read back the devices BAUD rate using AT commands, and while it does return that it goes to 115200 it doesn't accept any commands after that.
Can any one offer help as to how I can reliably change to BAUD rate?

Have you changed the baud rate OF your serial monitor and IN you program.

Yes I have, the setup process involving sending the AT commands seems to go through successfully but when i run the test_bluetooth method, again with the BAUD changed there as well, the test fails. I have also tried connecting it with the Android device when the BAUD is changed and there is no communication, unlike when using 38400, which communicates perfectly

source: Stack Exchange

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

sort: votes


text:
Atmega328 PWM frequency setting not working
I have an Arduino UNO with Atmega 328 SMD, and I am trying to use PWM, but by setting registers, not using analogWrite(). My code is:
DDRD |= (1 << PORTD6); //Setting pin D6 as output
OCR0A = 128; //50% duty cycle
TCCR0A |= (1 << COM0A1)|(1 << WGM01)|(1 << WGM00); //setting mode and fast pwm
TCCR0B |= (1 << CS01); //setting the prescaler to 8, which should yield PWM with frequency of 8 kHz

The problem is with the last line. No matter what I do, it results in PWM with frequency of 1 kHz. Setting different prescaler bits just yield 1 kHz PWM again. I was thinking that maybe its because I am programming this in Arduino IDE, and I kHz is Arduinos default frequency?
Or where am I making the mistake? Thanks for any answers.

but when I write this instead of the last line, it works:  TCCR0B = TCCR0B & B11111000 | B00000010;

Your code assumes that TCCR0n are zero. But what if they are not. What if there is some hidden initialization?
Timer0 is used by the Arduino micro/millis counter and the prescale (TCCR0B) is initiated by setting bits CS00 and CS01 in init() before setup() is called.
If you really want to use Timer0 you will need to set/clear all the prescale bits. Alternatively clear the register before setting any bit.

To clarify; |= doesn't overwrite any previously set bits. So instead you should use =.

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


text:
Can anyone explain how this code can be converted to work on a Arduino Uno
I was hoping someone could help, im totally new to this. I wish to use this code for a Raspberry Pi on an Arduino Uno with the Adafruit SD data logging shield. It is for recording reed switch closures on a tipping bucket rain gauge. The interrupt and bounce time are to allow program interrupts and false tip suppression. I am looking to tie it in with the RTC and SD storage options on the Arduino. Any help appreciated.
#!/usr/bin/python3
import RPi.GPIO as GPIO
import time

# this many mm per bucket tip
CALIBRATION = 0.200
# which GPIO pin the gauge is connected to
PIN = 17
# file to log rainfall data in
LOGFILE = "log.csv"

GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# variable to keep track of how much rain
rain = 0

# the call back function for each bucket tip
def cb(channel):
    global rain
    rain = rain + CALIBRATION

# register the call back for pin interrupts
GPIO.add_event_detect(PIN, GPIO.FALLING, callback=cb, bouncetime=300)

# open the log file
file = open(LOGFILE, "a")

# display and log results
while True:
    line = "%i, %f" % (time.time(), rain)
    print(line)
    file.write(line + "\n")
    file.flush()
    rain = 0
    time.sleep(5)

# close the log file and exit nicely
file.close()
GPIO.cleanup()

What have you tried? What part of it are you having problems with? If you don't know where to start then start at the very beginning - don't try and do it all at once. Get the Arduino to (for example) light up an LED when the reed switch closes, and build up from there. Read tutorials on how to read inputs. Read examples on how to deal with RTC and SD. We aren't a code conversion service.

This should help get you started but don't expect it to actually work as it is. Note that i did not test this at all, it's for example purposes.  if there is a specific programming problem it should be addressed separately instead of handing out working code.
const int CALIBRATION = 0.200;   //Calibration Constant
int pin = 2;                     //Pin it's on, this is int0 for uno.
volatile int rain = 0;           //Used in interrupt routine

void setup() {
    Serial.begin(9600);
    pinMode(pin, INPUT);
    attachInterrupt(digitalPinToInterrupt(pin), cn, FALLING);
}

void loop() {

     /* Output OR LOG DATA HERE
        Also You need a Time Library and RTC (Real Time CLock) the above
        code is for a raspberry pi that has all that. */

}

void cb() {
    rain = rain + CALIBRATION;
}


text:
Amplification of microphone circuit
I am getting constant values and I need to know the amplification of the circuit. I believe that amplification = R8/R6 though I am not sure.

You are mostly correct Diana.  The gain of an OP-Amp would normally be R8 divided by R6.
However, what needs to be recognized is that in your circuit, the resistance of R3 and the microphone get entangled with your R6.
The resistance (impedance of your microphone) is in series with R6. R3 also comes into play, but I will ignore it here (subject of another question on amplifiers).
So, since R of microphone is in series with your R6, your gain (amplification) will be slightly less than you have calculated.
The old 741 Op-Amp won't work very well (probably not at all) with a single ended power supply of 5 volts.  Although you have done a good job of biasing the non-inverting input (+) at 2.5 volts.
The 741 output can't get near the +5 volts, nor can it get near ground.  Try a better Op-Amp such as MCP6002. Look at how the output of the MCP6002 can approach the rails (your power supply and ground).

Thank you ,altough this is not my circuit design entirely.I have assumed that the microphone has a high impedance so I  got the amplification as R8/(R6+R3).You are right the 741 does not behave properly.


text:
Can I use GPS sensors in a country (India) that doesn't have its own GPS Sattelites?
I am living in India. I want to work on Arduino Projects with GPS Modules. But only a few countries like US, Russia, China etc. have their own GPS satellites. India is working on it. So I am hesitating to buy GPS sensors. Can I work normally with GPS modules in my country as shown in Online projects in my country ?

GPS is US only. The Russian version is called GLONASS. The EU version is called Galileo. China version is called BeiDou/COMPASS (this one only works in and around china). PS the 'G' in GPS stands for Global, to indicate it works around the globe/world.

GPS - anyone can use it anywhere that it works. Not so good nearer poles. Best choice for India.
GLONASS - also can be used by anyone. Works best in Nortthern areas- satellites are in very elliptical orbits where they "hand high and slow" over top of northern hemisphere and are "kow and fast"in southern.

Each of the countries listed has their own satnav system. GPS satellites cover the entire world and the US government allows anyone with a GPS receiver to use it, regardless of where on or above the surface they are located.


text:
Debugging library - Error- expected unqualified id before '.' token
I'm writing a library for my project, which interfaces sensors used and structures them in different systems.
But I'm such a noob at C++. The compiler is throwing this error:
libraries/cec-core/cec-core.cpp: In member function 'void Habitaculo::Update()':
libraries/cec-core/cec-core.cpp:15:8: error: expected unqualified-id before '.' token
_Sluz.Update();

This is the header of that class:
class Habitaculo
{
    public:
    Habitaculo(int refrate, int luzpin, int dhtpin);
    //Values from Indoor Sensors
    int temp;
    int hum;
    int luz;
    //Update Methods
    void Update();      //Updates sensors value
    void UpdateReg();   //writes to SD or enabled output method
    private:
    //Clock Managing
    long _PreviousMillis;
    unsigned long _CurrentMillis;
    int _RefreshRate;
    //Sensor instances
    class _Sluz;
    class _SDHT;
};

This are the member functions affected:
Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin){
    //Clock management
    _RefreshRate = refrate;
    _PreviousMillis = 0;
    //Systems to initialize
    LDR _Sluz(luzpin);      //analogpin
    DHT11 _SDHT(dhtpin);    //buspin
}
void Habitaculo::Update(){
    _CurrentMillis = millis();
    if (_CurrentMillis-_PreviousMillis > _RefreshRate){
        _Sluz.Update();  //unqualified-id before '.' token
        _SDHT.Update();  //unqualified-id before '.' token
        temp = _SDHT.temp;  //expected primary-expression before '.'
        hum = _SDHT.hum;  //expected primary-expression before '.'
        luz = _Sluz.value;  //expected primary-expression before '.'
        _PreviousMillis = _CurrentMillis;
    }
}

The error is thrown in every step of the Update method. But I can copy that piece of code right in the Habitaculo constructor and it works well. So I assume I'm missing something basic about language syntax, because I'm really new to all this scene.
Every class involved in this (LDR, DHT11) works fine. It's when I try to put all this together into a new class - inside an unified Update method - that everything crashes.

From what I guess in your code, here is how you want your class declared:
class Habitaculo
{
    public:
    Habitaculo(int refrate, int luzpin, int dhtpin);
    //Values from Indoor Sensors
    int temp;
    int hum;
    int luz;
    //Update Methods
    void Update();      //Updates sensors value
    void UpdateReg();   //writes to SD or enabled output method
    private:
    //Clock Managing
    long _PreviousMillis;
    unsigned long _CurrentMillis;
    int _RefreshRate;
    //Sensor instances
    LDR _Sluz;
    DHT11 _SDHT;
};

Of course, in your header file, you will have to #include the proper header files for DHT11 and LDR classes.
Then you will need to change your constructor as follows:
Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin)
:_Sluz(luzpin), _SDHT(dhtpin)
{
    //Clock management
    _RefreshRate = refrate;
    _PreviousMillis = 0;
}

Note the :_Sluz(luzpin), _SDHT(dhtpin) line before the constructor body, in C++, this is how members of your class that are instances of another class must be instantiated.
Actually, you could even empty the whole cosntructor body by also initializing _RefreshRate and _PreviousMillis in the same manner:
Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin)
:_PreviousMillis(0), _RefreshRate(refrate), _Sluz(luzpin), _SDHT(dhtpin) {}

which is a bit more idiomatic C++.

Seems like you hit the nail with what I'm trying to achieve. Is any problem if LDR and DHT11 are defined in the same header that Habitáculo?

No there is no problem here, as long as they are defined first, before Habitaculo class.

Done. So many thanks for the answer. Definitely I have to dig more in c++ and it's syntax. Thanks again!

class _Sluz;
class _SDHT;

You're forward declared two classes but I see nothing about what those classes are. You then to and use those class declarations as if they were class instances.
I think you are lacking a bit of basic syntax knowledge there. You may have meant:
Sluz _Sluz;
SDHT _SDHT;

Though not knowing what those classes are meant to be or how they are even defined I cannot know really what you think you're meaning.

I assume. It's basic knowledge lack. What I want to do is put two instances of LDR and DHT11 (defined and working) inside Habitáculo instance with names sluz and sdht

Are they instances that are defined outside the class (in your main sketch), or do you want to create two new, distinct, instances within your class?

I want to create them when I create an Habitáculo instance

So the "class" needs to be the actual class name that you are instantiating then. Like you would if you were making them in your sketch, but without any constructor arguments (those have to be in an initialization list for your constructor).


text:
Adapt a differently pin-interspaced chip to be used with an Arduino
Happy new year to everyone!
This is how my chip looks like:

Those numbers are millimeters. Both the pin spacing and pin width are different from what Arduino uses.
Is there any quick (or less quick) and reliable way to connect this chip to an Arduino Uno ?

It is not clear what you intend to do, but why not simply use wires and soldering?

@jfpoilpret Based on my tools, ability and the scheme above I would think I could not do it. The pin rows are too tightly spaced.

I'd use some solid copper wire, similar to shown in this video https://youtu.be/5iIcGaf7qPA?t=411 (6:51)

Wire wrap is an old technology, that may work best on the intended long square pins, but it will work on shorter headers like this too, and you can usually fit the tool between 2mm pins as well as the intended 2.54 mm ones.  It can thus be a handy semi-permanent way to make these connections without getting out the soldering iron (or getting solder on pins you may want to repurpose later), and you can always solder it later as well to overcome any long-term reliability questions from using wrapping on the wrong shape of pins.

The simplest option is to buy a pre-made ribbon cable with 2mm pitch (7x2) IDC connector on it.
Solder the free end (or cut the second connector off and strip it if you have a two-ended cable) and solder it to strip-board on which you have already soldered a 14-pin header for breadboard use.

An example of the cable I mean.

this inspired me to go through the junk heap of cables and I have found an old parallel cable that I hacked for my purpose.

Adapters from 2mm to 2.54mm (0.1") spacing exist.
Here is
an example and another example.
Alternatively you could make up a little PCB or, as suggested by @jfpoilpret, solder wires on.
A further option is to cut a piece of stripboard, score down the middle to break the tracks, stick your chip on, and run wires from the 2mm-spaced pins to the 2.54mm-spaced pins.  Off-cut resistor legs work fairly well, in my experience.  Here's one I made (fairly clumsily) earlier.  Your soldering skill may be better than mine. .

Thanks MArk; two problems with those adapters -first I would not want to wait for them a couple of weeks until they eventually reach me and they can only do one row of pins whereas my chip got 14 pins on two rows (7 + 7). Could you expand on making my own PCB ? Is that fast ? What do I nee for that ?

Clarified that there are two links in my answer. The wires would do the trick, or you could use two of the boards, one on each side.  Making your own PCB would be time-consuming and fairly difficult to do well (drilling it particularly, in my opinion and for my level of skill), and you'll have to wait just as long for the stuff to do it.  Google or YouTube will tell you how to do it, I'm sure.


text:
Turn on a LED when an other LED turn off
I'm a beginner on arduino.

I have an arduino mega with two LED (like the image with only 2 less and without the buzzer). A red LED and a green LED. When the arduino receive the code 200 I want the red LED turn on and the green LED turn off. But when I test that but any led turn off or turn on..
void setup()
{
  pinMode(LR, OUTPUT);
  pinMode(LV, OUTPUT);
  Serial.begin(9600);
}

void readSerial(){
  while(Serial.available() > 0){
    car = Serial.read();

    if(car != '+'){
      buff[i] = car;
      buff[i+1] = '\0';
      i++;
    }
    else{
      sscanf(buff, "%d", &received_code);
    }
  }
}

void loop()
{
  readSerial();
  if (received_code == 200){
    LRstate = HIGH;
    digitalWrite(LR, LRstate); // turn the LED on (HIGH is the voltage level)
    digitalWrite(LR,LOW);
    delay(100);
    digitalWrite(LV,LOW);
  }
}

How can I solve my problem?
Thanks a lot.

Please rephrase But when I test that but any led turn off or turn on., as this sentence isn't very clear.

Based on the connection and coding problems, I read this as "none of the LEDs responded."

JRobert addresses some of the wiring problems in his answer, but also note that the outer two rows on each side of the breadboard (the rows between red and blue lines) are connected the long way – that is, make up 50-pin bus lines – vs the columns-of-5 on each side of the centerline being connected the short way, making 5-pin bus lines.  So the diagram connects a bunch of Arduino outputs together, which is wrong wrong wrong usually

If your circuit is really connected as shown in the diagram, then your Arduino should have grilled already, since this diagram shows all outputs pins for LEDs directly connected to GND: short-circuit when an output pin is set to HIGH!

First, make sure the LEDs are connected correctly: I presume the red LED is connected to whichever pin LR is, and the green LED to LV.
According to your diagram, your LEDs will be on if the output is HIGH, and off if the output is LOW.  Your code sets LR to high, but then immediately to LOW again.
Here's a fixed (I hope) verson of your loop():
void loop()
{
  readSerial();
  if (received_code == 200){
    // Turn the red LED on
    digitalWrite(LR,HIGH);

    // Turn the green LED off
    digitalWrite(LV,LOW);
  }
}

Unrelated to the problem you're having, but worth a mention anyway:
There's nothing in your code to stop you overrunning buf if you get a longer input than you're expecting.  If this happens you'll get unpredictable results as you trash over whatever happens to be in that part of memory.

The code you showed turns on LR and turns off LV if received_code == 200, which I suppose meets the specification as given, since how the LEDs get back to LR off and LV on isn't stated.  But the question's loop() has a delay(100); in it, suggesting switching them back after that delay

@jwpat7 Yes - although I wasn't sure if that was intentional. It's hard to tell which of that group of lines doesn't match the intended behaviour, since it's not absolutely clear what the intended behaviour is.  If the OP clarifies what he wants, I'll adjust accordingly.

In addition to the code changes noted by @MarkSmith, the LEDs are not connected properly. The straight LED pin on the Fritzing diagram is its cathode and must be connected to grounded, and the bent pin is its anode and must be at +V (+5v, in this case), for the LED to light. To turn the LED on, the anode must be at +V and the cathode at ground. To turn the LED off bring both pins to the same voltage, usually by grounding the anode (logic 0 on its connected pin).

To identify the cathode on a real LED, look inside its plastic blob (that's a technical term :) and you'll see two bits of metal, each on a wire, like two flags. The larger flag is the cathode. Usually, the cathode also has a shorter external lead and the plastic blob has a flat edge on that side, but the larger flag is definitively the cathode:


text:
H_Bridge with PWM gets too hot
I'd like to use an H-Bridge  AND send PWM signal.
I've used this schematics: http://itp.nyu.edu/physcomp/Labs/DCMotorControl
and use the PWM signal inside the enablePin. But the H_Bridge is getting very hot.
Am I wrong?
EDIT:
I'm using and H-Bridge but not for driving a motor, instead I'm driving a peltier cell (like this one: https://www.sparkfun.com/products/10080). What I'm trying to achieve is to have a fixed peltier cell and to have in the same side sometimes hot, sometimes cold. This behaviour is done by switching the positive and negative with the H-Bridge. To control how much cold and how much hot I'm using PWM.

Short answer: You're drawing too much current through the H-bridge.
Longer answer: The H-bridge is most efficient when fully on and that's when the chip gets rated for the maximum current. The rating also, probably, states that a heat sink is attached to the chip. Using PWM to slow down the motor decreases the current going through the bridge, but also incurs inefficiencies because the transistors / MOSFETs are partially on, and thus acting somewhat as resistors. This inefficiency manifests as heat.
So you have several options.
1. Choose a smaller motor.  This reduces the overall current needed.  Only feasible if this is a learning project.
2. Choose a beefier H-bridge.  This increases the ratings of the bridge to handle current for this motor.
3. Add a heat-sink to the existing bridge.  This will help dissipate the heat generated.
Generally I'd recommend both 2 and 3, but it depends on your ultimate goal of the project.

I'm not using a motor, see the edits.

Ok, but the same applies to the peltier device. You're drawing too much current through the chip.  Choose a different chip for the bridge and heat-sink it. Though that may seem odd for a project with heating / cooling features, but if your bridge overheats it will stop doing what you want.

According to data sheet from factory, L293 and L298 do not go into fast stop mode if you connect and program them as below.
They have two inputs to control direction and one ENABLE for PWM.
When PWM signal is zero, both transistors are high impedance according to page 2 of factory data in http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=0CDUQFjAB&url=http%3A%2F%2Fwww.ti.com%2Flit%2Fds%2Fsymlink%2Fl293d.pdf&ei=0z7dU-G4OZPf8AX-loDQCA&usg=AFQjCNEHiZAPaBUP_j8kV3BBPstAKiFDyw&bvm=bv.72197243,d.dGc
Data sheet Page 6 of L298, PWM connects to enable. CD is 10 and 01 for direction. fast stop is CD 00 or 11
http://www.st.com/st-web-ui/static/active/en/resource/technical/document/datasheet/CD00000240.pdf
Hope it helps

This L298N board with heat sink is widely available, low cost, used in many successful project with 2 amperes capacity to support reasonably large motors.
Video, tutorial, code example in:
http://www.youtube.com/watch?v=qwNvYYqBy7I
http://www.icstation.com/product_info.php?products_id=2540#.U90l_kBbIlh
http://arduino-info.wikispaces.com/MotorDrivers
http://arduino-info.wikispaces.com/ArduinoShieldL298N

I'm not using a motor, see the edits.

Your peltier cell is 7A, well above L293 and L298. Choose one of these, says about 10A to 12A (with some spare for safety) http://www.pololu.com/category/11/brushed-dc-motor-drivers. Software is same, motor forward/backward become hot/cold. No issue of fast brake in your case. Some 2 pins units can be used. if doubt, ask tech support of the seller and they also have excellent document at web.

Temp control is relatively slow, depending on heat capacity of load. PWM can give you very accurate temperate control at range of 0.1 degree centigrade or better. If cost is concern, use on off control if no demand for too high accuracy, by solid state relay or mechanical relay (switching time slower, lower accuracy).

Are you using the L293NE or the SN754410?
My guess it the L293NE. With this one, if you set the enable to low, it will go into "Fast motor stop". What this does is short the two pins of the motor. This will make the motor turn into a dynamo, will all the current that is being generated going through the IC. This will make the IC hot.
This also means you motors are running very inefficiently.

I'm not using a motor, see the edits.

Try lowering the PWM frequency to something like 1hz.


text:
Multiplexing help for relay and pwm
I have to control with an Arduino UNO and xbee shield:

9 5V relay
9 RGB LED

What kind of multiplexing can you advice me? Do I have to use external power supply (like 12V DC external from arduino or from vcc)? Is there any kind of already ready-to-use shield?
EDIT
I'm planning to use a 8 relays shield plus one single relay

You can use shift registers to control the relays. This will only use 3 pins and allow you to use the xbee.
For the RGB LEDs you can use the TLC5940 to control 16 channels, so you will need two, giving you 32 channels. This is a PWM chip with serial interface.
Considering you will be using the board linked. It is driven by transistors, so you can use the shift registers.
For the power supply, if you will be operating all of the relays at the same time it will draw about 650 mA (9x72mA), you will need a separate 5V power supply for the relay board, as I believe drawing that much current will heat the board and regulator a lot. If one at a time it will not draw too much, so its possible you can run it all off the Arduino.
A forum post of someone running 360 relays with shift registers.

all of the relay can be on all time, and also the led

@nkint - definitely get a separate power supply. A power supply that can give 5V 1A should be sufficient


text:
Not sure I'm understanding pipes for NRF24
I've started working with the NRF24 library for some fun little side projects. I have only gotten through some basic tests but I'm starting to look at ways to tinker with the code. I have more experience as a programmer so the hardware side is always new to me. Where I'm a little confused is how the pipes are used. Working from this example, I see that one pipe is used to listen and another is used to transmit. If there's just two devices, why don't they both use the same pipe? If you have multiple devices on the same pipe transmitting, can it jumble the signals? Is there a way to receive on multiple pipes? I'd love more information on how pipes are or should be used.

I don't see any reason for doing this.
Multiple devices sending data at the same time will cause collisions irrespective of the pipe-nr they are using.
Pipe is also a not very accurate name for what it actually is. It's just a number, that the receiving NRF can check, to see if the packet that was received was intended for it. Kind of like a MAC address on a network.
You can have two unique reading pipes. Then there are 4 more pipes you can use, that are identical to the second pipe, except for the last byte.
The first pipe is used to specify the pipe you are sending through. So if you send to different pipes, this pipe isn't ideal for listening, as you'd have to change it back every time you send a packet. Possibly loosing a packet that was send in between.
If you want more information, i'd suggest reading the datasheet, and read the documentation of one of the libraries. I personally checked the sourcecode of the library a lot while at the same time referencing the datasheet, to really understand what it's doing.

Thanks that helps clear it up a bit. I've got a bit more to learn on it still but I think that clears some of the confusion up for me.

They are kind of weird these NRF24s

But they're cheap and if they work, they work. :D


text:
is there a timeout for Ethernet.begin?
I'm working on a project, but just for testing, I haven't connected it to the internet yet, even though the code SHOULD be ready to roll out.
When trying to test some of my code with the serial console, I realized my program was locking up and I traced it down to here. Now my arduino uno and ethernet shield isn't currently connected to the internet, so my question is, how could I timeout this function so that I can keep my program running when there's no internet to connect it too.
Here's my code in the setup function
if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }

If anyone has any thoughts or suggestions, I'd definitely appreciate it.

The default timeout is 1 minute for DHCP. There is also a response timeout, and in the library millis is used for timeouts. I don't know if there is a timeout for everything, but I suppose there is.
If it stops working when no ethernet cable is connected, that would be a bug. If something like that is in the library, then you have no way to bypass the Ethernet.begin when it took too long. How long did you wait ?
This is the source code for Ethernet.begin: Ethernet.cpp

Thanks, this is good to know. I don't know for certain how long I gave it, I'm guessing the customary 30 seconds so I'll need to give this another run and double my patience, lol

The code can actually hang up in W5100Class::execCmdSn function. It waits for command to complete by reading a register and waiting for read to return 0. If it returns non-zero for some reason (poor contact, etc.), the function will hang up.

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


text:
How do I change number and bracket colors in the arduino IDE?
I recently personalized my arduino IDE (changed the background color, input text color, etc....) by going into the theme.txt file and replacing some hexadecimal values. I made the background black and the text lime green, but for some reason numbers and brackets still remain black, thus I can't see them against a black background. Anyone know how to fix this? I would really appreciate the help, got sick of looking at a white background when making sketches.
Sal

Inside path C:\Program Files (x86)\Arduino\lib\theme\syntax there is file default.xml where I made some changes and the following lines are as follows:
  <style token="SEPARATOR" fg="ffffff" />
  <style token="LITERAL_NUMBER_DECIMAL_INT" fg="ffffff"/>
  <style token="LITERAL_NUMBER_FLOAT" fg="ffffff"/>
  <style token="LITERAL_NUMBER_HEXADECIMAL" fg="ffffff"/>

After this brackets and numbers occur white.

Ok i found the file and what I need to change. However, my computer opens the file in internet explorer. Do I need some software to open and edit xml files? If so, any suggestions?

Copy file and paste it to your desktop. Right click and select open with WordPad. Save after edit. Copy and  paste to original place. You are asked for admin rights. Give right by clicking option. Restart IDE.

In some windows you can select right click on file and edit as admin user.

I figured it out, wish I would have read your comment just above first haha would have saved me some trouble. I wound up using Visual Studio to change it. Thank you so much though for all the help


text:
Press on pressure sensor once, turn on LED for 6 seconds
I am working on a project where I would like to press on a pressure sensor (0-1024) once and turn on the LED and turn off by itself after 6 seconds. I am quite new to arduino and I can't seem to understand how to code this with using a pressure sensor as a switch rather than an actual switch. Any ideas?

When it is allowed that the Arduino does nothing during the delay, you can use the delay() function. Using millis() is a lot better, but that requires a specific way to use it. The Blink Without Delay ( https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay ) is a start to learn how to use millis(). Is the pressure sensor a FSR ? Is it a school project ? Can you show your sketch ?

Sensors which give a range of outputs need to have their outputs processed using a technique called hysteresis.  That is, normally, the turn on threshold is higher then the turn off threshold.
For example, the thermostat in your home uses hysteresis when controlling your HVAC system.  Otherwise your thermostat would constantly be turning on and off your HVAC system likely causing an early failure.
Here is a stackexchange Arduino question about hysteresis.

If you're having a problem implementing the system in software, there is a hardware approach to do it. The phenomenon is called monostable multivibrator. Monostable mode retains its output for a certain time interval before coming back to previous state. You can use a simple RC circuit configuration to implement this functionality along with Arduino setup. Just interface FSR in voltage divider format, read the voltage and switch another GPIO interfaced with RC circuit configuration.


text:
Powering 3.3v sensors from a coin cell
I want to build some small wireless temperature measurement boards, to sprinkle around the house. I'd like to power these from a single coin cell battery (CR2032).
For these I'd like to use the DS18B20 sensor. These sensor require a minimal voltage of 3v. A coin cell will however only provide 3v when it's full, and will drop to around 2.6v when 90% discharged.
From what I've read the DS18B20 will give some strange results when the supply voltage is below 3v. Also the precision can be off, when the supply voltage isn't regulated.
(The ATMega328p and NRF24L01, I plan to use, will work just fine at voltages down to 2v, so only the DS18B20 requires 3.3v.)
So I've come up with the following solutions:

Use two coin cells, and a (low quiescent current) voltage regulator. (Disadvantage: takes more space, more batteries, slightly more expensive.)
Use a boost regulator. (Disadvantage: even more expensive, and a lot more complex (for me at least).)
Implement a voltage doubler to power the DS18B20 when needed (every 15 minutes). To regulate the voltage I'd add a 3.3v zener diode to the output. (dirt cheap to implement)

I tend to lean toward option 3, but my question is, could it even work?
Is there something to look out for?
Or is there an even better solution?
edit I was planning to use the Dickson doubler circuit.

What type of voltage doubler are you considering?

@Majenko A Dickson doubler. See the schematic in my edit above.

A dickson is certainly a possible solution, and is commonly used in battery powered systems to get a higher voltage to run components that need it.  Better though is to not need it in the first place since any voltage conversion will entail losses that will shorten your ideal battery life.

If you are using a doubler you should use Schottky diodes to minimise voltage drop. Using a Zener diode without a limiting resistor would work in this circuit, but is likely to be very inefficient. A series regulator would be better. You could use a feedback circuit to vary the high phase of the clock as a simple switching regulator, and eliminate the Zener.

@Milliways I'll have to calculate the correct capacitor value, and frequency, to match the current needed for the sensor. Any excess current will indeed be lost through the zener.

You're missing out option 4, which is the option I would personally go for:

Use a different temperature sensor.

A quick parametric search on Microchip (my favourite, I'm a Microchip fanboy after all...) I find quite a nice one - the MCP9844.

Microchip Technology Inc.’s MCP9844 digital temperature sensor converts temperature from -40°C and +125°C to a digital word. This sensor meets JEDEC Specification JC42.4-TSE2004B1 mobile Platform Memory Module Thermal Sensor Component. It provides an accuracy of ±0.2°C/±1°C (typical/maximum) from +75°C to +95°C.
Operating Voltage Range (V): +1.7 to +3.6

However it is only available as a TDFN which makes prototyping difficult, although it is one of my two preferred footprints for real building - the other being variants of QFN.
I am sure you can search other makers for similarly specified chips that will do the job without the need for fancy boosters or doublers or the expense of multiple batteries etc.
One of the first steps of any design is the component identification. Often the chip or component that many people automatically reach for because it's the first one they used, or it's the one people most often talk about, may not be the right tool for the job. It pays to shop around a bit and look to see if there is something better that will fit the bill and save cost and time in the long run by ending up with a simpler system.

That's an interesting alternative. I was indeed working backwards on a problem. I wanted to try soldering TDFN/QFN anyways. Thank you. I'll go and search some more alternatives, and see what's available from my regular webshops.


text:
How to run a timer every 12 hours (exceeding the max size of int) without an RTC?
I'm experimenting with a Nano, and trying to trigger an action around twice a day. I'm aware that it's not super accurate, but I don't really mind, as long as it's in the ballpark.
I've tried using the SimpleTimer library but I'm running into an issue because it takes milliseconds as an int, and 12 hours is 43200000 (larger than 32,767 max). Is there another library, or another technique I can use for this?

On the page you linked it takes a long as an argument, not an int: int setInterval(long d, timer_callback f).

@NickGammon has it; there is no such limitation on the interval argument to setInterval() as "it takes milliseconds as an int". It takes a signed long, though it treats it internally as unsigned long, thus the max interval is over 49 days. Mark's answer will work, too, but is not actually necessary.

I better make it an actual answer then. :)

Set the timer for every hour, which is within the limit. In your action, keep a static int, initialized to zero, which you increment each time. When it ==12, do the thing you want to do and reset your int back to zero.

dang that's simple and smart

I'm running into an issue because it takes milliseconds as an int ...

No it doesn't. Look at the function prototype:

int setInterval(long d, timer_callback f);

Call function f every d milliseconds. The callback function must be declared as void f().

The interval d is a long. The int you see is the return value from the function, not the interval.

You have 2 other options to the setInterval() function:

delay() (blocking)
millis() (non-blocking)

Both of these functions deal with an unsigned long which has 32 bits = (2^32)-1 = 4,294,967,295. Doing the sums (and considering that both are in milliseconds), this will last for 49 days and 17 hours.
1 second = 1000 milliseconds
1 minute = 60 seconds
1 hour = 60 minutes
12 hours = 12 * 60 * 60 * 1000 = 43,200,000
delay(x) will delay for x number of milliseconds.  The delay function is blocking, meaning that while it is running/delaying you can't do any other task. The code would be:
delay(43200000);

millis() on the other hand is non-blocking and returns the number of milliseconds since power-up.  This can be implemented with the following code:
#define TWELVE_HRS 43200000UL
unsigned long startTime;

setup()
{
  startTime = millis();
}

loop()
{
  if (millis() - startTime > TWELVE_HRS)
  {
    // Put your code that runs every 12 hours here

    startTime = millis();
  }
}


text:
Vibrating motors with different intervals
For my project, I have 3 ultrasonic sensors and 3 vibrating motors; the motors need to buzz for a small amount of time, then wait for a specific time that corresponds whith the range of the ultrasonic sensor, then muzz again.
The problem I'm having is that I used delays at first but that would cause the third motor only to buzz after the first two already waited.
I basically need something like "digitalWrite(motorPin_1, HIGH) for X amount of time;"
and at the same moment it has to start "digitalWrite(motorPin_2, HIGH) for X amount of time;".
Sadly I can't get the motors to vibrate any softer or harder, so I use these intervals.

Did you check the Blink Without Delay Arduino tutorial?

oh, thanks i had no idea it was so simple. with the blink it works just as i wanted! :)

Like Edgar commented, you need to check out Blink Without Delay (http://arduino.cc/en/Tutorial/BlinkWithoutDelay). Learn what they are doing and you will get this just fine.
Also, I recommend you learn to use libraries. This library can do exactly what you are asking for: http://playground.arduino.cc/Main/LibraryList#Timing --> click on the "Timer" library by Simon Monk & J Christensen. Follow the examples there. This library works great!
Here is a complete set of code to answer your question. It should work perfectly for you.
/*
buzz3Motors.ino
By Gabriel Staples
http://electricrcaircraftguy.blogspot.com/
7 March 2015

To help this person here: http://arduino.stackexchange.com/questions/9089/vibriting-motors-with-different-intervals
*/

#include "Timer.h"

Timer t;

boolean buzzMotor1Now = false, buzzMotor2Now = false, buzzMotor3Now = false;
unsigned int buzzTime = 1000; //ms
byte buzzPin1 = 11;
byte buzzPin2 = 12;
byte buzzPin3 = 13;

void setup()
{
  //set pins to outputs
  pinMode(buzzPin1, OUTPUT);
  pinMode(buzzPin2, OUTPUT);
  pinMode(buzzPin3, OUTPUT);
}

void loop()
{
  //UPDATE YOUR BUZZMOTOR BOOLEANS HERE, and set to true if necessary

  /**
   * This method will generate a pulse of pulseValue, starting immediately and of
   * length period. The pin will be left in the !pulseValue state
   */
  //Function format: int8_t pulseImmediate(uint8_t pin, unsigned long period, uint8_t pulseValue);
  //see here: https://github.com/JChristensen/Timer/blob/master/Timer.h

  if (buzzMotor1Now==true)
  {
    buzzMotor1Now = false; //reset
    t.pulseImmediate(buzzPin1,buzzTime,HIGH);
  }
  if (buzzMotor2Now==true)
  {
    buzzMotor2Now = false; //reset
    t.pulseImmediate(buzzPin2,buzzTime,HIGH);
  }
  if (buzzMotor3Now==true)
  {
    buzzMotor3Now = false; //reset
    t.pulseImmediate(buzzPin3,buzzTime,HIGH);
  }

  t.update(); //update all timer events
}

Note that only 10 timer events can be ongoing at any given time. If you want to have more you must increase the MAX_NUMBER_OF_EVENTS value in the Timer.h (https://github.com/JChristensen/Timer/blob/master/Timer.h) file.
PS. Also look into the "oscillate", "after", "every", and "pulse" functions, that the library also supports.
If this answer meets your needs please mark the green check beside it to indicate accepted answer. Thanks.

you are completely right, the timer library works great, thanks for your replie. :p


text:
16Hertz Uno R3 Board vs Arduino Uno R3 Board
I bought a 16Hertz Uno R3 Board. When I installed the driver and the Arduino IDE,  in the IDE`s menu I saw:

Tools -> Board -> Arduino Uno

was selected by default which is great, but...

Tools -> Port -> COM3(Arduino Mega or Mega 2560)

was selected by default which I think might be some kind of misunderstanding...
When I chose:

Tools -> Board -> Arduino Mega or Mega 2560

On that tools menu appeared new menu "Processor" with two options:

Tools -> Processor -> ATmega2560 (Mega 2560)

which was selected by default and there was another option

Tools -> Processor -> ATmega1280

When I restore Tools -> Board settings back to "Arduino Uno" the "Processor" menu with the two options disappeared and Tools -> Port setting did not changed!
If you take my board and look at the Microcontroller there is written:

ATMEGA328P-PU

Also on that board is written:

16HzUNO

I need to know:

What does 16Hz mean? Does it mean the clock or frequency of this
Microcontroller? I think it does not, if I try to find out details of my Microcontroller on the rs-online site, there is written:

ATMEGA328P-PU, 8 bit AVR Microcontroller 20MHz 1 kB, 32 kB Flash, 2
  kB RAM, I2C 28-Pin PDIP

Why was there "COM3(Arduino Mega or Mega 2560)" written on the
Port's menu?
Is my 16Hz Uno R3 and the Arduino Uno R3 board the same? Which one
is better? When one of those is better?
Does the standard Arduino Uno R3 board have the same ATMEGA328P-PU
Microcontroller?

You need to have a look at the Arduino comparison table. This shows that all Arduino Uno boards run at 16 MHz. It seems that you have fallen for the marketing on the page for the Uno kit that you provided.
Also, which version of the IDE are you running? You should upgrade to the latest version, which is currently, at the time of writing, version 1.6.1.
To answer your questions in turn:

"16Hz" is the brand name and has nothing whatsoever to do
with the speed, which is actually 16 Mega Hertz. "Clock" and
"Frequency" refer to the same thing. 16 MHz is the clock frequency
of the board, and is the speed at which the ATmega328 runs at.
The RS Online link does indeed state 20 MHz, but that is merely the
maximum speed at which the ATmega328 can run at. The Uno under clocks it at 16 MHz.
The Ports menu will show you a number of possible devices, Arduino Uno should be one of them (which is the one you should select) and three items below that will be Arduino Mega or Mega 2560 (which you should ignore, you do not have a Mega board1). Unfortunately the Arduino site only shows the Mac menu, even on the Windows guide

which is no help to you, assuming that you are running the Arduino IDE on Windows. You should actually see this in the Board menu:

and this in the Port menu:

As you can see, there should be no mention of the microcontroller in the Port menu.
The 16Hz branded Uno and the Arduino Uno are to all intents and purposes the same and as I state in the first line, the 16 MHz Uno is exactly the same as a regular Uno, it is just marketing.
Both the 16Hz and the Arduino Uno have a ATmega328 and the Mega board has a ATmega2560. Again, check the Arduino comparison table to see the variety of the boards and their respective microcontrollers.

I hope that answers your questions.

1 If you do chose the Arduino Mega or Mega 2560 option, in the Board menu, then indeed there will be an additional Processor menu. However, this is irrelevant in your case, as you do not have a Mega board, and so you need to chose the Uno in the Board menu. If you do so, then the Processor menu will disappear, as it is not needed for the Uno.

Every Arduino is using a quartz crystal in order to get the frequency needed. ATmega328 can handle up to 20 MHz
??
Yes. You can't run the microcontroller by itself. It has an internal oscillator but none is using it. So basically you will have a 16 MHz crystal.
Pretty much the Arduino Uno, Nano, Mini and few others have the ATmega328P.
Note that the -PU -AU at the end defines the package. So they're the same.

Arduino Mega, Leonardo, Micro, Due use other chips.

Just a theory for 2:
The text that shows up in the Tools > Port list after the COMx
eg Tools -> Port -> COM3(Arduino Mega or Mega 2560)
is simply what the IDE thinks the board is based on the USB ID (VID/PID) of the board's USB interface chip. For some clones, this is blank because they don't even use the same chip as an authentic Uno. In your case, I would suspect that they have used the USB chip from a Mega board on your Uno board.
So the IDE thinks a Mega is attached because it is seeing a USB chip from a Mega, even though it is an Uno (clone).


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

Other than with X10?

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

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

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

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

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

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

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

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

authors: Μιλτιάδης Παντελαίος


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

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

int i = 0;
int state = 1;

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

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

 char key = kpd.getKey();

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

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

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

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

         //match input array to password array

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

         {

         //match input array to password array

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

         {

         //match input array to password array

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

         {

         //match input array to password array

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

         {

         //match input array to password array

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

         {

         //match input array to password array

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

         {

         //match input array to password array

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

while (state = 1);

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

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

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

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

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

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

How can I do it?

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

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

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

I guess it has to do something with my array?


text:
Smooth out digital signal from SW-420 vibration sensor in order to record duration?
I'm attempting to make a sensor that will record the duration and frequency of a pump going off. It always fires for at least 4 seconds, but the duration can be up to 7 days.  The vibration sensor I have is a SW-420, which I think will work. I'm fairly new at this, and I don't mind figuring out the actual code myself, but I'm running into newb problems.

Should I approach this as an interrupt that uses a callback while loop, or would it be better to look at it as a typical debounce sub? Is there a better solution?
Since the duration can (very rarely) exceed running for more than a few minutes, I'm wondering if I need an RTC module. The time is not very important, it just needs to be "close".
The duration info will be fed to node-red via MQTT. I can count frequency in that system... I'm trying to decide if I should do remote frequency calculations, or try and wrap it into the firmware on the Arduino. Any suggestions for this?

Bonus points if I can accomplish this without any additional libraries. I'd love to put this on an ESP8266.
Thanks for your help, I appreciate it.

Should I approach this as an interrupt that uses a callback while loop, or would it be better to look at it as a typical debounce sub?

No. If you want to use interrupts then just record the start time on one edge of the signal and subtract it from the current time on the other edge (not sure which edge is which on that sensor).

Since the duration can (very rarely) exceed running for more than a few minutes, I'm wondering if I need an RTC module. The time is not very important, it just needs to be "close".

It depends how you define "close".  An RTC can give you better accuracy over long periods, yes, and the Arduino struggles with > 49 days by itself.

The duration info will be fed to node-red via MQTT. I can count frequency in that system... I'm trying to decide if I should do remote frequency calculations, or try and wrap it into the firmware on the Arduino. Any suggestions for this?

What kind of frequency are you wanting? The frequency of the vibration itself, or the frequency at which some vibration occurs?  If the former the sensor you have won't do the job - that just tells you when there is vibration above a certain threshold.
To sense the actual frequency of vibration you need a more hands-on approach by the MCU. Either use the raw HDX-2 vibration sensor as used on the SW-420 (that's the blue tube at one end), or do it properly and use an accelerometer which you sample over time and perform an FFT on the sampled signal to isolate the different frequencies.

Thanks for responding. This sensor is normally closed, I'm pretty sure I can figure out which edge to use. It's just nice to have a direction to move towards.

The sensor (HDX-2) is normally closed, but it integrates that with a capacitor and uses a comparator to set a threshold. It's the output of the comparator that gives you your two edges, and I haven't spent the time working out which edge would be which.

The frequency I'm looking for is how often the pump goes off, not the actual vibrations of the pump. I basically want to know that the pump went off for 6 seconds at 10:59:40 and then again at 11:04:20 for another 6 seconds. This is the frequency I'm looking for. The timestamps can be handled by the remote end based on when the MQTT message was received, so I only have to pass on a duration of X seconds.

Then this sensor sounds fine to me.

I think that I may not have been clear on one point. When this sensor gets activated, it's not a simple ON and then OFF. it's a series of ON OFF readings that are between a few microseconds and several seconds. The hard part for me is determining the FIRST on and the LAST off. Any pointers on that one? I think that is what I was getting at when I mentioned the while loop... in my head, I see jumping into a while loop when the first ON is triggered, and then staying in that loop until last OFF was received > X MS ago. Does that make any sense, or am I just complicating things?

In that case you probably want to treat it like a normal button and debounce it well.


text:
How to reset an Arduino with node-serial?
I was reading about using an Arduino with a Makefile. In the Makefile-Arduino project there is a reference to the Python serial library required to reset the board.
Looking into the usage of PySerial to reset the board, there is some reference to DTR or here

What is DTR?
How to control this bit with node-serial and reset the Arduino?


text:
Electric interference from cnc spindle
I've got a CNC machine and I recently started using a spindle for it. At first it was running smoothly with no issues, but after the first brush pair wore off (I've replaced them later on) it started interfering with the Arduino/gshield and pc monitor. The monitor displays a "no signal" message, although after turning off the spindle or turning it to a low speed the signal comes back. The other problem is that after running a long job, sometimes the gshield disconnects and the job stops midway.

What part could be causing all this interference?
How can I shield that part so it stops interfering with other electronics?

I am using the following hardware:

600 watt spindle
600 watt power supply with variable speed
the wires from the spindle to the power supply are not shielded, although Ive tried covering them with aluminium foil, not sure if that should be of any benefit, I've read it somewhere so I gave it a try.
Gshield with Arduino, connected to a Raspberry pi.

All the electronics are within 70 cm radius.

"At first it was running smoothly with no issues...", which is good, but then "the first brush pair wore off" and "I've replaced them". I would suggest that you stop focusing on the country that manufactured the spindle and look instead on what changed to make the problem occur.

Brushes often need to "wear in" so that the ends of them fit nicely to the curvature of the commutator. Until that point you can get a lot more sparking than normal.

if the X  part dicsonnects, there probaly is arcing and making interference.

I would guess that arcing in the spindle causes spikes that travel through the power supplies and power wires. One thing you could try is to use a really long extension cord (say 15 meters or more) to power the spindle power supply. You can insert this cord to a different power outlet to gain additional distance.

@Omar K : It might be useful for others encountering similar issues if you described what you did and what results you got. That's what is great about stackexchange / stackoverflow: a huge knowledge base is created, piece by piece.


text:
Arduino DUE samples per second with the DAC
I want to know how many samples per second the arduino due DAC can generate, I need to generate an ultrasonic signal (40Khz), the arduino due is not going to do anything else that generate this signail for a very short period of time.

With this code, the Arduino DUE was able to generate 250 samples per second approx. I tested it with a signal generator and an oscilloscope. I have found it on this web page http://www.electrosmash.com/pedalshield. All credit is for them.
Here is the code:
// Licensed under a Creative Commons Attribution 3.0 Unported License.
// Based on rcarduino.blogspot.com previous work.
// www.electrosmash.com/pedalshield

int in_ADC0, in_ADC1;  //variables for 2 ADCs values (ADC0, ADC1)
int POT0, POT1, POT2, out_DAC0, out_DAC1; //variables for 3 pots (ADC8, ADC9, ADC10)
int LED = 3;
int FOOTSWITCH = 7;
int TOGGLE = 2;

void setup()
{
  //ADC Configuration
  ADC->ADC_MR |= 0x80;   // DAC in free running mode.
  ADC->ADC_CR=2;         // Starts ADC conversion.
  ADC->ADC_CHER=0x1CC0;  // Enable ADC channels 0 and 1.

  //DAC Configuration
  analogWrite(DAC0,0);  // Enables DAC0
  //analogWrite(DAC1,0);  // Enables DAC0
}

void loop()
{
  //Read the ADCs
  while((ADC->ADC_ISR & 0x1CC0)!=0x1CC0);// wait for ADC 0, 1, 8, 9, 10 conversion complete.
  in_ADC0=ADC->ADC_CDR[7];               // read data from ADC0
  //in_ADC1=ADC->ADC_CDR[6];               // read data from ADC1
  //POT0=ADC->ADC_CDR[10];                 // read data from ADC8
  //POT1=ADC->ADC_CDR[11];                 // read data from ADC9
  //POT2=ADC->ADC_CDR[12];                 // read data from ADC10

  //Add volume feature with POT2
  //out_DAC0=map(in_ADC0,0,4095,1,POT2);
  //out_DAC1=map(in_ADC1,0,4095,1,POT2);

  //Write the DACs
  dacc_set_channel_selection(DACC_INTERFACE, 0);       //select DAC channel 0
  dacc_write_conversion_data(DACC_INTERFACE, in_ADC0); //write on DAC
  //dacc_set_channel_selection(DACC_INTERFACE, 1);       //select DAC channel 1
  //dacc_write_conversion_data(DACC_INTERFACE, out_DAC1);//write on DAC
}

According to the datasheet:

2-channel 12-bit 1 msps DAC

So it's possible to generate 1 million samples per second. Of course that kind of speed would need DMA to drive it smoothly.
Assuming you want to generate a sinewave at 40KHz you have to first ask yourself what resolution (time-wise) you want from that sinewave, since that's the frequency that you need to generate samples for. For instance, if you want 100 samples in your sine wave you'd need to generate those at 4Msps, which you can't. At 10 samples per cycle you'd have 400Ksps which is more manageable, but the quality of the sinewave would be pretty poor.
Or, if you don't need a sinewave, if a square wave would do, just use a normal digital IO pin. You can generate MHz then.

I have never use any arduino board before, if i am rigth, the command to generate a signal  with de DAC is analogwrite, The resolution is not a problem I beleave, do you think that comand can generate those 10 samples per cycle???

I am saying this beacause I need to keep it simple, I do not have time for getting involve with more DMA code :D


text:
I2C — set int pin
I am using a blend micro board, where the digital pins 4, 6 and 7 are reserved.
I have connected a MPU6050 which uses the I2C protocol, so there is the need for the i2cdev lib to handle that.
The example I am using tells me to use pin 7 as int pin for the mpu6050, but that is not possible, since it is reserved.
Does anybody know how I could set this Pin to some other?
Thanks in Ahead!

Could you link to your example? The only other hardware interrupt pins on the ATMega32u4 are 0,1,2 and 3 (RX, TX, SDA SCL). So 2 and 3 are not available. That leaves 0, and 1, unless you are using serial for some other module. But maybe the example doesn't necessarily need a hardware interrupt pin at all.

All I want to setup is based on this project https://edtracker.org.uk/index.php

this is the very template I am using https://github.com/brumster/EDTracker2/blob/master/EDTracker2_6050/EDTracker2_6050/EDTracker2_6050.ino

board setup here: https://edtracker.org.uk/index.php/diy/build-it/breadboard

You need to change the code in that project. Change INT6 to e.g. INT2 if you  are using pin 0 instead.

@Gerben Could you please drop a line of code that shows that? I guess that is what I am looking for…

Change EIMSK &= ~(1 << INT6);, EIMSK |= (1 << INT6);, and ISR(INT6_vect) { from 6 to 2.


text:
How to get the ID of an Arduino?
I use Arduino Pro Mini. As I know, every MCU has a number. Different MCU has different number.  How to get it ?

You should also know that not everything you know is so.

Do you mean, every (single) chip has a unique number? Or does every type of chip have a signature?

@NickGammon   I mean every single chip has a unique number.

Arduino Pro mini is based on Atmega328 which does not have a unique ID. It has only device signature which you can read if you turn on Show verbose output during upload in Arduino IDE's File > Preferences.

But as I know , every Microchip  have a unique number.

Really? Where is this documented?

Could you be confusing the term micro-chip (often applied to any tiny, programmable electronic device) with the manufacturer named "Microchip" (who make the PIC series of micro-controllers, among many other products)? Microchip (the company) does make a line of products that have individually unique IDs. Most manufacturers do not provide unique IDs in their micro-controller devices, and AVR's Atmega 328 series devices do not have unique ID's.

Thanks, I understand you. Because I seemly remeber STM32 and 51 has unique ID, so I think 328 has too.


text:
Use interrupts with analog pins in arduino or another possible solution?
I have a very simple circuit, but my program is some what complicated.
Here is the circuit diagram:

Here is the code:
/*
  01 - GND -------- GND
  02 - +5V -------- 5V
  03 - V0  -------- Potentiometer Middle
  04 - Reset ------ 9
  05 - Read/Write - GND
  06 - Enable ----- 8
  07 - Data0 ------ NC
  08 - Data1 ------ NC
  09 - Data2 ------ NC
  10 - Data3 ------ NC
  11 - Data4 ------ 10
  12 - Data5 ------ 11
  13 - Data6 ------ 12
  14 - Data7 ------ 13
  15 - +LCD ------- 5V
  16 - -LCD ------- GND
*/

//include LCD library
#include <LiquidCrystal.h>

//Initialize an LCD object
/*Pins should be mentioned in this order:
  Reset
  Enable
  Data4
  Data5
  Data6
  Data7
*/
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
int onTimePin = A0;
int onTime = 0;
int offTimePin = A1;
int offTime = 0;
int ledPin = 13;

void setup()
{

  pinMode(onTimePin, INPUT);
  pinMode(offTimePin, INPUT);

  pinMode(ledPin, OUTPUT);

  //Begin the LCD interface
  lcd.begin(16, 2);

  lcd.print("ON  TIME : ");
  lcd.setCursor(0, 2);
  lcd.print("OFF TIME : ");

}

void loop()
{
  onTime = map(analogRead(onTimePin), 0, 1023, 1, 3);
  lcd.setCursor(11, 0);
  lcd.print(onTime);

  offTime = map(analogRead(offTimePin), 0, 1023, 1, 9);
  lcd.setCursor(11, 1);
  lcd.print(offTime);

  digitalWrite(ledPin, HIGH);
  delay(onTime * 1000);

  digitalWrite(ledPin, LOW);
  delay(offTime * 1000);
}

The above code works. But there is a small problem:
When I turn the potentiometer wiper, there is a delay.
It's obvious because when the loop completes, the changed value of potentiometer is displayed. So, I decided to do the same thing using interrupts. But only digital pins have interrupts.
I would like to know the solution for using interrupts on analog input.

There's a delay because you're delaying.

I'd put the led blinking inside a timer(-interrupt). Or use the technique described in blink without delay

@IgnacioVazquez-Abrams I know that there is a delay and I get the expected output. In short I want to have an led blinking as per the values given by potentiometer.

Avoid delay.
Very simplistic alternative:
unsigned long lastLedToggleTime;
unsigned long currentLedToggleInterval;

void loop() {
  ...

  unsigned long now = millis();

  if ( (now - lastLedToggleTime) > currentLedToggleInterval) {
    lastLedToggleTime = now;
    // We need to toggle the LED now.
    if ( digitalRead( ledPin ) == LOW ) {
      // LED was LOW, so we set it HIGH and setup next toggling after onTime.
      digitalWrite(ledPin, HIGH);
      currentLedToggleInterval = (onTime * 1000);
    } else {
      // LED was HIGH, so we set it LOW and setup next toggling after offTime.
      digitalWrite(ledPin, LOW);
      currentLedToggleInterval = (offTime * 1000);
    }
  }
  ...
}

Notice that we're dealing with 32 bit unsigned integer values here, which is why this code will work even if/when millis() rolls over to 0. Specifically, not only will now - lastLedToggleTime always return a positive value (because it is cast into the unsigned data type), it will also return the correct value due to two's complement representation and modulo arithmetic base 2^32.
Example: Let's just look at an 8 bit value for simplicity:
Say, lastLedToggleTime was at the last tick of the 8 bit timer value, i.e. lastLedToggleTime == 255. In the next timer tick, now will overflow to 0, so next we have now - lastLedToggleTime = 0 - 255 = -255. In two's complement, this value would need (at least) 9 bits to represent (binary: 1 0000 0001), but because we only have 8 bits of storage, the sign bit (MSB) is just discarded resulting in 0000 0001 binary = 1. We can see that 1 is the correct value for the number of ticks to get from 255 to 0; it's exactly one tick.

Your solution will fail when millis() rolls over. Although this may not be a very serious issue, there is no reason to keep the bug, especially since it is very easy to avoid. See the Blink Without Delay Arduino tutorial for the proper way to write the code.

millis() "will overflow (go back to zero), after approximately 50 days."

This is why I say “this may not be a very serious issue”. But yet, there is no valid reason to show buggy code in an answer, when it is just so easy to avoid the bug. The pseudo-code in the page you link to is also correct.

@EdgarBonet You did notice that the OP has both variable and independent on and off times?

@EdgarBonet Since it seems to be really bugging you as it was, I edited your proposed solution in now.

Thank you. I have verified the code sample and it works fine.

@EdgarBonet It will fail with the Blink Without Delay Code as well. Once millis() rolls over the pin in the example given will never go HIGH again. It will stay low. You will never get a result again greater than interval once rolled over. You need the absolute value of the interval... abs(interval)

@FredHendricks, You don't understand the roll over. read https://arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover

@FredHendricks Notice that we're dealing with unsigned 32 bit integers here which means we implicitly have modulo arithmetic. That's why now - lastLedToggleTime will always return the correct value, even when lastLedToggleTime is greater than now because now overflowed back to 0.

You are looking for the bad solution for a simple problem. As Ignacio
Vazquez-Abrams puts it, the problem is you using delay(). The simplest
solution is to manage the timings with millis(). See the Blink
Without Delay Arduino
tutorial.


text:
Problems with substring loop
Hey folks … I was hoping some of you might cast your eye over my code.
It splits up a string read from EEprom into an array of separate strings. Based on String length information stored in a separate array. (tempArray[])
It reads fine … and also seems to process fine (ie. it does turn one long string into separate array items)      for some reason it stops working no the 8th array item?
The splitting code (problem) starts on line 80 and i have included the output above it in comments.
http://pastebin.com/Ax4R6t6J   << Full code also available here.
void reJigFromMemory(){

  Serial.print("Eeprom read 1 :");
  Serial.println(eepromReadOne);
  Serial.print("EEprom read 2 :");
  Serial.println(eepromReadTwo);
  String tempArray[10];

  int charLength=eepromReadOne.length()+1;
  char charBuff[charLength];
  eepromReadOne.toCharArray(charBuff, charLength);

  //// GET MEMORY LOCATIONS
  /*
converts long string of numbers:
   13161717171717252533
   into separate strings:
   13
   16
   17
   17
   17
   17
   17
   25
   25
   33

   And stores them in an array.
   */
  for (int i = 0; i <10 ; i++){
    tempArray[i]+=charBuff[i*2];
    tempArray[i]+=charBuff[(i*2)+1];
    Serial.print("I just translated :");
    Serial.println(tempArray[i]);
  }
  /// GET THE STRINGS USING THE ABOVE ARRAYS
  /*
converts long list of data ie:
   |0|Bingo#999#|1|Retest2#9222#|2|Retest3#92299#|3|Retest4#99339#|4|Retest5#95599#|5|Retest6#96699#|6|Retest7#99119#|7|User Defined eighth#0#|8|User Defined ninth #0#|9|User Defined tenth (last) .#0#

   into individual array strings:

   From Number = :0
   To number : 13
   Record 0 :          |0|Bingo#999#
   From Number = :13
   To number : 29
   Record 1 :          |1|Retest2#9222#
   From Number = :29
   To number : 46
   Record 2 :          |2|Retest3#92299#
   From Number = :46
   To number : 63
   Record 3:           |3|Retest4#99339#
   From Number = :63
   To number : 80
   Record 4:           |4|Retest5#95599#
   From Number = :80
   To number : 97
   Record 5:           |5|Retest6#96699#
   From Number = :97
   To number : 114
   Record 6 :          |6|Retest7#99119#
   From Number = :114
   To number : 139
   Record 7 :               <<<<<< THIS ONE IS MISSING ? WHY?
   From Number = :139
   To number : 164
   Record 8 :               <<<<<< THIS ONE IS MISSING ? WHY?
   From Number = :164
   To number : 197
   Record 9 :               <<<<<< THIS ONE IS MISSING ? WHY?

   */
  String tempArray2[10];
  int fromLocation = 0;
  int toLocation=0;

  for (int i = 0; i <10 ; i++){                 /////// LINE 80

    toLocation += tempArray[i].toInt();

    fromLocation += tempArray[i-1].toInt();
    tempArray2[i]=eepromReadTwo.substring(fromLocation,toLocation);
    Serial.print("From Number = :");
    Serial.println(fromLocation);
    Serial.print("To number : ");
    Serial.println(toLocation);
    Serial.print("I just translated :");
    Serial.println(tempArray2[i]);

  }
}

please post code that is complete, i.e. it compiles and can be uploaded to an Arduino. Posting only some parts of your code may not be helpful.

Full Code Link in serial monitor type 1 to write data to the eeprom then 2 to read the eeprom to variables and then type 5 to process it and see the failure. Thank you!

The first issue I can see in your contrived code is fromLocation += tempArray[i-1].toInt(); where i=0: behavior there is undefined (may crash immediately or override memory used later...)

Thanks for advise, I will try and alter that part.  I'm a beginner and i appreciate all input :)

Your 2nd for loop should look something like this:
int fromLocation = 0;
int toLocation=0;

for (int i = 0; i <10 ; i++)
{                 /////// LINE 80

    toLocation += tempArray[i].toInt();

    tempArray2[i]=eepromReadTwo.substring(fromLocation,toLocation);
    Serial.print("From Number = :");
    Serial.println(fromLocation);
    Serial.print("To number : ");
    Serial.println(toLocation);
    Serial.print("I just translated :");
    Serial.println(tempArray2[i]);
    fromLocation += tempArray[i].toInt();
  }
}

On the first pass through the loop, fromLocation is 0. toLocation starts at 0 and gets the value in tempArray2[0] added to it.
After extracting a string, you add the current array value to fromLocation to advance the pointer to the beginning of the next string.
Note that String objects are very inefficient way to save 2 digit numbers. It would be better use an array of ints, and write code that extracts 2 characters at a time into int values.
With only 20 String objects it's not a huge deal, but bear in mind that String objects take a lot of memory overhead on a memory-starved platform like an Arduino. Better to learn how to use C strings.

Great thank you so much.    Strangely using the code about gave me all entries EXCEPT number 7.    However once I changed the Search locations from char to int everything started working :D
Final Function Code - PasteBin


text:
Is possible to process analogue inputs with variation frequencies in MHz?
Is it possible for Arduino boards to accurately process analog inputs that vary at MHz frequencies?
If possible, which Arduino board would be most appropriate for such application?
What adjustments would be required for it to handle such rapid analog input variations?

What frequencies?

Depends on what the signal actually is and what you want to measure.  The Arduino isn't fast, but you could, for example, build a board that gives you a measure of what the frequency is, if it changes slowly enough.  Or if it's a relatively constant frequency and you care only about the amplitude, you could use a variant of the standard super heterodyne circuit.

Your typical ATMega-base Arduino cannot sample anywhere near that kind of speed.
It takes 13 clock cycles to sample an analog value on an ATMega chip, and the maximum clock frequency for the ADC is 1MHz. That gives you an absolute maximum sampling speed of 76923 samples per second. That means the highest frequency you can sample is 38461Hz.
There are better chips on the market with higher sampling speeds, but they aren't Arduino. Some can sample at the tens of millions of samples per second allowing you to sample frequencies in the low MHz. Other specialised ADC chips are available that can sample in the Gsps range which are what are used in oscilloscopes and high speed communication (fibre optic) systems etc. Working with these kind of chips needs quite a lot of skill though as the analog signal paths requires special design and consideration.
Also when sampling at those kind of frequencies you need a lot of high-speed memory, which no Arduino can ever even consider the possibility of having.


text:
Arduino Wire.h send double to lcd
I'd like the double number 200.00 shown as 200.00 on my LCD screen.
For instance, when I pass just a number (int) like 40 to the LCD, it uses it as an ASCII code to show a character on the display.
Now I want to send a double to it and it should be displayed as a double.
#include <Wire.h>

void setup() {
   Wire.begin(0x63);
}

double f;
void loop() {

  f = 200.00;

  Wire.beginTransmission(0x63);
  Wire.write(byte(0x00));
  Wire.write(4); //HIDE CURSOR
  Wire.write(12); //CLEAR SCREEN
  Wire.write(13); //CURSOR 2nd LINE
  Wire.write("Frequenz: ");
  Wire.write(f); //<- How to do this?
  Wire.write("Hz");
  Wire.endTransmission();
}

The Arduino Wire class does only support write() of byte, string and vector of bytes. To write a double it must first be converted to a string. This can be done with the standard C library function dtostrf().
double f;

void loop() {
  char buf[10];

  f = 200.00;

  Wire.beginTransmission(0x63);
  Wire.write(byte(0x00));
  Wire.write(4); //HIDE CURSOR
  Wire.write(12); //CLEAR SCREEN
  Wire.write(13); //CURSOR 2nd LINE
  Wire.write("Frequenz: ");
  Wire.write(dtostrf(f, 0, 2, buf));
  Wire.write("Hz");
  Wire.endTransmission();
}

The class inherits from Print (via Stream) so that the overloaded member function print() for double can be used. In that case:
double f;

void loop() {
  f = 200.00;

  Wire.beginTransmission(0x63);
  Wire.write(byte(0x00));
  Wire.write(4); //HIDE CURSOR
  Wire.write(12); //CLEAR SCREEN
  Wire.write(13); //CURSOR 2nd LINE
  Wire.write("Frequenz: ");
  Wire.print(f);
  Wire.write("Hz");
  Wire.endTransmission();
}

Please note that the maximum number of bytes to write (between beginTransmission and endTransmission) is limited to 32 in the standard configuration of the Arduino core.
Cheers!

Use Wire.print(), instead of Wire.write() which is intended only to output single bytes or byte arrays.