text:
Use Arduino Mega to program Arduino Duemilanove
I hava an Arduino Duemilanove but I think that its FTDI chip is crashed.
I have an Arduino Mega too, so can I use it to program my Duemilanove?

Yes, this is not an uncommon activity.  This is called using an Arduino as an In-System Programmer (ISP)
This page has the information and Arduino program you need.  You'll need to adjust for the Arduino Mega pin differences, but that's fairly easy.
http://arduino.cc/en/Tutorial/ArduinoISP
Where the ArduinoISP page references pin 13, on the Mega it's pin 52.
Where the ArduinoISP page references pin 12, on the Mega it's pin 50.
Where the ArduinoISP page references pin 11, on the Mega it's pin 51.
Where the ArduinoISP page references pin 10, on the Mega it's pin 53.
Otherwise you should be able to connect the Mega to the patient in the same way as described, load the ArduinoISP sketch into the Mega, preferably from the GitHub repository linked in the article (https://github.com/rsbohn/arduinoisp).


text:
Change the backlight of 2x16 LCD
Today I ordered a 2x16 character LCD with white characters on black background.
Now I am wondering if I can change the backlight LED, which I guess is white for the characters, with a RGB LED to change the character color.
Did anyone do this before?
Is it even possible that way?
I've seen RGB negative LCDs from Adafruit and Sparkfun.

Not all LCDs are the same so you'll have to look at the item's datasheet for this. Do you know the part number?

Thanks for your answer! Ive got this one: http://mikroshop.ch/LED_LCD.html?gruppe=7&artikel=467 Theres a link to the datasheet. Stan

http://www.adafruit.com/products/399

@IgnacioVazquez-Abrams Thanks Ive already seen these as i said but i was wondering if i could replicate the same effect with a white/black lcd and some rgb leds on my own

Adafruit also sells the waveguides alone, so you could take an existing backlit LCD, strip out all the backlight hardware, put in a new waveguide, and glue on a new LED.

The backlight led (sample) is just a simple led with a large transparent panel, the size of the lcd, attached to it. This panel is diffused on the top in such a way that it distributes the light evenly. If you get a rgb led, file the top flat, and glue it to the side of this panel (where the leads get out of the plastic) you should get a pretty good effect.
I tested it on my white-on-blue lcd, by holding and led to the side of this panel, and it worked. Just note that you need a very bright led. Mine was pretty bright but the letters didn't light up that much.

The product you linked looks like a fairly standard LCD module, so it's probably very difficult to swap the backlight LED. Like most electronics, they're not designed to be modified by hand. It would likely need some precision re-soldering.
When you see LCDs with other types/colours of backlight, it's usually because they were originally manufactured that way.

I also have a 4x16 character lcd with white on blue thats why i thought of just ripping out the white led/smd, glue in the rgb led and control it via 3 potentiometers.

I'd be careful if you want to try that. You could easily damage the LCD in the process.

Over all this theoretical diskussion is it even correct that the led is coloring the characters? So the white makes white chars and blue for example makes blue chars?

Yes, for a negative LCD that's how it usually works. The LCD blanks out most of the screen, making individual pixels transparent so that the backlight shows through.

source: Stack Exchange

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

sort: votes


text:
Lighting 5 leds...the last one lit is always dim
I have a simple project with a close deadline.
I am trying to light up 5 LEDs as part of the project. The first 4 light up in sequence fine, and if I light up just the last one it lights up fine, but if all 5 are lit at once the very last LED is very dim. I swapped out cables, the pin on the Arduino, resistor, LED.
What would explain that? Input amperage? Too strong a resistor?
I have a 330 ohm resistor in between each LED and ground. I am using one of the neat resistors from SparkFun that packages up the 5 330 ohm resistors together, with a common ground wire. I bought two and tried swapping it out with no change.
https://i.sstatic.net/QZ4qU.jpg
Here is my code:
/* Blink without Delay
 http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
 */

const int startButtonPin = 6;
const int reedSwitchPin = 7;
const int ledPins[] = {8,9,10,11,13};
const int numLeds = 5;
const long interval = 1000;           // interval at which to blink (milliseconds)
const int revolutionsPerStage = 15;

int debounceDelay = 500; // for switches--interval to ignore short button presses/reed switch open/close
long lastDebounce = 0;
int buttonState = LOW;
int mapStage = 0;

unsigned long previousMillis = 0;        // will store last time LED was updated

void setup() {
  // set pin modes
  for (int thisPin = 0; thisPin < (sizeof(ledPins)/sizeof(int)) - 1; thisPin++)  {
    pinMode(ledPins[thisPin], OUTPUT);
  }
  pinMode(startButtonPin, INPUT);
  pinMode(reedSwitchPin,INPUT);

  digitalWrite(reedSwitchPin,HIGH); // activate the pull-up resistor
}

// Main program loop
void loop()
{
  buttonState = digitalRead(startButtonPin);
  //digitalWrite(8,HIGH);

  // wait for button press to begin program proper. we won't get back to this state except on first boot or if program finishes
  if (buttonState == HIGH) {
      digitalWrite(8,HIGH);
      chasingLEDs();
      //trackProgress();
  }
}

void trackProgress() {
  int blinkState = LOW;
  unsigned long currentMillis = millis();
  unsigned int numRevolutions = 0;

  do {
    digitalWrite(ledPins[mapStage], HIGH);

    // blink the current goal LED at constant interval specified earlier
    if(currentMillis - previousMillis >= interval) {
      // save the last time you blinked the LED
      previousMillis = currentMillis;
      blinkState = !blinkState;
      digitalWrite(ledPins[mapStage], blinkState);
    }
  } while (mapStage < numLeds);
}

// perform a simple welcome sequence to indicate we are ready to start pedalling
void chasingLEDs() {
   // turn LEDs on in sequence, then back off
   for (int i = 0; i < numLeds; i++){
     digitalWrite(ledPins[i], HIGH);
     delay(333);
   }

   for (int j = numLeds; j > 0; j--) {
     digitalWrite(ledPins[j], LOW);
     delay(333);
   }

   // flash the LEDs twice
   for (int k = 0; k < 2; k++) {
     for (int l = 0; l < numLeds; l++) {
         digitalWrite(ledPins[l], HIGH);
     }
     delay(500);
     for (int m = 0; m < numLeds; m++) {
         digitalWrite(ledPins[m], LOW);
     }
   }
}

I found the problem, it was a bug in my code. I had found code to read the array size online but it was off by 1.
Instead of:
for (int thisPin = 0; thisPin < (sizeof(ledPins)/sizeof(int)) - 1; thisPin++)  {
    pinMode(ledPins[thisPin], OUTPUT);
  }

When I changed it to thisPin < numLeds, it worked correctly. The last pin was simply set to be an input pin instead of an output pin.

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


text:
how can I accurately recieve potentiometer values over the USB port?
I want to read the analog values of my ardunio uno into a separate c++ program. On the Arduino I have a serial port initialized for 9600 baud:
int sensorPin = A0;    // select the input pin for the potentiometer

int sensorValue = 0;  // variable to store the value coming from the sensor

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

void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);
}

The output value should be right around 390, given the current settings. My serial port reading code seems to read the port fine, but only displays some of the characters sometimes.... some of the time, it reads the value fine. other times I get one or 2 of the characters, such as 3, or 39.
#include <stdio.h>      // standard input / output functions
#include <stdlib.h>
#include <string.h>     // string function definitions
#include <unistd.h>     // UNIX standard function definitions
#include <fcntl.h>      // File control definitions
#include <errno.h>      // Error number definitions
#include <termios.h>    // POSIX terminal control definitions
#include <iostream>
using namespace std;

int main(){
    const char* device ="/dev/ttyACM0";
/* Open File Descriptor */
//int USB = open( device, O_RDWR| O_NONBLOCK | O_NDELAY );
int USB = open( device, O_RDWR| O_NOCTTY );

/* Error Handling */
if ( USB < 0 ){
cout << "Error " << errno << " opening " << device << ": " << strerror (errno) << endl;
}

/* *** Configure Port *** */
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);

/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 ) {
   cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << endl;
}

/* Save old tty parameters */
tty_old = tty;

/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);

/* Setting other Port Stuff */
tty.c_cflag     &=  ~PARENB;            // Make 8n1
tty.c_cflag     &=  ~CSTOPB;
tty.c_cflag     &=  ~CSIZE;
tty.c_cflag     |=  CS8;

tty.c_cflag     &=  ~CRTSCTS;           // no flow control
tty.c_cc[VMIN]   =  1;                  // read doesn't block
tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines

/* Make raw */
cfmakeraw(&tty);

/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
   cout << "Error " << errno << " from tcsetattr" << endl;
}

if ( tcsetattr ( USB, TCSANOW, &tty ) != 0){
cout << "Error " << errno << " from tcsetattr" << endl;
}

/* Allocate memory for read buffer */
char buf [1024];
memset (&buf, '\0', sizeof buf);

/* *** READ *** */
int n = read( USB, &buf , sizeof buf );
cout << "buffer: " << &buf << endl;
/* Error Handling */
if (n < 0)
{
     cout << "Error reading: " << strerror(errno) << endl;
}

/* Print what I read... */
cout << "Read: " << buf << endl;

close(USB);
 return 0;
}

How can I read the correct value being sent every time?

https://www.arduino.cc/en/tutorial/potentiometer

It's odd that you don't care about Serial.print(), since it is the sort of thing Arduino gives to allow conveying data over a serial connection.  You mention "stable connection"; does this mean you have found your serial connection to be unstable?

I know how to set the arduino to send data on the serial port, its the receiving it elsewhere that I am struggling with. My interpretation of the results I am getting lead me to believe there is a stability issue.

Would capturing the Serial.print() output with a terminal emulator that supports logging output do, then post processing that file? At least it would confirm (or not) that the data being sent is correct (or not). If it's being sent correctly, your problem isn't with the Arduino or its code.

I am verifying with the serial monitor, I'd like to avoid doing loads of file IO and redirection. I think I might be getting close, set_blocking might be my final issue. .. then I'll have to try reading multiple pots.

So, after a complete rewrite of your (originally very poorly written) question you are now asking for something completely different: help with a C++ program written for your computer, not help with your Arduino....?

yea yea, poorly written perhaps, but its hard to know when your project doesn't work, whether you're approaching it in the right way at all. I'm an electrician, not a programmer, not an engineer, I don't have a degree, and I don't know how to get the data from my Arduino to my computer program reliably. The problem is the same, the question is the same. How do i get the data? please post your solution @Majenko

Your core problem is the way you're using read, as Edgar notes. You must read a line not just a random number of bytes.

There are a few issues at play here. One is that the Arduino
resets every time you open the serial connection on the PC side. You can
prevent this by putting a 1 µF (or more) capacitor between 5V and
RESET. A second issue is that the tty driver may be keeping old data in
its buffer, and you get this data when you open the connection. The
third issue is that read() returns as soon as it is able to read
some data: it doesn't wait until it has got sizeof buf bytes.
To fix those issues, I suggest:

Have some form of handshake, where the PC sends a request to the
Arduino, and then the Arduino acknowledges and starts to send the
data. The PC program would then discard everything preceding the
acknowledgement.
On the PC, repeatedly read() until you have a full line (which ends
with CRLF). You may want to use a line-oriented stream if you want
the libc to handle this for you: see fdopen(3) setlinebuf(3).

Edit: A very simple example of handshake: the PC sends S (for
“start”), then the Arduino sends OK, then it starts sending the data.
On the Arduino side:
void setup() {
    Serial.begin(9600);

    // Wait for the 'S' (start) command from the computer.
    while (Serial.read() != 'S')
        /* wait */ ;

    // Send acknowledgement.
    Serial.println("OK");
}

A longer “start” command would be more robust, but a bit more complex to
handle on the Arduino. The PC should wait a bit before sending the
command (in case the Arduino is restarting), or maybe send it multiple
times until it gets an answer.

have any good refference material for this?

@j0h: For what? About line buffering, the notation “fdopen(3), setlinebuf(3)” is a horthand for “see man 3 fdopen 3 setlinebuf.

the handshaking bit, I'm not clear on. is that Serial.read() reading from the serial port to the computer, or from the Arduino? Im thinking maybe I can send a character to the arduino, pc say, hey arduino, you there rsvp to char 42. arduino listens for char 42, gets it, and responds with a string of values or something, and posts a hangup sign, and goes back to listening for the next rsvp from the PC.  ... or something like that, is how I'm imagining it going

A USB connection is actually very complex.  And serial communications (or the CDC class of USB) is only 1 of over a dozen protocols used over USB.  Most cheap embedded processors save money by leaving out this feature.  Most Arduino's use cheap embedded processors.  For instance, the classic Arduino Uno needs a second chip (search for New USB in this link) to even talk Serial over the USB port.  Fortunately this is what Serial.print() does.  It takes care of setting up the Serial protocol over the USB port for you.  And will send your data over that connection.
How you pick up that data at the other end of the USB connection is usually beyond the discussion range of this stack exchange site.  But if you are on a windows machine it will probably be one of the COM ports.  And on Linux it will probably be something like /dev/ttyUSB0 or 1.

You don't have to, but comments are appreciated when ever there is a vote.  In either direction.  The objective is to edit and improve both the questions and the answers.

I might have to repost this, as it is now closed. But I appreciate the answer.

You can edit this question to be more focused.  That should trigger a message to person who closed it so that they can reconsider the edited version of the new more focused question.  Hint: It's always good to try something on your own first then ask when things don't go as expected.

yeah, I edited it, but its still closed. every vote to reopen helps. hint hint

I downvoted because it was and now even more is not an an answer to the question

Thanks @Juraj for responding.  I see your point.  But since @ Edgar Bonet gave such a complete answer I don't see a benefit in repeating even a part of what he said.  So as to mitigate confusion I'm going to leave things as they are.

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


text:
What will happen when I use an invalid pin number?

Related to:
  What happens if there is a runtime error?

This question is similar to the one above, however this is an alternate situation:
int pin = 999;
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);

What would happen in this instance? The compiler might catch it but if you used a random number would the IDE catch it?

The compiler will not detect any error and the code will compile and execute. Hence, to see what happens we need to explore the behind-the-scenes magic. For a summary, skip to end.

The second line in your code is where the magic will happen and thats where we need to focus.
pinMode(pin, OUTPUT);

The portion of pinMode relevant to this discussion is:
void pinMode(uint8_t pin, uint8_t mode)
{

    uint8_t bit = digitalPinToBitMask(pin); //The first instance where pin is used
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return;

//Do something
}

(The complete implementation can be found in wiring_digital.c)
So, here, digitalPinToBitMask seems to be using pin to compute an intermediate bit. Exploring further, digitalPinToBitMask is a macro defined in Arduino.h whose definition is this one-liner:
#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )

This weird looking one liner does a very simple task. It indexes the Pth element in the array digital_pin_to_bit_mask_PGM and returns it. This array digital_pin_to_bit_mask_PGM is defined in pins_arduino.h or the pin map for the specific board being used.
const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = {
    _BV(0), /* 0, port D */
    _BV(1),
    _BV(2),
    _BV(3),
    _BV(4),
    _BV(5),
    _BV(6),
    _BV(7),
...
};

This array has 20 elements in total, so we are out of luck. 999 will index a memory location in the flash memory outside of this array, thereby leading to unpredictable behavior. Or will it?
We still have another line of defense against runtime anarchy. Its the next line of the function pinMode:
uint8_t port = digitalPinToPort(pin);

digitalPinToPort takes us along a similar path. It is defined as a macro along with digitalPinToBitMask. Its definition is:
#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )

Now, we index the Pth element of digital_pin_to_port_PGM which is an array defined in the pin map:
const uint8_t PROGMEM digital_pin_to_port_PGM[] = {
    PD, /* 0 */
    PD,
    ....
    PC,
    PC,
};

This array contains 20 elements, so 999 is again out of range. Again, this command reads and returns a value from flash memory of whose value we cannot be certain. This will again lead to unpredictable behavior from here on.
There is still one last line of defense. That is the if check in pinMode on the return value of digitalPinToPort:
if (port == NOT_A_PIN) return;

NOT_A_PIN is defined as 0 in Arduino.h. So, if the returned byte from digitalPinToPort happens to be zero, then pinMode will silently fail and return.
In any case, pinMode cannot save us from anarchy. 999 is destined to result in doom.

TL;DR, the code will execute and the result of this will be unpredictable. Most likely, no pin will be set to OUTPUT, and digitalWrite will fail. If you happen to have exceptionally bad luck, then a random pin may get set to OUTPUT, and digitalWrite may set it to HIGH.

It's interesting there is no bounds checking. digitalWrite is so slow and bulky anyway, it wouldn't be awkward to put in either compile time or run time checks.

If all arduino pins are in a contiguous range, than couldn't they replace the port==not a pin check with a pin>BOARD_MAX_PIN check, where board max pin is defined in some header file based on some ifdef that detects the board?

You are forgetting that 999 cannot be represented in a uint8_t so it would first be converted to 231 by the code calling pinMode.  The end result is the same: pinMode and digitalWrite will have unpredictable behavior and could clobber random parts of memory if you call them with a bad pin argument.

In the standard libraries, there are macros designed for converting pins to ports, which are used in assembly. Here they are for the Uno from Arduino 1.0.5:
#define digitalPinToPCICR(p)    (((p) >= 0 && (p) <= 21) ? (&PCICR) : ((uint8_t *)0))
#define digitalPinToPCICRbit(p) (((p) <= 7) ? 2 : (((p) <= 13) ? 0 : 1))
#define digitalPinToPCMSK(p)    (((p) <= 7) ? (&PCMSK2) : (((p) <= 13) ? (&PCMSK0) : (((p) <= 21) ? (&PCMSK1) : ((uint8_t *)0))))
#define digitalPinToPCMSKbit(p) (((p) <= 7) ? (p) : (((p) <= 13) ? ((p) - 8) : ((p) - 14)))

There are more, but I won't show them here.
I believe your program would subtract 14 from 999, which would still be too big for the brogram. It would then try to point to the 985th element of the digital_pn_to_bit_mask_PGM array, which only contains 20 elements. This would most likely end up screwing the Arduino by pointing to a random spot in progmem.


text:
Assigning values to char array causes program to not run
I have the following code:
#include "LCD12864RSPI.h"
#include "DFrobot_bmp.h"
#include "DFrobot_char.h"

#define AR_SIZE( a ) sizeof( a ) / sizeof( a[0] )
unsigned char wangzhi[]=" www.DFRobot.com ";
unsigned char fused[1024];

void setup()
{
  pinMode(11, OUTPUT);
  for(int i=0;i<4;i++){
  digitalWrite(11,HIGH);
  delay(1000);
  digitalWrite(11,LOW);
  delay(1000);
  }
  LCDA.initDriverPin(2,7,10);
  LCDA.Initialise(); // INIT SCREEN
}
unsigned char* fuse3(unsigned char* a ,unsigned char* b,unsigned char* c){

  int i=0;
  int ac=0;//a counter
  int bc=0; //b counter
  int cc=0;//c counter

  for(int n=0;n<64;n++){
    for(int k=0;k<5;k++){
      fused[i]=a[ac];
       ac++;
       i++;
    }
       for(int k=0;k<5;k++){
        fused[i]=b[bc];
       bc++;
        i++;
    }
        for(int k=0;k<5;k++){
            fused[i]=c[cc];
            cc++;
             i++;
    }
    fused[i]=0x00;
    i++;
  }

  return fused;
}
unsigned char* getMatch(int input){
  input = input & 0x000f;
  switch (input){
   case 0: return g0;
   case 1: return g1;
   case 2: return g2;
   case 3: return g3;
   case 4: return g4;
   case 5: return g5;
   case 6: return g6;
   case 7: return g7;
   case 8: return g8;
   case 9: return g9;
   case 10: return plus;
   case 11: return minus;
   case 12: return times;
   case 13: return g1;
   case 14: return g1;
   case 15: return g1;
   default: return g1;
  }

}
void displayfuse(int number){
// LCDA.DrawFullScreen(fuse3(getMatch(1),getMatch(2),getMatch(3)));
}
void loop(){
  displayfuse(0x1234);

}

This code is a stripped version of the code I need to run to get a bigger project working. But if it somewhat works than the setup should begin by flashing a LED 4 times before continuing. Currently this works. However as you can see I have commented out the line LCDA.DrawFullScreen(fuse3(getMatch(1),getMatch(2),getMatch(3)));. uncommenting this line causes the LED's to flash continuously rather then just 4 times. The library I'm using can be found here. Does anybody know what is going on? To me the first few lines of a program can be affected by a change somewhere this deep inside the code is a form of dark magic.
Weirdly when I change the setup to the following:
void setup()
{
  pinMode(11, OUTPUT);
  for(int i=0;i<15;i++){
  digitalWrite(11,HIGH);
  delay(100);
  digitalWrite(11,LOW);
  delay(100);
  }
  for(int i=0;i<4;i++){
  digitalWrite(11,HIGH);
  delay(1000);
  digitalWrite(11,LOW);
  delay(1000);
  }
  LCDA.initDriverPin(2,7,10);
  LCDA.Initialise(); // INIT SCREEN
}

it stops flashing completely.
Edit having just reuploaded the code again this time the led just remains on all the time.
edit edit
Now with the following code:
#include "LCD12864RSPI.h"
#include "DFrobot_bmp.h"
#include "DFrobot_char.h"

unsigned char fuse[1024];
void setup()
{

  LCDA.initDriverPin(2,7,10);

  LCDA.Initialise(); // INIT SCREEN
  pinMode(11, OUTPUT);
  digitalWrite(11,HIGH);

}
unsigned char* fuse3(unsigned char* a ,unsigned char* b,unsigned char* c){
 unsigned char* fused =(unsigned char*)malloc(sizeof(char)*1024);

  int i=0;
  int ac=0;//a counter
  int bc=0; //b counter
  int cc=0;//c counter

  for(int n=0;n<64;n++){
    for(int k=0;k<5;k++){
      fused[i]=a[ac];
      ac++;
       i++;
    }
        for(int k=0;k<5;k++){
      fused[i]=b[bc];
      bc++;
       i++;
    }
        for(int k=0;k<5;k++){
      fused[i]=c[cc];
      cc++;
       i++;
    }
    fused[i]=0x00;
    i++;
  }
  return fused;
}
unsigned char* getMatch(int input){

  input = input & 0x000f;

  switch (input){
   case 0: return g0;
   case 1: return g1;
   case 2: return g2;
   case 3: return g3;
   case 4: return g4;
   case 5: return g5;
   case 6: return g6;
   case 7: return g7;
   case 8: return g8;
   case 9: return g9;
   case 10: return plus;
   case 11: return minus;
   case 12: return times;
   case 13: return g1;
   case 14: return g1;
   case 15: return g1;
   default: return g1;
  }
}
void displayfuse(int number){
 LCDA.CLEAR();
   delay(100);

 int mask1 = 0xF000;
 int mask2 = 0x0F00;
 int mask3 = 0x00F0;

 int firstnumber = number&mask1>>12;
 int operation = number&mask2>>8;
 int secondnumber= number&mask3>>4;

  LCDA.DrawFullScreen(fuse3(getMatch(firstnumber),getMatch(operation),getMatch(secondnumber)));
  delay(5000);
}
void loop(){
  displayfuse(0x1234);
  delay(1000)
}

This causes the led to not turn on but moving the lines where I make pin 11 output and high one up (beyond the  LCDA.Initialise(); // INIT SCREEN ) then the led will turn on. It can also be turned on by commenting out the       LCDA.DrawFullScreen(fuse3(getMatch(firstnumber),getMatch(operation),getMatch(secondnumber))); line.
Magic is happening...

Short answer: You're out of SRAM.

Memory usage is at around 6 kB leaving quite a bit around.

Are you running this on a Mega?

This is on the "funduino" clone but I have 32 kB avaible and 6 in use.

Is it the Funduino Mega2560?

No the funduino uno

Then the 32kB you have available is flash. You have 2kB of SRAM.

I doubt it; it should complain when you allocate the array space. You did allocate the array space?

Everything in the getMatch(int) function is allocated in a separate header file. The rest happens inside the code I posted.

I was indeed running out of SRAM thank you Ignacio, if you write it into an answer I will accept it.

The 'dark magic' is going to be your program rebooting every time it gets to that line. I would imagine (this isn't a library I know) that you're exceeding an array bound & generating a 'segfault', although it could be that you light up your LCD array & the power draw causes a reboot..
Because the LED flash is at the start of setup, it executes quickly, so generating the appearance of continual flashing when  it re-enters repeatedly.
Your code is going to assign g1[0] when the line in question executes - is g1[] defined to point somewhere valid?

Sounds plausible is there a good way of discovering if a segfault occurred? Normally I would use valgrind but what is the arduino option to check for this?

Headwork ;) Where is the code going when this line executes - see edit.

I'm not sure about it anymore I added in a second flash pattern (flash fast-flash slow) and now it doesn't even begin to flash anymore.

Oh and g[] is defined in a header file as a 320 chars array.

What about g1[]?

Everything in getMatched is well defined all of them are 320 chars arrays.


text:
Control arduino with keybaord via computer
I'm brand new to arduino but I'm trying to figure out how to set up a WASD steering system for my robot I made.
I have the physical setup all ready but I don't know the code to use that would allow me to use my computers keyboard. I would like to still have my keyboard attached to my computer while I do this. I.E. I don't want to manually plug the keyboard into arduino.
I asked this on Robotics stack exchange but they said to ask here.
A list of functions/blocks Iof code that is applicable would be the best answer, but I'll take anything that'll get my bot moving :)
Edit I'm using a wireless keyboard, but my arduino is connected via USB.

If you want the keyboard to remain connected to the computer then you need to have the computer tell the Arduino what to do.

Which could be as simple as opening a terminal program such as the IDE's serial monitor and having it pass keystrokes down to the arduino.

You did not mention what kind of communication you intend to setup between the comuter and Arduino: serial (USB), WiFi, Bluetooth... All code needed will first depend on that!

@IgnacioVazquez-Abrams Yes that right. how would I do that. like I said, I not fluent with the language yet. I do Python and Basic.

The problem with using the keyboard is the device would have to be tethered to your computer. If you mean for this "robot" to be an explorer, that limits its choices. If it's an arm or something that stays in place, you're fine using the typical serial libraries to monitor your keyboard for input like Chris suggests.
Unfortunately, I don't know of any way to simply plug in the USB keyboard and take in keys. Usually, serial communication is processed between two systems much like two people texting each other. When you see the light blinking on your phone, you know you have a text and how to open it to retrieve the message. In the case of the Arduino, it's checking for a flag bit called RX for the received message and flags a bit for transmitting a message (TX). Each system then pulls down its message and interprets it. In the case of your sketch, you'll be looking for this flag and schedule an action whenever it's checked. Read about Serial communications here and work through the examples to get a feel for it. Because you probably want a real-time response, it might be worth your while to check out interrupts, as well. These are sudden events that get flagged (such as receiving your text) and get handled immediately instead of waiting for the program to refresh and search for the values manually. As a final note, baud rates are the calculated time frames you and your recipient agree on. It would be difficult to receive a full message if you kept cutting off your friend, so it is with computers. This stuff can kind of be tricky at first, but keep at it. Nothing is more ridiculously satisfying than getting that response character from your device.
There's a neat tutorial for getting your Arduino to work through your iPhone here, but it requires an ethernet board, which means a router and wireless board.
Without knowing what you intend to do with it, it's hard to say how to help, but I hope this gets you into it.


text:
Problem with microSD SPI mode in AVR
I'm trying to read a microSD block. But I don't know why it doesn't work.
I do:
CS_UP;
for(uint8_t i = 0; i <14; i++){ /* Send 74+ clocks */
    spi_tranceiver(0xff);
}
_delay_ms(1); /* Wait 1 ms */

//CS_UP;

/* Initizalize microSD */
put_string("Go to idle state\n");
while (Reset_Card() != 0x01) // Go to idle state
    ;

put_string("Send IF COND\n");
while (Send_CMD8() != 0x01) // SEND IF COND
    ;

put_string("Send ACMD41 and CMD55\n");
for (int i = 0; i<100; i++)
    while (Send_CMD55() && Send_ACMD41())
        ;

setBlockLen(); // Set block read in 512 bytes
CS_DOWN;
put_string("\nConfigure finished correctly\n");

And then I just call:
readSingleBlock(0x00, &buf)

readSingleBlock is defined as follows:
uint8_t readSingleBlock(uint32_t block_address, unsigned char *buf)
{
    int i;

    block_address = block_address << 9;

    CS_UP;
    while (0x00 != sdsc_command(READ_SINGLE_BLOCK, block_address))
        ;

    while (0xfe != spi_rx ())
        ;

    for (i = 0; i < 512; i ++ ){
        //buf [ i ] = spi_rx();
        put_int(spi_rx());
        put_string("\n");
    }
    spi_rx();
    spi_rx();
    CS_DOWN;

    //for (i = 0; i<512; i++) put_int(buf[i]);

The problem is that the printout is:
0 0 0 ..(zeros).. 128 255 255 255 12 255 255 255 0 8 0 0 0 72 59 ..(zeros).. 85 170
Did somebody encounter this problem?
Do you have some suggestions?

Please add, which printout you were expecting. Also please post, how many zeroes are printed out at the respective parts of the output. This makes it easier to trace down the problem.

And now we're equating "AVR" with "Arduino"? What the hell?

I use Arduino Mega Board. But I don't use Arduino Language programming.

I formated the SD card, and then work correctly
Thanks!


text:
Why am I receiving random input values in my Arduino?
I want to use a switch for my Arduino using digitalRead(), but I keep receiving random inputs. Whenever I connect energy to that pin, it always returns HIGH, but otherwise it goes completely random.
I have tried using a resistor for the input pin, but that didn't seem to help. I am using an Elegoo UNO, and the input pin I am using is pin 2. Here's my code in case you need it:
const int switchPin = 3;

void setup() {
  // put your setup code here, to run once:
  pinMode(switchPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(switchPin) == HIGH){
    Serial.println("on");
  }

  else{
    Serial.println("off");
  }
}

No pulldown resistor on that pin then...?

Let me guess: You are not using an external pullup or pulldown resistor (relatively large value resistor from the pin to eiter Vcc or ground). When nothing is connected to a pin it is floating (basically an antenna). A pullup/down resistor pulls the pin to a fixed value, when nothing else is connected. You can use an external resistor, or you can use the internal pullup resistor by doing pinMode(switchPin, INPUT_PULLUP)

Does this answer your question? Digital Pin State - Some 1, Some 0

How did you connect the resistor for the input pin?

You're getting noise pickup on the input pin when the button is not pressed. You need a pull-down resistor, about 10 kΩ to ground, to quiet the noise when the switch is open.
Or even easier, use the built-in pull-up resistor in the Arduino, which is ~10 kΩ to +5 V, wire your button to ground instead of +5 V, and reverse the if tests to test for logic LOW instead of HIGH, to detect a button press. You'd change your pinmode statement to:
pinMode(switchPin, INPUT_PULLUP);  // engage the input pullup

and your test to:
 if (digitalRead(switchPin) == LOW ){ // Negative logic

No additional (external) hardware is needed!

Here is what you can do

Check if the switch is connected to the defined input pin. The Arduino starts form pin 0 and sometimes we can misread while connecting.

Check if the serial monitor has same baud rate as defined in the program.

Check the voltages around switch using a multimeter.

Still not getting a solution? Attach a pull-down resistor.

Still not getting a solution? Invert the logic and current flow as suggested by JRobert.

Your code mentions pin 3 while you describe using pin 2. Perhaps that has to do with your error.
Otherwise, check the following things:

do you use long cables or is it near strong magnetic or static
objects.
for your code since you only read if it is high, see if the button is connected to 5 V and pin 2 or 3 whichever one you use

You can try adding a resistor between your I/O pin and the ground.
Another test I prefer to do is:
Take a working jumper cable, test it with a voltmeter, or see if you can make an LED light up when connected to it (use the Arduino 5 V, ground and a resistor for this (resistor to not let your LED explode like that zeppelin).
With the working jumper cable or breadboard cable, connect one end to the pin you plan to use. Then run the program and connect the other end to ground, then 5 V, and then ground and so forth to see if it responds well.
This is based on an Arduino Uno. If you use another type of Arduino, make sure to use the proper voltage pin. You can always add a resistor between the wire and the Arduino for extra safety.

Few things that can be checked and used.

If you are using a normal push button then check the connections properly as two of the pins are internally connected two each other. So we need 2 pins that are not connected so check it with DMM.

You need a Pull-UP or pull-Down resisters attached to the input pin.
The value of a resistor depends on your requirement like if you have long wires or more noise you need a strong pullup or pulldown resister like 1k. And the best way is to test it out first with an internal pull-up resistor which is considered a week pullup and Atmega328p has its value of around 20k.
pinMode(switchPin, INPUT_PULLUP);

As TeD has stayed check that you are using the same digital pin in your hardware and code.

And last a simple counter type debouncing logic will help to denounce the button input signals. as shown in the below code.

#define switchPin 2
byte debounce_counter = 150;

void setup() {
  pinMode(switchPin, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  if (digitalRead(switchPin) == HIGH) {
    debounce_counter++;
  }
  else {
    debounce_counter--;
  }

  if (debounce_counter >= 240)
  {
    debounce_counter = 150;
    Serial.println("OFF");
  }
  else if (debounce_counter <= 60)
  {
    debounce_counter = 150;
    Serial.println("ON");
  }
}

You can also check other methods and libraries for debouncing the input signals which uses the millis function.

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


text:
Is it possible to generate an exact 15 kHz clock pulse using an Arduino?
I want to generate a 15 kHz pulse with an Arduino using Timer1, but the problem is that if we want a 15000 Hz clock we need to initialize the timer with 1/15000 seconds or 66.66 microseconds, but we can only pass integers without any decimal precision in the Timer1.initialize(66); function which generates a frequency of 15155 Hz.
So is it possible by any other means to generate an exact 15000 Hz or frequencies between 15000 Hz - 15155 Hz?
#include <TimerOne.h>

void setup() {
  pinMode(9,OUTPUT);
  Timer1.initialize(66);  // Frequency, 100 µs = 10 kHz
  Timer1.pwm(9,255);
}

void loop() {}

No you can't, at least not with a standard Arduino Uno and no other components. Trouble is, an Arduino Uno runs at 16MHz, which is not evenly divisible by 15,000Hz. You can only ever get an approximation using internal timers (which are all based on the main clock or some fraction of it).

any external component which can solve my problem? or any other microcontroller in which I can at least initialize my timer at 66.6 microseconds

Using a PIC32MX1xx or 2xx series running at 40MHz it's possible to generate 14999.992675785Hz using the reference clock output - that is, the system clock divided by (2*(1333+(171/512))).

If you can change xtal to 12MHz (bootloader for that xtal too), than it's easy :D

The LTC6903 can generate 14998.217Hz - is that close enough for you?

@StarCat while technically correct, it's kind of misleading, as I double OP will care if it's only a very tiny bit of. Dividing 16Mhz by 1067 would give you 14995Hz. Which is only 0.03% off. The 16Mhz crystal on the UNO probably has a higher error than that.

@Gerben, I realized that the OP was interested in a close(r) approximation after I'd already typed my comment. It was not meant to be misleading.

There is no such thing as "exact", only "to within tolerance", which you haven't really specified (unless you mean 15077.5±77.5).

No. Read the specification for the part you're using.  There is no such thing as an EXACT clock.  Even high-end microprocessors using PLLs have clock and phase jitter.

In practice, different oscillators will have different errors, and pretty much all oscillators are affected by the temperature, so you will obviously never get perfect, atomic-clock-grade 15kHz, even if you have a 15MHz oscillator. But after taking that into account, it boils down to the compromise: do you want 15000 ticks per second on average, or do you need the pulses to be equally spaced? With a 16MHz oscillator, you can have relatively fine adjustments of the interval in order to keep the average frequency close to 15kHz.

@chrylis-cautiouslyoptimistic-: I believe what is meant is "as exact as the source clock"

You can get pretty close if you program Timer 1 directly (not
through the library), and have it run with the prescaler set to 1.
Ideally, you want the period of the timer in clock cycles to be:
F_CPU / 15 kHz = 16,000 kHz / 15 kHz ≈ 1066.67 CPU cycles
If you round this to the nearest integer, you get
F_CPU / 1,067 = 16,000 kHz / 1,067 ≈ 14.9953 kHz
This is about 0.03% too slow, well within the tolerance of the ceramic
resonator clocking the Uno.
Here is my attempt at this. I have tested it.
constexpr float PWM_FREQUENCY = 15e3;  // 15 kHz
constexpr uint16_t PERIOD = round(F_CPU / PWM_FREQUENCY);

void setup() {
    // Configure Timer 1 for 15 kHz PWM on pin 9 = PB1 = OC1A.
    DDRB  |= _BV(PB1);    // set pin as output
    TCCR1B = 0;           // stop timer
    TCCR1A = _BV(COM1A1)  // non-inverting PWN on OC1A
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS10);   // clock @ F_CPU
    ICR1   = PERIOD - 1;  // period
    OCR1A  = PERIOD / 4;  // duty cycle
}

void loop(){}

What is the accuracy of the ceramic resonator? 0.5%?

@PeterMortensen: Typical tolerance is 0.5%. The tolerance is the worst-case frequency error. Typical error is more like 0.1%.

@PeterMortensen: If you calibrate the frequency error, you can adjust PERIOD to compensate for it. You then have about 0.1% resolution in the calibrated frequency.

Since the timer1 library only accepts whole numbers for the µs parameter you get a error. You could skip using the library and configure the timer directly. Or you could have a look at the source code of the library, and see that you can kind of bypass the limitation it has by only calculating a more accurate value for the ICR1 register.
Look at cycles = ((F_CPU/100000 * microseconds) / 20);. If you were to insert your 66.66666µs into this, instead of 66µs, you'd get 533 instead of 528.
This value is then used to set the PWM frequency in line 213. So you'd need to overwrite the ICR1 register with the more accurate value.
Your final code should look like:
pinMode(9,OUTPUT);
Timer1.initialize(66);
ICR1 = 533;
Timer1.pwm(9,255);

PS you might need to tweak this 533 value to get an even more accurate resulting frequency.

Can you please describe the role of ICR1 register here? I need to know how is it working with timer1.

Timer one keeps incrementing it counter (TCNT1) till it reaches ICR1. By increasing ICR1 by 5 is will take a bit longer to count to that, and thus give you a slightly lower frequency, than the 15155Hz you were getting. Hope that explains it a bit better. If not, feel free to let me know.

A better way to do the above average 15 kHz (or any other frequency) is with a phase accumulator scheme.  There are no IF tests; on each tick of an interrupt, you add a step to an accumulator and output the state of its MSB.  This can give incredible resolution, and is probably the best you can do.  But though the average frequency will be dead-on, the jitter can be terrible.  I use this method in my open-source DaqPort sketch
https://www.daqarta.com/dw_rraa.htm#00ff, which is used by DaquinOscope
https://www.daqarta.com/dw_rroo.htm and Arduino_Oscillators https://www.daqarta.com/dw_rrss.htm mini-apps running in Daqarta.  There's also a Jitter_Tbl macro to compute the jitter for arbitrary sample rates and output frequencies.  Although not relevant here, this phase accumulator method can also go to exceptionally low frequencies, into the micro-hertz range, and the jitter is extremely small there.

I can get within 5 Hz of 15,000 using a 16 MHz clock on a Nano, Uno or 2560. Here is the code...
// RTM_TimerCalc 1.20
// Timer-1 Mode_14_16Bit_Fast_TOP_is_ICR

TCCR1B = 0x18; // 0001 1000, Disable Timer Clock
TCCR1A = 0xA2; // 1010 0010

ICR1 = 1067-1;
OCR1A = (int) (ICR1 * 0.25);
OCR1B = (int) (ICR1 * 0.50);
TCNT1=0x0;

// UnComment following lines for UNO-NANO Timer-1 Pins
// pinMode(9, OUTPUT);  // OC1a
// pinMode(10, OUTPUT); // OC1b

// UnComment following lines for 2560 Timer-1 Pins
// pinMode(11, OUTPUT);  // OC1a
// pinMode(12, OUTPUT);  // OC1b

TCCR1B |= 1; // Prescale=1, Enable Timer Clock

Here is the Error Results...
ASK:        15,000 Hz
CALC:       14,995.3139643861 Hz
OFFSET:     -4.6860356139 Hz
hth

In answer to a comment from the OP asking for another microcontroller that can do this, and in addition to Majenko's reply comment:
A SAMD21G running at 48 MHz (as seen on some Arduinos) can make 15 kHz, in several ways.
Note that this assumes that the clock is exactly 48 MHz, and stable, and both assumptions could well be wrong, unfortunately. It helps if the clock is derived from a crystal; not all SAMD21G-based Arduinos do that, if any. This possible lack of clock precision and stability applies to all MCUs.
The SAMD21G does have a fractional PLL, and you can of course adjust the PER register, so some fine-tuning is possible if you have the equipment to measure the actual output frequency.
If you decide to go with one of the SAMD21G-based Arduinos: there is a PWM library for those (I know it well, as I wrote it) that will let you set a clock divider, a prescaler, and a resolution, which should make it easy enough to arrive at a (nominal) 15 kHz. There's a frequency table under "extras".

"It helps if the clock is derived from a crystal" are you saying that not all Arduino have crystal closk?

Yes, I am; there are also some that use a ceramic resonator, and some use the MCU's internal RC oscillator.

@JhonnyS: The Arduino Uno (and its many clones) uses a 0.5% ceramic resonator (there is a crystal on the PCB, but it is only used for the USB part). The official pages about Arduino Uno are quite misleading (by omission, wilful or not). They don't technically lie, but it is close. See Does the Arduino Uno have two crystals?. From the question: " the "big silvery" thing on the board (red) is the famous 16 MHz crystal of the Arduino. That's what I've believed until very recently."

@PeterMortensen thanks for the reference! It makes so much sense now! So three are two clock sources in Arduino! Was just wondering if these are synchronous in nature.

Yes, you can. Sort of...
A 66.6 µs delay means one delay of 66 µs and then two delays of 67 µs.
You could keep a close loop that calculates the micros() divided by 66 and modulo by 2 for every iteration. This will give you an alternating 1 and 0. Save the previous value to check this value for a change and digitalWrite HIGH or LOW.
I have no means at the moment to test the code, but in (semi-pseudo) code this would look something like:
void loop()
{
  int freq=15000;
  float interval = ((float)1000000/(float)freq)/2;//33.333333
  byte state=0;
  byte previousState=0;
  while (1)
  {
    unsigned long currentMicros=micros();
    previousState=state;
    state = (unsigned long)((float)currentMicros / interval) % 2;
    if (state==1 && previousState==0) digitalWrite(9,HIGH);
    if (state==0 && previousState==1) digitalWrite(9,LOW);
  }
}

This method will guarantee that after one second exactly 15000 periods have passed. The timing of the individual periods, however, might vary a little.

Note that this will provide a output that AVERAGES very close to 15KHz but will alternate between 1 cycle of 15.15 kHz and 2 cycles of 14.92 kHz.  That may or may not be acceptable depending on the use-case.

I guess that listening to the tone produced by this method will sound horrible.

I fixed the obvious errors (missing parentheses after micros, missing factor 2 in interval, state variable shadowing a previous declaration) and tested it on an Uno. Not only is the jitter huge, but the average frequency is wrong: about 8.5 kHz. The floating point calculations make the code so slow that it misses pulses.

I'd guess the frequency would be 7.5 kHz, but your factor 2 should have fixed that. I guess that the digitalWrite() take several clock cycles to execute. Too bad, because in theory this could have worked.

digitalWrite() is not that bad, the problem is the use of floats. I programmed something similar to your logic (timing with micros() and digitalWrite()) with integer-only arithmetics. The output does have some jitter visible on the scope, but is far from being as bad as this float-based version. And, as it does not miss pulses, it has an average frequency of 15 kHz.

@EdgarBonet this is awesome explanation so in micro-controllers we should avoid floating-point calculations if possible right? also what causes jitter in your case, despite using integer-only arithmetic?

@JhonnyS: Re “avoid floating point”: if you need to be fast, yes. If you have lots of time, or a microcontroller with an FPU, then floating point is fine. Re “what causes jitter in your case”: I guess it is mostly the resolution of micros(), which is 4 µs.

Re "I have no means at the moment to test the code": Can you update your answer when you have?

Edgar Bonet has fixed the typos and updated my code. See the second comment for his concerns.


text:
What is wrong with the way I write and or read the EEPROM adresses?
Consider:
#include <EEPROM.h>

byte guifactor1 = 1;
byte guifactor2 = 2;
byte guifactor3 = 3;
byte guifactor4 = 4;
byte guifactorgas = 5;
byte guifactorwater = 6;

volatile unsigned long count1factor;
volatile unsigned long count2factor;
volatile unsigned long count3factor;
volatile unsigned long count4factor;
volatile unsigned long countgasfactor;
volatile unsigned long countwaterfactor;

void loop(){
if (guifactor1 > -1){
    EEPROM.write(1, guifactor1);
    EEPROM.commit();
    count1factor = EEPROM.read(1);
    Serial.println(count1factor);
  }

  if (guifactor2 > -1){
    EEPROM.write(2, guifactor2);
    EEPROM.commit();
    count2factor = EEPROM.read(2);
    Serial.println(count2factor);
  }

  if (guifactor3 > -1){
    EEPROM.write(3, guifactor3);
    EEPROM.commit();
    count3factor = EEPROM.read(3);
    Serial.println(count3factor);
  }

  if (guifactor4 > -1){
    EEPROM.write(4, guifactor4);
    EEPROM.commit();
    count4factor = EEPROM.read(4);
    Serial.println(count4factor);
  }

  if (guifactorgas > -1){
    EEPROM.write(5, guifactorgas);
    EEPROM.commit();
    countgasfactor = EEPROM.read(5);
    Serial.println(countgasfactor);
  }

  if (guifactor1 > -1){
    EEPROM.write(6, guifactorwater);
    EEPROM.commit();
    countwaterfactor = EEPROM.read(6);
    Serial.println(countwaterfactor);
  }
}

void setup(){

}

The problem I have with my code is that it either doesn’t write the value to the EEPROM or it doesn’t read the value as it doesn’t print anything to the monitor.
I expected to read 1 2 3 4 5 6 from the monitor as I write the bytes to the EEPROM and then transfer the value to the unsigned long and print the variable.

What problem do you actually have? You didn't include any problem description. From your code I would say: guifactor1 and its siblings will be implicitly initialized with zero (since they are global and you don't explicitly initialize them). Checking guifactor1 > -1 won't ever be true, since you initialized them to zero and don't change them anymore, and also they are unsigned longs, so they cannot ever carry a negative value. You should rethink the logic of your program.

What does it print to Serial?

Your problem description is still too vague. Please describe exactly what you expected the code to do and what is actually did. Provide the expected and actual output. And write a minimal compilable example code, that shows your problem. We cannot debug code that we cannot see

What is the sense behind the if statements? guifactor1 and siblings still cannot ever be -1, since byte is the same as unsigned char which also cannot hold negative values. Also you still don't change these variables ever. So you won't see anything. The code inside the if statements is never reached

the question was about the reading and writing to the eeprom i have not given all of my code and it isnt finished i was just testing

If you are asking just about the code lines reading and writing the EEPROM, then the answer is "Nothing is wrong with it." The problem must be somewhere in the code that you refuse to show. And we just cannot help you with that. Our mind reading powers are limited.

the problem is solved

You know that EEPROMs are limited in the number of write operation, do you? As you're writing to EEPROM in loop without any delay, this code is one way to kill the EEPROM quite fast.

If your problem is solved, please mark the answer. Or if it does not answer your question, write an own. This site is to help many, not only you.

You forgot to call Serial.begin() in setup().
As a side note, your if tests are useless. The compiler warns me that:
comparison is always true due to limited range of data type

For reference: the previous answer, valid for the initial question
where guifactor1 and co. were all unsigned long.

The program does nothing because all the actions are conditioned on
tests such as
if (guifactor1 > -1)

and these tests are always false. The reason they are false is because
arithmetic comparison operators such as < perform usual arithmetic
conversions on their operands prior to doing the actual
comparison. Since guifactor1 is unsigned long, and this type has a
higher conversion rank than int (the type of -1), the second operand
is implicitly converted to unsigned long, yielding ULONG_MAX.

this is not my entire code. i didnt upload all of it because it could be a bit overwelming. i edited the code above so that the problem is a bit more clear i also changed the unsigned long to a byte.

@JayvandeWetering: Please, test the program you posted (not your original code, but the exact code that is in your question, as you just amended it) and make sure it does show the incorrect behavior.

i have tested the program i posted and it still either doesnt write or doesnt read from the eeprom

@JayvandeWetering: How do you know it doesn't write or doesn't read? Please update your question with the relevant details.

i think i updated the question enough so that it is clear what is expected and what is the actual output


text:
100khz square wave with 50% duty cycle
How to generate 100khz square wave with 50% duty cycle using arduino uno
The following code was tried but did not give appropriate output
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delayMicroseconds(5); // wait for 5 micro seconds, 100khz frequency with  50%
                           // duty cycle
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delayMicroseconds(5);              // wait for 5 micro seconds
}

https://www.arduino.cc/en/Reference/DelayMicroseconds and https://www.arduino.cc/en/Reference/Micros explain that the micros has a resolution of 4µS: "has a resolution of four microseconds (i.e. the value returned is always a multiple of four)."

Let us start with something easy: What are you assuming about loop() and digitalWrite()? 0 us?

The problem with your program is that it does not loop fast enough. Each
call to delayMicroseconds() should take roughly the requested time to
execute, but the CPU also needs time to execute the rest of your code,
including the time needed to return from loop() and call it again.
The period of the signal ends up being considerably longer than the
desired 10 µs.
The simplest software-only approach would be to get rid of the delay
using the technique described in the Blink Without Delay Arduino
tutorial. With one twist: instead of
// save the last time you blinked the LED
previousMillis = currentMillis;

you would use
// save the last time you should have blinked the LED
previousMillis += interval;

This way the small timing errors do not add up: you get, on average
the correct period. Oh, and obviously, you track time in microseconds,
not milliseconds:
const uint16_t TOGGLE_TIME = 5;  // toggle pin every 5 us

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

void loop() {
    static uint16_t last_toggle;
    static uint8_t pin_state = LOW;

    if ((uint16_t) micros() - last_toggle >= TOGGLE_TIME) {
        pin_state = !pin_state;       // invert pin state
        digitalWrite(13, pin_state);
        last_toggle += TOGGLE_TIME;
    }
}

This may somehow work if you have a fast enough Arduino, maybe a Due or
a Zero. If you have an AVR-based board (like the Uno and actually most
Arduinos), you will not get anything faster than ≈ 50 kHz with
this. This is because digitalWrite() is sooo slooow, it cannot cope
with your 100 kHz. You can improve things by using direct port
access[] instead of digitalWrite():
void loop() {
    static uint16_t last_toggle;

    if ((uint16_t) micros() - last_toggle >= TOGGLE_TIME) {
        PINB = _BV(PB5);             // invert pin state
        last_toggle += TOGGLE_TIME;
    }
}

Now you have roughly the requested frequency, but with some terrible
jitter: testing on my Uno I could see each level being held for
slightly less than 5 µs. Then, from time to time, one level is
held for ≈ 9 µs. Things could still be made faster by wrapping
the if inside an infinite loop, instead of relying on the Arduino core
to repeatedly call loop():
void loop() {
    uint16_t last_toggle = 0;

    for (;;) {  // infinite loop
        if ((uint16_t) micros() - last_toggle >= TOGGLE_TIME) {
            PINB = _BV(PB5);             // invert pin state
            last_toggle += TOGGLE_TIME;
        }
    }
}

And now the signal looks still worse: with the program running faster,
levels are held most of the time for only 3.5 µs, and then one out
of every ≈ 4 levels is held for about 9 µs. The average
frequency is probably right, but the jitter is absolutely awful, which
is likely due to the 4 µs resolution of micros() noted by user
Talk2.
The conclusion from these tests is: your only hope to get a somewhat
clean signal at this frequency is to generate it in hardware, not in
software. Choose one of the timers and have it generate the signal you
want. I would avoid timer 0, as it is needed by the Arduino timing
functions (delay(), millis()...). Here is how it can be done with
timer 2:
void setup() {
    // The output will be on digital 3 = PD3 = OC2B.
    pinMode(3, OUTPUT);

    // Configure timer 2 for PWM @ 10 kHz on OC2B.
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // mode 7: fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(WGM22)   // ditto
           | _BV(CS21);   // clock @ F_CPU / 8
    OCR2A  = 19;          // period = (19 + 1) * 8 CPU cycles
    OCR2B  = 9;           // HIGH for (9 + 1) * 8 CPU cycles
}

void loop() {
    // Nothing to do here, the signal is generated in hardware.
}

And now you have a perfectly clean 10 kHz square wave, while your
program is free to do other stuff at the same time. Notice that the
output is now on pin 3: the pin choice is limited when using the
hardware-based approach. Notice also that you loose the PWM capability
on pin 11, since it depends on timer 2.

First, be sure to use the "{}" in the menu to show your code in a code block
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT); }

// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delayMicroseconds(5); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delayMicroseconds(5); // wait for a second }

I think you could benefit from reading the Secrets of PWM
using a microsecond delay will only give you an approximate pwm signal.

The Arduino's programming language makes PWM easy to use; simply call analogWrite(pin, dutyCycle), where dutyCycle is a value from 0 to 255, and pin is one of the PWM pins (3, 5, 6, 9, 10, or 11). The analogWrite function provides a simple interface to the hardware PWM, but doesn't provide any control over frequency. (Note that despite the function name, the output is a digital signal, often referred to as a square wave.)


text:
Problems with Powering Led Project Through Vin Pin
I am working on lighting some WS2812 Leds with a nodemcu form hiLetgo. The project works when it is powered from the usb that is on the board, but as soon as it is powered from the barrel jack, the leds will only light up to the last color that they were set, ignoring code. A schematic and code are included for reference.
#include <ESP8266WiFi.h>
#include <Adafruit_NeoPixel.h>

// Which pin on the ESP8266 is connected to the NeoPixels?
#define PIN            D8

// How many NeoPixels are attached to the ESP8266?
#define NUMPIXELS      30

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int delayval = 10; // delay for half a second
int x, y, z;

void setup() {
  // put your setup code here, to run once:
  pixels.begin(); // This initializes the NeoPixel library.
  x = 0;
  y = 0;
  z = 0;
}

void loop() {
  // put your main code here, to run repeatedly:
   for(int i=0;i<NUMPIXELS;i++){
    x = (x+1)%256;
    // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255

    pixels.setPixelColor(i, pixels.Color(x,y,z)); // Moderately bright green color.

    pixels.show(); // This sends the updated pixel color to the hardware.

    delay(delayval); // Delay for a period of time (in milliseconds).

  }
  y= (y+1)%256;

}

can you confirm that the code is actually running when powered from  barrel jack

I have tested it with other code that shows that the code runs when powered form the barrel jack.

What voltage are you providing through the barrel jack?

5v according to the power brick, but according to my multi it's more like 5.2 - 5.3v. Also, it is rated at 3a.

First: What is the purpose of that resistor you have in there? It serves no purpose as far as I can see, and would only cause problems anyway. Lose it.
Second: You have logic voltage level problems:

You are supplying 5.2V to the LEDs.
The ESP8266 is a 3.3V device.
The ESP8266 outputs 3.3V as a logic HIGH.
The WS2812 accepts 0.7Vdd as logic HIGH (as stated in the datasheet).
0.7 × 5.2 = 3.64v

Ergo, the LEDs aren't seeing the logic HIGH signal as logic HIGH because it is too low a voltage.
Add to that the voltage drop across the resistor and your logic HIGH voltage will be even less.
So:

Lose the pointless resistor
Either reduce the supply voltage to the LEDs or increase the output HIGH voltage level with a logic level shifter circuit (3.3v -> 5v).

According to Sparkfun (https://learn.sparkfun.com/tutorials/ws2812-breakout-hookup-guide) it is important to use the resistor to protect the data pin.

@user3242816 They're talking gibberish. Protect it from what?!

My assumption was from excessive current draw, but I'm relatively new to the hardware side of electronics.

The only effect you would see from that resistor is a slight voltage drop and a low-pass filter formed with the input capacitance of the data pin that limits the maximum frequency you could use. There is nothing to draw excess current, since there is no fan-out, only a 1:1 connection from a low-impedance output to a high impedance input.

Interesting. I gave bypassing the resistor with a piece of wire a shot and now it works. Thank you for your advice!


text:
Sending number as byte through serial
I'm trying to send data from an Arduino to an Android device.
I saw an online guide for that which provided this code:
void setup()
{
  Serial.begin(115200);
}

void loop()
{
  byte msg[64];
  int len = Serial.available();
  if (len > 0)
  {
    len = Serial.readBytes((char*)msg, sizeof(msg)); // readBytes seems to need a char* not a byte*
    Serial.write(msg, len);
  }
}

I tried that example and it is working perfectly!
But when I put Serial.write("3");
in the setup loop after Serial.begin(115200);
it appears as question mark on my Android device,
I guess that I'm not sending it as a byte,
I searched online but without any luck.

What appears in the serial terminal when connected to a PC?

How are u communicating with the android device? Don't u mean that you are sending data from your PC to the android, through the arduino?

It sounds like you have the Arduino hooked up to the Android via a USB cable and are using a terminal emulator on the Android to communicate with the Arduino, with the code in loop() doing a simple echo of what you type in the terminal emulator. Is that right? Everything works using the example above, but when you modify it to send the string "3" to the Android, kind of like a prompt, the "3" is not displayed correctly. Am I missing something?

Start by changing it to Serial.write("3", 1);
Does that help, you're missing the second parameter to the Serial.write call, which is the number of characters (bytes) to write.

The second parameter isn't necessary for c strings, it will read until it sees the null terminator https://www.arduino.cc/en/Serial/Write

I think this is a timing issue. It is fairly normal for a garbage byte or two to be received shortly after doing a Serial.begin() because the transition of "not defined" (or high impedance) output to Serial (which is normally all 1-bits) can cause the receiver to think it got a start bit, and then misinterpret what follows.
Try adding a short delay after Serial.begin. You could also try a pull-up resistor on the serial Tx line to ensure it is high prior to Serial.begin being called.
Your use of Serial.available effectively builds in a delay.


text:
TX light not flashing, screen.print works sometimes.. UNO
I've got 2 Analog accelerometers and a Gyro/Acc/Mag connected to my arduino and it's been working and reading fine until a few hours ago.
I've got the arduino sending data over the serial connection and Unity reading the values and interpreting.
#include <Wire.h>
#include <LSM303.h>
#include <L3G.h>

LSM303 compass;
L3G gyro;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  compass.init();
  compass.enableDefault();
  gyro.init();
  gyro.enableDefault();
}

void loop() {

  /* Accelerometers: */

  int sensorValueA = analogRead(A0);
  int sensorValueB = analogRead(A1);
  //Serial.flush();
  Serial.print(sensorValueA);
  Serial.print(",");
  Serial.println(sensorValueB);
  delay(10);

  /* Accelerometer + Magnometer: */

  compass.read();
  //Serial.flush();
  Serial.print(compass.a.x);
  Serial.print(",");
  Serial.print(compass.a.y);
  Serial.print(",");
  Serial.print(compass.a.z);
  Serial.print(",");
  Serial.print(compass.m.x);
  Serial.print(",");
  Serial.print(compass.m.y);
  Serial.print(",");
  Serial.println(compass.m.z);
  delay(10);

  /* Gyro: */

  gyro.read();
  //Serial.flush();
  Serial.print((int)gyro.g.x);
  Serial.print(",");
  Serial.print((int)gyro.g.y);
  Serial.print(",");
  Serial.println((int)gyro.g.z);
  delay(10);

}

If I have it unplugged for several minutes then replug it, the print will work for a min or two then just stop completely. I've checked wires several times and it hasn't moved since it was working this morning.
As I said, which I think is probably of importance, the TX light is off when not printing.

Acc1: GND - GND | VCC - 3.3v | Y - A2
Acc2: GND - GND | VCC - 3.3v | Y - A3
Gyro: VIN - 5v | GND - GND | SAO - A4 | SCL - A5
Thanks

My guess is your I2C communications are locking up.  We'd need to see your setup though (schematic, pictures, etc) to be able to help further though.

Are you able to reproduce the problem with only 1 sensor attached?
If you can, that makes debugging much simpler.

Include a counter variable that increments once per pass of loop(). Dump the value before you start all the printing commands, then see if the lockup is happening after a similar running time. I've had this happen before with a straightforward "breathing LED" sketch: my cheap Chinese Uno was fine but my genuine version would hang after 90-120 seconds. Never got to the bottom of it!


text:
How do I write efficient callback functions on a Teensy 4.0?
I am looking at refactoring my code by implementing callback functions in order to be able to reuse the abstract logic of other functions/classes.
However, I feel I need to learn more about the limits of callback functions on embedded systems like the teensy 4.0 I'm using. The reason I ask is because - if I'm correctly informed - std::function is adviced against on embedded systems due to memory overhead. Another reason for asking is that the functions I want to use for callback might run the risk of violating the principle of keeping callback functions short.
I've consulted the chapter devoted to embedded programming principles in Stroustrup's Programming: Principles and Practice Using C++. Unfortunately, he doesn't give advice on callback functions for embedded systems, specifically.
I understand I can simply rely on a trial and error methodology using function pointers, but figured I'd ask for your experience and advice before I rewrite a lot of code. In other words, I'm asking for good principles and guidelines.

I frequently use callbacks in embedded systems, on much less capable MCUs than the Cortex (328p f/ex). The call overhead is minor - a call through a pointer instead of calling direct. This page has a guide to callbacks on the Teensy.

Do your callbacks need to carry state (i.e. be functor objects holding data), or would you just be using naked functions (or non-capturing lambdas)?

@EdgarBonet Off the top of my head it'll primarily be naked functions, but It's possible I'll also need other types of use cases.

I have been using callbacks quite intensively on an Arduino Mega 2560,
for managing RS-485 messages. This board has roughly 8 times less flash
and 128 times less RAM than your Teensy. However, as the AVR core does
not support std::function, I used the good old C idiom for defining
callbacks:
void MyClass::register_callback(
        void (*callback)(some_type some_data, void *callback_data),
        void *callback_data);

It is up to the caller to nicely pack all the state needed by the
callback into a struct, and pass a pointer to this struct as the
last argument of register_callback(). The class will record both the
function pointer and the void* pointer. When the expected event
happens, the class calls the callback, giving it the saved void* as
its last argument. The callback then casts this pointer to a pointer to
the expected struct, and now it can access the state it needs.
Yes, this is a bit clumsy, but it is a tried and true way of handling
callback state in plain C. And the cost is marginal, especially for your
board that has orders of magnitude more resources than my Mega.
If you are afraid of the cost of std::function, I suggest you
implement a simple callback example using this method, then using
std::function, and you compare the memory usage. If the cost of
std::function turns out to be significant, you can always go the C
way. I suspect std::function will be just fine, and it really is more
convenient than handling the function pointer and the state as separate
arguments.

Interesting, I'll look into it. Thanks for your reply!


text:
Arduino and PHP communication only work if I open the Arduino IDE
I have a problem. I try to open a channel to arduino and PHP talk, the PHP would send a command and the Arduino should answer that. It works, but only if I execute some steps before:

sudo chmod 777 /dev/ttyACM0
sudo arduino
Open the serial monitor in arduino IDE
Close the serial monitor
Now everything is ok, they can talk

The first step is ok, I really need to do this, the 2-4 seems irrelevant, but the communication do not start without it. I put one LCD in arduino to print what he receive, when I send "HEYARD" with PHP to him, the RX led blinks and the TX led also, but nothing is printed on LCD. If I do the 2-4 steps, when PHP send "HEYARD", LCD show HEYARD and arduino answer with "HEYPHP"
Anyone could help? There is some way to open it via Terminal, or, at least, open the Serial Monitor from arduino and close to see if this start

Does the PHP code set the correct baud-rate, parity etc.?

Yes, everything seems ok, the baud-rate is right, parity is "none", they can talk normally, but only if I open the serial monitor before.
I tried open the screen in terminal, but also do not worked, need to be the serial monitor.
Thank you

Try a proper terminal emulator like Minicom.

It could be that Arduino is setting the correct settings for /dev/ttyACM0, so others after it won't have to but should. Could you post the PHP code and screen command?

I tried use the minicom, until now, I could not read anything, but I will try make it start the port.

Here the setup block:
<?php
    require("php_serial.class.php");
    $serial = new phpSerial();
    $serial->deviceSet("/dev/ttyACM0");
    $serial->confBaudRate(9600);
    $serial->confParity("none");
    $serial->confCharacterLength(8);
    $serial->confStopBits(1);
    $serial->confFlowControl("none");
    $conect = mysql_connect("localhost", "root", "") or print (mysql_error());
    mysql_select_db("ANM", $conect) or print(mysql_error());
?>

And here the connection block:
<?php
    $serial->deviceOpen();
    exec("echo 'HEYARD' > /dev/ttyACM0");
    sleep(1);
    $read = $serial->readPort();
?>

stty -F /dev/ttyACM0 ignpar
stty -F /dev/ttyUSB0 ignpar

IGNPAR Ignore framing errors and parity errors.

That is what you need to fix minor framing issues.
Screen switches this by default; but NONE of the serial drivers do.
Especially when connecting PIs or BBB to Arduinos


text:
Attiny88 problem with LEDs and voltage
I have the following problem and wonder if anyone may have some inside into what may be happening.
I have an array of 20 leds that i manage to multiplex using the attiny88 using only 9 pins (4 columns by 5 rows). At any given time only one led is on. The different leds are activated with a pushbutton. Initially, i used five transistors with a 1k resistor to turn on and off the rows of the led array.
Everything worked like a charm even at voltages as low as 2.5 vol. I then decided to remove the transistors to free-up some space in my pcb. Now the circuit works well at voltages above four but at 2.5v it makes leds to turn on randomly, when pressing the pushbutton.
I presume this behavior is because the one led is taking to much current, but i wonder why could be the case if the chip is only driving one led at a time. Also keep in mind that the circuit works very well at 4vol.
Any clue about this and how could i fix it? I like the idea of not using the transistors.

Schematics please

Do you have the required current limiting resistors? If yes, where in the circuit are they? What value are they? A schematic is an invaluable resource for diagnosing your problem - without it we cannot have a hope in working out what is happening.

driving one led at a time. Are you sure you aren't lighting 4 leds at a time (one entire row).

Iwill have the schematic tomorrow. One thing i read is that some pins that do  no have pwm

I will have the schematics tomorrow. One thing i read is that maybe some pins without pwm may turn high at low voltages. Testing this is complicated for me as it is some massive rewiring. Any thoghts on this?


text:
Program Arduino Uno as a digital clock
I have an arduino Uno board with a screen attached on top (http://www.freetronics.com.au/pages/16x2-lcd-shield-quickstart-guide#.VUf0tMWN0iT This is the screen).
I'm trying to get it so that the screen displays the time in hours, minutes and seconds and counts on a 24 hours loop. Like a digital clock. I have it so that it can count but it just counts up to 99 then repeats.
I have this code which counts milliseconds but I need minutes and hours
    #include <Wire.h>
    #include <LiquidCrystal.h>

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    void setup()
{
    lcd.begin( 16, 2 );
}

    void loop()
{
    lcd.setCursor ( 0, 1);
    lcd.print(millis());
}

Why not trying the timer interrupt from atmega328 uC. You'll also learn something usefully and I think is more interesting than using a library and some methods ( functions) without knowing how they are implemented.
It's really simple to make a digital clock just by interrupting every second. In ISR you'll just have to update the the values for seconds/minutes/hours. For displaying on the LCD, if you don't want to mess with LCD commands and bytes, you can use LiquidCrystal.
Example of code:(here I also used an analog pin for modifying time)
#define F_CPU   16000000UL
#include <avr/delay.h>
#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const short buttonPin = 5;
volatile unsigned char seconds;
volatile unsigned char minutes;
volatile unsigned char hours;
void update_clock()
{
    seconds++;
    if (seconds == 60)
    {
        seconds = 0;
        minutes++;
    }
    if(minutes==60)
    {
      minutes=0;
      hours++;
    }
    if(hours>23)
    {
      hours=0;
    }

}

ISR(TIMER1_COMPA_vect)
{

  update_clock();

}

void setup()
{

  // initialize Timer1
  pinMode(A5, INPUT_PULLUP);
  cli();          // disable global interrupts
  TCCR1A = 0;     // set entire TCCR1A register to 0
  TCCR1B = 0;     // same for TCCR1B

  // set compare match register to desired timer count:
  OCR1A = 15624;
  // turn on CTC mode:
  TCCR1B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR1B |= (1 << CS10);
  TCCR1B |= (1 << CS12);
  // enable timer compare interrupt:
  TIMSK1 |= (1 << OCIE1A);
  sei();          // enable global interrupts
  lcd.begin(16, 2);
  lcd.print("HH:MM:SS");
  Serial.begin(9600);

}

void display_on_lcd()
{

  lcd.setCursor(0, 1);
  lcd.print(hours);
  lcd.setCursor(2,1);
  lcd.print(":");
  lcd.setCursor(3,1);
  lcd.print(minutes);
  lcd.setCursor(5,1);
  lcd.print(":");
  lcd.setCursor(6,1);
  lcd.print(seconds);

}

void loop()
{

  display_on_lcd();

  Serial.println(analogRead(5));
  if(analogRead(buttonPin)<1000)
  {
    if(minutes==59)
    {
      minutes=0;
      if(hours==23)
        hours=0;
      else
        hours++;
    }
    else
    {
      minutes++;
    }
  }

}

Just search and you'll find a lot of examples.

Nice sample! Do you think it's better to use the Timer Interrupts instead of the millis() function?

I really don't know how millis() is implemented to say why my implementations in bettter that one with millis(). I thought that is more "natural" to implement with timer interrupt compare, cause in real embedded you don't have a millis() function. Also, millis() return an unsigned long and that is a lot of bits. If you have a microcontroller with limited memory, you can't declare & store a lot of unsigned long variables just for calculating time. Also, think about that, for example, in the code with millis() you call the function on each iteration in while-loop and update the values.

those calls to function will generate delays ( clock cycles). also, for this type of problem you have to use extra variables? why to declare 3 more variables unsigned long currentMillis, previousMillis, elapsedMillis; when I only need seconds/minutes/hours. extra code! not talking about how much clock cycles take the branches. Again, not saying that is better with timer interrupts compare, but maybe the code is cleaner, less memory is used etc. millis() is more like a nice to have function, and was developed just to make development simpler but not to use in real projects.

Thanks for the clarification! yes, im with you, its more reliable and cost-efective. Thanks again

Simple but really unnecessary.  You already have a timer interrupt doing this in the core, why do you need a second one?  Now you've got two timers tied up instead of one.  Now Timer0 and Timer1 are both tied up counting time and now you've made Timer1 unsuitable for PWM.  Why not just stick with the timer interrupt that's already incrementing milliseconds and calculate the time from that?

Im with @arvid-jense on this one, if you are working on a serious Digital Clock, then you should get the Real Time Clock.
Now if you are learning Arduino and want to play with your LCD Minidisplay and build a clock, you must know some important limitations of the millis() function on this project:

The mills function will overflow, after approximately 50 days.
Your clock will be inexact because the cycles of the Arduino
loop, you will be checking how much mills has passed on each loop.
(it will be lagging ~ 10 seconds each day, so on day 7 you will be one minute late)
the parameter for millis is an unsigned long, errors may be generated
if a programmer tries to do math with other datatypes such as ints.

That being said
#include <Wire.h>
#include <LiquidCrystal.h>

/**
 * Clock Variables
 */
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds, minutes, hours;

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup()
{
    lcd.begin( 16, 2 );
}

void loop()
{
    setClock();
    /**
     * After set clock now you have 3 int variables with the current time
     */
     //seconds
     //minutes
     //hours
     lcd.setCursor ( 0, 1);
     lcd.print(millis());
}

void setClock()
{
    currentMillis = millis();
    elapsedMillis += currentMillis - previousMillis;

    /**
     * If we use equals 1000 its possible that because of the mentioned loop limitation
     * you check the difference when its value is (999) and on the next loop its value is (1001)
     */
    if (elapsedMillis > 999){
        seconds++;
        elapsedMillis = elapsedMillis - 1000;
    }

    if (seconds == 60){
        minutes++;
        seconds = 0;
    }
    if (minutes == 60){
        hours++;
        minutes = 0;
    }
    if (hours == 24){
        hours = 0;
    }

    previousMillis = currentMillis;
}

Nice tutorial on building an Alarm Clock

Your MILLIS_OVERFLOW is wrong. On recent versions of the Arduino library, millis() overflows at 2^32 (49.7 days), which means that testing for the overflow is useless.

Didn't know, thanks! i updated the constant MILLIS_OVERFLOW. (it's a digital clock, testing for the overflow isn't useless). Anyway, i think that the proposed solution by @23ars using Timer Interrupts is better than mine.

This code is still incorrect. Testing for the overflow is definitely useless: per the rules of modular arithmetic, which are guaranteed for unsigned numbers by the C and C++ languages, currentMillis - previousMillis will always yield the right answer, regardless of overflows.

@EdgarBonet sorry, but i don't get it. Did you test this code on Arduino? Please could you explain how this code should work without testing for the overflow. Thanks!

I tested it right now. When millis() overflows, it goes like crazy changing the time at each loop iteration. If you remove the test for the overflow, it works just fine. If you read carefully the liked article on modular arithmetic, it should be obvious that the test is useless.

I get it, i removed the test for the overflow. The difference will be always reflected by the two unsigned numbers.

Others mention a Real-Time Clock (RTC), and it may look like the obvious choice, but maybe it isn't. All a RTC does is keep counters for hours, minutes, seconds, date and month, but your microcontroller can do that as well.
Unfortunately the Uno doesn't have a crystal, but a ceramic resonator, which isn't nearly as accurate. Not that it matters much, even a crystal-based RTC may deviate several seconds a day. You can measure the error over a long time, and correct at regular times in software, but this is tedious.
If you want long-time accuracy there are two cheap ways:

use an atomic clock receiver. In Europe there's DCF77, in North-America it's WWVB which broadcasts very accurate date and time information. A receiver module for these costs around 10 dollar
use the mains frequency to clock your clock. On the long term this is extremely accurate (just think about your alarm clock: how often do you have to adjust that?) In Europe you would count 100 half periods per second (120 in the US). When your counter reaches that count, reset it and increment the seconds. If seconds reaches 60, reset it and increment minutes. And so on. If you're not exactly electronics-savvy you can ask on electronics.stackexchange.com to help you out. It's not difficult.

Getting a RTC over an Arduino will do you much better. The whole point of an RTC is to use a temperature stable crystal that is guaranteed to keep N seconds of accuracy every year.  The accuracy varies by model but the arduino xtals or ceramics will drift wildly faster

@portforwardpodcast: yes, the Arduino ceramic resonators will drift more than a crystal, but even a crystal-controlled RTC can drift a couple of seconds a day. That's a minute a month. You'll have to synchronize your clock from time to time anyway, so why not allow the Arduino's relative inaccuracy and sync once a day. With an RTC you'll have to do that too, only less frequent.

Also, while there exist temperature-compensated oscillators, the 32kHz crystals used for RTCs are not temperature stable.

Well you need to break this problem down.
If you are currently able to count in milliseconds, then you know 1000 milliseconds equal 1 second, so every time the milliseconds equals 1000, you reset it to 0 and increment the seconds by 1.
You keep going from here, if seconds equals 60, then you increase minutes by 1, and reset seconds to zero.. You get the picture.

Thanks everyone for your help! I've ended up with the code below which works quite well, there's the odd glitch with the seconds which is for some reason fixed if milliseconds is added on the end, but other than that it works very well.
#include <Wire.h>
#include <LiquidCrystal.h>

#define MILLIS_OVERFLOW 34359738

/**
* Clock Variables
*/
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds, minutes, hours;

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup()
{
  Serial.begin(9600);
  lcd.begin( 16, 2 );

}

void loop()
{
    setClock();
    /**
   * After set clock now you have 3 int variables with the current time
   */
   //seconds
   //minutes
   //hours
     lcd.setCursor ( 0, 1);
     lcd.print(hours);
     lcd.print(":");
     lcd.print(minutes);
     lcd.print(":");
     lcd.print(seconds);
     lcd.print(":");
     lcd.print(elapsedMillis);

}

void setClock()
{
    currentMillis = millis();
    /**
     * The only moment when currentMillis will be smaller than            previousMillis
     * will be when millis() oveflows
    */
    if (currentMillis < previousMillis){
    elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
} else {
    elapsedMillis += currentMillis - previousMillis;
}

/**
 * If we use equals 1000 its possible that because of the mentioned loop limitation
 * you check the difference when its value is (999) and on the next loop its value is (1001)
 */
if (elapsedMillis > 999){
    seconds++;
    elapsedMillis = elapsedMillis - 1000;
}

if (seconds == 60){
    minutes++;
    seconds = 0;
}
if (minutes == 60){
    hours++;
    minutes = 0;
}
if (hours == 24){
    hours = 0;
}

previousMillis = currentMillis;
}

The takeaway from the previous answers is that your best option is to
use an RTC (real-time clock). Failing that, you can emulate the RTC
using millis(), at the cost of a significant drift, especially if your
Arduino is clocked off a ceramic resonator.
I would just like to add that you do not have to write the logic of that
millis()-based “soft RTC” yourself, as this has already implemented in
the RTC_Millis class from Adafruit's RTClib:
#include <RTClib.h>
#include <LiquidCrystal.h>

RTC_Millis rtc;
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup() {
    rtc.begin(DateTime(F(__DATE__), F(__TIME__)));
    lcd.begin(16, 2);
}

void loop() {
    static DateTime last_time_printed;
    DateTime now = rtc.now();
    if (now != last_time_printed) {
        lcd.setCursor(0, 1);
        lcd.print(now.timestamp(DateTime::TIMESTAMP_TIME));
        last_time_printed = now;
    }
}

One nice thing about this option is that, if you later opt for a real
RTC, you will only need to do minimal changes to your code. Another nice
thing is that, if you measure the drift of your clock, you can easily
correct it: just replace RTC_Millis with RTC_Micros
and call rtc.adjustDrift() in setup(). You will be able to adjust
the drift with a 1 ppm resolution. Note that both RTC_Millis
and RTC_Micros are immune to rollover problems.

How stable is a ceramic resonator though? Doesn't the drift vary? A quartz crystal based clock is quite stable, so an adjustment factor should be quite effective, but doesn't the speed of a ceramic resonator vary by a good bit more than a quartz crystal?

@DuncanC: It does vary quite a bit indeed, but the average drift is typically larger than the drift variations.

Not sure what you're asking, but getting a Real Time Clock module will make your life a lot easier when dealing with time. Maybe post some sample code to show what your issue is.


text:
Salvaged Stepper Motor Blues
So recently my company threw away some rather large and reasonably old laser printers. One was a LaserJet 9050dn the other was a Epson printer/scanner combination. Being a little industrial I thought let me salvage them and brought them home.
I managed to salvage a couple of stepper motors. However I am having huge trouble is getting them to step properly. So lets get into the details.
Components used:

1x Freetronics eleven (Arduino Uno compatbile)
1X H-Bridge driver shield(Freetronics rated for 40V/2A max).
1X Old scanner power supply which has a output of 24V/2A.

Currently there are two stepper motors I am interested in using. They have the following part numbers:

1X MITSUMI M42SP-4N
1X Minebea-Matshushita 17PM-J212-G2ST

Just to keep this short I am going to focus on the Minebea-Matshushita 17PM-J212-G2ST. I have been unable to find exact matches on these serial numbers when looking for datasheets but I have managed to find the following sheets on the net.

Minebea-Matshushita 17PM-K datasheets found from Minebea. However I cant match the model exactly.
Minebea Stepper Motor Information & Specifications also carries some useful information.

So it appears that these are 24V steppers(in both cases). The Minebea-Matshushita 17PM-J212-G2ST appears to have a step angle of 1.8 degrees which should give me 200 steps per revolution. I have not been able to find the current needed to drive this motor but judging by the looks of things it will be between 0.8A and 1.2A.
I then used my multimeter to find the pairs of wires. It has 4 wires coming out (Bipolar motor I guess). The colours of the wires are red, yellow,orange and blue. First pair was red and yellow with red being positive/anode. Second pair orange blue with orange positive/anode side.
I wired my power supply into my h-bridge and started using the recipe and quickstart found at the freetonics site. This is where the frustration begins. When asking the motor to do one complete revolution(360 degrees) it does more than 360 degrees at times and other times it does less. I tied a cable tie to the motor so I can confirm it.
So I tried the one-step-at a time sketch to see if I can troubleshoot it. Here is what I have noticed. The steps are mostly correct one step at a time clockwise however every now and again it will jump counter clock wise and then clock wise again. I suppose you can call it a jitter.
Interestingly both these motor show the same behaviour pretty good step action just every 25 degrees or so a jitter. So I suspect that this might not be bi-polar motors but uni-polar? This blog entry points me to believe that this might be the case. However the datasheet in this case points to a M42SP-7.
So my question would be simple how do I figure out if they are bi-polar or uni-polar?
Can someone help me with a proper datasheet?
Any tips would be really appreciated.
Update:
Note that I can get both motors to step clock-wise and counter clock-wise I just cant get them to do a whole 360 degrees without a jitter. Based on the Wiring Mitsumi stepper ( M42sp-4np) with arduino blog  it appears that the Mitsumi is a uni-polar motor with a 2-2 phase excitation. What stumps me is that the wires are paired thus it must be bi-polar?
So last night I tried 2-2 phase excitation with the MITSUMI M42SP-4N and it appears to be solve the problem with this motor in particular. From early observations the motor now steps without jitter, however it was late so I will need to confirm this.
I was previously using 1-1 phase excitation i.e.
Step number: 1a 1b 2a 2b
1            1  0  0  0
2            0  0  1  0
3            0  1  0  0
4            0  0  0  1
5            1  0  0  0

When using 2-2 phase excitation I get a more steady step however this needs to be confirmed a bit more:
Step number   1a 1b 2a 2b
1             1  0  0  1
2             1  0  1  0
3             0  1  1  0
4             0  1  0  1
5             1  0  0  1

Just some added observations. The headache continues but I am learning a LOT about steppers motors.
Update:
Not a 2-2 phase excitation these are definitely bi-polar. I am currently watching the Minebea-Matshushita 17PM-J212-G2ST do 360 degrees both clock and counter-clockwise. I hooked them up to a 12V/1A power supply both motors are running smoother and cooler and stepping relatively jitter free. I suspect the whole issue is a lack of a proper data-sheet.
Will update as things progress and once solved add pictures and sketches so the next lucky sod wont loose as much hair as me.
Update:
Thanks to Chris who made me look at the sketch in detail again. These motors seem to have a minimum rpm of sorts. I was trying to go for a really slow rpm under 5rpm at this speed these motors show the jitter effect. However when moving the speed to 10rpm and up no jitter.

If it's a unipolar, you wouldn't get more than 2 steps out of them. Also, I don't think any unipolar exists with only 4 wires. Try lowering or raising the current limit.

As an experiment, try making the step speed such that it takes a number of seconds to complete a revolution.  If that is really a 24v motor, it's probably going to be disappointing in performance (usually one uses a motor having a coil rated for a few volts, with a chopping current drive with many times that in available supply voltage).  While it's really AC impedance (inductance) that you need to worry about for performance, what do you measure as the DC resistance of a coil?

@ChrisStratton I suspect that these motors might be using 2-2 Phase Excitation for stepping the recipe I am using appears to be 2-1 Phase Excitation. I have tried driving these with both 12V/1A power and 24V/2A power and getting same results. I am going to experiment a little more tonight but I suspect that the cause might be the phase excitation.

That seems unlikely to be the issue - at least when unloaded mechanically you should be able to get movement either way.  Don't rule out your program glitching especially if there are any bad interactions between motor and logic supplies.  Consider having the arduino log to the serial a continuous count of the pulses emitted, and make sure it increases consistently.  And try running it slow enough that you can see each step.

@ChrisStratton thanks. I can confirm that this is the case I have made it step one step at a time and monitor the serial log. I used the one_step_At_a_Time example sketch. All seems well. Smooth increments of counter nothing. Also added an update on the 2-2 phase excitation.

Keeping this here for future reference. It appears these motors have a minimum RPM of sorts and running them on a lower RPM causes the jitter effect described above.
Like I mentioned in the updates when running at 10RPM or above these motors seem to perform very nicely.
Update: I recently bought a ADAFruit motorshield and I am getting much more stable results with this shield and the stepper motors. I am even running them off 6V and they are working perfectly even at lower rpm.

This is a rather mistaken conclusion.  There is no "minimum RPM" to a stepper motor.  However, there can be speed ranges where various resonances cause problems.

@ChrisStratton thanks for putting that so clear. I suspect now in retrospect that the different shields have different driver ic's which indicates the problem is probably with the shields and not the motors. Its been two years since I worked with shields as I started making my own.