text:
Works for 2-3 hrs, then LED blinks rapidly - Sleep Mode and Watchdog timer wakeup
I hope somebody can shed some light on this problem. I've researched the internet and forums and noticed that others have experienced similar problems.
This sketch runs fine for a couple of hours...it activates a relay approximately every hour, has a 10 second loop for an LED flash and then enters sleep mode. The watchdog timer is set to 8 seconds and wakes it up from sleep. I don't know why it works for a couple of hours and then gets caught into some sort of loop with the LED flashing rapidly. The requirements for disabling and resetting the watchdog might be the problem but I just don't know where to go next. I have seen a few discussions on memory leakage but not sure what that means or how to check for it. I also wonder if need to add any short delays after resets, etc. Additionally, when I press the reset button it has no effect on restarting the sketch. The sketch is running on a breadboard atMega328p-pu. Any help would be greatly appreciated.
ps. in the preview I noticed the # statements are not shown. They are the following libraries: avr/sleep.h, avr/power.h, avr/wdt.h
// In this sketch, the LED's flash every 10 seconds, then at each approximately 1 hour period, the relay is activated
// for 12 seconds.  It uses the WDT at its maximum 8 second delay to wakeup the circuit from low power sleep.

// Source: citizen-sensing.org/2013/07/arduino-watchdog/

// Check this out for good explanation on the Watchdog timer and code.
// http://www.leonardomiliani.com/en/2013/impariamo-ad-usare-il-watchdog-2/

// SEE NOTE at the end on known WDT reset issue

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

int j = 1; // Elapsed time multiplication factor
int j2 = 0; // previous j value
float tCumm = 0.0; // Cummulative time
float hSet = 1.0; // Set relay activation once per hour
float hSet2 = 0.0; // Previous hSet value

// Create sleepNow function

void sleepNow() {

  wdt_reset();
  wdt_disable();

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Selecting the lowest power setting

// Set watchdog parameters
  MCUSR &= ~(1<<WDRF); // reset status flag
  WDTCSR |= (1<<WDCE) | (1<<WDE); // required to enable configuration changes
  WDTCSR = (1<<WDP0) | (1<<WDP3); // set the pre-scalar for 10, ie 8 seconds delay
  WDTCSR |= (1<<WDIE); // enable interrupt mode

// Disable the ADC
  ADCSRA &= ~(1<<ADEN); // Set bit 7 in ADC register to 1 to disable the ADC

// Ready for sleep
  sleep_enable(); // Enable sleep function
  sleep_mode(); // Go to sleep.  Will wake up upon interrupt via Watchdog timer in this sketch.

// disable sleep after waking up
  sleep_disable(); // Disable sleep for now after Watchdog timer interrupt activation
}

void setup() {

  pinMode(4, OUTPUT); // set pin 4 as output for LED
  pinMode(7, OUTPUT); // set pin 7 as output for relay
}

void loop() {

  // 10 second LED flashing + sleep loop

  for (int i = 0; i < 2; i++) {
  digitalWrite(4, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(200);               // wait for 0.2 sec
  digitalWrite(4, LOW);    // turn the LED off by making the voltage LOW
  delay(200);              // wait for 0.2 second
}

  // Add delay for total approx 2 sec
  delay(1200);

  // Start sleep / Low power / Watchdog interrupt
  sleepNow();

  // Cummulative time in increments of 10 seconds
  tCumm = ((2.0 + 8.0)*j)/3600.;

  // Time multiplication factor. Used to increment tCumm. Never resets to zero.
  j2 = j;
  j = j2 + 1;

  // Check to see if tCumm exceeds the user defined period (hSet) before activating relay
  if (tCumm > hSet) {

  // Activate relay for 12 seconds
    digitalWrite(7, HIGH);
    delay(12000);
    digitalWrite(7,LOW);

  // Reset hSet for next relay activation time
    hSet2 = hSet;
    hSet = hSet2 + 1.0;

    }
}

ISR (WDT_vect) {

}

NOTE from an online discussion: The problem is that a RESET does not turn off the watchdog timer once it has been turned on, and neither does the bootloader.  So you set things up to have the watchdog cause a reset in 15ms, and the reset occurs. Now the bootloader starts up, and starts its LED-flashing, and OOPS another 15ms has gone by with no one feeding the watchdog, and it resets again.  This repeats until a power cycle turns off the watchdog.
(This behavior is explicitly described in the ATmega datasheet...)

You should put the wdt_disable(); at the end of sleepNow. It doesn't make much sense to disable it right before setting it. I always put a distinct blinking pattern in the setup function, so I can detect when the Arduino is reset.

You have a watch dog timer for 8 seconds and when you activate the relays you do a delay of 12.
This means that your watchdog will trigger when you activate the relays.

Do you think I need to add a wdt_reset() or wdt_disable(), or both, right after the sleepNow() command in the loop function?

Given that the watchdog appears to be operating in interrupt mode (with an ISR that does nothing) rather than reset mode, I'm not sure that this matters.  The routine which goes to sleep seems like it is attempting to establish a suitable watchdog state before doing that, so it's not clear how an additional wdt timeout during the delay would matter.  But watchdog usage definitely needs careful thought.

But watchdog usage definitely needs careful thought. indeed. And using it with delays is making it very hard to predict what is ongoing.

Looking at this declaration
int j = 1; // Elapsed time multiplication factor
int j2 = 0; // previous j value

and then this code
// Cummulative time in increments of 10 seconds
  tCumm = ((2.0 + 8.0)*j)/3600.;

 // Time multiplication factor. Used to increment tCumm. Never resets to zero.
  j2 = j;
  j = j2 + 1;

along with the associated comments seems to indicate that this variable "j" which is a (signed) int only increments without ever resetting, and is critical to the process of calculating the next time at which your code will act.
Your includes indicate that you are building for an AVR-based Arduino, and under the compiler used, an int on this platform is only 16 bits, meaning it has a range of -32768 to 32767.  Most modern platforms including this one use 2's complement representation, and most non-DSP platforms including this one do not use saturating arithmetic.  Therefore, incrementing a positive number beyond the positive limit will actually product a negative value.  Once your target time exceeds the maximum possible result of a calculation that has a positive int as an input, it becomes a target you will never be able to achieve.
Given the the amount of time your loop takes to execute, such integer overflow may not be not the issue you are hitting first, and does not seem perfectly correlated to your rapid-cycling failure mode.  But if your loop takes around 10 seconds, it seems like this would be an issue in a little less than four days.

Thx..j increments 1 every 10 seconds...so.if I use a 5 hour period for example, j gets up to only 1800...56060/10...yes it will definitely run into the limit in 3-4 days looks like and will have to be fixed for sure...but now it only runs 2-3 hours...I think there is something about my watchdog setup that I'm missing with the resets, disabling, etc but i'm just guessing...


text:
Arduino I/O Shield relay won't switch
I have an Arduino Uno and the I/O Shield wired up and I'm trying to switch (i.e. engage) a relay on the I/O Shield, but nothing seems to be working.
I've identified the input pins correctly and am able to send digital signals to it and it responds correctly. I also see the LED next to the relay light up when I do a digital write on the Arduino to a specific relay pin.
I'm starting to think that I might need to use an alternative power source or that I am not using the Arduino API correctly to switch the relay. At the moment I do a digitalWrite(13, HIGH), delay, and then do a digitalWrite(13, LOW) - pretty simple.
The shield is just powered by the Arduino at the moment, and I haven't been able to find where I might be able to plug in power, so I'm assuming the Arduino supplies it with all of the power it needs.
#include <Arduino.h>

int relayPin = 13;

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

void loop() {
            digitalWrite(relayPin, HIGH);
        delay(5000);
        digitalWrite(relayPin, LOW);
        delay(5000);
}

So you did everything correctly? Then it works correctly, case closed. Maybe show someone what you did?

pinMode(13, OUTPUT); ?

yeah I setup the pin as an output as well

@wesleyLee - He is able to light up the LED which is next to the relay so I think he has declared the pin as output correctly.

or that I am not using the arduino API correctly to trip the relay Arduinos know nothing about relays, they only know about pins that can be outputs and then can go high or low (or float). If the connected LED turns on and off then that part is OK. Check the supply voltage for the relay, it needs more power than an LED.

Based on your newly-added photo, you are using the Velleman VMA05 I/O Shield (or the KA-05 kit version).
This shield requires a 12V 500mA (minimum current capability) power supply input to the Arduino Uno, as that board uses relays with a 12V coil.  Your symptoms (LED lights but relay does not switch) suggest that you are using a lower voltage, or lower current, power supply to your Arduino. If so, then the fix is: Use the required power supply to the Arduino.

I'm assuming the arduino supplies it with all of the power it needs.

Yes - but only if you meet the minimum requirements of the power supply which you connect to the Arduino. As documented in the Vellemen VMA05 datasheet and manual, this must be a 12V supply (not lower, not higher) capable of a minimum of 500mA.
(You would likely be able to use a 12V supply capable of a slightly lower current output, if you only wanted to have one or two relays active at the same time. However if more relays were active simultaneously, the risk would increase of incorrect or erroneous behaviour, due to the additional current necessary for each relay coil, in addition to powering the Arduino, eventually exceeding the capabilities of the power supply.)

I'm assuming I plug the power in to the power in pin of the arduino, from what I understand we can only supply 5v through the micro usb slot.

@ThePaxBisonica - "I'm assuming I plug the power in to the power in pin of the arduino" - Yes, using the round "barrel connector" (also called "coaxial power connector" or "DC power jack").

@ThePaxBisonica - In case you are unsure about Arduino power supplies (perhaps you have always used the USB connection for power?) here is a link to the Arduino website explaining more about choosing & connecting an Arduino external DC power supply. Although for powering just an Arduino Uno then a 9v supply would suffice, when using your relay shield (and several other models of relay shield), a 12V supply with sufficient current capability (in your case ideally 500mA minimum) is required.

Unless you share a schematic, it will be very difficult to provide a good answer.
Here are the things that you might be doing wrong:
1) Using a power supply which is not able to provide enough current to the relay.
2) Using a power supply of wrong voltage as required by relay coil. The relay might be needing 12 V and you might be trying to power it up with a 5 V power supply.
3) You might be trying to drive the relay directly with your GPIO pin (without using any external transistor switch).
4) Trying to raise a dead relay. There is a possibility that the relay is damaged. Check it by powering it up directly using a battery or another adequate power supply that you got.

when you say the relay might need 12v I'm a little confused because I've looked for a power input and there doesn't seem to be any, do you mean I need to power the arduino with a 12v power supply?

Yes, 12V / 500mA supply is the minimum required for this board to work correctly. 9V will make the LED turn on but not pull the relay contacts properly.  Also, I have had two of these boards where the back EMF diodes across the relay coils have gone short circuit causing excessive heating in the associated switching transistors.  The solution is to replace these diodes with a more suitable 1N4001 type since the 1N4148 that is supplied with the kit is really a small signal diode and really not suitable for this purpose.

source: Stack Exchange

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

sort: votes


text:
ATSAMD21 sleep + watchdog?
Has anyone got sleep/standby + watchdog to work together on their Arduino Zero or Sparkfun SAMD mini?
I am able to get the WDT to reset the device, and am able to put it to sleep - but can't get the WDT to bring it out of sleep.  Every time I try, it pops right back out of sleep mode again as if SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk was never even called

use this:
attachInterrupt(wakeUpPin, wakeupFunction, HIGH);
    USBDevice.detach();
    SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
    __DSB();
    __WFI();

void wakeupFunction(){
  NVIC_SystemReset();
}

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


text:
sending room temp data from multiple esp8266's to Mega 2560 to control CH gas boiler
My existing Arduino Mega set up has been in use for about 4 years controlling my gas CH system & heat pump HW system using an Arduino mega & 13 'wired' DS18B20 sensors; 2 of these sensors monitor the main room (lounge) temperature & 1 sensor monitors the outside temp. These 3 sensors control the CH by gas boiler using an algorithm that constantly adjusts the room temp setting as the outside temp changes. The others monitor HW tank temps, heat pump inlet & outlet temps.
I want to change this 'single zone' CH control to a 'multi zone' control using many more temp sensors (DS18B20 or ESP8266?) but laying in hidden wiring would be a real pain.
I've been looking at using ESP8266-07 as a wireless temp sensor for each 'zone', sending its data to the Mega for processing by the above refered to algorithm, so that the Mega can control the CH system better but I can't find any reference to receiving this wireless data at the Mega for processing within the IDE sketch.
I've tried testing the nRF24L01 & nRF24L01+ but my house has many 'black' reception areas & transmission is unreliable.
My 2.4GHz wireless LAN has 3 extenders around the house so this would be my prefered wireless solution.
Could a wireless 'master' be used at the Mega to process data coming in from the 'slave' sensors or am I misunderstanding this?
My programming skill is limited to 'basic IDE' & I find 'wireless' a bit of a black art (I'm a retired mechanical engineer!)

I am also in the middle of converting the control of my heating, multi-zone, but using Ciseco / Wirelessthings units as temperature sensors both inside and out. See https://www.wirelessthings.net
Simple serial interface is all you need from the Arduino to run these on a network. The coin cell battery lasts for over 1 year running 1 sample / 10min - the sample rate is configured but obviously the more samples you send the more the battery drains. Range seems to be OK and gets through 3 floors in the house and from the outside. I do use external antenna on the Arduino wireless unit to ensure I get all of the sensor readings.
However sounds like your house is BIG if running 3x WIFI extensions where as a single WIFI base station does me fine.

I've had a look at wirelessthings.net web site.  I want to monitor (zone) each room in the house that is fitted with wireless EQ3 thermostatic radiator valves (8 so far) so using the wirelessthings temperature sensors would amount to around £100!  Also, I need to sample the sensors every 30s or so as it controls the gas boiler hence my intent to not use battery powered devices but mains powered.  I'm still looking for a way to use the ESP8266 with the Arduino Mega.  My house is not that big but being 'split level' has produced a number of poor reception areas hence he use of wireless extenders


text:
Arduino Leonardo based h keyboard
I just want to configure my laptops keyboard buttons a,s,d,f,g,h and j. I wrote this code and it works for only a but I couldn't configure other buttons.
Code is:

#include "Keyboard.h"

const int buttonPin = 3;          // input pin for pushbutton
int previousButtonState = HIGH;   // for checking the state of a pushButton
int counter = 0;                  // button push counter

void setup() {
  // make the pushButton pin an input:
  pinMode(buttonPin, INPUT);
  // initialize control over the keyboard:
  Keyboard.begin();
  Keyboard.press('a');
}

void loop() {
  // read the pushbutton:
  int buttonState = digitalRead(buttonPin);
  // if the button state has changed,
  if ((buttonState != previousButtonState)
      // and it's currently pressed:
      && (buttonState == HIGH)) {
    // increment the button counter
    counter++;
    // type out a message
    Keyboard.print("a");
  }
  // save the current button state for comparison next time:
  previousButtonState = buttonState;
}

How can I configure other buttons s,d,f,g,h and j to pin buttons 4,5,6,7,8 and 9.
Thanks for help:)

You could basically duplicate your code and variables to handle each button, or you could do things with an array or even an object-oriented approach.  6 buttons is about at the point where duplication is unsophisticated, but still practical if it best fits your understanding.  Also you might want to get rid of what looks like a dummy/test 'a' in the setup.

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


text:
How to bootload a atmega328-pu using arduino uno?
I have some Atmega328-Pu micro-controllers without boot-loader program. Now I need to burn boot-loader to them all. I have two arduino uno boards having Atmega328 P-Pu micro-controllers on board. I used this circuit  from this page Installing an arduino boot-loader
It does not work. The boot-loader is not uploaded. Can you please help me out? If you need any more informations please ask. I have been struggling with this kind of boot-loading techniques for more than a week. I am using arduino IDE 1.0.1 and the board is Arduino uno R3

Have you uploaded the ArduinoISP sketch to the left-hand Arduino in your diagram and selected ArduinoISP under Tools->Programmer before using Tools->Burn Bootloader to burn the bootloader? BTW, I would strongly recommend upgrading to Arduino 1.6.8 - that is where my instructions are written from.

This thing has never let me down: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

@Whiskeyjack  ... and the Arduino ISP tutorial have never let me down (even with different Arduino types than described in the original tutorial; brief report to that effect).

is the target ATmega clock pin oscillating? Is there anything else connected to the SPI pins?

After uploading ArduinoISP and before trying to actually burn the bootloader, you have to put a capacitor (10 µF recommended, 1 µF always worked for me) between RESET and 5V of the Arduino on the left (the one running ArduinoISP).

Hi friends thanks for your support. It worked well as it is. No external capacitor I used.
I made the connection as shown in the above picture taken from LINK1.
I modified the file "boards.txt" and "avrdude.conf" as given in step 4 of LINK2
I first uploaded the ArduinoISP sketch to the board on the left.
And then I opened an "EMPTY ARDUINO SKETCH".
From that empty sketch I made the following changes
     Tools->Board = "Arduino328"
            Port  = COM4 in my pc
            Programmer = Arduino as ISP
Last step "Burn Bootloader"
Ta Da....
It worked. When I posted this question I burnt the boot-loader having the arduino ISP sketch opened. Only thing I changed now is I opened an empty sketch and hit burn from that sketch. Anyway.. thank you all. I dont think I wasted your time. If so, I apologise.


text:
Is this a proper implementation of FreeRTOS for Arduino?
I'm using the RGBLCDShield library and a few analog input signals and since it seems the interrupts are being used by the SPI interface of the LCD Shield, I decided to try it with FreeRTOS instead.  I don't currently have my arduino with me (left if at parents') but I wanted to get some feedback on this code to see if it would run properly; I might not be getting my UNO back for a few days but I wanted to at least have a usable code ready to be tested when I do get it.
The Analog inputs are just 2 low level signals and the digital outputs just control some IC switches.  One PWM is fed through a lowpass filter and into an amplifier input.
Here is my code in it's entirety:
#include <Arduino_FreeRTOS.h>
#include <Adafruit_RGBLCDShield.h>
#include <Wire.h>
#include <math.h>

// define tasks
void TaskAnalogRead( void *pvParameters );  // Check voltage input
void TaskLCDShield( void *pvParameters );   // Control Display
void TaskUserInput( void *pvParameters );   // User Interface - System Process

Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
unsigned int vSet = 0;  // Desired Voltage (potentiometer set)
unsigned int vOut = 0;  // Voltage on capacitor

// the setup function runs once when you press reset or power the board
void setup() {

  // Set up Tasks to run independently
  xTaskCreate(
    TaskAnalogRead
    ,  (const portCHAR *) "AnalogRead"   // A name just for humans
    ,  128  // This stack size can be checked & adjusted by reading the Stack Highwater
    ,  NULL
    ,  2  // Priority, with 1 being the highest, and 4 being the lowest.
    ,  NULL );

  xTaskCreate(
    TaskLCDShield
    ,  (const portCHAR *) "LCDShield"
    ,  128  // Stack size
    ,  NULL
    ,  3  // Priority
    ,  NULL );

  xTaskCreate(
    TaskUserInput
    , (const portCHAR *) "UserInput"
    , 128
    , NULL
    , 1
    , NULL );

  // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
  lcd.begin(16, 2);
}

void loop()
{
  // Empty. Things are done in Tasks.
}

/*--------------------------------------------------*/
/*---------------------- Tasks ---------------------*/
/*--------------------------------------------------*/

void TaskLCDShield(void *pvParameters)  // This is a task.
{
  (void) pvParameters;

  // Start Display
  lcd.setBacklight(0x7);
  lcd.setCursor(0,0);
  lcd.println(" PORTABLE SPARK ");
  delay(5000);
  lcd.clear();

  for (;;) // Continuously Update display
  {

    int volts = vSet * 100.0;
    int chg   = (vOut * 0.488)/volts;
    int vpos, cpos;
    lcd.setCursor(0,0);
    lcd.print("Voltage:       ");
    lcd.setCursor(15, 0);
    lcd.print("V");
    lcd.setCursor(0,1);
    lcd.print("Charge :       ");
    lcd.setCursor(15,1);
    lcd.print("%");

    lcd.setCursor(9,0);
    if(volts < 100)
      {
        lcd.print("    ");
        vpos = 13;
      }
    else if(volts < 1000)
      {
        lcd.print("    ");
        vpos = 11;
      }
     else if(volts < 10000)
     {
      lcd.print("     ");
      vpos = 10;
     }
     else vpos = 9;
    lcd.setCursor(vpos,0);
    lcd.print(volts, DEC);

    lcd.setCursor(9,1);
    if(chg < 10)
      {
        lcd.print("    ");
        cpos = 13;
      }
    else if(chg < 100)
      {
        lcd.print("   ");
        cpos = 12;
      }
    else cpos = 11;
    lcd.setCursor(cpos,1);
    lcd.print(chg, DEC);
    //digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
    //digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    //vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
  }
}

void TaskAnalogRead(void *pvParameters)  // Read Analog Voltages (VSet, Emonitor)
{
  (void) pvParameters;

  for (;;)
  {
    int eMon = analogRead(A0); // read input pins
    vTaskDelay(1);
    int vA = analogRead(A1);

    vSet = (vA/1024) * 15000;  // calculate actual values
    vOut = (5.0/1024.0) * 10000 * eMon;

    vTaskDelay(10);  // one tick delay (300ms) in between reads
  }
}  // End Analog Read

void TaskUserInput(void *pvParameters) // User Interface
{
  (void) pvParameters;

  // initialize digital pin 13 as an output.
  pinMode(8, OUTPUT);  // Fire signal
  pinMode(7, OUTPUT);  // Charge/Discharge signal
  pinMode(5, OUTPUT);  // Eprgm PWM output
  pinMode(4, OUTPUT);  // Cam/DAQ trigger

  bool charge = false;   // charge flag

  for (;;)
  {
    uint8_t button = lcd.readButtons();
    switch(charge)
    {
      case true:
        analogWrite(5, (vSet * 0.0204)/5);
        vTaskDelay(1);
        digitalWrite(7, HIGH);
        vTaskDelay(1);
        break;

       default:
        analogWrite(5, 0);
        vTaskDelay(1);
        digitalWrite(7, LOW);
        vTaskDelay(1);
        break;
    } // End Switch(charge)

    if(button & BUTTON_UP)  // Charge/Discharge button
    {
      charge = !charge;
    } // end if

    else if(button & BUTTON_DOWN) // Fire!
    {
      digitalWrite(8, HIGH);
      vTaskDelay(1);
      digitalWrite(4, HIGH);
      vTaskDelay(1);
      digitalWrite(7, LOW);
      charge = false;
      vTaskDelay(1);
      digitalWrite(4, LOW);
      vTaskDelay(1);
      digitalWrite(8, LOW);
    } // End else if

  }  // End for

} // End User Interface

My specific concern is with the 2wire interface of the LCD shield and whether it would be able to communicate with the Arduino - especially when it needs to read the button inputs.
Also, how do I determine the stack size for each task?  Is 128 for each enough to handle what I have?

“the interrupts are being used by the SPI interface of the LCD Shield”. I don't quite understand this sentence. Each interrupt source has its own interrupt (or interrupts). The SPI interface has one interrupt. It does not prevent you from using other interrupts if you want.

This is not a direct answer to the question. Instead, I suggest that you
do not need an RTOS to do what you want. A lightweight alternative is to
use millis() to decide when it is time to perform such or such task:
void loop()
{
    uint32_t now = millis();

    // Update the LCD every second.
    static uint32_t last_lcd_update;
    if (now - last_lcd_update >= 1000) {
        last_lcd_update = now;
        update_lcd();
    }

    // Read the analog inputs every 300 ms.
    static uint32_t last_analog_read;
    if (now - last_analog_read >= 300) {
        last_analog_read = now;
        do_analog_read();
    }

    // User input is handled continuously.
    handle_user_input();
}

This will use significantly less resources (flash, RAM and CPU time)
than an RTOS. Another advantage is that you do not need to determine a
stack size for each task, which is definitely not a simple thing to
do.


text:
Creating a library
I created a simple library for formatting text output on the serial monitor. It has thee functions, one that creates carriage returns, one that sets the number of spaces between characters and the last one prints dashes. I followed the tutorial on the Arduino.cc site. The problem I have is that I can’t pass the value to each of the functions when I call them in the code. If you look at the screenshot from the sketch when I create an instance of nFormat it requires me to put a value in and it passes that value to each of the functions (lines, spaces, dashes). I want to be able to specify the value directly when I call the function. See the second red line on the output screenshot. I know this post is a bit long I would appreciate it if someone could point me in the right direction.
nFormat.h
#ifndef nFormat_h
#define nFormat_h

#include "Arduino.h"

class nFormat
{
  public:
    nFormat(int counter);

    void lines();
    void spaces();
    void dashes();

   private:
    int _counter;
};

#endif

nFormat.cpp
#include "Arduino.h"
#include "nFormat.h"

nFormat::nFormat(int counter)
{
    _counter=counter;
}

void nFormat::lines()
{
for (int x = 0; x < _counter; x++)
    {
        Serial.println(" ");
    }

}

void nFormat::spaces()
{
    for (int x = 0; x < _counter; x++)
    {
        Serial.print(" ");
    }
}

void nFormat::dashes()
{
    for (int x = 0; x < _counter; x++)
    {
        Serial.print("-");
    }

Why are you using a class if you want to be able to pass all the parameters directly to the functions?

I want to avoid having to make an instance of nFormating everytime I want to change the value of the number of spaces or dashes. For example if I wanted to have 10 dashes instead I would have to create nFormat nFormatTwo(10); I get an error when I compile the program when placing the value inside the function call.

If you want to specify the number of spaces/dashes/... every time you
call any of these methods, you just have to make that number a parameter
of the method:
void lines(int count)
{
    for (int x = 0; x < count; x++)
        Serial.println();
}

Then, your class does not need its private _counter. Then, since there
is no data in the class, you do not need to instantiate it: just make
all the methods static and call the methods as
nFormat::method_name(). And since you are not making instances, you do
not need a constructor either. And since the methods are really trivial,
there is no point in implementing them in a .cpp file: you can just
inline them in the class declaration. Combining all this gives this small
demo program:
class nFormat
{
  public:
    static void lines(int count)
    {
        for (int x = 0; x < count; x++)
            Serial.println();
    }

    static void spaces(int count)
    {
        for (int x = 0; x < count; x++)
            Serial.print(" ");
    }

    static void dashes(int count)
    {
        for (int x = 0; x < count; x++)
            Serial.print("-");
    }
};

void setup()
{
    Serial.begin(9600);
    nFormat::dashes(5);
    nFormat::lines(5);
    nFormat::spaces(5);
    nFormat::dashes(5);
}

void loop() {}

It could be noted than this class serves only to avoid putting all the
functions in the global namespace. It is essentially a namespace. You
could as well replace class by namespace (and remove the public
keyword) to make that more explicit.


text:
Is it possible to connect 2 ultra sonic sensors to 1 arduino?
I am currently using the Arduino Pro Micro board and I want to connect 2 ultrasonic sensors to 1 board, whilst knowing which sensor is being triggered. The sensor I am using is a HC-SR04 Ultrasonic sensor.
Please help me thank you :)

Have a look at the newping library.

Yes, you can, as long as you serialize the send/receive pulse cycles, to avoid interferences.
basically, you attach the Trig/Echo lines to a different pair of pins, then do the reading on one sensor, then do the reading on the other.

Sorry i'm really really new and noob at this, so i really dont know what all these mean

What you need to do, for each sensor, is the following:

choose a GPIO that will drive the trigger line (make sure it is not a pin you are already planning to use, ex: TX/RX )
choose a pin that will receive the information from the Echo line, ideally using an interrupt driven implementation, instead of polling. The 328P supports exactly 2 independent interrupt lines: INT0 and INT1, so you could use one of them for each sensor.
have a time base and use it to time-stamp the Trig and Echo lines

Example for one sensor (for 2 just do the same and keep in mind that there might be interferences, like the OP said):

toggle the Trig line for the required duration (strobe)and save it
read the time
wait for the interrupt to occur (you can do other things in the meanwhile)
when the interrupt occurs, read again the time
subtract the timestamp taken after toggling Trig from the timestamp taken after the Echo interrupt
convert the delta time from the previous point into a linear measure, using the constant provided by the datasheet of the sensor

“The 328P supports exactly 2 independent interrupt lines: INT0 and INT1” is rather misleading.  Pin change interrupts suitable for sensing Echo lines are supported on about two dozen pins (ie on all pins except for Vcc, Gnd, ARef, AVcc, ADC6, ADC7)

@jwpat7 I think my comment is correct: it does indeed support 2 independent interrupt lines. What you mention is ORed within a port. Yes, one might choose only one pin per port and sort of simulate more independent interrupt sources, but it is bordeline a design trick and requires additional programming for the port masking. Given the level of knowledge implied by the question, it seemed more effective to give the answer that is simpler to implement and maps also to other architectures that do not have the concept of port.


text:
Weird characters in Serial Monitor and not functioning ESP8266 ESP-12e
I did a bit of playing with my new ESP-12e, but suddenly it kind of fails on me. It gives me some weird looks it didn't give me (as much) before.

This is what the Serial Monitor prints when I try to run a very simple sketch. When I restart the module, it just adds some more of these chars.
The following is the code for that:
const int statusLED = 16;

void setup() {
  pinMode(statusLED, OUTPUT);
  digitalWrite(statusLED, HIGH);

  Serial.begin(115200);
  Serial.write("The ESP-12e has started.");
  delay(500);
}

void loop() {
  delay(1000);
  digitalWrite(statusLED, LOW);
  delay(1000);
  digitalWrite(statusLED, HIGH);
}

This doesn't even involve the WIFI...
These are my board settings:
Board: Generic ESP8266 Module
Flash mode: QIO
Flash frequency: 40MHz
CPU frequency: 80MHz
Flash size: 4M (3M SPIFFS)
Upload speed: 115200
And finally, if it might help, how I connected the module:

All connections are solid, so that shouldn't be a problem. The connection board has GPIO15 printed on it twice, but the one I connected to the LED is actually GPIO16. I noticed that the onboard LED of the ESP-12e doesn't light on anymore.
I use the CP2102 USB to UART module.
Thanks!
Rogier

It seems like maybe the firmware itself is crashing. Have you tried reflashing the device a couple of times?

The output doesn't appear to be able to have come from your code. Are the states of GPIO[0,2,15] appropriate for booting, at boot time? For running from flash, at run time?

wow, a negative for that?  Problem isn't even solved yet. rough crowd.

Yes, the GPIO pins should be connected the right way. Also, I am able to upload to the flash memory.

Yeah, weird. I don't know who would do that. I will try to flash new firmware and get back to you! Thanks for your help!

you're welcome -- my ESP8266's have been super finicky, easy to get a bad flash on em

I noticed that the onboard LED of the ESP-12e doesn't light on anymore - looking at the pictures, I hope the power coming in on the barely visible orange wire is 3.3v

Yes, that is 3.3v input from a regulator. It also should have enough power (2A).

Hi @Malachi. It's been a while, and a struggle. I just can't get it to work! The new firmware was flashed no problem (kind of), but it just won't run my sketches, nor do the default AT commands work. I think it might just be broken somehow, so I have ordered a couple of new ESP-12Fs. Hope they all keep working.

Sorry to hear this.  I'm a little surprised to hear you mention AT commands, after flashing custom firmware I would not expect any AT commands to work.  One note: not necessarily gonna solve your problem, but get a genuine FTDI based setup - those CPxxx suckers have always added a layer of problems for me.

I have downloaded the firmware from the Espressif website, so it wasn't custom. What custom firmwares are there to try?j

For example your original posted sketch would constitute a custom firmware.  If you're using the ESP8266_AT firmware from the site, then yes I would expect AT commands to work (although I have never actually flashed that firmware before =)

Ah. OK! No the custom firmwares don't work either. Although they do upload without an error.

You should be seeing a blue LED flash when you power it on at least.  If not seeing that then I'd say power delivery or a broken ESP8266.  I use this to program mine: http://www.ebay.com/itm/252225272540

The blue LED flashes when I turn it on. I'll see if the new modules work.

OK that's good news - there's hope!  Is it possible for you to upload a youtube of the flashing process?  I get a lot of clues about how successful my flash is from how the lights blink. (hopefully your CP20xx has some lights... =)

A schematic is way more informative than those two photos. I really doesn't see how things are connected and can't check your circuit. (Not that I actually can, but someone else maybe).

NccWarp9 is right, e.g.: void setup() { Serial.begin(115200); you have to select 115200 in your baud serial monitor option. it works also for me (nodemcu 1.0)

Check what baud rate is serial window displaying. It should be the same as defined in your code.

Thanks. But that's the same. I have tried other baud rates, but that doesn't change it.


text:
How to filter a blank line received over serial - ESP8266
How can I filter a garbage completely blank line over my serial data? It comes from the wifi module ESP8266
How I read data:
  while (Serial1.available()){
       String inData = Serial1.readStringUntil('\n');

       Serial.println("Got: " + inData);

  }

Here is my common output:
Got: AT+CIPSEND=6
Got:
Got: OK
Got: >
Got: Recv 6 bytes
Got:
Got: SEND OK
Got:
Got: +IPD,21:Volume From: 99 To 89AT+CIPCLOSE
Got: CLOSED
Got:
Got: OK

That question may be too broad, and lacking in relevant context, for a meaningful answer to be provided.  Eg, we don't know if just suppressing all white space would work for you.  What kind of data, in what format, needs to be passed through the filter?

It's just a blank line / newline that prints between responses to my commands. I only want to get rid of that line. The only way to do it is to filter cos I don't have control over the firmware. I'll add some output. Thanks for pointing that out.

It might be a \r \n, carriage return and new-line. So effectively, the cr+lf is printed out as two blank lines, one cr and one lf. You may try String inData = Serial1.readStringUntil('\r'); but other than that, why even bother?

You are right in your assumption! It's a combination of both. I'll give it a try! For me the right solution is to filter any newline and concentrate on regex. It's quite difficult but it's working

inData.trim();
if( inData.length() > 0 ){
   Serial.println("Got: " + inData + "\n");

::trim() removes all leading and trailing whitespace characters including newlines. A line of [zero or more whitespace] + [newline] will get trimmed to the null string. If the result isn't null, then append the stripped off newline and print it. Note that this will flatten any indentation or vertical spacing that was supplied in the incoming text.

Worked like charm! Thanks! Since I don't want to process any blank line/newline I just removed the "+ \n"  since "println()" does it  automatically

You're right - missed that. (oops!). Glad you got it working.

Don't worry It's alright. Thanks for your effort


text:
What is more power efficient: GPRS or SMS for a GSM sim Arduino application?
I have a GSM shield for my arduino and am wondering the most efficient way to receive and send data to the cloud.
The specific project I am looking to accomplish is starting my car from a web browser (or custom built ionic mobile app) that will send data to my GSM shielded arduino and the arduino then "press the button" of an already installed remote car starter (which is all probably in the car's trunk).
What is more power efficient, sending and receiving a SMS (text message) or sending and receiving data via GPRS?
What is best when considering strategies like sleep, or deep sleep cycles?

I'd use Bluetooth instead.

@Gerben: Thanks Gerben, but the range of Bluetooth is too small for the project's needs. The GSM shield will enable me to start my car from any where in the world, where as bluetooth would limit me to to a range of 10 to 100 meters depending on the Class (1,2, or 3).

My gut response is SMS, just because it's a simpler protocol.  Not a scientific answer...

Looking at it logically SMS is probably the most power efficient method.
The thinking is this:
With SMS:

The shield sits there connected to the mobile network doing nothing much
An SMS is sent by you which travels through the mobile network
The SMS is sent from the mobile network to your GSM shield which then wakes up and does things with it
The shield sits there connected to the mobile network doing nothing much

With GPRS:

The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service and sees a request is available
The shield downloads the request
The shield acts on the request
The shield goes back to querying the on-line service
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
The shield queries an on-line service to see if a request is available
... etc ad nausium ...

As you can see with SMS the onus is on the mobile network to send the data to the shield, whereas with GPRS the onus is on the shield to keep querying an on-line service to see if there is any requests to handle. There is no way of you sending data to the shield directly (indeed, most GPRS services include at least one layer of NAT gatewaying). So your shield has to be active all the time and constantly looking at something online - not only power hungry, but potentially financially expensive too.

There is no way of you sending data to the shield directly. I'm not sure if this is entirely correct. Though you have to occasionally connect to the server to let it know what your IP is, and to keep the port open. And that is where things get messy, as none of the phone networks provide any data on these things.

If you are behind NAT, and chances you are (I am right now, on 4G) there is absolutely no way to get in from the outside.

@Majenko: Thanks for you response Majenko. Are you saying that protocols like MQTT (over TCP which simply keep an open connection without polling) won't work with GPRS? Are you suggesting that, through a GPRS connection, you can't "Push" messages to the arduino, but can only "Pull" messages? I would be curious as how iOS and Android do "Push" notifications, as is definitely seems like a real "Push", not a "Pull".

For those kind of connections you need a proper network connection. Whether or not you can do it with a GPRS shield is questionable and will depend on what the shield is capable. In general I don't think it is something that they do provide. Regardless, maintaining open connection whether you are using it or not will still be expensive on power.

@Majenko: Thanks for further explaining. How are SMS's sent to a phone/GSM shield. Do they keep an open network connection with the Cell Tower? Is that why, in general, GSM shields train so much power?

Yes but generally they are mainly listening. SMS is much lower bandwidth than the likes of 3G and uses less power to maintain a connection. It is also more reliable with poor signal levels.

@Majenko: I really appreciate your dialog. Thanks for your insight!

You could theoretically use a SIP Server in the middle to keep the session alive over GPRS or higher. And there are techniques you can use to make it as power efficient as can be, depending on your application (which is a rather simple one I assume with little data throughput).
However, as @Majenko stated above, it may not be as power efficient as SMS.
That said, there may be other considerations, such as cost of sending/receiving SMS messages that may matter as you weigh the totality of requirements for your application.
I haven't worked personally on a Particle board (particle.io) but they do have a MCU/3G board that provides a certain amount of free (as in no $) bandwidth per month that might be a reasonable solution to consider for your application.
Please keep us posted. I'm considering something similar myself.

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


text:
problem using GSM shield and GPS shield in one Arduino UNO R3
i try to program use the GSM shield Arduino with Arduino UNO i did it successfully but after that i try to use GPS shield but when i add the #include  for the program i got the error
#include <GSM.h>
#include <TinyGPS.h>
#include <SoftwareSerial.h> // when i add that one i got the output eroor
// PIN Number for the SIM
#define PINNUMBER ""

i got this error out put
Arduino: 1.6.6 (Mac OS X), Board: "Arduino/Genuino Uno"

libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `__vector_3':
/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:227: multiple definition of `__vector_3'
libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:499: first defined here
libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::read()':
/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:392: multiple definition of `__vector_4'
libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:487: first defined here
libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::read()':
/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:392: multiple definition of `__vector_5'
libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:487: first defined here
collect2: error: ld returned 1 exit status
exit status 1
Error compiling.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

It appears the GSM library has its own conflicting copy of SoftwareSerial, and not necessarily a matching version unless you're lucky.
Not sure how well this would work but you can try removing the library reference to SoftwareSerial, and fiddle about to use the GSM library's SoftwareSerial.

Indeed, if both peripherals are serially connected, the "only one instance" restriction of the software serial library may be a problem.  Alternate libraries could be considered, but most likely an ATmega-based Arduino is not the best platform.   A GSM module with integrated GSM could be another choice.

True that; my solution almost definitely won't result in 2 separate serial streams, which are likely needed.  This page may be of interest (alternate libraries) http://www.ernstc.dk/arduino/tinycom.html

thanks , i used SerialGSM.h instead the GSM library i can receive message but when i send the message not send it :(


text:
Building Multidimensional Arrays from simple arrays
Hi I am trying to write a functiont that will build a 2x4 array based on 2 1x4 arrays.
the two relevant functions are below. The first function gets information from some sensors and outputs it (I think) as a 1x4 array.
The second function is the problem and I have attached the error messages.
{
double quatCalib_mat[2][4];
double quatCalib_ABC[4];
double quatCalib_GHI[4];

 double  get_quat(Adafruit_BNO055 ref, double quatArray[])
{
  imu::Quaternion quat2 = ref.getQuat();

  quatArray[0]= quat2.w();
  quatArray[1]= quat2.x();
  quatArray[2]= quat2.y();
  quatArray[3] =quat2.z();

}

void Calibrate()
{
quatCalib_ABC=get_quat(bnoABC, quatCalib_ABC);

quatCalib_GHI=get_quat(bnoGHI, quatCalib_GHI);

quatCalib_mat= {
  {quatCalib_ABC},
  {quatCalib_GHI}
  };
}

the error messages
Arduino: 1.6.9 (Windows 7), Board: "Arduino/Genuino Uno"

E:\UNI2016\thesis\gizmo programming\Thesis_V3_M\Thesis_V3_M.ino: In function 'void Calibrate()':

Thesis_V3_M:101: error: incompatible types in assignment of 'double' to 'double [4]'

 quatCalib_ABC=get_quat(bnoABC, quatCalib_ABC);

              ^

Thesis_V3_M:103: error: incompatible types in assignment of 'double' to 'double [4]'

 quatCalib_GHI=get_quat(bnoGHI, quatCalib_GHI);

              ^

Thesis_V3_M:105: error: assigning to an array from an initializer list

 quatCalib_mat= {

              ^

exit status 1
incompatible types in assignment of 'double' to 'double [4]'

Cheers
Alex

The compiler is telling you what is wrong: The return type is not the same as the variable (double vs double[4]) in the assignment. Also there is no return statement.

As Mikael Patel said, the compiler is already hinting you about what is
wrong. But there are other issues.

In get_quat(), there is no point in returning anything, as the
function is already putting the relevant info in the quatArray
parameter.
Then, when calling get_quat(), you don't want to assign the return
value to anything.
You cannot assign an array like you did, unless it's an
initialization. I would explicitly copy the sub-arrays with
memcpy():

void get_quat(Adafruit_BNO055 ref, double quatArray[])
{
    imu::Quaternion quat2 = ref.getQuat();
    quatArray[0] = quat2.w();
    quatArray[1] = quat2.x();
    quatArray[2] = quat2.y();
    quatArray[3] = quat2.z();
}

void Calibrate()
{
    get_quat(bnoABC, quatCalib_ABC);
    get_quat(bnoGHI, quatCalib_GHI);
    memcpy(quatCalib_mat[0], quatCalib_ABC, sizeof quatCalib_ABC);
    memcpy(quatCalib_mat[1], quatCalib_GHI, sizeof quatCalib_GHI);
}

It could be noted that storing the calibration array twice (as both one
2D array and two 1D arrays) is a waste of RAM. You could get rid of the
1D arrays and have instead get_quat() fill the lines of the 2D array
directly:
void Calibrate()
{
    get_quat(bnoABC, quatCalib_mat[0]);
    get_quat(bnoGHI, quatCalib_mat[1]);
}


text:
Using HC-05 to play a sound on an app
I connected a HC-SR04 Ultrasonic Sensor to Arduino Uno and built the circuit as shown in the link below. I also used the code below the link. Together, this code and the circuit detect any motion that occurs in front of the ultrasonic sensor. When the sensor detects motion, the console in the Arduino IDE prints that it detects motion and how far away the moving object is. Otherwise, nothing is printed.
I created an app using MIT App Inventor. Every time the Arduino detects motion, I want a sound to be played on the phone of the person with the app. In order to do this, I plan on using a HC-05 Bluetooth Module.
Does anyone have any suggestions for how I should build the circuit and what code I should use?
arduinobasics.blogspot.de/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html
#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
 Serial.begin (9600);
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}

int prevdist = 0;

void loop() {
/* The following trigPin/echoPin cycle is used to determine the
 distance of the nearest object by bouncing soundwaves off of it. */
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);

 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);

 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);

 //Calculate the distance (in cm) based on the speed of sound.
 distance = duration/58.2;

 if (distance >= maximumRange || distance <= minimumRange){
 //Print "Out of range when there is no object within the range of the ultrasonic sensor.
 Serial.println("Out of range.");
 digitalWrite(LEDPin, HIGH);

 }
 else {

 /* Send the distance to the computer using Serial protocol, and
 turn LED OFF to indicate successful reading. */

   if((prevdist - distance) > 10 || (prevdist - distance) < -10)
   {
     prevdist = distance;
     Serial.println("[OBJECT MOVED]");
     Serial.print("Detecting object ");
     Serial.print(distance);
     Serial.println(" cm away");
     Serial.println();
     digitalWrite(LEDPin, LOW);
   }
 }

 //Delay 1 millisecond before next reading.
 delay(1);
}

Every time the Arduino detects motion, I want a sound to be played on the phone of the person with the app. In order to do this, I plan on using a HC-05 Bluetooth Module.
Does anyone have any suggestions for how I should build the circuit and what code I should use?

The Arduino sketch above is a good start.
The first step is to connect the Bluetooth module so that the Serial output can be sent. The circuit is simply connecting the Bluetooth module to RX/TX on the Arduino. I am assuming that you have written an app that can read from Bluetooth on the phone and write to the screen.
The second step is to parse the output and play the sound. That is also part of the app and not the code on the Arduino. To make this easier the sketch output statements can be changed to something easier to parse (detect).
All and all the work is mainly app programming.
Cheers!


text:
Arduino: put string through variable in array
I have a problem and I can't fix it.
I'm busy with an java to arduino project.
Java writes a string using writeString();
Arduino reads the serial monitor and put the incoming string into a function.
then I want to put the string into a variable and the variable into a char arr[];
The problem is: When I put the string directly in the arr[]; it works, but when I put first the incoming string in a variable and then the variable in the arr[]; it gives me the next error:

string-parser:44: error: array must be initialized with a brace-enclosed initializer
exit status 1
initializer fails to determine size of 'arr'

this is the code that doesnt work:
input = "2,5>2,6>2,7>4,8";

String splitStringIntoCoordinates(String input){
  char arr[] = input; // Place incoming route in char array
}

This is the code that does work:
String splitStringIntoCoordinates(String input){
  char arr[] = "2,5>2,6>2,7>4,8"; // Place incoming route in char array
}

I hope anyone can help me.
Thanks!

A String isn't a char array. You can't assign one to the other.
You shouldn't be using String, it's too heavyweight, and how you are passing your String object is wrong, it wastes huge amounts of memory making clones.
You should read this.
The only time you should ever consider using a String object is if you are using a third party library that requires a String object - and even then you should consider other methods.
Regardless of that, you need to copy the content of your string, not the string itself.  This code should work, but it doesn't address the underlying String issues:
String splitStringIntoCoordinates(String &input){
  char arr[input.length() + 1]; // Create a char array big enough including the terminating NULL
  strcpy(arr, input.c_str()); // Place incoming route in char array
  // ... etc ...
  // return a string
}

If you just want to reference the String as a C string you can just use the function input.c_str() to get the internal char * array pointer.

Thank you majenko! This worked for me. I never tought of that.


text:
How do I power my Arduino Micro directly?
I just need some confirmation, before I break something. So far I have been powering my project from USB, no I would like to power it from a battery. The official spec claims I should use a voltage anywhere from 7-12V, so I got myself a 9V block battery and would connect the positive lead to the VIN pin and the negative lead to the ground pin right next to it, based on this schematic: https://40.media.tumblr.com/cdadca4e95808b376de52a88a5468367/tumblr_mi61oww6cu1s5t695o1_1280.png
Do I need a resistor?

According to this schematic, VIN goes to the on arduino-micro's 5 and 3 volt regulators.  So you should not need a resistor.
The 5 volt regulator needs a bit more than 5 volts at it's input to do a good job.  That is why the specification calls for 7 to 12 volts.


text:
I am not able to compile,libraries missing
this was the error  message
Arduino: 1.6.7 (Windows 7), Board: "Arduino/Genuino Uno"
Sketch uses 1,068 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 11 bytes (0%) of dynamic memory, leaving 2,037 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "\.\COM17": The semaphore timeout period has expired.
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
Invalid library found in C:\Users\nehal\Documents\Arduino\libraries\leddelay: C:\Users\nehal\Documents\Arduino\libraries\leddelay
Invalid library found in C:\Users\nehal\Documents\Arduino\libraries\sketch_jan16c: C:\Users\nehal\Documents\Arduino\libraries\sketch_jan16c
Invalid library found in C:\Users\nehal\Documents\Arduino\libraries\leddelay: C:\Users\nehal\Documents\Arduino\libraries\leddelay
Invalid library found in C:\Users\nehal\Documents\Arduino\libraries\sketch_jan16c: C:\Users\nehal\Documents\Arduino\libraries\sketch_jan16c
This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
 What should I do?

You have two distinct issues here, one critical and one probably annoyance-level.  The critical one is that your chosen serial port is not available - maybe the board moved, or something else is trying to talk to it.  Separately, you seem to have some garbage in the libraries folder, maybe a sketch inappropriately saved there.   The IDE is complaining about that, but not refusing to compile on account of it in the way your title implies - you do not actually have a compile error.


text:
Sound or motion activated long term battery powered Arduino
Basically, I want an Arduino to power up whenever a "creature" enters viscinity (at least within up to 3 meters).
I would really like this to be able to keep monitoring for at least 4-8 weeks, without having to replace batteries. I don't want to use more than 1 or 2 18650 Liion cells.
Couple of methods that I believe would work:

Changes in light-conditions.
Sound.
Small vibrations in the ground.

Approaches to conserve power:

Checking for changes in light at most every 30 seconds (boot the Arduino, and power off quickly).
Checking for 1 second for sound, every 10-15 seconds.
Vibrations in the ground using an accelerometer?

The ideal solution does not run the Arduino at all, unless a trigger causes it to run. When the Arduino starts, it will have to turn itself off again to resume monitoring mode.
What approach should I go for? I'm not very good with electronics, and would like to avoid configurations involving transistors, resistors and so on - unless stricktly required.
Is it possible/easy to wire an Arduino Pro Mini to run directly off a 3.7 V battery, bypassing any power hungry voltage regulators?

Is this a counter device you are seeking to construct? What will the arduino perform once triggered by creature and powered on?
Is it practical to consider a solar charging system as an add-on, to keep your selected battery healthy during the desired period?

Many MEMS accelerometers can be programmed to generate a wakeup interrupt to a host MCU when a threshold is exceeded.  In terms of power savings, you will need care to both hardware and software design.  The simplest conservative power solution is indeed to run directly off the cell with no regulator losses, as that is in the allowable range for your MCU - but it may not be for the MEMS.  Greater efficiency would be a well chosen switching regulator running the electronics near their minimum suitable voltage where consumption will be lowest.  Watch out for voltages left across resistors!

I'd just go with a PIR sensor. I have my arduino check light levels every 250ms, and it runs for more that half a year on 2 AA batteries.

For a truly low-power, Arduino-based, solution the following it's needed:
A) HARDWARE SIDE:

Use a supply voltage and clock frequency as low as possible. The Arduino Pro Mini 3.3V @ 8Mhz board is a good starting point for a first project.
Get rid of all the LEDs in the board. Their consumption is in the mA range, way too high.
Get rid of the onboard regulator and replace it with a low quiescent current, low dropout regulator like the MCP1700. You don't need a switching regulator unless your Arduino spends most of the time awake and consuming a lot of current, which is a very unlikely scenario. The high quiescent current of switching regulators rules them out for this kind of applications.
Select a low-power consumption sensor and signal conditioning circuitry. PIR and CMOS logic family 74HC are good technologies for this.
The signal conditioning circuit must generate a level interrupt from whichever signal is delivered by the sensor. Timing elements (like capacitors) may be required for this. To be on the safe side, design it for a 100 ms resettable pulse.

B) SOFTWARE SIDE:

Install a low power Arduino library like this one. Use the ATmega328p power-down sleep mode.
Write a interrupt service routine (ISR). This is the piece of code  will deal with whichever needs to be done upon an interrupt event.
Configure the interrupts as required. Note that only level-triggered interrupts can wake up ATmega328p from power-down sleep mode, as per its datasheet:

Here you can find really good information on the way to go low power.

What you want to do after the triggering is an important part of this design.
An Arduino platform is not necessarily the best choice for power sensitive applications.  You identified one problem in your post: Linear regulators.  What you are likely wanting is an efficient switching power supply to support a wide range of voltages as your batteries drain.
Many embedded processor have low power modes.  Some are specially designed to reduce current draw down into the nA range when idle or sleeping.  However, all such processors require special care when configuring for these deep sleep modes.  That is to say, the application plays an important roll in deciding how to put a processor into such modes.
Supporting hardware is perhaps the most important aspect of a low power designs.  Contributions from the most advanced low power processors can be wiped out if supporting hardware runs at mA ranges.  A simple 10K pull up resistor will draw 0.5mA in a 5 volt circuit. The impact is meaningless in a mains powered application.  But for long term battery operation is could means days of lost time.
All that said, there are resources for Arduino low power operation.  Here is a low power library.  You will have to decide if it is sufficient for you application. Or if you need to also investigate low power hardware solutions.

Rechargeable lithium batteries have great energy density but they also have some significant self-discharge, making a bad choice for low-power applications. Have a look on this Arduino "clone": https://talk2.wisen.com.au/product-talk2-whisper-node-avr/, which is designed to run from standard Alkaline batteries and consumes very little (under 4µA when sleeping).
For the sensors, you should look for smart ones. You can find some very sophisticated MEMs sensors which will produce interrupt based on thresholds. You normally use I²C interface to talk to those little devices.
For example, you could use something similar to this one for light sensing: http://www.vishay.com/optical-sensors/list/product-83462/. Although this is a proximity sensor, it also has thresholds for the ambient light as well as consumes very little current.
The most important is to design the solution to run at lower voltage (3.3V instead of 5V) and also use interrupts to wake-up everywhere. If you like to run a bare ATMega328p directly from a 18650 cell, make sure everything will be ok to run from 4.2V to 3.0V as you're not using any regulation.


text:
Why is my potentiometer giving strange reading?
I have a 10kOhm linear Potentiometer. I connected it to analog 0, as in https://www.arduino.cc/en/Tutorial/Potentiometer.
The analogRead() gives a value between 0 and 1023, so I was expecting 0 if the potentiometer is at the lowest position, 1023 if it is at the highest position and 500 somewhere in the middle.
In fact I get ~40 at the lowest position, I get 1021 at the highest position (that's okay, I guess), and I also get 1021 at the middle. 500 is at a 1/4 position, I expected to have ~255 there.
I measured the resistance of the potentiometer. It reads ~200 Ohm at the lowest postion, 10kOhm (as expected) at the highest position and ~5kOhm in the middle, so, exactly as I expected.
So, what did I get wrong?

What arduino are you using? It sounds a bit like you are using a 3.3v arduino, but connected the pot to 5v.

I am using an Arduino mega 2560.

I tried the 3.3V instead of the 5V, but I have the same effect. Good results in the lower 1/4 of the poti, no change as soon as I go higher up.

Does a DMM give correct resistance readings at various positions?

Take the multimeter and measure the voltages you see at the Arduino pin.

Note the comment by @Posipiet is a very important one - measure the voltage at the Arduino pin, with the potentiometer in circuit. Just to rule out the possibility of, say, a poor 5V or 0V connection or something similar. Also the 200 ohm value at lowest resistance is a bit suspect...

Please describe how you wired all contacts of the potentiometer, not only the wiper. And please check what happens if you exchange the wiring of the endpoints.

Exchanging the endpoint wires flips the values around, so, zero is the other end of the poti. However, the effect stays.

Measuring the voltages between 5V and A0 on the arduino gives the readings I would expect with a logarithmic potentiometer. However, measuring the resistance of the poti confirms that it is linear.

Unfortunately I cannot comment. I can't really think of a reason why your readings are the way they are. Though you did not present to us an image of what potentiometer you are using and how you are really wring it up.
It is possible that your potentiometer is a center tapped type with 4 pins. You could have possibly connected the positive rail to the center tap pin, ground to the side pin and the wiper pin to the Arduino pin so that you would have the result you are getting.
Or potentially, you wired it correctly except for the fact the positive rail you connected to was 10V, but that is really dangerous.
Have you tried measuring the resistance of the potentiometer from one side pin to the other side pin?

Well, not sure what was going on, but rotating the cables helped. So probably something was connected wrongly.

Do you mean as in swapping the cables?

Yes, but, looking more closely, it did not help.

@Alex measure the voltage of the wiper at different positions. Also make sure you are not using any other components in the circuit (except for Arduino and power supply). An image would help us greatly.

@Alex basically follow the suggestions in the comments under your question. They will lead you to solving your problem.

It sounds like you have a log taper potentiometer rather than a linear taper potentiometer.  These are used in audio applications.
You can tell the difference by looking at the resistance code.  It may be written as:

103 B

or

10K B

both of which are 10KΩ LOG taper.  The letter A or B as a suffix is the taper type. A is linear, and B is logarithmic.  That's the "normal" standard, though, but Japan does it differently. They use A for Audio taper (log taper) and B for linear.

That was my thought too, but the OP claims that he measured it to be 5K in the middle.

500 (50%) at a quarter turn says logarithmic to me.

oh, at quarter-turn. Yes, of course. I should have reread that part before referring to it :)

The interesting thing is: I did measure 5kOhm in the middle, which says linear. But I also read 500 at a quarter position, which says log. So, WTF!


text:
Generate particular pulse using Arduino
How can I generate this pulse with an Arduino Micro?
Is it necessary an external component?

how much current will you be drawing / what will it be connected to?

is only for signal generator experiment

Looks like something for a 2-bit DA converter. https://en.wikipedia.org/wiki/Digital-to-analog_converter. A resistor ladder is the simplest solution; https://en.wikipedia.org/wiki/Resistor_ladder

Take two 10K or so resistors:
    +5V
     |
    10K
     |
Pin2-+---> output
     |
    10K
     |
    GND

The following program does the trick:
const uint8_t kPin = 2;
const uint32_t kDelay = 10;  // 100Hz

void setup() {
}

void loop() {
  pinMode(kPin, OUTPUT);
  digitalWrite(kPin, HIGH);
  delay(kDelay);

  pinMode(kPin, INPUT);
  delay(kDelay);

  pinMode(kPin, OUTPUT);
  digitalWrite(kPin, LOW);
  delay(kDelay);

  pinMode(kPin, INPUT);
  delay(kDelay);
}

When Pin2 (or any other pin for that matter) is set as INPUT, it is in high-impedance state (theoretically), so effectively you have a voltage divider giving you 1/2 Vcc. When it is set as OUTPUT, and now assuming that its output impedance is << 10KΩ, it drives the output to either +5V or 0V.

Obviously, this solution does not generalize to multiple levels; folllow @gerben's solution with a resitor ladder for that. However, I like using tri-state pins in creative ways. Charlieplexing is the canonical such example.

If both inputs are 0V, the output will be 0V.
If both inputs are 5V, the output will be 5V.
If one input is 0V and one 5V the output will be 2.5V.
However, if the device attached to the output doesn't have a high input impedance, the voltage will drop some. You could add an opamp to prevent this.
I think you can generate the 2 pins outputs using one of the timers in phase correct pwm mode. Freeing up the cpu and giving a very clean output signal, as using software "pwm" could be slightly of due to interrupts occuring.

ha! mine uses only one pin :)
What did you use to draw the circuit?

@JayEye cool solution. Didn't think about tri-state. I used kicad to draw the schematic.


text:
Syncing/taking external clock for SPI on Arduino Due
I have an Arduino Due with a SAM3X8E chip and am trying to read SPI data from an external source that is communicating in SPI. I was able to get data by identifying specific bytes that are identifiers but realized that the clock for my board is not synced with the source coming in. I print out the bytes in hexadecimal format (08 00 FF AB etc) and each message is 128 bytes long.
To be clear, the source is an SPI master that is sending out data on its own MOSI line, but I am currently treating my board as a master as well since I do not know how to do Slave mode on Due. I connect the Slaves MOSI line to my boards MISO line, and just transfer data and read 128 bytes but it would appear that I am not getting the same data. Is there a way for my to take in the clock from the external clock and synchronize my board with that clock to make sure? My source code is below. The only methods I can think of are to either figure out how to implement the board in slave mode (i'm not familiar enough with the registers and how to change this, or read data in slave mode) or synchronize the clocks so my board is reading and sampling the source data correctly.
Could someone check if my thinking is correct, or do I not need to make any changes since the data is in a shift register?
Thanks

void setup(){
Serial.begin(9600);
SPI.begin();
SPISettings settings (50000000, LSBFIRST, SPI_MODE1); //Sampling rate    50Mhz, source's max speed
SPI.beginTransaction(settings);
}

void loop(){
  int i = 0;
  uint8_t value;
  value = SPI.transfer(0x00);
  while (value != 8){//searching for identifier 0x08
    value = SPI.transfer(0x00);
  }
  SPI.transfer(buffer, 127);//get the rest of the 127 bytes
  Serial.print(value, HEX);
  Serial.print(" ");
  for (i = 0; i < 127; i++){
    if (buffer[i] == 0){
      Serial.print(buffer[i],HEX);
      Serial.print(0, HEX);
    }
    else{
      Serial.print(buffer[i], HEX);
    }
    Serial.print(" ");
  }
  Serial.println("\n");
}

For your external source to be an SPI bus master, it has to be the only one generating the clock signal. Yet, calling SPI.transfer() also generates a clock signal from the Arduino; both devices are attempting to drive the clock line simultaneously, hence your problems.
You have to bit-bang this or manipulate the SAM registers yourself to configure it as a slave; the SPI library doesn't support slave mode.
In order to bit-bang, you'll have to define your own MOSI, SCK, SS (and MISO, if you'll be writing to the master) pins and do all the sampling yourself with digitalRead(); there are no registers to be read from since you aren't using the SAM's SPI peripheral.
Since your SPI mode is MODE 1, it means the clock idle polarity is LOW, and that data is sampled on the falling edge. To bit-bang with digitalRead(), it is necessary that the SCK frequency be below 50 kHz (digitalRead() takes about 4us), taking overhead into account. You should use direct port manipulation, if you need a higher frequency. If you'll be blocking till you've read data, and assuming that the external source always sends data in byte units, then a basic algorithm:

Create a byte array to hold all the expected bytes
Define a byte variable (curr_byte, maybe) for holding each byte received
Wait till the SS pin goes LOW
Clear curr_byte to zero
Wait till SCK goes HIGH
Wait till SCK goes LOW
Read the bit on the MOSI line and shift it into curr_byte
If you've received up to 8 bits so far, save curr_byte to the byte array; if SS is still LOW, go to step 4, else exit this loop. But if you haven't received a complete byte yet, go to step 5.

After you leave the loop, you can then confirm the bytes you've received with Serial. If the external device can send data with any number of bits, then you should always check the SS line after you shift in a bit, to determine if the Due has been deselected or not i.e. if there are any more incoming bits.

Thanks, that seems to make sense. I think I understand bit-banging but am confused as to how I should sample accordingly since I can't call SPI.transfer(). Is it reading from SPDR or the data register? Because on Arduinho Due, I don't think it recognizes SPDR, but the objective should be to just wait until SCK is high and then read from the respective data register. I'm just not sure how to or which register the incoming external MOSI data will be found.

@wallenut I've edited my answer.

That clears it up a lot. Thank you, I just have to deal with the locating where MOSI data is shifted into registers and read those and it should be fine.

Your help answers my question. I just do not think it will work for the high clock rate at which this sends data (50 Mhz). I'm going to mess around and try to change the registers and operate it in slave mode, but there is not much Arduino due documentation for slave mode. Any tips on how to use the Atmel Data sheet? This is my first real Arduino project.

@wallenut You won't be able to achieve 50 MHz; the Due has an 84 MHz clock and the lowest SPI prescaler is 2, giving you a maximum SCK frequency of 42 MHz. Is it possible for you to get the master to send data at lower speeds? For a sample Due slave sketch, check this out: https://github.com/manitou48/DUEZoo/blob/master/spislave.ino. You'll have to change the SPI mode to MODE1 in the sketch, set the clock speed with SPI.setClckDivider(SPI_CLOCK_DIV2) and adapt the loop() for your purposes. I haven't used a Due before though, so I may not be much help.


text:
ATTiny85, how to fix overwritten clock pins?
I'm using an ATTiny85 with an external 16MHz clock. I accidentally set pins 3 and 4 to output using pinMode() in a program and uploaded it, and now I'm getting an invalid device signature (the signature is 0) error when I try to upload a sketch.
How can I go about fixing this (if possible)?
I am using an Arduino UNO as ISP, with an external 16MHz clock and capacitors connected to pins 3 and 4, and have rechecked my wire setup multiple times.

Holding the chip in reset while powering it on will ensure that the pins are never reconfigured.


text:
Arduino/Genuino not in board list
I've downloaded the Arduino IDE and the Genuino isn't in the list of boards. I'm running Rasbian and used the command line to install.

Which version of the IDE? A lot of Arduino boards are branded Genuino (after the fiasco of the dispute over the "Arduino" name). It could be a Genuino Uno, or Genuino Nano, or whatever.

"Genuino" is just a name, not an identifier. Pick the equivalent Arduino board from the list.


text:
Is my HC-05 broken?
I have an HC-05 wired with an Uno, and am using a sketch to control the HC-05 AT mode and send AT commands, per a variant of this instructable:  DIY Arduino Bluetooth Programming Shield
The error I have is simple in appearance, when AT mode is signaled off by bringing HC-05 pin 34 low after being high, then a low pulse is sent from the HC-05 to the HC-05 pin 32 which is wired to the Uno reset pin per the instructable.  The low pulse should not be occurring and is triggering the Uno to reset, even though it is only 1-2ms.  The low pulse also occurs when the HC-05 is powered on, neither low pulse occurs if the polar command is reset to normal "1,0".
After receiving the "AT+POLAR=1,1" command the HC-05 pin 32 should trigger low when a BT connection is made to the HC-05, that part works correctly.  The other low pulses triggering the Uno to reset when signaling to leave AT mode and when powering on the HC-05 are causing problems with running the sketch so I need to determine how to stop them.  I have checked the AT settings I am familiar with and they are as expected.
Any ideas are appreciated.  Thanks for your help.


text:
MQTT and IR code Raw
I want to upload/pubish RAW IR Code to MQTT server received through my ESP8266. I have received the following RAW IR code from the Television using the IR receiver sensor:
RAW IR CODE = {
  4650,4250, 700,1550, 650,1550, 700,1550, 650,450,
  650,500, 600,500, 600,500, 600,550, 550,1700, 550,
  1650, 600,1650, 550,550, 600,500, 600,550, 550,550,
  600,500, 600,550, 550,1650, 600,550, 550,550, 600,500,
  600,550, 550,550, 600,500, 600,1650, 600,500, 600,1650,
  550,1700, 550,1650, 600,1650, 550,1650, 600,1650, 600
}

I want to create a new variable with the following structure:
value = RAW IR CODE+";" + "ESP8266-01"(This is the ID of the esp8266)

value =  {
  4650,4250, 700,1550, 650,1550, 700,1550, 650,450, 650,500,
  600,500, 600,500, 600,550, 550,1700, 550,1650, 600,1650, 550,550,
  600,500, 600,550, 550,550, 600,500, 600,550, 550,1650, 600,550,
  550,550, 600,500, 600,550, 550,550, 600,500, 600,1650, 600,500,
  600,1650, 550,1700, 550,1650, 600,1650, 550,1650, 600,1650,
  600
}; ESP8266-01

I am unsure: which data type do I need to save the variable value so that it can later be retrieved/subscribed and sent to another IR sender using irsend.sendRaw, because I want to split the variable "value" into 2 parts after receiving it, the ID and the RAW code. After getting the RAW code, I want to use the irsend.sendRaw(RAW CODE, length of RAW , 38).
Could someone help me?
My attempts:
At first I tried to save it as a string, so that it can be retrieved and separated for irsend.sendRaw. However I am unable to compile it.
This is the code which I used to upload:
      /*
     * IRremoteESP8266: IRServer - MQTT IR server
     * An IR LED must be connected to ESP8266 RX port (GPIO-3)
     * An IR receiver to GPIO 0
     * used library:
     * https://github.com/markszabo/IRremoteESP8266
     */
    #include <WiFiClient.h>

   #include <ESP8266WiFi.h>

 #include <IRremoteESP8266.h>
    #include <PubSubClient.h>
    int RECV_PIN = 0; //an IR detector/demodulator is connected to GPIO pin 0

    IRrecv irrecv(RECV_PIN);
    decode_results results;

    const char* ssid = "MY-SSID";
    const char* password = "MY-WIFI-PSK";

    const char* topicRaportPrefix = "esp8266/02/info/";
    const char* topicSubscribe = "esp8266/02/sender/#";
    const char* topicPrefix = "esp8266/02/";

    const char* mqtt_server = "10.10.10.10";
    const char* mqtt_user = "mqtt_user";
    const char* mqtt_pass = "mqtt_pass";

    String clientName; // MQTT client name
    char message_buff[100];

     void dump(decode_results *results) {
        const int count = results->rawlen;
          Serial.println(c);
          c++;
          Serial.println("For IR Remote ");
          for (int i = 1; i < count; i++) {

          if ((i % 2) == 1) {
            Serial.print("+");
            Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
        uint16_t  raw_ir_code[count] = results->rawbuf[i]*USECPERTICK;
            client.publish( "esp8266/02/sender", raw_ir_code);

After doing the changes proposed, I still get an error in compiling:

no matching function for call to 'PubSubClient::publish(const char [18], uint16_t [(int)count])'

Check the prototype for the publish() member function and cast the parameter to the expected type. Check that null terminated string is not assumed. In that case you will have to do the conversion. The member function should have at least three parameters to work; topic, data pointer, number of data bytes.

First create a topic and include the ESP8266 ID. Do not make it part of the published value.
Second publish the raw data as-is, uint16_t raw_ir_code[RAW_IR_CODE_MAX]. The alternative is to convert to string (characters). But if the subscriber has the same architecture (interpretation of data), there is no need to convert it to string and back. Simply publish the raw data as it is.
You will need to cast the raw_ir_code vector to the appropriate type for the MQTT publish call.
Cheers!

Could you explain how to retrieve the value from the mqtt server.

What library are you using?

Esp8266IRremote

And what library for MQTT?

No specific library but using the code for normal connection with Mqtt server.


text:
Customize FTDI driver for custom PID and VID
I have changed PID and VID of my FTDI board for  arduino program because i wanted to rename the com port name.
The ic is  FT232R a USB to serial UART interface IC. I have store new vid and pid to EEPROM.
Now It is showing in unknown devices. I am not able to update driver of it.
I have followed this article http://forum.arduino.cc/index.php?topic=6929.0.
Can anyone tell how to make cutmoize driver for it.
Any suggestions will be very helpful.

Most likely you want to edit the .inf file to add new VID/PID options.

Thank you for a  valuable reply. I have change in inf but i am not able to install it.Would you tell me after changing inf file how to install it.

You may need to go through the convoluted "Update Driver" route in the device manager. It's not a nice method. You may need to (somehow) uninstall the old driver so that it will pick up the new one.

@Majenko Windows is saying the new driver is corrupted.

I have installed the customize driver to windows but forcefully because to driver signature issue. How to get it solve.

On Windows
You can refer to FTDI's documentation here for details on how to create your own custom device driver. The FTDI website has a lot of resources for this, however they seem to be a little outdated. Microsoft details how drivers work in it's Hardware Dev Center.
On Linux
On Linux it may be as easy as registering the device with modprobe. For example, for a device with a VID of 0102 and a PID of 1234, execute the following from the shell:
modprobe ftdi_sio
echo "0102 1234" | sudo tee /sys/module/ftdi_sio/drivers/usb-serial\:ftdi_sio/new_id > /dev/null

You can do it, but you cannot change the PID and VID without a new certificate.
Did you changed the name with the FT-Prog Tool (MProg is outdated)?
You can download the last version from here:
https://www.ftdichip.com/Support/Utilities.htm#FT_PROG
You can set everything on your FTDI chip, even change the PID and VID. But at this point, you will not be able to use the standard FTDI driver anymore as you need to sign it with a new certificate (it is about 400$/year).
What you can do is leave the PID and VID and just give another name. So you will be able to use the default driver and you will see your custom name in the device manager.
Of course, in the list you just see "USB Serial Port (COM X)". But in the description of the device (Serial port), you will find this string:
FTDIBUS\VID_0403+PID_6011+YOURCUSTOMNAME&1\0000
If you create an application, you can just check for this, to see if it is your module. If you want more, you have to develop and release your own driver. But you can't do it anymore without a certificate, or without start Windows in unprotected mode.


text:
Accessing configuration registers of OV7670 cam on i2c
I am a new user of Aurdino and want to interface OV7670 camera with aurdino uno which uses i2c mode of communication.I want to check the configuration of the device control registers and set them as per requirement. In this case, OV7670 is my slave device.
     How can I access a particular register inside the slave device?(The parameters for commands like wire.begin() etc., include slave address but not the address of the registers inside a slave device.)

I think this belongs on the Arduino SE

@stefandz I am using arduino uno

Thanks - my comment is meant to suggest that this question be migrated to the Arduino StackExchange site.

To communicate with the OV7670:

SIOC => SCL
(pulled up to 3.3V)
SIOD => SDA
(pulled up to 3.3V)
RESET => 3.3V
PWDN => GND
XCLK => Clock signal is necessary (at least 10 Mhz)
Vcc => 3.3V
GND => GND

The XCLK needs at least 10 MHz according to the datasheet, but from other accounts, it seems that's not a hard limit. You can get a 4 MHz clock from the Uno using its timer0; check out this post on how to do it. After this, you can write a small sketch along the lines of:
Wire.begin();
Wire.beginTransmission(0x21);
Wire.write(0x12);  // software reset
Wire.write(0x80);
Wire.endTransmission();
delay(500); // wait for reset to complete

Wire.beginTransmission(0x21);
Wire.write(0x01);  // u now read from reg 0x01
Wire.endTransmission();
Wire.requestFrom(0x21, 1);
while (Wire.available() == 0);  //block till u get something
while (Wire.available())
  Serial.println(Wire.read(), HEX);

You can place everything in setup() after including the Wire library and setting up the XCLK clock signal. If all goes well, 80 should be printed in the serial monitor and this will confirm that you're now communicating over the SCCB with the camera.
I should warn you that while others have used the Uno to grab images from the OV7670, the process is moderately complex, especially for a beginner, and it's not what the Uno is intended for; all you'll be able to do is grab frames and pass them on to some TFT screen or your PC and even then you'll get at most 5 fps, I think, with QVGA or QCIF output. You'd be better off with some ARM dev board, one running Linux perhaps. Good luck.

Take a look at the datasheet - that will show you the correct waveforms / transactions for this. However, something like this should work (assuming 8-bit addresses and registers)
// reading

Wire.beginTransmission(address);
Wire.write(reg); // set address to read from our requested register
Wire.endTransmission(false); // repeated start
Wire.requestFrom(address,(unsigned char)1);  // just a single byte
if(Wire.endTransmission()!=0){
    // put error code here
}
readValue = Wire.read();

// writing

Wire.beginTransmission(address);
Wire.write(reg);
Wire.write(value);
if(Wire.endTransmission()!=0){
    // put error code here
}


text:
Adruino Yun's Linux environment not working
I was recently given an Arduino Yun board from my university. I am able to upload sketch to the board, and it seems to function properly. However, I am unable to see the Linux booting up. When I want to reset the WLAN, ressing the WLAN RST button does nothing at all, the WLAN LED doesn't even blink or light up. Pressing the YUN RST button also does nothing.
So I did some Googling and found out that I could upload the YunSerialTerminal to the Yun, so I did that. And when I am trying to monitor the Linux boot up from the serial monitor. Nothing is shown. I press the TUN RST button as taught by the Arduino website while monitoring the Serial Monitor, nothing shows. However, the RX button does blink whenever I press enter.
Can anybody help me?

You might need to re-flash the operating system. Unfortunately it's not a trivial task.
I had to do something similar with a Dragino shield (like a Yun on a shield) that uses the same OS and core chip. Instructions were scarce and hard to follow, plus I run Linux, so there's even less instructions. I worked it out, though, and wrote a tutorial here.
While that is for Linux and the Dragino shield I am sure the basic principles are the same for the Yun - just make sure you get the right image file for your Yun (don't get the Dragino one I link to).
The main thing is to gain access to the boot manager (dr-boot, or whatever the Yun has), which means setting up a wired (ethernet) network and messing with UDP sockets (using nc in Linux - no idea what you can use in Windows).
I'm sure you can find a tutorial for fixing the Yun from Windows (or whatever OS you use) to help you get into the boot manager and upload a new OS image.

Warning use version 1.5.3. When you download the latest version 1.6.2 you also need to update the bootloader.


text:
How to determine Flash size?
I need to determine the flash size of my ESP8266 on my NodeMCU module in order to flash the AT firmware onto the board. Apparently different boards come with differently-sized flash memories. Can anyone tell me the easiest way to find the flash size?

By reading the manual for your NodeMCU. Which version is it?

It's Version 1.0

The version 1.0 uses the ESP-12E which has 4MB flash.

esptool.py -p COM5 -c esp8266 flash_id (you can find esptool inside ESP-IDF SDK components/esptool_py)

use ESP.getFlashChipRealSize()  in your code.

Arduino's ESP8266 support includes an example sketch called CheckFlashConfig. This probes the board, and prints the flash memory size.

The easiest way (windows at least) is to use Espressif's flash download tool - don't select anything to flash to the device, select the appropriate com port, click start, and the details of the device will appear in the Detected Info window


text:
Powering 3 servo motors and Arduino Uno with one 9 V battery
I wish to power an Arduino Uno board AND 3 servo motors using a single 9 V battery.
I have connected the positive terminal of the 9 V battery to the VIN pin. The negative terminal of the battery is connected to the GND pin immediately following. This, I believe, powers the Arduino Uno board.
Next, I have connected the power wires of all 3 servo motors to the 5 V pin on the Arduino board ( using jumper wires and a  breadboard). Similarly, all the servo ground wires have been connected to the second GND pin in the 'POWER' set of pins on the Arduino Uno board. And finally, the 3 signal wires from the servos have been connected to the three PWM pins on the 'DIGITAL' row, exactly pins 9, 10 and 11. THE SERVOS ARE NOT OPERATED SIMULTANEOUSLY, THEY ARE BEING OPERATED ONE-BY-ONE (but the load is still attached to each of them, a couple of grams is all).
Since the servo motors operate between 4.8 V - 6 V, and I don't have any spare AA batteries to approximate a 6 V battery, I thought this could solve the problem.My question is, does this pose any problems for the board or devices, does this draw a higher current? Will it damage the Arduino Uno board or the servo motors or any of the individual pins?  Please let me know soon, thank you very much.

Do you have any of the specifications for any of the things you are connecting?

@IgnacioVazquez-Abrams. Servo motor specifications: Operating voltage: 4.8 - 6 V. Operating speed: 0.2s/60 deg (at 4.8 V), 0.16s/60 deg (at 6 V). Stall torque: 3.8 kgcm (at 4.8 V), 4.5 kgcm ( at 6 V). Temp range: 20 degC - 60 degC. Is this what you were asking for?

I don't think anything should get damaged; the regulator is rated for 1A, and even beefy servos don't draw more than 200mA when moving against heavy load. The problem is that your battery won't last long. Even the heavy-duty Li primary 9V batteries are under 1000mAh, and the actual capacity is heavily dependent on the discharge rate.
Why can't you use a rechargeable Li-ion pack with an appropriate step-up or step-down converter?

I do have a rechargeable 9V Li-ion battery. Are you talking about a DC-DC converter? Isn't the Arduino's voltage regulator enough? Can you please explain why you suggested that setup. Thank you.

I'm sorry, since my question wasn't clear on this point. The servos are not being operated simultaneously, they're being operated one-by-one. In such a case, wouldn't the battery last longer than otherwise? If so, could you explain why? Thank you.

The 5V regulator on the Arduino is a linear regulator, not a switching regulator. In any case, you probably won't damage anything. Just connect it up and see how long it lasts, and whether that's enough for you.


text:
PID control arduino
I am hooking up an accelerometer to an arduino uno and running it through this pid controller. However the output isnt going to my setpoint. When i move the accelerometer back and forth the data goes to 255 or 0. Any ideas?
Datasheet for accelerometer:
https://www.sparkfun.com/datasheets/Components/SMD/adxl335.pdf
I get 336 for the x direction, which is the only direction i'm using, when its set flat on the table, which is my setpoint/desired output.
Note: Is the output the value away from the setpoint or the actual acceleration it calculates through the controller?
#include <PID_v1.h>

#define PIN_INPUT A0

//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Define the aggressive and conservative Tuning Parameters
double aggKp=4, aggKi=0.2, aggKd=1;
double consKp=1, consKi=0.05, consKd=0.25;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);

void setup()
{
  //initialize the variables we're linked to
Serial.begin(9600); //Start a serial session
int  xdata = analogRead(PIN_INPUT);
Input = map(xdata, 0, 1024, 0, 255); //Change read scale to analog out scale
int setPoint = 336;
Setpoint = map(setPoint, 0, 1024, 0, 255); //Change read scale to analog out
//turn the PID on
myPID.SetMode(AUTOMATIC);
}

void loop()
{
int xdata = analogRead(PIN_INPUT);
Input = map(xdata, 0, 1024, 0, 255); //Change read scale to analog out scale

double gap = abs(Setpoint-Input); //distance away from setpoint
if (gap < 10)
{  //we're close to setpoint, use conservative tuning parameters
 myPID.SetTunings(consKp, consKi, consKd);
}
else
{
  //we're far from setpoint, use aggressive tuning parameters
  myPID.SetTunings(aggKp, aggKi, aggKd);
}

myPID.Compute();

Serial.print("Setpoint = ");
Serial.print(Setpoint);
Serial.print(" Input = ");
Serial.print(Input);
Serial.print(" Output = ");
Serial.print(Output);
Serial.print("\n");
// analogWrite(PIN_OUTPUT, Output);
}

OUTPUT:
Setpoint = 83.00 Input = 87.00 Output = 0.00
Setpoint = 83.00 Input = 81.00 Output = 0.00
Setpoint = 83.00 Input = 64.00 Output = 255.00
Setpoint = 83.00 Input = 64.00 Output = 255.00
Setpoint = 83.00 Input = 68.00 Output = 255.00
Setpoint = 83.00 Input = 79.00 Output = 0.00
Setpoint = 83.00 Input = 91.00 Output = 0.00
Setpoint = 83.00 Input = 96.00 Output = 0.00
Setpoint = 83.00 Input = 99.00 Output = 0.00
Setpoint = 83.00 Input = 88.00 Output = 0.00
Setpoint = 83.00 Input = 68.00 Output = 0.00
Setpoint = 83.00 Input = 58.00 Output = 255.00
Setpoint = 83.00 Input = 64.00 Output = 255.00
Setpoint = 83.00 Input = 78.00 Output = 255.00
Setpoint = 83.00 Input = 95.00 Output = 0.00
Setpoint = 83.00 Input = 97.00 Output = 0.00
Setpoint = 83.00 Input = 95.00 Output = 0.00

(1) I don't see the make, model and link to datasheet of your sensor in your question. (2) I don't see a schematic. (There's a button on the editor toolbar.) (3) You haven't posted any voltage readings on the analog input to confirm that the accelerometer is working properly.

You appear to be slamming to the alternate output limits.  To investigate this type of problem, generally try reducing the gain, look at how the default sample interval means the calculation may only be performed on some loop iterations, and make sure you don't have any "all or nothing" integer vs. floating point conversions.  You may want to move the PID code into your sketch and add debug output to it.

Is the cycle time between reporting/looping mostly the time it takes to print each ~50char line at 9600 baud?  Is the input changing due to  just you wiggling the accelerometer?  Why use the map() rather than use the measurements and setpoints directly?  If you want to think in terms of '336' being level, you should use it drectle and scale your pid parameters to translate units of error into units of output.

Ensure that your period for the PID execution routine is reasonable for your system.  I generally like to execute my PID loops at 5 to 20 times the system impulse response.  For instance, with a motor, I will apply 100% power from a standstill and measure the time it takes to get up to 90% of final value.  I will then multiply that time by 0.1 and start there.  If it takes 1s, then I will start my PID loop executing every 0.1s.  Sometimes I adjust this up or down, depending on system requirements, but this is not a bad starting point.
If your PID loop is executing too fast, then it will respond too quickly to actually have a real-world effect on the system.  The output will tend to oscillate.  Motors vibrate and make more noise.... different systems respond differently, but you see the point.

Start at kp = 0,ki = 0, kd = 0
Increase kp until you get a reasonable response.  Don't expect your error to go to 0.  As long as you aren't oscillating, that should be good.
Very slowly increase kiuntil you are happy.
You should probably keep kd to 0.  It is for advanced usage and PI loops will meet the vast majority of application requirements.

This is a very crude guide.  There are better on google, but this should get you started.  PID loops are fun, especially with motors.  Enjoy!

If you find and study the code of the PID implementation (which should have been in or linked from the question) it already has a sense of sample interval, and simply does nothing if called before the next interval has elapsed.  So your first suggestion is basically already implemented, though the period may need consideration, and may be interacting oddly with the serial output.

Thanks for the catch, I am not familiar with the Arduino-flavor PID loop.  I'll edit the answer.