text:
Using PROGMEM to save RAM
I am successful putting and retrieving a char array into Arduino flash memory using PROGMEM char arrays.
I am building my application using header files with a class definition / implementation and would like to keep the strings in the same header file.
If I define another PROGMEM char array neither one can be executed. In other words, these PROGMEM are global arrays as far as the Arduino compiler is concerned. They compile, but they won't show up.
Here is my test code:
  lcd.clear();
  lcd.print(*strFlashDebug[0]);  // in CDebug
  lcd.setCursor(0,1);
  lcd.print(*strFlashTrack[0]);  // in CTrack

If I put both definitions in the same header file, it only works with only one lcd.print enabled, not commented out.
It appears that multiple PROGMEM arrays can be defined and compiled, but only one is actually usable. What is the explanation?

Please post your array definitions as well, or better even, a complete compilable example with just enough code to illustrate the issue.

The important thing to know for PROGMEM is that the AVR chip you’re using does not have a single flat address space. I.e., it does not use a von Neumann architecture; instead, it uses a specific version of what is known as a Harvard architecture: it has separate address spaces for RAM, program memory, and EEPROM. All of them start at 0. Which means that while dereferencing a null pointer is technically still undefined behavior in C++, it can be (and often is) perfectly valid in Arduino code.
The short version is: If you have a PROGMEM pointer, whatever function you pass it to must work on PROGMEM pointers. lcd.print does not, and as far as I can tell there isn't any way the function could possibly detect this is not a RAM pointer. You have to call a different function, assuming there is one in the first place.
See PROGMEM (Arduino reference) for examples on how to use PROGMEM data.

To add to this excellent description, you could, as a workaround, temporarily copy to RAM the PROGMEM data you need to pass to lcd.print() and pass it this copy. A wrapper function, say lcd_print_PMEM() could encapsulate the details, and the RAM used would literally only be allocated for the duration of that call.

A PROGMEM variable definition (i.e., declaration) allocates memory in FLASH. You need use an extern clause in the header file and a physical declaration in the C code which is linked in your code. It's pays also for potential static class properties.
Also check if lcd.print() accepts a PROGMEM array, i.e., if the overloaded procedure is defined and called.
Just note I recommend using much more effective string formatting via file streams (FILE) and fprintf_P().


text:
Pulse measurement
I am currently doing the project in pulse measurement using an Arduino Yún. I am using the pulse sensor SEN-11574.
When I verify the code I get this error:
Arduino: 1.5.8 (Linux), Board: "Arduino Yún"

pulse-sensor-arduino/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduino/pulse-sensor-arduino.cpp:39: multiple definition of `pulsePin'
sketch_feb10a.cpp.o:/home/system1/Downloads/arduino-1.5.8/sketch_feb10a.ino:18: first defined here
pulse-sensor-arduino/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduino/pulse-sensor-arduino.cpp:39: multiple definition of `Pulse'
sketch_feb10a.cpp.o:/home/system1/Downloads/arduino-1.5.8/sketch_feb10a.ino:18: first defined here
collect2: error: ld returned 1 exit status
Error compiling.

This is my code:
#include <pulse-sensor-arduino.h>

int pulsePin = 0;
int blinkPin = 13;
int fadePin = 5;
int fadeRate = 0;

volatile int BPM;
volatile int Signal;
volatile int IBI = 600;
volatile boolean Pulse = false;
volatile boolean QS = false;

void setup() {

    pinMode(blinkPin, OUTPUT);
    pinMode(fadePin, OUTPUT);
    Serial.begin(115200);
}

void loop() {

    sendDataToProcessing('S', Signal);
    if (QS == true) {
        fadeRate = 255;
        sendDataToProcessing('B',BPM);
        sendDataToProcessing('Q',IBI);
        QS = false;
    }

    ledFadeToBeat();

    delay(5000);
}

void ledFadeToBeat() {
    fadeRate -= 15;
    fadeRate = constrain(fadeRate,0,255);
    analogWrite(fadePin,fadeRate);
}

void sendDataToProcessing(char symbol, int data ) {
    Serial.print(symbol);
    Serial.println(data);
}

This is my pulse Arduino cpp file:
#include "pulse-sensor-arduino.h"

volatile int rate[10];                        // Array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;     // Used to determine pulse timing
volatile unsigned long lastBeatTime = 0;      // Used to find IBI
volatile int P =512;                          // Used to find peak in pulse wave, seeded
volatile int T = 512;                         // Used to find trough in pulse wave, seeded
volatile int thresh = 512;                    // Used to find instant moment of heart beat, seeded
volatile int amp = 100;                       // Used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;            // Used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;          // Used to seed rate array so we startup with reasonable BPM
volatile boolean Pulse = false;               // True when pulse wave is high, false when it's low
volatile int pulsePin;

volatile int PulseSensor::IBI = 600;          // Holds the time between beats, must be seeded!
volatile int PulseSensor::BPM;                // Used to hold the pulse rate
volatile int PulseSensor::Signal;             // Holds the incoming raw data
volatile boolean PulseSensor::QS = false;     // Becomes true when Arduino finds a beat

void PulseSensor::begin(int pPin)
{
  pinMode(pulsePin, INPUT);
  pulsePin = pPin;

  // Initializes Timer1 to throw an interrupt every 2 ms.
  TCCR1A = 0x00;
  TCCR1B = 0x0C;  // CTC (Compare match mode) and ClockIO/256
  OCR1A = 0x7C;   // 2 ms
  TIMSK1 = 0x02;
  sei();          // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

// THIS IS THE TIMER 1 INTERRUPT SERVICE ROUTINE.
// Timer 1 makes sure that we take a reading every 2 miliseconds
ISR(TIMER1_COMPA_vect)
{                         // Triggered when Timer1 counts to 124
  cli();                                      // Disable interrupts while we do this
  PulseSensor::Signal = analogRead(pulsePin); // Read the Pulse Sensor
  sampleCounter += 2;                         // Keep track of the time in ms with this variable
  int N = sampleCounter - lastBeatTime;       // Monitor the time since the last beat to avoid noise

  // Find the peak and trough of the pulse wave
  if(PulseSensor::Signal < thresh && N > (PulseSensor::IBI/5)*3){       // Avoid dichrotic noise by waiting 3/5 of last IBI
    if (PulseSensor::Signal < T){                        // T is the trough
      T = PulseSensor::Signal;                         // Keep track of lowest point in pulse wave
    }
  }

  if(PulseSensor::Signal > thresh && PulseSensor::Signal > P){          // Threshold condition helps avoid noise
    P = PulseSensor::Signal;                             // P is the peak
  }                                        // Keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  //
  // The signal surges up in value every time there is a pulse
  if (N > 250){                                   // Avoid high-frequency noise
    if ( (PulseSensor::Signal > thresh) && (Pulse == false) && (N > (PulseSensor::IBI/5)*3) )
    {
      Pulse = true;                               // Set the Pulse flag when we think there is a pulse
      PulseSensor::IBI = sampleCounter - lastBeatTime;         // Measure time between beats in mS
      lastBeatTime = sampleCounter;               // Keep track of time for next pulse

      if(secondBeat){                        // If this is the second beat, if secondBeat == TRUE
        secondBeat = false;                  // Clear secondBeat flag
        for(int i=0; i<=9; i++){             // Seed the running total to get a realisitic BPM at startup
          rate[i] = PulseSensor::IBI;
        }
      }

      if(firstBeat){                         // If it's the first time we found a beat, if firstBeat == TRUE
        firstBeat = false;                   // Clear firstBeat flag
        secondBeat = true;                   // Set the second beat flag
        sei();                               // Enable interrupts again
        return;                              // IBI value is unreliable so discard it
      }

      // Keep a running total of the last 10 IBI values
      word runningTotal = 0;                  // Clear the runningTotal variable

      for(int i=0; i<=8; i++){                // Shift data in the rate array
        rate[i] = rate[i+1];                  // And drop the oldest IBI value
        runningTotal += rate[i];              // Add up the 9 oldest IBI values
      }

      rate[9] = PulseSensor::IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // Add the latest IBI to runningTotal
      runningTotal /= 10;                     // Average the last 10 IBI values
      PulseSensor::BPM = 60000/runningTotal;               // How many beats can fit into a minute? that's BPM!
      PulseSensor::QS = true;                              // Set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (PulseSensor::Signal < thresh && Pulse == true){   // When the values are going down, the beat is over
    Pulse = false;                         // Reset the Pulse flag so we can do it again
    amp = P - T;                           // Get amplitude of the pulse wave
    thresh = amp/2 + T;                    // Set thresh at 50% of the amplitude
    P = thresh;                            // Reset these for next time
    T = thresh;
  }

  if (N > 2500){                           // If 2.5 seconds go by without a beat
    thresh = 512;                          // Set thresh default
    P = 512;                               // Set P default
    T = 512;                               // Set T default
    lastBeatTime = sampleCounter;          // Bring the lastBeatTime up to date
    firstBeat = true;                      // Set these to avoid noise
    secondBeat = false;                    // When we get the heartbeat back
  }

  sei();                                   // Enable interrupts when youre done!
} // end ISR

This is my pulse Arduino header file:
#ifndef PULSE_SENSOR_ARDUINO_H
#define PULSE_SENSOR_ARDUINO_H

#include "Arduino.h"

class PulseSensor
{
public:
  static void begin(int pulsePin);

  static volatile int BPM;
  static volatile int Signal;
  static volatile int IBI;
  static volatile boolean QS;
};

#endif

I modified the program, but there is a new error present:
Arduino: 1.5.8 (Linux), Board: "Arduino Yún"

pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::begin(int)'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `pulsePin'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `__vector_17':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:54: multiple definition of `__vector_17'
pulsesensor.cpp.o:pulsesensor.cpp:54: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::Signal'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `sampleCounter'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `lastBeatTime'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.thresh+0x0): multiple definition of `thresh'
pulsesensor.cpp.o:(.data.thresh+0x0): first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data._ZN11PulseSensor3IBIE+0x0): multiple definition of `PulseSensor::IBI'
pulsesensor.cpp.o:(.data._ZN11PulseSensor3IBIE+0x0): first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.T+0x0): multiple definition of `T'
pulsesensor.cpp.o:(.data.T+0x0): first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.P+0x0): multiple definition of `P'
pulsesensor.cpp.o:(.data.P+0x0): first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `Pulse'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `rate'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::BPM'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::QS'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.firstBeat+0x0): multiple definition of `firstBeat'
pulsesensor.cpp.o:(.data.firstBeat+0x0): first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `secondBeat'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.amp+0x0): multiple definition of `amp'
pulsesensor.cpp.o:(.data.amp+0x0): first defined here
collect2: error: ld returned 1 exit status
Error compiling.

Here is my change code
#include <pulse-sensor-arduino.h>

int blinkPin = 13;                // Pin to blink LED at each beat
int fadePin = 5;                  // Pin to do fancy classy fading blink at each beat
int fadeRate = 0;                 // Used to fade LED on with PWM on fadePin

void setup(){
  pinMode(blinkPin,OUTPUT);         // Pin that will blink to your heartbeat!
  pinMode(fadePin,OUTPUT);          // Pin that will fade to your heartbeat!
  Serial.begin(115200);             // We agree to talk fast!

}

void loop(){
  sendDataToProcessing('P', PulseSensor::Signal);     // Send Processing the raw Pulse Sensor data
  if (PulseSensor::QS == true){                       // Quantified Self flag is true when arduino finds a heartbeat
    fadeRate = 255;                  // Set 'fadeRate' Variable to 255 to fade LED with pulse
    sendDataToProcessing('B',PulseSensor::BPM);   // Send heart rate with a 'B' prefix
    sendDataToProcessing('Q',PulseSensor::IBI);   // Send time between beats with a 'Q' prefix
    PulseSensor::QS = false;                      // Reset the Quantified Self flag for next time
  }

  ledFadeToBeat();

  delay(5000);                             //  Take a break
}

void ledFadeToBeat(){
  fadeRate -= 15;                         //  Set LED fade value
  fadeRate = constrain(fadeRate,0,255);   //  Keep LED fade value from going into negative numbers!
  analogWrite(fadePin,fadeRate);          //  Fade LED
}

void sendDataToProcessing(char symbol, int data ){
    Serial.print(symbol);                // Symbol prefix tells Processing what type of data is coming
    Serial.println(data);                // The data to send culminating in a carriage return
}

My cpp file:
#include "pulse-sensor-arduino.h"

volatile int rate[10];                        // Array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;     // Used to determine pulse timing
volatile unsigned long lastBeatTime = 0;      // Used to find IBI
volatile int P =512;                          // Used to find peak in pulse wave, seeded
volatile int T = 512;                         // Used to find trough in pulse wave, seeded
volatile int thresh = 512;                    // Used to find instant moment of heart beat, seeded
volatile int amp = 100;                       // Used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;            // Used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;          // Used to seed rate array so we startup with reasonable BPM
volatile boolean Pulse = false;               // True when pulse wave is high, false when it's low
volatile int pulsePin;

volatile int PulseSensor::IBI = 600;          // Holds the time between beats, must be seeded!
volatile int PulseSensor::BPM;                // Used to hold the pulse rate
volatile int PulseSensor::Signal;             // Holds the incoming raw data
volatile boolean PulseSensor::QS = false;     // Becomes true when Arduino finds a beat

void PulseSensor::begin(int pPin)
{
  pinMode(pulsePin, INPUT);
  pulsePin = pPin;

  // Initializes Timer1 to throw an interrupt every 2 ms.
  TCCR1A = 0x00;
  TCCR1B = 0x0C;  // CTC (Compare match mode) and ClockIO/256
  OCR1A = 0x7C;   // 2 ms
  TIMSK1 = 0x02;
  sei();          // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

// THIS IS THE TIMER 1 INTERRUPT SERVICE ROUTINE.
// Timer 1 makes sure that we take a reading every 2 miliseconds
ISR(TIMER1_COMPA_vect)
{                         // Triggered when Timer1 counts to 124
  cli();                                      // Disable interrupts while we do this
  PulseSensor::Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // Keep track of the time in ms with this variable
  int N = sampleCounter - lastBeatTime;       // Monitor the time since the last beat to avoid noise

  //  Find the peak and trough of the pulse wave
  if(PulseSensor::Signal < thresh && N > (PulseSensor::IBI/5)*3){       // Avoid dichrotic noise by waiting 3/5 of last IBI
    if (PulseSensor::Signal < T){                        // T is the trough
      T = PulseSensor::Signal;                         // Keep track of lowest point in pulse wave
    }
  }

  if(PulseSensor::Signal > thresh && PulseSensor::Signal > P){          // Threshold condition helps avoid noise
    P = PulseSensor::Signal;                             // P is the peak
  }                                        // Keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250){                                   // Avoid high frequency noise
    if ( (PulseSensor::Signal > thresh) && (Pulse == false) && (N > (PulseSensor::IBI/5)*3) )
    {
      Pulse = true;                               // Set the Pulse flag when we think there is a pulse
      PulseSensor::IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
      lastBeatTime = sampleCounter;               // Keep track of time for next pulse

      if(secondBeat){                        // If this is the second beat, if secondBeat == TRUE
        secondBeat = false;                  // Clear secondBeat flag
        for(int i=0; i<=9; i++){             // Seed the running total to get a realisitic BPM at startup
          rate[i] = PulseSensor::IBI;
        }
      }

      if(firstBeat){                         // If it's the first time we found a beat, if firstBeat == TRUE
        firstBeat = false;                   // Clear firstBeat flag
        secondBeat = true;                   // Set the second beat flag
        sei();                               // Enable interrupts again
        return;                              // IBI value is unreliable so discard it
      }

      // Keep a running total of the last 10 IBI values
      word runningTotal = 0;                  // Clear the runningTotal variable

      for(int i=0; i<=8; i++){                // Shift data in the rate array
        rate[i] = rate[i+1];                  // And drop the oldest IBI value
        runningTotal += rate[i];              // Add up the 9 oldest IBI values
      }

      rate[9] = PulseSensor::IBI;                          // Add the latest IBI to the rate array
      runningTotal += rate[9];                // Add the latest IBI to runningTotal
      runningTotal /= 10;                     // Average the last 10 IBI values
      PulseSensor::BPM = 60000/runningTotal;               // How many beats can fit into a minute? that's BPM!
      PulseSensor::QS = true;                              // Set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (PulseSensor::Signal < thresh && Pulse == true){   // When the values are going down, the beat is over
    Pulse = false;                         // Reset the Pulse flag so we can do it again
    amp = P - T;                           // Get amplitude of the pulse wave
    thresh = amp/2 + T;                    // Set thresh at 50% of the amplitude
    P = thresh;                            // Reset these for next time
    T = thresh;
  }

  if (N > 2500){                           // If 2.5 seconds go by without a beat
    thresh = 512;                          // Set thresh default
    P = 512;                               // Set P default
    T = 512;                               // Set T default
    lastBeatTime = sampleCounter;          // Bring the lastBeatTime up to date
    firstBeat = true;                      // Set these to avoid noise
    secondBeat = false;                    // When we get the heartbeat back
  }

  sei();                                   // Enable interrupts when youre done!
} // end ISR

(1)The declaration
 volatile boolean Pulse = false;

occurs in two locations.
Is that intended?
(2) Also
volatile int PulseSensor::BPM;                // used to hold the pulse rate
volatile int PulseSensor::IBI = 600;          // holds the time between beats, must be seeded!
volatile int PulseSensor::Signal;             // holds the incoming raw data

pulsePin is declared twice too.

source: Stack Exchange

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

sort: votes


text:
Press the Windows key using "keyboard.press();"
Is it possible to allow an Arduino Leonardo to simulate pressing the Windows key using the keyboard.press(......); command?
If so, what is the required value?

Add a delay(20) after the keyoress

if i want to press numbers key which value I need to enter in program??
Like I want to press Control Key + number Key 1... Keyboard.press(KEY_LEFT_GUI); Keyboard.press('which value I need to enter for key 1?'); Keyboard.releaseAll();

They Keyboard.press() command accept modifiers per the documentation. You may need to do multiple press() commands before releasing.
For example, if you want to launch File Explorer you could use:
Keyboard.press(KEY_LEFT_GUI);
Keyboard.press('e');
Keyboard.releaseAll();

This is equivalent to shortcut keys Win + E.
The modifier GUI is what stands in for the "command key" which is the Windows Logo on a PC or clover (⌘) on a Mac.
I don't have any restriction on the higher value on my board (Pro Micro), as indicated by @frarugi87.

Looking at the list of the HID keyboard codes (page 53), the keys you are looking for have a code of E3 (Keyboard Left GUI) or E7 (Keyboard Right GUI).
Unluckily the Keyboard::press function (you can see it here) does not accept a so high value, since you can only input numbers between 0 and 255 and, in order to send a raw value, you have to send its value plus 136 (which leads to values 363 and 367).
However, looking at the header file, there are two predefined keys called KEY_LEFT_GUI and KEY_RIGHT_GUI. Maybe these modifier keys behave in exactly the same way.
So my suggestion is to

try using one of those values (i.e. keyboard.press(KEY_LEFT_GUI); or keyboard.press(KEY_RIGHT_GUI);, or use the keyboard.write(KEY_LEFT_GUI); to simulate a press on the key instead of you keeping it pressed).
If this does not work, create your own library copying the keyboard.cpp and keyboard.h files, calling the class differently and adding the possibility to send the E3 and/or the E7 keys. In this case, you will just need to modify the press function.

Good luck

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

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


text:
What is the Arduino Uno default sketch?
When I bought my Arduino Uno and connected it to my computer, I tried to make the simple blink circuit (before programming the Arduino) and suddenly the LED started blinking. Is the blink example the default Arduino sketch?
I am sure that I didn't uploaded anything to the board.

Some may have the "Blink" sketch pre-installed, but many don't. However, when there is no sketch installed the board sits in bootloader mode waiting for you to upload a sketch.  While it's in bootloader mode the LED pin pin D13 blinks.
If your LED is blinking about once a second then it's the Blink sketch.  If it's rapidly blinking three or four times per second or so then it's in the bootloader and you have no sketch loaded.

For me it was blinking 1 time at a second. By the way, what makes the bootloader blink the pin 13 if there is no sketch loaded, is it a normal sketch ?, and why that don't happen when I upload the "BareMinimum" example ?.

@AsadMarmash The bootloader is just software. It runs before the sketch runs if there is a sketch installed. If there isn't it just runs and runs and runs. It blinks the LED because it blinks the LED. That is what the programmer that wrote the bootloader decided to program it to do. It doesn't blink with BareMinimum because BareMinimum doesn't blink the LED, and it is a sketch, so the bootloader runs it.

See my answer about the bootloader. The bootloader only flashes the LED 3 times. If it keeps flashing then the supplier must have uploaded the Blink sketch as a default.

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


text:
Power consumption issue. I made project using atmel-328p
I made project using atmel-328p. I want to run it over a year. I am using power_down mode & 5500 mAh li-ion battery still battery discharges in 1 day. I am using standard code as explain on arduino site.
code is:
String uniqueid;
char value;
volatile int NbTopsFan; //measuring the rising edges of the signal
uint32_t Calc;
int hallsensor = 2;    //The pin location of the sensor
int power = 4;
// ph sensor
define SensorPin 0          //pH meter Analog output to Arduino Analog Input 0
define Offset 0.00            //deviation compensate
unsigned long int avgValue;    //Store the average value of the sensor feedback
// temp sensor
OneWire  ds(8);
byte i;
byte present = 0;
byte data[12];
byte addr[8];
int HighByte, LowByte, SignBit, Whole, Fract, TReading, Tc_100, FWhole;

int wakePin = 3;                 // pin used for waking up
int sleepStatus = 0;             // variable to store a request for sleep
int countsleep = 0;                   // counter

void wakeUpNow()        // here the interrupt is handled after wakeup
{// execute code here after wake-up before returning to the loop() function
 }
void rpm ()     //This is the function that the interupt calls
{
 NbTopsFan++;  //This function measures the rising and falling edge of the
//hall effect sensors signal
}
void setup()
{
 pinMode(hallsensor, INPUT); //initializes digital pin 2 as an input
Serial.begin(9600); //This is the setup function where the serial port is
pinMode(power, OUTPUT);
//initialised,
 attachInterrupt(0, rpm, RISING); //and the interrupt is attached
//initialised,
  //and the interrupt is attached
// temp sensor pin 8
        if ( !ds.search(addr))
        {
           //       Serial.println("temp sensor is not connected");
        delay(1000);
        ds.reset_search();
        return;
        }
        if ( OneWire::crc8( addr, 7) != addr[7])
        {
       //      Serial.println("CRC not valid!");
       delay(1000);
       return;
        }
pinMode(wakePin, INPUT);

  attachInterrupt(1, wakeUpNow, LOW); // use interrupt 1 (pin 3) and run function

}

void sleepNow()         // here we put the arduino to sleep
{
  countsleep = 0;
ADCSRA = 0;

   set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    sleep_enable();          // enables the sleep bit in the mcucr register
                             // so sleep is possible. just a safety pin
  // turn off brown-out enable in software
  MCUCR = bit (BODS) | bit (BODSE);  // turn on brown-out enable select
  MCUCR = bit (BODS);        // this must be done within 4 clock cycles of above

 sleep_cpu ();

    attachInterrupt(1,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                                       // wakeUpNow when pin 2 gets LOW

    sleep_mode();            // here the device is actually put to sleep!!
                             // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

    sleep_disable();         // first thing after waking from sleep:
                             // disable sleep...
    detachInterrupt(1);      // disables interrupt 0 on pin 2 so the
                             // wakeUpNow code will not be executed
}

void loop()
{

  countsleep++;
  delay(1000);                           // waits for a second
// compute the serial input
  if (Serial.available())
  {
    String content = "";
    char character;
// to read serial data coming
        while(Serial.available()>0)
          {
              character = Serial.read();
              content.concat(character);
          }
      String uniqueidread = content.substring(0,16);
      String parameter = content.substring(16,17);
      String checkuuid = content.substring(0,3);
      String putinsleep = content.substring(0,5);
       if (uniqueidread == uniqueid && parameter == "5")
{         //    Serial.flush();
digitalWrite(power,HIGH);
 NbTopsFan = 0;      //Set NbTops to 0 ready for calculations
 sei();            //Enables interrupts
 delay (1000);      //Wait 1 second
 cli();            //Disable interrupts
 Calc = (NbTopsFan * 60 / 7.5); //(Pulse frequency x 60) / 7.5Q, = flow rate

  digitalWrite(power,LOW);
          getTemp();
          delay(1000);
          getTemp();
          //   printTemp();
      Serial.print("Temp is: ");
           if (SignBit)
           {
                Serial.print(" - ");
           }
           if( Whole == 0)
           {
              Serial.print("temp sensor is not connected");
           }
           else
           {
              Serial.print(Whole);
              Serial.print(" C / ");
              Serial.print(FWhole);
              Serial.print(" F");
            }
              Serial.print(", Current Reading = ");
     Serial.print (Calc, DEC); //Prints the number calculated above
            Serial.print(" L/hour");
   phvalue();
            Serial.println("S=m");
              delay(100);
              sleepNow();
}

         if ( content == "sleep")
         {
          Serial.println("S=m");
          delay(100);     // this delay is needed, the sleep
          sleepNow();     // sleep function called here
         }
}

  if (countsleep >= 10)
  {
      Serial.println("T=m");
      delay(100);     // this delay is needed, the sleep
                      //function will provoke a Serial error otherwise!!
      sleepNow();     // sleep function called here
  }
}
      void getTemp()
          {
              int foo, bar;

              ds.reset();
              ds.select(addr);
              ds.write(0x44,1);

              present = ds.reset();
              ds.select(addr);
              ds.write(0xBE);

              for ( i = 0; i < 9; i++) {
                data[i] = ds.read();
              }

              LowByte = data[0];
              HighByte = data[1];
              TReading = (HighByte << 8) + LowByte;
              SignBit = TReading & 0x8000;  // test most sig bit

              if (SignBit) {
                TReading = -TReading;
              }
              Tc_100 = (6 * TReading) + TReading / 4;    // multiply by (100 * 0.0625) or 6.25
              Whole = Tc_100 / 100;          // separate off the whole and fractional portions
              Fract = Tc_100 % 100;
              if (Fract > 49) {
                if (SignBit) {
                  --Whole;
                } else {
                  ++Whole;
                }
              }

              if (SignBit) {
                bar = -1;
              } else {
                bar = 1;
              }
              foo = ((Whole * bar) * 18);      // celsius to fahrenheit conversion section
              FWhole = (((Whole * bar) * 18) / 10) + 32;
              if ((foo % 10) > 4) {            // round up if needed
                   ++FWhole;
              }
            }
void printTemp(void)
{
         Serial.println("");
         Serial.print("Temp is: ");
         if (SignBit)
         {
              Serial.print(" - ");
         }
         Serial.print(Whole);
         Serial.print(" C / ");
         Serial.print(FWhole);
         Serial.print(" F");
}
void phvalue()
{
    int buf[10];                //buffer for read analog
    for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
    {
      buf[i]=analogRead(SensorPin);
      delay(10);
    }
    for(int i=0;i<9;i++)        //sort the analog from small to large
    {
      for(int j=i+1;j<10;j++)
      {
        if(buf[i]>buf[j])
        {
          int temp=buf[i];
          buf[i]=buf[j];
          buf[j]=temp;
        }
      }
    }
    avgValue=0;
    for(int i=2;i<8;i++)                      //take the average value of 6 center sample
      avgValue+=buf[i];
    float phValue=(float)avgValue*5.0/1024/6; //convert the analog into millivolt
    phValue=3.5*phValue+Offset;                      //convert the millivolt into pH value
    Serial.print(" pH:");
    Serial.print(phValue,2);
    Serial.print(" ");
}

Welcome to Arduino SE! Can you please elaborate - what your code does, what is the hardware involved, and even post your full code so we could help you

My hardware involve atmel-328p, xbee, temp sensor, water flow sensor & pH sensor. I used xbee to wake up atmel-328p using interrupt. When data receive on serial port of atmel using xbee interrupt break the sleep mode. My code is as follows:

I would suggest editing your question and adding that information, which is crucial for answering your question.

What else info should I provide to you?

We will need schematics of your circuit (preferably not a board wiring made with Frietzing - unless your setup is dead simple) and the relevant parts of your code. Please edit your question to add that information. Thanks!

The schematic should tell us all we want to know, but do you, by any chance, use an Arduino board, such as the Uno? What do you use as voltage regulator? Not a LM7805, I hope. If you do, that's all your mAh are being wasted.

This excellent answer by Anindo Ghosh will tell you more about how to really save energy in your '328 MCU projects.

I am not using voltage regulator. I am connecting 3.7 v li-ion battery directly to +5v & gnd of schematics.

Try doing some measurements. Remove some components and see which one uses what amount of power. Try removing all components to see if your sleep code works (which it maybe doesn't do correctly, as you're calling  sleepmode twice (sleep_cpu and sleep_mode)). PS I'd disable the brownout detection in the fuses. Disabling it using code is very difficult to do right, and the lithium cells protection will kick in way before the brownout detection, so there is no use for it in your case.

What clock frequency are you using? 16MHz? If so, you're running it pretty close to it's minimum voltage for that frequency. Not sure if it is an issue, but maybe your MCU is resetting or running erratically. Anyway, that's probably something to look out for.

I am using 8MHz clock frequency. Internal clock.

Use the divider to reduce your clock further.  Verify you are actually sleepibg.  Make sure none of your resistors or internal pullups have a voltage difference across them, otherwise they are little micro-heaters draining your battery.  Watch out for power lost to (or donated by!) communication/debug interfaces.

You need to first check the individual current consumption of all elements:

pH sensor,
temp sensor,
water flow sensor
xbee.

Since many of these just have an output pin in addition to +V & GND, this means those have a permanent current consumption that, overall, may possibly drain your battery.
You should then check the datasheets for all these components and see the minimum current consumption (and conditions for this consumption to be achieved).
If the total minimum current for these components is too high for your system, then you can possibly:

use an available ATmel digital output pin to power them (and unpower them just before switching the ATmel to low power mode); that's possible only if you stay within current limitations of the MCU (there are current limitation per pin, 20mA IIRC, and total current for the whole MCU)
if current consumption is above ATmel limits then you can still use the method above but add a MOSFET in-between so that you limit ATmel current consumption

I strongly advise you this link from Nick Gammon, which is comprehensive and complete.

Just found out I added this as an answer although I wanted it as a comment (issue of using smartphone with SE...) Sorry for that. I'll try to find time to edit the answer and add some more details then.

OK, Thanks a lot, Now I am trying to measure individual current consumption of all elements, n will update soon. Looking forward for your help and suggestions.

Still battery drains in 24 hours, Now I power only standalone Atmel-328 with 3.7 li-ion cell having 5500 mAh capacity.

I think you should proceed step by step; your current circuit and code are too complex to start with. Simplify them first then perform some checks. In particular, verify that you spend the expected time in power down mode.

Yes, sensor & xbee is draining my battery. I can override with sensor providing power through atmel digital pins. But how can i override xbee power loss because I am using as a external interrupt in my circuit to wake up IC.

For xbee check if there is a low power mode (just like for the atmel); if it exists, check how it can help.


text:
LCD Backlight doesn’t work even at 5V. Using 330 Ohm resistor
I’ve been trying to make this project: https://create.arduino.cc/projecthub/chummer1010/electronic-safe-with-arduino-25d039
I’m confident that I’ve assembled everything correctly, but my LCD doesn’t display characters. Other projects seem to have fixed it by changing the potentiometer but I’m not using one.
Arduino code:
/*
Made by Marco Fusco
May 20, 2016
Contact me at: marcofusco111@gmail.com
*/

#include <LiquidCrystal.h>
#include <EEPROM.h>
#include <Servo.h>

int address = 0;
static unsigned long SaveTimer;
static unsigned long SaveDelay = (30 * 1000);

char CODE[10] = "1234E";
char Str[10];
char CodeLength = 4;
int Pos = 0;
bool Unlocked;
static unsigned long DisplayTimer;
static unsigned long DisplayDelay = 200;

LiquidCrystal lcd(12, 11, 9, 8, 7, 6);

int buttonPin1 = 2;
int buttonPin2 = 3;
int buttonPin3 = 4;
int buttonPin4 = 5;

int enterbutton = 10;
int clearlockbutton = 13;

Servo myServo;

void setup() {

  myServo.attach(A1);

  int EEPROMCodeOK = true;
  for (Pos = 0; Pos <= (CodeLength); Pos++) {
    Str[Pos] =  EEPROM.read(Pos);
    if (!(strrchr("1123456789", Str[Pos]))) {
      // not a valid code
      EEPROMCodeOK = false;
    }
  }
  Pos++;
  Str[Pos] =  EEPROM.read(Pos);
  if (Str[CodeLength + 1] != 'E') EEPROMCodeOK = false;
  if (EEPROMCodeOK) {
    Str[CodeLength + 2] = '\0';
    strncpy(CODE, Str, CodeLength + 1);
  }
  ClearCode();

  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  pinMode(buttonPin3, INPUT_PULLUP);
  pinMode(buttonPin4, INPUT_PULLUP);

  pinMode(enterbutton, INPUT_PULLUP);
  pinMode(clearlockbutton, INPUT_PULLUP);

  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Hello.");
  delay(2000);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Password:");

  DisplayTimer = millis() + 200;
}

void loop() {

  Lock();

  Pos = constrain(Pos, 0, CodeLength);

  int buttonState1 = digitalRead(buttonPin1);
  int buttonState2 = digitalRead(buttonPin2);
  int buttonState3 = digitalRead(buttonPin3);
  int buttonState4 = digitalRead(buttonPin4);

  int clButtonState = digitalRead(clearlockbutton);
  int enterButtonState = digitalRead(enterbutton);

  lcd.setCursor(9, 0);

  if (buttonState1 == LOW) {
    Str[Pos] = '1';
    Pos++;
    Str[Pos] = '\0';
    delay(250);
    while (digitalRead(buttonPin1) == LOW);

  }

  else if (buttonState2 == LOW) {
    Str[Pos] = '2';
    Pos++;
    Str[Pos] = '\0';
    delay(250);
    while (digitalRead(buttonPin2) == LOW);

  }

  else if (buttonState3 == LOW) {
    Str[Pos] = '3';
    Pos++;
    Str[Pos] = '\0';
    delay(250);
    while (digitalRead(buttonPin3) == LOW);
  }

  else if (buttonState4 == LOW) {
    Str[Pos] = '4';
    Pos++;
    Str[Pos] = '\0';
    delay(250);
    while (digitalRead(buttonPin4) == LOW);

  }
  else if (enterButtonState == LOW) {
    Str[Pos] = 'E';
    Pos++;
    Str[Pos] = '\0';
    delay(250);
    while (digitalRead(buttonPin1) == LOW);
     if (strcmp (Str,CODE) == 0) {
      Unlocked = true;
      lcd.setCursor(0, 0);
      lcd.print(" Access Granted");
      delay(2000);
      lcd.clear();
      lcd.print("    Unlocked");
    }
    else if (SaveTimer > millis() && (Pos + 1) == CodeLength) {

      strcpy(CODE, Str);
      for (Pos = 0; Pos <= (CodeLength + 1); Pos++) {
        EEPROM.write(Pos, Str[Pos]);
      }
      lcd.setCursor(0, 0);
      lcd.print("Saving Code:");
      lcd.setCursor(0, 1);
      lcd.print(Str);

      Unlocked = true;
    }

    else {

      lcd.clear();
      lcd.print(" Access Denied.");
      delay(2000);
      lcd.clear();
      lcd.print("Password:");

    }

    while (Unlocked) {
      Unlock();
      if (digitalRead(clearlockbutton) == LOW) {
        delay(200);
        lcd.clear();
        lcd.print("     Locked");
        delay(2000);
        lcd.clear();
        Unlocked = false;
        SaveTimer = millis() + 30000;
      }
    }

    ClearCode();

  }

  else if (clButtonState == LOW) {
    delay(500);

    while (clearlockbutton == LOW);
    if ((millis() - SaveTimer) > 4500) {

    }

    ClearCode();

  }

  if ( (long)( millis() - DisplayTimer ) >= 0) {
    DisplayTimer += DisplayDelay;
    lcd.setCursor(9, 0);
    lcd.print(Str);
    lcd.print("     ");

  }
}

void ClearCode() {

  Pos = 0;
  Str[Pos] = '\0';
  lcd.setCursor(0, 0);
  lcd.print("Password:");
  lcd.setCursor(0, 1);
  lcd.print("          ");

}

void Unlock() {

  myServo.write(150);

}

void Lock() {

  myServo.write(50);

}

but I’m not using one; why don't your? You can't just leave out parts of a circuit and expect it to still work. If you don't have any potentiometers, you test out combinations of two resistors, till the contrast is good. Lastly the question in the title has nothing to do with the question in the rest of the text.

Please add a foto of the display. Most likely you have problem with a contrast. Schematic at the link you've provided is very strange: pin 3, which is responsible for the contrast, is tied directly to GND, which sets the display to the minimum contrast. You should use either a potentiometer, or a voltage divider for this pin.

The 1602 displays I used so far worked well with either a 2k or a 5k resistor between the contrast pin and GND, depending on the model.

That's very strange for me, frankly speaking. All I've seen need some voltage on this pin, and it can't obviously be set by any single resistor. I2C adapters also have a small potentiomenter built on the PCB

That's what I had thought as well. I'm using both as regular 4-bit parallel displays. The 2k one is included in the "Elegoo Uno R3 Ultimate Starter Kit". The 5k ones are "GE-C1602B-TMI-JT/R" from "Gleichmann", which I used for work projects.

@towe for the chinese one from the starter kit there's no datasheet of course, but for the second I've found one: http://www.produktinfo.conrad.com/datenblaetter/175000-199999/183045-da-01-en-LCD_MODUL_16X2_LED_GE_C1602B_TMI_JT_R.pdf. It clearly states on a page 5, that you should use a pot in 10-20k range with the output on pin VO. On the bottom of the page there's a electrical scheme for that. Table states that at room temperature typical VO voltage is 3.7V.

With the 5.1k Ohm resistor to ground and a 5V Vcc, I get 1.08 V on VO and perfect contrast.

@towe first, this is contradictory to what is stated in the datasheet, and so is very strange. Second, I still don't get it. In order to get 1.08V out of 5.0V you need a couple of resistors. If one of them is 5.1k, then another one should be about 18.5k. please show your actual setup

I'm well aware of that. I just used what worked reliably. Custom PCB (so I was happy not to waste space for a pot), GND on GND, 5V as Vcc (either from an Uno over USB, or a Recom R-785.0-0.5), and a resistor of 5.1 kOhm from VO to GND.
The backlight is powered by either a 3.3V regulator directly (first version) or through a 100 Ohm resistor from 5V.

Start with the Liquid Crystal, HelloWorld, Example.   Find out if it's your pin configuration or pot/no pot issue, or if you have a doofed LCD.
Some LCD 1602 have an on board pot, so make sure that's not there too.
Process of elimination.


text:
LCD isn't working with if statement
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#define trigpinyellow 10
#define echopingreen 9
#define Grove_Water_Sensor 8
void setup()
{
    Serial.begin(9600);
    pinMode(trigpinyellow,OUTPUT);
    pinMode(echopingreen,INPUT);
    pinMode(Grove_Water_Sensor, INPUT);
    lcd.begin(16, 2);
}

void loop()
{
    long duration,distance;
    digitalWrite(trigpinyellow,LOW);
    delayMicroseconds(1000);
    digitalWrite(trigpinyellow,HIGH);
    delayMicroseconds(1000);
    digitalWrite(trigpinyellow,LOW);
    duration=pulseIn(echopingreen,HIGH);
    distance = (duration/2) / 29.1;
    Serial.println(distance);

    if( digitalRead(Grove_Water_Sensor) == LOW && digitalRead(distance) >=20  )
    {
        lcd.clear();
        lcd.print("water_came");
        lcd.setCursor(0, 1);
    }
    if( digitalRead(Grove_Water_Sensor) == LOW && digitalRead(distance) <=8 )
    {
        lcd.clear();
        lcd.write("Tank_is_full");
    }
    if( digitalRead(Grove_Water_Sensor) == HIGH && digitalRead(distance) >=20 )
    {
        lcd.clear();
        lcd.print("Fill The Tank PLEASE");
    }
    if( digitalRead(Grove_Water_Sensor) == HIGH && digitalRead(distance) <=8 )
    {
        lcd.clear();
        lcd.print("Tank_is_FULL");
    }
}

You might want to change digitalRead(distance) >=20 to just distance >=20

Your collection of if statements has holes which could result in no output to the lcd. For example, if Grove_Water_Sensor is LOW and distance is 10 would result in no output.

I will try it Gerben, 6v6gt and thanks for the advice

But why it will not show any output

Voted down. Please add more content, what is not working?

@Omar: you read some distance to variable distance. So this variable now contain some more/less random long number. Then you call digitalRead(distance) where you read pin with this number - so you read some random (maybe even non-existent) pin. With digitalRead you read digital, so result is else HIGH or LOW (which are 1 or 0). And then you compare valoue of 1 or 0 (obtained from random pin) with values like 8 or 20. Do you see, why it does not work this way?

Okay my problem is that When it is<=8 it gives tank is full but when it becomes >=20 after the lcd remains tank is full so the lcd display isn't changing at all so please help me

@Omar - the "answer" area is not for clarifying your question or replying to comments. This is not a forum. If you are asked a question in a comment, make a comment to reply. If you need to clarify your question edit the question.

Every time you instantiate digitalread(), you poll the pin. Here, you're polling pins 8 times every loop. Instead, poll the two pins at the start of the loop to update the variable, and then do your math and make your decisions afterward. Right now you're doing math with your distance variable, and then overwriting the variable during your if conditionals. Not sure if that's what you intend. You're also creating the variables duration and distance every single loop. instead, create those variables globally and just update them every loop.


text:
compare two hex files
I need to check if the code burned on the some Arduino is the same one as I have.
I know how to get the hex file from the Arduino. My question is what influence the hex code? Board Type? Microprocessor type? avrdude version? anything else?

The lines in a typical hex file include a VLI (variable length indicator). The hex files output from the IDE might have different lengths than those produced by avrdude. As a simple example:
File 1:
03ABC
03DEF

File 2:
06ABCDEF

Those files will compare differently to each other but convey the same information, split differently between lines.
To do a genuine comparison you would need to account for that.

Board Type?

Different boards, but with the same processor, might have identical files.

Microprocessor type?

Different processor would almost certainly have different hex files.

avrdude version?

Probably not, however see my comments above about the VLIs.

anything else?

As I said, the compiler may generate lines with (say) 16 bytes per line, but avrdude might read back lines with 32 bytes per line. Thus they would look different but convey the same hex codes, once you allow for that.

You may be able to use the copy of avr-objcopy included in the Arduino installation to copy a hex file to a newly generated hex file passing it through the same output generating code as would be used for a newly complied project made with that toolchain.  Then you can use diff.

dose compiler version also influance Hex file?

It might, because of different levels of optimization. Or even, that the command-line switches sent to your compiler are different to the ones used to make the hex file.


text:
Accelerometer (I2C) and Fona Shield (software serial) won't work together
I am using a Fona 808 shield with an Arduino Uno and the LSM303 accelerometer. The accelerometer is connected via I2C and the Fona uses software serial.
My project requires the accelerometer to be continuously polled and occasionally talk with the fona. I wrote a program that just used the fona, but once I added the accelerometer code the program would hang a few seconds after comms had been opened with the Fona. I have tested both the accelerometer and the fona shield separately, and they work fine. So, I wrote another smaller (test) program (which is attached below) to find the origin of the program, which I identified to be:
fonaSerial->begin(4800);

fona.begin(*fonaSerial);

After these lines of code are added, the problem arises. As I said before, this is what I see a few seconds after comms have been opened with the Fona.
http://pasteboard.co/A16708fo3.png
My test program reads the value from the accelerometer, calculates the magnitude of the acceleration and if it's over 20, it prints "Over 20", while also initialising Fona serial.
My question is: Why don't the accelerometer (I2C) and the Fona (Serial) work together and how this be fixed?
This is quite urgent so a quick responses are greatly appreciated!
My Code:
#include <Adafruit_FONA.h>
#include <Adafruit_Sensor.h>
#include <My2_Adafruit_LSM303_U.h>
#include <Wire.h>

#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4

#include <SoftwareSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;

Adafruit_FONA fona = Adafruit_FONA(FONA_RST);

volatile byte accelMagnitude;

Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(54321);

void setup() {
  // put your setup code here, to run once:

    accel.begin();

    Serial.begin(115200);

    fonaSerial->begin(4800);
    fona.begin(*fonaSerial);

}

void ReadAccel(){

//Get a new accelerometer sensor event
  sensors_event_t event;
 // Serial.println(F("Accel---------"));
  accel.getEvent(&event);

  accelMagnitude = sqrt( sq(event.acceleration.x) + sq(event.acceleration.y) + sq(event.acceleration.z));

}

void loop() {
    // put your main code here, to run repeatedly:

    ReadAccel();

    if (accelMagnitude > 20){

        while (accelMagnitude > 20){

            Serial.println("waiting");
            ReadAccel();
        }

        Serial.println("Over 20");

    }
}

Try adding some additional Serial.print commands, so you can see where the programs gets stuck.

The code works fine for about 4 seconds after opening comm with ATs and then it just stops completely.

How do you know that is stops completely? It could be that the accelerometer is returning false data, and that the arduino code is still running fine. That's why I suggested adding additional Serial.println commands. When debugging some code, I sometimes have a Serial.println between every line of code, so I know exactly where the problem occurs.

I added Serial.println("Hello");  into the loop. Hello is printed continuously and then stops after 4 seconds.

Well, there you have narrowed it a bit down. Try adding some more commands and see exactly after which statement is stops. In the mean time try changing sensors_event_t event; to static sensors_event_t event;. I've got a feeling, that maybe there's a memory issue.

I added static but nothing changed. I also added Serial.println("Bye"); into the ReadAccel(); function. The last word it prints is hello (which means the program stops in the ReadAccel() function).

What are you using to power the circuit?

Also, try adding a small delay in the loop, and see if it now takes more than 4 seconds.

I am using a 3.7V Lithium Polymer battery to power the circuit. I first added a 100 ms delay and then a 10 ms delay. The 100 ms delay worked for about a minute. The 10 ms produced the same problem as earlier and once I switched back to the 100 ms delay I again got the same problem as earlier.

I'm out of ideas. Sorry.

I removed the static and tried the delay again. It nows seems to sort of work. Why could this be?

Too little free RAM? Too little power (e.g. the fona connects to the cell-network after 4 seconds, and required a lot of power to transmit)? Something else?

Thank you, Thank you, Thank you, Thank you!!!!! The connection to the cellular network seems to be the problem. I added a 10 sec delay before starting the loop to allow the Fona to connect to the network!

Glad you got it working. But I'd still try and figure out the exact problem if you can. It might come up later, when you try sending a text-message for example. Maybe adding a large capacitor to Vcc.

I have the same problem, I'm not using an accelerometer, but a RGB sensor that works via I2C too. I did come to the same solution of waiting a fair amount of time before initializing the I2C, but after a random amount of time it restarts the arduino.

As Gerben suggests, it would not be a good practice to just add a delay and call it a day.
1) Have a large electrolytic capacitor between Vcc and GND as near as you can to the FONA and
2) FONA has getNetworkStatus(); make a small control loop and query it until you get status 1 or 5, depending on what network are you on.
From FONA's example:
if (n == 0) Serial.println(F("Not registered"));
if (n == 1) Serial.println(F("Registered (home)"));
if (n == 2) Serial.println(F("Not registered (searching)"));
if (n == 3) Serial.println(F("Denied"));
if (n == 4) Serial.println(F("Unknown"));
if (n == 5) Serial.println(F("Registered roaming"));

And then proceed with the rest of your code. You can make additional checks for signal quality with getRSSI();


text:
Can I link another device to the Uno's clock?
I'm trying to use an unusual 16x2 LCD display with my Uno. As far as I know, it's an EA-X16027AR. It doesn't seem to be compatible with the HD44780 driver, which is typically used for Arduino LCD's.
According to the datasheet, the display's ENB (Enable) pin requires a clock input, described as follows:

Basical Clock to perform Instructions in Controller LSI. The Clock at the same timing as MPU are usually input.

The timing graphs elsewhere in the datasheet show it wants a speed of around 2 MHz.
Is it possible to get the internal clock signal from the Uno, scale it down to 2 MHz, and output it to a GPIO pin or similar? Alternatively, is it possible to emulate a clock signal at that speed on-board, without adding additional timing components?

I don't have time to write an answer, but you can use one of the timers and the output compare functionality to do anything from either full clock speed down or half clock speed down (can't recall which one). This requires bare metal usage of the timers though.

Rather than using microprocessor-specific low-level programming, I was able to get a suitable signal using the core tone() function:
tone(11, 2000000);

It can be used to generate a 50% duty cycle square wave of a custom frequency on any individual GPIO pin (I'm using 11 in this case). Given the name, it's obviously designed for producing simple audio output, and 2 MHz is way above the range of human hearing.
The documentation doesn't list any upper limit on the frequency though, and the code it's based on doesn't appear to introduce any limitations. With that said, it clearly can't run faster than the internal timer it's based on (which I think will typically be 8 or 16 MHz).
It seems reasonable to assume that it will be in-sync with the microprocessor's internal clock, although I haven't been able to confirm that empirically as I don't have suitable equipment at home. Similarly, I haven't been able to confirm that it's actually producing a 2 MHz signal, but the LCD display is working properly so it's likely to be in the right vicinity. I had previously tried running it from regular PWM, but that didn't work, so frequency is obviously important here.
The signal can be stopped by calling:
noTone(11);

There are a couple of caveats to be aware of when using tone(). First of all, it can only work on a single pin at a time, so you can't generate multiple signals with it. And secondly, it will prevent some PWM output from working properly (on pins 3 and 11, according to the documentation). This is because it has to reconfigure one of the internal timers which is normally used for PWM.

The tone() command is using " microprocessor-specific low-level programming". It's just a wrapper that prevents you from learning how the MCU actually works.

@FakeName I'd argue that the core Arduino functions (like tone()) are an abstraction layer. In theory, they can be re-implemented under the surface to behave the same way on any microprocessor which supports the relevant features. By "low-level programming", I was referring more to things like directly manipulating special registers. That's definitely not portable, and is probably too advanced for a lot of the visitors we're likely to get here at Arduino.SE.

A wrapper is an abstraction layer. However, the Arduino abstraction layer tends to be dramatically slower, and is not much easier then dealing with the hardware directly. Personally (and this is IMHO), I think that while it's fine to use the arduino functions if you just want to throw something together, you should still read tha datasheet anyways. The hardware can do much more then is exposed by the abstraction layer, and you cannot really fully utilize it without dropping the intermediary entirely.

Basically, I look at the arduino wrappers like using GOTO, or any of a bunch of other programming structures that are easy to use, but lead to complex, hard-to-troubleshoot interactions as soon as you do anything complex. They're nice for hacking together small stuff, but poison for large or complex tasks, unless you understand in full what they're actually doing.


text:
Why can't I upload a sketch while other components/devices are connected to my Uno?
I wanted to make a fairly simple circuit which would flash a series of LEDs in sequence, using my Arduino Uno (more specifically, a SainSmart clone). I wrote my sketch and it compiled fine. After that, I connected 8 LEDS+resistors to pins 0 through 7, and then connected the Uno to my computer via USB.
I've uploaded sketches successfully in the past, so I'm sure my settings and drivers etc. are correct. However, when I tried to upload my sketch this time, it didn't work.
I tried removing everything I'd connected to the Arduino's pins, and suddenly the upload worked again.
Why does this happen? Does it mean I have to disconnect everything from the board every time I upload a sketch?

The problem is specifically pins 0 and 1. Although they can be used as regular digital IO pins, they also serve as the RX and TX pins for the Uno's serial port. The USB connection (for uploading sketches etc.) is routed to the same pins internally. Unfortunately that means anything connected on pins 0 and 1 can interfere with the serial connection, preventing communication via USB.
In short, it's not necessary to disconnect everything when uploading a sketch. It should only be necessary to disconnect anything from pins 0 and 1. Rather than going through that hassle every time a sketch is uploaded though, it may be best just to avoid using those pins unless necessary (e.g. you run out of other pins, or your project needs a serial connection to another device).

Nice way to teach the community.

Since the Arduino is also programmed by SPI, which resides on pins 10-13, it is also possible to prevent it from uploading on these pins

Well written Q&A! I would love to see more such posts from you :)

@TheDoctor - Incorrect! The SPI pins are only relevant if you're using an In-System-Programmer. The bootloader programming mechanism does not require the SPI pins at all. Unless you're hooking up a separate, hardware programming tool, this is not something you need to worry about.

" Peter R. Bloomfield " I used to upload sketch in my arduino uno by connecting Rx and Tx pin but my sketch get uploaded.
Actually problem is arduino uno driver may be deleted in your case

This was intended as a reference question. The same person asked and answered the question. I doubt his problem is that the driver was deleted.


text:
How do I use I2C devices with Arduino?
I have a few useful I2C components, such as a 16-bit port expander (MCP23017), which I'd like to use in various projects.
What do I need to do to make these work with Arduino? Will it work with any Arduino, or do I need a specific board or shield?

Arduino have the Wire Library that communicate with I2C.

This library allows you to communicate with I2C / TWI devices. On the
  Arduino boards with the R3 layout (1.0 pinout), the SDA (data line)
  and SCL (clock line) are on the pin headers close to the AREF pin. The
  Arduino Due has two I2C / TWI interfaces SDA1 and SCL1 are near to the
  AREF pin and the additional one is on pins 20 and 21. As a reference
  the table below shows where TWI pins are located on various Arduino
  boards.

Board   I2C / TWI pins

Uno, Ethernet    A4 (SDA), A5 (SCL)
Mega2560 20 (SDA), 21 (SCL)
Leonardo 2 (SDA), 3 (SCL)
Due  20 (SDA), 21 (SCL), SDA1, SCL1

You can take a look at , this examples.
Like @TheDoctor said:

The I2C data lines both need resistors to 3.3V. This keeps them from
  drifting if they are disabled. Andy resistor value should work, but it
  is recommended to use one between 10k ohm and 47k ohm.

Don't forget pullup resistors on the I2C lines

To expand on that, the i2c data lines both need resistors to 5v. This keeps them from drifting if they are disabled. Andy resistor value should work, but it is recommended to use one between 10k ohm and 47k ohm

It should be said that if you use 5V pullups on the Arduino due (which was named in the answer) you have damaged the board.
The Arduino Due uses 3.3V logic and it does NOT need 5V pullups, also SDA and SCL are already pulled up internally by the board.

Additional shields are not needed.
You only need the Wire library and a couple of wires to connect the device to SDA and SCL.
The position of these pins is different on the various Arduinos, please have a look here.

For future readers: use the Adafruit_MCP23017 library.


text:
Arduino stopwatch, which board to use?
I am planning on making a simple stopwatch with:

A display
One or two additional buttons to start the stopwatch and stop the stopwatch and
maybe reset it.

The problem is that it has to be as small as possible.
With all those different Arduino boards out there, I don't know which one I should buy (mini, micro, nano, ...).
I am not sure how many pins I need for the LCD since I have read that in fact not all pins are mandatory for the LCD. I have done something earlier with an LCD and I found the pot meter for the LCD contrast level a bit of waste of space. Could I just replace it with a certain resistor or something?
How many pins in the end would I need and which board would be fitting for this little project?

http://www.atmel.com/devices/ATTINY26.aspx

What LCD are you planning to use?  What power supply?  If you can still get one, I think the Arduino framework has mostly been ported to the ATmega-based AVR Butterfly, which might have everything you need.

It should be a pretty basic LCD like this for example.
I guess a 9V battery would be the maximum I could use as size.

That's not really a basic LCD. Common, sure, but not basic. And I'd use two Lithium cells instead of a 9V.

Ok thanks for the comment. I will look into a more basic LCD. Which arduino board would you recommend?

If you need it to be as small as possible then you should look at using bare AVRs instead, such as the ATtiny26. It has more than enough pins to interface with both a HD44780-based LCD and all the buttons you need.

How small is "as small as possible" This is possible but perhaps not what you meant.

By that photo you posted, you pretty much answered a decent part of your question. You'll need six pins for the LCD, and one or two for the button. That means that you need a total of 8 pins. That Uno pictured has 20 (analog can act as digital, too).
As far as the boards, if you feel comfortable with some extra work, I'd recommend an ATtiny. From what I can find, it seems like you can drive a LCD with a 44 or an 84 (similar, but the 84 is more powerful).

Source for image and how to program chip. I'm not going to go into the details for this method, as the link has the necessary files...

That's the smallest way to do this*, however, if you want to use a real Arduino board, then I'd recommend the Micro for a few reasons.
First of all, it has the newer ATMEGA32u4 chip, found on the Leonardo. I do not recommend the Mini because, although it's the smallest of the three, it doesn't feature on board USB. You would have to buy another adapter to program it. If you're already using a breadboard, the extra 2cm (or so) is worth not having to spend more to buy both of those components. The Nano is the equivalent of the Mini, only with USB. Also, the Nano and the Micro are roughly the same size, one a little bit longer and one a little bit wider.
However, the Nano and Micro are roughly the same as far as processing power, so I'd recommend that, if you can get one significantly cheaper, to go with that. It doesn't really matter that much.
*If you're building this on a breadboard, it won't be smaller. If you're transferring to a PCB, then you should use an ATtiny.

As far as the pot goes, I'd recommend getting a trimmer with an equivalent value. Some of them are very small, as I have one that fits on the USB connector part of my thumb drive. They need a screwdriver to adjust, but I would recommend it. I've had issues moving it from a dark room to in the sun and not being able to see it clearly. Spend the two cents and the 2 cm2 and have an opportunity to change it if needed.
For the battery, I would recommend any rechargeable battery (under ~3.5V) if and only if you add a proper chip to not waste energy in the conversion. I talked about this in this post.

Looks like I'm going with a cheap copy of the Arduino Micro or Nano, depending which one is the cheapest. I don't have a lot of knowledge in electricity so the ATTiny 44 looks a bit too complex for me.


text:
How I could make a bus connection in a prototype shield?
I am a programmer but pretty new to electronics , I recently bought a prototyping shield like the picture :

In my view there is no bus connections here . I have lots components need connect to solder into a single board , and some ports like GND and VCC , SDA and SCL need connect via buses , how could I make solder such a bus connection by using this shield?
Should I just continuously solder through the holes I want to form a bus?
Thanks..!

If the board has copper on both sides you can solder a copper wire on the bottom to create a "bus".

Sounds reasonable ,however I don't have copper currently , can I just use the solder?

You can, but solder doesn't really want to stick to the solder-mask between the pads. You can just strip some electrical cable, speaker cable, whatever you have laying around.

Thanks Gerben , so should I put copper wire straight on the back face of the board and cover holes , then I soldering other wires in the front face ? or should I soldering wires first , and use a copper attach them and solder together both in front face ?

Doesn't really matter. Whatever works for you. I never liked protoboard. So went almost straight to developing my own circuit-boards.

I would mount the components to the board first then create busses with wire. Depending on the components you might be able to use the same row the component leads are in or you may need to lay the bus in the adjacent row and bridge the gap with component leads.
A quick search turned up an image that sort of gives an idea of what I'm talking about. If you look closely you can see the wire bridging the gap between each solder pad.
https://www.bing.com/images/search?q=soldering+protoboard+bus+wiring&view=detailv2&&&id=EF1514CA6486FC44E0132E7DE1CFBFDBFD015809&selectedIndex=15&ccid=vQ%2beHllm&simid=608022938507020230&thid=JN.TBpqHtXSA7o3dTvD8dPVaQ&ajaxhist=0


text:
Mac OSX Yosemite no serial ports showing for Uno R3
I have a MacBook Pro running OS X Yosemite (10.10.3). I connected my Arduino UNO R3 to my computer for the first time after the Yosemite upgrade - it worked fine before this!
When I opened the Arduino IDE I selected Tools > Board > "Arduino UNO", but when I try to choose a Serial Port the only options are:
/dev/tty.Bluetooth-Incoming-Port
/dev/cu.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/cu.Bluetooth-Modem

I have followed several tutorials and threads on how to 'fix' this issue, all to no avail:
I've installed the latest version of the FTDI drivers (even though, from what I recall the UNO doesn't even need them): FTDIUSBSerialDriver_v2_3.dmg
Downgraded to a prev. version of the FTDI driver hoping that would clear it up: /Volumes/FTDIUSBSerialDriver_v2_2_18
I followed a tutorial of how to remove the existing Apple drivers and removed the kext files, etc...
Tried connecting arduino to both USB ports.
Tried various cables, including the one that a I used before the Yosemite upgrade.
Tried installing updated Silabs drivers:
Arduino compatible's serial port not showing Mac OSX
Walked through the entire Arduino Mac OSX guide:
http://www.arduino.cc/en/guide/macOSX
After looking into the system info of my Macbook Pro, I can see the USB Controller is Broadcom based, in case that helps. I searched for Broadcom USB drivers but got hits for Silabs one instead.
Under my Tools > Port menu.. I can see these options:

clicking the Serial Ports option doesn't do anything.
Running ls -1 /dev/tty.* or ls -l /dev/tty.usb* from terminal gives me:
/dev/tty.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem

The Board does NOT show up under system networking (as it has for others), so it's not recognized as an incorrect device.
I'm at a complete loss. The board powers up... but I cannot connect to it.
SIDE NOTE: This is a legit Uno R3, not a clone.

If it is a legitimate Uno, then all of the FTDI and SiLabs efforts are an irrelevant distraction at best.  Ideally, test the board and cable on an another machine to make sure it has not been damaged in the meantime, and try a different USB port on the Mac (especially try connecting through a keyboard or hub if you tried directly, or directly if you had tried a hub).  I believe if you look in system information you can get a listing of all USB devices, which would be good to include in your post.

That's what I was thinking - regarding the FTDI drivers - but those were the only solutions I could find claiming to 'solve' this issue. I have tried other USB ports on the Macbook and will fire up my Apple keyboard since it has a USB port and reply back. I did write in my post the USB devices recognized in terminal.

Ok, tried my Apple YSB keyboard - connecting Uno to USB port === no dice

Moved the Apple USB Keyboard back to my iMac and tried to connect to Uno there.. selected Uno from the Board menu and still only shows bluetooth modems from the Serial Port menu.

After updating the Arduino app to 1.6.4 the Port menu now shows the same options as my Macbook (shown in the image in Orig. Post)

You really should look not just in the Arduino IDE but in system information or whatever they call it (get there from the about this mac, and advanced, etc) and see what USB devices it is seeing.  And again, test the board on another machine to make sure it is still good.

I've checked for 'visible' USB devices in both the System Info screen and via the Terminal.. both show the same.. and only bluetooth are present (aside from keyboard and my external HDD).  2) I have now tried this on both my Mackbook Pro and my iMac .. neither of which 'see' the USB connection.

Post a complete list of the raw USB (not serial) devices (ie, VID/PID) the system (not IDE) sees connected.

I did. I copied the LS from Terminal as well as identified, through the system settings screen, that there are only the USB to Bluetooth, Keyboard and Internal Memory Card controller. I checked both the IDE and the System screen after: 1) changing cables, 2) adding an Apple USB keyboard and using it;s USB port, 3) trying the same sequence on my iMac (keyboard usb and main usb).. nothing. The board is not listed. Period.

@ChrisStratton If there is another way to do this, to get the info you're asking for.. please let me know. But at this point, I've looked/checked everywhere that I know how to.

Until you have demonstrated that the board still works on some system (at this point probably not a Mac) you will have to consider it to be damaged.

Well, looks like the board might very well be shot. I fired up my wifes Windows laptop, installed Arduino, etc.. attached power and USB to Uno and it doesn't show in either the Arduino app or File Explorer. Not sure what/how it happened as the board was stored in an air tight, dry, cool container within a static free bag - the one it shipped it. And, I'd already ran this sketch once to perfection... bummer. Any other thoughts or possibilities?

After reading this I just tried out some of my Arduino machines, which worked properly so far, and indeed after upgrading to Yosemite yesterday, now none of my machines and none of my cables are recognized. I suspect a driver incompatibility...

Just wanted to add that I was having this same issue and switching to a different USB cable worked for me. I did not even know there was such a thing as a power-only USB!

This posted question has shown me the truth after a good 12 hours of absolute bupkis trying to get my V3 to show up in the serial ports. Thank you OP, for the release from hell.

This is the best solution and drivers I've found: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver

Probably, you have Chinese Uno analog which works on CH340 USB-to-serial chip, so you need to install driver for it.
Steps to fix:

Install the CH340 driver
Run the command in Terminal: sudo nvram boot-args="kext-dev-mode=1" (disable kext signing introduced in Mac OS X 10.9 Yosemite)
Reboot

Also you're right according to Uno and FDTI:

Differences with other boards
The Uno differs from all preceding boards in that it does not use the FTDI USB-to-serial driver chip. Instead, it features the Atmega16U2 (Atmega8U2 up to version R2) programmed as a USB-to-serial converter.

Thanks for including the CH340 chip number right in your answer.

On OSX 10.11.6, installing the driver and rebooting solved this for me.  No need for step 2.

This worked on 10.9.4 without step 2. Now I expect my private SSH keys to be located on some chinese servers though :)

@polym - was the second half of your comment really necessary?

Unfortunately the driver causes a kernel panic as soon as I plug in the Arduino. I'm on macOS Sierra 10.12.2.

@Colin did you manage to get it working?

@Ronny-AndréBendiksen No I didn't get it working. I just moved the upload step to my Raspberry Pi. :P

OSX 10.12.4 gives the following error when trying "sudo nvram boot-args="kext-dev-mode=1" " => nvram: Error setting variable - 'boot-args': (iokit/common) general error

If you're on Sierra, use this patched version of the driver. Worked like a charm: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver

When I run nvram, I get an error: nvram: Error setting variable - 'boot-args': (iokit/common) general error

@IgorGanapolsky - Starting with macOS Sierra, you must be booted to the recovery partition to run the nvram command.

This solution didn't fix the problem for me.  However, since it seems to work for some people, the new v1.4 version of the driver that supposedly works for High Sierra is here. :  https://drive.google.com/file/d/1lUYkw-mCOekJjY1MVA5YuEbERHNWNCZW/view?usp=sharing

I was able to get a new /dev/cu.wchusbserial1410 to show up by following the instructions from https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver , didn't need nvram. Thanks for the link

I get the following after installing the driver from github.com/adrianmihalko and executing the sudo kextload /Library/Extensions/usbserial.kext step.  Then I get this: /Library/Extensions/usbserial.kext failed to load - (libkern/kext) system policy prevents loading; check the system/kernel logs for errors or try kextutil(8).

The cable that shipped with my Arduino Uno worked for power but not data transmission so the /dev/tty.usbmodem was not showing up in the Tools --> Port menu. After I switched to a different cable, the /dev/tty.usbmodem port showed up and it worked beautifully.

The same thing happened to me.  I was trying to connect my Arduino with a power-only cable.  Once I switched USB cables, the USB device appeared.

I had this same problem and all it took was a different cable

This is definitely the solution for me! Thanks a ton!

I have had this problem before, with Circuit Playgrounds, but forgot all about it. Switching the cable should always be the first attempt.

Same, I got the elegoo mega 2560 kit and the little usb c cable seemed to only work part of the time. Odd...

This fixed the problem for me:
http://blog.sengotta.net/signed-mac-os-driver-for-winchiphead-ch340-serial-bridge/
... and the direct link to download.
EDIT: I have one of the cheap clones with a CH340 USB chip. So this might not solve your problem, but could be beneficial to others.

The board in question does not have a ch340

Cheap clones do have CH340.

The question however, is quite specific about which board is involved, and it is quite specifically one which does not have a ch340.  The poster is answering a different question than the one which was asked.

Good point. I edited my answer with a clarification. I wanted to post it anyway though, because I spent a lot of time googling for a solution to my problem and stumbled onto this thread among the rest. Maybe it'll help others.

This is the answer I was looking for, unaware that my cheap clone had a different chip from the genuine Arduino.

Thanx a lot, it works for me =)

This site fixed the problem for me:
http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html
...somebody else has made an alternative to the ftdi drivers, and this website show you how to install them correctly.

Yosemite 10.9 (and OS X 10.10 and newer) requires a signed USB driver kext (kernel extension).  You can find one on the FTDI web site here: http://www.ftdichip.com/Drivers/VCP.htm
Use version 2.3 for 64-bit OS X 10.9 or later.  Install and reboot.
Plug in your Arduino, and the Terminal command:

/usr/sbin/kextstat | grep FTDI

will tell you if the FTDI VCP driver actually loaded.
Also a /dev/tty.usbserial-xxxxxxxx entry should appear in your /dev directory.
If not, the Mac USB port isn't talking to your Arduino.  So it's no use trying the Arduino IDE application.
Also make sure your USB cable isn't for power only, but fully connected.

Note that the Uno R3 does not use an FTDI chip.

This exact same thing happen to me on my mac running the same operating system. I had to restart this system a few times to get it to work. I restarted it with the arduino plugged in; and that worked rather than my previous attempts when i rebooted then plugged in.

Will try this power cycling and try again this evening.. thanks for the response!

I have an osepp r3, seemingly an accurate clone. Computer is Mac os10.10.5.
A lot of sites claimed that the mac osx.* does not require FTDI drivers, but.....
After an awkward, google searching beginning, where the board only accepted a new sketch after being physically unplugged and replugged, I downloaded the latest FTDI driver, installed, and RESTARTED the mac. Now, joy and peace reigns. No side-effects with other mac functions, thankfully. Hope this helps.

Check this video https://www.youtube.com/watch?v=0zuRukW7o0A

Reboot and press CMD+R immediately after reboot to enter in Recovery Mode
Open Terminal from Recovery mode
Run the command csrutil enable --without kext
Reboot
Install driver

Stumbled across this. It worked for Mac OS X Yosemite 10.10.5
install the CH340 driver
Run the command in Terminal:
sudo nvram boot-args="kext-dev-mode=1"
Reboot
However, I installed:
MAC system：www.wch.cn/downfile/178
so YMMV
a user here:
http://forum.makeblock.cc/t/mac-os-x-yosemite-arduino-1-0-6-doesnt-recognize-makeblock-orion/728
found the solution, there:
http://forum.arduino.cc/index.php?topic=261375.15
so kudos - to all that sweated out the driver, uninstall, install, and activation...
Ted

First, check the USB cable - I had the same problem. If you have checked it, try the HoodLoader2:
I am using it and it works with Arduino Leonardo.

Can you please elaborate on your answer? Link-only answers are frowned-upon. What if the link goes down?

In my case, there was some kind of incompatibility with the ESP8266 connected to the Nano board. As soon as I removed it the Serial Port appeared again.

The OP does not appear to be using a ESP8266


text:
Why are Arduino timer registers not 0?
I'm trying to use the timer registers to do some timing on my Arduino Mega 2560.
The output of the following code confuses me:
void setup ()
{
    // Set up serial connection
    Serial.begin(9600);
    while (!Serial) {}

    // Print control registers of timer 1
    Serial.println(TCCR1A); // Outputs 1
    Serial.println(TCCR1B); // Outputs 3
}

void loop () {}

Why is TCCR1A equal to 1 and TCCR1B equal to 3? The documentation of the chip says the initial values of the registers are zero. I could of course set them to zero, but I want to understand why it works like this. The values are the same for the other 16-bit timers (3, 4 and 5).

The Arduino core does things at startup. One of those things is to configure the timers ready for PWM operation.
Here's the relevant bits from init() in wiring.c:
    // set timer 1 prescale factor to 64
    sbi(TCCR1B, CS11);
#if F_CPU >= 8000000L
    sbi(TCCR1B, CS10);
#endif

#if defined(TCCR1A) && defined(WGM10)
    sbi(TCCR1A, WGM10);
#endif


text:
Using an Arduino as a crystal oscillator
I want to overclock my Game Boy Advance SP. It has a built-in 4 MHz crystal, and I was able to temporarily replace it with an 8 MHz crystal to see if I was able to overclock it, which I was :).
However I'm wondering if it's possible to emulate/simulate a crystal using an Arduino? Like instead of a crystal soldered to the Game Boy, two output pins from the Arduino? If not, is there a such thing as a variable oscillator? Like a crystal with a potentiometer to change the frequency when the potentiometer is adjusted?

Why would you waste a 10$+ Arduino/ATmega328 to replace a 0.25$ crystal?

Its temporary. I want to add a female port(s) to the side of the Gameboy where I can attach the Arduino to control the clockspeed.

The Arduino Uno (and most other Arduinos) doesn't really have a crystal oscillator (the on-board one is for the USB-to-serial chip, not the main processor).

You want to use the Uno? You can set up a timer to output varying frequencies and output them on a pin. I have a page about timers which might help. The fastest you can get with a 16 MHz processor is 8 MHz output however you can get other frequencies by changing the timer parameters.
The ATtiny85 can output higher frequencies if you use the PLL clock option, I think you can then adjust the resulting frequency.

If not, is there a such thing as a variable oscillator?

Adafruit make a Clock Generator Breakout Board - 8KHz to 160MHz. You connect that via I2C to your Arduino and then program assorted frequencies as a clock output. That uses the Si5351A clock generator chip.

Example code to output 8 MHz on a Uno or Mega2560:
#ifdef __AVR_ATmega2560__
  const byte CLOCKOUT = 11;  // Mega 2560
#else
  const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
#endif

void setup ()
  {
  // set up 8 MHz timer on CLOCKOUT (OC1A)
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
  OCR1A =  0;       // output every cycle
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

To output 4 MHz change OCR1A to 1 rather than 0.

Thanks for the reply! So I understand my UNO can output 8mhz. Now this might sound like a stupid question, but since it outputs on only 1 pin, how would I connect it to a device that would normally use a 2-Pin crystal oscillator? Would I connect that one pin to both sockets of where the crystal would be, or would I connect the one output pin to one side and GND to another?

Ok, so I found this code which outputs 8MHz on an Arduino Micro (which I own). I'm trying to figure out how to output 4MHz instead, while keeping the code similar.   http://pastebin.com/JFP7pUiF

Would I connect that one pin to both sockets of where the crystal would be, or would I connect the one output pin to one side and GND to another? Yes, but the Gameboy might not be designed for that. A circuit that expects a crystal should probably be given a crystal. You could get different value crystals from eBay for a couple of dollars.

Hmm. that's what I was thinking but then I saw this: https://youtu.be/nwJQxD8LLNY. He said he used a frequency generator, which to my knowledge, outputs a set frequency, so I thought he result would be the same with an Arduino. Can you show me how I'd go about changing this code (http://pastebin.com/JFP7pUiF) to output 4MHz, and show me how you did it? I checked out your page, and I'm normally pretty good with Arduinos, but I am COMPLETELY lost with this timer thing.

Since you tagged your question with "Uno" I've amended my answer to show how to do it on a Uno. The register OCR1A is what you count up to. If it contains 0 then it toggles the pin every clock cycle. If you count to 1 it toggles the pin every other clock cycle.

Ugh, just joined SE. Couldnt figure out the stanky tag thang! Thank you so much for the help! You are a GOD!

A crystal oscillator connection to a microcontroller typically consists of two pins - an output "driving" pin, and an input "amplifying" pin. The crystal sits between the two pins (basically between the input and the output of the amplifier) and the amplifier oscillates at the frequency of the crystal.
In general you can bypass the crystal itself and just provide a clock signal on the input pin (often labelled OSC1 or OSCI) and ignore the output pin since it isn't needed to drive a crystal.
Some microcontrollers provide a special "EC" mode (External Clock) which disables the amplifier and just expects a clock signal.

Thanks so much for the clarification! This clears it up alot!

Using the Arduino platform as a signal generator (oscillator) results in too high a granularity factor.  Software that has been suggested can only change between 8 and 4 MHz but not output anything between those two frequencies.
It would be better to use some sort of DDS or Frequency Synthesizer circuit
that can be adjusted incrementally with a granularity of 1 Hz or better.
My suggestion would be to use the Arduino to control a modern synthesis IC
like the S15351a.  This combination can output any frequency from 3KHz to
160 MHz in 1 Hz steps.  The device is inexpensive and has 3 outputs which
can be adjusted independently.  Google "Si5351a Arduino" to find some
circuit suggestions.
https://www.qrp-labs.com/progrock.html

On many Arduinos, including Arduino Uno, the main microcontroller uses a poor ceramic oscillator with a 0.5% tolerance (the crystal is only used for the USB side)


text:
Problem with deploying matlab simulink mode to Arduino UNO
I encounter a problem when deploy matlab simulink model to Arduino UNO
Following shows the error
*The call to realtime_make_rtw_hook, during the after_make hook generated  the following error:
The build failed with the following message: The system cannot find the path specified
The build process will terminate as a result.
The build failed with the following message: The system cannot find the path specified。
Component: Simulink | Category: Block error*

When type >> getenv('path')
ans =

C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;E:\MathWorks\runtime\win64;E:\MathWorks\bin;E:\MathWorks\polyspace\bin;C:\Program Files\MATLAB\R2014b\runtime\win64;C:\Program Files\MATLAB\R2014b\bin;C:\Program Files\MATLAB\R2014b\polyspace\bin;C:\Program Files\Microsoft Windows Performance Toolkit\

I did not see anything wrong with the path. I tried to solve the problem following the "http://www.mathworks.com/matlabcentral/answers/168555-what-does-the-path-in-the-system-cannot-find-the-path-specified-refer-to". However it does not work.
Anyone know how to solve it?
OS:Win8.1 Matlab 2014b 64bit

Right click on your MATLAB shortcut and click "run as administrator". See if helps. Then do all the necessary steps and see if it happens again.
Also test with x86 version. I have seen lots of these kinds of error with x64 version. Always had compiling related issues with MATLAB x64 and Simulink!


text:
Detect movement on moving robot? PIR Sensor
I am working on a human following robot project and I am trying to achieve this with 1 Ultrasonic sensor that makes sure the robot won't crash into something and 3 PIR sensors that will detect human movement.
The robot has an Ultrasonic Sensor and a PIR sensor attached to the front and a PIR sensor attached to the right side and another PIR sensor attached to the left side.
If the front PIR reads HIGH, then the robot will move forward. If the left or right PIR reads HIGH, then the robot will start turning in a 360 degree motion to the left/right side and will keep on doing so until the front PIR reads HIGH, and the robot moves forward again.
I am currently working with this build and I am having issues with the sensors. Sometimes they read HIGH when they shouldn't and sometimes they read LOW when they should be reading HIGH.
So my question is, what can I do to help the PIR sensors with getting the correct reading and is it possible to do so while the robot is turning?
Also, how will calibration work here? Am I able to let the robot turn slowly in 360 degree motion so the 3 PIR sensors will be calibrated with the rooms surrounding or is this a dumb question? If so I'm sorry, I am pretty new to PIR sensors.

UPDATE:
Thanks for the help everyone. I have now replaced the side PIR sensors with Ultrasonic sensors. I have kept the front PIR sensor though. It is working a lot better than with the side PIR sensors and I thank you all for your input.

I don't think its fundamentally possible for a PIR sensor to tell the difference between the an object moving while the sensor sits still and a still object while the sensor moves.

Same, I think  that if you move a PIR sensor around, it's likely to detect 'movement'. I should do it with some distance sensors and then just track whatever is closest to you. So if you stand near the robot, it'll move towards you (and brake when he is close) So he will keep following you. (If you also implement these sensors at the 'sides'). Detecting movement, while moving yourself isn't really going to work. You could let the robot sit until he sees movement and then use range-sensors to track the moving object.

Basically you have a robot and sensors that can detect movement.
There is one caveat though. For the PIR sensors to (non false-positive) detect motion, they have to be stationary (as far as I know).
So with only these PIR sensors it's unlikely that you can track something well.
Tracking something would be done best by using a range/proximity sensor.

The image below, seems to be a cute robot, with eyes.
You could take 3 sensors and place them under an angle (one forward, one forward/left and one forward/right) [picture 2]. Or just have one that rotates (will be more difficult) [picture 1].
You would want the robot to start following anything that comes close (or when one of the sensors sees a difference in distance. And then the robot will try to keep that distance, brake when he gets closer, drive when he gets further.
If that's working, you can implement the sensors at the side, that if suddenly he loses track of the object/person, he'll adjust his alignment so that the middle sensor sees it again. This could also be done by simpler sensors [picture 3]
When the robot gets to close, and the other object doesn't try to run for quite a time, you can make him check for another target. (With a PIR or by rotating and stopping rotating to check range/pir)
I believe this solution is more applicable as with only PIR sensors, as it's usefull to know the range when you're following something. You don't want to bash into it.

Thanks for your answer Fuaze. I will go ahead and use Ultrasonic sensors instead of the PIR sensors then. I just wish I had done more research on PIR sensors before hand ^^.

No point, those PIR sensors can be used to detect the initial movement around the robot anyway, to decrease the amount of ultrasonic sensors needed. And to give a view all around the robot.
And bet you can find another great use of the PIR sensors in another project! You already know how they work, which is great for further usage.

Try using heat detectors(technically speaking, Infrared sensors) (along with >1 Ultrasonic sensors and PIR motion sensors for greater accuracy) with 1 ultrasonic sensor.
Comment if you want more help.


text:
Ultimate GPS Logger Shield : Soft Serial Sketch Error
Im using a OSEPP Uno R3 Plus to connect with a Ultimate GPS Logger Shield. I am currently working through the Adafruit Ultimate GPS Logger Shield pdf. When connecting in Soft Serial Mode and loading a parsing sketch. In the com window my values are showing but unreadable. I have included an image. Any help is appreciated.

You should describe your problem with further details if you expect some help. Currently I get no idea of what you have done so far to get there (eg source code). It seems likely you have an issue with Serialconfiguration, but without any code, it is hard to tell. Also you did not mention how the serial console is setup (speed in particular).

jfpoilpret > My apologies for not including enough information and details. But your comments did lead to me resolving my issue. I did not change my baud rate to match the baud rate of the source code and the script is working now. Appreciated.