text:
Getting Firmata to control WS2801 LEDs
I am trying to control a strip of WS2801 LEDs through an arduino uno running firmata from Python on my laptop.
I've written some basic code based on adafruit's library here (from line 187):
from pymata_aio.pymata3 import PyMata3
from pymata_aio.constants import Constants
import time

leds = [(255, 255, 0), (255, 255, 0), (0, 255, 255)]

uno = PyMata3()

uno.set_pin_mode(2, Constants.OUTPUT)  # signal
uno.set_pin_mode(3, Constants.OUTPUT)  # clock

def show(leds):
    for pixel in leds:
        for channel in pixel:
            i = 0b1
            for x in range(0,8):
                if i & channel:
                    uno.digital_write(2, 1)
                else:
                    uno.digital_write(2, 0)
                uno.digital_write(3, 1)
                uno.digital_write(3, 0)

                i = i << 1

    uno.digital_write(3, 0)
    time.sleep(0.001)

When I run the code it seems to run ok, but only the first LED will light up. I think (too quick to be certain) that it flashes through all the colours - ie displaying each colour rather than passing them through.
I'm wondering if there is something wrong with the timing for the clock pin making it latch, but I'm grasping here.

You cannot do precise timing of I/O mediated by USB like that. Regardless of the serial baud rate in use, the USB mode utilized basically puts a 1ms minimum interval between any two distinct communication operations.
Providing there are no intervening reads, if firmata is coded to deliver its data to the host's serial API in buffers matching or exceeding the USB packet size rather than individual writes for each command, it is possible that "keeping the pipe full" may mean that commands are able to be executed without such gaps, but any little interruption could introduce a problematic delay.
The key problem with delay is this part of the data sheet:

CLK pin keeps low more than 500uS will make the WS2801 internal status register reset, and at this moment, the gray scale data
  in the data shift registers will be latched.

Basically, that says that you need a clock low pulse of more than a half millisecond to start the process, but by extension it also means that all of the subsequent clock pulses have to be shorter than that or you will inadvertently reset the process, and this is not something you can easily achieve reliability of with a USB bus of the type utilized here mediating your software manipulation of the clock line.
Essentially, don't try to bit-bang things with Firmata.  You should send the desired intensity values across the USB as byte data, and then have software running on the Uno clock this data out in accordance with the WS2801 timing requirements.
Personally, I'd just write that as an ordinary sketch reading the Serial input - no need for firmata.  You can still feed the data from python on the host if you like, or anything else that can push data over a serial port.

Thanks, that's great.
I thought that would probably be the case, and I'd already thought I might have to make my own protocol for controlling the LEDs.
I'm very new to programming, so its great to have my instincts confirmed.

I'd offer you my protocol but it's designed to be used over raw USB rather than a serial connection.

Yes, raw USB can actually make things simpler as you can use the start of each packet as an alignment marker.  With a plain serial port, you have to come up with some sort of in-band (or long-timeout) synchronization method, reserved code with escapes, or just escape everything by encoding it in readable hex, and use newlines...

@IgnacioVazquez-Abrams , that would be really useful. I'm kinda fumbling my way through this (and really enjoying it when I'm not frustrated and angry at it). So any help would be fantastic.

@angusprune: I don't actually have the protocol formally documented anywhere, but here's the Python script that I use to control the device.USB_SET_LED_COUNT tells the device to allocate an internal buffer to hold the LED colors. USB_SET_LED_RGB takes an index and color and sets a buffer entry. USB_UPDATE_LEDS tells the device to transfer the colors from the buffer to the LEDs.

Hmm, I'm not sure I'd use individual control writes for that, but then when I looked at this it was for pumping constant data to the maximum number of LEDs the string protocol could support.  The bigger issue for angusprune will be that USB provides a built-in "this is a start of a new message" indication which serial lacks when carrying binary data.  Though if the update rate is slow, sending things in a textual format such as [LED]=[VALUE]\n could work.  Ironically if these are handed off to the serial API in large buffers they might be faster than USB control transfers.

It's possible that time.sleep is causing a latching issue. You should instead use pymata-aio's sleep function:
uno.sleep(0.001)

The documentation for it can be found here: http://htmlpreview.github.io/?https://github.com/MrYsLab/pymata-aio/blob/master/documentation/html/pymata_aio.html#module-pymata_aio.pymata3
You could also try a different pin and see if you still have the issue?

I think Chris' answer hits the nail on the head. I'll have a go at writing a protocol to transfer the data rather than bit banging directly.


text:
Arduino Nano USB Serial Bypass
I have a Nano clone here, that sporadically fails to get detected by my banana pi. This is annoying, because it works for days and hours, but fails to work randomly.
The Nano gets it's own power via VIN and thus should have enough power.
I thought of bypassing the FTDI and make a Serial connection via 2 Wires. Alternatively: Is there a way to force the arduino to use external Power over USB. I have the feeling, the the arduino wrongly decides, that USB is the better power source and uses it, causing the errors ( device not accepting address 21, error -62 )
P.S.: There is also a touch-screen connected to the banana pi via USB. Whatever port I use, It works and never failed. Just the Nano fails from time to time.

Many arduino type boards have a resistor between the USB-serial function and the main ATmega, potentially allowing an external "strong" driver to take over.  But the Banana pi may not (?) support 5v I/O.  Your best bet is probably to locate and remove that resistor, then build a level shifter with resistors.  For safety you could put one on both transmit and receive, since the the receive pin could potentially be misprogrammed as a 5v output.  As for the USB, is your "arduino" and especially its USB-serial chip real, or fake?

One could lower the 5V line from arduino to the banan pi with 2 resistors (voltage divider)/. That would be it.

Minimal recommended voltage for Vin is 7 Volt!

@ansi_lumen It's probably easier to just remove the 5v wire from the USB entirely, or remove the diode D1 from the board (the black two pin component on the bottom)

Is it truly an FT232 on it, or the el-cheapo Chinese CHwhatever it is?

@Gerben. Shure? Think there is no voltage regulator for Xto5V on the Nano. The chip takes 5V. I think 7V would kill it.

@Majenko Package looks okay. Flashed it with ftdi_eeprom and it still works.

@Gerben To remove the 5V line from the USB is also a good idea. But I think, I'll be faster with soldering a serial connection cable with voltage divider. This way I would get a free port for other stuff.

Assuming that USB-power was the actual problem here.

I can't comment so have to post this as an answer, but perhaps connect the GNDs together? But I also see that someone else mentioned the whole el-cheapo concept, too. I have noticed differences between boards sometimes, and exchanging them with one from a known supplier sometimes fixes my problems.

@ansi_lumen did you ever solve your problem. If so, could you post the answer here please?

To answer this question
The arduino in question was broken. Shortly after asking I was not even able to connect it to my PC successfully. I replaced it with a new one and everything runs smoothly now for months.
Since this unit survived a whole product development-process I am not surprised at all. In fact I had three and expected one to get killed in action.

source: Stack Exchange

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

sort: votes


text:
Weird OneWire bus problem
I have two DS18B20 temperature sensors connected via a OneWire bus to an arduino. I noticed that these sensors get hot, when permanently powered and decided to just turn them on for measurment.
First attempt: Define a pin as output and feed the sensors. Because I received only one value (first sensor on bus), I assumed that the current delivered may not be high enough and utilized a transistor (+resistor) as switch for the main 5V line to feed the sensors from the mains (as before). The result is the same. I only get the value of the first sensor. When I connect the sensors directly, I get both values.
I tried up to 4 seconds delay after switching the bus on and again after reading the values (before switching the bus off again), with no luck. Only the first sensor answers.
Do I have a timing or a current problem here?
UPDATE
Wiring (working): Two DS18B20 in parrallel with a 4,7k resisor between DATA and VIN. One Arduino pin used, Sensors directly powered by power-supply (same as arduino)
Wiring (not working): Broke the VIN line and added a transistor as switch between power-supply and sensors VIN. Used a second pin and a resistor to power up the line.
The transistor is a TC124E (npn) logic level transistor. I have the feeling, that this boy is not providing enough current to the sensors, which in addidtion have five meter cables attached...
UPDATE II
It is not the current. I replaced the transistor with a mosfet (70T03H) and the result is exactly the same: When switched, only one sensor answers . When I connect the gate directly to a +5V line, I get both values as expected.
Kinda think, that the switching of the pin irritates the bus or the specific device.
UPDATE III (Solution)
I tracked this down to a mixture of

Different resolution settings on the sensors
my code not waiting long enough to get the sensor with the higher resolution to setup (on-to-read time). Giving the bus slightly more time to setup before any reading is accepted, solved my problem.

Please add the wiring used.

Cable length won't lead to sensor heating but may cause sufficient distortion of signals to prevent recognition of all the devices.

@JRobert  I know :), but the cable "consumes" current and I beg this is my problem her. Going to heat the iron and report the outcome.

Or to be more accurate, the current in a long cable could cause a voltage drop (current in must == current out at any point on the bus). But yes, testing with a short bus is a good first step. Also see my (ASCII) schematic for a parasitic bus with strong pullup, in my answer below.

If you were trying to wire your bus in parasitic mode, here is what I am using:
OneWire Bus in parasitic mode:

+------------+     +5v            +---------+     +---------+
|    MCU     |      |             | DS18b20 |     | DS18b20 |
|            |  R_pu = 4.7K       | g  d +5 |     | g  d +5 |
| Strong-    |      |             +-o--o--o-+     +-o--o--o-+
| Pullup   > o------o               |  |  |         |  |  |
|            |      |               +--|--+         +--|--+
|            |      |               |  |            |  |
|    Data <> o------o---------------|--o------------|--o------ - - -
|            |                      |               |
+------------+                      V               V

I run at least three sensors this way on an approximately 6 meter bus, completely reliably.

Nice Work. Upvote for that, even If it is not my wiring.

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


text:
Understanding writing to input pins and pull up resistors
I am new to Arduino, and am trying to understand the following code.  The question is: Is my understanding correct, or if not, what is happening here?
I have to reverse engineer an existing undocumented project, based on Marlin firmware for 3D Printers.  The relevant lines from the source are:
#define DIO87_PIN               PINE2
#define DIO87_RPORT             PINE
#define DIO87_WPORT             PORTE
#define DIO87_DDR               DDRE
#define DIO87_PWM               NULL

#define MASK(PIN)  (1 << PIN)
#define _TOGGLE(IO)  do {DIO ##  IO ## _RPORT = MASK(DIO ## IO ## _PIN); } while (0)
#define TOGGLE(IO)  _TOGGLE(IO)

TOGGLE(87);

1) Reducing this code gives me:
DI087_RPORT = 1 << DI087_PIN
2) Which reduces further to:
PINE = 1 << PINE2
3) Which reduces further to:
PINE = 00000100
4) I understand this to mean that we are setting Pin 2 of the Inputs Register (of Port E) to "High". (and are setting the other 7 pins to low)
5) I understand this to mean, as we are writing to an "Input", that we are enabling the internal pull-up resistor on Port E Pin 2.
(EDIT: I have made a mistake here in point 5: to enable a pull-up resister, you write to a pins OUTPUT register, not it's INPUT register. (but you must write to it's output register when it is in "input mode")
Questions:

Is my understanding and work-through above correct?
If yes, does this also mean that we are also disabling the pull-up resistors to the other 7 Input Pins at the same time?

I am confused by the "TOGGLE" code given above - it seems that it is "destructive" in the sense that by "toggling" the input resistor on one pin, you also disable the resistors on all other pins?  Would it not make more sense to just toggle the one pin with a bitwise or.
e.g:
PINE = PINE | 1 << PINE2

Ah, now I understand a little more: IF DDRx is set so pin(x) is OUTPUT, then writing a 1 to a PINx will toggle the corresponding PORTx value. (i.e will indeed toggle the "output" of that pin)
However, IF any pins are set to INPUT in the DDR, (and have pull up-resistor enabled), then wouldn't this TOGGLE macro still inadvertently turn off those pullup resistors?

Maybe it's not completely obvious from the datasheet, but it can be seen in the figure of an I/O pin: writing a logic zero to PINxn has no effect whatsoever. Writing to a PINx register affects only those pins where you write a logic one.

Thanks. I understand that, when DDRx=1, that writing a logic zero to PINx has no effect.  Does the same hold true when DDRx=0? (input mode)?  If this also does nothing, then how does one turn off the pull-up resistor?

I believe I have a mistake in my reasoning, point (5). To enable a pull up resistor, one writes a 1 to PORTxn not PINxn.  And to disable a pull-up, one writes a 0 to PORTxn.

As noted in the I/O-Ports – Introduction section of the ATmega2560 datasheet,

... writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register.  In addition, the Pull-up Disable –  PUD bit in MCUCR disables the pull-up function for all pins in all ports when set.

Bits masked with a zero won't be affected.  You can toggle several bits at once if the byte written to the PINx register has several 1's in it.
Pullups are on for an input bit when the data bit is high and the PUD bit in  MCUCR is low.  So as suggested in your comment, pullups for toggled bits would toggle too, if PUD is low.
Regarding the macro code, your reduction looks right.  But note that use of _TOGGLE as an identifier in that code violates section 17.4.3.1.2 of the C++ Standard.  Names beginning with an underscore followed by an uppercase letter are reserved for use by language-implementation software.  They are off-limits for user code.  See What are the rules about using an underscore in a C++ identifier? for discussion.

The feature is well documented in the datasheetss.
Just be aware that it is not available on all across chips.
Atmega8 for example is a notable exception.

Now that I have improved my understanding, I provide a full answer here for completeness.

To enable (or disable) a pull up resister, you write a 1 (or 0) to
the PORTxn (data) register.
Writing a 1 to a PINxn (input)register, toggles (bitflips) whatever value is in the PORTxn data register.
Writing a 0 to PINxn does nothing, ever.
The structure of the Macro means it is hardcoded to only write to a PINxn register - it is impossible (with this code structure) to call "TOGGLE" on a PORTxn (Data) register.
Thus, this TOGGLE macro will never cause any issues, as writing zero's to PINx causes no action.

Specifically the answer is in the following two lines of code:
#define DIO87_RPORT             PINE
#define _TOGGLE(IO)  do {DIO ##  IO ## _RPORT = MASK(DIO ## IO ## _PIN); } while (0)

(TOGGLE is hardcoded to use "DIO_XX_RPORT" which is PINx)


text:
Pro Micro - Measuring voltage between two pins, without using GND
Quite new to this but making pretty good ground. I have an issue I'm not sure how to solve. I want to add a Pro Micro to an RC Toy, I can easily power it from the toys GND and 5V power. But then I want to use the voltage going to an LED on the toy (uses a different ground) to trigger an event within the Pro Micro.
I can power the Pro Micro from USB and and accomplish what I need with AnalogRead(). But if I connect the GND from the toys main power input to the GND from the LED it no longer acts as it should. I'm thinking these GNDs are not common, or are a separate circuit.
What I'm wanting to know is.. I'm using PIN10 on the ProMicro for the AnalogRead(), can I make it so that maybe PIN11 is the GND for that reading?
Thanks.

No, you cannot - the ATmega's ADC is referenced to its ground, and there are also some strict limits on providing inputs more than a little bit outside of the range between its power and ground.
You may be able to read two analog inputs and subtract them for a sort of "software differential" analog input, but the signal on an LED is unlikely to be meaningfully "analog" anyway - it might be pulsed with a duty cycle, but it will probably not have a steady reduced voltage.
It's actually quite likely that the anode of the LED is connected to the toy's positive supply, and it is the negative path to the cathode which is being switched - this is the most traditional way of doing things, because historically semiconductor switches suitable for "low side switching" have had better performance than those suited for "high side switching".  There will probably be a resistor on one side or the other of the LED.
With care and verification of suitable voltage ranges, you may be able to read the voltage on the LED cathode as a digital signal and invert it in software.


text:
How can I create a battery level circuit
Im trying to create a circuit so that I can monitor the voltage drop on my battery and send an message when the voltage drop reaches the drop out. But I'm having some problems with my voltage divisions.
I created this circuit to enable a flow so that it does not flow (drain the battery) while not necessary. But as I understand it analog input must not be above 1 volts.

The +3.3V represent the MCU (ESP-12, arduino with wifi) turning the circuit on, letting battery flow to the analog input (red circled ground). However, at analog input, the volt is 2,24V, which is more than the 1V it should be. Do I just divide it again? If I divide it again ill be at 1,12 so I need to divide it yet again. I don't think Im doing it right.
The maximum voltage of the analog pin on the ESP-12 is 1V. How can I get there?

Can you not just use ADC_MODE(ADC_VCC) and ESP.getVcc()? (Source) This eliminates all additional hardware, and doesn't sink any extra current.

Firstly, if I understand your schematic right, you're not "dividing" anything there. If the ringed red symbol is where you are connecting the ADC then either you will see near 4V on there (if it's only connected to the ADC), or 0V (if it's connected to ground).
You should be connecting the ADC between the resistors to get a reading.
Secondly, you should be using a P-channel MOSFET, not a PNP transistor. You can use a PNP transistor, but you will have to subtract the voltage drop imposed by the transistor from your calculations to get any meaningful reading. With a P-channel MOSFET, the on-resistance would be (or should be if you choose a sensible one) negligible compared to the resistance of the voltage divider.
You are right that you can't exceed 1V on the ADC, so you will have to size your resistors accordingly. You aren't restricted to just using a pair of 10K resistors - you can choose any values you like that yield the correct result.

simulate this circuit – Schematic created using CircuitLab
In this example, 10K and 2.2K give you no more than 0.9V from a 5V input. (Tip: choose an input voltage slightly higher than you expect to give a small safety margin).
I calculated those by:

Use the voltage divider formula R2 = R1×(1/((VIN/VOUT)-1)) to calculate the lower resistor (2500Ω).
Choose the next lowest "common" resitor (2200Ω)
Re-calculate the new output using the chosen resistor values using VOUT = (R2/(R1+R2))×VIN (0.9V)

For something like lithium, I'd suggest doing some sort of basic calibration after building the circuit, as the discharge curve for lithium (and maybe a few others) is relatively flat, and a small change in voltage could mean a large change in state of charge. This could be as simple as taking a multimeter to get a better resistance ratio ( < ±1% for even a cheap meter vs. ±5-10% for the stated resistor values). If you wanna go all out, you could go so far as to find a few different stable voltage references and build a mapping function of adc output to actual voltage.

For lithium using a proper fuel gauge chip would be a better option.

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


text:
74HC595N shift register with separate power supply
I have wired up a 74HC595N with an Uno, and the standard 8 LEDs and resistors, per the usual youtube "shift register tutorial" and written a sketch that works.  For example, I wrote a routine to walk from values 0 through 255 and light up the LEDs as a hex number.  So my wiring and code are correct.
As an experiment, I tried disconnecting the pin on my breadboard's power rail that goes to the Arduino 5V, and the pin that goes to Arduino ground, and instead plugged in a breakout (if that's the right word) that plugs into the breadboard and provides 5V on the power rail when a 9V battery is plugged into it.  (It's been checked with a multimeter, it's just under 5V.)  The only pins still going to the Arduino are for DS, SHCP and STCP.
Things sort of work, but not really.  It seems clear to me that the shift register keeps getting reset. (All of the LEDs briefly light back up in each iteration as I'm running my hex number display routine.) All of the other wiring remains the same; specifically OE-bar is still connected to ground on the power rail.  But it still seems to reset.
Can someone explain why the shift register keeps resetting?  Also, am I doing anything that might burn up the Arduino and/or shift register?

All ground connections except those which are explicitly isolated must be connected together in order to provide a common voltage reference for the circuit. Any breaks in the ground connection can result in gross misbehavior such as what you are experiencing.

Thanks.  Can you elaborate on what "explicitly isolated" means, or is that too broad of a question?

Also.  Let's say that I wanted to chain shift registers together, to the point that they needed too much current for the Arduino to handle.  Does that mean that this is just a brick-wall limitation of the Arduino?

Optocouplers and the like. No, just provide a more powerful external 5V supply for both the Arduino and the shift registers.


text:
Thermometer project shows fluctuation due to varying sensor value and voltage
I built this thermometer that reads the sensor value from the temperature sensor and displays it on the LCD display. It basically works fine, but the displayed temperature shows a fluctuation between +/-2 degrees due to varying sensor value and voltage every second.
(This is my very first Arduino project and I am pretty new to electronics.)
The Arduino gets the power via my Mac through USB.
When I check the sensor value and voltage, it slightly differs each second (or whatever delay interval I use in my code). Sensor value is between 123-125 and voltage usually 0.7, but also changes slightly, which causes the temperature calculation to vary around 2 degrees, which for a "thermometer" is quite a lot.
Is there any way to stabilize it? Should I use a capacitor or another resistor?

Code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const float powerSupply = 5.0;
const int sensorPin = A0;
const float baselineTemp = 23;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.print("Temperature:");
}

void loop() {
  int sensorVal = analogRead(sensorPin);
  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal/1024.0)*powerSupply;
  Serial.print(", Volts: ");
  Serial.print(voltage);

  Serial.print(", degrees C: ");
  float temperature = (voltage - .5)*100;
  Serial.println(temperature);

  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(temperature);
  // lcd.print(String(sensorVal) + ", " + String(voltage) + ", " + String(temperature));
  delay(1000);
}

What you need to do is take an averaged reading, this is because the sensor is always fluctuating, noise on the 5V line or the signal line. There are possible hardware solutions.

Adding a capacitor between Vcc and Gnd near the sensor, 0.1µf
Adding a low-pass filter on the signal line of the LM35 to Arduino
heatsink on the LM35(they are very sensitive to movement, giving odd readings)

The capacitor on the Vcc and Gnd will lessen the effects of voltage spikes from the rest of the Arduino's circuitry.
The low-pass filter will help give a more filtered output from the sensor with a better response over time.
                2.2k
LM35>---------/\/\/\-0------<Arduino
                     |
                     |
                     |
                    === 1µF
                     |
                     |
                    GND

The heatsink will allow the LM35 to get a better reading of the general temperature and not the temperature of the breeze from a window.
All three of the above solutions will probably give the best results.
What you could do in software too is to have an averaging algorithm/function in your code and actually take the averaged reading across the whole second that you delay the MCU.
An example of this would be:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const float powerSupply = 5.0;
const int sensorPin = A0;
const float baselineTemp = 23;
int sensorVal = 0;

//these are NEW
unsigned long lastTime = 0;     // last time reading taken
unsigned long currTime = 0;     //current time variable intialised
float AverageReading = 0;

float _readingAv = 0;   // static variable for keeping the averaged reading
int _readingsCount = 0;
int _readings = 100;     //the number of readings to take

void setup() {
  Serial.begin(9600);
  //  lcd.begin(16, 2);
  //  lcd.print("Temperature:");
}

void loop() {
  currTime = millis();

  if ((currTime - lastTime) < 1000) {  //checks to see if a second has passed
    sensorVal = analogRead(sensorPin);

    if (_readingsCount < _readings) {
      _readingAv += sensorVal; //add the current value to the last
      _readingsCount++;
    }
    else {
      AverageReading = _readingAv / _readings; //get the average
    }
  }
  else {
    Serial.print("Sensor Value: ");
    Serial.print(sensorVal);

    float voltage = (AverageReading / 1024.0) * powerSupply;
    Serial.print(", Volts: ");
    Serial.print(voltage);

    Serial.print(", degrees C: ");
    float temperature = (voltage - .5) * 100;
    Serial.println(temperature);

    //~ reset the values used by the previous function
    _readingsCount = 0;
    lastTime = currTime;
    _readingAv = 0; //Important to set this back to 0 so not to get odd values

    // set the cursor to column 0, line 1
    // (note: line 1 is the second row, since counting begins with 0):
    lcd.setCursor(0, 1);
   // print the number of seconds since reset:
    lcd.print(temperature);
    // lcd.print(String(sensorVal) + ", " + String(voltage) + ", " + String(temperature));
  }

}

Probably a better version of making filtering code of the LM35.

There are a few things you might try to stabilize your readings.

Add a small ceramic capacitor, say 22pF between the analog signal from the temp sensor (green on your example) and ground;
Perform multiple reading from your analog, let's say 10, discard max. and min. values and calculate the average. Use this instead of a single reading;
User the "internal" voltage as reference. It's normally more stable than using the external 5V. Just bear in mind that you might need to use a voltage divider as the "interval" voltage reference max value is 1.1V (https://www.arduino.cc/en/Reference/AnalogReference);
Reduce the wire sizes and make sure all connections are OK.

Probably just by using technique number "2" listed above you'll get much more stable results and don't need any hardware, just a small looping. Also adding the capacitor would be quite simple.
Hope it helps. Cheers!


text:
Square wave generator generates a shorter pulse from time to time
I am  using an arduino Micro to generate 8 square waves on 8 pins. The idea is as follows: on pin 13 is the main square wave. It represents a certain BPM (beats per minute). The other 7 pins should give multiplications or divisions of that BPM.
It uses timer1 to trigger an interrupt at BPM/192 (this number is choosen to enable easy multiplications). It counts those interrupts and changes the states of the outputs when needed.
The codes seems to run fine for most divisions and most multiplications. However in certain cases like /2, there seem to be shorter pulses from time to time that throw the whole timing off.
Adding a short delay at the end of the loop seems to make the system more stable but still the short pulses appear from time to time.
Does anyone have an idea what the problem might be.

int counter[8] = {0,0,0,0,0,0,0,0}; //storing number of interrupts since last pulse
int trip[8] = {191,383,767,1535,3071,6143,12287,24575}; //number of interrupts needed for div/mult
int outputPin[8] = {13,12,11,10,9,8,7,6};

void setup() {

  for (int x = 0; x < 8; x++){

    pinMode(outputPin[x], OUTPUT);
    digitalWrite(outputPin[x], HIGH);

  }

  cli();
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  OCR1A =2602; // 16000000 / (x * 8) -1
  TCCR1B |= (1 << WGM12);
  TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);//prescaler of 8
  TIMSK1 |= (1 << OCIE1A);
  sei();

}

void pulse(){

  for (int count = 0; count < 8; count++){

    counter[count]++;

  }

}

ISR(TIMER1_COMPA_vect){

  pulse();
}

void loop() {

  for (int y = 0; y < 8; y++){

    if(counter[y] > trip[y]){

      digitalWrite(outputPin[y],!digitalRead(outputPin[y]));
      counter[y] = 0;

    }

  }

  delayMicroseconds(100);

}

There are two issues here:

There is a data race on counter[]: it can be modified in interrupt
context while it is being read (or even modified) by the main
program.

Clearing counter[y] will make you loose ticks if for some reason
(say some interrupt) you do it a little bit late. You should instead
decrement it by trip[channel].

Here is a safe way of managing the counters:
volatile int counter[8] = {...};  // don't forget `volatile`

// Return whether this channel has tripped, and update the count.
bool tripped(int channel) {
    noInterrupts();
    bool did_trip = counter[channel] >= trip[channel];
    if (did_trip) counter[channel] -= trip[channel];
    interrupts();
    return did_trip;
}

void loop() {
    for (int y = 0; y < 8; y++)
        if (tripped(y))
            digitalWrite(outputPin[y], !digitalRead(outputPin[y]));
}

Notice that the critical section (the section with interrupts disabled)
lives within the for loop, rather than around it. It is better to have
multiple small critical sections rather than one large one.
Edit 1: You don't need the delay. It makes the system “more stable”
because it reduces the likelihood that, on any given TIMER1_COMPA
interrupt, the main program is accessing the counters (as it will spend
most of its time delaying). Adding this delay is in a way treating the
symptoms rather than the root cause of the data race.
Edit 2: Answering a comment. If you want the squares waves to stay
in sync, their frequency ratios should be integers. In your program,
this is almost, but not quite the case. For example, if you look at the
ratio between the first two channels:
channel 0: 191 interrupts per signal toggle
channel 1: 383 interrupts per signal toggle
ratio: 383 ÷ 191 ≈ 2.0052
The easy fix is to add 1 to every element of the trip array (384 ÷ 192
is exactly 2).

I tried your code. The pulses themselves seem to be stable now but now all square waves drift apart. None of the waves keeps in sync with the first one now.

@Janw: See amended answer.

Thank you that solved it!

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


text:
Control multiple LEDs with multiple buttons
Problem 1: LED1 needs to be on only when button1 is held down. Right now it takes several presses to turn on and off and stays on.
Problem 1: LEDs 2,3,4 do not turn off with buttons 2,3,4. They are all turned off by button1, which is what I want, but I also need them to turn of with their respective button presses.
I need buttons 2,3,4 to light up LEDs 2,3,4 and stay lit until I press the respective buttons again OR button1 which turns off all lights, and the LED for button1 must only stay on when button1 is held down.
I am half way there with just a few minor problems. The first is LED1 stays on rather than when I hold the button1 down only. And the other problem is, it takes many presses to turn the LEDs on or off. I fixed this on 2,3,4 by removing the following code for each pin:
if (digitalRead(buttonPin2) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
  { digitalWrite(ledPin2, LOW);       // turn ledPin2 on
    ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
  }

After I remove that code the LEDs light straight away and stay on until I press button 1 which is what I want. But I would also like LEDs 2,3,4 to turn off with their respective button press. With that code removed LEDs 2,3,4 no longer work independently of button1.
Full Code:
// set pins
const int buttonPin1 = 2;                 // Pin1's pushbutton
const int buttonPin2 = 4;                 // Pin2's pushbutton
const int buttonPin3 = 6;                 // Pin3's pushbutton
const int buttonPin4 = 8;                 // Pin4's pushbutton
const int ledPin1 = 3;                    // Pin1's LED
const int ledPin2 = 5;                    // Pin2's LED
const int ledPin3 = 7;                    // Pin3's LED
const int ledPin4 = 9;                    // Pin4's LED

// set variables
int ledPin1_status = 0;
int ledPin2_status = 0;
int ledPin3_status = 0;
int ledPin4_status = 0;

void setup() {  //initialize pins
  pinMode(buttonPin1, INPUT); // set PINn as INPUT
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);
  pinMode(buttonPin4, INPUT);
  pinMode(ledPin1, OUTPUT);   // set LEDn as OUTPUT
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
}

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

void loop() {
  if (digitalRead(buttonPin1) == HIGH) { // check if buttonPin1 was pressed (be sure to use a resistor?)
    if (ledPin1_status == 0) {           // check if ledPin1 was not already pressed
      digitalWrite(ledPin1, HIGH);       // turn ledPin1 on
      ledPin1_status = 1;                // 1 = on, set ledPin1_status to 1
    }
    else {
      digitalWrite(ledPin1, LOW);        // turn ledPin1 off
      ledPin1_status = 0;                // 0 = off, set Pin1_status to 0
      digitalWrite(ledPin2, LOW);        // turn ledPin2 off
      ledPin2_status = 0;                // 0 = off, set Pin2_status to 0
      digitalWrite(ledPin3, LOW);        // turn ledPin3 off
      ledPin3_status = 0;                // 0 = off, set Pin2_status to 0
      digitalWrite(ledPin4, LOW);        // turn ledPin4 off
      ledPin3_status = 0;                // 0 = off, set Pin2_status to 0
    }
  }

  if (digitalRead(buttonPin2) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
    { digitalWrite(ledPin2, HIGH);       // turn ledPin2 on
      ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
    }
  }

  if (digitalRead(buttonPin2) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
    { digitalWrite(ledPin2, LOW);       // turn ledPin2 on
      ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
    }
  }

  if (digitalRead(buttonPin3) == HIGH) { // check if buttonPin3 was pressed (be sure to use a resistor?)
    { digitalWrite(ledPin3, HIGH);       // turn ledPin3 on
      ledPin3_status = 1;                // 1 = on, set ledPin3_status to 1
    }
  }

  if (digitalRead(buttonPin3) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
    { digitalWrite(ledPin3, LOW);       // turn ledPin3 on
      ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
    }
  }

  if (digitalRead(buttonPin4) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
    { digitalWrite(ledPin4, HIGH);       // turn ledPin4 on
      ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
    }
  }

  if (digitalRead(buttonPin4) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
    { digitalWrite(ledPin4, LOW);       // turn ledPin4 on
      ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
    }
  }

names like buttonPin1, ledPin1 and ledPin1_status clutter up the code listing .... just use names like  button1, led1 and led1_status

First thing, you need to debounce your buttons. The fact that you
declared the (unused) variable debounceDelay suggests you have though
about debouncing, but you did not implement it.
Next thing, you should look for button press and release events.
That's when the button pin changes state from LOW to HIGH or vice
versa. It is not enough to check whether the pin is HIGH or LOW, you
have to check for the changes in state. This is usually called edge
detection.
With enough effort, you could probably do that yourself. However, to
make your life easier, you can use a debouncing library that does edge
detection, such as the quite popular Bounce2. This library provides,
for each button it debounces, a rose() method that tells you when the
input signal rose (i.e. transitioned from LOW to HIGH) and a
fell() method that tells you when it fell (transitioned HIGH
→ LOW). Using these methods, your problem can be coded in a fair
natural way. For example (not tested):
#include <Bounce2.h>

const int     BUTTON_COUNT = 4;
const int16_t DEBOUNCE_DELAY = 50;
const uint8_t buttonPins[BUTTON_COUNT] = {2, 4, 6, 8};
const uint8_t ledPins[BUTTON_COUNT] = {3, 5, 7, 9};

Bounce buttons[BUTTON_COUNT];
uint8_t ledStates[BUTTON_COUNT];

void setup() {
    for (int i = 0; i < BUTTON_COUNT; i++) {
        buttons[i].attach(buttonPins[i], INPUT);
        buttons[i].interval(DEBOUNCE_DELAY);
        pinMode(ledPins[i], OUTPUT);
        ledStates[i] = LOW;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

void loop() {

    // Update the debouncers.
    for (int i = 0; i < BUTTON_COUNT; i++)
        buttons[i].update();

    // When the first button is pressed:
    if (buttons[0].rose()) {

        // Light up the first LED.
        digitalWrite(ledPins[0], HIGH);

        // and turn off all the others.
        for (int i = 1; i < BUTTON_COUNT; i++) {
            ledStates[i] = LOW;
            digitalWrite(ledPins[i], ledStates[i]);
        }
    }

    // When the first button is released:
    if (buttons[0].fell()) {

        // turn off the first LED.
        digitalWrite(ledPins[0], LOW);
    }

    // When any other button is pressed:
    for (int i = 1; i < BUTTON_COUNT; i++) if (buttons[i].rose()) {

        // Toggle its state.
        ledStates[i] = !ledStates[i];
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

Edit: In order for the first button to only turn off LEDs 1 and 2,
the lines
// and turn off all the others.
for (int i = 1; i < BUTTON_COUNT; i++) {
    ledStates[i] = LOW;
    digitalWrite(ledPins[i], ledStates[i]);
}

should be replaced by:
// and turn off LEDs 1 and 2.
for (int i = 1; i <= 2; i++) {
    ledStates[i] = LOW;
    digitalWrite(ledPins[i], ledStates[i]);
}

Wow Edgar, what a great sketch, so neat, hopefully I can learn a lot from it, thanks. What methods are there to make windows recognise it as a controller? Is it code or windows I have to play with, or both.

How would I go about selecting only certain buttons to turn off with button1? Say I wanted to have button 4 independent.

@TRUEBRIT: 1. Sorry, I know nothing about Windows programming, which is out of topic here anyway. 2. In the section right after the comment “and turn off all the others”, instead of looping through buttons 1 through 3 (they are numbered from zero), you only turn off button 1 and 2.

I can't see how to do that?

@TRUEBRIT: See amended answer.

Thanks again Edgar. If I were to add other inputs such as a Rotary encoder, would the debounce library affect that?

@TRUEBRIT: This is unrelated to the original question.


text:
Print with round towards zero instead of round to nearest
When printing with one decimal place, Arduino's Serial.println() rounds numbers like 123.89 to “123.9”. Is there any way to change the rounding mode? For some reasons I want the value to be rounded towards zero (i.e., truncated) to one decimal place, like 123.89 → “123.8”.
here is the code
void setup() {
Serial.begin(9600);

}

void loop()
{
float A = analogRead(A0);
A = (A/1023)*5.0;
Serial.print("A = ");
Serial.println(A,3);
float B = A*10;
Serial.print("A * 10 = ");
Serial.println(B,1);
delay(1000);
}

the output is
A = 2.473
A * 10 = 24.7
A = 2.488
A * 10 = 24.9
A = 2.517
A * 10 = 25.2
A = 2.527
A * 10 = 25.3
A = 2.507
A * 10 = 25.1

instead I want the output to be like this
A = 2.473
A * 10 = 24.7
A = 2.488
A * 10 = 24.8
A = 2.517
A * 10 = 25.1
A = 2.527
A * 10 = 25.2
A = 2.507
A * 10 = 25.0

is it possible ?

We can't tell you what you're doing wrong if we don't know what you're doing.

This is not the serial monitor.  It is the serial output statements in your sketch, or more likely the floating point format itself.  You might perhaps consider using a double instead of a float.  But it's also unclear that the value being printed is not already the most accurate decimal approximation of the value internally stored.   Without your code this is unanswerable.

I have written it I was monitoring some analog values and printing it on the serial monitor for example let the values be like 2.59 and when I was printing it upto one decimal place it was getting rounded to 2.6 for some reasons I need the value to be like 2.5

Analog values in Arduino (and just about all MCUs) are integers, so you have done something to turn them into floating point values and something else to print them.   You must show your code by editing it into the body of your question.  If you do not, the question will probably be closed and deleted from the site.  (Additionally, analog values are expected to show noise variation)

check it @ChrisStratton

@IgnacioVazquez-Abrams

So you want the output to be truncated instead of rounded? 2.59 as 2.5 instead of 2.6?

yes truncated @Craig

What you are describing is by no means a value that is "exact up to one decimal place"   Your major problem here is that you've failed to really articulate that you want a value that is intentionally inexact.  Do you have any actual justification for distorting your data like this???

Note that most decimal numbers are not exactly representable as floats. For example, if you type float x = 23.40;, the compiler rounds that number to the nearest representable float, which happens to have the exact value 23.3999996185302734375. If you truncate this to one decimal place, then 23.40 ends up being printed as “23.3”!

A cheap trick to round a number to one decimal place (in "chop-off mode") is to multiply it by 10, convert it to an integer, and divide by 10.0f again:
float myVal = 123.89f;
myVal = (long)(myVal * 10) / 10.0f;
// = ((long)1238.9) / 10.0f
// = 1238 / 10.0f
// = 123.8

You can then print this modified number to the serial monitor.
This method can also be generalized to other precisions. For 2 decimal places, we just have to multiply by 10^2 (100) and divide by 10^2. A macro would be:
#define TRUNCATE(val, numDecimalPlaces) \
    (float)(((long)((double)(val) * pow(10, (numDecimalPlaces) * 1.0f))) / (pow(10, (numDecimalPlaces)* 1.0f)))

Note: You don't have to actually dynamically compute pow(10, numDecimalPlaces), you can also create macros for each decimal precision from 1 to x and simply precompute that value (100, 1000, 10000, ..).
The same can also be achieved by using the standard library function trunc from math.h:
#define TRUNCATE_TO_ONE(val) \
    (trunc((val) * 10.0f) / 10.0f)

See http://www.cplusplus.com/reference/cmath/trunc/.
Here's a small sketch in which it is demonstrated:
#include <Arduino.h>

#define TRUNCATE(val, numDecimalPlaces) \
    (float)(((long)((double)(val) * pow(10, (numDecimalPlaces) * 1.0f))) / (pow(10, (numDecimalPlaces)* 1.0f)))

#define TRUNCATE_TO_ONE(val) \
    (trunc((val) * 10.0f) / 10.0f)

void printValueFormatted(float value, int numDecimalPlaces) {
    //format correctly
    char buf[20];
    char* res = dtostrf(value, sizeof(buf)-1, numDecimalPlaces, buf);

    //skip over empty chars
    while(*res == ' ')
        res++;

    //print buffer
    Serial.println(res);
}

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

void loop(void)
{
    float myVal = 123.8978f;
    printValueFormatted(myVal, 4);
    printValueFormatted(TRUNCATE(myVal, 1), 1);
    printValueFormatted(TRUNCATE(myVal, 2), 2);
    printValueFormatted(TRUNCATE(myVal, 3), 3);
    printValueFormatted(TRUNCATE(myVal, 1), 4);
    printValueFormatted(TRUNCATE(myVal, 2), 4);
    printValueFormatted(TRUNCATE(myVal, 3), 4);
    delay(1000);
}

Prints
123.8978
123.8
123.89
123.897
123.8000
123.8900
123.8970

I am having some problems when I am using this piece of code.. I am using serial print to print some analog values from the A0 and A1 pin of an arduino uno and dividing the values from each other to get a ratio. Eg:  A = A0 and B = A1 after that C = A/B and printing values C * 100 on the serial monitor. Everything is working perfectly fine until I made the value of B very low. Applying this code giving me negative values of the ratio and without it it is giving perfect values which is rounded to the nearest. Is there anything else to overcome this problem?

@PeouseDutta int is a 2-byte integer with a range of about -32K to +32K. Might be too small for you if you suddenly multiply by 100. I updated the code to convert it to long instead.

Note that pow() is expensive if you don't have an FPU.

Then what do you suggest @Edgar Bonet?

I addressed this above. The pow is only needed to compute 10^x, just precompute it.

I did a small test and it turns out that a call to pow() with compile-time constant arguments gets optimized out by gcc into a constant. So you should be fine with pow(). Check the generated assembly if in doubt.

Use the given [function] for your problem. This function works on a pre-defined [algorithm].
int roundTowardZero(float number, int decimal_place) {
    float round_number = round(number);
    if(round_number > number) round_number = round_number - 1;
    float deci = (number - round_number) * pow(10, decimal_place);
    float round_decimal = round(deci);
    if(round_decimal > deci) round_decimal = round_decimal - 1;
    round_decimal = round_decimal / pow(10, decimal_place);
    total_number = round_number + round_decimal;
    return total_number;
}

Place this function above int setup()
like:
int roundTowardZero( ... ) {
    ...
}
void setup() {
    ...
}
void loop() {
    ...
}

Function syntex is like this : roundTowardZero([Enter a Decimal Value], [Enter Round Place Value])
Example :roundTowardZero(123.89, 1) //Output : 123.8
Please comment below is you find any problem or face any error.


text:
Create a dead zone for joystick
I'm trying to create a dead zone so the joystick will turn the motor off completely when in the center position. It's much too sensitive and will start the motor if barely touched. How could I fix the code so the off position of the joystick is bigger? This is the original code.
#include <Servo.h> //Using servo library to control ESC

Servo esc; //Creating a servo class with name as esc

void setup()
{
  esc.attach(9); //Specify the esc signal pin,Here as D9
  esc.writeMicroseconds(1000); //initialize the signal to 1000
  Serial.begin(9600);
}

void loop()
{
  int val; //Creating a variable val
  val = analogRead(A0); //Read input from analog pin a0 and store in val
  val = map(val, 0, 1023, 1000, 2000); //mapping val to minimum and maximum(Change if needed)
  esc.writeMicroseconds(val); //using val as the signal to esc
}

Please post your code within the code tag for readability. As the compiler error tells you, it appears that your using a variable named 'adc_center' that is not declared. Are you familiar with C++?

When you edit the question, do not remove the tags (\``c++and````) timemage and I have put around the code. There are there for a reason.

Here's how to create the new mapped range with a dead zone. I used Servo.write() which specifies the position in degrees because I couldn't understand what microsecond timings you need, but it should be easy to change it back. I've also added some debug statements to print val as the joystick is moved.
#include <Servo.h>

// Constants for servo angles in degrees.
const int SERVO_MIN = 0;
const int SERVO_MID = 90;
const int SERVO_MAX = 180;

// Constants for raw ADC values of joystick positions.
const int ANALOGUE_MIN = 0;
const int ANALOGUE_MID = 512;
const int ANALOGUE_MAX = 1023;
const int ANALOGUE_THRESHOLD = 100;

Servo esc;

void setup()
{
  esc.attach(9);         // Specify the esc signal pin as D9.
  esc.write(SERVO_MID);  // Move servo to mid position in degrees.
  Serial.begin(115200);
  Serial.println();
  Serial.println("Servo Test");
}

void loop()
{
  static int old_val = -1;   // Initialise to invalid value.
  int val = analogRead(A0);  // Read input from analogue pin A0.

  // Process val if it has changed.
  if (val != old_val)
  {
    old_val = val;
    Serial.print(val);
    Serial.print(", ");

    // Create the dead zone as per Majenko's algorithm.
    val -= ANALOGUE_MID;
    int direction = val < 0 ? -1 : +1;
    val = abs(val);
    val -= ANALOGUE_THRESHOLD;
    if (val < 0) val = 0;

    // Create a new mapped range with a dead zone.
    val *= direction;
    val += ANALOGUE_MID;
    Serial.print(val);
    Serial.print(", ");
    val = map(val, ANALOGUE_MIN + ANALOGUE_THRESHOLD, ANALOGUE_MAX - ANALOGUE_THRESHOLD, SERVO_MIN, SERVO_MAX);
    Serial.println(val);

    // Move servo to new angle in degrees.
    esc.write(val);
  }
}

Note that in your case, the width of the input range (1023) is only very
slightly larger than the width of the output range (1000). You could
take this width difference (23) as the dead zone, and this would
simplify the arithmetics: now the linear parts of your map have a slope
of exactly 1, and you do not need multiplications or divisions.
The map is then:

[0,  500] → [1000, 1500] (slope =1)
[500, 523] →  1500 (slope = 0)
[523, 1023] → [1500, 2000] (slope = 1)

In code:
/*
 * Map:
 *   [  0,  500] -> [1000, 1500]
 *   [500,  523] ->  1500
 *   [523, 1023] -> [1500, 2000]
 */
if (val < 500)
    val = 1000 + val;
else if (val < 523)
    val = 1500;
else
    val = (1500 - 523) + val;

My method is to separate the direction from the magnitude:

Subtract the "center" value to create a ± range
Use the sign to indicate the direction
Take the abs to give the magnitude
Subtract the "threshold" value
If negative set to zero

So, with example values:
int val = analogRead(0);          // Raw value
val -= 512;                       // Subtract center value (512)
int direction = val < 0 ? -1 : 1; // Direction is either -1 or +1
val = abs(val);                   // Remove the sign
val -= 10;                        // Subtract the threshold (10)
if (val < 0) val = 0;             // Anything below zero is now zero
// val is now 0-501 with a dead zone, and direction is -1 or +1.

Thank you for responding, I tried your modification, now I get an error: 'val' does not name a type.

Then you must have implemented it wrong. That code snippet compiles perfectly fine when wrapped in a function.

I'm sure I did implement it wrong. Could you show me how to wrap it in a function? I am not a coder.

I got it to compile but now the motor doesn't do anything. Could  someone help me with this please?

@edrummer You'll have to edit your question and add an update to it with your new code so that we can see what you have done wrong.

I put the original code up with no modifications. If the snippet will add a dead zone. please tell me where to put it and anything else I need to know to make it work.

Possible typo? int val = analogRead(0); Should that be A0 instead of 0?

@tim The two are one and the same.

How so? int analogPin = A0; Serial.println(analogPin); prints out 14. What am I missing?

@tim You're missing this: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring_analog.c#L53


text:
keypad storing problem any idea store more than 11 numbers like phone number
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>

SoftwareSerial mySerial(6,5);
int table[]={0,0,0};

#include <Keypad.h>
#include <Wire.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

char keys[ROWS][COLS] = {
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'*','0','#'}
};
byte rowPins[ROWS] = {2, 3, 17, 16}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {15, 14, 13}; //connect to the column pinouts of the keypad
int count=0;
Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
char entryStr[13];   // This can hold up to 4 digits
int i=0;
***char n1, n2 , n3;
char buf [15] ;// i put here***

void setup()
{
    Wire.begin();
    mySerial.begin(9600);
    Serial.begin(9600);
    lcd.begin(20, 4);
    ask();
}

void loop()
{
    Wire.requestFrom(2, 3);    // request 6 bytes from slave device #2
    for (int i = 0; i < 3; i++)
    {
        int c = Wire.read(); // receive a byte as character
        Serial.print(c);
        table[i] = c;
        Serial.print('\t');
        // print the character
    }
    Serial.print('\n');
    Serial.print(table[0]);
    Serial.print('\t');
    Serial.print(table[1]);
    Serial.print('\t');
    Serial.print(table[2]);
    Serial.print('\n');

    //if(table[0]<=8)
    //{
    //Serial.print("Flame Detected!");
    //Serial.println("Level1");
}

void ask()
{
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no1.:");
    lcd.setCursor(0,1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    n1 = GetNumber(buf, sizeof (buf) - 1);

    Serial.print(n1);

    delay(1);

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no2.:");
    lcd.setCursor(0, 1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    n2 = GetNumber(buf, sizeof (buf) - 1);

    Serial.println(n2);
    delay(1);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Enter no3.:");
    lcd.setCursor(0,1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1,2);
    n3 = GetNumber(buf, sizeof (buf) - 1);

    Serial.println (n3);
    delay(1);
    Serial.println (n1);
    Serial.println (n2);
    Serial.println (n3);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("list of numbers ");
    lcd.setCursor(0, 1);
    lcd.print("will be shown press");
    lcd.setCursor(1, 2);
    lcd.print("reset if wrong");

    delay(7000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Numbers Stored:");
    lcd.setCursor(0, 1);
    lcd.print("no1.:0");
    lcd.print(n1);
    lcd.setCursor(1, 2);
    lcd.print("no2.:0");
    lcd.print(n2);
    lcd.setCursor(2, 3);
    lcd.print("no3.:0");
    lcd.print(n3);
}

void GetNumber(char * result, const int maxLength)
{
    char key = kpd.getKey();
    int i = 0;   // how far through buffer we are
    while (key != '#')
    {
        switch (key)
        {
            case NO_KEY:
                break;

            case '0': case '1': case '2': case '3': case '4':
            case '5': case '6': case '7': case '8': case '9':
                lcd.print(key);
                if (i < maxLength)
                {
                    result [i++] = key;
                    result [i] = 0;  // terminating null
                }
                break;

            case '*':  // backspace
                if (i > 0)
                {
                    i--;
                    result [i] = 0;  // terminating null
                }
                break;
        }

        key = kpd.getKey();
    }
} // end of GetNumber

I changed it..it gave me this error

Did you look at your question before posting it? It is a mess. Select the code part, and then hit Ctrl+K to indent it by four spaces so it looks like code.

In my answer the number is not returned, it is passed back in the argument (buf). Thus you should not try to save it in nl.

 long GetNumber()

A long type (on this platform) can go up to 2^31 (that is 2,147,483,648). Large 10-digit numbers (ie. starting with "9") will not fit.
You could work with a 10-character string (or longer) instead of a long.

Make GetNumber deal with strings, like this:
void GetNumber(char * result, const int maxLength)
{
  char key = kpd.getKey();
  int i = 0;   // how far through buffer we are
  while (key != '#')
  {
    switch (key)
    {
      case NO_KEY:
        break;

      case '0' ... '9':
        lcd.print(key);
        if (i < maxLength)
          {
          result [i++] = key;
          result [i] = 0;  // terminating null
          }
        break;

      case '*':  // backspace
        if (i > 0)
          {
          i--;
          result [i] = 0;  // terminating null
          }

        break;
    }

    key = kpd.getKey();
  }
} // end of GetNumber

Now, to call GetNumber supply a char buffer and the maximum length (allowing for the 0x00 needed to terminate a string), like this:
  char buf [15];
  GetNumber (buf, sizeof (buf) - 1);

How can I convert long to string it gives me error if I put String GetNumber() and String n1, n2, n3; thanks for help :)

You don't use long at all. See my amended answer.

Use a string or a char. They store their numbers a character per character and not a huge number. A long can hold a max of around 2 000 000 000.
For example, 123 declared as an lon would be litteraly, mathematicly 123 (as 100 + 20 + 3). On the other side, a char will consider it as 1,2,3. It can store higher digits number.

Can you give me idea how to do it in my code?Please elaborate thanks a lot


text:
LED Programme where it delays the amount written in the Serial Monitor
I have written a simple code to delay the blinking of LED 13, the delay time is set by us.I have incurred a problem when I enter a 2 digit value in the serial monitor.There is some problem with the ASCII. Is there a way to solve this problem without using Serial.parseInt().
void setup()
{
  Serial.begin(9600);
  Serial.println("Programming is starting");
  pinMode(13,OUTPUT);
}

void loop()
{
  if(Serial.available())
  {
    int val=Serial.read();
    int val1=val-'0';
    Serial.println(val1);
    digitalWrite(13,HIGH);
    delay(val1*1000);
    digitalWrite(13,LOW);
  }
}

Blink without delay.

I know this .But i want to use ascii for 2 digit.

It does not use serial monitor.


text:
Problem with coding
Recently I got this code from a friend which is unfortunately unavailable right now.
When button is pressed two halfbridges are supposed to change directions with increasing  frequency of direction change until button is pressed again and than that frequency remains same.
Potentiometar is there to regulate that incriese of frequency.
For some reason one output is always on other one gets one when I press the button.
This is mentioned double halfbridge board:
http://www.ebay.de/itm/272620735999?_trksid=p2060353.m2749.l2649&var=571741857121&ssPageName=STRK%3AMEBIDX%3AIT
It is working, I checked button and potentiometer too,
Here is the code:
#include "options.h"

float ratio = CHANGE_FREQUENCY_MAX_SEC / 1023.0;

void setup() {
  pinMode(PIN_PWM_COIL_1, OUTPUT);
  pinMode(PIN_PWM_COIL_2, OUTPUT);
  pinMode(PIN_DIR_MOTOR, OUTPUT);
  pinMode(PIN_START_STOP, INPUT_PULLUP);

  digitalWrite(PIN_DIR_MOTOR, HIGH);
  digitalWrite(PIN_PWM_COIL_1, HIGH);
  digitalWrite(PIN_PWM_COIL_2, LOW);
}

void loop() {
  float voltage = 0;
  long steps;
  long pwm_half_period;
  unsigned long change_freq_time = 0;
  unsigned long value_steps = 0;
  unsigned int stop_freq = 0;

  if (digitalRead(PIN_START_STOP)) {
    return;
  }

  steps = (FREQUENCY_STOP_HZ - FREQUENCY_START_HZ) / FREQUENCY_STEP_HZ;

  if (FREQUENCY_STOP_HZ < FREQUENCY_START_HZ ) {
     return;
  }

  // If max number is reached we do nothing error in seetings
  if (steps > FREQUENCY_MAX_CHANGES) {
    return;
  }

  value_steps =  analogRead(PIN_POTENTIONMETER_IN) * ratio + CHANGE_FREQUENCY_MIN_SEC;
  value_steps *= 1000000;

  pwm_half_period  = 500000 / FREQUENCY_START_HZ ;

  change_freq_time = 0;

  while(!digitalRead(PIN_START_STOP)) {

    digitalWrite(PIN_PWM_COIL_1, LOW);
    digitalWrite(PIN_PWM_COIL_2, HIGH);
    delayMicroseconds(pwm_half_period);

    digitalWrite(PIN_PWM_COIL_1, HIGH);
    digitalWrite(PIN_PWM_COIL_2, LOW);
    delayMicroseconds(pwm_half_period);

    change_freq_time++;

    if(value_steps == change_freq_time) {
      change_freq_time = 0;
      pwm_half_period += 500000 / FREQUENCY_STEP_HZ;
      stop_freq = 1000000 / FREQUENCY_STOP_HZ;

      if(FREQUENCY_STOP_HZ == (2 * pwm_half_period)) {
         break;
      }
    }
  }
}

and here is options.h
#ifndef __OPTIONS_H__
#define __OPTIONS_H__

#define PIN_PWM_COIL_1    5
#define PIN_PWM_COIL_2    6

#define PIN_DIR_MOTOR     4

#define PIN_START_STOP    7

#define PIN_POTENTIONMETER_IN A0

#define FREQUENCY_START_HZ    5
#define FREQUENCY_STOP_HZ     1000

#define FREQUENCY_STEP_HZ     10
#define FREQUENCY_MAX_CHANGES 120

#define CHANGE_FREQUENCY_MIN_SEC  1.0
#define CHANGE_FREQUENCY_MAX_SEC  30.0

#endif

and here is the circuit:

It makes little sense to drive both PWM pins but only one DIR pin. Could you post your schematic please?

There is not that much to a curcuit, Just poti and push button.
_PWM_COIL_1 is on 5
_PWM_COIL_2 is on 6
and DIR_motor 2 is on 4 (this one I do not get at all)


text:
Error: request for member 'RGB' in 'redLed' , which is of non-class type 'int'
My 10 year old received great gift from older brother (Crate Creations) and I am trying write the program and getting this error. It looks to me that I matched the required code word for word symbol for symbol but I just can't figure out what I did wrong:
void loop () {

  for (float x = 0; x < PI; x = x + 0.00001) {
    RGB[0] = power * abs(sin(x * (CommonMathVariable)));
    RGB[1] = power * abs(sin((x + PI/3) * (CommonMathVariable)));
    RGB[2] = power * abs(sin((x + (2 * PI) / 3) * (CommonMathVariable)));
    ambientLight = analogRead(ldrPin);
    if (ambientLight > 600) {

    analogWrite (redLed.RGB[0]);
    analogWrite (greenLed.RGB[1];
    analogWrite (blueLed.RGB[2];

  }

I get this error:
request for member 'RGB' in 'redLed' , which is of non-class type 'int'

Nick,  Thanks so much...that got me past the error i have been stressing over... the booklet just looks like a period and not a comma....you rock..here is the rest of the code...after i corrected the comma i am getting an error for 'pulseSpeed not declared'

for (int i = 0; i < 3; i++) {
if (RGB[i] < 1)  {
delay (20 * pulseSpeed);
}
else if (RGB[i] < 5)  {
delay (10 * pulseSpeed);
}
else if (RGB[i] < 10)  {
delay (2 * pulseSpeed);
}
else if (RGB[i] < 100)  {
delay  (1 * pulseSpeed);
}
else {}
}
delay (1);
}

I can't really make out that comment. This sounds like a different question. Can you make a new one please? On the face of it you haven't declared pulseSpeed, unless there is more code you haven't shown. A declaration looks like: type name, for example: int pulseSpeed;

Probably you didn't spot commas:
    analogWrite (redLed,   RGB[0]);
    analogWrite (greenLed, RGB[1]);
    analogWrite (blueLed,  RGB[2]);

The function analogWrite takes two arguments, separated by commas. You were missing some brackets as well.


text:
Arduino Uno - Raspberry PI - Float Sensors - Water pumps
I am experimenting with Aquaponics and since I am a software developer I found it "smart" to use arduino/raspberry in order to control the water flow and not simply use a water pump with mechanical means.
The advantage is that I am able to expand easier the system. The disadvantage is that I haven't yet met the reliability that I would lie to have.
I am a software engineer with basic knowledge in the hardware field. That is why I thought of starting with Raspberry.
Initially I made a setup with a single raspberry PI a few float sensors like this: https://www.hellasdigital.gr/electronics/sensors/humidity-sensor/tank-pool-water-level-liquid-sensor-float-switch/
and relay like this one: https://wiki.52pi.com/index.php/DockerPi_4_Channel_Relay_SKU:_EP-0099
I saw that sometimes the system was hanging with the relays open! This had the side effect to loose water. This is the most precious in aquaponics!
Thus I thought of creating a cluster. Thus I made a cluster of three Raspberrys. The two had the relays and only one PI had the sensors. In order to open the water pump both PIs should have given the green light. This worked better and when one of the PIs hanged then we lost no water.
But again I am thinking that it was not acceptable that the system was hanging so often (at least several times per week). Thus I thought maybe if I use an Arduino for this purpose then this would be better.
Thus this is what I did. I created a simple program (no cluster and a single Arduino). Unfortunately this had even worst results!!!
For the Arduino I used normal 5 Volt relays like this one: https://www.nettop.gr/index.php/hlektronika/relay/8-channel-5v-relay-module-with-light-coupling-5v.html and the same float sensors.
I do not believe that is software related the issue but it must be hardware.
The problem is that my knowledge in the hardware field is limited!
What should I do in order to prevent this? Do you think that is related with the water pumps and the relays ?
The same erroneous behavior happens at both the Raspberry and Arduino, I mean that the relay stays open and the water overflows. For Raspberry I can tell that the system stop to respond, I am sure about it. But for Arduino I cannot say for sure if the whole system was frozen or if input only for the float did not work.
I paste a link to the quick and dirty Arduino code as well for your reference.
The temperature were the systems were operating could be quite hot (30 ~ 48 degrees Celsius) for several hours.
Here is the code for the Arduino:
#define POT_1_FLOAT_SENSOR  2
#define POT_1_RELAY_1       11

#define PIPE_1_FLOAT_SENSOR  5
#define PIPE_1_RELAY_1       9

#define PIPE_2_FLOAT_SENSOR       3
#define PIPE_2_RELAY_2      10

#define PIPE_3_RELAY_3       12
#define PIPE_3_FLOAT_SENSOR       4

// pot 1
const unsigned long POT_1_MAX_WATERING_PERIOD = 120000;
const unsigned long POT_1_DRAIN_PERIOD = 70000;

unsigned long pot1StartMillis = 0;
unsigned long pot1DelayStartMillis = 0;

// Pipe 2
const unsigned long PIPE_2_MAX_WATERING_PERIOD = 300000;
const unsigned long PIPE_2_DRAIN_PERIOD = 300000;

unsigned long pipe2DelayStartMillis = 0;
unsigned long pipe2StartMillis = 0;

// Pipe 3
const unsigned long PIPE_3_MAX_WATERING_PERIOD = 760000;
const unsigned long PIPE_3_DRAIN_PERIOD = 300000;
unsigned long pipe3DelayStartMillis = 0;
unsigned long pipe3StartMillis = 0;

// Pipe 1
const unsigned long PIPE_1_MAX_WATERING_PERIOD = 180000;
const unsigned long PIPE_1_DRAIN_PERIOD = 300000;
unsigned long pipe1DelayStartMillis = 0;
unsigned long pipe1StartMillis = 0;

bool pot1RedFlag = false;
bool pot1SetStartTime = false;

bool pipe1RedFlag = false;
bool pipe1SetStartTime = false;

bool pipe2RedFlag = false;
bool pipe2SetStartTime = false;

bool pipe3RedFlag = false;
bool pipe3SetStartTime = false;

void setup()
{
  Serial.begin(9600);
  // initialize the pushbutton pin as an input:
  pinMode(POT_1_FLOAT_SENSOR, INPUT_PULLUP);
  pinMode(POT_1_RELAY_1, OUTPUT);
  digitalWrite(POT_1_RELAY_1, LOW);

  pinMode(PIPE_1_FLOAT_SENSOR, INPUT_PULLUP);
  pinMode(PIPE_1_RELAY_1, OUTPUT);
  digitalWrite(PIPE_1_RELAY_1, LOW);

  pinMode(PIPE_2_FLOAT_SENSOR, INPUT_PULLUP);
  pinMode(PIPE_2_RELAY_2, OUTPUT);
  digitalWrite(PIPE_2_RELAY_2, LOW);

  pinMode(PIPE_3_FLOAT_SENSOR, INPUT_PULLUP);
  pinMode(PIPE_3_RELAY_3, OUTPUT);
  digitalWrite(PIPE_3_RELAY_3, LOW);

  pot1StartMillis = millis();
  pipe1StartMillis = millis();
  pipe2StartMillis = millis();
  pipe3StartMillis = millis();
}

void loop()
{
  checkAbstractWateringTimer(pot1SetStartTime, pot1RedFlag, pot1DelayStartMillis,
                                POT_1_DRAIN_PERIOD, POT_1_MAX_WATERING_PERIOD,
                                pot1StartMillis, POT_1_FLOAT_SENSOR, POT_1_RELAY_1);

  checkAbstractWateringTimer(pipe1SetStartTime, pipe1RedFlag, pipe1DelayStartMillis,
                                PIPE_1_DRAIN_PERIOD, PIPE_1_MAX_WATERING_PERIOD,
                                pipe1StartMillis, PIPE_1_FLOAT_SENSOR, PIPE_1_RELAY_1);

  checkAbstractWateringTimer(pipe2SetStartTime, pipe2RedFlag, pipe2DelayStartMillis,
                                PIPE_2_DRAIN_PERIOD, PIPE_2_MAX_WATERING_PERIOD,
                                pipe2StartMillis, PIPE_2_FLOAT_SENSOR, PIPE_2_RELAY_2);

   checkAbstractWateringTimer(pipe3SetStartTime, pipe3RedFlag, pipe3DelayStartMillis,
                                PIPE_3_DRAIN_PERIOD, PIPE_3_MAX_WATERING_PERIOD,
                                pipe3StartMillis, PIPE_3_FLOAT_SENSOR, PIPE_3_RELAY_3);

  delay(200);
}

void checkAbstractWateringTimer(bool &abstractSetStartTime, bool &abstractRedFlag, unsigned long &abstractDelayStartMillis,
                                unsigned long abstractDrainPeriod, unsigned long abstractMaxWateringPeriod,
                                unsigned long &abstractStartMillis, int abstractFloatSensor, int abstractRelay) {
  if (!abstractSetStartTime || (abstractSetStartTime && millis() - abstractDelayStartMillis >= abstractDrainPeriod)) {

    if(digitalRead(abstractFloatSensor) == LOW && !abstractRedFlag) // Need one more condition in order to emulate the delay...
    {
      digitalWrite(abstractRelay, LOW);
      Serial.println("Pot 1 pump is open");

      // Set it only once at the beginning
      if (pot1SetStartTime) {
        abstractStartMillis = millis();
        abstractSetStartTime = false;
      }

      Serial.print("duration ");
      Serial.println(millis() - abstractStartMillis);

      if (millis() - abstractStartMillis >= abstractMaxWateringPeriod)  //test whether the MAX watering period has elapsed
      {
        // Close pump and do not oopen it again. Red Flag...
        Serial.println("Pot 1 pump is closed and the red flag is ON");
        digitalWrite(abstractRelay, HIGH);
        abstractRedFlag = true;
      }
    }
    else
    {
      Serial.println("Pot 1 Pump is closed");
      digitalWrite(abstractRelay, HIGH);
      abstractSetStartTime = true;
      abstractDelayStartMillis = millis();
    }
  }
}

Please any ideas, suggestions or tests that I could do are more than welcome in order to create a reliable system.
-- UPDATE --
Both when I was using Raspberry and Arduino I haven't included any resistors between the float sensor pins and the ground. Are there any chances that this is related with the instabilities that I experienced?
Maybe I should add a resistor (10K) between the float sensor pin and the ground?
Thank you

Re “for Arduino I cannot say for sure if the whole system was frozen”: make the built-in LED blink in loop(). If it stops blinking, it's frozen.

Thank you Edgar, good idea I will do.

Maybe I should add a resistor (10K) between the float sensor pin and the ground? -- No, you have (roughly) 30k internal pullup resistors. Adding a 10k pulldown resistor would just confuse everything. However adding 10k pullups to 5V would help with noise rejection.

if relays sap your psu into dropping in voltage, it can affect your sensors.

Majenko thank you about your comment. You mean that I should follow something like this: https://en.wikipedia.org/wiki/Pull-up_resistor and at the Vin I should place 5 Volts and at the Vout I should connect it to my digital input. Correct ? Sorry about confirmation but my hardware knowledge is limited.

Thank you Abel about your comment. I believe I understand what you say. I have a 12 V power supply and if I remember out of my head is rated a 1.5 Amps. My question is what should I do about it if your statement is true? Buy better power supply?

Majenko I read a bit more about the pull up resistors from this link as well: https://learn.sparkfun.com/tutorials/pull-up-resistors/all
I am connecting the float sensor like this: https://www.gadgetronicx.com/interfacing-float-sensor-arduino/
As you might have noticed in my code I use the INPUT_PULLUP. I understand that adding a 10K pullup resistor to 5V as you said will help with noise rejection while I should leave my code as it is. Correct ? I mean having the internal pull up resistor plus the external one would be fine.  Or should I adapt my code adequately as well?

Do you think it is advisable to use an external power supply for the 8-module relay ? Would this make any sense?

How long are the cable runs? Is there any electrically noisy equipment near the cable runs? Consider using some form of galvanic isolation to interface the float sensors to the MCU. The relays require 50 to 60 mA drive current but the Arduino pins can only supply 40 mA.

Hi Tim thank you for your useful input. This you suggest that I should connect the relay module to an external power supply (vin and ground I suppose will be coming from another power source). Now about the noise could be. I have a hell of a lot of cables there! The max distance for each float sensor is under five meters. I will investigate about the galvanic isolation. Thank you!!!

Tim if you have a link related to the "galvanic isolation" would be great!!!!

Hi Tim I used this link to power the relays from an external power supply correctly https://lastminuteengineers.com/two-channel-relay-module-arduino-tutorial/. Thank you

I think I will give a try with these two modifications first. External power supply and pull up resistors. Normally it should be fairly quick if this is going to work or not.

Hi guys I run the system approximately for ten hours now and it looks that this was it!!! Fingers crossed but up to now it works very well. I am really grateful for all your answers that greatly helped me. I introduced the pull up resistor and an external power supply tot the relay module. I also used the internal led as a visual heartbeat. Thank you all again once more!!!

I hope that it will not crash in the next hour or so.... :D but even if it does I know that we will be able to find the root cause in this thread!!!

Glad we could help. Texas Instruments has a great series of videos on the subject of galvanic isolation which discusses inductive, capacitive and optical isolation techniques. Something else to consider is debouncing the float sensor signal either in hardware with a low-pass RC filter or with a software debouncer. For stronger pull-ups you could try 1K resistors, though this will use more current.

Guys I would like to accept your answers (more than one as well). Is this possible? If not at least Tim's answer. You need to post an answer instead of a comment for me to accept it?

Up to now it looks ok. No overflow. The only thing that I noticed is that it stopped after several hours working. But this could be a different issue I suppose. Maybe an overflow or something else.

Hi again Tim/all unfortunately this morning we had a water overflow. It means that one specific sensor did not gave the correct signal to Arduino. I watched the galvanic isolation video from TI. That's great but I think that the relay module they already have opto couplers. Now I am considering to introduce a low pass RC filter as you said to each float sensor. Do you have any suggestions for the values of the Resistor and capacitor? The pull-up resistors are 10K. I will change them to 1K. Any other suggestions?

Does it make any difference if I use two arduinos? One to control the float sensors and one the relays? Afterwards these two will have to communicate.

Do you think that I will not have these issues that I experience now with this sensor ? https://www.hellasdigital.gr/electronics/sensors/humidity-sensor/gravity-photoelectric-water-liquid-level-sensor-for-arduino-sen0205/

You are right that the relay modules already have isolators, but you've overlooked that the sensors don't have any isolation. You need to isolate the signals in both directions - both the inputs and the outputs.

As requested, I've collated my comments into an answer.
How long are the cable runs? Is there any electrically noisy equipment near the cable runs? Consider using some form of galvanic isolation to interface the float sensors to the MCU. Texas Instruments has a great series of videos on the subject of galvanic isolation which discusses inductive, capacitive and optical isolation techniques. Isolate the signals in both directions – both the inputs and the outputs.
For stronger pull-ups you could try 1K resistors, though this will use more current.
Something else to consider is debouncing the float sensor signals either in hardware with a low-pass RC filter or with a software debouncer (which I've put on GitHub).
The relays require 50 to 60 mA drive current but the Arduino pins can only supply 40 mA, so the external power supply is a good idea.
Redundancy, i.e. having multiple sensors for the same measurement, will guard against the loss of a single sensor causing chaos in a critical system, e.g. loss of precious water in a hot climate. You could have 3 float sensors for each water level at different locations, then use a voting system of >= 2 to take action. The system should also flag when sensors disagree so that someone can investigate the issue. And also route the cables via 3 different paths. This physical separation will guard against a single localised event (e.g. a wayward tractor or lightning strike) damaging all the sensors at the same time.
Also consider the fail-safe mode. For example, this could be to switch off all water valves when sensors disagree and then send an alert to someone and/or sound an alarm.
As your aquaponic farm is outside, consider lightning strike protection such as using TVS diodes on all inputs and outputs.
You could add feedback sensors to the relays to verify whether they have actually responded to the commands from the Arduino to switch on or off, i.e. compare commanded value with FB sensor value. These sensors could be pullup/pulldown resistors.
These additional relay FB sensors and the float sensors could be incorporated into the fail-safe logic. Some examples include:

If a relay is on when it's supposed to be off, flag the discrepancy.
If it takes 5 minutes to fill a tank and the inlet relay has been on for >5 minutes, it might be overflowing or dodgy sensors.
If the float sensors say a tank is empty, but the inlet relay has been on for >5 mins, something is wrong, e.g. leaking tank or dodgy sensors.
If it takes 10 mins to drain a tank but the float sensors say it's still full after 11 mins, something is wrong, e.g. blocked drain or dodgy sensors.
Are inlet and outlet relays on at the same time? Is this a valid condition?

There are many permutations. Happy coding...

thank you for your valuable input. I can say that now the system is stabilized.
The source of my issues was a faulty sensor but I have taken into account all advices. For example I separated the signal cables from the power cables that this was one more source of issues, I have introduced the pull up resistors, I have used separate power source for the relay module.
Generally for me ALL the comments from this thread were super important.
Thank you!

Something else to consider is redundancy, i.e. having multiple sensors for the same measurement. This will guard against the loss of a single sensor causing chaos in a critical system, e.g. loss of precious water in a hot climate. You could have 3 float sensors at each location, then use a voting system of >= 2 to take action. The system should also flag when sensors disagree so that someone can investigate the issue.

I've assumed up till now that this is an indoor aquaponic farm. If it's outdoors, you should also consider hardening to lightning strikes, e.g. using TVS diodes on all inputs and outputs. And a slight correction to my previous comment: the 3 sensors per measurement should be at different locations, but at at the same water level. And also route the cables via 3 different paths. This physical separation will guard against a single localised event (e.g. a wayward tractor or lightning strike) damaging all the sensors at the same time.

Yes indeed it is outdoor on my house's roof. I will have a look at the diodes that you are talking about. Thank you again for the great hardware ideas that you give me. I appreciate them.


text:
Micro USB to USB adapter m/m
I'm looking into working with an Arduino micro, and I'd like to be able to plug it into my computer directly(without a cable). I've been looking around, and the best thing that I found was this. The reason I haven't bought the linked adapter is because I've seen a number of bad reviews of the seller with close to half of the reviews being 1-star. Anybody have an idea where I can find something similar?
EDIT: I'm going to be using this for security testing, emulating a rubber ducky usb, so I need the computer to recognize the Arduino as an HID, not an arduino, but I also (obviously) need to be able to load my code onto it

http://www.ebay.nl/itm/2Pcs-Micro-USB-Male-to-USB-Female-OTG-Adapter-Converter-For-Android-Tablet-Phone-/281886855395?hash=item41a1c410e3:g:-7IAAOSwwE5WXp6V . But it's the wrong one like Majenko said

Hack a usb male onto the board and plug it in.

http://www.ebay.nl/itm/USB-male-type-A-to-micro-USB-male-adapter-converter-for-cellphone-camera-mp3-4-/231488735028?hash=item35e5cdc734:g:Qk8AAOSwbqpTwPNc This is the smallest I could find at the moment.

@J. Doe, This isn't really the place for shopping recommendations. Questions on Arduino, code, usage, etc are fine. I also don't see how an adapter would be way better as a cable. And Gerben has a sufficient answer (in my opinion). So I'm voting to close this question since it's more about USB connectors as actually about Arduino.

That adapter is not suitable. Not only is it the wrong gender on the large end, but it is designed for a completely different purpose.
That is an "On The Go" adapter which is designed for connecting things with a USB A plug (such as a memory stick, etc) to a mobile phone's USB socket.  It is not suitable for connecting things to an Arduino.
I have never heard of an adapter like you want, but I have heard of Arduino-like boards that plug direct into a computer like you want. One example is the Digispark from Digistump which is an ATTiny85 on a USB plug.

I've updated my question to clarify what I'll be using it for to see if it makes a difference.


text:
MQ4 gas sensor is not working with Arduino UNO
I am trying to detect LPG leakage by using MQ4 gas sensor.
I have made this circuit

My Arduino code is
int sensorValue;

void setup()
{
  Serial.begin(9600);      // sets the serial port to 9600
}

void loop()
{
  sensorValue = analogRead(0);
  Serial.println(sensorValue, DEC);
  delay(100);
}

On my serial monitor, I am getting values like
307
277
289
282
283
283
260
248
265
285
308
278
278
315
321
316
327

These values are not getting change even after putting sensor near gas lighter. Did I made any mistake in circuit or this sensor could be faulty ? Any help is appriciated.

That is what I would expect to see with one of these sensors.
I'm not sure on the wiring, I think you may be wrong.  Have a read of http://playground.arduino.cc/Main/MQGasSensors#readdatasheet and see if you agree.
Did you leave the sensor to warm up?  It takes a few minutes (from memory) and until its warm it won't give you a proper reading.
An MQ4 should be able to detect Methane, butane and propane, so was your lighter using on of these gasses?  When it does detect the target gas, the number will go up, and stay up for a while.
Another thing you can try is blowing on the sensor, the results will vary depending on what you have been eating, but it should shift one way or another.
If it still doesn't work then buzz out your connections, just to triple check, and re-read the manual.

thanks for replying, I let it warms for 5mins or so. One thing I also noticed that when I touch the sensor, its value goes down to range 0-50. Blowing on it doesn't change its value. :(

If the value changes when you touch it I would check the earth connection.

I think my wiring was wrong, after re-doing everything its working fine. Its value getting changed when sensor is exposed to LPG gas. Thanks.

authors: นายสมพงค์ ทุ่งมีผล


text:
Rc switch library transmit using protocol 5
I'm trying to transmit using mode 5 with the rc switch library, but my reciever tells me that the data is using protocol 2. I'm using the RecieveDemo_simple example as a sniffer for 433 MHz and I'm recieving data with protocol 5 from a wireless electric plug that I want to replicate.
I am able to send the data, but it is using the wrong protocol most of the time.
Here's some output from the reciever:
Received 15766156 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 5
Received 15885740 / 24bit Protocol: 2
Received 15885740 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 5
Received 15885740 / 24bit Protocol: 2
Received 15885740 / 24bit Protocol: 2
Received 15885740 / 24bit Protocol: 5

The code:
/*
  Example for different sending methods

  https://github.com/sui77/rc-switch/

*/

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {

  Serial.begin(9600);

  // Transmitter is connected to Arduino Pin #10
  mySwitch.enableTransmit(10);

  // Optional set pulse length.
  // mySwitch.setPulseLength(320);

  // Optional set protocol (default is 1, will work for most outlets)
  mySwitch.setProtocol(5);

  // Optional set number of transmission repetitions.
  // mySwitch.setRepeatTransmit(15);

}

void loop() {

  /* Same switch as above, but using decimal code */
  mySwitch.send(15885740, 24);
  delay(1000);
  mySwitch.send(15766156, 24);
  delay(1000);

}

I would expect your sending protocol 5 just fine.
But because protocol 2 and 5 are very similar, your receiver gets confused about which protocol it sees when there's noise or other interference.
This is the definition of the two protocols from the code:
{ 650, {  1, 10 }, {  1,  2 }, {  2,  1 }, false },    // protocol 2
{ 500, {  6, 14 }, {  1,  2 }, {  2,  1 }, false },    // protocol 5

Note the last three parts are the same, which are the pulses for 0, 1, and whether or not the high/lows are inverted.
The first part is also very similar, which is the pulse length. It's so similar that the difference probably falls within the margin for error the receiver software uses.
Only the second parts differs a bit more, which is the sync bit, it's a short high pulse followed by a longer low pulse. It's easy to mistake the one for the other though when there's noise and such.


text:
GPS Transmits False Data with SD card in; True data with SD card out
I've programmed my Arduino Ethernet to receive data from a Skytraq Venus GPS receiver and separate it using TinyGPS, then store it on an SD card. With the SD card inserted, everything else except the time is totally wrong. Once I remove the SD card and reset, the longitude and latitude are still wrong but everything else is correct. I've tried supplying more power, replacing the receiver, antenna, the arduino itself, even switched the serial ports I use but I can't seem to find a solution.
Here's a link for the TinyGPS library and a link for the NewSoftSerial library. And for the schematics, I haven't drawn any yet but I'm using the Arduino Ethernet's SD port as my SD shield. My Skytraq GPS receiver's RX pin is connected to pin 2 on the arduino ethernet and the TX pin is connected to pin 3 on the ethernet. (Ethernet TX/RX has been set to pin 3 and 2 respectively.)
I'm using the Sparkfun Venus GPS with SMA connector from sparkfun.com. I would post the link but it says I need at least 10 reputation to post more than two links. Serial signals at 3.3V and GPS module is a 3.3V module. I use the same sketch with and without the SD Card. SD.begin is called just once and Serial.begin is also called once.
Here's my code:
#include <SoftwareSerial.h> //NewSoftwareSerial Library
#include <TinyGPS.h>        //TinyGPS Library
#include <SPI.h>            //This Library is used by the SD library.
                            //Must be defined before SD library to prevent errors.
#include <SD.h>             //SD Card Library

//NB: To avoid SD Card Errors, use an SD Card whose size is at most 2GB
//and use FAT16 format. Arduino has problems with FAT32 and cards>2GB.

#define RXPIN 2
#define TXPIN 3

const int chipSelect = 4; //This selects the SD card port for read/write

#define GPSBAUD 9600

File logs; //Used to write to SD card later

TinyGPS gps;

//Initialize the Software Serial to recognize
//our UART pins (Read(RX) and Write(TX))
SoftwareSerial read_gps(RXPIN, TXPIN);

void getdata(TinyGPS &gps);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);  //Start the serial port
  read_gps.begin(GPSBAUD);  //Start reading from the gps

  pinMode(chipSelect, OUTPUT); //Make pin 4 an output pin
  pinMode(10, OUTPUT);  //Pin 10 must always be set to output to avoid errors
  digitalWrite(10, HIGH); //Pin 10 must always be high to prevent errors.

  Serial.println("");
  Serial.println("Awaiting Lock");
  Serial.println("");

  //Initialize the SD Card
  SD.begin();
  Serial.println("Initializing SD Card. Please Wait.");
  if(!SD.begin(4)){//If card not available or card not recognized
    Serial.println("Failed.");
    return;
  }
  Serial.println("Card Initialized");

}

//the loop function is used to read the data from the gps,
//check for valid data and then separate the data based on our specs.
void loop() {
  // put your main code here, to run repeatedly:
  while(read_gps.available()){//as data is received from the gps
    int c = read_gps.read();
    if(gps.encode(c)){//check if new valid data available
      getgps(gps); //read the valid gps data and process
    }
  }

}

void getgps(TinyGPS &gps)
{
  float latitude, longitude;

  gps.f_get_position(&latitude, &longitude); //Feature of tinygps.
                                             //Gets the latitude and longitude

  Serial.print("Latitude: "); Serial.print(latitude);
  Serial.print("\nLongitude: "); Serial.print(longitude);

  int yr;
  byte mnth, dy, hr, minu, sec, hundredths;
  gps.crack_datetime(&yr, &mnth, &dy, &hr, &minu, &sec, &hundredths); //Gets the date and time and separates them
                                                                      //into individual components.

  Serial.print("\nDate: "); Serial.print(mnth, DEC); Serial.print("/");
  Serial.print(dy, DEC); Serial.print("/"); Serial.print(yr);
  Serial.print("   \nTime: "); Serial.print(hr, DEC); Serial.print(":");
  Serial.print(minu, DEC); Serial.print(":"); Serial.print(sec, DEC);
  Serial.print("."); Serial.println(hundredths, DEC);

  Serial.print("Altitude(metres): "); Serial.println(gps.f_altitude());

  Serial.print("Speed(kmph): "); Serial.println(gps.f_speed_kmph());
  Serial.println();

  logs = SD.open("datalogs.csv", FILE_WRITE);  //open the datalog file on the sd card. If it doesn't exist on the card, create it.

  if(logs){//Start writing data to SD Card
    Serial.print("Writing to datalogs...");
    logs.println("\nLatitude: "); logs.print(latitude);
    logs.print("\nLongitude: "); logs.print(longitude);
    logs.print("\nDate: "); logs.print(mnth, DEC); logs.print("/");
    logs.print(dy, DEC); logs.print("/"); logs.print(yr);
    logs.print("   \nTime: "); logs.print(hr, DEC); logs.print(":");
    logs.print(minu, DEC); logs.print(":"); logs.print(sec, DEC);
    logs.print("."); logs.println(hundredths, DEC);
    logs.print("Altitude(metres): "); logs.println(gps.f_altitude());

    logs.print("Speed(kmph): "); logs.println(gps.f_speed_kmph());
    logs.print("\n");
    logs.println();

    logs.close(); //close the file
    Serial.println("done.");
    Serial.println("\n");
  }
  else{
    Serial.println("Error opening file.");
  }

  unsigned long chars;
  unsigned short sentences, failed_checksum;
  gps.stats(&chars, &sentences, &failed_checksum);
}

Please provide schematics and the configuration/setup of your sketch. Also include links to libraries that you are using --- and I bet you will soon have helping hands.

link for the TinyGPS library
link for the NewSoftSerial library.
And for the schematics, I haven't drawn any yet but I'm using the Arduino Ethernet's SD port as my SD shield. My Skytraq GPS receiver's RX pin is connected to pin 2 on the arduino ethernet and the TX pin is connected to pin 3 on the ethernet. (Ethernet TX/RX has been set to pin 3 and 2 respectively.)

Please update the question instead. And do not forget to add at least the setup/configuration code.

Sorry, my mistake. I've updated the question and included my code as well.

Please use code format. Edit and use the code {} button.

I've used the code format. Can anyone help now? I'm still trying to solve this problem but I'm coming up empty.

Why are you calling SD.begin() twice? Provide a sample of the results you get, with and without the SD card. Also do you use this same sketch when the card isnt inserted?

Add link to the GPS module. Is it 3.3V? And are the serial signals at 3.3V logic? No details no help.

Unfortunately, I can't post the link because I don't have more than 10 reputation but I've mentioned the GPS module in the updated question. Also, I'm calling SD.begin just once. The other begin statement is Serial.begin.

You're trying to do too much (SD and Serial print operations) at the wrong time (GPS character receiving).
Most GPS devices will send several "sentences" per second, in a batch.  TinyGPS.encode returns true after each sentence, so your code will try to write multiple sentences per second to the SD card.  But it takes so long to open/write/close the SD card (and print to Serial) that the input buffer fills up and overflows.  Here's a detailed description of what is happening.
You must wait until the GPS "quiet time" begins.  Even then, you could have trouble, depending on how much data you need to save and print.
It may be possible to make it work with TinyGPS, but I eventually gave up in frustration and wrote the NeoGPS library to help address these problems.  It can be configured to save just the data you need (via the configuration files), and it can be used to detect when the quiet time begins (see NMEAorder.ino and NMEAfused.ino).  It uses much less RAM and takes much less time to parse the GPS characters.  This will be important if you try to add the Ethernet libraries to the sketch.
If you still have trouble getting all the information written during the quiet time, you can use a companion library (e.g., NeoSWSerial) to handle the GPS characters during the RX interrupt.
Regardless, I would suggest replacing SoftwareSerial with NeoSWSerial.  It, too, is much more efficient than the CPU-killer SoftwareSerial.  It won't fix the main problem, but it will pay off later.

Would it still be doing too much if I just took out the writes to the serial monitor and just left the sd writes in there?

@M.ar, yes, still too much.  The links (blue text) in my answer describe what's happening and how to make it work.

I tried running the NMEA example using SoftwareSerial to define the gps port and it says "java.io.IOException: Access is denied.."

Never mind. Figured out what I did wrong. I'll try to do the writes during the quiet time. I'll let you know how that goes.

Quick question. What do I set trace to if I don't want it to be serial? In this case, i want the output to go to the SD card.

@M.ar, the trace reference is really just from the example programs.  Do the examples really print it in the format you want?  Except for trace_header, you could redirect the example printing like this: sdFile << fix; or sdFile << gps.fix();  This is provided by Streamers.CPP.  You could also cut and paste from Streamers into your own sketch, which would allow you to change the order, add your own variables, or whatever.

Also, may I ask why the NEOGPS library combines the date and time? I'm asking just in case I can actually separate them for future use.

I tried the sdFile << gps.fix() and I realized that if the sdFile is in .csv format, the data stored will not include the date and the hour portion of the date and time; just the minute and the second. If stored in .txt format, the data stored has everything.

@M.ar, Yes, the NeoGPS::Time structure contains both date and time information.  You can access the pieces individually.  See Time.h line 79 and/or Time.CPP line 25.

@M.ar, the SD file name (.CSV or .TXT) does not affect what gets written.  Perhaps you should edit your question and insert an UPDATE section at the end with your new code.  As before, select the code and press ^K.  And if you have some data from the SD card, insert that in another code section above (redact your location).