text:
Modbus RTU controller monitoring with arduino and RS485 module
I'm a medium user in Arduino. I baught a pHmeter controller with RS485 output (MODBUS RTU protocol).
I want to get pH value read by the controller over RS485 module and Arduino.
According the controller's manufacturer, we should operate as bellow:
Sent by computer : 00 03 00 00 00 01 85 DB
Return from controller : 00 03 02 02 AE 05 58.

#include SoftwareSerial.h

#define SSerialRX        10  //Serial Receive pin
#define SSerialTX        11  //Serial Transmit pin
#define SSerialTxControl 3   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW
#define Pin13LED         13

SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
byte byteSend;

void setup()
{
  // Start the built-in serial port, probably to Serial Monitor
  Serial.begin(9600);
  Serial.println("SerialRemote");  // Can be ignored

  pinMode(Pin13LED, OUTPUT);
  pinMode(SSerialTxControl, OUTPUT);

  digitalWrite(SSerialTxControl, RS485Receive);  // Init Transceiver

  RS485Serial.begin(9600);
  delay(2000);
  digitalWrite(SSerialTxControl, RS485Transmit);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x03);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x01);
   RS485Serial.write((byte)0x85);
   RS485Serial.write((byte)0xDB);
   Serial.println(" ");

   digitalWrite(Pin13LED, LOW);
   delay(10);
   digitalWrite(SSerialTxControl, RS485Receive);

}
void loop()
{

  if (RS485Serial.available())
  {
    byteSend = RS485Serial.read();   // Read the byte
    Serial.print(byteSend, HEX);
    Serial.print(" ");
  }
}

I tried this following sketch who does not work.
I would like to know if it is the good way to send request to the controller?

add to question a wiring schema and complete sketch

Post update with wiring and complete sketch

If you ask if there is a better way to send the request, then yes there is. but it will not make it work. byte request[] = {0, 0x03, 0, 0, 0, 0x01, 0x85, 0xDB};  RS485Serial.write(request, sizeof(request));

Good, it's working well.

To send series of bytes over Serial or any other Stream (Print) implementation use the "write buffer" method size_t write(const uint8_t *buffer, size_t size)
For the case in question:
byte request[] = {0, 0x03, 0, 0, 0, 0x01, 0x85, 0xDB};
RS485Serial.write(request, sizeof(request));

If someone is curios about the Modbus RTU request bytes. They are:

station address
function - 0x03 Read Multiple Holding Registers
register address - 2 bytes
number of registers to read - 2 bytes
checksum - 2 bytes

The response:

station address return
function or error code
data length
data - length bytes
checksum - 2 bytes


text:
Problems bluetoothing float values
I have two Arduino Unos, one of which is connected to a HC-05 bluetooth device and a temperature reader, the other has just a HC-05 bluetooth and is expected to output temperature readings in serial monitor.
This is first device:
#include <SoftwareSerial.h>
const int tempPin = 1;
SoftwareSerial BTSerial(10, 11);

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

}

void loop() {
int value = analogRead(tempPin);
float mv = value * (3300/1024);
float x = (mv - 500)/100;
Serial.print("Temperature is: ");
Serial.println(x);
BTSerial.print(x);
delay(5000);
}

This is the second device:
#include<SoftwareSerial.h>
void setup() {
BTSerial.begin(38400);
Serial.begin(9600);
}
void loop() {
if(BTSerial.available())
{
float x = BTSerial.read();
Serial.println(x);
}
}

The first program is able to give me accurate readings (around (15 degress Celsius) but the second program gives readings between 40 - 60 *C (as well as that it spits out 5 different readings between delay intervals). Why is that? How should I change this so both devices output the same readings

Two problems:
Your first program sends an ASCII representation of the temperature with no line ending.  So after a few readings you get something like:
20.2520.2520.5021.0021.25

etc.  You need some line endings in there to break them up.
Secondly your second program reads one byte at a time as a number (float) and prints it - so would get something like:
50.00
48.00
46.00
50.00
53.00
50.00
48.00
... etc ...

You need to, in association with sending line endings in your first program, read each character of a single line either into a string and then parse that as a float (with dtostrf()) or directly into a float using a state machine.
You can read more about working with serial here and working with a number reading state machine here.

Hi, thanks for the response!
Just a quick question; by line ending do you mean something along the lines of a "println()" statement or something else? thanks for the tips, will look into working with serial now

Hi, I just read through your article. Okay I understand, still wrapping my head around the code but I understand the theory behind it. Thank you, this helps a lot!

source: Stack Exchange

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

sort: votes


text:
Missing arduino bootloader problem?
I have a arduino clone that is not being assigned a /dev/tty by Debian Stretch (Stable).  It does have the ch340g chip.  I have tried the driver from the manufactures site with no joy.  Would the lack of a bootloader cause this problem?
Thanks.

Trying a random manufacturer driver makes no sense on a Linux system, the proper CH34x driver is already in the mainline kernel sources.  To figure out what is actually wrong you should start with dmesg and lsusb.

Been there done that.  And the source is from the Actual board manufactures site. usb 2-1.3: new full-speed USB device number 14 using ehci-pci
[136679.079624] usb 2-1.3: device descriptor read/8, error -32
[136679.207639] usb 2-1.3: device descriptor read/8, error -32
[136679.314532] usb 2-1-port3: unable to enumerate USB device

this information should have been in your question when you posted it . ... please update your question with this info (use the edit button)

What is actually wrong with the board is a different question than was asked.  Though again, despite being irrelevant to the actual issue, with Linux you all but never want to use a manufacturer's driver, and definitely not when there's a known-good and actually code reviewed one in the mainline kernel sources.

No.  On Arduino-style boards which use distinct chips for the main processor (ATmega328p) and Serial interface (CH34x/ATmega8u2/ATmega16u2/FT2232 etc) the presence or absence of a bootloader on the main processor has no bearing on the recognition of a USB/Virtual Serial device by a host.
However on ATmega32u4 and some ARM-based boards it can.
Since you are describing a classic board with distinct chips, whatever your actual issue is, it is something else.

Figured as much.  I was just hoping that when a new board gets here I could install a bootloader to it and have it start working.  So I expect that the chip is bad and I have a brick.  To bad it would cost as much to send it back as it cost in the first place.

If you desolder the USB chip the ATmega processor might still be good.

See my question & answer about debugging board issues

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


text:
Need help with understanding the CapacitiveSensor circuit diagram
Hey guys I need help with understanding the circuit diagram from this link: https://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense
As of now, this is the schematic I drew from what I understand:

I know it is wrong since they make use of 2 capacitors, but I do not know where should the other capacitor be connected to.

look again, they do not use any capacitors

They mentioned adding of capacitors in the documentation and it is also shown in dotted lines.

Looks like the cross-post was removed.

Also asked at: https://github.com/PaulStoffregen/CapacitiveSensor/issues/27 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

The other capacitor shown in the article is the ambient capacitance (that is, the capacitance between the pin and the things around it). There is no actual capacitor.
What it is saying is that there is a RC circuit (the supplied resistor and the capacitance in the air) which will change the charging time of the RC circuit as the capacitance changes, when you move your hand near it.

From a comment:

and the other capacitor with a value of 20-400pF

Yes, it does say that:

Adding small capacitor (20 - 400 pF) in parallel with the body capacitance, is highly desirable too, as it stabilizes the sensed readings.

However that doesn't make any sense to me. How do you add a capacitor in parallel with your body? Do you carry one around with really long wires? And how do you hold it? I would ignore that part.

Based on the documentation, it mentions that 2 capacitors are used. 1 of the capacitor with a value of 100pF and the other capacitor with a value of 20-400pF.

@DominicTeo See amended answer.

So ignoring the capacitor in parallel with the body, does my circuit drawing looks correct?

Yes it looks like what the referenced web site has.

This question appears to get posted every week!
There is NOT 2 capacitors.
The Csensed capacitor in dotted lines is the capacitance added when you touch the plate.
The Cpin capacitor is suggested to stabilise the readings and is not required.
So in the circuit NO capacitors are used.
All you need is a high value resistor between the Send Pin and Receive Pin and put your plate on the Receive Pin.

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


text:
How to store the content of message sent to GSM module (SIM900a) into a string?
I am Working on a project to control the system via the GSM messaging Scheme.
eg:- If I send 1 via an SMS to the GSM module, the Arduino would read this message and disable or enable the system.
But I am unable to process the message, since the received message format is;

+CMT: "+91xxxxxxxxx","","17/07/07,21:57:04+08"

#include<SoftwareSerial.h>
SoftwareSerial myGSM(9,10);// Rx and Tx
int a;
int b[5];
int actuator = 5;

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

void loop()
{
  msg_read();
  for( int i = 0; i < 5;  ++i )
   b[i] = (char)0;
}

void msg_read()
{
  myGSM.println("AT+CNMI=2,2,0,0,0");//AT command to recieve live SMS
  delay(1000);
  if (myGSM.available()>0)
  {
    char c;
    char store[30];
    c = myGSM.read();
    store[30] = c;
    int a = 10;
    a += 1;
    store[a] = 0;
    char* command = strtok(c, ",");
    while ( command != 0)
    {
      int i = 0;
      b[i] = atoi(command);
      command = strtok(0, ",");
      i++;
    }
  }
  for( int j = 0;j <= 2; j++)
  {
  msg_send(b[j]);
  }
}

void msg_send(int c[])
{
   myGSM.println("AT+CMGF=1");//Sets GSM module in text mode
  delay(1000);
  myGSM.println("AT+CMGS=\"+91xxxxxxxxxx\"\r");
  delay(1000);
  if( c[0] == 1)
  {
    digitalWrite( actuator, HIGH);
    myGSM.println("SYSTEM ENABLED");
  }
  else if( c[0] == 2)
  {
    digitalWrite(actuator, LOW);
    myGSM.println("SYSTEM ENABLED");
  }
  if( c[1] == 3)
  {
    myGSM.println("GEOFENCE ENABLED");
  }
  else if( c[1] == 4)
  {
    myGSM.println("GEOFENCE DISABLED");
  }
}

Requirement

I need a code that will allow me to recover the message content and compare it with a predefined string.
Can I use the GSM library with SIM900a module or is it reserved only for GSM shield?

I am using an Arduino Uno.

https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Thank you, the guide helped me figure it out. I encoded the message as #xy,  where x and y can take 0 and 1. I stored each character sent to the arduino in a variable.            char c = myGSM.read();                         Continued this until I found '#' and then used if statements to determine if the message was 1 or 0.


text:
Switch between timer2 and manually setting output of pin 3
I have a 62.5 kHz square wave created by timer2 on the pin 3. I would like to be able to use digitalWrite(3, HIGH) to force pin 3 high for several clock cycles, but then I would like it to return the 62.5 kHz square wave. Is there a way to reset a single output without resetting the entire program?
void setup() {
  Serial.begin(9600);
  pinMode(3, OUTPUT); //Output for OCR2B (Timer 2)
  //The following block allows sets the Timer2 properties for PWM
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(WGM22) | _BV(CS20);
  OCR2A = 255; //Sets the period to 16us (62.5kHz)
  OCR2B = 0; //Sets the duty cycle of the signal (8-bit(255) resolution)
}

void loop() {
  int pot = analogRead(A0);
  int duty = map(pot, 0, 1023, 0, 255); //scale to duty cycle resolution
  OCR2B = duty; //set duty cycle
  delay(10000); //arbitrary wait time
  digitalWrite(3, HIGH);
  delay(10000); //arbitrary wait time
  //undo the digitalWrite to continue the pulse train here
}

Can you show how you are currently setting up the square wave? That is, are you using a library in Arduino, or are you using the timer/counter registers directly to produce the waveform? Are the "several clock cycles" actual MCU clock cycles, or cycles of the 62.5 kHz waveform?

"several clock cycles" is just an arbitrary time where the output is force either high or low.

please do not put code in comments .... somebody moved the code to your question, where it is supposed to be .... please delete the two comments

If you clear the clock select bits in TCCR2B, then the PWM stops and you can control the port normally. To re-start the PWM, set the CS20 bit just as you did in setup().

to clear the bits would i set tccr2b = 0; or just the _bv(0) part?

TCCR2B &= ~(_BV(CS20)); will clear just CS20 bit and leave all else the same.


text:
Can Arduino control 8 solenoids?
I know very little about Arduino and even less about programming one. Before I purchase a board, and learn how to program it, I was wondering if my idea is feasible.
I want to program the Arduino to sequentially open one after another irrigation valve. There would be approximately eight 24 volt solenoid valves. Each one would need to be open for approximately 15 minutes, then open the next valve in sequence and finally close the previous valve. Similar to a multi-zone irrigation controller.
I see that I may need to use a transistor in the power circuit of the solenoid. But it is not clear to me if the Arduino can control eight solenoids and if so, does each solenoid require its own transistor?

is this what you really want? it is different from irrigation. Each one would need to be open for approximately 15 minutes, then open the next valve in sequence and finally close the previous valve. .... the sequence has to be absolutely clear in your mind, otherwise it will prove difficult to write a program that does what you want it to do.

Are these AC or DC solenoids? I see a lot of irrigation solenoids are AC.

If this is an educational endeavor: welcome.  If this is something you need to get done in a reasonable amount of time, then I recommend using existing irrigation solutions.   There is significant time and $ investment to not only program the device, but select switching mechanisms and ensuring they are hardened for the field

An Arduino can control (at least) 8 devices. Instead of a transistor, it might be much easier to use an 8 way relay controller, something like this:
8 relay module
Just connect all 8 valves to the relays, you power the relay with a separate source for the valves, and connect the pins to the Arduino.
These ones have opto couplers, which give an extra security between the valves and the Arduino.
8 relay module with opto couplers
(note I just put the first entry I found, you might find better/cheaper similar items, e.g. at AliExpress for $4).
As Andre said in a comment below, you can use an Arduino Mega if you need more outputs. Or if you want a challenge you can use use a multiplexer IC like 74HC595 (plenty of examples to be found with Arduino).
For controlling one relay with an Arduino enough examples can be found, for 8 it's similar (just use 8 GPIOs), or a multiplexer IC.

Ya, depending on the amount of current, it is better to have some pysical iscolation between your 24V/higher current side of the valves.  and the 5v/low current side of the arduino.

@ChadG For 10 euro I wouldn't take the risk myself, assuming the valves are more costly (or the risk not irrigating if that is the main goal).

These relay module usualy have opto-coupler isolation, but indeed check.

If you need more than i/o just use an Arduino mega.

@AndreCourchesne Thanks for the comments, I have updated my answer accordingly.

Why would one suggest a 70 IO Mega to control 8  outputs?

@CrossRoads Only in case he needs more outputs ... for 8 it's not needed, but I know from experience projects can grow easily.

@MichelKeijzers I was agreeing with you in case that was not clear, I was saying have physical isolation (Relays) was better then driving it with a transistor. Having opto-couplers on the relays is nice, but probably overkill for those little relays.

@CrossRoads Seeing as the OP had not bought a board, and was still exploring his options(and didn't say if he had planned on any specific board), suggesting a Mega was not out of line. The valves alone are 2/3 of the IO of a Uno, and it would make sense that he would want to add some sort of sensors or manual control down the road.

The choice between a Uno and Mega is also about flash/ram. On some application the Uno 2k of ram can be an issue.

@Chad Maybe optocouplers are overkill, but these all-in-once modules are so cheap, I don't think this 'extra'  is a problem.

Yes, you will need something to drive 24 volt solenoids, because the Arduino cannot do it alone.
My preferred method would be to use a ULN2803 device, which will allow you to drive all those eight solenoids (assuming they take less than 500mA or current) and has inbuilt protection against the voltage spike when the solenoid switches off.
http://www.ti.com/lit/ds/symlink/uln2803a.pdf
These devices are available on eBay.
The software will be quite simple for this application and should be well within the capabilities of anyone who reads an Arduino tutorial.

There are 2 wires to a solenoid, and 2 ways to operate them:
1- Closing a relay sends 24V out, with return wires going to 0 volts.
2- 24V Always goes out, and a relay can short the return wire to 0 volts.
Either way, test 2 by running the wires to a control board, and manually activating solenoids. When that works, add Arduino relay control as other suggest.
Keeping the switches will help, if you want to operate a solenoid manually OR you suspect you have a broken relay / solenoid.

Most irrigation valves are AC operated, typically using 24VAC at about 250mA (Double that to 500mA for the inrush current).  The best way to drive these is via a triac.  If you want isolation between your controller and the valve voltage an opto coupler with a triac output is the best way to go.  A good choice given the typical irrigation valve is the Vishay VO3023:  5mA LED input current and 1A output current and only about $0.50 per unit.  Triacs are pretty tough devices and have no moving parts like relays so they are quite reliable.

An Arduino board is merely a microcontroller with the stuff around it that is necessary to keep it running. By stufff, I mean thinks such as the voltage regulator that provides the power, the oscillator that provides the frequency for the controller, the GPIO pin connectors, and so on.
This is a very simple application and could easily be done by an Arduino. The programming doesn't have to run quickly. You are only doing one thing at a time.
I found an 8-channel relay module that should do what you need. You would need four of them, but they are only about $11 apiece. I have never used this device before, so I don't know how well it works, but the specifications seem right. They can be controlled by almost any computer with output pins that have 5 volts. So you'd need to use an Arduino with 5V output pins.
You will probably need more output pins than a standard Arduino, but that is easy enough to do with the Mega version.

it is not 24 valves. it is 8 24V valves :-)

That makes it even easier. The module I linked can handle 30V DC at 10 amps. It can also handle AC up to 250V. And now only one is needed.

Yes, Arduino can control eight transistors.
Each solenoid will need a transistor.
Ideal would be to use logic level N-channel MOSFETs that the Arduino 0/5V output can drive directly.  IRFL540 is mentioned a lot, you can get them at digikey.com.
Drive the gate thru a 150 ohm resistor, and have a 10K resistor from the gate to Gnd so the transistor is off while the Arduino is reset (and the IO pins all revert to Inputs).
Depending on the current draw, you may able to use a shift register with Open Drain outputs. TPIC6C595, 100mA. TPIC6B595, 150mA. TPIC6595, and TPIC6A595 are even higher current capable parts.
Add a diode with the same current rating across the solenoid coil, cathode to +24V, so the burst of current generated by the coil when the transistor closes has somewhere to dissipate. (current in a coil wants to keep flowing as the magnetic field in the coil collapses, it can't go thru the turned-off transistor, so it goes thru the coil and dissipates in the coil's wire-resistance).

this is not electronics.stackexchange

Your comment does not make sense. Arduino controlling transistors is a primary function of what it can do.

@Juraj knowing how to hook up the electronic portion of a system to an Arduino is an integral part of choosing/using Arduino devices. What made you think that it was perhaps off topic for this SE?

why not use relay modules? or any other actuator or sensor you can by as module with supporting circuit soldered in factory with so small components? What can he make more specialized for the application, then the of the shelf relay board? the questions are not rhetorical. I really want to know what is the drawback.

The solenoids I installed recently for my irrigation system were 24V AC-powered which would make a MOSFET or BJT transistor unsuitable. A Triac might be better in this case.

An alternative method is to use an I2c port expander such as a PCF8574.  These are available as break out boards.  By selecting a different I2C address on each break out board up to 64 relays can be controlled using opto isolated relay modules.  Thus 64 0utputs or inputs with just two Arduino pins.

You hardly need that for 8


text:
Getting a truly random number in Arduino
What is the best method to get a truly (as opposed to pseudo) random number in Arduino, or at least the best possible approximation? From my understanding, the function randomSeed(analogRead(x)) it's not random enough.
If possible the method should leverage the basic Arduino setup alone (no additional sensors). Solutions with external sensors are welcome if they improve significantly the randomness over the basic setup.

What is the application? Must it be cryptographically secure? What are you doing with the randomness then? Then without an external chip implementing a TRNG from a physical entropy source, you're out of luck. You could also implement a determenistic RNG like a HMAC DRBG and seed it from something static plus a low-quality entropy source, but that still won't be cryptographically secure.

Yes, I need random numbers for cryptographically secure applications.

randomSeed(analogRead(x)) will only produce 255 sequences of numbers, which makes it trivial to try all combos and produce an oracle that can couple to your output stream, predicting all the output 100%. You are on the right track however, it's just a numbers game, and you need a LOT more of them. For example, taking 100 analog reads from 4 ADCs, summing them all, and feeding that to randomSeed would  be much better. For max security, you need both unpredictable input and non-deterministic mixing.
I'm not a cryptographer, but I've spent thousands of hours researching and building hardware and software random generators, so let me share some of what I've learned:
Unpredictable Input:

analogRead() (on floating pins)
GetTemp()

Potentially Unpredictable Input:

micros() (w/ a non-deterministic sample period)
clock jitter (low-bandwidth, but usable)
readVCC() (if not battery-powered)

External Unpredictable Input:

temp, humidity, and pressure sensors
microphones
LDR voltage dividers
reverse-bias transistor noise
compass/acceleration jitter
esp8266 wifi hotspot scan (ssid, db, etc)
esp8266 timing (the background wifi tasks make scheduled micros() fetches indeterminate)
esp8266 HWRNG - RANDOM_REG32 -extremely fast and unpredictable, a 1-stop

collecting
The last thing you want to do is spit out entropy as is comes along. It's easier to guess a coin flip than a bucket of coins. Summing is good. unsigned long bank; then later bank+= thisSample; is good; it will roll-over. bank[32] is even better, read on. You want to collect at least 8 samples of input for each chunk of output, ideally much more.
Guarding against poisoning
If heating the board causes a certain max clock jitter, that's an attack vector. Same with blasting RFI towards the analogRead() inputs. Another common attack simply unplugging the unit thus dumping all the accumulated entropy. You should not output numbers until you know it's safe to do so, even at the cost of speed.
This is why you want to keep some entropy around long-term, using EEPROM, SD, etc. Look into the Fortuna PRNG, which uses 32 banks, each one updated half as often as the one before it. That makes it difficult to attack all 32 banks in a reasonable amount of time.
Processing
Once you collect "entropy", you have to clean it up and divorce it from the input in a hard-to-reverse way. SHA/1/256 is good for this. You can use SHA1 (or even MD5 really) for speed since you don't have a plaintext vulnerability. To harvest, never use the full entopy bank, and ALWAYS ALWAYS add a "salt" to the output that's different each time to prevent identical outputs given no entropy bank changes: output = sha1( String(micros()) + String(bank[0]) + [...] ); The sha function both conceals inputs and whitens output, protecting against weak seeds, low accumulated ent, and other common issues.
To use timer inputs, you need to make them indeterministic. This is a simple as delayMicroseconds(lastSample % 255); which pauses an unpredictable amount of time, making "successive" clock reads non-uniform in difference. Do that semi-regularly, like if(analogRead(A1)>200){...}, provided A1 is noisy or hooked to a dynamic input. Making each fork of your flow rather difficult to determine will prevent cryptoanalysis on decompiled/ripped output.
Real security is when the attacker knows your whole system and is still helpless to overcome it.
Lastly, check your work. Run your output through ENT.EXE (also available for nix/mac) and see if it's any good. Most important is the chi square distribution, which should usually be between 33% and 66%. If you get 1.43% or 99.999% or something edgy like that, more than one test in a row, your random is crap. You also want the entropy ENT reports as close to 8 bits per byte as possible, > 7.9 for sure.
TLDR:
The simplest fool-proof way is to the uthe ESP8266's HWRNG. It's fast, uniform, and unpredictable. Run something like this on an ESP8266 running the Ardunio core, and use serial to talk to the AVR:
// ESP8266 Arduino core code:
void setup(){
 Serial.begin(9600); // or whatever
}

void loop() {
  // Serial.write((char)(RANDOM_REG32 % 256)); // "bin"
  Serial.print( String(RANDOM_REG32, HEX).substring(1)); // "hex"
}

** edit
here is a bare-board HWRNG sketch I wrote a while back, operating as a not just a collector, but a whole CSPRNG spitting out of the serial port. It's built for a pro-mini but should be easily adaptable to other boards. You can use just floating analog pins, but it's better to add stuff to them, prefereably different things. Like microphones, LDRs, thermistors (trimmed to max spread around room temp), and even long wires. It does pretty well in ENT if you have even moderate noise.
The sketch integrates several notions I've mentioned in my answer and follow-up comments: accumulating entropy, stretching by over-sampling less-than-ideal entropy (von neumann said it's cool), and hashing to uniformity. It forgoes entropy quality estimation in favor of "gimme anything possibly dynamic" and mixing using a cryptographic primitive.
// AVR (ardunio) HWRNG by dandavis. released to public domain by author.
#include <Hash.h>

unsigned long read[8] = {0, 0, 0, 0, 0, 0, 0, 0};
const int pincount = 9; // adjust down for non pro-mini boards
int pins[9] = {A0, A1, A2, A3, A4, A5, A6, A7, A0}; // adjust for board, name analog inputs to be sampled
unsigned int ticks = 0;
String buff = ""; // holds one round of derivation tokens to be hashed.
String cache; // the last read hash

void harvest() { // String() slows down the processing, making micros() calls harder to recreate
  unsigned long tot = 0; // the total of all analog reads
  buff = String(random(2147483647)) + String(millis() % 999);
  int seed =  random(256) + (micros() % 32);
  int offset =  random(2147483647) % 256;

  for (int i = 0; i < 8; i++) {
    buff += String( seed + read[i] + i + (ticks % 65), HEX );
    buff += String(random(2147483647), HEX);
    tot += read[i];
  }//next i

  buff += String( (micros() + ticks + offset) % 99999, HEX);
  if (random(10) < 3) randomSeed(tot + random(2147483647) + micros());
  buff = sha1( String(random(2147483647)) + buff + (micros()%64) + cache); // used hash to uniform output and waste time
  Serial.print( buff ); // output the hash
  cache = buff;
  spin();
}//end harvest()

void spin() { // add entropy and mix
  ticks++;
  int sample = 128;
  for (int i = 0; i < 8; i++) { // update ~6/8 banks 8 times
    read[ read[i] % 8] += (micros() % 128);
    sample = analogRead(  pins[i] ); // a read from each analog pin
    read[ micros() % 8] += ( read[i] % 64 ); // mix timing and 6LSBs from read
    read[i] += sample; // mix whole raw sample
    read[(i + 1) % 8] += random(2147483647) % 1024; // mix prng
    read[ticks % 8] += sample % 16; // mix the best nibble of the read
    read[sample % 8] += read[ticks % 8] % 2147483647; // intra-mix banks
  }

}//end spin()

void setup() {
  Serial.begin(9600);
  delay(222);
  int mx = 2028 + ((analogRead(A0)  + analogRead(A1) + analogRead(A2)  + analogRead(A3)) % 256);
  while (ticks < mx) {
    spin();
    delay(1);
    randomSeed(read[2] + read[1] + read[0] + micros() + random(4096) + ticks);
  }// wend
}// end setup()

void loop() {
  spin();
  delayMicroseconds((read[ micros() % 8] %  2048) + 333  );
  delay(random(10));
  //if (millis() < 500) return;
  if ((ticks % 16) == (millis() % 16) ) harvest();
}// end loop()

(I’m short on characters here, sorry.) Good overview! I would suggest to use a counter for the salt; micros() is a waste of bits because it may jump by several steps between calls. Avoid the high bits in analogue inputs, restrict to the lowest one or two bits. Even with a targeted attack those are hard to pin down (unless you can put a wire on the Input). "Non-deterministic mixing" is not something you can do in software. SHA-1 mixing is standardised: https://crypto.stackexchange.com/a/6232. The indet. timer you propose is only as random as the source you already have is. Not much gain here.

sha simplifies and protects, so that you don't have to worry about how many bits to grab from an analog input for example. a few inches of wire connected to an analog (or a serpentine pcb trace) will swing it more than a few bits. the mixing is non-deterministic by virtue of the unsaved and unknown salt fed to the hash with a subsample of accumulated values. micros() is harder to replay than a counter, esp when fired at non-deterministic intervals.

I have a question. You said that taking 100 measures is better. But isn't taking lots of measures a sort of "average" that limits the effectiveness of taking these "random" data? I mean, usually you average to get less noisy (so less "random") measurements...

well I recommend constant sampling, i was just saying 100 is better than 1 since it offers more combinations. An accumulation model like Yarrow/Fortuna is still vastly better. Consider concatenating (not summing) those 100 analog samples before hashing; stronger because it makes sample order important, and being one char off yields a whole different hash. So, even though one could average the samples to get less noise, an attacker would have to verbatim recite all values or no match... My main point is "accumulate, mix, and verify" more than advocating a specific noise source.

The Entropy library uses:

the watchdog timer's natural jitter to produce a reliable stream of true random numbers

I like this solution because it doesn't use up any pins of your microcontroller and doesn't require any external circuitry. This also makes it less subject to external failures.
In addition to a library, they also provide a sketch that demonstrates the use of the same technique used to generate a random seed for the microcontroller's PRNG without the library:
https://sites.google.com/site/astudyofentropy/project-definition/timer-jitter-entropy-sources/entropy-library/arduino-random-seed

From my experience, analogRead() on a floating pin has very low
entropy. Maybe one or two bits of randomness per call. You definitely
want something better. The watchdog timer's jitter, as proposed in
per1234's answer, is a good alternative. However, it generates entropy
at a pretty slow rate, which can be an issue if you need it right when
the program starts. dandavis has quite a few good suggestions, but they
generally require either an ESP8266 or external hardware.
There is one interesting entropy source that has not been mentioned yet:
the contents of the uninitialized RAM. When the MCU is powered up, some
of its RAM bits (those that happen to have the most symmetrical
transistors) start up in a random state. As discussed in this
hackaday article, this can be used as an entropy source. It is only
available on a cold boot, so you can use it to fill an initial entropy
pool, which you would then periodically replenish from another,
potentially slow source. This way your program can start its work
without having to wait for the pool to slowly fill up.
Here is a example of how this could be harvested on an AVR-based
Arduino. The code snippet below XORs the whole RAM in order to build a
seed that it later feeds to srandom(). The tricky part is that the
harvesting has to be done before the C runtime initializes the .data
and .bss memory sections, and then the seed has to be saved in a place
the C runtime will not overwrite. This is done by using specific
memory sections.
uint32_t __attribute__((section(".noinit"))) random_seed;

void __attribute__((naked, section(".init3"))) seed_from_ram()
{
    const uint32_t * const ramstart = (uint32_t *) RAMSTART;
    const uint32_t * const ramend   = (uint32_t *) RAMEND;
    uint32_t seed = 0;
    for (const uint32_t *p = ramstart; p <= ramend; p++)
        seed ^= *p;
    random_seed = seed;
}

void setup()
{
    srandom(random_seed);
}

Note that, on a warm reset, the SRAM is preserved, so it still has the
whole contents of you entropy pool. This same code can then be used to
preserve the collected entropy across a reset.
Edit: fixed an issue in my initial version of seed_from_ram() that
worked on the global random_seed instead of using a local seed.
This could lead to the seed being XORed with itself, destroying all the
entropy harvested so far.

Nice work! can I steal? re: pins: one or two bits of unknown is enough if utilized right; that would only limit the output speed of perfect secrecy (yuck), but not the computational secrecy we need...

@dandavis: Yes, you can reuse, sure. You are right about analogRead() being usable if you know what you are doing. You just have to be careful not to overestimate its randomness when updating an estimate of your pool's entropy. My point about analogRead() is mostly meant as a criticism of a poor yet often repeated “recipe”: randomSeed(analogRead(0)) just once in setup() and assume it's enough.

If analogRead(0) has 1 bit of entropy per call, then calling it repeatedly will yield 10000/8 = 1.25 KBytes/sec of entropy, 150 times as much as the Entropy library.

If you don't really need entropy and simply want to get a different sequence of pseudo-random numbers on every startup, you can use EEPROM to iterate through consecutive seeds. Technically the process will completely deterministic, but in practical terms it's much better than randomSeed(analogRead(0)) on an unconnected pin, which will often make you start with the same seed of either 0 or 1023. Saving the next seed in EEPROM will guarantee that you start with a different seed each time.
#include <EEPROM.h>

const int seed_addr = 0;
unsigned long seed;

void setup() {
    seed = EEPROM.read(seed_addr);
    EEPROM.write(seed_addr, seed+1);
    randomSeed(seed);
}

If you need real entropy, you can collect it either from clock drift, or by amplifying external noise. And if you need a lot of entropy, external noise is the only viable option. Zener diode is a popular choice, especially if you have a voltage source above 5-6V (it will work with 5V too with an appropriate Zener diode, but will produce less entropy):

(source).
The amplifier output has to be connected to an analog pin, which will produce several bits of entropy with each analogRead() up to tens of MHz (faster than Arduino can sample).


text:
Standalone Programmer
I am trying to make my small stand-allone programmer to work using this code:
https://github.com/adafruit/Standalone-Arduino-AVR-ISP-programmer
But when I hookup everything and press button to flash my IC, I get this:
AdaBootLoader Bootstrap programmer (originally OptiLoader Bill Westfield (WestfW))

Type 'G' or hit BUTTON for next chip
Starting Program Mode [OK]

Reading signature:200
Searching for image...
 Not Found
Image fail

When I try to flash the same IC (just to make sure that IC is fine) via Arduino, there's no issues.
Any idea what can be wrong with this?

What IC are you programming?

I am trying to program ATMega328P-PU and with other assembled programmer which already have firmware which contains some variation of this OptiBoot_atmega328.hex it works.

Is images.cpp missing?

Nope, images.cpp is there, and signature there is fine

Looks like the problem was with fuses, fuses are not being set properly with this sketch. Once I write this IC with some other tool (like original OptiLoader) this sketch started to work.


text:
Coding force sensitive resistor to give output based on time used?
I have a basic set up of having a force sensitive resistor being used to power an LED as can be seen below. I am wondering how I can code it so that the LED is lit after a pressure has been applied to the FSR for a specified amount of time. Leading on from that I would like to use an RBG LED and have it so that after specified intervals on continuous pressure the LED changes colour.
Any advice would be greatly appreciated.
//Constants:
const int ledPin = 3;     //pin 3 has PWM funtion
const int sensorPin = A0; //pin A0 to read analog input

//Variables:
int value; //save analog value

void setup(){

  pinMode(ledPin, OUTPUT);  //Set pin 3 as 'output'
  Serial.begin(9600);       //Begin serial communication

}

void loop(){

  value = analogRead(sensorPin);       //Read and save analog value from potentiometer
  Serial.println(value);               //Print value
  value = map(value, 0, 1023, 0, 255); //Map value 0-1023 to 0-255 (PWM)
  analogWrite(ledPin, value);          //Send PWM value to led
  delay(100);                          //Small delay

}

You'll need to declare a variable to hold the start time (millis()) of when the force has exceeded the threshold.
You'll need to declare a constant to hold the threshold value (with analog data, you likely don't want to have your pressure threshold be "anything greater than 0", because noise and other things like small vibrations will trigger.
Also declare a constant to hold your "hold-off time" in milliseconds.
In your loop(), when you have an analog value that exceeds the pressure threshold, store the value of millis(). Also in your loop(), when the current millis() minus the start value  is greater than the "hold-off time", activate your LED.
For RGB, same setup, but you can set your color based on how much greater the time difference is than the hold-off time.


text:
Send serial data to local server
I am new to arduino coding.
I am reading data from serial port and storing it in char array.
I want to send that data to the local server but it is not getting converted to string
Code :
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server;
char* ssid = "Office RTPL";
char* password = "********";
char data[64];
char data1[64];
String str;
void setup()

{
  // put your setup code here, to run once:
  WiFi.begin(ssid,password);
  Serial.begin(115200);
  while(WiFi.status()!= WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.print("IP Address: ");
  Serial.print(WiFi.localIP());
  server.on("/",[](){server.send(200,"text/plain","Data Test");});
  server.on("/toggle",serialData);
  server.begin();
}
void loop()
{
  // put your main code here, to run repeatedly:
  server.handleClient();
 ;
}
void serialData()
{
  if(Serial.available() > 0)
      {

        server.send(200,"text/plain","Data");
         for(int n=0; n<64; n++)
         {
           data[n] = (Serial.read());

         }
         String str (data);
         server.send(200,"text/plain",str);

  else
        {
        String no_data = "No Serial Data";
        server.send(200,"text/plain",no_data);
        delay(5000);
        }

}

Please help

As I mention in my answer about serial communication:

Before reading, always make sure data is available. For example, this is wrong:
if (Serial.available ())
  {
      char a = Serial.read ();
      char b = Serial.read ();  // may not be available
  }

The Serial.available test only ensures you have one byte available, however the code tries to read two. It may work, if there are two bytes in the buffer, if not you will get -1 returned which will look like 'ÿ' if printed.

In your code:

if(Serial.available() > 0)
    {
    server.send(200,"text/plain","Data");
     for(int n=0; n<64; n++)
     {
       data[n] = (Serial.read());

So you know that one byte is available, but you are reading 64. No, that won't work.

May u please guide how should i read it.

Read how to read incoming serial data without blocking.

Alternatively you could change that if test to be: if(Serial.available() >= 64)


text:
Switch case does not work after booting system
int value1;
int value2;
int runs1 = 0;
int runs2 = 0;

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 16, 2);
int inPin = 6;
int val = 0;
int push_count = 0;
int buttonState = 0;
unsigned long previousMillis = 0;
const long interval = 1800000;
int currentTime;

void setup() {
  Serial.begin(9600);
  lcd.begin();
  pinMode(inPin, INPUT);
}

void loop() {

  unsigned long currentMillis = millis();
  currentTime = 30-(currentMillis - previousMillis)/60000;
  if (currentMillis - previousMillis >= interval || previousMillis == 0) {
    previousMillis = currentMillis;

  measure();
  }

  buttons();
}

void measure() {
 value1=300;
 value2=300;

  if (value1 <= 650)
{
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("1");
   delay(2000);

}
else
{
  lcd.clear();
  lcd.print("Pump 1 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs1++; // increment the number of times pump 1 has run

}

  if (value2 <= 550)
{
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("2");
   delay(2000);
   Serial. print("Pump 2 OK");
}
else
{
  lcd.clear();
  lcd.print("Pump 2 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs2++; // increment the number of times pump 2 has run
  Serial. print("Pump 2");
}
  }

void buttons() {
  val = digitalRead(inPin);

  if (val != buttonState && val == HIGH){
    push_count++;
  }
      else {
      // do nothing
    }

  buttonState = val;
  switch (push_count) {
    case 0:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Sensor 1 reads");
      lcd.setCursor(0,1);
      lcd.print(value1);
      delay(20);
      Serial. print("Case 0");
      push_count++;
      break;
    case 1:
      Serial. print("Case 1");
      break;
    case 2:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Sensor 2 reads");
      lcd.setCursor(0,1);
      lcd.print(value2);
      delay(10);
      push_count++;
      break;
    case 3:
      break;
    case 4:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Pump 1 ran");
      lcd.setCursor(0,1);
      lcd.print(runs1);
      lcd.setCursor(5,1);
      lcd.print(" times");
      delay(10);
      push_count++;
      break;
    case 5:
      break;
    case 6:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Pump 2 ran");
      lcd.setCursor(0,1);
      lcd.print(runs2);
      lcd.setCursor(5,1);;
      lcd.print(" times");
      delay(10);
      push_count++;
      break;
    case 7:
      break;
    case 8:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Next cycle in");
      lcd.setCursor(0,1);
      lcd.print(currentTime);
      lcd.setCursor(5,1);
      lcd.print(" Minutes");
      delay(10);
      push_count++;
      break;
    case 9:
      break;
    default:
      push_count=0;
  }
}

When I boot the system (standalone atmega328p circuit) the connected LCD either shows

Plant
2

originating from
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("2");
   delay(2000);
   Serial. print("Pump 2 OK");

or in my real code (where value1 and value2 are actually measured)

Pump 2 turned ON
Water for 40 sec

originating from
  lcd.clear();
  lcd.print("Pump 2 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs2++; // increment the number of times pump 2 has run
  Serial. print("Pump 2");

after I use the button to cycle through all the cases everything works fine. On the next button press I get to case 2 (-> 3).
After a full cycle case 0 (-> 1) gets displayed correctly.
The above MCVE runs perfectly on my breadboard setup, but not in the real setup.
Here's the schematic of the real setup.
So somewhere in the real setup has to be something that my code does not handle properly. The breadboard setup is minimal, just all GND and VCC connections, a 16 Mhz crystal with 22 pF caps.

Consider writing an MCVE

@DmitryGrigoryev I wasn't sure whether I should do that, I didn't want to delete the faulty part of the code by accident. See my edit, I guess I have to do some further testing tonight. I use pull down resistors in my atmega setup for the button.

The "V" part of MCVE means Verifiable – Test the code you're about to provide to make sure it reproduces the problem

@josecanuc For some reason I can't reproduce the error on the arduino or the breadboard. Only in my real system. I know that this makes finding the root cause for people here almost impossible.

Intermittent errors are likely to be undefined values. That could be software uninitialized variables, or hardware: floating pins. You may also be dealing with bouncing button contacts, as noted in one answer.

When I boot the system (standalone atmega328p circuit) the connected LCD either shows .... you do not say what it shows, i am pretty sure that it does not list the code

Could the downvoter elaborate what I could improve? @jsotola Of course it doesn't list the code, I quoted the sections so you can easily see where the output comes from. Updated!

Try posting the results of all those serial prints.

@idkfa, what you think that the code tell it to display is not necessarily the same as what is actually displayed ... you updated the question with the "displayed text" .... i removed the downvote

int buttonState = 0;

So buttonState is initially zero (LOW).
  val = digitalRead(inPin);

  if (val != buttonState && val == HIGH){
    push_count++;
  }

Since you have an external pull-up on inPin it will read HIGH initially. Thus push_count will be incremented immediately.
  switch (push_count) {
    case 0:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Sensor 1 reads");
      lcd.setCursor(0,1);
      lcd.print(value1);
      delay(20);
      Serial. print("Case 0");
      push_count++;
      break;
    case 1:
      Serial. print("Case 1");
      break;

Therefore you execute case 1 initially.

Also, I don't see how this works:
 value1=300;
 value2=300;

  if (value1 <= 650)
{
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("1");immediately
   delay(2000);

}
else
{
  lcd.clear();
  lcd.print("Pump 1 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs1++; // increment the number of times pump 1 has run

}

  if (value2 <= 550)
{
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("2");
   delay(2000);
   Serial. print("Pump 2 OK");
}
else
{
  lcd.clear();
  lcd.print("Pump 2 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs2++; // increment the number of times pump 2 has run
  Serial. print("Pump 2");
}

Since you are doing both if tests it seems likely (indeed certain) that you will display "Plant 1" and then immediately* overwrite it with "Plant 2" so quickly that you wouldn't notice it.
* apart from the 2-second delay of course. :)

Luckily this project is one of my first so everything is still in prototype stage, i.e. a lot of jumper cables so this was an easy fix. So actually my code progressed the cases on release, not on press. To answer the second part of your answer ( ;) ) this is intended. It's just a visualization if you happen to watch the display during measurement. It will display "reading sensors" before. I also got a boot animation which I probably won't ever see again once the system doesn't need changes anymore.

Personally I don't like the way you handle the "state machine", and I'd implement it in what I perceive is a more robust way (I may be wrong, though).
Moreover if you have a button please add a debounce; I usually do this with the Bounce2 library (or alternatives I code which are modified versions of that library). So... Let's change the things in the way I prefer.
// Include the library
#include <Bounce2.h>

// declare a bounce object
Bounce buttonDebounce = Bounce();

//in the setup:
pinMode(IN_PIN, INPUT); // or INPUT_PULLUP?
buttonDebounce.attach(IN_PIN);
buttonDebounce.interval(5);

//in the loop:
buttonDebounce.update();

Then in the loop you can use the buttonDebounce.rose() function or buttonDebounce.fell() to detect the button presses.
Now, for the state machine. You have four meaningful states (let's call them DISPLAY_1 to 4). It's better to give them more meaningful names. And let's add an invalid state. I usually prefer to use const bytes to force the size rather than enums or defines, but.. whatever ;)
So outside loop or setup declare the values and the state variable:
const byte SM_ErrorState = 0;
const byte SM_Display_1 = 1;
const byte SM_Display_2 = 2;
const byte SM_Display_3 = 3;
const byte SM_Display_4 = 4;
const byte SM_Display_5 = 5;
byte SM_currentState;

Now, the function buttons can be implemented in the classical way I learned to implement state machines, which is first make a switch case to test whether you have to advance, then advance to the next state if necessary and perform the entry action.
void buttons()
{
    buttonDebounce.update();

    nextState = SM_currentState;

    // Check if a new state is requested
    switch (SM_currentState)
    {
    case SM_Display_1:
        if (buttonDebounce.rose())
            nextState = SM_Display_2;
        break;
    case SM_Display_2:
        if (buttonDebounce.rose())
            nextState = SM_Display_3;
        break;
    case SM_Display_3:
        if (buttonDebounce.rose())
            nextState = SM_Display_4;
        break;
    case SM_Display_4:
        if (buttonDebounce.rose())
            nextState = SM_Display_5;
        break;
    case SM_Display_5:
        if (buttonDebounce.rose())
            nextState = SM_Display_1;
        break;
    default:
        nextState = SM_Display_1;
        break;
    }

    // If an advancement is requested, advance and then perform the entry action
    if (nextState != SM_currentState)
    {
        SM_currentState = nextState;
        switch (SM_currentState)
        {
        case SM_Display_1:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Sensor 1 reads");
            lcd.setCursor(0,1);
            lcd.print(value1);
            delay(20);
            Serial. print("Case 0");
            break;
        case SM_Display_2:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Sensor 2 reads");
            lcd.setCursor(0,1);
            lcd.print(value2);
            delay(10);
            break;
        case SM_Display_3:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Pump 1 ran");
            lcd.setCursor(0,1);
            lcd.setCursor(5,1);
            lcd.print(runs1);
            lcd.print(" times");
            delay(10);
            break;
        case SM_Display_4:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Pump 2 ran");
            lcd.setCursor(0,1);
            lcd.print(runs2);
            lcd.setCursor(5,1);;
            lcd.print(" times");
            delay(10);
            break;
        case SM_Display_5:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Next cycle in");
            lcd.setCursor(0,1);
            lcd.print(currentTime);
            lcd.setCursor(5,1);
            lcd.print(" Minutes");
            delay(10);
            break;
        default:
            break;
        }
    }
}

Now, the initialization. Remember that I told you to add an error state? This way you can force a state change on initialization by setting the variable to the SM_ErrorState value.
Then, the millis management in the loop. I'd avoid the particular case of the variable equal to 0 to trigger an immediate execution, since this will lead to errors later. Then I also prefer to sum the interval, to avoid having a drift. So I changed your way to another one. I also changed some code for better readability (for instance, letting the "timer" reset every minute rather than every 30 minutes, and changing the defines accordingly).
Here is my complete code; I left out the measure function since it does not impact the other code.
Let me know if this solves your problem. Oh, BTW, UNTESTED CODE, so some bugs may appear...
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Bounce2.h>

LiquidCrystal_I2C lcd(0x3F, 16, 2);

int value1; // I think it is better if these
int value2; // two variables are initialized
int runs1 = 0; // Unsure if this is needed
int runs2 = 0; // Unsure if this is needed
int val = 0; // Unsure if this is needed

int inPin = 6;
unsigned long previousMillis = 0;
const unsigned int millisInOneMinute = 60000U;

byte elapsedMinutes;
const byte intervalMinutes = 30;

Bounce buttonDebounce = Bounce();

void setup() {
    Serial.begin(9600);
    lcd.begin();
    pinMode(inPin, INPUT);
    buttonDebounce.attach(inPin);
    buttonDebounce.interval(5);
    previousMillis = millis();
    elapsedMinutes = intervalMinutes; // Force a new measure
}

void loop() {
    if (((unsigned int)(millis() - previousMillis)) >= millisInOneMinute)
    {
        previousMillis += millisInOneMinute; // Avoid drifting
        elapsedMinutes++;
    }

    if (elapsedMinutes >= intervalMinutes)
    {
        elapsedMinutes = 0;
        measure();
    }

    buttons();
}

void measure() {
    // do your stuff
}

void buttons()
{
    buttonDebounce.update();

    nextState = SM_currentState;

    switch (SM_currentState)
    {
    case SM_Display_1:
        if (buttonDebounce.rose())
            nextState = SM_Display_2;
        break;
    case SM_Display_2:
        if (buttonDebounce.rose())
            nextState = SM_Display_3;
        break;
    case SM_Display_3:
        if (buttonDebounce.rose())
            nextState = SM_Display_4;
        break;
    case SM_Display_4:
        if (buttonDebounce.rose())
            nextState = SM_Display_5;
        break;
    case SM_Display_5:
        if (buttonDebounce.rose())
            nextState = SM_Display_1;
        break;
    default:
        nextState = SM_Display_1;
        break;
    }

    if (nextState != SM_currentState)
    {
        SM_currentState = nextState;
        switch (SM_currentState)
        {
        case SM_Display_1:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Sensor 1 reads");
            lcd.setCursor(0,1);
            lcd.print(value1);
            delay(20);
            Serial. print("Case 0");
            break;
        case SM_Display_2:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Sensor 2 reads");
            lcd.setCursor(0,1);
            lcd.print(value2);
            delay(10);
            break;
        case SM_Display_3:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Pump 1 ran");
            lcd.setCursor(0,1);
            lcd.setCursor(5,1);
            lcd.print(runs1);
            lcd.print(" times");
            delay(10);
            break;
        case SM_Display_4:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Pump 2 ran");
            lcd.setCursor(0,1);
            lcd.print(runs2);
            lcd.setCursor(5,1);;
            lcd.print(" times");
            delay(10);
            break;
        case SM_Display_5:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Next cycle in");
            lcd.setCursor(0,1);
            lcd.print(elapsedMinutes);
            lcd.setCursor(5,1);
            lcd.print(" Minutes");
            delay(10);
            break;
        default:
            break;
        }
    }
}

EDIT: Generic implementation of a state machine
Ok, here I post my generic scheme for a state machine. Usually I use the "state-based" state machine, which is actions are linked to states; sometimes I also saw "transition-based" state machines, where actions were linked to transitions, but... Ok, I'm not a real expert, so I don't want to write a lot of (wrong) things.
In this kind of machines, each state can have up to three kind of actions and a check:

actions you perform when you ENTER the state
actions you perform continuously when you are INSIDE the state
actions you perform when you EXIT the state
and of course, you have to CHECK whether you need to make a transition to another state

For instance, when you have in a microwave a state corresponding to the ON state, you have to:

when you ENTER the state, turn on the heater
when you are INSIDE the state, update the timer value
when you are done and you are EXITing the state, turn off the heater
when during the CHECK you see that the timer has expired or the stop button was pressed, you switch to another state

So there are four kind of actions: ENTER, INSIDE, EXIT and CHECK. For linearity I learned that it is much better to write each of them in a separate switch case. This is my usual implementation scheme:
void stateMachine()
{
    byte nextState = currState; // currState of course is defined outside

    switch (currState)
    {
    // Here you have to CHECK, for each state, the conditions
    // needed to switch to another state; if you switch, put
    // the new state in nextState
    }

    if (nextState != currState)
    {
        switch (currState)
        {
        // Perform the EXIT functions for each state
        }

        // Advance to the next state
        currState = nextState;

        switch (currState)
        {
        // Perform the ENTER functions for each state
        }
    }
    else // See note below
    {
        switch (currState)
        {
        // Perform the actions to be performed continuously
        // INSIDE each state
        }
    }
}

NOTE: the else can be omitted or not. If you leave it, in the cycle that you detect the change you do not perform the INSIDE action; if you omit it, the INSIDE action will be performed. This is useful in different cases.
Now, usually (and yours is one of these cases) you only need the CHECK and ENTER sections (if you look at the code, you will see that only these two sections were implemented). Once in a while you will need also the INSIDE section, and once in your life you will also need the EXIT ;) (at least in my experience)

I will report back once I had the time to implement and test the code. Your answer is greatly appreciated. However I have a small note on why I handled the statemachine the way I did: If I see it correctly the selected case runs every loop in your code too. This creates a flickering of the text on the LCD as it gets deleted and rewritten every cycle. That's why I wrote it once, and advanced to the next case where nothing happens.

@idkfa (BTW nice nickname, but I preferred iddqd :P) no, the code is executed just once. I'm adding a quick section at the end of the answer to explain the way I usually implement state machines (it is the way they thought me), but the code here is executed only once..

I finally got around to read through your examples. I learned a lot from it and I must say I definitely understand now why you didn't like my implementation. I also see how this avoids the flickering issue. Thank you very much!

@idkfa I'm glad I could help you :)

You haven't ever set value1 or value2, but your if-else statements depend on them.
Before you can test a variable to have a specific value, you must set the variable at some point prior to using it. In your code, value1 and value2 are declared global, but never initialized and never set, so they are undefined and could have any value in them at the start.

I added the values (and confirmed that it still doesn't work). They got lost during creating the MCVE from my code.

Global variables are set to zero by the compiler.


text:
Using a rotary switch
I don’t have a sketch for this project, just doing some thinking before I pullout the keyboard (this is my phone).  I was interested in writing a program that uses a predetermined time limit, for instance having a definition like...
#define RUNTIME 30000

So the game runs for 30 seconds.
By doing this it would be a simple matter of changing the 30000 to 60000 and uploading to the Arduino.
After thinking about that a while, I would prefer to be able to adjust the time using a selector switch.
So my question is....  if I use a 1p4t (on-on-on-on) rotary selector switch,  assign each position to a pin and run 5v to the common. Each pin would defined as RUNTIME and a different time limit, 30000, 60000, 90000, 120000, three pins would be LOW and one HIGH depending on position.
Then using IF and ELSE statements in the loop setup would I be able to switch the times?  I know once the Arduino is powered up the selector switch would need to be at the correct location and if you choose to change the “RUNTIME” a reset would need to be pressed.
Thank you for any assistance or ideas.

Better to use GND not +5V and use the INPUT_PULLUP mode for the pins. If you don't you then need to add a pulldown resistor to all 4 inputs.

You would not HAVE to reset when changing the switch position. you could periodically check the switch input and update the value while running.

you could use an analog pin and 4 voltages instead of many pins.

for a simpler keyswitch circuit look at the keypad schematic at the bottom of this page ... in the "More" section .... https://www.dfrobot.com/wiki/index.php/LCD_KeyPad_Shield_For_Arduino_SKU:_DFR0009    ......... use the code on the page for reference

If I understand you well, it's very easy.
Assuming the 4 outputs of the switch will be connected to 4 GPIO's you just can check for the state of each GPIO and act on it
// Pin numbers where switch 1 to 4 are attached to.
#define PIN_SWITCH_1  8
#define PIN_SWITCH_2  9
#define PIN_SWITCH_3 10
#define PIN_SWITCH_4 11

unsigned long timer_value = 1000; // No switch selected

void setup()
{
     // Set switch pins to input mode.
     pinMode(PIN_SWITCH_1, INPUT);
     pinMode(PIN_SWITCH_2, INPUT);
     pinMode(PIN_SWITCH_3, INPUT);
     pinMode(PIN_SWITCH_4, INPUT);

     // Check switches
     if (digitalRead(PIN_SWITCH_1) == HIGH)
     {
         timer_value = 30000;
     }
     else if (digitalRead(PIN_SWITCH_2) == HIGH)
     {
         timer_value = 60000;
     }
     else if (digitalRead(PIN_SWITCH_3) == HIGH)
     {
         timer_value = 90000;
     }
     else if (digitalRead(PIN_SWITCH_4) == HIGH)
     {
         timer_value = 120000;
     }
     else
     {
         // Keep default value
     }
 }

 void loop()
 {
     // Here you can use timer_value to check for the end of the game.
 }

Thank you everyone for your input.  I will be moving  ahead with this project.

pin 1 is a trap for the beginner?

@Juraj ... yes it's mean of me to use those pins ... I was not near an Arduino so I should check which are really free and obvious to use.


text:
Power Down Interrupt Arduino
Does anyone know a way to call an interrupt when an Arduino loses power to have it fire a small function real quick?
It'd be a quick EEPROM write of one variable.
I know you can use interrupts on certain pins when they get pulled low, I'm just not sure if it's possible on the power pin.
Or if there would still be enough power in the controller to finish that function.
I have the Node MCU board but it's programmed in Arduino c++.

Not directly, no.  When an Arduino or ESP8266 has lost power it's lost power. You need external circuitry to keep providing power after the power input has been removed, and alert your target chip that power has gone.

simulate this circuit – Schematic created using CircuitLab
C1 wants to be massive. The ESP8266, because of the WiFi interface in it, consumes a lot of power.  Also, writing to EEPROM or Flash (which the ESP8266 has instead of EEPROM) takes extra power.
Ideally, C1 wants to be a small Super-Cap to keep the physical size small.  For an ESP8266 you're probably talking thousands of uF.
An alternative is to use the 47L16 (or similar) EERAM chip which is designed to save its internal SRAM contents to internal EEPROM when power is lost using its own dedicated capacitor-based power reservoir.

Does the 47L16 save to it's own internal EEPROM or to the EEPROM of the MCU?

Internal. RTFM.


text:
function returning String-Array
i'm still new to arduino and also to C++ and have a short question.
What i want to do is to write a function (in my case to parse the query-string of an URL) to get the parameter names and values (varying number of parameters).
My function looks like the following:
String function readParams()
{
   String params[x]; // x: number of params

   // fill params[0]... params[x] with parameter names

   return params;
}

void loop()
{
   // do some stuff

   String params[x] = readParams();

   for(int i=0; i < x; i++)
   {
      debug(params[i]);
   }
}

What is the correct return-type for the readParams() function in this case?
And how to access the params in the main (loop) -function?
I hope the code makes it clear what i want to do.
Thanks,
Marius

Some tips:

Don't use String.
Use char * and slice the string in-place.
Pass a pointer to an array of pointers and fill that with pointers to the portions of the string you have sliced.
Return the number of entries in the array you used.

I do something similar in my CLI library.  I use a custom "getWord" function, but similar can be done with strtok().
You can read more about working with C strings here.

I'm inclined to agree with Majenko that you shouldn't use String in the first place, but if you want to, you can pass by reference:
const int numParams = 2;

void readParams(String (& params) [numParams])
  {
  params [0] = "foo";
  params [1] = "bar";
  }

void setup()
{
  Serial.begin (115200);
  String params [numParams];
  readParams (params);
  for (int i = 0; i < numParams; i++)
    Serial.println (params [i]);
}

void loop() { }

An easier thing is to make the parameters a global variable.

what if number of parameters is not known in the beginning ? how would you initialize numPaams then ?

Typically you would use new and make an array of whatever it is you want to make multiple copies of. Or you could consider the STL (Standard Template Library) which supports things like vectors.


text:
How to work with analog readings using RPi and Firmata?
For context: I'm working on a project where I need to use sensors to figure out the current state of the environment. This process is done using an Arduino UNO and a RPi. The easiest way that I found to perform communication between both boards is by uploading Standard Firmata and reading the code from RPi using Serial communication. I'm using pyfirmata to write the code in Python on the RPI side. Also, the Arduino is powered by the RPi using the USB port.
My problem was: The ADC component in the Arduino uses as the analog reference the 5V provided by the USB. When I tested the integration, I was using my laptop. So, the computer was providing 5V to the Arduino. So far so good. When I integrated the Arduino board to the RPi, I got some problems related to the precision of the sensor. I figured out that the RPi was only giving 4.75 V to the Arduino Board. This was messing with my readings since the ADC was using 4.75V while my code had 5V to compute things. After adjusting the code, everything proceeded as planned. Both 4.75 V and 5 V were hardcoded in my code.
So, these are my questions:

Is there a way to read the Vcc using pyfirmata to figure out the correct voltage without having this hardcoded?
Is there a way to modify the analog reference to use the INTERNAL reference of 1.1V?

About the analog reference, I found this: https://github.com/firmata/arduino/issues/39 . So, pyfirmata implements send_sysex method, I just have to execute these steps, but I still don't know how.

It does not appear that Firmata has proceeded with the ability to change the analog reference source. You referenced one of the issues opened for it, but I don't see anywhere where it committed to the current master branch.
There's no way for an Arduino to read a voltage without some reference, and as you are experiencing, the default reference is Vcc. That means everything must be compared to Vcc, and if you compare Vcc to itself, you will always find out that Vcc is equal to Vcc.
The pull request to implement is here, so you could play around with it yourself.

So, you are saying that even if I use the send_sysex method (which I'm still not sure that can solve my problem), it wouldn't matter since the analog reference modification is not implemented in the current Firmata version?

I'm not an expert on Firmata, but I searched through the source code for the firmata code that would run on an Arduino and no were in there does it implement anything that sets the analog reference.

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


text:
Change Arduino Uno clock from 16MHz external to 1MHz internal
I've got a project where I need to program an ATmega328P on an Arduino Uno board, then transplant it into a custom PCB - however, this board does not have an oscillator installed, and so I need to run the microcontroller off its internal clock.
My goal here is to be able to code my software with the Arduino IDE, insert a factory-fresh ATmega328P straight from the tube into the socket on the Arduino Uno board, then move the device from the board to the PCB without any changes along the way. What's the best way to go about this?

don't recall where, but i've seen a board def for a bare 328 set to run at 8mhz w/o xtal; maybe it will allow 1mhz as well...

That will not work. To change the clock source, you'd need to change the fuses. I don't know of any way to do this while the chip is inside the UNO.
Secondly, a factory fresh 328P won't work in an UNO board, because it doesn't have the correct fuses, and doesn't have the bootloader programmed.
I'd suggest placing the 328P chips in a breadboard; connect the ISP pin to the UNO, and use the Arduino-as-ISP to change the fuses, and upload your program.
PS why run at 1Mhz. The internal oscillator runs at 8Mhz. By default the divide-by-8 fuse is set, so it runs at 1Mhz out of the factory, but you can unset this fuse.
PPS use this website http://www.engbedded.com/fusecalc/ to generate the right fuse settings for your project.

This would set up the factory fresh device to work as an Arduino, right? That is, I could put the newly programmed chip into an empty Uno, program it, then move it onto a custom PCB?

You can easily change the fuses using something like the sketch described in my answer - you just connect to the ICSP pins (MOSI/MISO/SCK/RESET).

Kind of, but you don’t want to do just that. You can program the 328 with your sketch directly, while it is in the breadboard. No need to take it out of the breadboard and put it into the UNO.

You can set the fuses to run on the internal oscillator easily enough. You can still run at 8 MHz which the IDE supports (choose Lilypad in the IDE) and then the delays, serial prints, etc. will still work properly.
As for programming a new chip, you can use an Arduino as ISP, an external ISP programmer (available cheaply from eBay), or see my page about uploading hex files which just needs a few hook-up cables, and a $15 SD card adapter like this:

You upload the sketch onto your Uno to make it into a programmer. Then you compile the code for your target chip and get the .hex file that the compiler produces.
Example setup:

The hex uploader sketch also lets you change fuses.
The AVR Fuse Calculator page will help you with getting the correct fuse settings.

This is perfect - I assume the Lilypad is pin-compatible with the Uno?

The Lilypad is just an Atmega328P clocked at 8 MHz, so that is fine for compiling from your point of view. It's the same processor, so in that sense, yes it's pin-compatible.

Even better is that I have an 8MHz ceramic resonator on hand, so even though the Lilypad schematic specifies an external clock source, I've got that covered without having to order extra components!

I usually use the internal oscillator which generates 8 MHz. No extra parts needed.

I've heard horror stories about fuse bits, so the further I stay away from those, the better. I also don't have to explain to my professor why my board has an empty slot as well...

Lots of commercial boards have empty slots. :) You can say it is for future expansions. As for the fuse bits, there are only a couple of disastrous changes you can make, and the code in my hex uploader program specifically disallows those. See here in the code.


text:
Using the TimedAction library
I need to make use of the TimedAction library for a project. The Arduino website gave an example of how to use this library which you can see here:
#include <TimedAction.h>

//this initializes a TimedAction class that will change the state of an LED every second.
TimedAction timedAction = TimedAction(1000,blink);

//pin / state variables
#define ledPin 13
boolean ledState = false;

void setup(){
pinMode(ledPin,OUTPUT);
digitalWrite(ledPin,ledState);
}

void loop(){
timedAction.check();
}

void blink(){
ledState ? ledState=false : ledState=true;
digitalWrite(ledPin,ledState);
}

This example however does not work, the Arduino ide gives back an error stating that the blink function is declared outside the scope. What is the correct way to implement this?

try moving the void blink() function code to before the timedAction declaration

Or try adding void blink(); right before TimedAction timedAction = TimedAction(1000,blink);

Ahhh, that's all it took to work! Thank you, I feel like such a fool for not thinking of that!

you can use ledState = not ledState; or ledState =  ! ledState;  instead of ledState ? ledState=false : ledState=true;   ....  the compiler prduces the same code for all three, i think

@Gerben care to convert your comment to an answer? Some additional information: The above code did compile in Arduino IDE 1.6.5-r5 and older but with the change to the arduino-builder tool in 1.6.6 the automatic function prototype generation inserts the blink prototype in the wrong place (https://github.com/arduino/arduino-builder/issues/50).

Regular C programs require putting the function declaration before the place you are using it. Arduino does this for you. Except in this case, where it doesn’t place it high enough. No need to feel bad. It’s Arduino that is trying to be clever, but fails.


text:
Can I make my own TFT LCD shield?
I have a few TFT LCD displays lying around which I salvaged from old phones. I would really like to use them with my Arduino. I didn't get anything about making a shield on the net but only links to eBay and Amazon. Please help.
It is a 36 pin tft for which adapters can be found.
But I don't know the wiring or the pins concerned.
Here is the supposed pin data sheet for my lcd for ur help

gre_gor , the image I provided shows the commonest of LCDs with 36 pins, for which adapters can be found. The question you refer above has a lcd with a custom adapter, and thus of very limited use in a Arduino.Thanks though.

Well I asked about the wiring and the concerned pins to which I can connect it. I don't know about that. And I couldn't get the wiring diagram of the tft shield that is in the market.

The adapter is irrelevant. The answer is the same.

Thanks , but I will wait for some others to answer. No hard feelings though gre_gor.

Unless you can get the datasheet for the TFT with the details of each pin on the connector you have zero chance.

Majenko, I am adding a pic to my question that shows the pin data sheet for a 3.5 inch tft lcd, and I think mine should be similar. Please help now.

Unless it is the exact same screen by the exact same manufacturer chances are it's different. There is no standard, and many screens the "same size" are completely different.

TFT shields are so cheap why waste your time trying to salvage something you have no data for? If you want to make your own (and I make my own systems with built-in TFT screens) buy a new TFT screen that you can get the datasheet for. I get mine from http://www.buydisplay.com


text:
Problem with motor driver shield
I have recently bought a L293D shield and 2 BO motors. Whenever I connect the motors to the shield it makes a beeping noise. I searched online and found that I need to change PWM frequency but I know nothing about it and anyone please tell me about the PWM frequency and how to change it.
I have used almost every sketch found online but condition remains same. I am using 9V battery as External power supply and it is absolutely new. Please help me.

Motor driving 101: 1) Do not use 9v batteries, they are for low current circuits not motors.  2) Do not use the antique and horribly lossy L293 or L298.

Then what should I use to drive motors from arduino @Chris Stratton

Probably an FET bridge.  Which one depends on the motor specs, for some small motors the TB6612FNG can be good.

Acting as a conduit for Google: Arduino Change PWM Frequency shows me:
https://playground.arduino.cc/Code/PwmFrequency
Which has the following example function:
/**
 * Divides a given PWM pin frequency by a divisor.
 *
 * The resulting frequency is equal to the base frequency divided by
 * the given divisor:
 *   - Base frequencies:
 *      o The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.
 *      o The base frequency for pins 5 and 6 is 62500 Hz.
 *   - Divisors:
 *      o The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64,
 *        256, and 1024.
 *      o The divisors available on pins 3 and 11 are: 1, 8, 32, 64,
 *        128, 256, and 1024.
 *
 * PWM frequencies are tied together in pairs of pins. If one in a
 * pair is changed, the other is also changed to match:
 *   - Pins 5 and 6 are paired on timer0
 *   - Pins 9 and 10 are paired on timer1
 *   - Pins 3 and 11 are paired on timer2
 *
 * Note that this function will have side effects on anything else
 * that uses timers:
 *   - Changes on pins 3, 5, 6, or 11 may cause the delay() and
 *     millis() functions to stop working. Other timing-related
 *     functions may also be affected.
 *   - Changes on pins 9 or 10 will cause the Servo library to function
 *     incorrectly.
 *
 * Thanks to macegr of the Arduino forums for his documentation of the
 * PWM frequency divisors. His post can be viewed at:
 *   http://forum.arduino.cc/index.php?topic=16612#msg121031
 */
void setPwmFrequency(int pin, int divisor) {
  byte mode;
  if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
    switch(divisor) {
      case 1: mode = 0x01; break;
      case 8: mode = 0x02; break;
      case 64: mode = 0x03; break;
      case 256: mode = 0x04; break;
      case 1024: mode = 0x05; break;
      default: return;
    }
    if(pin == 5 || pin == 6) {
      TCCR0B = TCCR0B & 0b11111000 | mode;
    } else {
      TCCR1B = TCCR1B & 0b11111000 | mode;
    }
  } else if(pin == 3 || pin == 11) {
    switch(divisor) {
      case 1: mode = 0x01; break;
      case 8: mode = 0x02; break;
      case 32: mode = 0x03; break;
      case 64: mode = 0x04; break;
      case 128: mode = 0x05; break;
      case 256: mode = 0x06; break;
      case 1024: mode = 0x07; break;
      default: return;
    }
    TCCR2B = TCCR2B & 0b11111000 | mode;
  }
}

And numerous results from this SE community also:
https://www.google.com/search?q=arduino+change+PWM+frequency+site:arduino.stackexchange.com
Which note methods for calculating/setting specific frequencies and pitfalls and side-effects of making such changes.


text:
Is there a way to disable modules like ADC without a sleep mode?
I'm working on a binary watch project. I want my circuit to live off of batteries for as long as possible, so I want to decrease the power consumption of my chip.
I'm using a barebones ATmega328P-PU with two 74HC595 shift registers. The ideal situation would be to keep the CPU, clock, flash, and I/O going so my program can continuously count the time on its own, but disable everything else that I'm not using, such as the ADC, BOD, TWI, timer1 and timer2, USART0, etc.
I took a look at the ATmega328P datasheet for the sleep modes, and it seems as though they all disable the CPU/Clock. Is this true? And if so, are there ways to disable the modules without enacting a sleep mode?

You do not want to keep the CPU running on a battery-powered project! You should use a timer for keeping the time, and let the CPU sleep. Ideally, you would connect a 32,768 Hz crystal to TOSC1/TOSC2 and have Timer 2 work in RTC mode. I have a clock running since June 2012 on the same pair of AA cells using this low-power technique.

You could use sleep_mode_idle. You can also try running at a slower speed. But that won't save a whole lot. I'd second the idea from Edgar, in using a 32kHz cystal to run timer2 in asynchronous mode, and put the MCU in SLEEP_MODE_PWR_SAVE.

Certainly there is.
  // disable ADC
  ADCSRA = 0;

You can disable lots of internal modules like this:
  power_all_disable();  // turn off all modules

See my page about power saving.

Majenko commented that turning off the ADC, while leaving the processor running was pointless. The real way to save battery power is to sleep, and it is possible to do that and still keep track of the time.
On my page about timers there is code to use a 32.768 kHz clock crystal to sleep and wake every second, which you could then use to alter the display on your watch.
Code from that page:
#include <avr/sleep.h>
#include <avr/power.h>

const byte tick = 3;

// interrupt on Timer 2 compare "A" completion - does nothing
EMPTY_INTERRUPT (TIMER2_COMPA_vect);

void setup()
 {
  pinMode (tick, OUTPUT);

  // clock input to timer 2 from XTAL1/XTAL2
  ASSR = bit (AS2);

  // set up timer 2 to count up to 32 * 1024  (32768)
  TCCR2A = bit (WGM21);                             // CTC
  TCCR2B = bit (CS20) | bit (CS21) | bit (CS22);    // Prescaler of 1024
  OCR2A =  31;              // count to 32 (zero-relative)

  // enable timer interrupts
  TIMSK2 |= bit (OCIE2A);

  // disable ADC
  ADCSRA = 0;

  // turn off everything we can
  power_adc_disable ();
  power_spi_disable();
  power_twi_disable();
  power_timer0_disable();
  power_timer1_disable();
  power_usart0_disable();

  // full power-down doesn't respond to Timer 2
  set_sleep_mode (SLEEP_MODE_PWR_SAVE);

  // get ready ...
  sleep_enable();

  }  // end of setup

void loop()
  {

  // turn off brown-out enable in software
  MCUCR = bit (BODS) | bit (BODSE);
  MCUCR = bit (BODS);

  // sleep, finally!
  sleep_cpu ();

  // we awoke! pulse the clock hand
  digitalWrite (tick, ! digitalRead (tick));

  }  // end of loop

Whilst asleep, the processor uses very little power. In the example sketch I measured 1.46 µA current consumption, when the output was LOW, if running from 5V power supply, and 1.1 µA if running from 3.3V power supply.

Example setup:

I have two decoupling capacitors (the blue ones). A pull-up resistor on Reset.
A 32.768 kHz crystal between pins 9 and 10. A 22 pF capacitor between each leg of the crystal and ground.
A current-limiting resistor and a LED. It works, and toggles at 1 Hz. When asleep (LED not on) it draws 1.46 µA as mentioned above.

Thank you for the quick response! I added these to the void setup() part of my code, recompiled/loaded and tested it, but there was no change in the power draw of my circuit. It's sticking around 0.39mA. Is this normal?

I only tried out the top suggestion (as well as power_adc_disable();), since I don't want to power off everything, as the bottom line of code suggests.

The ADC contributes about 0.00001% to the total power draw. The saving is swamped by the CPU consumption. Turning off just the ADC is pointless.

Have you tested that? According to my measurements turning off ADC results in almost 1/1000 times power consumption.

With that there the power consumption drops a large amount, down from 335 µA to 0.355 µA! (that is, 355 nA)

Of course, I'm assuming you take other reasonable steps, like not using a power LED, not using a USB chip, not using a voltage regulator, and going into sleep mode. But once you have done all that, the ADC uses quite a lot of power.

Comparing ADC on to ADC off when asleep, i.e., the CPU not running, yes the ADC uses "a lot". But compare that to when the CPU is running and that "massive" drop is swamped by the huge amount the CPU is using.  The OP specifically (if completely incorrectly) doesn't want to go to sleep. So switching off the ADC in that situation is pretty pointless.

Also, for a "binary watch" project I suspect that the MCU is only using a small fraction of the overall power, and the LEDs and shift registers (how big is this "watch"?!?!) will use considerably more than the MCU, and a billion times more than the ADC is using...

@Majenko: Regarding the power consumption of the LEDs. I remember a long time ago owning a digital watch with LED display. The display was active only while a specific button was held down. Inconvenient, but that's how you could get reasonable battery life despite the LEDs.

@EdgarBonet You were posh then ;) For about 2 years, when you became old-fashioned overnight :)

I've added code to show how you can keep track of the time with a 32.768 kHz crystal, and still have low power consumption.

Thank you, @NickGammon! Question, what purpose does making the crystal count to 32*1024 serve?

Well, since it oscillates at 32768 Hz, counting to 32768 will mean you get one interrupt per second.

@NickGammon I set up a mock circuit to test out your code, and the ATmega sticks at about 200uA. The only line I changed was digitalWrite(tick, HIGH) and I connected that pin to an LED. It seems like it's stuck in sleep mode though, because the LED never turns on. I have the 32.768kHz crystal connected to XTAL1/XTAL2. Is this result I'm getting correct?

I made up the test again to check it works OK. See amended answer. Yes, it works. You need a 22 pF capacitor between each leg of the crystal and ground. I got 1.46 µA of current draw at 5V input, and 1.13 µA if running from 3.3V.