text:
Code throwing errors after an IDE update
I'm really new to coding for arduino.  My current project is a monitor for my terrarium using an arduino UNO board, a DHT11 and a DS3231 RTC, displaying Temperature(from both DHT (in the terrarium) and the RTC (outside)) as well as time and humidity.
The code was functional, but recently the IDE said there were some updates (which I ran) and now it won't verify. All this code was basically obtained through examples for the hardware I'm using.   Can someone please point me to what I need to correct?
The code as is ....
#include <DS3231.h>

#include <dht11.h>

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
DS3231  rtc(SDA, SCL);
dht11 DHT;                        //Note:DHT on behalf of the temperature         and humidity sensor
const int dht11_data = 6;
int temp=0;
int hum=0;

#include "Wire.h"
#define DS3231_I2C_ADDRESS 0x68
                              // Convert normal decimal numbers to binary   coded decimal
byte decToBcd(byte val)
{
  return( (val/10*16) + (val%10) );
}
                              // Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)

{
  return( (val/16*10) + (val%16) );
}

void setup()
{
  Wire.begin();
                              // set the initial time here:
  // DS3231 seconds, minutes, hours, day, date, month, year
  // setDS3231time(30,42,21,4,26,11,14);
  rtc.begin();                    //Initialize the rtc object
  lcd.begin(16,2);                //Initialize LCD display
  lcd.print("Terrarium ");        //Splash Screen text line 1
  lcd.setCursor(0,1);             //Set Cursor Position for second line of Splash screen
  lcd.print("Monitor 1.3");       //Splash screen text line 2
  delay(3000);                    //Delay 3 seconds on Splash screen
  lcd.clear();                    //Clear LCD
}

void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte
dayOfMonth, byte month, byte year)

{
  // sets time and date data to DS3231
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0);                  // set next input to start at the seconds register
  Wire.write(decToBcd(second));   // set seconds
  Wire.write(decToBcd(minute));   // set minutes
  Wire.write(decToBcd(hour));     // set hours
  Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
  Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
  Wire.write(decToBcd(month));    // set month
  Wire.write(decToBcd(year));     // set year (0 to 99)
  Wire.endTransmission();
}

void readDS3231time(byte *second,byte *minute,byte *hour,byte     *dayOfWeek,byte *dayOfMonth,byte *month,byte *year)

{
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
                              // request seven bytes of data from DS3231       starting from register 00h
  *second = bcdToDec(Wire.read() & 0x7f);
  *minute = bcdToDec(Wire.read());
  *hour = bcdToDec(Wire.read() & 0x3f);
  *dayOfWeek = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month = bcdToDec(Wire.read());
  *year = bcdToDec(Wire.read());
}
void displayTime()
{
  DHT.read(dht11_data);
  temp=DHT.temperature;
  hum=DHT.humidity;

  lcd.clear();                    //clear display

  lcd.print("rH=");               //Display text rH= on LCD
  lcd.print(hum);                 //Display relative humidiy reading from    DHT11
  lcd.print("%");                 //Display Percent sign

  lcd.setCursor(9,0) ;            //set cursor position
  lcd.print("Ti=");               //display"Ti="
  lcd.print(temp);                //Displays temperature reading from     DHT11, designated is Internal Temperature
  lcd.write(0xDF);                //Display custom characters '°'
  lcd.print("C");                 //Display text "C" to designate Celsius     units

  byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

                              // retrieve data from DS3231
  readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month,  &year);
                              // send it to the serial monitor

  lcd.setCursor(0,1);
  lcd.print(hour, DEC);           //Displays hours value on LCD
                               // convert the byte variable to a decimal number when displayed
  lcd.print(":");                 //Displays ":" between hours and minutes
  if (minute<10)
  {
    lcd.print("0");
  }
  lcd.print(minute, DEC);         //Displays Minutes value on the LCD
  lcd.setCursor(9,1);
  lcd.print ("Te:");              //Displays text "Te:" on LCD
  lcd.print(rtc.getTemp());       //Displays Temperature from DS3231 designated as "External Temperature"

}
void loop()
{
  displayTime();                  // display the real-time clock data on the Serial Monitor,
  delay(1000);                    // every second
}

and the errors it is throwing are:
> > Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"
>
> Terrarium_Monitor_1.3:8: error: no matching function for call to
> 'DS3231::DS3231(const uint8_t&, const uint8_t&)'
>
>  DS3231  rtc(SDA, SCL);
>
>                      ^
>
> F:\Arduino Kit Stuff\my
> sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino:8:21: note:
> candidates are:
>
> In file included from F:\Arduino Kit Stuff\my
> sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino:1:0:
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:64:3:
> note: DS3231::DS3231()
>
>    DS3231();
>
>    ^
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:64:3:
> note:   candidate expects 0 arguments, 2 provided
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
> note: constexpr DS3231::DS3231(const DS3231&)
>
>  class DS3231 {
>
>        ^
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
> note:   candidate expects 1 argument, 2 provided
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
> note: constexpr DS3231::DS3231(DS3231&&)
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
> note:   candidate expects 1 argument, 2 provided
>
> F:\Arduino Kit Stuff\my
> sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino: In function
>    'void setup()':
>
> Terrarium_Monitor_1.3:34: error: 'class DS3231' has no member named
> 'begin'
>
>    rtc.begin();                    //Initialize the rtc object
>
>        ^
>
> F:\Arduino Kit Stuff\my
> sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino: In function
> 'void displayTime()':
>
> Terrarium_Monitor_1.3:112: error: 'class DS3231' has no member named
> 'getTemp'
>
>    lcd.print(rtc.getTemp());       //Displays Temperature from DS3231
> designated as "External Temperature"
>
>                  ^
>
> Multiple libraries were found for "LiquidCrystal.h"  Used: E:\Program
> Files (x86)\Arduino\libraries\LiquidCrystal  Not used:
> C:\Users\Ursinos\Documents\Arduino\libraries\arduino_136712 exit
> status 1 no matching function for call to 'DS3231::DS3231(const
> uint8_t&, const uint8_t&)'
>
> This report would have more information with "Show verbose output
> during compilation" option enabled in File -> Preferences.

As I said, I was working when I uploaded it to my arduino on last changes a week ago (and it's still running on the board right now), but after doing the updates to the libraries and whatnot, it's now throwing all these errors.   I know the code isn't very elegant, I'm still learning.  Please help
edit:  After altering the line as advised in the answers, I now get the following errors.
Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"

F:\Arduino Kit Stuff\my sketches\Terrarium_Monitor_1.3  \Terrarium_Monitor_1.3.ino: In function 'void setup()':

Terrarium_Monitor_1.3:34: error: 'class DS3231' has no member named 'begin'

   rtc.begin();                    //Initialize the rtc object

       ^

F:\Arduino Kit Stuff\my sketches\Terrarium_Monitor_1.3  \Terrarium_Monitor_1.3.ino: In function 'void displayTime()':

Terrarium_Monitor_1.3:112: error: 'class DS3231' has no member named 'getTemp'

 lcd.print(rtc.getTemp());       //Displays Temperature from DS3231 designated as "External Temperature"

             ^

Multiple libraries were found for "LiquidCrystal.h"
 Used: E:\Program Files (x86)\Arduino\libraries\LiquidCrystal
 Not used: C:\Users\Ursinos\Documents\Arduino\libraries   \arduino_136712
exit status 1
'class DS3231' has no member named 'begin'

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

Could this have anything to do with my Arduino IDE being version 1.8.3 instead of the newest version?

the I2C (Wire) pins SDA and SCL are constant on Uno. no need to give them into the constructor. change DS3231  rtc(SDA, SCL); to DS3231  rtc;

huh, that's pretty weird since so many of the code examples I've come across have it entered like I had it.

because the libraries are cross platform and on some platforms you can choose the pins. and in new version they disabled for AVR the constructor with parameters

I found this online but I can not verify it.
http://www.instructables.com/topics/no-matching-function-for-call-to-DS3231DS3231const/
The relevant part for you I think is:

I don't know where you get the syntax
DS3231 rtc (SDA, SCL);
My copy of the DS3231 library says you need only DS3231 rtc; //no
  arguments. BUT you need the Wire library.

So change your code and make sure you have the Wire library.

I have the wire library installed and included.  I tried changing that segment of code and it did not help

actually, I figured out what I did wrong the first time I tried changing it.  It cleared the error for that one segment, Editing original post to show new errors.

so why did you accept the answer?

because it was part of the problem

Alright, so I figured it out by gasp going and reading the documentation for the DS3231 library I'm using.
It seems when the library updated, one of the keywords changed.
so, after removing the (SDA, SCL) from the one line, I had to remove the line
rtc.begin();

and change
lcd.print(rtc.getTemp());

to
lcd.print(rtc.getTemperature());

thanks for the help :D

Thanks for advising us of that. Personally I don't update the IDE very often. What is the point? I currently use 1.6.9. It works, and there is a danger if you upgrade then things stop working. It's not as if your Arduino has to connect to some new-fangled printer that was only released last week.


text:
Can't get values of max232 with loopback
I didn't find answers which solves my problem with the max232 yet.
I connected it like this to my Arduino uno, so my Arduino provides the +5V VCC and the ground:
max232 connection

The only thing what is differences are that I do a loopback at the RS232 side and I use 1µF for every capacitor even for the bypass one. I did a loopback so I can see if the max232 works. I don't get anything out of it when I send some data to it.
I measure +8.7V on pin2 and -8.15V on pin 6.
My Arduino code:
/*
  Software serial multiple serial test

 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 10 (connect to TX of other device)
 * TX is digital pin 11 (connect to RX of other device)

 created back in the mists of time
 modified 25 May 2012
 by Tom Igoe
 based on Mikal Hart's example

 This example code is in the public domain.

 */
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.print(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

What did I do wrong or is my max232 broken?
EDIT
I think the serial monitor (same baudrate) doesn't write to the ports so I rewrite some code.
loop code:
int i = 0;
void loop() // run over and over
{
  if(i == 10)
    i = 0;

  mySerial.write(i);
  Serial.print(mySerial.read());
  i++;
  delay(3000);
}

In serial monitor I get strange values back for a cascade counter.
Values:
-1 45 49 52 53 52 57 53 ...
These numbers aren't ascii code for ectual numbers I think.
EDIT 2
Now the loopback works thanks to the answer below.
Now I replaced the loopback with the module FUM DCF-U.
The loop code has changed to this:
void loop() // run over and over
{
  if(Serial.available())
    Serial.println(Serial.read());
}

The problem is that the result is '000000000000000000000000000000000...' in a fast rate and not every second.
The module gets its 3.3V and is connected to the same GND as the MAX232.
Pin connections:
Arduino - MAX232
11 - 11
0 - 12
MAX232 - FUM DCF-U
14 - 3
13 - 4
Thanks in advance

Does loop back work without the MAX232?

SoftwareSerial cannot both send and receive at the same time, as it does receiving inside an ISR, and turns interrupts off when sending. Thus this will never work properly.
I suggest you switch to HardwareSerial. Or, if you want to see the results, send using SoftwareSerial and receive using HardwareSerial. For example:
#include <SoftwareSerial.h>
SoftwareSerial mySerial (10, 11); // RX, TX

void setup ()
  {
  Serial.begin (115200);
  mySerial.begin (115200);
  }  // end of setup

unsigned long lastSend;
char c = ' ';
void loop ()
  {
  // time for another test send?
  if (millis () - lastSend >= 500)
    {
    mySerial.print (c++);
    if (c > 'z')
      {
      c = ' ';
      Serial.println ();
      }
    lastSend = millis ();
    }

  // check for response
  if (Serial.available ())
    Serial.print (char (Serial.read ()));
  }  // end of loop

I tested that as a simple loopback and it worked fine. Connect pin 11 (Tx) to pin 0 (Rx). Disconnect the wire to pin 0 whilst uploading.

My loopback works fine but now I added my atomic clock module the FUM DCF-U and changed the code so that only the last if-clause remains. This results in only '0' (without the char cast) in a fast rate instead of some data every second. Why does this happen?

Perhaps amend your question, and post this amended code. Neither my colleagues here, nor I, are good at debugging code where "I changed a few things but ...".

Editted the question.

source: Stack Exchange

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

sort: votes


text:
Arduino will not read three successive packets in the serial connection
I have written a small program to send serial commands from Python to the Arduino Micro.  This is my code for both:
Python
import serial

ser = serial.Serial('COM5', 9600)

ser.write(b'0')
ser.write(b'1')
# ser.write(b'2')

print('done')

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

void loop()
{

  while (!Serial.available()){}
  Serial.println(Serial.read()-48);

}

If I keep the ser.write(b'2') line in the Python code commented out, the code executes nearly instantly, and I am able to see both transmissions in the serial monitor. If I uncomment it, the Python code takes about 5-7 seconds to execute, and none of the data comes through the serial monitor.
I've tried different baud rates but that hasn't helped. I've also tried sending an integer rather than b'#', and the same thing happens, no data is transmitted if I have all three serial commands active.
What is happening in my code? Is the serial buffer overloaded by the three successive writes and the buffer ends up flushing?

are you sure it is not a problem every second run and not dependent on the write lines?

Hi Juraj, I'm not sure what you mean, can you clarify?

It runs reliably with 2 writes.  It fails every time with 3 writes.

what if you send '0' and '2'  or '1' and '2'.   Same issue?

You don't overload your input buffer, but your output buffer

Chad, I will try that, but I think the last time I did, I just got 0's at the output.
Chrisl, Are you sure?  This serial test is part of a much larger program which sends hundreds of serial commands every second, and I suspect the output buffer would have gotten saturated very quickly, but I haven't run into that problem, I dont think....

Are you testing with the code above, or with your larger program? That makes a difference. The above code will most likely fill the output buffer fast, because there is nothing, that would slow the loop down. If you have a larger program, it may slow down the loop enough (depending on the program). so that the ATMega has enough time to send out the data and empty the buffer.

This may be an issue with python. A full RX buffer on the Arduino does not do anything to the python program, since there is no flow control with Arduino UART. If the input buffer is full, data will simply lost. No blocking of the sender.

Hmm, I don't see a loop that is able to overflow any buffer. The python script just finishes after sending 3 bytes. The arduino sketch will only print if anything anything has been received. Also, from my experience an atmega running at 8Mhz is absolutely fast enough to poll for incoming bytes that are transmitted at a baudrate of 9600...

Oh, sorry, my mistake. Read it falsely. But still I would assume, that the error lies more with the python side, assuming that the OP really tests with the code above and not with the larger code.

The problem is that your code works but you substract 48 from what you received.
Which if python sends a char with values: '0' '1' '2' it will result in the serially outputted values of NUL SOH STX which are invisible.
If python transmits the raw byte value (aka 0x00 0x01 0x02) this would result in 0x00 - 48 = undefined behaviour with a underflow (same goes for 0x01 and 0x02)

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


text:
How to control two 12 V motors with the dual MAX 14870 Motor Drive Shield for Arduino?
How to control two 12 V motors with the dual MAX 14870 Motor Drive Shield for Arduino?
I am a beginner and I need help on how to control two 12 V motors using the Pololu dual MAX 14870 Motor Drive Shield for Arduino Uno.

I had attached the screenshot for this
This picture tells you about the Arduino Connection with the with the SHIELD.

EN (Enable Pin) is used to enable and disable the motor drivers. As it is inverted SET this PIN HIGH will Disable the Motors and vice versa.
DIR pinS is used direction of rotation. It highly depends upon your connection, setting this PIN HIGH LOW will make the motor rotation from CLOCKWISE & ANTI CLOCKWISE or vice versa depends upon your hardware connection.
PWM pins are used to control the rotation speed of the MOTOR. Driving PWM signal on this pin will adjust your rotational speed. MAX PWM frequency suggested is 50Hz.
Fault is the INPUT PIN to Arduino with ACTIVE LOW signal indicating some kind of fault is there.

du i have to download and install a library for that shield.

No you can use simple digitalWrite and analogWrite instructions for handling all the pins.

thank you, you have been most helpful.

i'v been looking all over for help, i'm surprised there are not tutorials on how to use the Dual Max14870 Motor Driver Shield

You can use this l293d with arduino for referral as they have similar properties. They are not exactly same but it will help you understanding with the CODE.

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


text:
sim800l only receiving SMS after serial monitor is started otherwise not receiving
I am using SIM800L and Arduino Uno.
The programme is working fine when I turn the serial monitor on using Arduino IDE but when I start the Arduino board by using the adapter it is not receiving anything. I have blinked LED on receiving SMS.
#include <SoftwareSerial.h>

SoftwareSerial wire(3, 2);
String  Grsp;

void setup()
{
   wire.begin(9600);
   Serial.begin(9600);
   wire.println("AT+CMGF=1");
    wire.println("AT+CNMI=2,2,0,0,0");
  pinMode(8, OUTPUT);
  digitalWrite(8, HIGH);
  delay(1000);
    digitalWrite(8, LOW);

   delay(100);
}

void loop()
{

  if (wire.available()>0)
  {
        Grsp = wire.readString();
     Serial.println(Grsp.length());
     Serial.println(Grsp);

     if(Grsp.length() > 100)
     {
       Serial.println("if crossed");

      digitalWrite(8, HIGH);
       delay(1000);
        digitalWrite(8, LOW);

      }

}

}

Do you have any common ground 'GND' between arduino and sim800l module. UART works when there is TX RX and GND terminals are connected between both modules. When you connect it with PC and open your terminal the both got supply from PC thus have common GND connection.

thank you so much Vaibhav you made my day,it was same as you said i used common GND on breadboard.


text:
Servo going up to the limit as soon as attached
I have a Futaba S148 servo (https://servodatabase.com/servo/futaba/s148)
connected to an Arduino Uno.
As soon as the script attaches the servo, it rotates to its limit and gets stuck.
I've tried several scripts, and narrowed to the simplest:
#include <Servo.h>  // servo library
Servo servo1;  // servo control object
void setup()
{
  //  Attach the servo1 object to digital pin 4.
  servo1.attach(10);
}
void loop()
{
}

Also connected the servo to the board with this:
#include <Servo.h>  // servo library
Servo servo1;  // servo control object
void setup()
{
  //  Attach the servo1 object to digital pin 4.
  //servo1.attach(10); <--- notice this commented out
}
void loop()
{
}

and then the servo remains still.
I'm using a battery pack of 4.8 V which works fine with the servo and the RC radio, so the battery and the servo, works fine together with remote control.
I have another different SG90 servo running with its own power source and connected to the pin 9, and with a different sketch, it works perfectly.


text:
error: espcomm_upload_mem failed ESP8266
So, I downloaded tools for my ESP8266 using this link:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
I installed the last version in my motherboard manager (2.3.0) and tried to execute my first example ("Blink"), but here is what I get :

What can I do to prevent this?
P.S My ESP8266 is connected to an Arduino Mega

And how exactly is it connected, and what are you running on the mega?

@Majenko I used the scheme from that article : http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/

@Majenko Nothing except the ESP is connected to my Arduino

The reason why this error comes up is because the programmer cannot communicate with the bootloader of the ESP.
The link you mentioned in the comments misses a very important step, which is to remove the ATmega chip already on the Uno board. Otherwise the programmer will see corrupt data due to 2 bootloaders on the same UART lines.
Remember that only one device can communicate on the UART lines.
The Mega board has the ATmega chip soldered to the board, so you don't have much hopes of isolating the UART lines.
Another thing to remember is to always reset the ESP into flash mode (reset the ESP with GPIO_0 pulled low).
If you still want to use the ESP with the Mega board, go through the Multi Serial examples given in the IDE. The concept requires making two GPIO lines communicate with the ESP, while the original Serial lines to the programmer (the computer).
All data sent via ESP is routed to Mega's serial lines and vice versa.

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


text:
Is the ShiftOut tutorial on the official Arduino website really wrong regarding the capacitor?
I'm talking about this tutorial "Serial to Parallel Shifting-Out with a 74HC595" from the official Arduino website. It provides the following schematic:

I've read a couple of times now, that the placement of the capacitor is wrong:

This is a well known shit tutorial which for some unknown reason they refuse to fix.
  That capacitor should be connected between the Vcc pin and ground, NOT the latch pin.

Source: forum.arduino cc/index.php?topic=408135.0
They recommend this placement:

Who's right? Please explain where to place the capacitor. Can the arduino even be damaged?

My low reputation score doesn't allow me to put the URLs as links. Maybe someone with a higher reputation can edit and fix it. :-)

Alright, links are working now. Thank you, editors :-)

That tutorial, as with a number on the Arduino site, is wrong.
Yes, the capacitor should be across Vcc/GND - it is a decoupling capacitor used to absorb the current surges when you turn LEDs on and off.
Not to mention that with that circuit if you turn on all the LEDs you are overloading the 74HC595. That has a maximum 70mA through Vcc/GND pins. Each LED there (assuming red LEDs at 2V forward voltage) will be drawing about 13.6mA. 8 LEDs would be 8*13.6 = 109mA.
Ouch.
The problem with many of the Arduino tutorials is they were written in the early days of Arduino when they didn't have much knowledge and experience. Since then the arduinosphere has grown and there are people now with far more knowledge and experience than Arduino had at the time the tutorials were written. We come here.

The Arduino team is actually remarkably receptive to corrections/improvements to the documentation. If a small fraction of the time people have spent complaining about this issue had been used to instead submit an issue report to https://github.com/arduino/Arduino/issues it would have been fixed long ago.

@per1234 Unfortunately, they said the opposite thing in the posts of the linked Arduino forum thread... It seems to have been reported numerous times and no correction has taken place. :-(

They emailed it to the Arduino "webmaster" email address which is a complete waste of time. And no, the Arduino team don't read the forum. Those guys have been around years longer than me so they should know how things work. I've explained this to them in a different thread where that tutorial was brought up but still nobody bothered to open an issue. I guess they just like to complain. I'd report it myself (and I have done so with many other issues) but I only report things that I can personally verify.

@per1234 Fair point. I found a TI datasheet which backs the opinions of this SO post and the forum posts, so I opened a new issue: https://github.com/arduino/Arduino/issues/6433 Thanks :-)

You can figure out the impedance of that capacitor for high frequency signal....
What they have there is really a low pass filter.
Terrible ideal to out that big of a capacitor there.

Are you talking about the capacitor connected to the latch pin?

Liam, of course is @dannyf talking about the capacitor to the latch pin. A capacitor to a digital output pin is not normal, it's really bad, it's worse, it's a terrible idea, it's super extraordinary terrible, it's... (you get the idea).

Liam, I'm reading the last post on the Arduino forum with the link you gave. Grumpy_Mike says it's stupid and can damage the Arduino outputs. I totally agree with that. The latchPin is a digital output from the microcontroller and any capacitor to that pin (even the smallest capacitor) is really bad and indicates a design flaw.

You do not need a capacitor to use the 74HC595 in conjunction with shiftOut(). I found this YouTube video to be very useful in explaining how to wire up and code the shift-register for a 7-segment display.

Indeed, it seems like the Arduino tutorial is wrong. I just found the following schematic in Datasheet SN74HC595 - Texas Instruments from 10.2 Typical Application, Figure 5:

The capacitor connects VCC to GND. Nothing to do with the latch pin.


text:
Coding or Wiring? Dual Piezo sensor not triggering LED lights
I am running two piezos off an Arduino UNO and trying to get 10 LED lights to trigger when the piezo voltage exceeds a certain threshold. Problem is, the LEDs wont fire when the Piezo voltage exceeds that threshold and I'm not sure if it is a coding or wiring problem.
Below are pictures of the wiring (Top and bottom) and code. Any help is much appreciated!!

/*
  Dual Piezo Bond Auger Sensor; Blinking LED Light Stack Sketch

  -----------------------------------------------------*/

//Piezo 1 Pin (PiezoPin1)
//Piezo 1 connected to A0
int PP1 = 0;

//Piezo 1 Pin (PiezoPin1)
//Piezo 2 connected to A1
int PP2 = 1;

//Sets the threshold for the detected sound to trigger the LED
const int threshold = 0.01;

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

  for (int i = 4; i < 12; i++) {
    pinMode(i, OUTPUT);
    //sets the led pins 2-11 to output
  }
}

void loop() {
  //Ensure to turn off ALL LEDs before continuing
  for (int i = 4; i < 12; i++) {
    digitalWrite(i, LOW);
  }

  /* Read the Piezos
    Reads both piezos and outputs the values. Triggers LED lights
    to fire when a peak voltage is exceeded
    Adjust the value based on the peak signal voltage you
    want to trigger the LED lights*/
  int Piezo1ADC = analogRead(PP1); // Read Piezo 1 ADC value
  float Piezo1V = Piezo1ADC / 1023.0 * 5.0; // Convert to voltage
  int Piezo2ADC = analogRead(PP2); // Read Piezo 2 ADC value
  float Piezo2V = Piezo2ADC / 1023.0 * 5.0; // Convert to voltage
  Serial.println(Piezo1V); //Print the voltage from Piezo 1
  Serial.println(Piezo2V); //Print the voltage from Piezo 2
}

// The blink function - used to turn the LEDs on and off
void blink(int LEDPin11, int LEDPin2, int LEDPin3, int LEDPin4, int LEDPin5, int LEDPin6, int LEDPin7, int LEDPin8, int LEDPin9, int LEDPin10, int Piezo1V, int Piezo2V, int threshold) {
  if (Piezo1V >= threshold || Piezo2V >= threshold) {  //toggle status of LED pins linked to PP1
    // Blink the LEDs on for both Piezos
    { digitalWrite(LEDPin2, HIGH);
      // Delay so that you can see the LEDs go On.
      delay(10);
      // Turn the LEDs Off
      digitalWrite(LEDPin2, LOW);
      // Increase this Delay if you want to see an actual blinking effect.
      delay(10);
    }
    { digitalWrite(LEDPin3, HIGH);
      delay(10);
      digitalWrite(LEDPin3, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin4, HIGH);
      delay(10);
      digitalWrite(LEDPin4, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin5, HIGH);
      delay(10);
      digitalWrite(LEDPin5, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin6, HIGH);
      delay(10);
      digitalWrite(LEDPin6, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin7, HIGH);
      delay(10);
      digitalWrite(LEDPin7, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin8, HIGH);
      delay(10);
      digitalWrite(LEDPin8, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin9, HIGH);
      delay(10);
      digitalWrite(LEDPin9, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin10, HIGH);
      delay(10);
      digitalWrite(LEDPin10, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin11, HIGH);
      delay(10);
      digitalWrite(LEDPin11, LOW);
      delay(10);
    }
    { digitalWrite(LEDPin10, HIGH);
      delay(10);
      digitalWrite(LEDPin10, LOW);
      delay(10);
    }
  }
}

Edit your question to format the code. Select all the code and hit Ctrl-K.


text:
NRF24L01 Networking
We checked Xbee, ZigBee and other alternatives already and we're trying to figure out a way for good and cheap network system. NRF24l01 looks good but 32 bytes not enough actually. Even so looks like we'll use it but some questions;
Questions' scenario contains 1 master and 300 slave devices with NRF24l01. We're thinking about making a addressing system like computer networks and every message will contain device id or device group tag. Master will be at the center of the room. Room do not have any inner wall or obstacle. Maximum range is less than 100m².
1) May messages get corrupt or latency ?
2) Is there any prepared library for Arduino for this kind of communication ?
3) Do you think is there any better solution for this kind of master & slaves networking logic (must be cheap and stable) ?

google NRF24L01 mesh

1) May messages get corrupt or latency ?

For uni-directional Master to One Slave, no, there should be no corruption (at least not caused by there being lots of slaves present). For bi-directional Master to Multiple Slaves at the same time, yes, you're going to run into problems when the slaves try and reply. Keeping your protocol really simple will be beneficial.

2) Is there any prepared library for Arduino for this kind of communication ?

There's nothing special about what you propose. The RF24.h library will probably do the job (though I have never used it, so don't ask me how to use it).

3) Do you think is there any better solution for this kind of master & slaves networking logic (must be cheap and stable) ?

They're all a bit of a muchness really. RF communication is RF communication. It's how you use it that matters.
The nRF24L01+ has a number of benefits that mean you can do some things in hardware:

Multiple receive pipes, each with their own address - so you can have one for the device address, one for a group address, and one for a global "broadcast" address
Auto-acknowledge and re-sending of failed packets for more reliable communication (only for one-to-one communication)
Automatic packetisation so you don't have to worry about crafting a low-level protocol of your own
Direct communication giving low-latency
Power Amplifier option for greater range.

You could use WiFi, however that would struggle with so many devices (most home access points and routers can't handle more than a few dozen devices), plus it adds extra latency that it sounds like you don't want.
The nRF24L01+ is probably a good choice for this kind of communication - however, be cautious with cheap clone devices: some of them have a silicon error that causes them to not be compatible with other nRF24L01+ devices.

I was surprised to read that RF24.h supports packetisation which I read as in supporting payloads larger than 32 bytes. Could you provide a link that explains that?

@ChristianLindig By packetisation I mean that it deals with all the frame construction, CRCs, etc. You still have to split your data into 32 byte chunks and add any other identifying segment numbering.


text:
Arduino Uno Multiple Modules
I have an Arduino Uno and I want to connect;

RFID Reader (RC522)
WiFi Module (ESP8266 ESP-01)
SD Card Module
RTC (Real Time Clock - DS1307)

Same time but pinouts are not enough. Is there a way to doing this with Uno or I have to buy an Arduino Mega ? I saw "Expansion Sensor Shield"s but I do not know what is the logic of using this ?
Regards

It depends. You need to provide more detail. Some of the devices use I²C which can share connections provided they have different addresses. Others use SPI which need individual select pins.

Let's see which device uses which communication protocol:

WiFi Module (ESP8266 ESP-01) uses Serial communication.
RTC (Real Time Clock - DS1307) uses I²C communication.
RFID Reader (RC522) uses SPI communication.
SD Card Module also uses SPI communication.

Now, the Arduino UNO supports One I²C, One SPI and One Serial (by default) communication port.
So, you can easily connect your Wifi and RTC modules.
Now, actual problem is: "How to access multiple SPI interfaces on Arduino" (and that is a solved problem).
Hope it helps and you don't have to buy an Arduino MEGA.


text:
How to define a SoftwareSerial object inside a class?
I have a header file called Rhino.h with class Rhino. I want to pass RX and TX pin numbers to this object class, and with this, define a SoftwareSerial object to be used inside the Rhino class. The code in my header file looks like this (there are more number of functions like gotoPos() which I have omitted for brevity purpose):
#include "Arduino.h"

class Rhino
{
public:
    Rhino(int rx,int tx):serial(rx,tx){}

    void gotoPos(int pos)
    {
        serial.write(pos);
    }
private:
    SoftwareSerial serial;
}

And my Arduino code looks like this:
#include <Rhino.h>
Rhino motor1(9,10);
void setup()
{
    motor1.gotoPos(10);
}
void loop() {}

I get this as error:
Arduino: 1.0.6 (Windows NT (unknown)), Board: "Arduino Uno"
S:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 -IS:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino -IS:\Program Files (x86)\Arduino\hardware\arduino\variants\standard -IS:\Program Files (x86)\Arduino\libraries\Rhino C:\Users\Samvrit\AppData\Local\Temp\build2516495983752907071.tmp\Test2.cpp -o C:\Users\Samvrit\AppData\Local\Temp\build2516495983752907071.tmp\Test2.cpp.o

In file included from Test2.ino:6:
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:740: error: 'SoftwareSerial' does not name a type
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In constructor 'Rhino::Rhino(int, int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:16: error: class 'Rhino' does not have any field named 'serial'
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::init()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:21: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::reset()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:30: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::autoCalibrate()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:37: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::sendCmd(String)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:46: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::sendCmd(char*)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:58: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::rotate(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:76: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::stopMotor()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:88: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoPos(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:103: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoAngleDeg(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:123: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoAngleRad(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:143: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoAngleDegC(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:164: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoAngleRadC(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:185: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoRel(long int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:218: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoRelDeg(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:253: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoRelRad(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:289: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setSFGain(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:306: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setP(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:322: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setI(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:338: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setD(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:355: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setSpeed(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:372: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setI2CAddr(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:389: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setPos(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:406: warning: unused variable 'curr_pos'
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:415: warning: unused variable 'curr_pos'
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:426: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getPos()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:474: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'float Rhino::getAngleDeg()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:501: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'float Rhino::getAngleRad()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:528: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getSpeed()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:555: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getRotSpeed()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:582: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getI2CAddr()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:609: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getSFGain()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:636: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getP()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:663: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getI()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:690: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getD()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:717: error: 'serial' was not declared in this scope

Put a semicolon (;) after right brace (}) that ends the class def.  As noted in a C++ Syntax: class page (at end of Track.h section),  “The end of the compound statement ... is followed by a semi-colon [unless defining] a class and an object of that class in a single statement”

In your header file, I dont see where you included SoftwareSerial.h; this may be a part of why you got those errors. Also you need to end the class definition with a semi-colon, like you were advised in a comment.
That said, you could just pass a pointer to a SoftwareSerial object to your Rhino constructor. In your library header:
#include "Arduino.h"
#include <SoftwareSerial.h>

class Rhino {
  private:
    SoftwareSerial * serial;

  public:
    Rhino(SoftwareSerial * ss);
    // other prototypes
};

In your .cpp source:
#include "Rhino.h"  // assuming thats what you named the header

Rhino::Rhino(SoftwareSerial * ss){
  serial = ss;
 }

void Rhino::begin(uint32_t baud){
  serial->begin(baud);
}

void Rhino::gotoPos(int pos)
{
  serial->write(pos);  // must use the structure pointer operator
}

In your Arduino sketch:
#include "Rhino.h"
#include <SoftwareSerial.h>

SoftwareSerial ss(2,3);
Rhino rhino(&ss);  // pass a pointer to ss

void setup(){
  rhino.begin(9600);
  rhino.gotoPos(50);
}

Thank you. It worked when I included the SoftwareSerial library in my Arduino sketch. Also, I figured that it is better to include the SoftwareSerial.h in the Rhino.h as well, because then the order of including the header files in the Arduino sketch doesn't matter. Otherwise the SoftwareSerial.h should be included BEFORE the Rhino.h library.

Personally I wouldn't go down this route. Instead I would pass a Stream object (as a pointer or a reference) to the constructor and use that. Then it is up to your sketch to define what that Stream object is and initialize it.
That way if you want to use the same class on a hardware UART instead of a SoftwareSerial you just change the sketch, not the library.
So you would initialize as something like this:
SoftwareSerial mySerial(6, 7);
Rhino myRhino(mySerial);

void setup() {
    mySerial.begin(9600);
    myRhino.gotoPos(34);
}

Your Rhino class would look something like this:
class Rhino {
    private:
        Stream *_dev;

    public:
        Rhino(Stream *dev) : _dev(dev) {}
        Rhino(Stream &dev) : _dev(&dev) {}
        void gotoPos(int pos);
};

void Rhino::gotoPos(int pos) {
    _dev->write(pos);
}

The double constructors, one with a pointer and one with a reference, allow the simplicity of passing an object as in the example, or as a pointer, which could be done with the new operator all in one step. I like the way shown in the example though since it is nice and clean.
Of course, because you now have a pointer to your stream object, you need to use the pointer dereference operator instead of the normal .:
_dev->write(pos);

Changing to a hardware UART is then as simple as, for example:
Rhino myRhino(Serial);

Heck, you could even send it through the internet since an Ethernet or WiFi Client is also a Stream object.

that's a very interesting approach. Such infinite knowledge you have sir.

Thank you. Your method is of course more compatible. However, I have functions in my library which use the begin(), listen() & available() functions, which are not available in Stream class. Also, the Rhino motor that I am trying to operate using this library uses only UART. I solved the issue by including SoftwareSerial.h in both the Arduino sketch and the Rhino.h header file.

Also, I don't want the user to initialize an additional SoftwareSerial object in the Arduino code and then send it to the Rhino library. It's better that the user just sends the pin numbers and everything is taken care in the Rhino library.

You need to import the SoftwareSerial library into your Rhino.h file, since you are using that class in your header file. Perhaps you are also in need of a forward declaration. Inside your Rhino.h file, include SoftwareSerial library, and then above class Rhino, type class SoftwareSerial;. This effectively lets the compiler know that Software Serial is being used. More information on forward declarations can be found here.
Modified Code:
#include "Arduino.h"
#include "SoftwareSerial.h"

class SoftwareSerial; //this might be unnecessary, but doesn't hurt to have it.
class Rhino
{
public:
Rhino(int rx,int tx):serial(rx,tx){}

void gotoPos(int pos)
{
    serial.write(pos);
}
private:
    SoftwareSerial serial;
}

Thank you. It did work when I included the SoftwareSerial.h in the Rhino.h.

authors: مشعل الزبيدي


text:
10k ohm Potentiometer vs 10k ohm Resistor on LCD Display
I'm trying to use a LCD Display with my Arduino, but I don't have a potentiometer and all of the guides I find always require one, usually a 10k ohm potentiometer.
The point is that I'm not very good at this stuff, but I understand that the potentiometer is actually a resistor that can vary, am I correct? In that case, if I use a simple 10k resistor I would have the same result as if I was using that potentiometer at the higher resistance (10k).
Would it be correct to use the resistor instead of the potentiometer? Then I would have to plug the positive on one side of the resistor and both the negative and output to the LCD on the other side of the resistor?

I understand that the potentiometer is actually a resistor that can vary - more like a voltage divider where you can vary the ratio.

No, it would not be correct to use a single resistor to replace a potentiometer.
On an LCD the potentiometer is used to adjust the bias level of the LCD - that is the contrast.  You need to use it to set a voltage between Vcc and Vee, which you feed into Vo.  That is, a voltage somewhere between +5V and -5V.
You can't do that with one resistor.
You can, however, do it with two resistors.  Some experimentation will provide the right values to use.  Pick a pair of resistors which add up to around 10K (the exact value doesn't matter that much) and join them together end to end.  The two ends are the equivalent to the ends of the track of the potentiometer, and the join in the middle is the wiper.
To change the "value" of the potentiometer you then need to change the value of both resistors.  If you reduce one resistor you need to increase the other so that they still add up to around the same value.  What you are working with here is not the actual values of the resistors, but the ratio of the values of the two resistors.

Thanks a lot for the explanation. I will try that and see what i can do. It's very interesting, but i still suck in physics/electric.

@GeorgeRappel You can read more about the theory here: https://en.wikipedia.org/wiki/Voltage_divider

you can use the digital pin to do this instead of resistance or potentiometer. I used a delay 500 which gave me good readable display. a value of 100 was to bright
void setup() {
  pinMode(13, OUTPUT);
}

void loop()
{
 digitalWrite(13, HIGH);
  delayMicroseconds(500);
/* 100 gives Approximately 10% duty cycle @ 1KHz with 500 i get a good value for screen text brightness*/
  digitalWrite(13, LOW);
  delayMicroseconds(1000 - 500);

/* now you can add your LCD code to print what ever you like.*/
}

This is both somewhat impractical, and quite misleading.  For this to work, your processor will be largely tied up in performing this software pulse-width modulation, and you entirely fail to state that.  Such a scheme could still be useful if the display is allowed to blank while other operations are performed and only resumes when the sketch is idle waiting for input to act on.  But it would be far better to use one of the hardware or interrupt-based software PWM schemes the Arduino offers.

why not just analogWrite() a value to the pin?


text:
Is there a away to transmit sensor signal over RF without Arduino?
I would like to place analog sensor in a place, that is impractical to reach with a wire. But it looks like an overkill to use a separate small Arduino board to read and transmit sensor signal to main Arduino board at a close range (~1 m).
Is there a cheap practical way to setup such sensor signal broadcast over RF without using Arduino board? Something that could work for considerable duration with a small tablet like battery?

Thank you both for very helpful solutions. I've chosen first one, because in  Aliexpress at a lot of 10 I can get all needed components for ~1 EUR and second solution at a lot of 10 costs ~1,8 EUR. Will consider all pros and cons and maybe even stick to pricier solution due its ready-made nature.

What kind of sensor? E.g. there are wireless temperature sensors that you can buy in the store, and the signal those send out can be pretty easily read by and arduino.

I've meant solution available for different sensors not only temperature. I did find wireless sensors to purchase, but these were kind of expensive.

You don't have to use a $30 Arduino. You can make a "breadboard" one for a few dollars, like this:

$5 for the chip and a couple of dollars for a couple of capacitors and resistors.

Add to that a NRF24L01 transceiver like this:

Available from eBay for around $1 each. You need two, as you need to transmit from one and receive from another.
So the whole thing could be done for under $10.

Something that could work for considerable duration with a small tablet like battery?

See Power saving techniques for microprocessors

So the only solution is to use NRF24L01 transceiver and barebone Arduino or ATtiny chip. There is no cheap ready-made transceiver that I could connect to sensor and a battery? If no other solutions will be given by other members, I'll select your explanation as an answer. Thanks!

I don't know of any ready-made transceivers that will happen to work with your Arduino base-station.

I would recommend investigating the ESP8266 modules.  Many people use them as a WiFi interface to an Arduino, but they are also capable of being used completely standalone.
You can pick up a cheap module and program it using a readily available USB to TTL UART adapter using the ESP8266 plugin to the Aduino IDE.
https://github.com/esp8266/Arduino
It's like having an Arduino and a WiFi interface all embedded in one chip, and the modules are tiny too - perfect for embedding in a project.
There are many different modules available, some with more pins than others for IO.  The best one is the NodeMCU since it has the programming interface built in (go for version 1.0 not version 0.9 since it has better IO options), but the higher end ESP8266 modules on carrier boards (ESP-12, etc) are as good, if a little harder to work with.

Is it possible to have the ESP8266 run for a reasonable amount of time (>few months) on batteries? I haven't seen any projects that use batteries on the ESP8266.

There is a sleep mode available on it. I don't know how effective it is, or how you use it, but it does exist.

You can probably get it to work if you only send an update every hour or so. More frequent updates will probably drain the battery too soon. Setting up a wifi connection take quite a bit of time. Optionally you could batch upload the data.


text:
Programming an ATMEGA2560 using FTDI
I want to know how exactly do I program (upload arduino sketches) an ATMEGA2560 which is boot loaded with an Arduino Bootloader using a FTDI programmer and an Arduino IDE, is there any capacitors/resistors required?

If you have a bootloader, you just need to connect up four wires from the FTDI cable:

Pin 1 (black) -> Ground
Pin 2 (CTS)   -> not connected
Pin 3 (Vcc)   -> 5V
Pin 4 (TxD)   -> Rx (Mega pin D0)
Pin 5 (RxD) -> Tx (Mega pin D1)
Pin 6 (green) -> not connected

This will not auto-reset, so you will have to press (and release) the Reset button on the board at the moment that the sketch starts to upload.

How to make it auto reset?

What you should be able to do is connect RTS to Reset on the board, using a 0.1 µF capacitor (in series). I found in practice that this did not bring Reset low enough to trigger it - I'm not sure why, except maybe the board has a stronger pull-up resistor on /RESET than expected. That technique works for me on breadboard Arduinos.
Since it didn't work for me, I did not put it in my original answer. You could try that, and if it works, well and good.

I don't want to do that? How to make it auto reset?

See amended reply. Is there any reason why you don't just use the USB interface? That usually works.

I've fabricated a custom PCB with ATMEGA2560 mounted on it, I added your bootloader sketch and I'm trying to upload sketches to it using the arduino IDE, so that is why I'm using the FTDI chip to do this.

You need to break the "RESET-EN" jumper just above the 47µF capacitor on the Mega2560.
When/ if you want to use the on-board USB again, solder a two pin header onto these points and put a removable jumper on.

The question was about an Atmega2560 not the Mega2560 board. Thus, there is not necessarily a RESET-EN jumper on it.


text:
Serial print and sensor readings halts
I'm trying to write a state machine for my robot.
While the robot is moving around I would like to read the values of the sensors, but after some time the reading stops working.
For the first half hour it's ok, then I don't know what changes.
It looks like it halts when jumping from one state to another, or when the sensor value has a big jump...
I tried to move the debugOutput function inside the main loop, but the behavior is the same..
In addition to the serial halting, also the state machine itself seems to stop working good, since even if the sensor value change, the state is not updated..
Could you please help me with this?
Thanks a lot!
Here is the code:
    // motor one
    int enA = 13;
    int in1 = 12;
    int in2 = 11;
    // motor two
    int enB = 9;
    int in3 = 10;
    int in4 = 8;

    int sens1 = 0; //ingresso sensore bobina 1
    int sens2 = 1; //ingresso sensore bobina 2

    float soglia_barriera_norm = 1.5;
    float soglia_barriera_scarico = 390;

    // define the states
    #define DRIVE_FORWARD     0
    #define TURN_LEFT         1
    #define RADDRIZZA         2
    #define SCARICO           3 //Scarico cerca il filo

    int state = 3; //to start from state 3

    void setup()
    {
      // set all the motor control pins to outputs
      pinMode(enA, OUTPUT);
      pinMode(enB, OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(in3, OUTPUT);
      pinMode(in4, OUTPUT);
      pinMode(53, OUTPUT);
      Serial.begin(9600);

    }

    //------------------------ LETTURA SENSORI ---------------------------
    //average of n readings

    float sensorReadDX(int n_medie) {
      int i, temp = 0;
      for (i = 0; i < n_medie; i++) {
        int sensorValue1 = analogRead(sens1);
        temp += sensorValue1;
      }
      float volt = (temp / n_medie);
      return volt;
    }

    float sensorReadSX(int n_medie) {
      int i, temp = 0;
      for (i = 0; i < n_medie; i++) {
        int sensorValue2 = analogRead(sens2);
        temp += sensorValue2;
      }
      float volt2 = (temp / n_medie);
      return volt2;
    }

    float differenza(float volt1, float volt2) {
      float D = volt1 - volt2;
      return D;
    }
    //----------------------------------------------------------------------

    //----------- MOTOR MOVEMENTS ---------------------------------------------

    void moto_dx_forward(int vel) {
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      analogWrite(enA, vel);
    }

    void moto_dx_backward(int vel) {
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      analogWrite(enA, vel);
    }

    void moto_sx_forward(int vel) {
      digitalWrite(in3, LOW);
      digitalWrite(in4, HIGH);
      analogWrite(enB, vel);
    }

    void moto_sx_backward(int vel) {
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      analogWrite(enB, vel);
    }

    // to stop motors
    void moto_dx_stop() {
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      analogWrite(enA, 0);
    }

    void moto_sx_stop() {
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
      analogWrite(enB, 0);
    }

    //---------------------------------------------------------

    void debugOutput() {
      Serial.print(millis());
      Serial.print("\t");
      Serial.print(sensorReadSX(50));
      Serial.print("\t");
      Serial.print(sensorReadDX(30));
      Serial.print("\t");
      Serial.println(state);
    }

    void stateMachine() {
      float sensSX = sensorReadSX(30);
      float sensDX = sensorReadDX(30);

      if (state == DRIVE_FORWARD) {
        debugOutput();

        if (sensSX <= soglia_barriera_norm || sensDX <= soglia_barriera_norm) {
          moto_dx_forward(255);
          moto_sx_forward(255);
        } else {
          state = RIMBALZA;
        }
      }

      else if (state == SCARICO) {
        debugOutput();
        if (sensorReadSX(50) < soglia_barriera_scarico){ //|| sensorReadDX(20) < soglia_barriera_scarico) {
          moto_dx_forward(255);
          moto_sx_forward(255);
        } else {
          moto_dx_stop(); //ferma i due motori e poi raddrizza
          moto_sx_stop();
          state = RADDRIZZA;
        }
      }

      else if (state == RADDRIZZA) {
        debugOutput();
         while ( sensorReadDX(30) <= 490){
          //ruota su se stesso
          moto_sx_stop();
          moto_dx_forward(255);
        }

        moto_dx_stop();
        moto_sx_stop();
      }

    }

    void loop() {
      stateMachine();

    }

Try outputting the current state.  Is there any logic which can change from the RADDRIZA state to any other?  It sort of looks that it could become stuck there with both motors off.

no, at the moment when RADDRIZZA is finished it stays there with motor stopped.. however I found the problem, it stopped outputting because during the while ( sensorReadDX(30) <= 490) it doesn't execute what's outside the loop!


text:
Arduino AD-converter tolerance
I created a quite simple Arduino sketch:
void setup() {
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);

  float voltage = sensorValue * (5 / 1023.0);
  Serial.println(voltage);

  delay(1000);
}

I use the following circuit:

My multimeter measures 3.31 V, between the pin 3V3 and GND.
I get a sensorValue of 730 and a calculated voltage of 3.57 V. This is 8% higher that 3.3V. What is the tolerance by the AD-converter?

Did you connect the 3V3 directly to A0 with no current limiting resistor?

What voltage does your voltmeter say the "5V" supply is? That's the 5.000 that you're using in your calculation.

In engineering (and usually also in life in general) when asking questions or seeking to learn, it is usually wise to avoid the mind set that goes with "Of course" and " ...the problem MUST BE something with ...". Both of these lock you into mindsets that hide information and/or  decrease the likelihood that people will make the effort to help you.

The absolute accuracy of the ADC in the ATmega328P when its clock is within its optimal range is given in the datasheet as 2LSB. This means that the actual value could be anywhere between 728 and 732.
Of course this depends on the accuracy of VCC, since it is being used as the ADC reference. This is why supply voltage measurements should be performed using the internal bandgap voltage instead.

Did you read the first sentence of the answer?

@Dennis: If 730 count is 3.31V, 1023 count is about 4.64V. Your supply voltage is low. Which is what the second paragraph covers.


text:
fading colors on a ws2812 strip
I have a strip of 7 leds. its ws2812. Im starting them on blue. Next I want them to do a slow fade into pink. So all Im trying right now is to increment r.
I can get them to work one by one. But I need them to all fade together from blue to pink.
Ive moved my r++ loop around till I was cross-eyed. Still it didnt fade all 7 leds to pink all at once.
sometimes it would stay blue and do nothing sometimes fade to pink one pixel at a time.
How do I get all 7 leds to fade together?
Thank you.
#include <FastLED.h>
#define NUM_LEDS 7
#define DATA_PIN 6
#define BRIGHTNESS 45
#define COLOR_ORDER GRB
#define g 50
#define b 100

int r; //changed it to undefined

CRGB leds[NUM_LEDS];

void setup(){
FastLED.addLeds<WS2812, DATA_PIN, GRB>(leds, NUM_LEDS);

 }
void loop(){

this lights all leds to blue
  for(int x = 0; x < NUM_LEDS; x++){

  leds[x] = CRGB(r,g,b);
 }
  FastLED.show();
  delay(10);

this code should grab all 7 leds in NUM_LEDS store it in x
  for(int x = 0; x < NUM_LEDS; x++){

  leds[x] = CRGB(r,g,b);

Heres the problem area. I get no errors but it doesnt fade all 7 leds at a time.
Ive tried moving my code around but it either doesnt fade or fades to pink one led at a time. where should my 'for loop' for incrementing r be at?
Should I be changing rgb all at once using array?
//take r and fade it up to 254

for(int r = 0; r < 254; r++) {

  }
  }
     FastLED.show();
 delay(100);

}

What library are you using?

FastLEDs library. 3.03

If you want to fade all the LEDs form blue to red at the same time, I think you want code like this (explanatory comments embedded)...
#include <FastLED.h>
#define DATA_PIN 6
#define NUM_LEDS 7

#define COLOR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup(){
  FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

}

void loop(){

  // Let's take 256 steps to get from blue to red
  // (the most possible with an LED with 8 bit RGB values)

  for( int colorStep=0; colorStep<256; colorStep++ ) {

      int r = colorStep;  // Redness starts at zero and goes up to full
      int b = 255-colorStep;  // Blue starts at full and goes down to zero
      int g = 0;              // No green needed to go from blue to red

      // Now loop though each of the LEDs and set each one to the current color

      for(int x = 0; x < NUM_LEDS; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
      FastLED.show();

      delay(10);
  }

}

@bigjosh has provided code, so I will provide some plain text logic to explain what you should be doing.
To fade from one color to the next, in this case from Solid Blue (0,0,255) to Pink (Red + Blue, 255,0,255), you need to change the value a little, latch it, then wait before you change the value again. Pseudo code:

rgb = 0,0,255
write rgb
wait X milliseconds
rgb = r + 1,0,255
write rgb
wait X milliseconds
loop until r = 255

At each step, you need to push out the value to the leds before delaying and then starting again. The delay can and should be varied to your satisfaction. I find a fast fade better. At single steps of r + 1, even slow delays will seem mostly smooth.


text:
Looking for circuit diagram for evaluation of a pulsed signal
How can I evaluate a pulsed signal in Arduino? The signal comes from an car alarm system and is called (-) output 200 mA. Arduino and the car have the same GND. Can I attach the output through a resistor to PB0 (D8) or PD5 (D5)?
Alarm system is called Ampire. Probably the same as Viper. I just wanted to read these pulses, but I do not know exactly how I connect this output correctly with Arduino.
This is the description for this Output:

HN1/9 BROWN/WHITE – 200mA (-) Horn honk output: This wire supplies a 200mA (-) output that can be used to honk the vehicle’s horn. It provides a pulsed output when the security system is armed/disarmed and in trigger sequence or in panic mode. In most vehicles with (-) horn circuits this wire can control the vehicle’s horn without adding a relay. If the vehicle has a (+) horn circuit, an optional relay must be used to interface with the vehicle’s horn circuit.

What brand alarm system? When you say (-) output does that mean it is negative? This is a hard question to answer with so little information.

@NickGammon It sounds to me like it might be an open drain output with a current limit of 200mA but that's just wild surmising.

Alarm system is called Ampire. Probably the same as Viper. And yes, the output is negative transistor output with limited current. The system sends certain impulses when the alarm is triggered (panic alarm, full alarm). I just wanted to read these pulses, but I do not know exactly how I connect this output correctly with Arduino.

This is the description for this Output: HN1/9 BROWN/WHITE – 200mA (-) Horn honk output: This wire supplies a 200mA (-) output that can be used to honk the vehicle’s horn. It provides a pulsed output when the security system is armed/disarmed and in trigger sequence or in panic mode. In most vehicles with (-) horn circuits this wire can control the vehicle’s horn without adding a relay. If the vehicle has a (+) horn circuit, an optional relay must be used to interface with the vehicle’s horn circuit.

Can you edit this extra information into the question please? It will look better, as you can put in line breaks, and then the question makes more sense.

I found a user manual at AMPIRE Car Alarm System for High-Speed CAN-Bus.

N1/9 BROWN/WHITE – 200mA (-) Horn honk output:
This wire supplies a 200mA (-) output that can be
  used to honk the vehicle’s horn. It provides a pulsed output when the security system is armed/disarmed
  and in trigger sequence or in panic mode. In most vehicles with (-) horn circuits this wire can control the
  vehicle’s horn without adding a relay. If the vehicle has a (+) horn circuit, an optional relay must be used
  to interface with the vehicle’s horn circuit.
IMPORTANT!
   Never use this wire to drive anything but a relay or a low-current input! This transistorized output can only supply (-) 200mA and connecting directly to a solenoid, motor or other high current device will cause the module to fall

Judging by that this output will sink up to 200 mA. You could conceivably set an Arduino pin to INPUT_PULLUP and let this output drive it low to indicate it is active.
Personally I think I would use an optocoupler, in case there were unexpected voltages on that pin. You would need a series resistor to limit current through the LED in the optocoupler, say 1 k would be about right if you were connecting it to the 12V car system.
Vf = 1.2V (say)
Voltage over resistor = 12 - 1.2 = 10.8 volts
Current through LED = 10 mA
Limiting resistor = 10.8 / 0.01 = 1080 ohms

Now the output of the optocoupler can sink your Arduino pin, which you have configured as input pullup.
Write a test sketch to see what you are getting through it, but a multimeter should probably tell you, if it just flashes it slowly.

Suggested schematic:

Many thanks, Nick! I'll try to implement your suggestions in a circuit diagram.

See amended post with schematic.


text:
help with 7- segment display
I'm playing with a 7 segment display.
The following works on my breadboard:
5V -> 330 Ohm Resistor (same row, row 9)
330 Ohm Resistor -> Com Port (row 9 to row 15)
h led (the dot/row 17) -> ground rail

I get the dot to light up.
However, the following does not light up:
5V -> h led (the dot/row 17)
Com Port -> 330 Ohm Resistor (Row 15 -> row 38).
330 Ohm Resistor to negative rail (row 38 -> negative rail)

I realize that the row numbers are meaningless -- things just need to be on the same row. I've included them to make it easier to visualize.
So basically, if the circuit goes:
5V -> Resistor -> Com, then I can use the ground wire to light up any part I want.
If the circuit goes Com -> Resistor to Ground, I can't use the 5V to light up any part.
I'm not sure why given that all the stuff is in serial?

Because you have a common-anode display and you're trying to use it as a common-cathode display. LEDs, like all diodes, only conduct freely in one direction.

I was just stating to suspect that  -- as it wasn't labeled. Thanks! At least now I won't forget :-).


text:
ESP-01 adapter and logic level converter
I read that I'll need a logic level converter like this to run an ESP8266-01 from the Uno.
But I saw this ESP adapter:
http://www.ebay.com/itm/ESP-01-ESP8266-Serial-Wi-Fi-Wireless-Adapter-Module-3-3V-5V-Compatible-Arduino-/282524471281?hash=item41c7c54ff1:g:wp0AAOSwQ59ZaClP
Two questions:

The ESP-01 has 8 connections but this has only 4, how come? Will I get the same functionality?
If I'll use this adapter, then I won't need the logic level converter?

"with an integrated logic level converter like the wemos d1 mini" ... please show me the schematics and point to the logic level converter.

My electronic background is limited, but with the wemos you don't need any logic converter for the ESP so I can only assume that it's built in. @yeti

I'll just move this to a comment: save yourself time and get an ESP module without any extra parts like the wemos d1 mini.

The ESP-01 is a microcontroller that works only with 3.3V. If you don't use a logic converter, it will not work correctly with 5V on TX and RX and you might even damage your module if you use it like that. So answering your second question, the important thing to keep in mind is that you need to power it with 3.3V and the logic level of the data you send must also be 3.3V.
As for the number of pins, the 4 pins are for VCC, GND, TX and RX. These are the only ones you'll need to connect with Arduino. The other pins on the ESP-01 are CH_PD, RST and two GPIOs.
(I'm not sure if you need to connect any of these while using it with Arduino, but in my experience using it standalone i know CH_PD must be connected to VCC in operation mode, and RST must be connected with GND on flashing mode.)

I used in one of my projects, instead of a logic level converter, some voltage dividers on the pins, Arduino inputs don't mind the 3.3v, it works just the same.


text:
Reading from a KY-040 rotary encoder with Digispark
I have a rotary encoder KY-040 connected to a Digispark like this:

CLK go to p0 and and DT go to p2, SW is disconnected for now (it's just a button).
I did everything like the instructions here: http://henrysbench.capnfatz.com/henrys-bench/keyes-ky-040-arduino-rotary-encoder-user-manual/
#include <DigiKeyboard.h>

 int pinA = 0;  // Connected to CLK on KY-040
 int pinB = 2;  // Connected to DT on KY-040
 int encoderPosCount = 0;
 int pinALast;
 int aVal;
 boolean bCW;

 void setup() {
   pinMode (pinA,INPUT);
   pinMode (pinB,INPUT);
   /* Read Pin A
   Whatever state it's in will reflect the last position
   */
   pinALast = digitalRead(pinA);
   Serial.begin (9600);
 }

 void loop() {
   aVal = digitalRead(pinA);
   if (aVal != pinALast){ // Means the knob is rotating
     // if the knob is rotating, we need to determine direction
     // We do that by reading pin B.
     if (digitalRead(pinB) != aVal) {  // Means pin A Changed first - We're Rotating Clockwise
       encoderPosCount ++;
       bCW = true;
     } else {// Otherwise B changed first and we're moving CCW
       bCW = false;
       encoderPosCount--;
     }
     Serial.println("Rotated: ");
     if (bCW){
       //Serial.println ("clockwise");
       DigiKeyboard.sendKeyStroke(KEY_V); //or DigiKeyboard.write("1");
     }else{
       //Serial.println("counterclockwise");
        DigiKeyboard.println("cc");
     }
     Serial.print("Encoder Position: ");
     Serial.println(encoderPosCount);

   }
   pinALast = aVal;
 }

I only changed the pin numbers in the code and the Serial.println (... to any of the following:
DigiKeyboard.write("1");
DigiKeyboard.println("1");
DigiKeyboard.sendKeyStroke(KEY_V);

All of them didn't do anything when rotating the knob...
Any ideas?
Maybe the 10K resistors are too much?

This might help: https://github.com/Bluebie/volume_knob/blob/master/volume_knob.ino

Shown below is a KY-040 test program that in my tests doesn't lose any counts and is more accurate than some other software; it picks up the counts between detents as well as those at detents.  You may be able to adapt it to your DigiKeyboard ATtiny system.
/*  roto_jw4.ino -- JW, 29 September 2015 --
 *  A 4-state state-machine implementation of rotary
 *  encoding for KY-040 rotary knobs.  The state-machine picture at
 *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
 *  in a Feb 4, 2014 7:40 PM post by Anthony Seely shows counts
 *  increasing on transitions 10 -> 11 -> 01 -> 00 -> 10 and
 *  decreasing on transitions the other way.  Transitions between 00
 *  and 11 or 10 and 01 are invalid.  This code detects valid
 *  transitions by (abOld xor abNew) equaling 1 or 2.  It detects
 *  up-count events by the tri-bit value ABA' (where A' is the new
 *  reading on pin A) being equal to 1, 2, 5, or 6 (a bit mask of
 *  0x66), and down-count events by ABA' being equal to 0, 3, 4, or 7
 *  (a bit mask of 0x99).
 *
 *  On a KY-040 unit I tested, there are 30 detent positions per turn.
 *  With this unit the code generates 60 counts per turn, which can be
 *  seen individually as one turns the rotor slowly.  Odd counts
 *  appear between detents, even counts at detents.
 *
 *  Set quadrature-signal pin numbers, via PinA and PinB constants.
 *  Set IPINMODE to INPUT_PULLUP if there are no external pull-ups
 *  on encoder AB pins, else set IPINMODE to INPUT
 */
enum { PinA=2, PinB=3, IPINMODE=INPUT };

static  byte abOld;     // Initialize state
volatile int count;     // current rotary count
         int old_count;     // old rotary count

void setup() {
  pinMode(PinA, IPINMODE);
  pinMode(PinB, IPINMODE);
  attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
  attachInterrupt(1, pinChangeISR, CHANGE);
  abOld = count = old_count = 0;
  Serial.begin(115200);
  Serial.println("Starting Rotary Encoder Test");
}

// On interrupt, read input pins, compute new state, and adjust count
void pinChangeISR() {
  enum { upMask = 0x66, downMask = 0x99 };
  byte abNew = (digitalRead(PinA) << 1) | digitalRead(PinB);
  byte criterion = abNew^abOld;
  if (criterion==1 || criterion==2) {
    if (upMask & (1 << (2*abOld + abNew/2)))
      count++;
    else count--;       // upMask = ~downMask
  }
  abOld = abNew;        // Save new state
}

void loop() {
  if (old_count != count) {
    Serial.print(millis());
    Serial.print("  ");
    Serial.println(count);
    old_count = count;
  }
}

Since some ATtiny's only have one external-interrupt pin, it may be necessary to use two pin-change interrupts instead of two external-interrupt pins.
(Six of the pins on an ATtiny45, for example, support pin-change interrupts, and only one is an external-interrupt pin.) Change PinA and PinB to appropriate pin numbers, and replace
  attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
  attachInterrupt(1, pinChangeISR, CHANGE);

with
  enableInterrupt(PinA, pinChangeISR, CHANGE); // Set up pin-change interrupts
  enableInterrupt(PinB, pinChangeISR, CHANGE);

and add the following #include near the beginning:
#include <EnableInterrupt.h>

To install the .h file for use via the Arduino IDE, unpack an EnableInterrupt zip file (for example, enableinterrupt-0.8.2.zip from bintray.com/greygnome) in the directory ~/sketchbook/libraries.  I think the package works with ATtiny's as well as more-standard Arduinos.

This is the only code so far worked for me. All the others caused erratic outputs at some encoder ticks. How to adjust this code so to have only one count output for each tick. I mean your code outputs two consecutive numbers for each tick like this for example for 5 ticks I get: 12 34 56 78 910 But I want to get 1 2 3  4 5. How can I do that? Thanks in advance.

@user16307, There are several ways; which is best depends on intended use.   You can:  • Divide count by 2 before using it  • Use the count only if (count&1), or !(count&1), ie, only when odd (or even) • In ISR, instead of count++ say icount++, where icount is a static internal counter, and then say, count += icount&1, or count += 1-(icount&1) to increment  count only when icount is odd (or even); and similarly for the count-- case.  Please let me know if you find bugs in any of these approaches if you try them.  Thanks!

@JamesWaldby-jwpat7, your answer is so great! It helped me with proper values from the encoder. Please, could you explain pinChangeISR function? I am new to cpp and I would like to understand it. I understand that there are bit operations and shifts, but explanation would be great. thank you

@Dawe, I will edit the answer next week to add some detail re pinChangeISR.  For the moment, refer to the comments in the first paragraph of code and to the referenced state machine diagram

 int pinA = 0;  // Connected to CLK on KY-040
 ...
   Serial.begin (9600);

Hardware Serial uses pins 0 and 1. I would try other pins. (Oh, it's an ATtiny - well I'm not sure about HardwareSerial on that, but it looks suspicious).
See my page about rotary encoders for more ideas.

I only changed the pin numbers in the code and the Serial.println (... to any of the following:

Maybe post the code you actually used, that would be helpful. Not some code you didn't use.

Maybe the 10K resistors are too much?

No, that looks fine.

This is the code I used, the only difference was with changing the Serial.println (... to other things as I mentioned.
On the digispark p3,p4 are used for usb communication, p5 is the reset and p1 is connected to the led so I'd have to add a resistor, so p0 and p2 are only really free ones to use.

So you left the Serial.begin in? I can't help you without seeing your code, maybe someone else can.

Yes, I edited the question.

... the only difference was with changing the Serial.println (... to other things as I mentioned. - not really: Serial.println(encoderPosCount);

That was in the original code too.

The Serial.println stuff doesn't do anything since the digispark doesn't have a serial com port nor serial to usb converter.

I would not personally be calling a function that cannot do anything useful, as you acknowledge. For all you know it is doing something to one of the ports which stops it doing what you want.

Nick, while your page about rotary encoders is interesting and informative, both of the programs there tend to lose a lot of counts, eg 2 or 3 out of 30 per turn for the single-interrupt-line version, and 1 or 2 per couple of turns for the two -interrupt-line version.  Also, both of them only see half of the countable transitions.  I'll post a version below that doesn't lose counts, is twice as accurate, and about the same amount of code.


text:
Timer1 firing immediately
I'm trying to use Timer1 to get fired once a certain event occurs (about 1ms after the event). Using the timer to get a periodic interrupt works fine, but the very first interrupt fires immediately, rather than after the time I want it.
#include <Arduino.h>

void setup() {
  Serial.begin(115200);
  Serial.println("start");
}

#define ENTRIES 5
long stack[ENTRIES+1];
int ctr = 0;

ISR(TIMER1_OVF_vect) {
  cli();
  TCNT1 = 50000;

  // if (micros() - stack[0] < 500) return; // work around guard would skip stray 1st interrupt

  stack[ctr++] = micros();

  if (ctr > ENTRIES)
    TIMSK1 &= ~(1 << TOIE1);

  sei();
}

void loop() {
  if (ctr > ENTRIES) {
    for (int i = 0; i < ENTRIES-1; i++) {
      Serial.print(i);
      Serial.print(": ");
      Serial.println(stack[i+1] - stack[i]);
    }
    ctr = 0;
  }

  if (!Serial.available()) return;
  char c = Serial.read();
  if (c == 't') {
    Serial.println("testing");

    stack[0] = micros();
    ctr = 1;
    cli();

    TCNT1 = 64000; // tick in around 1ms
    TCCR1A = 0;
    TCCR1B = (1 << CS10); // no prescaler
    TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt

    sei();
  }
}

When you enter t on the console it enables the interrupt and - unexpectedly - the timer fires at once. The next one comes after 1ms. A sample output looks like
start
testing
0: 8
1: 980
2: 980
3: 980
testing
0: 8
1: 980
2: 980
3: 980

Uncommenting the guard yields
start
testing
0: 988
1: 972
2: 976
3: 976

How can I modify my code (except setting a guard in the beginning of the ISR) so it is triggered once AFTER 1ms.

Interrupt flags are set even without interrupt enable flags, so there is pending overflow that you didin't cleared. And guess what happens after enabling TOIE1 flag. It gets handled by ISR. That's on behalf of Arduino's analogWrite() PWM outputs (all timers are up and running in 8bit mode and 1.024ms period).
Btw global interrupts are disabled and reenabled inside of ISR handler by hardware so you shouldn't have cli() and sei() in it.
Also there is another issue - counter mode is preset to 8bits and much bigger prescaler, so the first round is way off.
void setup() {
  Serial.begin(115200);
  Serial.println("start");
}

#define ENTRIES 5
long stack[ENTRIES+1];
int ctr = 0;

ISR(TIMER1_OVF_vect) {
  TCNT1 = 50000U;
  stack[ctr++] = micros();
  if (ctr > ENTRIES)  TIMSK1 &= ~(1 << TOIE1);
}

void loop() {
  if (ctr > ENTRIES) {
    for (int i = 0; i < ENTRIES-1; i++) {
      Serial.print(i);
      Serial.print(": ");
      Serial.println(stack[i+1] - stack[i]);
    }
    ctr = 0;
  }

  if (!Serial.available()) return;
  char c = Serial.read();
  if (c == 't') {
    Serial.println("testing");

    stack[0] = micros();
    ctr = 1;

    TCCR1A = 0;           // you have to change the timer mode before changes
    TCCR1B = 0;           // stop the timer
    TIFR1 |= _BV(TOV1);   // clear the overflow interrupt flag by writing 1 to it
    TCNT1  = 50000U;      // tick in around 1ms / this makes more sense if it's set correctly
    TCCR1B = _BV(CS10);   // no prescaler ?????  REALLY???? this one is prescale by 8
    TIMSK1 |= _BV(TOIE1); // enable timer overflow interrupt
  }
}

That looks like a live saver :-) Too tired now, but will check this tomorrow! Thanks

That got me wake and it's exactly what I was looking for. Thanks also for the info about the interrupt handling :-)

Ah, and one remark about the remark: The compiler knows that TCNT1 is an unsigned and will coerce literal numbers correctly. So TCNT1  = 50000; works as well.

@thomaskilian it wasn't about signess. More likely about previous setting by Arduino. You were using the value 64000. Anyway it's better to use unsigned literals especially for bit shifts.

64000 < 64k = 64512


text:
connecting RTC DS1307 to ethernet shield
What is the easiest way to mount DS1307 to ethernet shield?
I tried to do this:
https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/wiring-it-up
but my program just freezes when I try to read data from RTC. Is there any other ways to do it?
Code looks like this:
const int RTCpin2 = 2;
const int RTCpin3 = 3;

void setup() {
    pinMode(RTCpin2, OUTPUT);
    pinMode(RTCpin3, OUTPUT);

    analogWrite(RTCpin2, LOW);
    analogWrite(RTCpin3, HIGH);
}

void loop() {
     // process RTC time
}

What do you hope to achieve with that code?

this is not the whole code, is bunch of other things too, so I need ethernet shield and then RTC mounter to it.

Yes, but what do you hope to achieve with that code that you have shown? What do you think it will do?

5V to pin3, reading with pin2?

Nope, you couldn't be more wrong. I assume those pins are supposed to power the RTC? Well, first you are using the wrong pins, and secondly you are using the wrong functions.

I assume that snippet of code is supposed to provide the +5Vand GND for powering the RTC module.  Well, there's two fundamental flaws with it:

Pins 2 and 3 are the DIGITAL pins, not the analog pins. Instead you want to be using pins A2 and A3.
analogWrite controls the PWM output on pins that support PWM. HIGH is 1, so analogWrite will be providing a 1/255 duty cycle PWM signal on that pin.

So to fix it:

Use pins A2 and A3 instead of 2 and 3
Use digitalWrite() instead of analogWrite().


text:
Arduino Skill Stop Push button error
I made a skill stop game from Arduino Uno and a pushbutton.Here is the code:
byte led_one=2;
byte led_two=3;
byte winner_led=4;
byte led_four=5;
byte led_five=6;
byte pushbutton=12;
byte score=0;
int pushbutton_value=digitalRead(pushbutton);

void setup()
{
// put your setup code here, to run once:
   pinMode(led_one,OUTPUT);
   pinMode(led_two,OUTPUT);
   pinMode(winner_led,OUTPUT);
   pinMode(pushbutton,INPUT_PULLUP);
   pinMode(led_four,OUTPUT);
   pinMode(led_five,OUTPUT);
   Serial.begin(9600);
  }

void loop()
{
// put your main code here, to run repeatedly:

  for (int x=1;x<=6;x++)
  {
    digitalWrite(x,HIGH);
    delay(250);
    digitalWrite(x,LOW);
    delay(250);
    if(pushbutton_value==HIGH && x==winner_led)
    {
       score+=500;
    }
    else if(pushbutton_value==HIGH && x==led_one)
    {
       score+=100;
    }
  }
 Serial.println(score);
}

My Problem is that Whenever I push the button The Serial Monitor is printing out the wrong score

It'll even notice that push button is pressed? I wonder how - the only reading is in pushbutton_value initialization. Also if you have INPUT_PULLUP, you should be checking for LOW as button should be switching ground.

LOW not working too

Well, more specifically: Where do you read the current state of the push button?

To the pushbutton_value variable

And when this digitalRead happens?

What do you mean

This happens once after the reset: int pushbutton_value=digitalRead(pushbutton);. Never ever again (except if you reset the MCU).

What should the score be? How do you want the scoring work?

The initialization of int pushbutton_value should be done after the IO has been stetted (in the void setup() after pinMode(pushbutton,INPUT_PULLUP);)

I wonder why you initialized score as byte! Change it to int. As you can see when you Serial Print your score value doesn't cross 256 because the largest value a byte can have is 256 but you are summing score to 500

Hmm after I did this It still isnt working

digitalread your pushbutton_value in the loop, and whats was the output before..its still not crossing 256?

it is 0 now. What should I dp?

Could you please spoon feed me the code

How to predict the score without counting the number of pushbutton_value==HIGH recorded for the x==winner_led and x==led_one events ? Add 2 integers counters to follow those events.


text:
digitalRead(A0) returns true when A1 is HIGH
I have an Atmega328P-AU with 16Mhz crystal(schematics). And its analog pins A0 to A3 are connected to button inputs.
All these pins are pulled-down(10K res). And in code, I have digitalRead(A0) to digtalRead(A3).
When I press button attached to A3 and A2. They works as they should. But when I press any button attached to A0 or A1, both their digitalRead() returns true.
I checked 3 times, all resistors and buttons wires are well connected and are not shorted.
Here is test code
void setup()
{
    Serial.begin(9600);
    pinMode(A0, INPUT);
    pinMode(A1, INPUT);
    pinMode(A3, INPUT);
    pinMode(A2, INPUT);
}

void loop()
{
if (digitalRead(A0))
    Serial.println("A0");
if(digitalRead(A1))
    Serial.println("A1");
if (digitalRead(A2))
    Serial.println("A2");
if (digitalRead(A3))
    Serial.println("A3" );
delay(400);
}

Here are outputs.
When pressed A0
A0
A1

When pressed A1(same result)
A0
A1

When pressed A2
A2

When pressed A3
A3

I'm wondering what could be causing this problem ?
Edit:
Test

When I press A1 button, the A1 pin is high with 4.8V as well as A0
pin is high with 2.6V to 3.8V.
When nothing is pressed, A1 has 180mV while A0 has -180mV.

simulate this circuit – Schematic created using CircuitLab

Have you actually checked the voltage on the A0 & A1 inputs when their switches are pressed, and only 1 of them goes high? Because this sounds like a short between A0 & A1...

Just to point this out too, but when both A0_SW, A1_SW are pressed R1, R2 go into parallel where they can be seen as a single 5k resistor.

Assuming you've not activated any ADC functionality in your Arduino code (i.e. assuming the sample code you've posted here is 100% what you've tried, and no analogReference(); statement), then I still think your problem is a partial short between AO & A1.  If my above assumptions are not the case, then there are other possibilities.
With a 5.0V Vcc rail, anything more than 0.5Vcc (i.e. 2.5V) will register as a high/1 (datasheet section 30 - Electrical characteristics, 30.2 DC Characteristics), so based on the measurements you posted to the edit of your question, your code is indeed correctly reporting a 1 on A0 when you push A1 button.
But it's only barely a 1/high, and as you've said, it varies from 2.6 to 3.8, another classic sign of a soldering or partial short circuit somewhere.
If you're able to remove the '328 from the circuit, use your multimeter to read resistance between A0 & A1.  Also try a new/different '328, maybe you damaged one of its input in the past.

I recreated this experiment on my Arduino and it worked like it should. This should work the way you want it to. The only thing I can think of is maybe the chip possibly being partially fried or the pullup resistors not being adequet (not having a low enough resistance) for the job. The resistors I used are 1k. Other than that there is not much else I can think of.

Ok so it could be a number of factors.  You are sure that the pins are 5V tolerant in the mode you're using?  It's possible to burn out pins if they don't have internal current regulation.  You said analog pin which is weird since a button will cause lots of debouce, but it looks configured digital.  Debounce is still an issue on digital circuits with buttons.

First of all, I did not down voted you. I never do, unless the answer is very stupid and needs to be deleted.

And how would I be sourcing current if pin is set to be INPUT only.

Yes, I've read those 10 ways. None of them are true in my case. I haven't done those things. Beside I do believe the uC has gone bad.

I mean the most common way for it to go bad is abuse of the specs.  At some point you probably exceeded the capabilities of the pin.  You are right that in "INPUT" mode the pin is a high-z so it shouldn't draw too much current.


text:
Can't upload sketches to breadboard Arduino

I have an ATmega328 chip with the boot-loader installed.
I also have an Arduino Uno with the ATmega328 chip removed.
I hooked this chip up to a breadboard with the proper 22pF caps, 16MHz crystal, and 10kΩ pull-up resistor.
The LED flasher was loaded prior, and this works fine when I hook an LED and resistor up to pin 19. I have confirmed my external crystal works by disconnecting it, and the flashing stops, when I reconnect the crystal, the flashing continues.
Power is fed from my Arduino Uno 5 V out to the DIY Arduino
I connected the reset wire, and data wires, ensuring pin 2 went to RX and pin 3 to TX.

In the software
First to confirm everything works, I removed the chip from the breadboard and placed it in the Arduino. The sketch uploaded successfully using the settings:  Arduino Uno as board and AVRISP mkll as programmer.
Now I move the chip to the breadboard, and ensure all the wires are connected. The LED starts to blink again, but when I try to upload the sketch, I get an error:
avrdude: stk500_recv(): programmer is not responding
I ensure continuity between the reset, TX, RX, and power connections and try different settings like Arduino as ISP and different boards under settings including the Duemilanove and nano but nothing seems to be working.
Any suggestions on what to try next?

So you have 5 wires, right? 5V, Gnd, Tx, Rx and Reset? Stick to the Uno in the boards menu, after all it worked as a Uno when plugged in, didn't it? Can you post a photo please?

5 wires, works when chip is plugged into the socket.

Never mind, found the problem. My software switched to the bluetooth for some reason after I changed some other settings. Hate when the simple things always get me

Answered by Skyler440:

Never mind, found the problem. My software switched to the bluetooth for some reason after I changed some other settings.

Converted to answer to reduce unanswered questions.

@ChetanBhargava : Removed request. However is their a link for that assertion?

well, on raspberry pi SE, I did same thing and I was told my a mod not to do that. That was a while back on a chat session.

Found it here

There are two AVR ICs present on the Arduino board, one is used for the USB to ICSP interface and the other one is the μC which you're using.
As I've noticed that you've tried to connect Tx and Rx pins including reset for programming the IC. Those pins are used for communication on serial protocol, where as the AVR in Arduino is programmed using SPI Protocol, so you should be using MISO, MOSI, SCK, SS (they're pins 13-10 respectively) and Reset pins on the Arduino, then the AVR which is used as USB-SPI bridge for programming can communicate with the μC and program it.