text:
Having some trouble incrementing counters
So, I have some simple code here. I'll just try and explain what I am trying to have my code do here.
I am trying to rotate my stepper motor by half a turn, and then move it back and forth by 200 steps or so.
The problem I have is in my loop function, where I have a variable called ctr. I am trying to increment this ctr when I execute an if statement. The ctr increments inside the if statement and I can see the result when I do Serial.println as it changes to 1. However, when I Serial.println(ctr) right below the if statement, it prints out as 0 even after the previous print statement prints out 1.
Why is this happening? I am a C/C++ noob, so is there something I am missing about variable scoping or pointers?
void loop()
{
    stepper1.run();
    int ctr = 0; //counter value to store how many times the back and forth motion has occured
    if(stepper1.currentPosition() == 1024){
      backMotion(stepper1.currentPosition());
      ctr++;
      Serial.println(ctr);
    }
    Serial.println(ctr);
    if(stepper1.currentPosition() == 824 && ctr > 0){
      forthMotion(stepper1.currentPosition());
    }
}

void backMotion(int value){
    int current = value;
    int back_distance = current - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion(int value) {
  int current = value;
  int forth_distance = current+200;
  stepper1.moveTo(forth_distance);
}

Someone correct me if I'm wrong but don't you want your void backMotion... and void forthMotion... before void loop()? When you declare a function like forthMotion or backMotion, it should be before you call the function.

@KingDuken I'll correct you because you are wrong. Normally you are right, but the Arduino IDE inserts function prototypes automatically for you which allows you to be lazy with your function ordering.

Make CTR static or place it in the global scope. As it stands you set it to 0 every time you go through loop.
The line:
int ctr = 0;

literally means "Create a new variable on the stack called 'ctr' and give it the value 0", and that happens every time loop() is executed.
Instead making it static will change it so that it only happens the first time loop() is executed so it retains its value across successive executions of loop().
static int ctr = 0;

Agreed. A declaration int ctr = 0; inside a function tells the compiler to assign 0 to ctr every time it passes that line.

loop() != main()
when declaring a variable inside a function, it is cleaned up when returning from the function.
if cnt was in a main() function, it would have worked (as it's the only function that may have an infinite loop in a program. In the arduino world, it's not the case. The main() function is hidden, but loop calls the loop() function.
Workaround is to use the static quelifier when you declare variables inside loop() (or in any other function if you want the variable to remain inside the function scope, but don't want it to be initialized each time you enter the function).


text:
POE with Arduino Leonardo Eth
I recently purchased a Leonardo Eth and a 5v POE module in an attempt to have a POE micro-controller.  I installed the module in the holes closest to the Ethernet jack side of the board, but when I apply power, the green power light turns on every second or so, but never fully turns on.
What am I doing wrong? Did I install the module wrong? Is it the wrong module?

So you have PoE injector with 36V to 72V power supply? (I suppose 48V ones are most common as 24V is out of range for your PoE Module)

I have a PoE 48v 802.3 af switch

Have you verified that your terminations on the cable are good, and you are getting the necessary voltage at the Arduino end of the cable?  Once that is verified, check the output pins of the POE module, verify the necessary voltage, and if possible, hook a scope up to it, and watch what is happening.

POE switch and cable work fine, as I can power other POE stuff with it.  I measured the output voltage of the device and it was very unstable.  I think I will just buy a different module.

From the arduino.cc website.
"The optional PoE module is designed to extract power from a conventional twisted pair Category 5 Ethernet cable. PoE module features are as follows: IEEE802.3af compliant Input voltage range 36V to 57V Overload and short-circuit protection 12V Output High efficiency DC/DC converter: typ 85% @ 80% load 1500V isolation (input to output)"
It sounds like you need the 12V PoE module

source: Stack Exchange

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

sort: votes


text:
Control a motor with a button
Code:
int motorPin = 9;  // the pin the motor is connected to

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

void loop()
{
 motorOnThenOff(); //motorAcceleration
}

void motorOnThenOff(){
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for
  int offTime = 1000; //the number of milliseconds for the motor to turn off for

  digitalWrite(motorPin, HIGH); // turns the motor On
  delay(onTime);                // waits for onTime milliseconds
  digitalWrite(motorPin, LOW);  // turns the motor Off
  delay(offTime);               // waits for offTime milliseconds
}

void motorOnThenOffWithSpeed(){

  int onSpeed = 200;  // a number between 0 (stopped) and 255 (full speed)
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for

  int offSpeed = 50;  // a number between 0 (stopped) and 255 (full speed)
  int offTime = 1000; //the number of milliseconds for the motor to turn off for

  analogWrite(motorPin, onSpeed);   // turns the motor On
  delay(onTime);                    // waits for onTime milliseconds
  analogWrite(motorPin, offSpeed);  // turns the motor Off
  delay(offTime);                   // waits for offTime milliseconds
}

void motorAcceleration(){
  int delayTime = 50; //milliseconds between each speed step

  //Accelerates the motor
  for(int i = 0; i < 256; i++){ //goes through each speed from 0 to 255
    analogWrite(motorPin, i);   //sets the new speed
    delay(delayTime);           // waits for delayTime milliseconds
  }

  //Decelerates the motor
  for(int i = 255; i >= 0; i--){ //goes through each speed from 255 to 0
    analogWrite(motorPin, i);   //sets the new speed
    delay(delayTime);           // waits for delayTime milliseconds
  }
}

This code spins the motor. In the circuit, I have a button which I want to toggle the spinning of the motor.
This is the circuit:
https://circuits.io/circuits/4267039-spin-motor-spin/edit
How would I make it so that the button toggles the spinning of the motor? like a fan and its switch?

add this variable at the top of your program:
const int buttonPin = XX;   // the pin for the button
bool bState = false;

in the setup() function:
pinMode(buttonPin, INPUT_PULLUP);
// in case INPUT_PULLUP is not defined, comment the above line and uncomment below
//pinMode(buttonPin, INPUT);
//digitalWrite (buttonPin, HIGH);  // enable internal pull-up

in the loop() function, change your code with this:
update_bState();

if (bState) { digitalWrite(motorPin, HIGH); }
else        { digitalWrite(motorPin, LOW); }

then, at the end of your program, add the getButton function:
void update_bState(void)
{
    static bool buttonDone = false;
    static uint16_t timeButton;

    if (!digitalRead(buttonPin))
    {
        if ((!buttonDone) && ((uint16_t) (millis() - timeButton) > 100))
        { // Do once when button is pressed for at least 100ms (debounce)
            bState ^= true;     // Toggle button state
            buttonDone = true;
        }
    }
    else
    {
        buttonDone = false;
        timeButton = millis();
    }
}

Now that all the work is done, you should add acceleration when launching and deceleration when launching and stopping :D
By the way, I did not tested any code, so there may be some typo errors...

Yes I do, first line I tell to add in the loop

I beg your pardon, so you do

No problem. I checked, I could have forgotten something.

you have some issues in the circuit too, you need to put pull up or pull down resistors with push button in order to stop floating values.

@Muhammad Did you notice that the button is initialized as INPUT_PULLUP? This enables internal microcontroller pull-up resistor for the pin, thus avoiding the use of external pull for the button.

I also used that KEYWORD twice but it didn't work for me that's why I ask about that.

@Muhammad depending your board definitions or arduino version, INPUT_PULLUP may not be defined. In this case, pinMode(buttonPin, INPUT); digitalWrite(buttonPin, HIGH); should work. Writing a 1 to an input declared pin turns the internal pull-up on.

Thanks for sharing such information and for enhancing my knowledge.

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


text:
Servos stop after a while in case of 8 servo motor control
I recently purchased 10 units of MG996R servo motor and the 16 channel 12-bit PWM/Servo driver from Adafruit for a small project. I confirmed that all of my servos are functional and that my code is correct. My issue is that there seems to be a limit on the number of servos I can run. With 4AA batteries, I can power about 3 of the MG996R servos. Starting with the 4th one, they stop moving. I supposed that the current drawn from the servos is high, so I tried powering the servos by providing two 4AA batteries in parallel (8AA). This appeared to have increased the number of servos I can run. But after a few minutes, the servos stop responding and I have to disconnect the power for a while before the servos respond again. I read on Adafruit that I may need to add a capacitor to the PWM/servo drive if I have multiple servos. Is this my problem or I just need to provide more power? Why do the servos seem to respond initially but stop moving after a while? Thanks in advance.

If Adafruit say to use the kit to drive multiple servos you need to add a cap and without the cap you can't drive multiple servos, then yes your first port of call should be to add the cap.
However that's probably not all that's wrong.  If it runs for a bit before dying then it could be a number of causes.

Not enough power.
Something is overheating.
Code problem.

Use a decent transformer with more than enough amps to power your motors.
Use your nose, does something smell hot?  If you use your fingers you will get burnt!
We can't fix invisible code.


text:
Why the command noDisplay() clear all LCD screen?
i want to preserve video information for long time without communicating with arduino on lcd 1602, i'm tryng to use the command of liquidCrystal library noDisplay() but when i use it,this clear all display. On arduino website here is the description of this command "Turns off the LCD display, without losing the text currently shown on it." but i lose all on screen. Thanks for reply
there is my test code
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // Turn off the display:
  lcd.noDisplay();
  delay(500);
  // Turn on the display:
  lcd.display();
  delay(500);
}

with this code display blinking and don't show continuos "hello word".

I tried out your code. It's working absolutely fine.
Whenever lcd.noDisplay() executes then LCD not displaying hello, word!...
And whenever lcd.display() executes then LCD displaying hello, word!...
So, that's why "hello word" not continuously displaying.
And you can also find the display() and noDisplay() functions to turn on and off
the display comment on top of arduino sketch.

I tried out your code. It's working absolutely fine.
Whenever lcd.noDisplay() executes then LCD not displaying hello,
  word!... And whenever lcd.display() executes then LCD displaying
  hello, word!...
So, that's why "hello word" not continuously displaying.
And you can also find the display() and noDisplay() functions to turn
  on and off the display comment on top of arduino sketch.

To follow on @Hasan's answer:
noDisplay() doesn't clear the previous displayed stuff, it just inhibits it, all displayed pixels are latched in the chip while it remains powered on.
In case you need to clear the display, you can use lcd.clear() function.

i don't need to clear but to preserve the words on display without communicating

Then, as Hasan answered you, just remove the first 2 lines of the loop... particularly lcd.noDisplay(); ... By the way, you can remove everything that is in the loop() function. Just update the text when needed using lcd.print("new text") function.


text:
Using two MIDI inputs with Arduino UNO (with one serial)
Would it be possible to use TWO MIDI inputs (and a MIDI output) on an Arduino having only one RX/TX serial port? Timing will be somewhat critical so a software serial port is not usable probably. I need to listen continuously to both MIDI (in) ports not to miss messages.
Or is it better to use an Arduino Mega having 4 serial ports?

Use a Mega. SoftwareSerial is shaky at best and cripples everything else while it runs, and there really is no substitute for real hardware UARTs.
Alternatively look around and see if you can find a board based around the ATMega328-PB (note the "B") which has a second UART built in.

I can find the IC, but It's in SOP format, and since I have barely 0 soldering experience, the safest way is to go for a Mega for now. But nice to know there is an alternative.

FYI: I went for a Mega and now use 3 UARTS without any problem (leaving the 4th for debugging).


text:
Low Power Library 4 seconds ON, 10 minutes OFF
Could someone please demonstrate how to use a counter with the Arduino 'low power' library to wait for 10 minutes then digitalWrite 4000, HIGH and loop. (I don't mean the simple 'blink' sketch).
I'm trying to save as much power as possible, so any advice is appreciated.
Thanks!

For low power you really need a better board (or own design). The Uno burns a lot of power on extra circuitry and LEDs. Low power library (mode) will not give much. The board will still draw approx. 10 mA.

And using counter means you can't go deeper than to the IDLE mode and it's not so "saving" at all. You can't use Timer2 in asynchronous mode on UNO, as there is crystal resonator for the main oscillator on the same pins.

In principle, you put the arduino in sleep mode (powerdown) and configure the watchdog timer to wake it up after a certain length of time. Since the maximum time is about 8 seconds, you have to cycle through about 80 wakeup cycle to achieve your 10 minutes.
Here is a good guide: https://www.gammon.com.au/forum/?id=11497

Your problem here is your 10 minutes mark. If you're willing to take a somewhat more complex route, you could use a low-power, programmable, external timer like TPL5110. You can set an interval of up to 120 minutes by selecting the appropriate value of the programming resistor.
This kind of timers can be used to drive the gate of a logic-level P-channel MOSFET that acts as a switch for the power line of the Arduino.

Then, you simply you do all your stuff on the setup() function and leave loop() empty. You can switch off the Arduino by sending back a DONE signal to the TPL5110 at the end for your setup().

If, for whatever reasons, you really want your Arduino to be running for exactly 3 seconds, then you should run a timer in it (beware: not related in any way with TPL5110). Set it up so you the ISR of the timer breaks a do-while waiting loop just before the line of code that sends back the DONE signal.

Agreed with what most others have already mentioned;
The Arduino as-is is not suitable for low power operation - it is best to turn it off completely. The circuit below should do what you want, and is based on a very simple and cheap IC, the 555 timer.

simulate this circuit – Schematic created using CircuitLab
A similar version of this has been working for me for about 2 years in a remote sensing setup. A few things to note to make sure that it works;

This needs the TLC555 chip which is a CMOS IC. The TTL version (NE555) will not work with such high value timing resistors.
The timing capacitor (shown as 141uF, just use 3 x 47uF in parallel) needs to be a tantalum capacitor. The normal electrolytic version has too high a leakage current.
As shown, this should turn off the Arduino for about 580s, and on for 120s. To turn off the Arduino sooner, drive digital pin 5 high. This will discharge C1 through R3 and Q1 quickly (about 500ms).
To change the delay times, alter R1, R2, and C1. The datasheet has all the equations that you need for this.
it would probably be wise to put a bypass capacitor between the supply rails very close to the TLC555 chip. 10uF should do.
This circuit should draw around 360uA while the Arduino is off.

One final thing - the task that you are using the Arduino for sounds pretty simple - driving a digital line high for 4 seconds every 10 minutes. I guess that you have more to it than that, but if not, then you could save yourself the cost and complexity, and do away with the Arduino completely. In that case, R1 should be about 6M1, and R2 about 41K, you can remove Q1, D1, R3 and R6, and whatever you are driving goes in place of the Arduino.


text:
EEPROM write time
I will implements an emergency backup feature before power off, on Arduino Mega 2650.
Arduino is powered by capacitor, for the time (I hope) of the EEPROM write.
On AVR2650 Datasheet is reported that the typical EEPROM writing time is 3.3ms.
But 3.3ms for what? a byte? a word? the whole EEPROM?
I need the data for calculate the capacitors.

On AVR2650 Datasheet is reported that the typical EEPROM writing time is 3.3ms. But 3.3ms for what? a byte? a word? the whole EEPROM?

That is per byte (erase and write 3.4 ms, only write is 1.8 ms). When writing multiple bytes there are a few clock cycles to be gained by preparing for the next byte during an ongoing EEPROM write. Or even better use an ISR for the EEPROM feed. Not faster but allows some additional processing while a block is written. The largest gain is to have the EEPROM erased before the write (1.8 ms per byte instead of 3.4 ms).
Please see http://www.nongnu.org/avr-libc/user-manual/group__avr__eeprom.html,  http://www.atmel.com/images/doc2578.pdf and table 9-1, pp. 35, http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf.
Cheers!

Re “largest gain is to have the EEPROM erased before the write”, note that AVR-level eeprom.h includes a comment,  “All write functions force erase_and_write programming mode”, so having EEPROM erased before the write entails coding EEPROM routines from scratch.  ¶  To some extent, separating erase and write precludes possible time savings from not rewriting cells with unchanged value.

The ATmega2560 needs 4.5V to run at 16MHz. Newer chips allow a lower voltage and also write faster to EEPROM. How many bytes do you need to write ? Arduino has a function to skip the bytes that are the same: https://www.arduino.cc/en/Reference/EEPROMUpdate
Perhaps there are things that you can do in software, to prepare for an emergency backup.
When storing data in EEPROM, you could write it with a checksum, and have the data two times in EEPROM.


text:
Using Arduino as a pc remote controller
I would like to create a simple remote controller (IR) with my Arduino Nano that would control my PC. (Volume up/down, stop, play and that sort of things...)
I have no problem with creating 'hardware part' and Arduino script, that would send commands through serial as a reaction to IR signals.
I can imagine python script that would react to commands received on the serial port.
My problem is: "How can I detect on which port should I listen to?" What is the right way to do it?

What operating system is on the computer?

And following a different route, could you have the device  emulate a USB keyboard? Many Arduino-like devices can do that. There are standard keys for play, volume etc.

@MarkSmith The arduino Leonardo has that ability, though I have never used it, and cannot speak to it's functionality.

Both Linux and Windows I guess, though Windows will be the preferred one.

i used node.js to monitor the serial port. based on the it codes coming in, it would execute small EXEs made with autohotkey to press keys/combos like VOL_UP.

@dandavis Thanks a lot. I can do that with python as well, only question is, how does the script which port to listen to... :(

well, when i re-assigned the "ftdi"'s COM port in windows, it stuck as COM10, even after rebooting, so that part was easy for me. there might be better ways, that's just what i got running one sunday...

@dandavis I ended up hoping that the COM port will stay the same. (If not, really easy to change port in python script)

Since I can not commemnt due to low reputation, I'm "commenting" here.
You can search for LIRC and WinLIRC


text:
Trying to move a stepper motor back and forth
So, I am trying to move a stepper motor through a halfway revolution (1024 steps), and once that is completed, have it move back and forth by about 100 steps in either direction.
I am having some trouble with this though, because while it will move in one direction, it will not move in the other.
void setup()
{
    stepper1.setMaxSpeed(1000);
    stepper1.moveTo(1024);
    stepper1.setAcceleration(100);
    Serial.begin(19200);
    while(!Serial);
}

void loop()
{
    stepper1.run();
    static int ctr = 0; //counter value to store how many times the back and forth motion has occured
    if(stepper1.currentPosition() == 1024){
      backMotion(stepper1.currentPosition());
      forthMotion(stepper1.currentPosition());
      ctr++;
    }
//    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
//      forthMotion(stepper1.currentPosition());
//    }
}

void backMotion(int value){
    int current = value;
    int back_distance = current - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion(int value) {
  int current = value;
  int forth_distance = current+200;
  stepper1.moveTo(forth_distance);
}

So, when I call the forthMotion function right after the backMotion function, it will just move forward. Which makes no sense to me. Shouldn't it be moving backwards, and then forwards in an infinite loop?
Because it will hit 1024, go back to 824, hit 1024 again, and so on and on...
Also, when I call the backMotion function, isn't the Arduino code supposed to be blocking in that, nothing else gets executed while that is running?
Edit: The code seems to work when I uncomment the if statement in the loop function.

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.  Your current snippet does not reveal which libraries you are using or how you declared and initialized the stepper1 object.  Anyhow, please edit your question to include that information via an MCVE.

Looks like you are missing a few  stepper1.runSpeedToPosition();

@MikaelPatel - why do I need the runSpeedToPosition function?

The manual says "Runs at the currently selected speed until the target position is reached". You might want to give the stepper some time to complete the operation. http://www.airspayce.com/mikem/arduino/AccelStepper/MultiStepper_8pde-example.html

You also need to define what "stepper1" is in your scope.

I guess the solution might be this:
in back motion
void backMotion(){

    int back_distance = - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

In forward motion
void forthMotion() {

  int forth_distance = 200;
  stepper1.moveTo(forth_distance);
}

In loop
void loop()
{
    stepper1.run();
    static int ctr = 0; //counter value to store how many times the back and forth motion has occured

    stepper1.moveTo(1024);
    while(ctr < 30){

      backMotion();
      delay(500);

      forthMotion();
      delay(500);
      ctr++;
    }
//    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
//      forthMotion(stepper1.currentPosition());
//    }
}

Your main code will be like this
void setup()
{
    stepper1.setMaxSpeed(1000);
    stepper1.moveTo(1024);
    delay(3000); // wait till stepper gets to destination
    stepper1.setAcceleration(100);
    Serial.begin(19200);
    while(!Serial);
}

void loop()
{
    stepper1.run();
    static int ctr = 0; //counter value to store how many times the back and forth motion has occured

    while(ctr < 30){

      backMotion();
      delay(500);

      forthMotion();
      delay(500);
      ctr++;
    }
//    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
//      forthMotion(stepper1.currentPosition());
//    }
}

void backMotion(){

    int back_distance = - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion() {

  int forth_distance = 200;
  stepper1.moveTo(forth_distance);
}

Steppers don't typically have feedback about their position (as opposed to servos). Normally you're just telling a stepper how much and how quickly to rotate. As opposed to servos, which you tell which position to rotate to.
Are you sure you're using a stepper?

Nothing in the posted question supports your theory.

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


text:
Arduino LED Dimmer Proportionate to Ambient Light
I am trying to get an LED dimming reversely proportionate to natural light level in a room.
So as the sun rises, the LED dims and vice-versa.
I am using the standard LDR+ 10k Ohm resistor divider, an LED, and an Arduino Leonardo Clone.
The issue is, regardless of the values I adjust in map(), it does not change the flickering rate or brightness of the LED.
What range of map shuold I be using?
The LED ought to shut off while the LDR takes a reading.
I have two variations of the code; one uses PWM, the other simulates PWM using delay()
Here are my sketches:
/set pin numbers
//const won't change
const int ledPin = 1;   //D1 the number of the LED pin (OR to MOSFET input wire for controlling high power LED
const int ldrPin = A0;  // A0 the number of the LDR pin
//10K ohm resistor as voltage reference.

void setup() {

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
}

void loop() {
  digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
  int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
  // KEEP LED OFF TIME BASED ON AMBIENT LIGHT LEVEL...
  int dim2 = map(ldrStatus, 0, 1023, 500, 0); //OFF FOR UP TO 0.50 seconds.
  digitalWrite(ledPin, HIGH);
  delay(dim2);

   }

Sketch two:
//set pin numbers
//const won't change
const int ledPin = 1;   //D1 the number of the LED pin (OR to MOSFET input wire for controlling high power LED
const int ldrPin = A0;  // A0 the number of the LDR pin
//10K OHM resistor as voltage reference.

void setup() {

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
}

void loop() {
  digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
  int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
  int dim = map(ldrStatus, 0, 1023, 255, 0);     // scale it to use it with the LED (value between 0 and 255)
  digitalWrite(ledPin, dim);               //Flash LED at that rate to adjust brightness.

   }

Why do you think you should be using digitalWrite()?

I was mistaken. I switched it to analogWrite() , but no changes happened.

You need to use PWM pin, like pin 3, but  different sets for different Arduinos.

For certain Arduino models, the PWM pins are different. For the iteaduino lite, a usable PWM pin is pin D5.
Here is the code updated to use D5 instead of D1, which lacks PWM abilities:
//set pin numbers
//const won't change
const int ledPin = 5;   //D5 PWM the number of the LED pin (OR to MOSFET input wire for controlling high power LED
const int ldrPin = A0;  // A0 the number of the LDR pin
//10K OHM resistor as voltage reference.

void setup() {

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
}

void loop() {
  digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
  int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
  int dim = map(ldrStatus, 0, 1023, 0, 255);     // scale it to use it with the LED (value between 0 and 255)
  analogWrite(ledPin, dim);               //Flash LED at that rate to adjust brightness.
  Serial.println(dim);
   }

There is still flickering, but that is to be expected. map() ranges can be adjusted to set when the LED will be fully off or on.
It is still unclear how to allow the light sensor to take a reading while the LED is OFF, then power back on rapidly enough to not have a visible flicker.
If anyone has thoughts on that, it would be appreciated!
Thanks everyone for helping.

analogRead() is slow. You should consider using the ADC at a lower level if you need improved speed.


text:
Arduino Yun Analog Read Problem
I am having some major issues with my Arduino Yun.
When attempting to read a value from the analog pins, the Yun is giving me incorrect constant values.
I have attached everything to a common ground, and I am supplying 3.3 volts to the A0 pin on the Yun.
The weird thing is, the pins all give constant values in ascending order, no matter what is connected to them, or if nothing is connected at all.

A0 - 18
A1 - 19
A2 - 20
A3 - 21
A4 - 22
A5 - 23

The code I am running is a very simple script.
float i;

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

void loop() {
  i = A0;
  Serial.println(i);
  delay(1000);
}

You are not reading from any analog pins. You are just printing out the digital pin number of the analog pin.
Look at some basic examples on how to read analog values.
/*
  AnalogReadSerial
  Reads an analog input on pin 0, prints the result to the serial monitor.
  Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  This example code is in the public domain.
*/

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

oh my goodness, wow I feel like an idiot;
I had it set up with "analogRead" at first but I must have removed my code without noticing it. At first, I was reading analog values just fine, then this happened out of no where
Anyhow, thank you!


text:
External Flash Memory File System
I'm building a weather data collector and I want to be able to dump that weather data somewhere. I've considered the options, and since I'm going to be storing a fairly small amount of data (in the megabyte range) I don't want to use SD cards (also SD cards are expensive). I've heard of use of NAND flash memory chips (like the W25Q32), and I was hoping that I could possibly interact with them in a simple way (since most ways require writing to each individual address). Is there possibly a way to build a file system within one of these small flash memory chips and interact with them as simply as interacting with an SD card?
TLDR: I want to interact with a flash memory chip easily to store basic ASCII data

While you can put a filesystem on an SPI flash, it's generally a bad idea, as many filesystem map poorly to the block-erase nature of NOR flash, and filesystem APIs don't well represent access carefully tuned to the needs of flash.  If you do, use a fileystem optimized for flash.  Probably better and simpler though to organize your writes as a linear journal of data.

Could you set up a server with a simple web application, put a WiFi module on the Arduino, and have it store data in a database?  Could use apache or IIS if your on windows.  set it up to run PHP.  Set up a MySQL database.  Have a page that accepts GET variables of the data and insert it into the database.  You could set up another page to access/search/analyze  the data.

@rpmerf I've done this before, but it consumes FAR too much power and I plan to put these small weather data collectors in places away from infrastructure.

Why not use the raw device commands and write blocks? Does your sketch really need a file system, i.e. more than a few files?

There are a few Arduino boards out there that have RTC, SPI Flash and RF-modules, and are real low power design. See for instance Anarduino http://www.anarduino.com/miniwireless/, or Moteino https://lowpowerlab.com/guide/moteino/.

the esp8266 lets you store a few MB as a SPIFFS file system, other boards probably offer the same.

@ChrisStratton do you maybe have a link to how to do it anyways?

@CarrotM An SD card doesn't implement a file system either.  In both case you have to implement the file system in your software on top of the storage device.  The inefficiency in doing so is particularly a bad idea on small devices, but if you really want to do it, the process would be comparable to the filesystem code you would use on top of an SD card.

I2C is common for EEPROM chips and can be accessed with a minimal amount of coding effort using the Wire library.

Have you considered FRAM (Ferroelectric RAM)? It comes in both SPI and I2C formats.  I got my first units from Adafruit. You can read and write as much as you want it has a very long life below 85C. I believe they have some application software on there site.

This lib offers a means of reading and writing ASCII arrays to flash devices. This would be a simple solution for such a data logger requirements. It's ASCII orientated.
https://github.com/schinken/Flash

I don't think you need a file system: that is usually needed when you want to manage many files. Your weather data log sounds like a single file.
What you seem to need is to access EEPROM as a stream, exactly like you would for an open file. There are stream wrappers around some EEPROM libraries, e.g. this one for ESP. I suggest you check it out and see if you can adapt it to the EEPROM library you use.

There is a way to do this. Using a $2 adaptor from eBay, you can hook it up to a micro sd card. An sad card for $4 can store 128mb of data, which is plenty for you.
Arduino Storage Tutorial with weather
128mb Micro Sd card

This does not answer the question which was asked.  The poster already seems familiar with what you propose, and is seeking to do something else.


text:
How to connect 70 analog sensor to a single Arduino (Mega or Uno) device?
I was working on a project in which I need to collect soil moisture data for a farm. For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino. But, this is not possible as there are just 6 analog pins on Arduino Uno and 16 analog pins on Arduino Mega. I have restrictions on the number Arduino that I can use that is just one due to monetary constrains.
        The data would be collected at a delay of 5 seconds. The data gathered would be stored on SD card module which would be analyzed later.
      Any suggestion on how I can collect data from 70 analog sensors on a single Arduino would be highly appreciated. Are there any alternatives that I can use in place of Arduino? I heard that we could do something with AVR  atmega Microcontroller, am I correct? I don't know how to use Microcontroller; any useful resources will be highly appreciated. Thank You.

There are fairly inexpensive chips called "analog multiplexers" which let you choose one input out of a range (8 or 16 is typical). You could take the reading, then switch to a different input, and take another reading.
I have a page about analog multiplexers.
Example of it in operation:

In this example you have 8 inputs, and by setting the A/B/C pins appropriately, one of the 8 is selected and appears at the O/I pin (output/input).
There is a 16-channel model as well. I see the 16-pin chip (74HC4067) available on eBay for $US 1.26 right now. You can get four of them (which would give you 80 inputs) for $4.88.
Also see the Wikipedia article on multiplexers.

For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino.

Yes, well how will these sections get their data into one place? That is probably the bigger problem.
You may need to use a lengthy cable using RS485 (balanced signals) or maybe cheap radio transceivers.
Trying to use a "single Arduino" on what might be quite a large farm is the issue. It's not the Arduino's fault. You have to have some way of sending the data from the further points to where it is to be collected.

@ Nick Gammon: Thank you. Your answer was helpful. Relating to collection of data in one place, I was planning to use wires which will transfer the data to the Arduino. What problem will be caused by this? The idea of using radio transceivers is great. As I am planning to do this on a large scale, the major cost of my plan comes from the soil moisture sensor (as they are used majorly) . Now if I use a transmitter, I need to use it for all the soil moisture sensors which are doubling my budget.

If you are reading analog, extra wire adds extra resistance, which throws off your readings.  Look into the ESP8266.  WiFi module that costs about $5 at the cheapest and has a 1v analog input.  You can drive it off batteries without an Arduino.

Quite right, although the OP seemed to want to keep the device count down. It seems odd to only have a "single Arduino" but to go and buy 70 x ESP8266. However that may well be the best solution. :)

You should use some cheap chips to collect the data and use only one with big capacity to finally combine and process the data further.

Consider using a cheap small Arduino to build a "base module" that can do some of the tasks needed, build a bunch of them and hook them up to a R485 bus, and have one master Arduino control them all. That would be a much more flexible and expandable system. The cheapes Arduinos cost around 10$. If you build your own you could probably do it even cheaper.

Source:
[1] http://forum.arduino.cc/index.php?topic=73861.0
(quote)
[2] https://arduino-info.wikispaces.com/RS485-Modules (bus)

Given that good moisture sensors are going to be an order of magnitude more expensive than the logger, I'd suggest that you are giving yourself more problems than it's worth to try to connect that many sensors to the same unit. A Pro-mini based logger rarely comes in >$25. Even though we can connect that many one-wire sensors to a single logger ( https://thecavepearlproject.org/2015/03/01/using-ds18b20-sensors-to-make-a-diy-thermistor-string-pt-1-the-build/ ) it's not a good idea from the perspective of the amount of data that is lost if you have a single point failure. Generally we only put 10-15 sensors on any one unit, and we try to deploy them in "parallel" sets so that if one multi-sensor unit does fail, we loose spatial resolution, but still have enough information to work with.


text:
How do I write and read internal EEPROM?
I am working on an Arduino Mega 2560. I want to read and write the internal EEPROM.
Can I use EEPROM.get()/EEPROM.put()?
I want to store 3 things in EEPROM:

Boolean status.
String password: length 5 digits.
String Mobile number: length 10 digits.

Yes. Is your question how you can do it?

the easy way to get that working is to simply read/write them all each time, and use a char as a delimter, like "~", to split the loaded values.

How do I write and read internal EEPROM? Can I use EEPROM.get()/EEPROM.put()?

Yes, the Arduino Reference for EEPROM contains an example of what you are asking for. Below is a simple rewrite of the example for EEPROMGet for your info.
struct MyObject{
  bool status;
  char password[6];
  char mobileNumber[11];
};

void setup()
{

  int eeAddress = 0; //EEPROM address to start reading from

  Serial.begin( 9600 );
  while (!Serial) ;

  MyObject customVar; //Variable to store custom object read from EEPROM.
  EEPROM.get(eeAddress, customVar);

  Serial.println(F("Read custom object from EEPROM: "));
  Serial.println(customVar.status);
  Serial.println(customVar.password);
  Serial.println(customVar.mobileNumber);
}

For more details and examples see https://www.arduino.cc/en/Reference/EEPROM.
Cheers!

Avoid the 'String' object, use a character array of fixed length. You might want to add one extra byte for the zero-terminator. Put everything in a 'struct' and then you can use the EEPROM.get() and EEPROM.put() to read and write the complete struct. I prefer a struct to keep the data from EEPROM together. That makes it easier to add a checksum and a version number for the data. When something is wrong with the data from EEPROM then default values could be used.
Instead of a struct, you can also read and write the seperate items. The EEPROM.get() and EEPROM.put() should be able to use a character array of fixed length.


text:
What's the difference between analogWrite and digitalWrite?
As the title states. What's the difference between the two?
analogWrite(pin,0-255) vs digitalWrite(pin,LOW-HIGH)

I don't mean to be rude but what was confusing about this in the documentation at arduino.cc or included with the IDE?

digitalWrite will set the specified pin to one of two states - HIGH/LOW, which equate to 5v (3.3v on some boards) and ground respectively.
analogWrite can vary by the type of output used.
If applied to a PWM pin - it will set the pin to a periodic high/low signal, where the percentage of the signal spent high is proportional to the value written.
for example  -
    analogWrite(PWMpin,255)

Will be HIGH 100% of the time, while
    analogWrite(PWMpin,127)

Will be HIGH 50% of the time, and LOW 50% of the time
When applying analogWrite to a DAC pin (available on some boards, like the DUE or MEGA)
analogWrite will actually cause the specified pin to output a voltage level proportinal to the specified analog value
For example, on the Due, with maximal voltage of 3.3v and a default analog resolution of 8 bits -[0:255]
    analogWrite(DACpin,255)

Will cause the specified pin to output 3.3v, and-
    analogWrite(DACpin,127)

Will cause the specified pin to output 1.35v

No, there is no DAC on the Mega.

you are correct, answer edited to reflect this.

Great. I took the liberty to make the edit more concise.

I believe there is a "maxanalog" define or constant, to provide better compatibility with other platforms. The esp8266 has an analogwrite that can range from 0 to 1024. *I've scratched some hairs out trying to find why my RGB led controller wouldn't be as bright with the same code, thought it was due to the difference in power or voltage, but I used an MOSFET with suitable (gain?) factor. It was simply on for (1024/256) of the time.

analogWrite(): The analogWrite() method sets the value of a PWM output pin. The analogWrite() is on a scale of 0 - 255, such that analogWrite(255) requests a 100% duty cycle (always on), and analogWrite(127) is a 50% duty cycle (on half the time).

Syntax: analogWrite(pin, val)
Where,
pin: the PWM output pin number.
val: int value of duty cycle between from 0(always off) to 255(always on)
Example Code:
int outLed = 10;  //LED connected to digital pin 10
int value = 0;    //variable to store the read value
int analogIN = 3; //input pin

void setup()
{
  pinMode(outLed, OUTPUT); // set the PWM pin as OUTPUT
}

void loop()
{
  value = analogRead(analogIN); // read the value of analogIN (values between from 0 to 1023)
  analogWrite(outLed, value/4); // sets the read value on outLed (values between from 0 to 255)
}

digitalWrite: The digitalWrite() method sets the value of a digital pin as HIGH or LOW. Here, 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.
Syntax: digitalWrite(pin, val)
Where,
pin: the pin number
val: HIGH or LOW
Example Code:
int ledPin = 13;                // LED connected to digital pin 13

void setup()
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(ledPin, HIGH);   // sets the LED on
  delay(1000);                  // waits for a second
  digitalWrite(ledPin, LOW);    // sets the LED off
  delay(1000);                  // waits for a second
}

digitalWrite sets the output pin to either LOW or HIGH (where those voltages depend on the Vcc of the processor. For a Uno or Mega that would be 0V or 5V (or close to it).
Here's a screenshot of digitalWrite (LOW):

That is, the output pin is at 0V.

Now for digitalWrite (HIGH):
The output voltage is 5V.

analogWrite really should have been named PWMwrite since it configures the processor timers to output PWM (pulse-width modulation).
Let's try analogWrite(1):

You can see that the voltage level is 0V most of the time, and going to 5V for short periods. You also see that the frequency is 490 Hz which is what the reference page for analogWrite says it will be.

Zooming in:

The output is high for 8 µs, which is exactly 1/256 of 2048 µs which is the period of the timer. So, we have a duty cycle of 1/256 (0.39%).

Let's try analogWrite(127) - half-way from 0 to 255:

Now you can see that the output is HIGH exactly half the time, and LOW the rest of the time.

Let's try analogWrite(254):

This is the opposite of analogWrite (1). The output is HIGH all the time except for a brief period. Zooming in:

Now the output is off for 8 µs - compared to the earlier image where it was on for 8 µs.

analogWrite (0) is the same as digitalWrite (LOW).
analogWrite (255) is the same as digitalWrite (HIGH).
This is proven by the relevant code in wiring_analog.c:
if (val == 0)
{
    digitalWrite(pin, LOW);
}
else if (val == 255)
{
    digitalWrite(pin, HIGH);
}

Summary
analogWrite basically configures the hardware timers to output PWM. Once you do that the timer hardware outputs the requested duty cycle (from 0 to 255) where 0 is always off, 255 is always on, and some value inbetween gives you PWM (pulsed output).

For more information about the timers see my page about timers.

digitalWrite sets the pin to an high or low value that remains at exactly that value until digitalWrite is called for that pin again.
analogWrite sets the pin to have an oscillating value which has a pulse length based of the duty cycle specified as the second parameter.
So:
digitalWrite (5, HIGH);    // Pin 5 goes high
analogWrite (6, 127);      // Pin 6 oscillates regularly between 0v and 5v (or 3.3v) at about 250Hz.

analogWrite():
Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.
For details visit: https://www.arduino.cc/en/Reference/analogWrite
analogRead():
Reads the value from the specified analog pin. The Arduino board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega), 10-bit analog to digital converter. This means that it will map input voltages between 0 and 5 volts into integer values between 0 and 1023. This yields a resolution between readings of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per unit. The input range and resolution can be changed using analogReference().
For details visit: https://www.arduino.cc/en/Reference/analogRead

digitalWrite set the specified pin to one of two states - HIGH/LOW
Where, HIGH = 5 V and LOW = 0 V
analogWrite Set the PWM value of PWM pin
(In Arduino UNO, PWM pins are 3, 5, 6, 9, 10, 11)
It will set the pin to a periodic high/low signal.
analogWrite(PWMpin,255)

Will be HIGH 100% of the time, while
analogWrite(PWMpin,127)

Will be HIGH 50% of the time, and LOW 50% of the time

So what's the difference between analogWrite(X, 255) and digitalWrite(X, HIGH)? Probably nothing, except perhaps the processor has to do some extra stuff to work out that it doesn't need to use PWM, and also style.

Another subtle difference between analogWrite(pin, 255) and digitalWrite(pin, HIGH) is that digitalWrite requires you to set the pin to output using pinMode. analogWrite sets the pin to output on each call, which makes it slower and might ruin the code which uses the same pin alternatively as input and output, and relies on the fact that writing to the input pin using digitalWrite doesn't switch it to output.


text:
Arduino Sdcard database Library
Im using Arduino connected to an SD card and PIR sensor , and based on the inputs from the PIR sensor the data needs to be written on the sd card , It is done , but for retrieving the data from the SD card is there any library for arduino ? Ive seen Extended Database library ,since im retieving huge amount of data from the SD card and i should be able to do Lots of sorting operations based on the CSV values in the file , So can i do Sorting operations in  Extended Database library from an Sd card ive seen the Examples but it doesnt have any sorting operations ,Is Querying data from the SD card using this library is Possible ?ie)Selecting data Based on some Conditions even if it can be done is there any tutorial ? Or is there any other alternative Library? for this purpose . Thank You

When you are reading the data are you reading it on a PC or Arduino?  If its a PC, you are asking the wrong forum.  If its on an Arduino how are you going to load 32GB of data into 32kB of memory?

@Matt  No im loading the data from SD card into arduino that too after sorting and selecting a particular record and loading it into arduino


text:
Problem regarding Arduino & GSM module kit
I am using the following program to receive messages from a GSM module.
As we start our kit, we received two messages "main door is open" and "store room is open". (Depending upon sensor position)
This program is run properly, but the problem is that it repeats the message after some time. It does not depend on time.
Suppose our store room is closed. I receive this message on my given mobile number, but after some time two "the store room is open" messages are received and after this message immediately the message "received store room is closed". (means it sets sensor to its initial mode i.e. closed) Same problem is happening with this main door.
My kit contains an Arduino UNO board, GSM module SIM800 and two limit switches (one for the main door and second is for the store room)
I keep my both sensor and Arduino board distance over 17 meters by using CAT5e cable.
My code:
const int Main = 7;  // pin define for main door sensor
const int Store = 8; // pin define for store room sensor
const int Main_led =  13;  // indication for main door sensor
const int Store_led =  14;  // indication for store room sensor

void setup() {
  Serial.begin(9600);
  pinMode(Main_led, OUTPUT);
  pinMode(Store_led, OUTPUT);
  pinMode(Main, INPUT);
  pinMode(Store, INPUT);
}

void sendMessage(char *text) {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print(text);
    Serial.write(0x1A);
    delay(5000);
}

void loop() {
  static int oldState1 = -1;
  static int oldState2 = -1;

  int buttonState1 = digitalRead(Main);
  if (buttonState1 != oldState1) {
    digitalWrite(Main_led, buttonState1);
    if (buttonState1 == HIGH)
      sendMessage("Main Door is closed");
    else
      sendMessage("Main Door is open");
    oldState1 = buttonState1;
  }

  int buttonState2 = digitalRead(Store);
  if (buttonState2 != oldState2) {
    digitalWrite(Store_led, buttonState2 );
    if (buttonState2 == HIGH)
      sendMessage("Store room is closed");
    else
      sendMessage("Store room is open");
    oldState2 = buttonState2;
  }
}

Do the LEDs reflect the messages when you get these odd messages?  It sounds like there is a "glitch" in the sensor data, the equivalent of a switch bouncing, if so add some de-bouncing code.  When a sensor reports a change in state, wait one second (ish) before reporting the change in state.


text:
Scheduled loops using same function
I am using an Arduino due and have multiple schedules running at the same time. I am using this Library.
I have a function that 3 different loops use. Two of the loops are driven by user interaction so timing is not possible. The function does reset global variables and I would have no issue with the variables being reset multiple times as it wouldn't cause any problems for me.
What I was wondering, on the very slim chance that two loops called the function at the same time, is it possible for the loops to modify the same variable at identical times?
My understanding of the scheduler would lead me to believe that the scheduler will only yield to another loop after it has completed a line of code and thus the to instructions to reset the global variable could not happen at the very same time, just extremely quickly one after the other.
Would this be a correct assumption?

From the [Arduino Reference][1] pages:

This is a cooperative scheduler in that the CPU switches from one task
  to another. The library includes methods for passing control between
  tasks.

[emphasis mine]
Which means that your code decides when it yields control to another scheduled loop (by calling yield(). At a quick glance, it appears that it also yields by returning. So yes, your assumption is correct.

Awesome that will work, I just wanted to ensure they ran 1 by 1 so that no corruption of global data could occur.  Great news, thanks JRobert

It is a simple schedular. It only changes to another task when yield() is called. The delay() function uses yield() and a lot of code and libraries use delay().
That means that if you code does not contain a delay() then you need to call delay() or yield() now and then, or other tasks will never execute.
It is probably safe to use the same function, but every time a delay() is used, an other task could run or another task will continue from there.

Awesome, thanks for that Jot looks like It will work for what I need.

I'm testing that Scheduler library at the moment. It is very simple, but useful. The stack for the new tasks are allocated in the heap. The original Arduino loop() function uses the normal stack. It might therefor be better to do big things like Ethernet in the Arduino loop() and do smaller things in the created tasks.


text:
I would like to know the ATMEGA wiring to Arduino

I would like to know which pins are connected to the output of the Arduino.
For example:

PC6 is digital 12
PB5 is analog 13
etc...

Image searching for the term "arduino uno pinout" reveals a better pinout diagram.

I prefer this image, as it combines the arduino pin numbers and PWM capabilities, with the names and functions from the datasheet.

I usually preferred this image. It very useful for me every time.

I think this is the diagram you are seeking.

thanks for your help everyone
just another question
is there another program to implement the code to the arduino
other than the official arduino  program
i need a program where i can debug and put break points like mplab
thanks for your help

Start a new question...

Or you could simply look at the Arduino Uno schematic, which has everything you should ever need to know.

Updated: Pins PB6 & PB7 while available as I/O pins (D6 & D7) are committed to the external crystal on this board and not brought out to the connectors.

That is not true: you cannot find a connector for XTAL for instance.


text:
HC-SR04 and LCD Circuit Problem
I was designing a circuit that measure distance using HC-SR04 and display it into a LCD.This circuit also have 4 LEDs indicator.But i have a problem.The LEDs doesn't turn on.The LCDs backlight turn on, but it didnt display anything. Btw, i'm using LCD with I2C module.Here is the code:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
#define trigPin 6
#define echoPin 7
int led5cm = 8;
int led7cm = 9;
int led10cm = 10;
int ledoor = 11; //ledoor means LED Out of Range
void setup() { // put your setup code here, to run once: lcd.begin(16,2); lcd.setCursor(0,0);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led5cm, OUTPUT);
  pinMode(led7cm, OUTPUT);
  pinMode(led10cm, OUTPUT);
}
void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
  if (distance <= 5)
  { lcd.println("Distance < 5 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, HIGH);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  } else if (distance >= 5 || distance <= 7) {
    lcd.println("Distance < 7 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, HIGH);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
  else if (distance >= 7 || distance <= 10) {
    lcd.println("Distance < 10 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, HIGH);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
  else if (distance > 10) {
    lcd.println("Out of Range");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
}

Can you please help me solve this problem? Thank you very much!!

All the code in a single line is unreadable. Properly format it. And I don't see any power connections or current limiting resistors for the LEDs.

I'm sorry, i maybe had mistake when pasteing the code.I will edit it.Yes, im forget to add the resistor in the schematic.Only in schematic.

Did you first check if distance was right using Serial.print

No, i'm using LCD screen.Not serial monitor.So, it will be lcd.print not Serial.print right?

gre_gor I double checked the code.The code are properly formated

You have this instantiator for LiquidCrystal_I2C:
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
Where did you get that? Which library exactly are you using? A common one I found only uses 3 values -- I2C Address, Columns, and Rows. What size is your LCD?

+jose can u c I'm using library written by F Malpartida.Link https://arduino-info.wikispaces.com/LCD-Blue-I2C

@deadguy88 I don't know what you are seeing, but this is not properly formatted.

That LCD library is intended for a module with the PCF8574* I2C IO expander. Please give more details about your LCD device.

@jose can u c Yes my LCD has PFC8574AT I2C IO.

Please show us more details about the I2C IO Expander on your LCD. Can you confirm that the pins on the IO Expander is connected to the pins set in your initialization call?
Basically, please re-write your question and/or schematic to show us more, as you have asked why the LCD doesn't display, but you have given nearly zero information about the LCD and how it's connected.
Also, you noted that the schematic omitted the pull-up resistors, but the only way we can help you is if what you tell us is accurate.

To make your LCD work, add code like the following in setup().  (Substitute appropriate values in place of LCDcols and LCDrows, or give them appropriate values via const int ... or enum { ... }; statements.)
  lcd.begin(LCDcols, LCDrows);
  lcd.setBacklightPin(3,POSITIVE); // Might not need this, since info appears to be included in lcd declaration
  lcd.setBacklight(HIGH);
  lcd.clear();          // Clear the display
  lcd.home();

To make the LEDs work better, you may need to change the || connectives in some of the if statements to &&.  An if condition with terms joined by ||, OR, is true if any of its terms are true; with terms joined by &&, AND, all of its terms must be true for the condition to be true.
For example, the condition (distance >= 5 || distance <= 7) is true if distance is 5 or more, or 7 or less; in other words, is always true.


text:
Custom DAC for Arduino UNO
I am currently following this tutorial on building a Simple Audio Player for the Arduino. I was about to finish the circuit only to realize that the required board is an Arduino Due and I have the Uno.
Because the Uno does not have its own DAC port, I was wondering what other options are available for me to accomplish the same thing while keeping the circuit as similar to the one listed in the tutorial.
Thanks

What's a Duo? Never heard of an Arduino called a Duo before...

My bad. I fixed it.

Ah, that makes more sense.

There are three basic ways of creating a DAC.
The simplest, though roughest, is to use PWM, then low-pass filter it.  Not perfect, but rough and ready. Only needs a resistor and a capacitor.
The highest quality way, though slowest for interfacing, is to use an external DAC chip. Fine for low frequency response reproduction, and the linearity is second to none. The MCP4821/2 is a popular choice (SPI connected).
The third option is to build your own DAC using an R-2R ladder. You can make an 8-bit DAC with very fast response by using all 8 pins of a single IO port (such as pins 0-7 on the Uno are bits 0-7 of port D). However the linearity of an R-2R ladder very much depends on how well matched your resistors are.
The R-2R ladder should be buffered with an amplifier of some form before driving a low impedance device like a speaker.
None of them are really great for audio work - for that you need a chip with much more processing power and memory, and a high speed digital audio interface, such as I2S, to interface a proper audio CODEC chip. Personally I use PIC32MZ chips for audio work.

The major problem you have is that the Audio library functions are specifically written for the ARM based Due.
You could certainly add an I2C 10 bit (Mono or Stereo) DAC chip to an Arduino Uno capable of producing stereo signals through an LM386, but you would have to re-write the Audio library to support that functionality on the Uno.

You can probably use the same circuit and the PWM "Analog" output of the Duo (after adding a low pass filter) to play simple tones, and maybe do something on the input side to allow you to change the frequency in response to some user input.
I don't think you'll get the Duo to read from the SD Card and play the audio simultaneously.


text:
Arduino Control TV over RS232
I have a LG TV(LG 32SL800 ZB), which has a RS232-Port for Control and Service.
And I am wondering if I could control this port with my Arduino (NODE-MCU) and a module like this one RS232 Board?
How could I then control the TV? This is the Manual for the TV at page 124 there are the commands how to control it, but how can I send them?
My last question is, how long can the cables from the arduino to the module be? They have to be about 2-3m long! Is that possible without any other hardware?

And I am wondering if I could control this port with my Arduino (NODE-MCU) and a module like this one?

Yes, you can, though choose a board based around the MAX3232 for a 3.3V MCU board.

How could I then control the TV? This is the Manuel for the TV at page 124 there are the commands how to control it, but how can I send them?

Exactly as they show in the manual. For example:
Serial.print("ka 0 01\r");

That would turn on every TV connected to the serial bus.

My last question is, how long can the cables from the arduino to the module be? They have to be about 2-3m long! Is that possible without any other hardware?

You can get away with no more than maybe 1 meter between the Arduino and the RS232 board. Keep that as short as possible. However between the RS232 board and the TV you can have up to 15 meters of cable.

I now have tried the commands! The "ka 01 00\r" which should turn on the TV works perfectly but any other command doesn't work?


text:
Global memory reduction when using SPI/SD
I want to use an SD card and when including the library both SPI.h and SD.h are included. Also later I want to use an external SRAM chip (probably using SPI.h as well). However, without the SRAM chip my sketch uses around 849 bytes of global memory, where I expect most of it taken by the SD.h / SPI.h combination. Without these includes only 9 bytes are used.
How can I reduce the amount of global memory (still I want to use the SD and SPI interface)?
Edit:
According to a remark below 512 bytes are used for the SD so that explains mostly of the 849 bytes. And some additional questions:
Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes ...I only need to read a file (128 KB) and copy it to an SRAM (external). And I don't mind if it will be transferred in 16 byte blocks. Actually, I could get rid of the buffer at all after the SD to SRAM copy.
My ultimate goal is to leave 1KB + some dynamic memory (for function call stacks/local variables). However, finally I need to move to the Arduina Mega anyway, but was hoping I could already start the project with my Arduino Uno.

First you need to understand the terms and measurements. If your memory "usage" figure comes from the Arduino IDE, then it does not include dynamic memory at all.  Only a very careful modeling or output from actual execution could measure that.  In terms of the static allocations you are probably measuring, buffers would be a likely suspect, not only for the those libraries, but also if you make use of Serial, etc.  If you want more precise control or optimization you may need to replace libraries with your own tuned code.

Sorry with dynamic memory I mean the SRAM usage internally within the Arduino Uno. The global data is 849 bytes. And the remainder (1150 bytes or so) is used for dynamic allocation..
And yes, the buffers is indeed something that needs to be tweaked. What would be the best way? To copy the library files to be changed within the project and use those instead of the original ones... I don't like the change the generic library files since it will affect all projects I might do in future.

What is your ultimate objective? At present you are using less than half the available RAM. What is the problem exactly? Any SD card interface is likely to require a disk buffer (probably 512 bytes) so you won't get much below that.

Thanks for your good question and remark about the SD buffer. I will edit the question.

Note that there are various ARM chips that cost no more than an ATmega but have substantially more RAM.  Some of them even have Arduino ports of various maturity.

@ChrisStratton I know (I thought they were more expensive though), but I think they use 3.3 V and I am really a beginner electronics wise, also I probably need to rely on common libraries/lots of support and for the Arduino Uno there is more 'help' available. Also since it will be my first real project I want to know what I can get maximum out of a (simple) Arduino before making it too 'easy'.

Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes

The Arduino SD library uses an internal file block caching (512 bytes) to improve performance. It is possible to read directly from a file block on the SD but that would be very slow. Every 16 bytes read would require reading from file block, discharging all preceding bytes (as the file block is read serially), reading the 16 bytes, and then stopping the block read.
There are a few tiny SD libraries that actually use this technique. See for instance Petit FAT File System http://elm-chan.org/fsw/ff/00index_p.html
Another technique is to block copy from the SD directly to the external SRAM without going through additional buffers. This requires a refactoring of the SD library so that it uses a callback instead of the internal buffer.
Cheers!

Thanks for the answer. In that case I will keep the 512 bytes (it shouldn't be a sub-project just to overcome this problem.  However, if the Petit FAT works, maybe I can use it temporarily.
The last sounds interesting, but might be a bit tricky but workable.
Or maybe I try to dynamically create the 512 byte buffer and just remove it after use (which is after the copy).

To allow BMP images (from SD) to be written to LCD without a lot of buffer copying I introduced a callback in the Cosa Canvas handler in the  form of a virtual member function. Please see https://github.com/mikaelpatel/Cosa/blob/master/libraries/Canvas/examples/CosaCanvasBMP/CosaCanvasBMP.ino for an example.

Thanks, I will take a look into that, very nice to have an example, it might be similar with buffer copying to an SRAM


text:
Time delay without using delay() and millis()
I am designing an industrial control panel using arduino. I have to use time delays as long as 10 seconds and since using delay() makes a halt in the controller I tried using millis(). But it is complicated and it will work only for 50 days. I want the system to work continuously without any maintenance and I need to control as many as 6 relays. So, I need a better solution (hardware or software based) to tackle this problem. How can I do this?

See How can I handle the millis() rollover?. In short: the correct way to handle the rollover is to write rollover-safe code, like in the standard example Blink Without Delay.

I use double loops. The outer loop is your entire delay time, (say, 10 minutes = 10,000 ms divided by the duration of the inner loop delays) and the inner loop is how often you need to check for a condition that necessitates calling some function, (maybe every 1000 ms) - so your halt times are determined by the inner loop delay.   And the outer loop can be used to update a display on a less-periodic basis.  The 50 day thing is not relevant.

i would "upgrade" to relays to latching, or at least driven by a 1-bit state machine, like an "SR Latch" that the MCU can read and write. That way, an MCU crash won't affect the relays at all.

You misunderstand the 50 day thing. Yes it rolls over after 50 days but that doesn't mean it stops working. As long as you program your comparisons correctly (something people often don't do in online examples) then all it means is the maximum delay you can have is 50 days.

all it means is the maximum delay you can have is 50 days. it is pretty trivial to extend millis beyond 50 days. so yes, you can generate much longer delay sout of millis().

Well yes, but without writing your own code to extend it the maximum is 50 days. And anyway millis() is not that accurate, so anything more than an hour or two you really need to use an RTC.

You may have to find a library that eases the use of what you're trying to do.
I made some timer library, called SeqTimer.
You can find it here: Link
or use the Arduino library manager, it's there too.
It's a simple library using millis(), without callback, so it's pretty straightforward.
If you need more advanced timer, search for 'timer' for example in the arduino library manager, there's a bunch of libs related to timers.
Yet, I'm not really sure what you mean by:

work only for 50 days

The function millis () returns an unsigned long, which is the number of milliseconds since the processor was reset (until it overflows).
Example:
unsigned long startTime = millis ();
Since there are 2^32 bits in an unsigned long it can count from 0 to 4294967295.
Computing this in terms of days we have:
2^32 / 1000 / 60 / 60 / 24 = 49.710 days
So, the number returned will overflow (go back to zero) after around 49 days (almost 50 days, as the reference page says).

That's what I thought you meant. In fact, millis() will rollback to 0, so it shouldn't be a big problem. Anyways, SeqTimer or any other lib would work for you.

When you do "millis() - previousMillis" it will always return the difference between the two, even at the very moment millis() does a rollover. Both variables must be unsigned long to make it work. When only short delays or intervals are needed, it is allowed to use less bits of millis(), for example 16 unsigned bits. However, I think it is easier to always use 32-bit unsigned long when using millis().

I'll probably change to 32b compare someday, yet I did tried the lib for a while with the simili rtc sketch with a serial spy displaying frames reception time, it kept working on the whole test, and derived in time just as it should, as not using a timer interrupt.

Might be a solution to the former question. Using a timer interrupt, with a correct prescaler, and maybe counting some to get 10s before launching action.

it will work only for 50 days.

it overflows in 50 days but comparisons based on it can be good even if it overflows. you just need to recognize the overflow and program accordingly.
so millis() is perfectly fine for what you are trying to do. no need to reinvent the wheels.

You wrote: “you just need to recognize the overflow and program accordingly”. If you really need to recognize the overflow, you are doing something wrong.


text:
Pin identification for a salvaged LCD
I salvaged an SPI interface LCD from an old CDMA telephone. It seems it uses SPI to display something on the screen. The pins marks are DATA, CS, SCLK, BL, VDD, GND, LED, A0, and RES. How do I wire it up to an Arduino?

i would try some of the LCD libraries, the ones people use for 5110 displays.

They seem pretty self-explanatory. Data, sclk and cs are normal SPI MOSI, CLK and CS. A0 is probably equivalent to C/D. RES is reset - tie high to run. Power and ground are obvious. The others look related to the back light.
However... How are you going to operate it? Do you know the SPI instructions to send? They will be specific to the display, so without a datasheet you're pretty much stuffed.

It's unlabeled, the silicon driver chip is on the glass covered by black silicone. I will try some LCD libraries. If there's a resolution mismatch, I will have to modify the library. A0 (and BL)is the only reason why I asked. Thank you


text:
Liquid level sensor
We're currently working on a direct sketch to printed circuit board printer for our design project. We need a sensor for the ink level since we're using a pen. Can we use this ( https://www.dfrobot.com/wiki/index.php/Non-contact_Liquid_Level_Sensor_XKC-Y25-T12V_SKU:_SEN0204) as a sensor even if its non-conductive type ink (normal ink we use for writing)? Thanks for the response!

Your link page says:

There are no special requirements for the liquid

So, I would not concern about the conductivity of the liquid.


text:
SD card in Arduino
Im connecting an SD card module to arduino pro with 3.3v , the card is getting initialized , but im getting an error message that FAT 32 partition is not available , but it is already in FAT 32 format , is this an voltage issue ? should i connect it to a 5v line? Ive tried it two libraries SD and sdfat libraries , im getting same results, im using 8gb memory card

A SD card is 3.3V.
Have you read this: Arduino.cc forum about SD Formatter ?
Perhaps it is a cheap module with bad contacts.
Perhaps your 8GB card is not compatible. Do you have another memory card ? Preferably older and less memory.
Perhaps you use long wires, or a breadboard with bad contacts.
In most cases it should work without problem. When the initialization is okay then the wiring is probably okay. Therefor I suspect that the card itself or the partition on it, is not compatible.

and Ive tried formatting with SD formatter , no change .Im not using long wires since this is a closed circuit .and upto my knowledge arduino supports upto 8gb fine and good . and ive triple checked the connections , its good .Is there something with the memory ? Please do let me know If there is something

Could you try with another SD memory card ?
Is something else connected to the MISO ?
When the module has a voltage regulator, and a 3.3V and 5V pin, then you could try to power it with 5V to the 5V pin and leave the 3.3V pin of the module open.
The SD card module could be broken.

@ Jot Yeah ive tried it with 16gb memory card its working ,I dont know why its not working with 8 gb memory card

I'm glad it is working. Some memory cards are not compatible with the Arduino SD library, it happens.


text:
Problem sending array data from matlab to arduino
I've two LEDs connected to the arduino uno's pin 12 and 13. I want to control the LEDs independently from the MATLAB serial command.
Here is my MATLAB serial command from where I'm sending char array
s = serial('COM4','BaudRate',9600);
fopen(s);
output = [2,1];
data = char(output);
fprintf(s,'%d',data);
fprintf(s);

And this is my Arduino code to receive char array
char d[4];
void setup()
{
   Serial.begin(9600);
   pinMode(12,OUTPUT);
   pinMode(13,OUTPUT);
}

void loop()
{
    if(Serial.available()>0)
  {
    for(int i=0;i<3;i++)
    {
      d[i] = Serial.read();
    }
    d1 = d[0]-'0';
    if (d1 == 1)
   {
    digitalWrite(12, HIGH);
    delay(1000);
     digitalWrite(12, LOW);
    delay(1000);
    }
  else if (d1 == 2)
    {
    digitalWrite(12, HIGH);
    delay(2000);
    digitalWrite(12, LOW);
    delay(1000);
    }
    d2 = d[1]-'0';
    if (d2 == 1)
   {
    digitalWrite(13, HIGH);
    delay(1000);
     digitalWrite(13, LOW);
    delay(1000);
    }
  else if (d2 == 2)
    {
    digitalWrite(13, HIGH);
    delay(2000);
    digitalWrite(13, LOW);
    delay(1000);
    }
  }
}

The MATLAB command is intended to keep the LED on for the given seconds. When I tried this code for one LED(sending only single char) it worked fine. But when I tried it for two LEDs it turns on only LED connected to pin 12 twice.
Eg:
MATLAB command output = [2,1], turns on LED(pin 12) for 2 sec and then for 1 sec but I want it should be to turn on LED(pin 12) for 2 sec and LED (pin 13) for 1 sec.

And the question is?

If you look at the serial data sent in a terminal what is it? If the serial data is "2,1" then you want d2 = d[2]-'0'; not d2 = d[1]-'0'; Also instead of a load of if statements wouldn't be easier to get the time by multiplying the value by 1000? digitalWrite(12, HIGH);delay(d1*1000);


text:
Laser emitter + receiver for Arduino (Arduino to Arduino communication)
I'm working on a project using 2 Arduinos connected to 2 computers to demo Serial to Serial communication.
We're using Arduino Uno connected to the computer via Serial and software serial for inter-Arduino communication. We used wires to connect software serial RX & TX lines, but we'd like to connect these pins to a laser transmitter and receiver.
We're trying to show wireless communication using an optical medium, which is why we wanted to use a Laser transmitter and receiver.
We're trying something like the setup in this YouTube video $3 laser transmits audio over 100m (Arduino)
Any idea how high a baud rate we will be able to achieve using the transmitter and receiver?
Receiver: Laser Sensor Module non-modulator Tube Laser Receiver
Transmitter: 5V ... Board For Arduino AVR ... KY-008 Laser Transmitter

you can use a red or ir led to receive, or a phototransistor, all of which should give dozens of KHz.

Speed is likely to be limited by use of software serial instead of the laser link.  You might consider using Mega2560's (which have 4 UARTs) instead of Uno's

This particular receiver module is advertised as being "non-modulated" which means it is just a digital on/off indicator.  I can't find info on the latency in the circuit before it determines whether or not it can find the laser signal, so presume the speed will be very very slow.  You would be better off using just a LDR or something else other than this module.

@dandavis I tried feeding a square wave to an IR LED. I hooked up a photodiode (and resistor) to an oscilloscope. The rise times became too slow above 2kHz.

hook the LED to the oscilloscope (w/o resistor), and shine a laser into the led. you should get up to the forward voltage an a few microamps of current. "waterclear" LEDs work a lot better than diffused.many in series adds voltage; i used 3 flat ones in series as an opto-isolated mosfet driver (K-d, A-g, 10Mohm s-g).

Any idea how high a baud rate we will be able to achieve using the transmitter and receiver?

Looks like the receiver module has a low-pass filter. That could reduce the baud-rate depending on the RC-factor (10 Kohm * 10 nF gives a cut-off frequency of 1.6 kHz). I would recommend checking the actual components. The above is a guesstimate.
Cheers!

Possible. But the capacitor is connected across the supply terminals of the component, not the signal (I'm too sure about filters, just guessing). Wouldn't the capacitor need to be connected between signal and ground (with a series resistor) for it to be a filter? A person on Youtube used this sensor with a 115200 baud rate, but I'm not sure about the error rate he encountered.

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


text:
Controlling amplifier using remote control jack
Many older amplifiers support wired remote control through connector jacks or ports. My 10-year old Marantz also supports this function, using a simple RCA connector.
Originally these were used with external IR receivers when the unit was not kept in plain sight.
I wonder if there is a way to control the amplifier using an Arduino, which probably means by generating the required signal over the connector instead of receiving it from an IR receiver. Any pointer to a similar project is appreciated as well.

Sounds like the sort of thing which might be possible. Unless someone happens to know specifics of how they work, a spec for the connection, and/or a circuit diagram of either/both the amp or/and a suitable controller would help a lot.

it's probably just the same pulses as the IR, but you'd need an oscilloscope or a service manual to be sure. you can always improvise

You'd have to know the protocol, which is probably proprietary. I'd just use IR, by connecting an IR led to the Arduino.

@dandavis That's exactly what I think. But given that Marantz IR protocol is well-known, do I really need to check the pulses manually? Note, I wouldn't need to do that even if I wanted to emulate a Marantz remote controller with actual IR output.

That's what I was assuming - that you would stand a good chance of guessing the protocol with some trial-and-error, but it would be really helpful to have some idea of how it works electrically to get you started, otherwise you've got two degrees of freedom (and you might possibly damage the device). Two connections (as on an RCA) isn't enough for an IR receiver (you need three) so it's not immediately obvious (to me, anyway) how it would work. Even a working example IR receiver circuit would get you started.

i seem to recall an article 20 years ago that said marantz gear could interact with sony using those control signals. if that's true, or maybe just for an overview look into sony's...

According to this thread on remotecentral the signal on the RCA connector is just the inverted signal that the IR-LED receives. So if you load an RC5 library and invert the output (0=1 and 1=0), you should be able to send codes to that connector with an arduino. Or even better, use an ESP8266 and control it over wifi ;)
The RC5 codes and their functions are in this  nice excel sheet or use this information if you want to send raw hex

Someone blogged how to do it using a Raspberry PI and LIRC. The excel shet link is broken, found a copy here. Another useful dicsussion here.


text:
Arduino eeprom_put sketch writes data in two locations?
Using precisely this code - the eeprom_put example in the Arduino IDE, and am seeing some strange results...
The sketch does write correctly to eeAddress = 0, and the corresponding eeprom_get sketch does return the data.
Please note that I've initialized the entire EEPROM with 'FF's before any test...
The weird part is this sketch writes exactly the same data starting at Address = 2048. The loop is not running; I see no jump to offset 2048... I gotta be missing something!
I'm dumping EEPROM using avrdude, and viewing results in an external hex editor.
How is this stuff stored? Apart from not being able to directly view a float - OK, I get it - should the other data be simply viewable in hex?
My own experiments in writing hex bytes directly also work, but also write in two locations.
Small update to this: Precisely the same behavior seen with a RobotDyn Mega. Both the 'clone' Mega and the RobotDyn report: Device signature = 0x1e9801 (probably m2560)
#include <EEPROM.h>

struct MyObject {
  float field1;
  byte field2;
  char name[10];
};

void setup() {

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  float f = 123.456f;  //Variable to store in EEPROM.
  int eeAddress = 0;   //Location we want the data to be put.

  //One simple call, with the address first and the object second.
  EEPROM.put(eeAddress, f);

  Serial.println("Written float data type!");

  /** Put is designed for use with custom structures also. **/

  //Data to store.
  MyObject customVar = {
    3.14f,
    65,
    "Working!"
  };

  eeAddress += sizeof(float); //Move address to the next byte after float 'f'.

  EEPROM.put(eeAddress, customVar);
  Serial.print("Written custom data type! \n\nView the example sketch eeprom_get to see how you can retrieve the values!");
}

void loop() {
  /* Empty loop */
}

What board/mcu are you using? And did you give a larger eeprom size to avrdude to dump?

It's a mega2560 - in fact, avrdude correctly detected it, and its 4k EEPROM size. No, did not override any EEPROM size parameters.

What is probably happening is aliasing.  Let's say your processor has a 16 bit address bus.  16 bits can count up to 2^16 = 65536 = 64k memory addresses.  Each address is a byte (B) so your processor has 64k-Bytes of address space.  It can physically address 64kB of memory.
What happens if you only have one memory chip with 4KBytes of memory, with  only 12 address lines?  Well, if the designer was lazy (or cost-conscious), the first 12 address lines on the processor will be connected to the 12 lines on the memory chip.  The other 4 lines on the processor will be ignored.
So it doesn't matter what the processor does with address lines 13-16 -- they're not connected to the memory chip.  Therefore the contents of the memory chip appears where you expect, starting at address 0, but also again at address 4096, and again at address 8192 and so on.

Ah! I had no idea about this. And I imagine it seems a reasonable possibility for a cheap clone Arduino Mega2560? Supposed to have 4k of EEPROM, but sounds like you're saying a big chunk of it may not be usable!

The Arduino Mega 2560 has 4k of EEPROM and all 4k is usable. Only a few ATmega chips have 2k EEPROM, for example the ATmega644. Perhaps you are doing something wrong, perhaps avrdude is limited, or perhaps you hit a bug. When you do a read from 2048 in the sketch, you only see FF ?

Well, it's slightly more nuanced than that. Board reports it has 4k bytes, as I'd expect. Its behavior at this point seems consistent with Mark Smith's comment above. A good test will be an attempt to write to addresses above 2048 - will try this tomorrow.

Another update: Yup, similarly weirdness when writing to address: byte eeAddress = 0x800.
Data is written to both 0x800 and 0x00. Wow!
@Mark Smith - whaddaya think?
Anybody else interested in testing this on their own boards?

That's exactly the same behavior. 0x800 = 2048. Because of the incomplete decoding of the addresses, those addresses address the same piece of memory. They are the same piece of memory.