text:
Is Arduino stable enough to use it for a door lock?
I want to replace my door lock with an one made with an Arduino and a servo, but I'm not sure if the platform is stable enough to use it for something like this.
If I do everything right (code, connections, constant power), could I trust in this?

If you use the watchdog timer, I'd trust the Arduino part. I would be more worried about the mechanical parts. Just make sure you have an alternative way of access. Just like the digital vaults that still have a key.

About safety: in case of power out, will your door be left open or closed? And if closed, do you have a way to get out, for example in case of fire? Sorry for offtopic comment, but it might be a case of life and death for some.

@Molot in case of fire maybe I could prepare a mojito and enjoy the temperature

IMHO, manage your security and access to vital things only with really reliable and unaffected by external events systems, as a well-oiled good-quality mechanical door lock. Sorry to write that in an arduino post.

Software/hardware stability aside, you may want to check with your insurance company to ensure that they regard your setup as something that qualifies as a "lock". In case of a break-in, you need to be sure your insurance won't be void because "your door was not locked".

If this is intended to be secure against an actual attempt to break in, make sure the electronics are far enough away from access and that the connection to the lock is protected. Otherwise, a simple high-voltage discharge to the lock could fry the CPU and possibly trigger an unlock.

I'm not sure if the platform is stable enough to use it for something like this.

Absolutely it is. As I describe in my post about an RFID door lock I use a Uno (and some additional parts) to unlock my door.
Since writing that I improved the software as described here so you can reprogram the valid list of cards "on the fly" (without uploading new code) as the valid cards are stored in EEPROM.

My system has been operating for over 5 years without any problems, except once when there was a brownout in the area and I had to power cycle the system (possibly the RFID reader failed and not the Arduino).
My system "fails shut" so it keeps the door locked in the event of a power failure. However I have alternate ways of leaving the building in the event of a power failure combined with a fire.
You are talking about a servo rather than an electric strike. That is likely to be the weak point, and not the Arduino as such. You would need to ensure it was powerful enough to do whatever-it-is you are planning to do, and that it had suitable drivers (eg. MOSFET or driver board).
My system gets used dozens of times each day. We never have a problem with it.

Pretty useful info. +1. Source is nice and simple. Just to be clear; do you feed that Uno 5V to the 5V pin? What's the power supply for 5V?

@user2497 - the Uno is powered by a 12V wall-wart. That gives 12V on Vin which is used to activate the door lock (it is a 12V model). The Uno itself has a voltage regulator on-board which drops the 12V to 5V for the logic circuits.

Oh, I thought I saw 5V to the MCU. I use 7808s between 12V and Vin now, since I had a few devices die on me. What's your secret - do you heatsink those tiny regulators?

@user2497 - the current consumption of the logic (Uno) is low. The door lock doesn't go through a regulator.

If you want to use an Arduino in this sort of environment, there are a few things to watch out for:

Heat (usually from sunlight striking the enclosure). This could be
relevant for your project, depending on the installation and location
of the door. Choice of enclosure material, colour and finish can all affect this.
Rollover of millis() (see http://playground.arduino.cc/Code/TimingRollover). After 55 days, the millis() function on the Arduino rolls over and resets back to 0. Depending on if/how you use this, it may affect you.
Power supply stability. If you choose to power your Arduino directly from 5v, ensure that it is a smooth stable supply. I've had noisy power supplies cause some weird resets and glitches.
Water ingress. Again, this depends on location. Don't forget to account for condensation and frost (if applicable).
Flyback from relay switching and locking solenoids. Add flyback diodes to relay coils and solenoids to stop any flyback voltages killing your control circuitry. See https://en.wikipedia.org/wiki/Flyback_diode

I've run in to all of these issues across various Arduino projects. They may not cause the system to fail completely, instead causing strange behaviour.
If you design your system to account for all of these factors, then it is absolutely reliable enough to run something 24x7x365.

But not on the last day of leap year?

As far as Water ingress goes, look for enclosure's and connectors rated IP67 or better.

@MichaelKaras - very amusing!

@MichaelKaras That's the routine maintenance day :)

@BigHomie IP67?!?! Only a few months ago everyone was trying to migrate to IPV6!  Just shows you how fast the internet moves...

I had a similar system running for my garage door for about six years without incident. It only died when lightning struck the fence next to it. Planning for lightning is harder..

If you can guarantee that your hardware and software skills are impeccable then you can certainly trust the MCU on the board. After all, the ATMega chips aren't toys, even though many people around here seem to treat them as such. They are a professional industrial product.
Of course, this is assuming that the Arduino you have is genuine and not some cheap Chinese knock-off with gawd knows what on the board.

Not to mention, try explaining to your insurance agent that the reason your house was broken in to was because you screwed up a pointer reference that caused your door to unlock at midnight. :) It's better to leave it up to a commercial lock—one that has been tested. The mere fact that the OP is questioning the board and their skills may suggest that they should get something already built, at least for securing their home.

The prices for the originals (Genuino here) are too high. Tell me how they are more reliable.

The last commercial lock I tried took almost a full minute to tell me anybody was at the door because it took a 27,000km detour to Amazon's servers first. Popular product, rhymes with bling, but was certainly not.

Replying to Majenko's answer with more depth. The limits of the Arduino hardware depend on the ATmega CPU it's built around (I suspect you'll be directly migrating from Arduino to the final PCB).

but I'm not sure if the platform is stable enough to use it for something >like this.

Thus it may be worth considering for you to read through the data sheet. I'd read through it and look at the parameters which could affect your project. For example, the ATmega is only designed to work properly within certain temperature ranges (so this may affect your lock if it's outdoors in the cold). If you're relying on the built-in timer for something in your project, then that can get affected by temperatures, for example — as opposed to using a quartz crystal for reliable timing.
So you'd need to think how your project can fail with the parameter limits of the hardware components. For example, if you're activating the door lock with a secret code stored on external memory, then the memory used may get corrupted when it gets near a magnetic field.

To add to the already good advice so far.
Safety and security wise you need to plan and anticpate for failure. An electromechanical lock or your power supply are hardware wise probably more likely to cause issue than the Arduino board, just watch for back emf and use a flyback diode or snubber as mentioned if required. There may be issues though in your code being stuck in a loop or say card reader or contact faults and so on, this may require a simple on-off at best.
Consider using a battery backed power supply for short blackouts or brownouts.
Then consider your lock type and what will happen in an emergency or with a fault.
Locks such as a strike or mortice lock allow you to use standard door hardware so you have the capability to use a free handle egress out so you won't be trapped in an emergency. You can then also fit a key barrel so if the lock has failed you have a backup way of entry.
With either type you can then have a fairly good balance of safety and security, if you set it up as fail secure your house will not be vulnerable in a power outage or PSU fault whilst also not trapping you inside.
In a commercial setting fail safe is commonly used on non secure common areas and rooms but preference for a residential front door is fail secure.
Other lock types such as maglock, drop bolt, V-Lock, hook and loop and automatic doors among others do not have purely mechanical methods of using the door in a fault so are harder to use in a residential setting and may need emergency breakglass or stop buttons to cut power on the inside and keyswitch or pincode unit on the outside in case of fault if no other entry point available.
Maglocks for example are fail safe only and will open once power is off,potentially leaving your home vulnerable, so need fairly significant battery backup. However I have also experienced issues where a door controller has failed and will not release, as it is a maglock the power has to be broken and there was no method of release externally and no other point of entry.
I would suggest a strike or electronic mortice lock for your purpose and suggest an off the shelf unit, it will be far more reliable long term.


text:
How can I list only files that begin with "/LOG?"
Trying to list root directory of LittleFS; but only files beginging with "/LOG."
String str;

                     if (!LittleFS.begin())
                     {
                          Serial.println("LittleFS failed to mount !");
                     }
                     Dir dir = LittleFS.openDir("/");
                     while (dir.next())
                     {

                        if(strncmp(dir.fileName().c_str(), "/LOG", 4) == 0)
                        {

                            str += "";
                            str += dir.fileName();
                            str += "";
                            str += "    ";
                            str += dir.fileSize();
                            str += "
\r\n";
                        }
                     }

                     client.print(str);

If I comment out "if(strncmp(dir.fileName().c_str(), "/LOG", 4) == 0)" and associated braces; all files list.  Code with "if(strncmp(dir.fileName().c_str(), "/LOG", 4) == 0)" no files are listed.
How can I list only files that begin with "/LOG?"
William

And you're sure that the filenames do begin with precisely the characters /LOG ?

Just a sanity check here. But isn't / used as path separator? In my world / is an invalid character for file or directory names. Listed file names in directory / should not contain / then.

@Kwasmich Unless the result of dir.fileName() is the fully qualified absolute path of the file. Which is why I was asking if the filenames really do start /LOG

@Majenko true. Just to make sure nothing gets overlooked. strncmp is case-sensitive!

@Kwasmich Indeed. Not a problem if it's using 8.3 filenames, but could be a problem if the FS uses LFN.

you have a String object returned by fileName and you take the c-string from it to use it in strcmp? String has startsWith. And I guess the listed files don't start with /.

Give a filename String to text...
String text = "/LOGsdfsdf";
if(text.startsWith("/LOG")){
//wee file begins with /LOG
}else{
// wops wrong file.
}

Look in here
https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/
Method url startsWith("");
https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/startswith

FileZilla shows filename as "LOG0608.TXT."  Naming convention is "LOG + Month + Date + '.TXT'."    I could have carried the "/" over from the web server.

Need "dir.fileName()" to compare acutal filename to LOG0608.TXT.  I only want files starting with "LOG" to be displayed.

Dose dir.fileName() gives a string as "LOGXXXX.TXT" or "/LOGXXXX.TXT"

Used:  String file_name = dir.fileName();
        if(file_name.startsWith("LOG"))
        {                                                                               Thanks!

gr8 glad I can help you

source: Stack Exchange

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

sort: votes


text:
Make a float using integers
I want to make a floating point number that has only one decimal point.
I have separate integers for both side.
Ex:
int n1 = 8;
int n2 = 2;
I want to make 8.2 as float value using separate integers.
Please give me a solution.

Seems too simple:
float x = n1 + n2 * 0.1;

Is there a trick?
Edit: The method proposed by Michel Keijzers, namely
float x = n1 + n2 / 10.0;

(I removed the redundant casts) can be slightly more accurate, but takes
longer to compute, because division is significantly slower than
multiplication on the Uno. Computing n2/10.0 always yields the
correctly rounded result, namely the float that best approximates the
exact mathematical result. On the other hand, n2*0.1 involves two
rounding operations: one at compile time, in the representation of 0.1
(which is not an exact float), another at run time, which rounds the
result of the multiplication. If n2 is between 0 and 8, you end up
getting the correctly rounded result anyway, just as with n2/10.0.
However, if n2 is 9, then

n2*0.1 yields 0.900000035762786865234375 (error ≈ 3.6e-8)
n2/10.0 yields 0.89999997615814208984375 (error ≈ -2.4e-8)

The former carries a rounding error 1.5 larger than the latter.

float x = (float) n1 + (float) (n2 / 10.0);

This works only if the value of n2 has 1 digit. Otherwise the following make it smaller until n2 gets below 1.0:
float x = (float) n1;

float f2 = (float) n2;
while (f2 >= 1.0)
{
   f2 /= 10.0;
}
x = n1 + f2;

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


text:
Format Integer in Arduino
How to format an integer as 3 digit string? If I give 3 formated string should be 003
printf("%03d\n", 3); // output: 003

This doesn't work in Arduino.

You can use sprintf with a char array buffer and then pass it to Serial.print().

Thanks its worked,
'char buff[3];
sprintf (buff,"%03d",3);
Serial.print(buff);'

Rather use char buff[4] as you need one byte for the terminating zero that will be added by sprintf. If you don't, it may overwrite some value in your stack, leading to hard to understand problems.

Or you could setup printf() to print through Serial. This way you don't have to allocate room for sprintf(), which can be (as you just experienced) error prone.

BTW, you will need more than 4 chars if the number you print happens to be less than -99 or more than 999. With buffer[7] you can safely print any int, and with buffer[12] you can print any long.

See this if you have a lot of strings and don't want them using up the limited amount of RAM.  https://www.arduino.cc/en/Reference/PROGMEM

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


text:
Custom sleep function for Nextion
I have a Nextion 7 inch enhance type display.
I have enabled sleep using thsp = 120 and thup = 1 line of code. Now display become sleep mode after 2min, if there is no any touch event.
But, this sleeping is completely turn off the display.
I have several pages and I want to reset to a specific page, if there is no any touch event in any page instead of sleep function.
Greatly appreciate if someone can give a solution for this.

I solved the problem using a Nextion timer. (tm0)
I got a timer and change tim value. ( unfortunately Nexion allow to maximum to 65535mS). vscope should be globle, otherwise you cant use timer in every page.
I reset the timer in page touch event. In timer event I put this code.
if(tm0.tim==60000) //reset time in mS
{
   page 0 //specific page to load
}

The Nextion screen has a command for this. It is called wup and defines the id of page that the screen should go to on wake from sleep. The default is set to 255, which means that the display wakes up on the page it was on before the sleep event.
16 wup Wake Up
 Page wup=2, n0.val=wup
Sets which page Nextion loads when exiting sleep mode
 min is 0, max is # of last page in HMI, or default 255
 When wup=255 (not set to any existing page)
– Nextion wakes up to current page, refreshing components only
 wup can be set even when Nextion is in sleep mode

Thanks for your answer. But, I want to sleep to a specific page. Not wake up.
wup sets wake up page. Not sleep page.


text:
High speed rotary encoder with Arduino MEGA
I'm trying to develop length measuring system and I'm using a industrial rotary encoder as the sensor.
A have decided to use an Arduino external interrupt for connect the encoder. But, Encoder will rotate very fast. I need to calculate PPR(Pulse per revolution) of the encoder according to maximum interrupt frequency of Arduino MEGA.
So, What is the maximum interrupt frequency of Arduino MEGA?

it depends on the program that you are running

Using the atmega's counter module might be the way to go


text:
What controller should i use?
I'm working on a little DIY project in which I intend to make my own dataglove. Now I'm kinda stuck on choosing the right microcontroller. And since it can be quite costly, I thought to ask for some help.
So: I'm going to use 12 flex sensors (maybe 14) and 1 IMU (probably the 6050). now the problem is that I need a total of at least 14 AI.. And the small controllers only have about 6.
The controller can't be too big for dexterity reasons and also will need the availability to add a Bluetooth module.
I've been looking at some multiplexing/shield options but I'm just not confident (and rich) enough start ordering..
Peace out,
Lars
PS: other brands besides Arduino work for me to

Use suppliers parametric searches. I use PIC32 mainly, and I know they have plenty of analog inputs.

How about a Teensy? The guys that make Teensy have developed many of the well known Arduino libraries and have also helped develop the Arduino IDE in the past so they know their stuff.
I see the Teensy LC at about $11. the spec says its almost the same as Teensy 3.1 which has 20+ Analog In
https://www.pjrc.com/store/teensylc.html
https://www.pjrc.com/teensy/index.html
The 3.1 and 3.6 are more powerful and more expensive at around $29
note: Read the index for which boards are 5v tolerant if that's what you need.

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


text:
How to communicate with GPS SIM900a without Serial Monitor
I am fairly new to Arduino. I was working on a project where I use a GSM SIM900a modem interfaced with an Arduino. The AT commands are sent via the Arduino to the GSM Modem. The problem, however, is that the commands are only sent when I open the Serial Monitor. I have an IR proximity sensor and I would like the AT commands to be sent when the sensor detects an object. I am putting the code for the GSM modem below (I have not yet put in the code for the IR sensor).I want to know how to send the AT commands when the Arduino is hooked up to a battery and not to a PC
#include <SoftwareSerial.h>
SoftwareSerial myGsm(7,8);
float temp;
int tempPin = 0;
void setup()
{
 myGsm.begin(9600);
 Serial.begin(9600);
 delay(500);

myGsm.println("AT+CIPSHUT");
 delay(1000);
 printSerialData();

 myGsm.println("AT+CIPMUX=0");
 delay(2000);
 printSerialData();

 myGsm.println("AT+CGATT=1");
 delay(1000);
 printSerialData();

 myGsm.println("AT+CSTT=\"bsnlnet\",\"\",\"\"");//setting the APN,2nd parameter empty works for all networks
 delay(5000);
 printSerialData();

 myGsm.println();
 myGsm.println("AT+CIICR");
 delay(6000);
 printSerialData();

 myGsm.println("AT+CIFSR"); //init the HTTP request
 delay(2000);
 printSerialData();

 myGsm.println("AT+CIPSTART=\"TCP\",\"122.178.80.228\",\"350\"");
 delay(5000);
 printSerialData();
 delay(5000);

 myGsm.println("AT+CIPSEND");
 delay(2000);
 printSerialData();

sendtemp();
delay(3000);
myGsm.println("AT+CIPCLOSE");
printSerialData();

myGsm.println("AT+CIPSHUT");
delay(1000);
printSerialData();
}

void loop()
{
}

void printSerialData()
{
 while(myGsm.available()!=0)
 Serial.write(myGsm.read());
}

void sendtemp()
{
  temp = analogRead(tempPin);
  temp = temp * 0.48828125;
  Serial.print("TEMPERATURE = ");
  Serial.print(temp);
  Serial.print("*C");
  Serial.println();
  delay(5000);
 myGsm.println(temp);
 delay(3000);
 printSerialData();
 myGsm.write(0x1A);
 delay(3000);
   printSerialData();

}

Well, I too had the same problem until now. The simple way to fix is just to delay the void setup() before Serial communication begins. Add delay(15000); //15 Seconds so that GSM module boots up and connects to the network. And there is no need of changing any part of code. Hope this helps someone out there like me. :)

This saved my a*s a few hours before my final year university presentations.


text:
Setup J-K Flip-flop for logging on Arduino RESET
There are two events I plan to log; using no switches or requiring manual input of some kind.  One of the events is whenever the Arduino Serial Monitor is opened; the other, is when external event occurs that causes a Arduino RESET.  Second event produces a LOW pulse used to CLK the J-K Flip-flop.  digitalRead of J-K Flip-flop Q; using a conditional statement, if Q = HIGH log to SD Card as event1 date/time stamp else log to SD Card as event2 date/time stamp.  I need the J-K Output Q to be STORED thru the Arduino RESET, so Q can be read.
After reading Q, will need to clear Q; plan to do this from running sketch with a DigitalWrite
74HC73 is the chip I plan to use; it is triggered with a negative going CLK.
What needs to happen with the J and K inputs?  Will this work in toggle mode; with both J and K tried to +5 volts?

I am only looking to log when a LOW condition at Q output.  When I open the Arduino Serial Monitor with the way the 74HC73 is wired now, it immediately toggles, need to HOLD the status of Q until the J-K Flip-flop is reset.  Work finished so far:  http://tinyurl.com/jkflipfop includes testing code and wiring diagram.

Rather than having events that set 1Q or 2Q, consider having the external events take 1R\ or 2R\ low, to reset 1Q or 2Q.  When your sketch starts up, it would read 1Q and 2Q.  If one or the other is low, its event occurred and you can log it.  Then the sketch sets both Q's by dropping the CP lines with J's wired high and K's wired low.  You'd use three I/O pins: two for reading 1Q and 2Q, one for strobing the CP lines to set the Q's after reading them.
Arduino AVR pins default to inputs on Reset so the Arduino can reset without affecting the 74HC73's state.  A 10 to 20KΩ resistor to passively pull the CP lines high is reasonable.
Edit: Note, 1R\ and 2R\ operate asynchronously, and are independent of clock inputs.  This leads to simpler interface requirements for your external events.  However, it may also increase sensitivity to electrical noise; if your system is in a noisy environment a different approach might be needed.

Using with an external watchdog circuit that sends a  LOW pulse to reset the Arduino; this is what I am trying to aquire by reading Q.  The reading of Q takes place in Setup portion of sketch.  Okay, will read 1Q and 2Q, external event to 1R and strobe CP.  Can I use the strobing from input of the external, watchdog?  Are there any specific requirements for strobe at CP?

@William, see edit.  CP is relevant when your program is setting 1Q, 2Q after reading them.  CP is not relevant to 1R, 2R\ lines -- they operate asynchronously.  At 5V and 25℃, nQ goes low within 15 ns of nR going low; see Table 7 in nxp specsheet.

My resolution:

This is the code for logging Arduino RESET and WDT RESET.  Plus the code for resetting the J-K Flip-Flop.
 /////////////// J-K Flip-Flop 74HC73,  Status of Q Monitor ///////////////////////////////////////

 delay(10);

 getDateTime();

 if(value == 1)
 {

      //Creates an entry in "Server.txt" for every RESET cause by "Dual Watchdog Timer"
      SdFile serverFile;
      serverFile.open("Server.txt", O_RDWR | O_CREAT | O_APPEND);

      if (!serverFile.isOpen()) error("Watchdog Start Server");

      serverFile.println("Watchdog RESET:  " + dtStamp);
      serverFile.close();
      Serial.print("Watchdog RESET  ");
      Serial.println(dtStamp + "  ");
      Serial.println("Listening for connections...  ");
      //Serial.println(value);

 }
 else
 {

      //Creates an entry in "Server.txt" for every RESET; caused by opening Serial Monitor
      SdFile serverFile;
      serverFile.open("Server.txt", O_RDWR | O_CREAT | O_APPEND);

      if (!serverFile.isOpen()) error("Manual Start Server");

      serverFile.println("Manual RESET:  " + dtStamp);
      serverFile.close();
      Serial.print("Manual RESET  ");
      Serial.println(dtStamp + "  ");
      Serial.println("Listening for connections...  ");
      //Serial.println(value);

 }
 //Sends LOW to RESET the 74HCT73, JK Flip-flop
 digitalWrite(RESET, LOW);
 delay(10);
 digitalWrite(RESET, HIGH);
 delay(10);
 digitalWrite(RESET, LOW);

///////////////////////////////////////////////////////////////////////////////////////////////
William Lucid 12/22/2016


text:
How to latch a 200mS LOW pulse?
Trying to latch a 200 mS, LOW event to log the event.  LOW only occurs when external Watchdog timer sends reset pulse to the Arduino.
Is a D Latch suitable for this application?  It has been years since my digital class; help most appreciated.
How would you proceed?

Just as a side-note; you know the arduino chips have build in watchdog timers, right?

I am using Switchdoc Labs, "Dual Watchdog Timer" with an Arduino Mega running a Data logger/web server.

Project web page: http://tinyurl.com/Data500

I understand your question to be :  you want to latch (and indicate) whenever an external watchdog timer has reset your Arduino.
D type flip flop (latch) can be used.  You would use the clock input as the trigger. However, most D types clock on a rising edge. You could use an inverter on the input to the clock to get the D type to clock on a falling edge. You would also connect the D (Data) input high (logic 1). Then when your input (event) goes low, the Q output will latch high.  The 200 mS is irrelevant because the latch ocurrs at the change from high to low (low to high on clock input).
You would also need a means of resetting the latch, which many D types have a reset input or a clear input.

You could also use a more simple SR latch (set reset latch) using 2 Nand gates.  SR latch changes state when the “set” input goes low (providing that R input was high).  Make the R input go low to reset the latch.

POSSIBLE ALTERNATIVE :  If you have some means of operator intervention (or even a switch).  You could have your program light an LED at startup.  Operator (person) could reset LED.  Then afterwards,  any reset (restart of program) would light the LED.

I tried a S-R Latch (74LS279); so far it is not working.  What voltage should I expect on a LOW to the S input?  Measured 150mV, is this a failed 74LS279?

First, power from 5 volts.     Second : Tie all unused inputs HI. On the SR latch that you are using, R must be high (except when resetting). When S goes low, the Q output should be near 5 volts.

I have the 74LS279 wired and working; however, there is not enough drive from the external Watchdog timer output.  Will two inverters in series give me more drive?  Measured 2.5 volts at the bottom of the pull-up resistor.   Need to go to the Arduino Mega reset and to the S input of the Latch.  --Thank you for the help!

Documentation on the Dual WatchDog is poor. The output is reported as "pulled to ground",  "otherwise high-impedance". You didn't say what value of pull up resistor you are using.  Measuring 2.5 volts indicates that your pull up resistor might be too large of a resistance.

Normal operation of Arduino (program running) Q= HIGH, S" HIGH, and R= LOW.  When a WATCHDOG reset occurs I see Q go momentarily LOW (0.565 Volts. --HIGH being 4.77 Volts.) Observation made with voltmeter.  Problem is that it happens so fast by the time the Arduino reads the pin for Q status; it is already a HIGH.  I never get a Q value Of LOW when I read the pin connect to Q.  I am trying to do a conditional based on the status of Q. Suggestions?

You Do NOT want R = Low. . .  Let us try again.  S= Hi . .  R = Hi (presuming that Q=LO after a reset on R). . .  . .When watchdog goes low , (this is tied into the Arduino Reset), and also, S is pulled low by watchdog.  S going low  causes Q to go HI. Q stays HI until R is pulled low by operator (human).

Now using a D-Latch (74LS74) with an inverter (74LS04) it appears to be working; needs some tweaking and testing.  Weblink has two files of what I am doing with D-Latch code wise and the hook-up to the Arduino Mega-and-SwitchDoc Labs, "Dual Watchdog Timer.".   http://tinyurl.com/74ls74


text:
Integration of signal
In my house, I have a low voltage AC signal (0-10V) that is proportional to the amount of current that is drawn at any moment (or as it is presented: kW) (europe, 50Hz). Presently, it is just shown as a dial in my kitchen, of course I would to log this. I want to rectify and integrate this singnal over an appropriate time span (maybe on minute) As far as I can see, I basically have two ways of doing this:

The pure arduino approach: Using a voltage divider to get it down to 0-5 V (after rectification) (and maybe throw in a zener diode as an extra protection) Then using an adc in the arduino and measure the voltage directly. The problem I foresee with this approach is that I will need a pretty high sampling rate to make sure I get the peak values. If I managed to sample at exactly the same frequency as my mains,I could just calibrate the measured value (unless I managed to hit the cross overs) but I do not think that would be feasible So I think I need to maybe sample on approx 500 Hz and pick out the highest value from each 1/50 second.
Using an opamp, a few resistors and a capasitor to set up an analog integration circuit, then use the arduino to read out and reset that at appropriate times. Setting up the integration circuit is no problem for me, but I need some feedback on the reset circuit. I have been looking around a bit, but I have not found any standard way to reset an integrator circuit, it seems like the idea is that it should be integrating for as long as it is running.. As far as I can see, as long as it running on <= 5V, I could use an input on the arduino to drain it? - I would then need to make the dimensions such that the low current the arduino input draws will allow the integrator to be reset fast enough.

Any comments? Have I overlooked something? is there a third approach that I have not been thinking about? Is the 1st approach easier that what I think?

“proportional to the amount of current that is drawn at any moment (or as it is presented: kW)” Is it current or wattage you are reading? They are not the same: If you have inductive loads in your house (motors...) or switched-mode power supplies, and want to estimate the consumed power, you will have to monitor the mains instantaneous voltage (at least the phase) and multiply current × voltage. Simply multiplying RMS(current) by RMS(voltage) works only with resistive loads.

What I have is a voltage, what the meter tells me it knows is the "wattage"- I don't know if it is true kW or to which degree it is messed up with inductive load (althoug at least at wintertime, most of my usage is for heating, which should be pretty resistive load)

If that voltage is an image of the wattage, you should just run a low-pass filter on it, with no prior rectification.

Thanks works like a charm! typical what (watt?) happens when you know a bit of a topic but do not really know it - and ends up with a too complicated solution...

Sorry, but.. Why integration? Just use a peak detector like this one:

The output will "float" to the peak value of the input signal, minus the voltage drop across the diode:

The output oscillates between 9.7V and 9.2V, which is a 5% maximum error. If you want to reduce it, sample with a sample rate not multiple of 50Hz and average the measures.
The RC constant is 500ms. This means that it will require less than a second to pass from a value to a lower one:

Here in almost 500ms it will go from 10V to 5V.
If you want to reduce the diode effect (9.7V instead of 10V) use a schottky diode. This, however, will not reduce the 9.2V effect.
You should divide by 2 the voltage; you can either

divide it before the diode (but then the diode effect will be more evident - you can however correct it in software
divide it after the circuit (In this case, replace the 500k resistor with two 250k resistors and take the voltage in the middle)

Of course 500k and 250k are not standard values, but you can use any nearby value without affecting the behavior

That's pretty cool - that was the third option I didn't think about

Again thanks, I have implemented it, works like a charm!

Glad it worked :)

With an Arduino Uno, you can get 9615 samples per second from an analog
input, and do the data processing at the same time. That's more than
enough to reliably detect a peak. For this, you have to set the ADC to
"free running mode" and do the processing in the ADC interrupt service
routine. Se this answer for
a detailed explanation and code.
Oh, and instead of peak detection, you could just integrate your signal.
That should be simpler, and simple is good for interrupt-driven data
processing.

I'm not quite clear on the 'peak' detection - this would mean your reading would be changing several times a second potentially. Does the current in your house vary that much per second? I don't think your electricity meter is that clever anyway (there must be a smoothing effect, I reckon). For example, if you turned on your electric kettle for 1/50th of a second, would your domestic meter accurately record that (or the 0-10V signal vary)? I personally doubt it but I'm no meter designer! Anyway, you also mention that you want to log over a minute? I'm unclear on the exact requirements here.
Anyway, if you are reading the 'max' current (so you can accurately calculate bills, for example) I think your first approach would work - after all a 50Hz sampling rate is very low for an Arduino. You won't need a 500Hz sample rate as the data doesn't change that frequently anyway, does it?
Perhaps you could trigger the sampling activity by synchronising to the mains frequency (which you sort of allude to) and then do the reading? Use an analog input to detect the rising LV mains cycle and then do the reading? Or use a Schmidt trigger to trigger the Arduino (sounds a bit of overkill, I think the Arduino could do it all).
Experimentation is called for to see what works and what doesn't but your first approach seems eminently feasible to me.

I must have been a bit unclear, when I was talking about peak detection, I meant to measure (close to) the sinus peak to avoid aliasing effects.


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

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

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

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

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

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

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

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

work only for 50 days

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

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

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

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

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

it will work only for 50 days.

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

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


text:
Can I drive an LM334(Z) from an Arduino with AnalogWrite()?
I need programmable current control, fading from zero to 2 milliAmps.  I was hoping to use Arduino's AnalogWrite(), which uses Phase Width Modulation (PWM) to simulate analog output with a sawtooth wave on a duty-cycle; to control an LM334Z to deliver a slowly ramped low current delivery.
[The application is a TransCranial Direct Current Stimulation (TDCS) micro-current delivery to the human scalp. Jumping straight to 2 milliAmps is uncomfortable].
Will PWM work? Or, do I need some sort of smoothing circuitry to soften the PMW before it is applied to the LM334Z's Rset pin to accomplish the above?

an LED glued to the face of an LDR converts voltage to resistance, but a digital pot would be simpler to calibrate. I'm using a MCP41010 with the 334, which works very well and cost me ~$1us

an LM317 can provide 0-2ma CC with common 1/4watt resistors, look at the datasheet.

On Arduino, PWM stands for Pulse Width Modulation, not  “Phase Width Modulation”

If you don't need super high accuracy, using a MOSFET's ohmic region, plus a smoothing filter on the output of your PWM (analog out), could be a solution.

LM334Z's Rset pin to accomplish the above?

Most of that type of circuit has its operations be determined by the current In or out of that pin. So a voltage signal may not work - you will need to experiment. I have had some success with analogs dds chips and linear programmable osscillators.
So try it on your chip. Nothin to lose.

since it's output current is independent of any voltage, that will not work, it needs a resistor.

You control the LM334 with a resistance, not a voltage. The current is set by multiplying the current through the resistor.
Maybe you can do what you want by replacing the Rset with a digital potentiometer?


text:
Smooth breathing led
I am trying to make a simple breathing led circuit in which the intensity of the led varies between 0 and 255. I followed the Fade tutorial on the Arduino site, which gives me what I want, but I notice that the change in brightness is much more noticeable when the intensity is at 0.
In other words, the brightness seems to be bouncing back from 0, rather than slowly gliding back up.
I tried mapping the value of the delay to brightness: del = map(brightness, 0, 255, 10, 1); but that did not do the job.
The mapping seems to work better when I use 30 instead of 10 as longest delay time:  del = map(brightness, 0, 255, 30, 1); but I think what I really need is to implement some sort of sinusoidal function to make transitions smoother, but I am really struggling with the math... Any suggestions?
Here is the code:
int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 1;    // how many points to fade the LED by
int del;

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }

  // here I map the delay to brightness
  del = map(brightness, 0, 255, 10, 1);

  delay(del);
}

Maybe use a sinewave to set the brightness. Or possibly you want a logarithmic scale?

Sinewave would be good, and a logarithmic scale too.. just really not sure about how to implement those...

I think you should look into gamma correction. Our eyesight is logarithmic, so for our eye to see something as twice as bright, it has to be around 4 times as bright. For example, using the standard fade sketch, the leds starts to increase in brightness fairly rapidly, but then seems to slow down.

These days there are so called "Digital Potentiometers", these can work with a board, to actually change the voltage into the led, instead of simulating it with a pwm

There's two ways you could algorithmically do what you want, both with different results.
The first is with a sinewave:
for (int i = 0; i < 360; i++) {
    analogWrite(5, (sin(i * 0.0174533) + 1) * 127));
    delay(3);
}

Basically you work your way 360 degrees around a circle and take one axis (e.g., the vertical one), offset it so that the values are all positive (sin gives a value between -1 and +1), then multiply it to fit the full brightness.
This is the smoothest way of fading an LED, but it doesn't respect the different sensitivities your eye has to the different brightnesses (you see more brightness variation when it's dim compared to when it's bright).
The other method is much cruder but does respect those differences in sensitivities. This specific method only gives you 8 brightnesses as opposed to 256, but they are on a log2 curve:
for (int i = 0; i < 9; i++) {
    int v = (1 << i) - 1;
    analogWrite(5, v);
    delay(100);
}
for (int i = 7; i > 0; i--) {
    int v = (1 << i) - 1;
    analogWrite(5, v);
    delay(100);
}

The theory of this one is it uses bit-shifting to gradually fill a byte with 1 from the least significant bit upwards.
When i is 0, this formula:
int v = (i << i) - 1;

gives:
1 << 0 == 0b00000001
0b00000001 - 1 = 0b00000000

If i is 4, you get:
1 << 4 == 0b00010000
0b00010000 - 1 = 0b00001111

So you effectively end up with a set of values:
0: 0
1: 1
2: 3
3: 7
4: 15
5: 31
6: 63
7: 127
8: 255

That code gives -1 3 15 47 127 319 767 1791 4095 1791 767 319 127 47 15 3.

Seems there's a typo there - i instead of 1 - easily done. I've also fixed another bug.

I thought about making a regular fade, with a logarithmic delay:
for an example:
val=30*(1-((sqrt(brightness))/(sqrt(255))));
delay(val);

The three 255 values for RGB colour space  (255^3) is 16,581,375 colours. These include for brightness level.  The reason you're experiencing brightness issues is not to due with your arduino board but, with the RGB color space.  And by breathing, and i'm guessing here, that you are trying to transition thru RGB:
void colorLoop() {

    static int Col1;
    static int Col2;
    static int Col3;

    static int C1;
    static int C2;
    static int C3;

  if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

  C1 = random(1, 3);
  C2 = random(1, 3);
  C3 = random(1, 3);
  }

  if (((C1 == 1) && (Col1 != 0))) {
      Col1 = (Col1 - 10);
  }
  if (((C2 == 1) && (Col2 != 0))) {
      Col2 = (Col2 - 10);
  }
  if (((C3 == 1) && (Col3 != 0))) {
      Col3 = (Col3 - 10);
  }

  if (((C1 == 2) && (Col1 != 250))) {
      Col1 = (Col1 + 10);
  }
  if (((C2 == 2) && (Col2 != 250))) {
      Col2 = (Col2 + 10);
  }
  if (((C3 == 2) && (Col3 != 250))) {
      Col3 = (Col3 + 10);
  }

if (((Col1 <= 90) && ((Col2 <= 90) && (Col3 <= 90)))) {  //avoid black
   C1 = 2;
   C2 = 2;
   C3 = 2;
 }

    for (uint8_t i = 0; i < LED_COUNT; i++) {
     leds[i] = CRGB(Col1, Col2, Col3);
    }
    delay(100);
    LEDS.show();
  }

You may have more success or find it easier to use a HSL or HSV colour space. HSV uses Hue, Saturation and Value instead of RGB. FastLED has optimized it's implementation of HSV to use a 0-255 addressing for Hue (instead of 360), keeping it fast for animations run on microcontrollers:
https://github.com/FastLED/FastLED/wiki/FastLED-HSV-Colors
here is a similar effect using the HSV color spectrum:
void rainbow_fade() {

 int ihue = 0; //some microcontrollers use HSV from 0-255 vs the normal 0-360
    ihue++;
    if (ihue > 255) {ihue = 0;}
    for(int i = 0 ; i < LED_COUNT; i++ ) {
     leds[i] = CHSV(ihue, 255, 255);
    }
      LEDS.show();
      delay(100);
  }

I'm not sure that it will work with a normal led. Some 20mA leds are still bright with only 1mA. The programmable RGB 5050 leds (for example the NeoPixels) are easier for a smooth visual brightness change.
The human eye is logarithmic for light brightness. Therefor a 10-based exponent or a less steep natural-based exponent can be used.
This will give a smooth brightness change:
y = a * exp (-b * x * x);
// x is incrementing in time.

If you really need a very smooth brightness change for a normal led, you might need an extra output with a higher resistor value to the same led, for a higher resolution at low brightness.

Use a timer interrupt and in thee Isr change a pwm generator duty cycle. Or
Use a timer and set up two compare channels with a fixed offset. In the compare Isr, advance the math points forward and then flip an output pin. You will see the brightness goes up and down, whose speed depends on the offset.

No need for gamma correction.
edit: to demonstrate how the 2nd approach might work, here is a quick example.
It runs off of TIMER0, Output Compare Ch A and Ch B.
TIMER0 is set with a 256x prescaler, free running. Ch A is set to interrupt every LED_PR ticks, and Ch B is set to interrupt every LED_PR + LED_OFFSET ticks. they run the same user interrupt handler -> to flip a pin attached on LED_PORT / LED pin.
tmr0_init(TMR0_PS256x);                 //initialize tmr0 with a prescaler
tmr0a_setpr(LED_PR);                    //set up output compare ch a period
tmr0a_act(led_flp);                     //install user handler for ch a
tmr0b_setpr(LED_PR + LED_OFFSET);       //set up output compare ch b period, with offset
tmr0b_act(led_flp);                     //install user handler for ch b
ei();

and here is how it works in simulation:

the DC will go up then down, then up and then down, ....

Just recently I published a blog post about this very topic at https://thingpulse.com/breathing-leds-cracking-the-algorithm-behind-our-breathing-pattern/
Turns out you get very pleasing results if you use f(x) = e^sin(x). If you bring this down to 0 and have an amplitude of 255 the formula becomes f(x) = (e^sin(x) - 1/e) * (255/(e - 1/e)). Finally, you stretch x so you get a frequency of 12-20 breaths per minute: x * PI/2.
#include <math.h>

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

void loop() {
  float val = (exp(sin(millis()/2000.0 * PI)) - 0.368) * 108.0;
  analogWrite(9, val);
}

authors: Илья Кондобаров


text:
(Beginner) Blinking led call function
I'm completely new to this world, so probably my question would sound noobish, but here it is:
I'm trying to make a led blinking just for 5 times by calling a "for" cycle inside void loop(). The confirmation of the successful cycle would come from the Serial Monitor which will print "let's star over", and at the end of each blinking cycle, it will print the text "cycle done".
The point is that my code doesn't work, the led remain switched ON and the serial monitor blank. What is wrong with it?
int ledred = 3;
int count = 5;

void setup() {
  digitalWrite(ledred, LOW);
  pinMode(ledred, OUTPUT);

}

void loop() {

    blinkingred(ledred, count);
    Serial.println("let's start over")

}

void blinkingred(int ledred, int count)
{
  for(byte i=0; i == count; i++)
  {
        digitalWrite(ledred, HIGH);
        delay(1000);
        digitalWrite(ledred, LOW);
        delay(1000);
        Serial.println("Cycle done !");
  }
}

There's two things wrong with your sketch - one fatal and one that is more confusing for humans.
First the fatal problem:
for(byte i=0; i == count; i++)

That for loop is never going to do anything.  The way it is written it will loop only while i is equal to count (0 == 5) which it never will. Instead you need to loop while i is less than count:
for(byte i=0; i < count; i++)

The second issue is that you have named your function parameter variables the same as your global variables. While this is syntactically valid (the local variables will override the global ones) it is incredibly confusing for people to follow what is what and should be avoided at all costs.

the simplest would be to unroll your loop and repeat the code 5 times.
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);

hard to get that wrong.


text:
Open video file if sensor reaches certain threshold value
I am an ABSOLUTE beginner at Arduino and my first project I've proposed to my teacher is as follows: an Mq-2 smoke sensor will sense smoke and if the level of smoke reaches a certain value (only because I want the smoke to accumulate for aesthetics purposes) then a video file in whatever directory opens and plays. It seemed plausible at first, but as I search for pertinent info., I am faced with content and hobbyists whose instructions and "knowledge" are way out of my depth. Can anyone help me with this? If anyone knows a good website/tutorial videos/documents/books that a beginner like me should take to improve his programming and physical computing(?) skills, please let me know!


text:
Two ints declared simultaneously, one "does not name a type"
I have several integers, all of which are declared and set to zero in setup. However, in a method, I can only modify the value of half of those integers. The method is to read several buttons and return which of them have been pressed (precondition is that no more than one buttons are pressed):
  int readButtons(){
  rbuttonState = digitalRead(right);
  lbuttonState = digitalRead(left);
  sbuttonState = digitalRead(sel);
  obuttonState = digitalRead(off);
  nbuttonState = digitalRead(snooze);
  int ret = -1;
  if (rbuttonState != lastrButtonState){
        if (rbuttonState == HIGH) {
            ret = right;
          }
        }
        if (lbuttonState != lastlButtonState){
          if (lbuttonState == HIGH) {
            ret = left;
          }
        }
        if (sbuttonState != lastsButtonState){
          if (sbuttonState == HIGH) {
            ret = sel;
          }
        }
        if (obuttonState != lastoButtonState){
          if (obuttonState == HIGH) {
            ret = off;
          }
        }
        if (nbuttonState != lastnButtonState){
          if (nbuttonState == HIGH) {
            ret = snooze;
          }
        }
  }
  lastrButtonState = rbuttonState;
  lastlButtonState = lbuttonState;
  lastsButtonState = sbuttonState;
  lastoButtonState = obuttonState;
  lastnButtonState = nbuttonState;
  return ret;
}

Yet I have the errors that
Arduino: 1.6.12 (Mac OS X), Board: "Arduino Nano, ATmega328"

Nixie_Clock_0:65: error: 'lastrButtonState' does not name a type
   lastrButtonState = rbuttonState;
   ^
Nixie_Clock_0:66: error: 'lastlButtonState' does not name a type
   lastlButtonState = lbuttonState;
   ^
Nixie_Clock_0:67: error: 'lastsButtonState' does not name a type
   lastsButtonState = sbuttonState;
   ^
Nixie_Clock_0:68: error: 'lastoButtonState' does not name a type
   lastoButtonState = obuttonState;
   ^
Nixie_Clock_0:69: error: 'lastnButtonState' does not name a type
   lastnButtonState = nbuttonState;
   ^
Nixie_Clock_0:70: error: expected unqualified-id before 'return'
   return ret;
   ^
Nixie_Clock_0:71: error: expected declaration before '}' token
 }
 ^
exit status 1
'lastrButtonState' does not name a type

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

(The last line of code is line 72).
I am at a complete loss. Any help?

Where is the rest of your code?

There is an end bracket too many. Indent the code correctly and you will find it.

the posted code does not contain 70 some lines of code.  It only contains 40 lines of code.  Post the actual code.

@Mikael Patel thanks! I can't believe I missed that!

the following code

is properly indented
is missing the declarations of the variables for the 'button states' and the 'prior button states'
has additional text about a format error
is properly indented
has the code blocks properly separated by a single blank line

and now the code
int readButtons()
{
    rbuttonState = digitalRead(right);
    lbuttonState = digitalRead(left);
    sbuttonState = digitalRead(sel);
    obuttonState = digitalRead(off);
    nbuttonState = digitalRead(snooze);
    int ret = -1;

    if (rbuttonState != lastrButtonState)
    {
        if (rbuttonState == HIGH)
        {
            ret = right;
        }
    }

    if (lbuttonState != lastlButtonState)
    {
        if (lbuttonState == HIGH)
        {
            ret = left;
        }
    }

    if (sbuttonState != lastsButtonState)
    {
        if (sbuttonState == HIGH)
        {
            ret = sel;
        }
    }

    if (obuttonState != lastoButtonState)
    {
        if (obuttonState == HIGH)
        {
        ret = off;
        }
    }

    if (nbuttonState != lastnButtonState)
    {
        if (nbuttonState == HIGH)
        {
        ret = snooze;
        }
    }
}  << extranious closing brace ends the actual function

    lastrButtonState = rbuttonState;
    lastlButtonState = lbuttonState;
    lastsButtonState = sbuttonState;
    lastoButtonState = obuttonState;
    lastnButtonState = nbuttonState;
    return ret;
}


text:
Is EEPROM's location relocated on sketch compile?
I assumed the microcontroller has 3 components as per storing data:
- flash memory for the program
- RAM for variables
- EEPROM for non-volatile user-storage
And I always assumed those are separate chips on the board. However, working directly with a RobotDyn Uno R3 leads me to believe I may be wrong somehow.
I compiled this program:
#include <EEPROM.h>

struct SettingsStruct {
  String server;
  String port;
  String user;
  String password;
  String description;
} gSettings = {
  "192.168.1.6",
  "8080",
  "fci blah vlak",
  "zangazang4",
  "Extra string here"
};

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

  //saveConfig();

  Serial.print(F("EEPROM size is: "));
  Serial.print(EEPROM.length());
  Serial.print(F(" bytes"));
  Serial.println("");

  loadConfig();
  Serial.print(F("Server: "));
  Serial.print(gSettings.server);
  Serial.println("");
  Serial.print(F("Port: "));
  Serial.print(gSettings.port);
  Serial.println("");
  Serial.print(F("Username: "));
  Serial.print(gSettings.user);
  Serial.println("");
  Serial.print(F("Password: "));
  Serial.print(gSettings.password);
  Serial.println("");
  Serial.print(F("Description: "));
  Serial.print(gSettings.description);
}

void loop()
{
  // nope
}

void loadConfig() {
    for (unsigned int t=0; t<sizeof(gSettings); t++)
      *((char*)&gSettings + t) = EEPROM.read(t);
}

void saveConfig() {
  for (unsigned int t=0; t<sizeof(gSettings); t++)
    EEPROM.write(t, *((char*)&gSettings + t));
}

Problem is that each time I add new elements to the struct, and I run the program, the serial prints different things. I recognize previously saved strings but they are right shifted, meaning that somehow the ZERO address of EEPROM might have moved backwards and previously saved strings move right and offocurse, appear on other struct variables.
This leads me to believe the actual EEPROM is related with the flash memory and depends on it on each compile. As if the ZERO address of EEPROM is established after each compile.
Can anyone confirm this or lead me to some documentation relating this? It's a weird mystery that I would like to clear out.

The EEPROM is a completely separate part of the silicon inside the chip. It has no address of its own.
You are making a fundamental error in what you are doing, though - you cannot directly store the contents of strings by looking at the addresses of those strings. The data in them is dynamically allocated in RAM and is completely separate from the object. You will have to come up with a different way to store your data.

The assumption was that EEPROM starts ALWAYS at the same address. the struct defined above should be able to be loaded as long as the save is equivalent. And it actually is. Problem was that data is shifting in EEPROM and I don't know why. I read your answer many times and it still does not help me understand this. What am I missing?

The struct is saved and loaded fine. The point is that the string data isn't in the struct for you to save. The struct only contains the String objects, and those just contain a pointer to dynamically allocated (at runtime) memory for the string data.

There's my problem. "dynamically alocated at runtime". My thought was that EEPROM is a fixed data storage entity you can always address the same way, similar to old assembly addressing mode. The fact that the EEPROM chip is separate also allows me to sustain this assumption. Why would runtime execution allow data shifting?

You're missing the fundamental issue here. The issue has nothing at all to do with EEPROM. That is exactly as you assume it to be - fixed. You read from address 0 exactly what you write to address 0. The fundamental issue is that you are not writing what you think you are writing to the EEPROM. It's like you have stored the envelope a letter came in and burned the letter itself, then go back to the envelope expecting it to be the letter.

My struct has a single variable called letter. I write it to eeprom, and I expect the /0 termination indicates the end of the string. Then, I add another variable to the struct. Another string, called title, before letter. Without writing, I read the new structure and observe that the title is gibberish then I can see my old letter further on. Where is the gibberish coming from and why is it before what I wrote before at address zero? This is basically what I don't understand. I do get that you are explaining that the struct itself is a reference. I don't get the field result.

You still aren't understanding what I am saying. Your struct does not contain your data . It contains objects that point to RAM which is allocated at runtime when the object is created where your string data is.

When you reload the objects from EEPROM the pointers point to areas of RAM that now are not allocated to the objects so give you gibberish.

Let us continue this discussion in chat.

Not all Arduinos, if you define Arduino as something which can run Arduino core code, have the same EEPROM concept. For instance, the ESP8266 simulates an EEPROM in a bit of flash memory. Clearly, however, in the OP's case an EEPROM as in say the atmega328p is being referred to and the problem is, as mentioned, that strings are not a primary datatype but an object, the data of which is not resident in the structure being saved. These should be converted to, say, an array of characters before being saved.


text:
Using Bluetooth module HC-05 when Arduino is powered using a battery
I have a project that involves sending messages from an Android device to an Arduino using a bluetooth module. I am using an HC-05 bluetooth module and an Arduino Mega 2560.
It works as long as I power the Arduino to my laptop using a USB cable. However, I need to use an external power source and have been using a 6F22 9V battery connected through the VIN pin for this purpose, without facing any problems. But on connecting the HC-05, it does not even light up.
The Arduino is also connected to four dc motors, five servo motors (all of which are externally powered, only get digital signals from the Arduino), and seven HC-SR04 ultrasound sensors, whcih are powered through the 5V pin.
I have connected the HC-05 to the Arduino as follows:
HC-05   Arduino
VCC      3.3V
GND      GND
TX       RX
RX       TX           through a voltage divider
I am new to all this, and would be grateful for any help. Thank you.

6F22 (PP3) batteries are among the wimpiest of batteries available.  They are not a good choice for anything except extreme low power applications, and anything involving radio transmitters is definitely not an extreme low power application.
Use a better battery.  I would recommend 6 AA batteries (you can get 6xAA battery holders with the same connector as a PP3 battery) which will give you considerably more power than a little PP3.
Either that or a 7.2V "2S" Li-Ion battery pack.

Thank you for the reply! Is the problem occurring because the current provided by the 6F22 is not enough?

Quite possibly. Try a more powerful battery and see if the problem goes away.


text:
Trouble with large numbers
Probably something stupid, but I can't figure out how to work with these large numbers, then cast the result (which will be small) to an integer. I keep getting negative numbers, which I think means I'm overflowing somewhere.
int freq = 440;
int len = 256;
long timer = 2000000.0 / (freq * len);
int roundedTimer = int(timer);

I should get 18, but I'm getting -108...

Well, I'm not sure I exactly understand why, but it seems that the result of freq * len needs to be explicitly a long too: long timer = 2000000L / ((long) freq * len);

Majenko has the reason - your divisor calculation overflowed. Either your solution (as coded above) or his, works. Casting either freq or len to long forces the other to be promoted to long for the calculation, and the long result to be used for division. However the solution you described (not the one you coded) would fail. You do have to calculate the divisor as a long. Casting the product comes to late; it will already have overflowed.

The "answer" by JeffThompson is really a comment on Majenko's answer. I'm going to convert it into a comment for you. Please only use answers for answers to the posted question.

freq * long, since they are both integers, are calculated as integers.
440*256=112640 - in binary that is 1 1011 1000 0000 0000 and trimmed to 16 bits becomes 1011 1000 0000 0000 which is -18432 and that is where the heart of your problem is.  Unless you explicitly say otherwise the Arduino's compiler does all calculations (except floating point) as 16-bit signed integers.
By casting the values to long it forces the compiler to 'overflow' the 16-bit limit and use a 32-bit limit instead:
long timer = 2000000 / ((long)freq * (long)len);

Another alternative is to define freq and len to be long from the outset instead of int.


text:
SoftwareSerial runs out of "text" space on ATtiny
I have an ATtiny and am trying to send a very large byte array stored in a separate .h file over SoftwareSerial:
for (int i=0; i<numElements; i++) {
    softSerial.println(myList[i]);
}

I imagine it will very slow, which is fine, but I'm getting a cryptic error when compiling:
Firmware.ino.elf section `.data' will not fit in region `text'

It seems that this is due to the println() command running out of memory for some reason – if I comment out the println() command everything works fine. How to fix this?

perhaps, if you remove the line where you use the array, compiler optimizes the code removing the not used array

how big is the .h file?

@Juraj – not sure I understand? The array is what's getting sent over serial, which is the point of my program.

@ChadG – it's about 140kb.

is it used elsewhere in the sketch or only in the commented println?

@Juraj – it isn't used anywhere else, just printed over serial.

how do you expect it to fit in 8KB worth of program space( thats what the ATtiny85 has)

if something is not used, the compiler doesn't put it into final code. it is why you do not get the warning if you comment the print of the array

The uno only has 32KB but the Mega does have 256KB. Remember though, there is a difference between where stuff is stored, program space and ram. There is still not enought ram on any of these devices to handle that large of a byte array.

have a look here     https://www.arduino.cc/en/Tutorial/Memory

Is there a way to compress this data? Any repeating sections? Only a limited amount of different characters? ASCII only needs 7 bit!

How big is the array? In other words, what is the data declaration for myList? Is it, for example: int myList [35000];

@NickGammon – the version I had was 143186 bytes long. I'm now seeing there's no way that takes up less that 141k in the Arduino's memory though, right?

I would prefer if you answered my question. How is the array declared? I don't care how big the file is, it might be full of comments.

However unless the file is 99% comments then it is unlikely that it will fit into 8KB of program memory. Also the compiler generates code to copy variables with initial values from program memory into RAM, unless you declared it as PROGMEM, and it is even less likely your data will fit into your 512 bytes of RAM. See my page about that.

@NickGammon – here's the first little bit: const unsigned char dna[] = { 0x37, 0x7a, 0xbc, 0xaf... }; I think I was confused since it compiled with no issues, until I actually needed to use the array.

OK, you are letting the compiler determine the size. Do you know offhand how many bytes are in this array? (eg. 0x37 is one byte). You could conceivably put that array onto a larger machine (eg. use gcc on your PC) and then use sizeof to find how big the array is.

Yes, it compiled with no issues, particularly if you didn't reference the array, so that the linker can then strip the array from the final hex file.

Your sketch doesn't fit into program memory of the ATtiny. If you comment out the println of the array, the compiler evaluates that the array is not used and doesn't attach it to the program. Then the program fits into memory.
EDIT
Chad suggests some good alternatives below, if you need to store more data than flash or PROGMEM will allow.

Thanks – 140kb is the ascii representation of all those bytes. I had read that it gets crunched down to binary on compile, and was trying to see if it fit. Didn't realize the array would be ignored until invoked by println().

There is not enough room in program memory for 140KB. ATiny only has 8KB for the whole program. So there is no way to fix this with your current hardware.
Options-
add a storage device (SD card, sram module, others....) where you can store the data, and then read it in small chunks and send it out
possibly use a arduino mega. It has 256KB of program space. you will still have to make sure you are not trying to store the whole byte array in an array since that would get stored in sram (which there is still only 8KB) but it could again to written in chunks to avoid this problem.

The ATTiny only has a limited amount of RAM. A lot less that flash-memory.
Using a normal array, the entire contents of the array are placed into RAM (during initialization). Which is very limited.
I'd suggest, looking into PROGMEM. This is a way to read the data directly from the flash-memory.

Looking at the comments, this will still not fit the 140kb you want. But the ATTiny85 only has 512 bytes of RAM, but a whole 8KB of Flash/Program memory.


text:
Calculate OCR2A from audio frequency
I'm working on a Arduino-based synthesizer using this tutorial, specifically using a wavetable and 1-bit DAC. I understand that the value for OCR2A register sets the frequency, but how do I calculate the value?
I've seen this list of notes which is great, but I want arbitrary frequencies in Hz...
Here's the code I'm working from:
#include <avr/interrupt.h>

// sinewave parameters
#define FREQ 18
#define PI2 6.283185    // 2*PI saves calculation later
#define AMP 127         // scaling factor for sine wave
#define OFFSET 128      // offset shifts wave to all >0 values

#define LENGTH 256      // length of the wave lookup table
byte wave[LENGTH];      // wavetable

void setup() {

  // populate wavetable
  for (int i = 0; i < LENGTH; i++) {
    float v = (AMP * sin((PI2 / LENGTH) * i));
    wave[i] = int(v + OFFSET);
  }

  // set timer1 for 8-bit fast PWM output
  pinMode(9, OUTPUT);       // make timer’s PWM pin an output
  TCCR1B = (1 << CS10);     // set prescaler to full 16MHz
  TCCR1A |= (1 << COM1A1);  // pin low when TCNT1=OCR1A
  TCCR1A |= (1 << WGM10);   // use 8-bit fast PWM mode
  TCCR1B |= (1 << WGM12);

  // set up timer2 to call ISR
  TCCR2A = 0;             // no options in control register A
  TCCR2B = (1 << CS21);   // set prescaler to divide by 8
  TIMSK2 = (1 << OCIE2A); // call ISR when TCNT2 = OCRA2
  OCR2A = FREQ;           // set frequency of generated wave
  sei();                  // enable interrupts to generate waveform!
}

void loop() {
  // nothing to do here!
}

// called every time TCNT2 = OCR2A
ISR (TIMER2_COMPA_vect) {   // called when TCNT2 == OCR2A
  static byte index = 0;    // points to each table entry
  OCR1AL = wave[index++];   // update the PWM output
  asm("NOP; NOP");          // fine tuning
  TCNT2 = 6;                // timing to compensate for ISR run time
}

Shouldn't this be in Arduino.SE?

Perhaps, didn't realize there was a separate forum. Happy to migrate if that's appropriate.

Whoever wrote the code for that tutorial needs their head examining. asm("NOP; NOP"); and TCNT2 = 6; are total nonsense and should be removed, as should the sei(); line from setup (it's unnecessary). Also, the LENGTH #define is totally ignored in the ISR, so if it was ever set to something other than 256 the code would break. >_<

Hmm, I tried it without TCNT2=6 and got a lot more high-freq partials. With TCNT2=6 but no asm("NOP;NOP") I get no audio, just buzzing. It seems to be fine without sei(), but (obviously) my timer programming is really bad, and I don't entirely understand what they do.

Well the asm() statement that according to the comments adds two nops only adds one, so...

The reason it misbehaves when you remove the lines is because whoever wrote the code doesn't understand how to set up the timers. In the setup it should be TCCR2A = (1<<WGM21) to set into CTC mode. Otherwise the timer just counts all the way around to 0xFF and overflows (setting TCNT2 to 6 was clearly a hack to get around that issue without understanding what was actually causing it).

@TomCarpenter – if you'd like to suggest changes to make this code better, I'm all for it!

The equation to calculate it is given in the first article you linked:

The 2MHz value comes from the factor of 8 prescale on the 16MHz clock and 256 is the size of the lookup table specified by your LENGTH define. If you start from a frequency you want to synthesize, just use the above equation to solve for the necessary value of OCR2A. Note that since you have to input integer values to OCR2A, you can't really achieve arbitrary frequencies, but you're certainly not locked in to the values given in the supplemental musical note PDF you reference.
So, to solve for OCR2A:
OCR2A = TCNT2_rate / (desiredFreq * wavetableLength);

Thanks! It took me a while to figure out that the equation told me that! So, my math is really terrible: how do I swap the equation to get me OCR2A from frequency? :)

@JeffThompson just swap them over in the equation (stick frequency where OCR2A is, and vice versa)

Sorry, feeling really stupid: so OCR2A = TCNT2/(freq*tableLen)?

As Cheibriados said, you won't get arbitrary frequencies. From the table you linked you can see that OCR2A of 15 gives you a frequency of 523.25 Hz, and making it 16 gives you a frequency of 493.88 Hz. Thus you cannot get any frequencies in-between.


text:
How to pull a pin low?
On the instructions for this motor driver, it says that motors can be put to sleep by "pulling a pin low".

SLP - Logic Input. When pulled LOW, outputs are disabled and power consumption is minimized.

I'm guess this means connect to ground? How could I trigger that via my Arduino board?

Connect it to an IO port and set it to OUTPUT and LOW. That's what it means to "pull low".
It helps if you understand how an IO port works. This may help you.

Thanks – I get that this makes the Arduino pin go low, but will it also "pull" the pin on the driver to ground?

Yes, that is what going LOW is. Did you read the tutorial I linked to?

Sometimes it also is needed to put a resistor from the pin to ground to pull it low, or put a resistor to +5V to pull it high. This happens in cases where a pin needs to be set before the sketch can set a pin to low or high.


text:
Using Temperature sensor arduino to trip off an ac device
Using Temperation through arduino to trip off an ac device?

My hovercraft is full of eels.

I assume that what you are trying to ask is something like: "How can I use a temperature sensor to control an AC (mains) powered device with an Arduino?" It really helps if you can state a clear question. Perhaps you could edit the post to add some detail and clearly state your question. Also as a new user it encourages people responding to you if you follow up on comments quickly.

@Majenko, I understand the frustration that comes with fuzzy questions, but in the long run I think we do better if we can offer constructive advice on how to ask good questions. Someday I'm going to get around to writing some Text Expander snippets so that I can make my suggestions when I'm in a good place and then reuse them :-)

Welcome to Arduino Stack Exchange. We hope you find this site useful. Please read How to ask a good question. Your question as it stands is very unclear.

Yes, there are lots and lots of project descriptions similar to yours (if I guesstimate) on the web. Google is your friend.
Here is one link to an interesting project - if you are interested in brewing beer.
Cheers!

Nice project, Mikael. And @user16651 - these are the sort of details you should include in the question. For example, are you attempting to brew beer? Or not? Every bit of information helps get a better answer.


text:
DC motor kickback diode?
I have the following circuit:
And I know it works and that the diode protects the negative voltage from flowing back into the transistor. This is essentially the circuit:
Could someone illustrate what happens when the motor stops? The current normally flows from 5V to GND (and the electrons from GND to 5V, but this doesn't matter (I think?)), and then it reverses when you switch it off, so current comes out of the top of M1, and then what? I don't get it here.

This may not be the best suited for Arduino, it's more about Electronics..

While the motor is being powered the current flows from Vcc to GND as in this circuit:

When the power is disconnected (such as the transistor in the ground connection in your circuit is switched off) amongst other things (including the collapsing of magnetic fields) the spinning of the motor turns it into a generator.  The power generated is the opposite of what was being provided to make it move.  As the magnetic field of the coils collapses additional high voltages are also generated.
When disconnected the motor can be represented as a battery connected backwards.  In that configuration the current flows from the + of this hypothetical battery through the diode into the - thus stopping any current from going elsewhere, as in this circuit:

If it was only the motor turning into a generator, most transistors could cope with that, because the voltage generated by an open generator is limited. The residual current in the motor coils is the problem, because they provide a infinite voltage in theory when interrupted: U=L*dI/dt. In reality this voltage can reach some kV before it breaks down by some means.

@Ariser One thing at a time for the poor learner's brain.

Thank you. This makes a bit more sense now. I was wondering why current wouldn't flow into the arduino but it is shut down so it will obviously find the shortest way which is into the motor. Your representation of the motor as a battery helped me understand it. Thank you!


text:
Will the Uno bootloader work in the Duemilanove?
I had an old duemilanove lying around (Which was not working because i accidentially busted the atmega) and I recently bought some atmegas pre-flashed with the UNO bootloader. So I tried to put one of those in it, and it seems to work fine except that I have to select the UNO board in the arduino IDE.
My question is: Is there anything problematic to be aware of when using the UNO bootloader in an duemilanove?

So I researched it a bit, and there does not seem to be any problems with running the UNO bootloader on a Duemilanove board.
The biggest difference between the two seems to be the USB interface:
USB interface
Duemilanove uses FTDI, UNO uses another microcontroller (ATmega8u2).
Since the USB to serial is transparent for me as an end user for the most parts, it doesn't really matter to me.
Leaner bootloader
The UNO bootloader is smaller than the duemilanove.


text:
When to use different variable types?
There are several different types in the Arduino programming language. They each have different applications that can use up the limited RAM in the Arduino. When should i use each?

Could just be me, but this doesn't seem on-topic. I mean, it's basically an SO question. Maybe a topic for a [meta] question?

While I'm inclined to agree that this isn't entirely on-topic, I suppose it's worth noting that the types available using the Arduino IDE aren't exactly the same as regular C++. Notably, the type names boolean, byte and word. are not standard C++. Additionally, the String class is nothing like the C++ std::string. Perhaps a more specific question about the differences is warranted?

I think this question has value as these are not standard types. Explaining how the map from Arduino to avr-gcc is important.

First of all, arduino programmers may not want to go to SO to get their questions answered. second of all, The Arduino has very limited ram, so variable choice based on variable size is important.

The question was in context of specific usage and differences from that when used in Arduino.

I can understand the practicality of this question based on your answer, but from the question it's not immediately clear to me. Perhaps rewording the title to something like "What are the limits of the data types on the Arduino platform?"

It should probably also be mentioned that no one should use int, long, long long or similar variable declarations anyways. They should be using the types defined in <stdint.h> (e.g. uint8_t, int16_t, etc...), since int does not have a specified size in C/C++, and making compilation behaviour dependent on compiler implementation defined behaviour is irresponsible.

@TheDoctor - If you rewrite this question to be better phrased, it would probably be reopened. Right now, there is no evidence of even understanding what the difference between types.

@FakeName Relying on some of the stdint types for compiler portability isn't always a good idea because they won't necessarily exist. Things like uint32_t will not be defined if the compiler doesn't support a type matching the specified size. Therefore, where exact size is not critical, it may be better to use more generic types.

One should appreciate that the Arduino is an Embedded Processor. Specifically that it has limited resources of RAM and ROM(aka Flash/program space).
Often is the case I see coding use the "int" defaultly. Almost sloppily. If that works great.
BUT!!!!
You can run out of room REAL FAST with only 2K of RAM.
I would recommend that you size down your type to the minimum of what it needs to be describing it. One also gets a better understanding of what it really is and its limitations. There is no need for an array of int(16bits) from bytes that were recieved from the SPI, UART or I2C. Or a matrix of RGB's that consume 3 bytes each, being int's. You cut your capacity in half.
The pro/con: PRO: using default int everywhere makes it more inter changeable. The CON is that such interchangeability can lead to unintentional casting errors.
I would also recommend using C99 type def's which can be found at "avr_stdint.html">http://www.nongnu.org/avr-libc/user-manual/group_avr_stdint.html" and elsewhere. It makes things vivid, regards to this aspect. Hence a "int" would be a "int16_t", "unsigned long" be "uint32_t" etc...
It is worth knowing that in some cases a byte or char can not be replaced with int8_t, as such when used with string array functions. But they are still just as vivid.

Or you could use the mega with 128x the ram :)

@TheDoctor - the mega only has 4X the ram. 2K vs 8K

@FakeName - sorry, that's 256kb flash

@TheDoctor - That's still only 8X. 32K vs 256K.

An overview of the most commonly used variables:

byte: uses one byte (8 bits), holds numbers from 0 to 255
char: a signed byte
boolean: uses 1 byte, but only holds a value of true or false
int: uses 2 bytes, holds numbers from -32768 to 32767, mostly used in general programming. an int is what is known as a signed variable, where the last bit controls if it is negative or positive
long: uses 4 bytes, holds numbers from -2147483647 to 217283648, it is also signed
long long: uses 8 bytes, can hold -9223372036854775808 to 9223372036854775807, signed
float: uses 4 bytes, holds decimals from -3.4028235E+38 to 3.4028235E+38.
double: almost identical to float
string: an array of chars that represent text
String: not to be confused with string, this is a class that holds text data with extra functions

Most variable declarations can be prefixed with signed or unsigned to change the function of the sigh bit. For example, unsigned int x = 0; would create a variable that holds numbers from 0 to 65535 because the sign bit is used as an extra data bit.

This makes some extremely broad assumptions, and does not list their caveats. All the variable sizes are not specified, can vayry on some platforms/compilers, and is compiler implementation dependent. Furthermore, you're grossly oversimplifying things like floats, which have a large range, but limited resolution.


text:
Newbie needing help with debounce errors in arduino
So I found a code I would like to use and not sure how to edit the code properly.
#include <Debounce.h>

void matrix(char matrix[7]) {
  int map[10];
  map[0] = 2;
  map[1] = 3;
  map[2] = 4;
  map[3] = 5;
  map[4] = 6;
  map[5] = 7;
  map[6] = 8;
  map[7] = 9;

  int i=0;
  for(i=0;i<=7; i++) {
   if(matrix[i] == 0x30) { // 0x31=1, 0x30=0
      Serial.println(map[i]);
      digitalWrite(map[i],LOW);
   }
   else digitalWrite(map[i],HIGH);
  }
}

void show(int number) {
  switch(number) {
    case 0:
      matrix("11111100");
      break;
    case 1:
      matrix("01100000");
      break;
    case 2:
      matrix("11011010");
      break;
    case 3:
      matrix("11110010");
      break;
    case 4:
      matrix("01100110");
      break;
    case 5:
      matrix("10110110");
      break;
    case 6:
      matrix("10111110");
      break;
    case 7:
      matrix("11100000");
      break;
    case 8:
      matrix("11111110");
      break;
    case 9:
      matrix("11110110");
      break;
    default:
      matrix("00000010");
      break;
  }
}

#define t1 13
#define t2 12

Debounce debouncert1 = Debounce( 20 , t1 );
Debounce debouncert2 = Debounce( 20 , t2 );

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

  // initialize the digital pin as an output:
  pinMode(13, INPUT);
  pinMode(12, INPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
}

int setCountPlus(int count){
  if(count == 9){
    count = 1;
  }
  else{
    count++;
    count %= 10;
  }
  return count;
}

int setCountMinus(int count){
  if(count==1){
    count = 9;
  }
  else{
  count--;
  count %= 10;
  }
  return count;
}

void loop()
{
  int i=-1;
  show(i);
  while(1){
    debouncert1.update();
    debouncert2.update();
    if(debouncert1.read()){
      i=setCountPlus(i);
    }
    if(debouncert2.read()){
      i=setCountMinus(i);
    }
    if(i==10){
      i=1;
    }
    show(i);
    delay(250);
  }
}

as for the errors.
sketch 65: error: 'Debounce' does not name a type
sketch 66: error: 'Debounce' does not name a type
sketch .ino: In function 'void loop()':
sketch 108: error: 'debouncert1' was not declared in this scope
sketch 109: error: 'debouncert2' was not declared in this scope
Any help would be great on fixing the code to stop getting errors.

Where did you believe that Debounce was supposed to be found?

You need to install the Decounce library first.

Depending on the switch type:
-SPDT (SIngle Pole Double Throw) - You would use a Cross Coupled NAND Gates (Flip Flop, Set Reset) This will set true to the side it sees power at from the switch and if it bounces it can't change state until the switch touch the other contact.
-SPST (Single Pole Single Throw) - You can use a software debounce where you would detect a signal and then wait for 10ms then read again and if there is a signal still, it is a debounced signal.  --OR--  You can use capacitors to help extend the life of a signal.
so debounce code
bool sw13=false;
bool sw12=false;
while(1){
if(digitalRead(13)==HIGH && !sw13){
  delay(20); //Delay For 20ms
  if(digitalRead(13)==HIGH){
    i=setCountPlus(i);
    sw13=true;
  }
}else{
    sw13=false;
}
if(digitalRead(12)==HIGH && !sw12){
  delay(20);
  if(digitalRead(12)==HIGH){
    i=setCountMinus(i);
    sw12=true;
  }
}else{
    sw12=false;
}
if(i==10){
  i=1;
}
//show(i);
delay(250);
}

In the description of Debounce, you'll find the hint that this library is outdated and no longer maintained.
Its successors, Bounce1 and, more recently, Bounce2 are available from a github repository by Thomas Fredericks, Bounce-Arduino-Wiring.
Instead of simply downloading and unzipping the archive to ${HOME}/sketchbook/libraries, you might want to consider that this is the right moment to get familiar with git repositories as an easily updatable source for third-party libraries.
Supposed that you're on a GNU/Linux system with git installed, you would
cd /${HOME}/sketchbook/libraries
git clone https://github.com/thomasfredericks/Bounce-Arduino-Wiring.git

to obtain a clone of the necessary data.
If the name of the directory of the library contains dashes (-), you'll have to change this name: remove the dashes or replace them with underscores (_). Names with dashes aren't valid!
Once in a while, you would change to the directory of the respective library and simply run git pull to update your local copy to the latest version of the repository.


text:
Can I turn off a device using the 5V and analog pins?
Could I connect a device that requires minimum 5V 1A from the 5V Pin to the Ground and somehow turn it off inside  a sketch?
edit: I'm using a Due based boad, the digix http://digistump.com/wiki/digix/tutorials/basics

Provided you do not need to switch the load many times a second, your simplest solution to a task like this will be a shield with either magnetic or solid state relays on it - while transistor/FET solutions can be engineered to work, relays dramatically lessen the chance of the load coupling noise or damaging voltage spikes back into the Arduino.

You would use a transistor. Something like this would work.
In this case the Arduino controls a transistor to drive a brushless motor.
Source: Arduino Cookbook: (https://www.inkling.com/read/arduino-cookbook-michael-margolis-2nd/chapter-8/figure-8-9)
Update:
For the sake of clarity I should point out that the TIP102 is the device to use for the 1A required (not the 2N2222). And as pointed out by others the 5V supply of most Arduino boards would not be sufficient to supply 1A, so an external supply would be advised.

Thanks for this. Theres no reason why the motor power source and ground couldn't be 5v and gnd respectively,  right?

The 2n2222 is nowhere near up to the job, especially not the plastic TO-92 cased PN2222 shown.  And no, using the Arduino's 5v rail to power a high current external device is not a good idea.  Use a common ground, but a distinct supply.

Short answer: NO. It would fry your Arduino.
Long answer:
The current of Arduino pins is very limited (40mA max on UNO).
If you need to draw 1A, then you need a transistor between the Arduino pin and your device.
In such case, what you would normally do is:

connect any Arduino logical pin to the transistor base (through a resistor),
plug your device between a 5V supply (capable of 1A current providing) and the transistor collector,
connect the transistor emitter to the Arduino GND pin (and connect that pin also to the 5V-1A supply)

Note that you don't need to use an analog pin for that, a logical pin is enough if you just want to switch the device on or off.
Now notice that I specified a 5V 1A supply, that should normally be distinct from the 5V pin of the Arduino.
So the next question is: can you draw 1A out of the Arduino 5V pin?
The Arduino UNO page does not specify the current limitation on that pin. However it mentions the following:

5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V).

So the max current on this pin depends on 2 factors:

what is the power supply for the board: it is either USB, or an external power supply, which can be connected to the power plug or to the Vin pin.
the specs of the 5V regulator voltage on the Arduino board

If you use USB as power supply, then you are limited to 500mA as stated in the Arduino UNO page:

The Arduino Uno has a resettable polyfuse that protects your computer's USB ports from shorts and overcurrent. Although most computers provide their own internal protection, the fuse provides an extra layer of protection. If more than 500 mA is applied to the USB port, the fuse will automatically break the connection until the short or overload is removed.

If you use an external power supply that provides at least 1A, then we have to find out the max current by ourselves.
If we take a look at Arduino UNO schematics, then we see that this regulator is referenced as "NCP1117ST50T3G" (this is "U1" on the top-right corner).
The spec sheet for this regulator mentions that it can supply 1.0A.
So in theory, that should work, however, you also have to consider that this regulator also supplies current to the Arduino borard itself and all its pins.
If you love your Arduino and don't want to fry it, you should probably stay away from using its 5V pin for your purposes.
Now if you're open to experiment, you may try it :-)

What if I used the 5V pin and the ground and put a transistor between them and attached that to a analog line?

According to what I understood from the question (load wired between 5V and ground board pins), the limiting factor will be the voltage regulator, and not the ATmega MCU. The 40mA absolute maximum current applies only to the MCU, which in my opinion is not the case. See my answer for more details.

The simpler solution is to power Arduino from some external supply, then fork that power through a relay to controlled device.
Then you can switch the device by controlling that relay through your digital pin.

A standard magnetic relay cannot be driven by an Arduino Digital pin because of current requirement and inductive kick-back from the relay coil.

Have you try using a digital potentiometer name AD5220, it let you adjust the resistance
with using your hand. You can find more info about it at www.analog.com. I would upload an
image of the schematic but i just don't know how.

A digital potentiometer doesn't particularly sound like a solution for this problem.


text:
How can I sense very high temperatures with Arduino?
I've seen many temperature sensors, but the highest temperature they go up to is 125 degrees C (257 degrees F). I want to reach higher temperatures than that. I'm thinking about rigging up a closed loop sensor for my soldering iron (for a convenient LCD display), but I can't find out how to sense the temperature of the tip due to the higher operating temperature than most sensors.

You probably want to use a thermocouple. It'll give you the ability to measure much higher temps than regular temperature sensor. You'll also need a IC like the MAX6675 to interface with it.

The MAX6675 performs cold-junction compensation and digitizes the
  signal from a type-K thermocouple. The data is output in a 12-bit
  resolution, SPI™-compatible, read-only format.
This converter resolves temperatures to 0.25°C, allows readings as
  high as +1024°C, and exhibits thermocouple accuracy of 8 LSBs for
  temperatures ranging from 0°C to +700°C.

Page 6 of the datasheet has the serial interface protocol information and. You can really just set the Chip Select line and it'll give you 16 bits of information, 12 of which will be the temperature.

One of the options to measure high temperatures would be to use thermocouples. This table provides a basic description of the types and the corresponding temperatures that they can sense.
A simple search led me to these components.

Thermocouple Type-K Glass Braid Insulated - A mid range thermocouple
Thermocouple Amplifier MAX31855 breakout board - Board to interface the thermocouple with the Arduino. This is needed as the voltage changes in the thermocouple are extremely small, and the rise is non-linear.

This is how the board is connected to the thermocouple.

There is also a tutorial on Adafruit that deals with using and interfacing thermocouples.

This is an image of the thermocouple interfaced with the Arduino.