PFC8574 4x4 keypad: correct wiring? I bought a few PFC8574 and 4x4 keypads for a small project. I'm unclear on the correct wiring of the keypad to the PFC8574.

On the Arduino Playground's site, there are pull-up resistors for each column, but on a few other sites (like this one that I can't read, but I understand a schematic and there's a third example too, but I don't have the reputation to post it), the wiring does straight into the IC.

Does it depend on the library that's being used?  Or what am I missing?

Thanks!

Ok look at this image:

I'm not sure how your keypad is layed out but if you use a probe pin to test your connections via a multimeter, you can mark which ones correspond to the image.

I am ASSUMING you are going to use the code from arduino playground.

This is the format:

Pins of keypad (IN THE IMAGE) - Pins of PFC8547

Here are the pin connections:

1 - nothing

2 - 9

3 - 4

4 - 6

5 - 7

6 - 10

7 - 11

8 - 5

Also include the pull-up resistors.
Your ABCD keys will be ignored

(This is like wiring a bomb...)


How to convert the 0-5V to a 4-20mA current loop? I'm pretty clueless about electronics so everything has to be explained in simple terms to me.

I have an Arduino with a program which provides a value via the Analog output, so that is anything from 0-5V.

On the other side I have a PLC (programmable logic controller) with an IO card which allows to connect to a (4-20mA) current loop.

How do I convert from lets say 1-5V to the 4-20mA in a somewhat cheap and safe way (I don't want to destroy the PLC [and possibly the Arduino])?

Of course the Arduino and the PLC have separate power sources.

If all you need is analog 4-20mA loop transmitter, then you need an op-amp, the transistors that its output drives, a sense resistor, and a few other resistors. Note that these are at least 1% resistors. This needs to be built on a printed circuit board, not a solderless breadboard.  Two of my coworkers at Maxim Integrated wrote an applications note about a 4-20mA current-loop transmitter: http://www.maximintegrated.com/en/app-notes/index.mvp/id/5610  see this figure:

Since you are already using a PWM (hopefully with an RC low-pass filter), you just need everything after the DAC output. (Performance will not be as good with an Arduino PWM as it would be with a 16-bit voltage-output DAC, but the general idea would still work.) For your purpose, you can also ignore all of the stuff about the HART modem -- that's an extra feature for sending digital information along the same loop. Only relevant if your PLC receiver was expecting it.

There are also numerous prebuilt 4-20mA transmitter boards available, this has been around many decades in the industrial control market. Since Maxim Integrated makes precision DAC chips, we don't make reference designs that take 0-5V (especially from a PWM!) and convert to 4-20mA -- but we do sell reference design boards that include the DAC. Such as our Monterey system board (MAXREFDES15#). http://www.maximintegrated.com/en/app-notes/index.mvp/id/5683

There's also a 4-20mA Current-Loop Transmitter from ti.com, XTR117: http://www.ti.com/lit/ds/symlink/xtr117.pdf

There's also a board from mikroElektronika, MIKROE-1296 (available through mouser.com) that uses an Analog Devices DAC (through SPI interface) to drive the 4-20mA transmit circuit. Again, this is an idea that's been around many decades, so a search for 4-20mA transmitter should yield lots of useful information.

So your best bet is probably to purchase one of these prebuilt 4-20mA transmitter boards, which most likely will include its own precision DAC. You'll have to modify your Arduino code to drive the SPI interface, specific to whichever DAC you end up using. Or, if you really want to use the PWM to drive 4-20mA (at reduced performance), be sure to at least use an RC low-pass filter to get it as close as possible to a stable DC level.


Will 5V to input pin damage the Arduino board? I am fairly new to Arduino. When I am experimenting with circuits, do i need to worry about shorting out a pin if I accidentally connect the +5V pin on Arduino to an input pin on Arduino without a resistor? I just want to make sure I avoid destroying the board when learning how to create circuits.

No, no short. Arduino (Atmega) pins default to inputs. Pins configured this way are said to be in a high-impedance state. Input pins make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 megohm in front of the pin.

Answer provided by Look Alterno and converted from a comment.


GPS: Not receiving any valid output from ATGM336H I have an Arduino Pro Mini along with a GPS Unit - ATGM336H. Below is the sketch I'm currently using:

#include <SoftwareSerial.h>
#include "Ublox.h"
SoftwareSerial GPS(4,5);
Ublox serial_gps;

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

void loop(){
  while(GPS.available()){
  char c = GPS.read();
  if(serial_gps.encode(c)){
  Serial.println(serial_gps.longitude);
    }
  }
}

I'm able to receive NMEA stream from the GPS Unit and parse (tried TinyGPS++, TinyGPS and Ublox) the stream but the data is not valid nor does it ever change. I've read that this GPS unit can take up to 32 seconds to get a fixed position and deliver valid co-ords but I cannot receive any.

Is there anything obviously wrong with my sketch or hardware setup?

Any and all help would be greatly appreciated!

while(GPS.available() > 0) {....

Also is the GPS unit outside?


Problem updating Arduino WiFi Shield's Firmware I'm using Arduino Uno R3 and the official Arduino WiFi Shield R3. I'm trying to update the Shield's firmware to 1.1.0 through this guide.

Everything goes fine until Step 9. When I execute the code in Step 10, I get an error (see attachment) as:

AtLibUsbDfu: 3EB 2FF8 no device present

FAIL Could not open USB device.

ISP done.

EDIT: I re-installed the firmware on my shield and now the problem's gone.

I cant comment because of reputation... You've already upgraded the firmware. Just when you try upgrading again your wifi device is rebooting itself because of upgrading before.


Arduino/Arduino clone board suggestions I am planning to buy a Arduino board. I am also considering Arduino clones, too. My requirements are that the board should inbuilt communication modes like Ethernet, WiFi and a SD card slot, too. Also the board should have a decent amount of memory and the processor must be a a little more powerful than the Uno. The board must be capable of running a OS if possible!

I was looking at the Yun and Due. The Yun has all the communication modes but runs on a low end processor. The Due on the other hand runs on a ARM processor but has none of the communication modes. So now I am in a fix.

Which board should I choose?

I would go with a Yun. Despite having a low end CPU, it runs at 400MHz and the disk space can be expanded using the uSD card (see this blog post).

If you don't plan to make CPU intensive tasks (such as real time video streaming and manipulation), the Yun is a nice tool. Otherwise, the Tre fits better (however, at the time of writing, it still has to be released).


Stepper motor driver not working properly I have a problem. I am following this guide about controlling a NEMA 17 stepper motor: https://www.makerguides.com/a4988-stepper-motor-driver-arduino-tutorial/
I uploaded the code to my arduino uno and powered on everything, but the stepper motor doesn't rotate, except when I put my finger on the metal screw of the a4988 driver. The arduino is powered by a 5v 1A adapter and the a4988 driver is powered with a 12v 2amp adapter.
What is causing this?

The "metal screw" is a "trim potentiometer" that is used to set the current used to drive the motor. It sounds like you may be altering the current when you push against it. Try turning it to different angles to see what effect that has on the motor.
Alternatively if it only ever works when you push on it then it could be that you have a faulty potentiometer on your board.


Is SoftwareSerial left out for the ATTiny85/84? I want to use SoftwareSerial with my ATTiny85 and when I google it several projects claim that they are using it... I downloaded the hardware from https://code.google.com/p/arduino-tiny/, but when I try to add SoftwareSerial and compile I get:

fatal error: SoftwareSerial.h: No such file or directory

Switching the board to UNO makes the problem go away, so did they leave it out? How can I fix this?

Short answer - no. It's not left out, on the contrary.

But before addressing to the compiler error you mentioned, a small clarification:

  I downloaded the hardware from https://code.google.com/p/arduino-tiny/

The link you provided is not hardware, but software called the ATtiny core files. It contains the necessary files that will help you compile and upload code from Arduino IDE to the ATtiny (even when using ArduinoISP as programmer).

The SoftwareSerial is a library that comes with the Arduino IDE zip/installation. If you have downloaded the latest version of Arduino IDE from the Arduino Website, you should be able to find the SoftwareSerial library files located at:

[Path to Arduino installation folder]\libraries\SoftwareSerial

Example for SoftwareSerial library files you should expect to find there are SoftwareSerial.cpp and SoftwareSerial.h.

  fatal error: SoftwareSerial.h: No such file or directory

The compiler error you receive seems to imply that the compiler cannot find the header file (SoftwareSerial.h) for SoftwareSerial library. This indeed seems quite odd, since this library does not require any special installation, and as mentioned, is part of the libraries that are built into the Arduino IDE installation.

So, to mitigate this, I would recommend that you will:

Make sure the library folder exists in the location mentioned above
If it doesn't, then you should probably re-download the Arduino IDE installation, and after that install the ATtiny core files as per the instructions (important!). Installation instructions are located in the README file inside the ATTiny core zip file
(tiny\avr\README).
If it does exist, and you still get this compiler error, then you must have a corrupted installation (perhaps the compiler include folders is messed up). I would still recommend following the re-installation as mentioned in the previous bullet.
Make sure that you can find the ATtiny 85 in the board list, at Tools->Board and that it is selected.
Another angle that might shed more light on this error, would be to turn on the verbose output for the compiler (you can do it in the Arduino IDE, by choosing File->Preferences-> "Show verbose output during" and checking "compilation"). Verbose output can help you track down any compiler command line errors, like missing include folders.
Last but not least, if the SoftwareSerial folder exist, you could use the Arduino IDE to check if the IDE can identify its existance, by going to Sketch->Import Library, and looking for SoftwareSerial. If it's not there, then the folder is not located properly under the 'libraries', verify the path as mentioned above (did you move it?)

Finally, when you will be able to compile your code, try using the SoftwareSerial example that comes with the library to check it. Note that it is not going to work 'out-of-the-box' as with the Arduino Uno; The ATtiny does not have the same FTDI hardware for communicating directly with USB, so for sending and receiving serial messages using the ATtiny you will have to either use the Arduino Uno as a proxy (using the Uno's pins 0 & 1) or to use dedicated USB to Serial hardware similar to this one.

  Switching the board to UNO makes the problem go away

As a side note, switching to the Uno will make most ATtiny problems 'go away' since the Uno is much more equipped than ATtiny85/4, both on the MCU level and on the breakout board level, which you get with the Uno (and which you don't get when working directly with a chip like ATtiny). Also, most of the code base out there is targeting the Uno and not ATTiny.
So if you are doing your first steps with the ATtiny, be prepared that many things that 'just worked' with the Uno will require extra/different code before they could work with the ATtiny (and some won't work at all).

You can use my simple Analog to Serial code :

/*
Takes an input on the AtTiny85 from the VERY TRICKY analogue input pin 2 (as labeled in HLT tutorial)
 and outputs these with Software serial to the arduino uno, or Duemillanove
 Hookup
 ATTINY85 pin 3 -> Arduino Uno pin 0
 ATTINY85 pin 4 -> Arduino Uno pin 1

http://www.instructables.com/id/Easy-ATTiny-Serial-Communication-with-Tiny-AVR-Pro/
 */

#include <SoftwareSerial.h>
// Definitions
#define rxPin 4
#define txPin 3
SoftwareSerial mySerial(rxPin, txPin);
int sensorPin = 7; //ACTUALLY PIN LABELED AS "2" on the HLT tutorial
int sensorVal = -1;

// the setup routine runs once when you press reset:
void setup() {
  pinMode(sensorPin, INPUT);
  mySerial.begin(9600);
analogWrite(0,1); // This is kind a heart beat to show the ATTINY is "alive"
}

// the loop routine runs over and over asensorpingain forever:
void loop() {
  sensorVal = analogRead(sensorPin);
  mySerial.print("Input Val: ");
  mySerial.print(sensorVal);
  mySerial.println();
}


Changing the brightness on a Hitachi HD44780 LCD screen I am finishing up a project- an LED game alarm clock. Seeing as this is a clock, I need to have a way to conserve power, which right now my Uno R3+ is eating up like a politician. My question is, how do I turn the screen off, or turn the back-light off using software only on a Hitachi HD44780 16x2 LCD screen? Or how do I set a sleep mode on one component? The way I plan on turning it off is with an ultrasonic range finder, if I get close it turns on the screen. If anything I say doesn't make sense, ask me to clarify, I'm in a bit of a rush.

Place a transistor in series with a 33R resistor between the LCD pin 16 (backlight ground) and GND and switch the transistor on and off with a digital pin. That way you'll be able to turn the backlight on and off.

You can have a finer control over brightness if you put a PWM pulse on said pin. Just call analogWrite(D3, value) where value is the desired brightness.

The schematics is below. It's from Freetronics 16x2 LCD SHield.


Methodology for designing/prototyping LED patterns Several of my projects go through this time-consuming and tedious phase:

design a LED pattern for a geometry of WS2812 LEDs
implement it with e.g. FastLED
write to Arduino and see results
goto step 1

The second step, implementing different ideas in C with FastLED (or similar) takes a lot longer than I'd like it to. How is this step usually solved? Are there higher-level software solutions? Specialised idea-testing hardware?

I'd like to easily try out ideas such as "what if these four LEDs blinked magenta every second, while a gradient was cycling around the gradient over here".

For designing patterns for visual evaluation, it would be better to just have the arduino/controller be a pass-through from something like a full computer. There is a project called FadeCandy, which allows one to send various patterns to a WS2812 chain using a protocol called Open Pixel Control.

Some options would be to build or buy a FadeCandy board, or to implement the OPC protocol on your own arduino so that you can play around with test patterns and designs in a rapid development environment like Python or just making the raw patterns in a file and dumping that to your device over the serial port or TPC, etc.

Once you have your patterns or design the way you want it, then you can translate it to C code and FastLED, knowing you have a fixed specification you are trying to implement, rather than reflashing an arduino for every iteration.


Why does my code treat my sound sensor as if it's always HIGH I have a sound sensor that was working perfectly fine as I was using it as a clap sensor to turn lights on and off. However, I tried to change the code to make it work a little smoother and for whatever reason it stopped working. I then tried to write a very simple script to allow it to turn on and off using just one clap but now it treats the sound sensor as if it's always inputting HIGH. Any ideas why this might be happening?

note: I've turned up the sensitivity and can see that the sound sensor isn't always HIGH. Even when it's too high to hear me clap it still turns the LED on and off as if the if statement below was always true.

int SENSOR = 2;
int LED = 13;

void setup() {
  // put your setup code here, to run once:
  pinMode(LED, OUTPUT);
  pinMode(SENSOR, INPUT);
}

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

  if(digitalRead(SENSOR) == HIGH){
    digitalWrite(LED, (digitalRead(LED) == HIGH ? LOW : HIGH));
    delay(100);
  }
}

This is the sound sensor module I am using: Robojax Sound Detection Microphone Module

The robojax microphone switch I was using outputs LOW when it senses a sound rather than outputting HIGH as I assumed. The solution was just to replace all the if statements testing for a HIGH input with LOW.

note: sorry about not looking into the microphone earlier.


How to measure the supply voltage of Arduino without using an analog pin I'm using Arduino Nano to measure temperature with a 10 kohm thermistor and a voltage divider. My problem is I'm getting only 4.2V on the 5V pin. The power is supplied via a USB cable from a desktop PC.

I measured the output voltage of a USB port on the PC and it was around 4.5V. It doesn't look normal. So I suspect the power supply unit of the PC is not strong enough.

But it still makes sense to measure the voltage at the 5V pin since there is no guarantee it's exactly 5V. Its error will affect the calculated resistance of the thermistor. So I got it by connecting the pin directly to the A1 pin.

On the other hand, it seems to me Arduino internally and digitally knows the value of the supply voltage. So it would be faster and easier to get it rather than using the A1 pin. But I don't know how to do it.

After searching on the Internet, I could find only these things which didn't help me much.

voltage level - What are the 5V and VIN pins for? - Arduino Stack Exchange
voltage level - Getting 3.3v on 5v pin in Arduino Uno - Arduino Stack Exchange

I also considered using an external power supply, say 9V to the VIN pin but I don't feel like doing that much.

How can I measure the supply voltage of Arduino without using an analog pin?

Yes, you can do it.

You can measure the voltage of the internal (approximately) 1.1V reference voltage using the ADC and use the results of that to calculate what the reference voltage you used (VCC) must have been to get the results you did.

This is a function I commonly use:

long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1125300L / result; // Back-calculate AVcc in mV
  return result;
}

Depending on how close to 1.1V your internal reference voltage is, you may need to adjust the value 1125300L in the code above.  Measure the actual VCC voltage and adjust that value until it results in the same voltage being returned (multiplied by 1000 since that function returns millivolts).

However, as Edgar Bonet mentions, you don't need to care about the supply voltage in your situation, since your thermistor readings are just a ratio that input voltage, whatever it is. Change the input voltage and you will get the same results, since the ADC returns a value between 0 and Vcc in 1024 steps. With different supply voltages you still get 1024 steps.


constant current or constant voltage power supply to use with RGB shield with high power LEDs So, I got an arduino uno and a RGB shield from velleman for christmas because I mentioned I might want to do a project with high power LEDs - a neat surprise, but now I have to use it (:
The shield can do PWM on an external power supply and this can be wired through to the high power LEDs itself. I aim to power about 10W of LED light in total, with different colors in order to make good use of the board. Can I go for Option 1? If not, what would you advise?

Option 1

As high power LEDs need a constant current, I am inclined to connect a constant current supply as the external supply of the board (assuming all channels' LEDs need the same current).

Update: I talked to an electrician and a constant current supply typically works on a PWM basis; putting this in series with the PWM of the shield is not smart.

Option 2

Alternatively I could connect a standard constant voltage supply and make sure that the current is within limits:

One option would be to use resistors; but, with 12V DC and 350mA I would need like 33 Ohm resistance dissipating 4 Watts of power, which is inefficient.
Alternatively there are DC voltage to constant current LED drivers which will take care of the constant current for me; I could put those at the exits of the shield for the LEDs. They supposedly have a better conversion efficiency than the resistors, but I do have any knowledge about their performance with PWM as input; but I have serious doubts they would like that type of input. Furthermore, these drivers also often have PWM capabilities. This kind of module would render the shield functionality largely useless.

Your thinking and reasoning is pretty much spot on.

The board you have is basically a trio of high current low side switches. So yes, you need something to limit the current, and as you have noted resistors are not going to be very efficient.

The best way to drive high power LEDs is, as you know, with constant current. However, you need a constant current source per LED channel, not one single one for the whole board. That means three individual constant current sources, each providing the right current for the LEDs you are driving on that channel.

It's possible to roll your own cheap constant current sources using LM317T linear voltage regulators (http://diyaudioprojects.com/Technical/Current-Regulator/). It's a cheap option, though pretty much as in-efficient as using resistors, just easier to deal with the heat sinking.  Note that on the LM317T the tab is live, so you must use three separate heat sinks for each channel.

My personal preference though is to use PWM capable constant current sinks. My favourite is the CAT4101 which can deal with up to 1A per channel (more if you parallel them) and uses a single resistor to set the current. It has a PWM input that you can drive direct from an Arduino's PWM pin. Of course, as you note, that then makes your nice shield redundant.


How to prevent ATTiny program from running after I flash it with Arduino? I am making a simple voltage regulator. The whole idea is to just use ADC to read voltage on output side and based on the result, adjust PWM power. I am using PWM on physical pin 5. That's the same pin as the one connected to Arduino pin 10 on this image below:

This means that if I try to flash the program, ATTiny will start to put PWM power into my Arduino. I don't want that to happen. How can I flash the program safely? Can I do something to prevent it from starting?

This means that if I try to flash the program, ATTiny will start to put PWM power into my Arduino. I don't want that to happen.

Why do you think that is a problem? The "PWM power" cannot be any higher than the supply voltage, and that is 5V. The Arduino has no problem with you providing a 5V PWM signal to an input pin.

The only time it could be a problem is if the pin you are sending the PWM to is set to an output, in which case you could risk overloading the pin. To get around that you just need to insert a small resistor between the ATTiny's pin and the Arduino's pin. 330Ω or so should do it. Just enough to limit the current to a safe value (< 20mA) but small enough that it won't interfere with the programming communication.

A well design schematic for an Arduino ICSP programmer would have had these resistors in all the data communication lines anyway.


Can anyone identify these headers? I'm very new to the Arduino platform and micro-controller projects in general, which is why I'm still learning about all the parts needed for circuit creation. There is one particular part that I would need for my current project but I'm having troubles figuring out what exactly this "thing" is ...

Please take a look at this picture: https://i2.wp.com/makezine.com/wp-content/uploads/2015/08/rolljam-hardware.jpg?fit=929%2C724

I need to know, please, what exactly these dual row female headers are called that are placed right to the Teensy board and are holding the two CC1101 units (so I can find them on Amazon or in other shops).
Obviously, they are spanning the gap on the breadboard but is there something you can buy like this? Or are these common dual row headers that have had their pins bent and put into single row headers?
I can't quite tell. The whole thing looks custom made though (to me it even looks like some hot glue was used, but I might be entirely wrong about that).

^^ And if my assumption is right, what might be the purpose of doing this? From my understanding this would create a full row for the power (instead of having two shorter rows), which the gap on the breadboard is meant to prevent?!

Thank you for suggestions.

From the pic, it looks like a 2x16 female header, PCB mount, with the pins bent outward and soldered to some male header pins.

I think they do this to provide mating sockets for the 2x5 male pins on the CC11001s that can be hooked up to a breadboard.

You could avoid this by prototyping on something like "stripboard' or 'Veroboard' like https://www.amazon.com/Soldering-Prototype-Printed-Circuit-Stripboard/dp/B019Q14GRQ/ and cutting/soldering a few traces where appropriate.

Or you could use a small chunk of stripboard tor protoboard to do the adapting from the 2x5 at 0.1" centers, to 2x5 on 0.1"x0.4" centers.


Switching methods/functions with a button I am trying to program a basic counter using 7segment display and a button.
What I am trying to achieve is the following:

Display 0 at the beginning.
When the button is pressed: Start Loop 0-9
Display 0 when the button is pressed the second time.

So basically the button should function as ON/OFF switch for the looping numbers function.

So far I have managed to change the mode from  displaying 0 to looping 0-9, but can't seem to get changing the mode back to displaying 0:

int buttonPin = 10; // Button connected to digital pin 10.
// variable for reading the pushbutton status
boolean buttonPressed = false;
int mode;

void setup() {
    // initialize the pushbutton pin as an input:
    pinMode(buttonPin, INPUT);

    pinMode(1, OUTPUT);
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);
    pinMode(13, OUTPUT);
}

void displayZero() {
    //while (buttonState == true){
    // Displays 0.
    digitalWrite(11,1);
    //button();
    delay(1000);
    //}
}

void displayCounter() {
    // Displays 0.
    digitalWrite(4,1);
    digitalWrite(11,1);
    delay(1000);

    //Displays 1.
    digitalWrite(2,1);
    digitalWrite(3,1);
    digitalWrite(4,1);
    digitalWrite(8,1);
    delay(1000);

    //Displays 2.
    digitalWrite(2,0);
    digitalWrite(8,0);
    digitalWrite(6,0);
    digitalWrite(4,0);
    digitalWrite(9,1);
    digitalWrite(3,1);
    digitalWrite(11,0);
    delay(1000);

    //Displays 3.
    digitalWrite(4,1);
    digitalWrite(9,0);
    digitalWrite(11,0);
    delay(1000);

    //Displays 4.
    digitalWrite(2,1);
    digitalWrite(8,1);
    digitalWrite(3,0);
    delay(1000);

    //Displays 5.
    digitalWrite(6,1);
    digitalWrite(2,0);
    digitalWrite(8,0);
    digitalWrite(11,0);
    delay(1000);

    //Displays 6.
    digitalWrite(4,0);
    delay(1000);

    //Displays 7.
    digitalWrite(3,1);
    digitalWrite(4,1);
    digitalWrite(6,0);
    digitalWrite(8,1);
    digitalWrite(11,1);
    delay(1000);

    //Displays 8.
    digitalWrite(3,0);
    digitalWrite(4,0);
    digitalWrite(8,0);
    digitalWrite(11,0);
    delay(1000);

    //Displays 9.
    digitalWrite(4,1);
    //button();
    delay(1000);
}

void loop() {
    // Check button status.
    int buttonStatus = digitalRead(buttonPin);

    if (buttonStatus == HIGH)
    {
        // Checks if button is pressed and changes buttonPressed from false to true.
        buttonPressed = true;

        // While button is pressed.
        while(buttonPressed == true) {
            // Calls displayCounter method 10 times.
            for (int i=0; i<10; i++) {
                displayCounter();
                delay(30);
                buttonPressed == false;
            }
        }
    }
    else if (buttonStatus == LOW)
        displayZero();
}

In your loop() function, the statement buttonPressed == false; doesn't do anything; it is simply an expression that evaluates to 0 or false (because buttonPressed is equal to true). Your while() loop will never end which is why you can't stop the counter by pressing the button again.

You probably meant buttonPressed = false;, which is an assignment statement setting the value of buttonPressed.  But doing that within the while loop makes the loop contents iterate once which it would do anyway, so there is no need for the surrounding while statement. The for() statement will still be executed once, without the while (the loop contents will be iterated 10 times in that one execution).

So you can reduce your loop() function to:

void loop() {

// Check button status.
   int buttonStatus = digitalRead(buttonPin);

   if (buttonStatus == HIGH)
   {
      // Calls displayCounter method 10 times.
      for (int i=0; i<10; i++){
         displayCounter();
         delay(30);
      }
   }
   else
      displayZero();
}

which will check the button state on each call to loop() and either run the counter or zero it, once, depending on the state.

You'll need another refinement, that of debouncing the button. Push buttons (and some other kinds of switches don't have a clean 0 -> 1 (or vice versa) transition but take some amount of time during which their state appears to bounce between 0 and 1 before finally settling to the new state. Read Nick Gammon's excellent article about contact bounce to see why and what to do about it.


Arduino : send data via satellite (or other solutions ? without GSM) I'm a researcher and I'm looking to build a very tiny embedded system. I must to send data from the desert and above the ocean, to do that I think that my single option is to use satellite transmission (and not GSM).
Thus, I found Iridium Satellite (RockBLOCK) but my main issue is that their Arduino module is too big for my project (4cm of length and too heavy).
Do you know if there is other module to send data via satellite with Arduino ?
If not, do you know other microcontroller which can do that ? (Using Arduino is not mandatory for me)
Thank you a lot,
Sincerely.

My two cents: A possibility might be LoRaWAN on the 2.4GHz spectrum, for which there are also satellites in orbit.
The LoRaWAN ("Long Range Wide-Area-Network") protocol is based on a chirp-spread-spectrum (CSS) modulation and has a very high range.
I've used LoRaWAN before but not on 2.4GHz or with a satelitte, so I can't comment on the practical feasibility. However, there are some materials from The Things Conference (by The Things Network, a leading developer of LoRa network servers).

https://www.youtube.com/watch?v=iwocSYupdIQ
https://www.youtube.com/watch?v=jlNyBDxpKUw
https://enterpriseiotinsights.com/20190618/channels/news/lora-shoots-for-75pc-of-iot-market
https://enterpriseiotinsights.com/20200130/channels/news/lorawan-enters-2-4gh-plus-satellite-boost-network-sharing-embedded-security
https://www.semtech.com/company/press/semtech-and-swarm-deliver-satellite-communications-with-lora

Also maybe other modules that can talk to the Iridium satellites suite you better. Sparkfun has a few

https://www.sparkfun.com/products/13745
https://www.sparkfun.com/products/16394


Switch 230V 50Hz using a digital out pin I would like to control normal household appliances like lamps, pumps etc. using my Arduino with up to 5 A. I looked a little around, but it seems, that most relais draw more current than the Arduino is capable of supplying.

How can I switch an 230 V AC current using my Arduino?

The good advice to people asking how to drive a relay to control mains voltage is: don't.

Start with a complete solution such as those from PowerswitchTail.com and sold by many places:  Powerswitch Tail

You can get these already built or in kit form.  The 20 $ price is small price compared to damage to people or home you might incur with a home built solution.


Arduino Voice recognition Is it possible to use only arduino to do voice recognition? or maybe with esp32 no internet.

I found speech recognition chip but that's not what i want
I got esp32 esp8266 and arduino board.
I would like to know if somebody could do it

No. It's as simple as that. No. Voice Recognition is a very very complex task. To do it fast and well in a "general" way takes a neural network, or a very powerful PC (note: all common ones now use online resources to do all the work).

A voice recognition chip generally is pre-programmed to respond to specific words.


Can't upload arduino code on the board due to some programmer issues As I connected my arduino-uno board and made sure of the "Board" selected, and the "Port" selected as well. There is a problem while uploading, I tried updating the arduino IDE, reinstalling all the arduino drivers, I tried to borrow a new arduino board from a friend and I am 100% sure it is working.

The message I get from the IDE:

Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1d

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Thanks in advance!

I faced the same problem while uploading.

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding

To solve that I changed my port to another USB port and I selected the particular port, Its uploaded successfully. But it's in MacBook not in Windows.

Try this once, by changing the port.


Monitor two baud rates I am using different codes which set different values of baud rate through the Serial.begin() function.
I have an Uno using Serial.begin(9600) connected to an ESP8266 ESP-01 module
SoftwareSerial WiFiBoard(2, 3);
WiFiBoard.begin(115200)

Both of them are printing and reading from Serial, but when I use Arduino IDE Serial Monitor, I'm only able to display the content of the 9600... Am I missing a setting somewhere?
Also, when I configure both of them to use the baud rate 9600, I still only see the Uno information

Your computer can not see what is going over the WiFiBoard serial connection because that connection has nothing at all to do with the connection to your computer.
If you want your computer to see what is being received on that port you must read the data from that port then send it to your computer.
It doesn't (much) matter about the difference in baud rates (only that if one sends too much data too fast for the other to forward it you will lose some data).
It's common to use something like:
while (WiFiBoard.available()) {
    Serial.write(WiFiBoard.read());
}

That will forward anything received from the WiFi board over the serial port to the computer.


Attiny85 Timer 1 comparator B doesn't work properly (while A does) I'm writing a simple program that is using Timer 1 comparator B to generate a square wave on DEBUG_PIN.

So my code at first turns on timer 1 with prescaler 8192 so that one tick is approximately 1ms. Then , when timer reaches up to 100 I turn off all timers, than enable timer1 compB and drive DEBUG_PIN high. When timer1B interrupt occurs, then it drives DEBUG_PIN low and disables TIMER1B interrupts.

The problem is that whenever I run the code, DEBUG_PIN state is always high. Here is the strange thing: when I change comparator from B to A on the same timer, everything works fine!
Here is the code:

#include "avr/interrupt.h"

#define DEBUG_PIN 4

volatile bool flag = false;
volatile int counter = 0;

ISR (TIMER1_COMPB_vect){
  digitalWrite( DEBUG_PIN, LOW );
  bitClear(TIMSK, OCIE1B);
}

void setup() {
  cli();

  pinMode( DEBUG_PIN, OUTPUT );

  digitalWrite( DEBUG_PIN, HIGH );
  //stop TIMER1
  TCCR1 = 0;
  //prescaler is 8192 sot that 1 tick is 1ms, enable timer1
  TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);
  sei();
}

void loop() {

    if( TCNT1 >=100 ){
      cli();
      counter = 0;
      //disable compB
      bitClear(TIMSK, OCIE1B);

      digitalWrite( DEBUG_PIN, HIGH );

      /* enable compB */
      //set comparatorB value
      OCR1B = 70;
      //enable compA interrupts
      bitSet(TIMSK, OCIE1B);

      TCCR1 = 0 ;

      TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);

      TCNT1 = 0;

      //reset OCF1A interrupt flag, just in case
      bitSet(TIFR,OCF1B);
      sei();
    }
}

Does anybody has any idea where this comes from?!?!

Here is the code:

that code can be greatly improved:

1) break down your task into logical blocks;

2) code each block as per the datasheet, with comments;

3) tell your readers what you intended your code to do and what your code did.

4) read the datasheet.

edit: your code, following the steps above, set to flip PB4 at OCR1B = 70, on an attiny85 @ 8MIPS, produced the following.

you are close so keep working at it.

edit 2: once setup, the code is fairly simple.

ISR (TIMER1_COMPB_vect){
  //bitClear(TIMSK, OCIE1B);
    //update the next match point for timer1, ch b
    OCR1B +=(IO_GET(DEBUG_PORT, 1<<DEBUG_PIN))?(DEBUG_PR - DEBUG_DC):DEBUG_DC;
    IO_FLP(DEBUG_PORT, 1<<DEBUG_PIN);   //flip the output pin
}

void loop() {

}

the above code generates a pulse train with a duty cycle of DEBUG_DC / DEBUG_PR. Nothing in the loop() so it is fully transparent to the user.


How do I connect through a HC-05 to PS4 Controller? Searching for Arduino and PS4 on google, I find always the same construction using a USB host shield and a Bluetooth dongle.

But I'd like to connect a PS4 Controller to a HC-05 device. Is it possible? If not, why not?

The HC-05 uses the Bluetooth Serial Port profile (SPP). The PS4 controller doesn't.

Hence you need something that is capable of using the same profile that the PS4 controller uses (HID?). And to that end you need something a little more configurable than a simple HC-05. One option is, as most people use, a USB Host shield with a Bluetooth dongle that can then be configured to communicate using the right profile.


SFML Packet and Arduino Can the sf::Packet class of SFML-network be ported over to arduino for use with the Ethernet library or would it be too big? I'm working on a client-program where an arduino is a server and a regular computer is the client making a request. I'm using the SFML-network library to make networking easier on myself and would prefer to use the built in features of SFML to make networking easier. If it is not feasible would I be better off using fixed width data to communicate with the arduino

Without knowing how it all works, my guess is that you would have to port the whole of SFML, which would be HUGE.  So, "No!" is the answer.

You could, of course, write a library of your own that had an SFML-like interface, but the Arduino networking libraries are already pretty simplistic and easy to use, so what's the point?


I can't receive a letter using UART I wrote a simple program where I transmit and receive a letter via UART. The transmit function works 100% but the receive interrupt function doesn't work at all... Can someone adjust the receive interrupt function so I can receive a string instead of a char?

#define FOSC 16000000 // Clock Speed
#define BAUD 9600
#define MYUBRR FOSC/16/BAUD-1

void setup() {
  USART_Init(MYUBRR);
  interrupts();
}

void loop() {
}

void USART_Init(unsigned int ubrr) {
  /*Set baud rate */
  UBRR0H = (unsigned char)(ubrr>>8);
  UBRR0L = (unsigned char)ubrr;
  UCSR0B = (1<<RXEN0)|(1<<TXEN0);
  //Enable receiver and transmitter */
  UCSR0C = (1<<USBS0)|(3<<UCSZ00);
  /* Set frame format: 8data, 2stop bit */
  UCSR0A |= (1 << RXCIE0);
  UCSR0C=0;
}
void USART_Transmit(unsigned char data) {
  /* Wait for empty transmit buffer */
  while(!( UCSR0A & (1<<UDRE0)));
  /* Put data into buffer, sends the data */
  UDR0 = data;
}

ISR(USART__RXC_vect) {
  char ReceivedByte;
  ReceivedByte = UDR0;
  // Fetch the received byte value into the variable "ByteReceived"
}

ISR(USART__RXC_vect)
{
  char ReceivedByte;
  ReceivedByte = UDR0;
// Fetch the received byte value into the variable "ByteReceived"
}

USART__RXC_vect is not the name of the interrupt vector, USART_RX_vect is.

If you don't get the name right there is no compiler warning, however the interrupt routine is not called.

UCSR0A |= (1 << RXCIE0);

That line is wrong. RXCIE0 is in UCSR0B not UCSR0A. If you set the bit in the correct register you will get an interrupt.


Is this example for playing music without delay correct? I've followed the directions from this answer, to try and play music without delay. This is my code so far:

#include "pitches.h"

int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

const int tonePin = 4;
unsigned long previousMillis = 0;
int counter = 0;
int numberOfNotes = sizeof(melody)/sizeof(int);
boolean outputTone = false;

void setup() {
  pinMode(tonePin, OUTPUT);
  //Serial.begin(9600);
}

void loop() {
  unsigned long currentMillis = millis();
  unsigned long noteDuration = 1000 / noteDurations[counter];
  unsigned long pauseBetweenNotes = noteDuration * 1.30;

  if (counter < numberOfNotes) {
    if (outputTone && ((currentMillis - previousMillis) >= noteDuration)) {
        previousMillis = currentMillis;
        noTone(tonePin);
        outputTone = false;
        counter++;
    }
    else {
        if ((currentMillis - previousMillis) >= pauseBetweenNotes) {
        previousMillis = currentMillis;
        Serial.println(melody[counter]);

        if (melody[counter] == 0) {
          noTone(tonePin);
        } else {
          tone(tonePin, melody[counter]);
        }

        outputTone = true;
      }
    }
  }
}

pitches.h can be found here.

So with this code, the music plays, but slower. The pauses between notes seem longer, and I can't figure out why.

Also, I'm not sure where should I increment my notes counter.

There's a variable called "pauseBetweenNotes". Try modifying that and see if the pause between notes becomes smaller.

Regarding your counter question, the way the counter is set up looks fine to me.


String compare when using Serial I try to detect commands given by user in Serial Monitor, but strcmp fails to flag as identical.

What do I do wrong ?

Is there a better way not reading as String and convert to char for comparison ?

Guy

char* additional_callbacks [] = {"command_1", "command_2", "command_3"};

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

void loop() {
  if (Serial.available() > 0) {
    char tmpchar[50];

    Serial.print("entered_text:");
    String str = Serial.readString();
    str.toCharArray(tmpchar, 50);
    Serial.println(tmpchar);

    for (int i = 0; i < sizeof(additional_callbacks) / sizeof(char*); i++) {
      if (strcmp(tmpchar, additional_callbacks[i]) == 0) {
        Serial.println("match");
      }
    }
    Serial.flush();
  }
  delay(50);
}

In your for() loop, use Serial.println() to display both strings before the compare. You'll be able to see why the compare is failing.

Update:

  it seemed identical.

Something has to be different for the test to fail. If the strings look identical then there must be some non-printing characters that differ: \r, \n, , , missing \0 ), etc.

Try printing your buffers byte-by-byte in hex for a few more bytes than the string length, to be sure there is an  where it should be.

Or print the buffers with this hexdump function which lists a specified memory range in both ASCII and hex:

/***

Name:       hexdump

Function:   Dump memory contents to terminal

Description:Dump a specified range of memory in hex and ASCII

Parameters: byte *mem       - starting address
            uint16_t len    - # of bytes

Returns:    void

Notes:      Based on: http://grapsus.net/blog/post/Hexadecimal-dump-in-C
            Formats with sprintf(); outputs with Serial.print().
            Modified to print ...0 - ...F of each hex-block containing
            any of the requested memory range. Data not in the range are
            not shown.

***/

void hexdump(byte *mem, uint16_t len)
{
   byte *p, *pfirst, *plast;    // -> curr byte, first & last hex-blocks to print from
   char buf[10+1];              // sprintf o/p buffer

   // Print entire hex-blocks that contain the requested mem range,
   // except only show data within the range.
   pfirst = (byte *)((uint16_t)mem & 0xFFF0);           // beg of 1st  hex-block
   plast = (byte *)((uint16_t)(mem + len) | 0xF);       // end of last hex-block

   for( p = pfirst;  p <= plast;  ++p ){

      /* Print block addr */
      if( ((byte *)((uint16_t)p & 0xF)) == 0 ){
         sprintf_P(buf, PSTR("%06X: "), (unsigned int)p);
         Serial.print(buf);
      }

      // Print hex data, or if outside mem range, print spaces
      if( mem <= p && p < (mem + len) ){
         sprintf_P(buf, PSTR("%02hhX "), *p);
         Serial.print(buf);
      }
      else
         Serial.print("   ");                   // outside requested range - just spaces

      // Maybe print gutters and/or ASCII data
      if( ((uint16_t)p & 0xF) == 0x7 )
         Serial.print(" ");                     // narrow gutter after 8 bytes
      // If at end of hex block, print a gutter & re-print the block as ASCII
      if( ((uint16_t)p & 0xF) == 0xF ){
         Serial.print("  ");                    // wide gutter after 16 bytes

         // Print as ASCII.
         // Note: In this loop, we re-use the outer loop's index, 'p', to rescan
         // the hex block. We must leave 'p' as we found it!
         for( p = (byte *)((uint16_t)p & 0xFFF0);  ; ++p ){
            if( !(mem <= p && p < mem+len) )
               Serial.print(' ');               // not in requested mem range
            else if( !isprint(*p) )
               Serial.print('.');               // not printable
            else
               Serial.print(*(char *)p);        // print as ASCII

            if( ((uint16_t)p & 0xF) == 0xF ){
               break;                           // end of hex-block
            }
         }
         Serial.print('\n');
      }
   }
}


What to with reset pin when laying out Arduino PCB? I'm designing a PCB with a standard arduino ATMEGA328 DIP IC. Do I need to make a connection to the reset pin?

"Atmel AVR042: AVR Hardware Design Considerations"


Arduino for kids toy with Battery (safe), Can Arduino overheat the Battery with long running code I am making a learning toy which kids can play with and learn basics of programming. But i am tired of keep replacing the AA batteries as they run out in few days. So i am thinking of using rechargeable battery. But i am very worried to use it considering it is kids toy and people says lipo and li ion battery can explode. There are dangers or over charge and heat etc.

Is it safe to use them? Which one to use?

I am using Arduino pro mini 3.3v and some times 5v.

I was planning to use: XCSOURCE 5 pcs 1A 5V Micro USB TP4056 Lithium Battery Power Charger Board Module TE420

I think some users have misunderstood the question and have voted this question to be closed. This questions is very much to deal with programming also apologies if i have not made it clear.

We can get the battery level in the code, but is there any way in code we can some how turn off the charging when the battery has been fully charged.
I am under impression (might be wrong, you can correct me), normal
battery single AA cell dies after some time on heavy use (using dc motor etc). But
rechargeable batteries are bigger with multiple cells in it they will
last longer. So if i am running some code in a loop for long time
will the battery get over heated will it be a problem.

Probably the easiest/cheapest and safest option is to buy a original USB Power Bank and there you have it. Power banks for cellphones/tablets have overvoltage/overcharge/undercharge protection on them and they are also completely sealed, so it should be perfectly safe to handle one of those to your kids (Of couse not some cheap chinese crap).

They can then charge the power bank over USB on any PC or Wall charger and then use it for hours/days.

If I'm allowed to give you a tip, you could eventually pick one of these here, they are pretty good in my opinion.

Of course there are a ton of others around, so you can just pick one which fit your needs.

On your case you just cut a USB cable and plug the ends on the Pro Mini. If a short is detected, Power banks often just shut off and only turn on when they are charged again (You might try this first). If you use a 3.3V Pro Mini, just put a voltage limiter between it. You might also write "3.3V" on the voltage limitor and "3.3V" on the 3.3V version of the Arduino and teach your kids that if the Arduino has "3.3V" written on it, they should put that "3.3V" voltage limitor before it (or just not use 3.3V variants for ease of use).


Vin and Ground pins shorting only under specific conditions So I have an Arduino Nano that I think might have gone bad. The Vin and ground pins are shorting (I'm checking continuity with a multimeter). But it only shorts when:

The Arduino has power
The red lead of the multimeter is on ground and the black is on Vin (not the other way around)

I've tried checking with the leads both ways (red to ground as well as red to vin) while both on and off, and with two different multimeters, one of which is brand new. Completely at a loss for words because this isn't really how physics is supposed to work (continuity shouldn't depend on lead orientation from the multimeter or whether the circuit is powered, right?). Any insight would be appreciated. Do I have a bad board?

But it only shorts when: The Arduino has power

You must not use a continuity checker or ohm meter on a powered circuit.

Not only will it not work, you risk damaging the meter.

It's also not necessarily safe to use such a meter on an unpowered active electronic circuit like an IC or eval board, as the meter must apply a small amount of power to the circuit to make a measurement - how much power varies between meters and settings, and how much a circuit can tolerate in an unintended way depends on things like polarity and the state of other parts of the circuit.  However, it is common practice to do so - especially for example when there's a fear that the device might already be damaged.


Arduino Uno Reading Fuses I am trying to read the fuse values for the Arduino Uno, but keep getting the following results returned back to me:

enter code hereavrdude: Version 6.0.1, compiled on Dec 16 2013 at 17:26:24
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "/usr/local/CrossPack-AVR-20131216/etc/avrdude.conf"
     User configuration file is "/Users/hd334/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

     Using Port                    : /dev/cu.usbmodem1421
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
       lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : Arduino
     Description     : Arduino
     Hardware Version: 3
     Firmware Version: 4.4
     Vtarget         : 0.3 V
     Varef           : 0.3 V
     Oscillator      : 28.800 kHz
     SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0

avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: safemode: Fuses OK (H:00, E:00, L:00)

avrdude done.  Thank you.

I have tried using avrisp as the programmer too, but this reports an invalid device signature. If I override the device signature check with -F I get the same results as above.

I am using an Uno as the ISP to another uno and have connected the two together as detailed in
https://www.arduino.cc/en/Tutorial/ArduinoISP

I have boot loaded the Arduino Atmega328P boot loader and from the fuse settings given in the boards.txt file expect to see:
lfuse reads 0xff
hfuse reads 0xde
efuse reads 0x05

Another question is with the low fuse set to 0xff the CKDIV8 is programmed so won't the clock be set to 2MHz?

Please help

Concerning your questions about clock division settings: have a look at this pretty tool, it gives you a avrdude query for setting fuses (take care!). The CKDIV8 bit of the low fuse is set by default, so an AT328p will run at 1MHz, clearing this bit will result in 8 MHz.

When flashing you should never override any checks as this may damage/lock your chip.

I see that avrdudes states the supply voltage to be 0.3 volts which is far to low for communication. Any received bits would be low level and therefore any information read will be 0. ISPs usually provide a supply voltage which often can be selected by switches on the programmer. If you are sure your programmer is allright, check your circuit in general.

Btw, which ISP-model do you use?
Is your mcu assembled on a custom pcb (setup?)? If yes, do you have an arduino(like) board to verify this behaviour?


How do I clear previous values while using strcat() to add strings? Is there any other function to add strings into buffer and updating values as well.

This is the problem I am coping with while using strcat()

char temp[2] = "A";
char temp_end[2] = "a";
char buf_adc[20]="alok";
char buf_hum[20]="lok";
char buf_temp[20]="vjf";
char buf[100];
void setup() {
Serial.begin(115200);

}

void loop() {
  strcat(buf,buf_adc);
strcat(buf,temp);
strcat(buf,buf_hum);
strcat(buf,temp);
strcat(buf,buf_temp);
strcat(buf,temp_end);

Serial.println(buf);

}

strcat always concatenates to the end of the string. Instead, for your first strcat you should really be using strcpy, which copies one string over the top of the other - that is, it places it at the start of the string, effectively starting a new string.

However, unless you really need the data in a string for some specific reason, you don't need to build a string up - just print each part to serial separately with its own Serial.print function.


fatal error: avr/io.h: No such file or directory I'm compiling a project on Due that was working correclty using UNO. I get this error : 'avr/io.h: No such file or directory'. Searching across the web, it seams I'm not the only one to get that error when using Arduino Due but didn't clearly figured out why it appears.

Of course, the file is present where it should be, I verified ..\Arduino\hardware\tools\avr\avr\include\avr\io.h

I opened it and see something like that :

...

#if defined (__AVR_AT94K__)
#  include <avr/ioat94k.h>
#elif defined (__AVR_AT43USB320__)
#  include <avr/io43u32x.h>
#elif defined (__AVR_AT43USB355__)
#  include <avr/io43u35x.h>
#elif defined (__AVR_AT76C711__)
#  include <avr/io76c711.h>
#elif defined (__AVR_AT86RF401__)
#  include <avr/io86r401.h>
#elif defined (__AVR_AT90PWM1__)
#  include <avr/io90pwm1.h>
#elif defined (__AVR_AT90PWM2__)
#  include <avr/io90pwmx.h>
#elif defined (__AVR_AT90PWM2B__)
#  include <avr/io90pwm2b.h>
#elif defined (__AVR_AT90PWM3__)
#  include <avr/io90pwmx.h>
#elif defined (__AVR_AT90PWM3B__)
#  include <avr/io90pwm3b.h>
#elif defined (__AVR_AT90PWM216__)
#  include <avr/io90pwm216.h>
#elif defined (__AVR_AT90PWM316__)
#  include <avr/io90pwm316.h>
#elif defined (__AVR_AT90PWM161__)
#  include <avr/io90pwm161.h>
#elif defined (__AVR_AT90PWM81__)
#  include <avr/io90pwm81.h>

...

so I suppose that a line referring to my card is missing or something like that ?

I'm using Arduino 1.6.12

The Due is SAM architecture. avr/io.h is specific to the AVR architecture of the Uno's microcontroller. The compiler will not look in the avr tools folder for that file and even if it did it wouldn't help because that file is not compatible with the SAM architecture.

This error indicates that part of the code you're attempting to compile (probably a library) is AVR specific. You will need to either port that code to the SAM architecture or find an alternative that is already compatible with Due.


Use Adafruit 16-Channel 12-bit PWM/Servo Shield to switch relays I'm wondering if using the Adafruit 16-Channel 12-bit PWM/Servo Shield is it possible to switch relays, such as use that shield as a multiplexer and use digital output without PWM.

Is it possible? example code?

That will work. Just make sure you are not using Servo part of the library, but only the PWM part, and set the duty cycle to 100%. The relay should still work, even if the duty cycle is slightly lower, as the magnetic field takes a bit of time to collapse. Just make sure you don't forget to add a (flyback) diode to the relay.

Looking at the datasheet I think you need to use the following code

pwm.setPWMFreq(1000);//put this in setup()
...
// enable relay at channel 15
pwm.setPWM(15, 1, 0);
...
// disable relay at channel 15
pwm.setPWM(15, 1, 1);


Weird sound when modulating the pulse width on Arduino I'm trying to generate a pulse width modulated sound using Arduino Nano.

But it generates the weird sound unlike my expectation.

Here's my code:

class Phasor
{
public:
    Phasor(const float frequency)
    :frequency(frequency)
    ,phase(1.0f)
    ,lastTimeMicros(0){};
    virtual ~Phasor(){};
    void setFrequency(const float frequency)
    {
        this->frequency = frequency;
    }
    float process()
    {
        const unsigned long currentTimeMicros = micros();
        if (phase == 1.0f) lastTimeMicros = currentTimeMicros;
        const unsigned long elapsedTimeMicros = currentTimeMicros - lastTimeMicros;
        const unsigned long cycleDurationMicros = static_cast<unsigned long>(1000.0f / frequency) * 1000;
        if (elapsedTimeMicros < cycleDurationMicros)
            phase = static_cast<float>(elapsedTimeMicros) / static_cast<float>(cycleDurationMicros);
        else
            phase = 1.0f;
        return phase;
    }
private:
    float frequency;
    float phase;
    unsigned long lastTimeMicros;
};

class PulseOsc
{
public:
    PulseOsc(const float frequency, const float pulseWidth)
    :phasor(frequency)
    ,pulseWidth(pulseWidth){};
    virtual ~PulseOsc(){};
    void setFrequency(const float frequency)
    {
        this->phasor.setFrequency(frequency);
    }
    void setPulseWidth(const float pulseWidth)
    {
        this->pulseWidth = pulseWidth;
    }
    float process()
    {
        const float phase = phasor.process();
        if (phase <= pulseWidth)
            return 1.0f;
        else
            return -1.0f;
    }
private:
    Phasor phasor;
    float pulseWidth;
};

Phasor *phasorLFO;
PulseOsc *pulseOsc;

void setup()
{
    Serial.begin(9600);
    pinMode(9, OUTPUT);
    phasorLFO = new Phasor(0.1f);
    pulseOsc = new PulseOsc(440.0f, 0.5f);
}

void loop()
{
    pulseOsc->setPulseWidth(phasorLFO->process());
    int outVal = LOW;
    if (pulseOsc->process() > 0.0f) outVal = HIGH;
    digitalWrite(9, outVal);
}

The resulting sound is very weird and glitchy.
It works fine when I fix the pulse width value. (without LFO)

What is wrong with my code?
How do I fix this? I would appreciate any advice.

Seems like you are using the system clock micros() to  calculate elapsedTimeMicros, so probably the time spent on the process of calculation and sending signal to the pin may affect it, which may lead to inconsistent duty cycle.


Connecting two analog multiplexers (CD4051b) Is it possible to connect two CD4051b analog multiplexers together so that I can receive 14 analog inputs through  them? Just by using one analog pin and three digital pins on the Arduino UNO.

Each CD4052B multiplexes 8 input to one output, and you need three digial pins to control it.  You have the six analogue input pins available and those pins can also serve as digital outputs, so you should be able to use  them to do what you need.

I would do as follows:

Assign three of your spare pins to be digital outputs.  Use these three to address both CD4052Bs together -- so both devices will receive the same addressing.

Connect the output of one CD4052B to the fourth analogue pin, and the output of the second CD4052B to the fifth analogue pin.  These will be your inputs.

On both CD4052Bs, tie the INHIBIT pin low, so they are permanently on.  (If you want to be able to switch them off, for some reason, you an use your sixth pin to control the INHIBIT line on both devices.)

Now when you want to read from sensor 1, you set 000 on the address lines (A, B and C) and read from the first input.  At the same time you'll have sensor 9 on the second input.

It would be well worth reading the data sheet


What do these pins mean? Where should I plug them in? I am trying to collect data from the arduino into a SD card for the first time, so I bought the adapter at my local electronics/arduino shop. However, I could not find an explanation as to what each pin does, and the other adapters that I have seen online have different pins, so I am not sure what to do with the pins (except for the obvious ones, GND and VCC)

The order of pins is as follows:
CD, DO, GND, SCK, VCC, DI, CS.

Could you help me figure out what they mean and where to plug them into my arduino?

This is called the SPI interface (See Serial Peripheral Interface, Wikipedia. The pin names typically used for SPI are:

GND : Power Ground
VCC : Power input
CS : Chipselect
SCK/SCLK (SD-Clock): SPI Clock
MOSI (SD-DI, DI) : SPI Master out Slave in
MISO (SD-DO, DO) : SPI Master in Slave out
CD: Card Detect (see comment of rollinger below (thanks).

On an Arduino Uno the SPI pins are:

CS – digital 10; this can be in principle any pin
SCK – digital 13
MOSI – digital 11
MISO – digital 12


How to trigger an alarm when toilet paper is low? Anyone with kids knows they never help with the toilet paper. Anyone know how to track when it's low or out and sound an audible alarm? I just don't know what sensor to use that may help.

Some that came to mind are: by weight, by reflection (the color of the paper) or some laser tripwire - all right on the spool. I don't mind building it, it's just I don't know which sensor. Anyone know which to use?

Bring up several rolls at a time and hang one for use. Put the other two on a short vertical pole within reach of the sitter. Sitter can take another roll when needed.

Mechanically sense lack of weight on the shelf at the bottom of the pole. Alarm triggers when the last roll is removed. No one has to get caught short.

To sense the weight use a force sensitive resistor such as the FSR 400 (see datasheet). Alternatively, you could use a lightweight coil spring to rest the toilet paper on with a micro switch that is released when both rolls are removed. Another option would be an IR beam break detector where the circuit is completed when the last roll is removed.


Can you power the ESP8266E-12 with any of the 3.3V pins? If I want to operate the NodeMCU on the 3.3V input with 2.5V to 3.6V; can I use any of the 3.3V pins to do so?

On the nodeMCU board all the 3.3v pins have continuity. That means they all do the same thing. And yes, you can apply ~3.3v to them. I have trouble with voltages under ~2.8 though, 2.5v is likely not going to work.
Use a buck+boost to keep it 3.3v if needed. For cheap dc/dc converters, I strongly prefer ones with XL semi chips; clean enough to please the ESPs.


Reading inside critical sections from ISR Is it necessary to protect reads of volatile variables in critical sections when using interrupts? Or are critical sections only required when concurrently writing variables?

Here is an example of a variable written within an ISR which is protected with a critical section:

void loop() {
    portENTER_CRITICAL(&mux);
    uint other = variable_written_from_isr + 1;
    portEXIT_CRITICAL(&mux);
}

What will happen if an interrupt changes variable_written_from_isr while it is being read? Would anything worse that inconsistencies happen?

Here is an opposite example where a variable is written from an interrupt and read from the loop (or a task):

void IRAM_ATTR handleInterrupt() {
    portENTER_CRITICAL_ISR(&mux);
    uint other = variable_written_from_loop + 1;
    portEXIT_CRITICAL_ISR(&mux);
}

Please note that I aware of stdatomic. I am mainly interested in understanding the behavior of concurrent access in the context of interrupts.

You should use critical sections around any operations that could potentially be affected by the execution of an ISR (or which could affect an ISR) that aren't atomic.

Simply put, an atomic instruction is one which can be represented by a single assembly language instruction. You can't interrupt during the execution of an assembly instruction, so anything that only takes one instruction can't be interrupted until it's complete.

Examples would be moving a value from one 8-bit variable (assuming an 8-bit architecture) into a register, storing an 8-bit value into memory, etc.

What instructions are likely to be atomic very much depends on the architecture that you are working on.  The only real way to be sure is to compile the code into assembly language and examine what is produced. Of course, that means learning the assembly language of your chosen architecture.

However: if in doubt, use a critical section. Better to be safe than sorry. But keep those critical sections as short as possible to not disturb the interrupts more than is needed.

For example, instead of starting a critical section, reading some volatile value, doing some calculations with it, and writing it elsewhere, you should use the critical section just to read the volatile value into a temporary variable. After the critical section, you can then do your calculations and things with it, while the interrupt is then free to be called again.


Press on pressure sensor, then wait 5 seconds, turn on LED I'm having some trouble wrapping my head around timers in Arduino. I've got a FSR Pressure Sensor and I want it to turn on my NeoPixel LED after pressing on it for 5 seconds. Any help is much appreciated!

My goal:
FSRReading > 1022 then wait 5 seconds, turn on NeoPixel
FSRReading < 1022, then reset timer, turn off NeoPixel

This is what I currently have for my code, I can detect and act on sensor readings, but no timer:

#include <Adafruit_NeoPixel.h>
#define PIN 6
#define NUMPIXELS 16
#include "Timer.h"

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

int fsrPin = 9; // FSR is connected to analog 0
int fsrReading; // the analog reading from the FSR resistor divider int LEDbrightness;
int LEDbrightness;
Timer t;

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

void loop(void) {
fsrReading = analogRead(fsrPin);
Serial.println(fsrReading);
Serial.print("Analog reading = ");

// we'll need to change the range from the analog reading (0-1023) down to the range // used by analogWrite (0-255) with map!
LEDbrightness = map(fsrReading, 0, 1023, 0, 255);

if (fsrReading < 10) {
Serial.println(" - No pressure"); } else if (fsrReading < 200) {
Serial.println(" - Light touch"); } else if (fsrReading < 500) {
Serial.println(" - Light squeeze"); } else if (fsrReading < 800) {
Serial.println(" - Medium squeeze"); } else {
Serial.println(" - Big squeeze"); }
delay(50);

for(int i=0;i<NUMPIXELS;i++){

  // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
  if (fsrReading>1022){
  pixels.setPixelColor(i, pixels.Color(0,255,0));
  } else if (fsrReading<1022) {
  pixels.setPixelColor(i, pixels.Color(0,0,0));
  }

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

The basic concept for tracking timing in the loop() is as follows:

1) when your event occurs, you store the current time in a variable:

unsigned long lastReading = 0;
uint8_t waiting = false;

if ( !waiting && fsrReading > 1022 ) {
  lastReading = millis();
  waiting = true;
}

2) you compare the lastReading variable against the current time and when enough time has passed, you can perform you timed action. ie:

int timeToWait = 5000; // 5 seconds

// are we waiting? and has enough time passed?
if ( waiting && millis() - lastReading > timeToWait ) {
   waiting = false; // reset

   // Light up lights
   ...
}

Note: this specific implementation only requires the sensor to rise above 1022 once, then wait 5 seconds before executing the timed action. If you want the sensor reading to be maintained above 1022 for the entire duration then you would add a check for a release with something like:

if ( fsrReading < 1022 ) {
  waiting = false; // reset because reading fell below 1022
}


i586-poky-linux-g++: no such file or directory Error compiling for board Intel® Edison I'm facing this compilation issue.

Arduino: 1.8.4 (Linux), Board: "Intel® Edison"

fork/exec /home/jimish/.arduino15/packages/Intel/tools/core2-32-poky-linux/1.6.2+1.0/i686/sysroots/pokysdk/usr/bin/i586-poky-linux/i586-poky-linux-g++: no such file or directory
Error compiling for board Intel® Edison.

Arduino IDE:

Web IDE:

The problem here is that Intel, in their infinite wisdom* have lots of hard-coded paths to libraries in the binaries (why, heaven only knows) and then a set of scripts that munge those binaries to sort out where the libraries really are.

That script uses an option to find that was deprecated 13 years ago.

Way to keep up with the times, Intel...

So you need to make some fixes to get the toolchain to install properly.

I have created "fix" scripts for both the Edison and the Galileo that you can use to replace your broken toolchain.

https://github.com/majenkotech/IntelFixes

*i.e., sheer incompetence


Need library help for Arduino USB host shield Recently Purchased a "TOOGOO(R) T45 USB Host Shield" from Amazon. I attempted to use the "USB Host Shield Library" from Github, but It seems like it might not support this particular shield.

I would really like to learn how to use this shield to interact with my joystick but the only tutorial information I have found to help me with this is from Circuits@home and they seem to be using a specific shield in their development of the code library.

Can anyone point me to a tutorial or Github library that can help me learn to work with this setup?

I'm using an Arduino Uno and a Thrustmaster USB joystick.

Thanks in advance.

UPDATE*

I fixed the initial problem of accessing the HIDDESC report. I now have the report, but the formatting of the report is particularly hard to understand. Using the Circuits@home articles I'm a little lost on how to read the report data I was given. It does not seem to be formatted in the same way as the example. Can anyone help with interpreting my device report?

  Start
  0000: 05 01 09 04 A1 01 09 01 A1 00 09 30 09 31 09 32
  0010: 09 BB 15 80 25 7F 46 FF 00 66 00 00 66 00 00 75
  0020: 08 95 04 81 02 C0 09 39 15 01 25 08 35 00 46 3B
  0030: 01 65 14 75 04 95 01 81 02 05 09 19 01 29 04 15
  0040: 00 25 01 75 01 95 04 81 02 95 08 81 01 05 08 09
  0050: 43 15 00 26 FF 00 35 00 46 FF 00 75 08 95 04 91
  0060: 82 55 00 65 00 55 00 65 00 55 00 C0
  Usage Page Gen Desktop Ctrls(01)
  Usage Game Pad
  Collection Application
  Usage Pointer
  Collection Physical
  Usage X
  Usage Y
  Usage Z
  Usage Undef
  Logical Min(80)
  Logical Max(7F)
  Physical Max(FF00)
  Unit(0000)
  Unit(0000)
  Report Size(08)
  Report Count(04)
  Input(00000010)
  End Collection
  Usage Hat Switch
  Logical Min(01)
  Logical Max(08)
  Physical Min(00)
  Physical Max(3B01)
  Unit(14)
  Report Size(04)
  Report Count(01)
  Input(00000010)
  Usage Page Button(09)
  Usage Min(01)
  Usage Max(04)
  Logical Min(00)
  Logical Max(01)
  Report Size(01)
  Report Count(04)
  Input(00000010)
  Report Count(08)
  Input(00000001)
  Usage Page LEDs(08)
  Usage Slow Blk On Time
  Logical Min(00)
  Logical Max(FF00)
  Physical Min(00)
  Physical Max(FF00)
  Report Size(08)
  Report Count(04)
  Output(10000010)
  Unit Exp(00)
  Unit(00)
  Unit Exp(00)
  Unit(00)
  Unit Exp(00)
  End Collection Game Pad Pointer X Y Z Undef(00)(00)(7F)(00)
  Hat Switch(00)
  Btn0001
  (00) Btn0002
  (00) Btn0003
  (00) Btn0004
  (00)
  (00)(00)(00)(00)(00)(00)(00)(00)
  Slow Blk On Time

The photos on Amazon show a clone of the circuit@home board so the same library should work. You may be running into the problem mentioned in the following page.

https://esp8266-notes.blogspot.com/2017/08/defective-arduino-usb-host-shield-boards.html


Arduino Mega, Ubuntu, Time.h: No such file or directory I'm using an Arduino Mega with Ubuntu 15.10.

Sadly I've got an error during compilation, that the Time.h library cannot be found. The verbose compile output shows:

/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall
-fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega2560
-DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105
-D__PROG_TYPES_COMPAT__
-I/usr/share/arduino/hardware/arduino/cores/arduino
-I/usr/share/arduino/hardware/arduino/variants/mega
-I/usr/share/arduino/libraries/LiquidCrystal
-I/usr/share/arduino/libraries/SPI
/tmp/build6998056390288565759.tmp/Home_Guard.cpp -o /tmp/build6998056390288565759.tmp/Home_Guard.cpp.o
**Home_Guard.ino:2:20: fatal error: Time.h: No such file or directory**
compilation terminated.

I've already tried to use "time.h" instead of "Time.h" but it doesn't help.

ok. It seems that the Ubuntu arduino package does not contain this library. The file Time.zip has to be downloaded from the authors website: http://www.pjrc.com/teensy/td_libs_Time.html and added in the Arduino GUI menue bar: Sketch -> Import Library -> Add Library


What are the traditional ways to optimize program memory usage? While doing big projects using Arduino boards (Uno, Atmega328P MCU). I used to get warnings like this
Sketch uses 13764 bytes (44%) of program storage space. Maximum is 30720 bytes.
Global variables use 1681 bytes (82%) of dynamic memory, leaving 367 bytes for local variables. Maximum is 2048 bytes.

Low memory available, stability problems may occur.

What are the generally practiced methods for the optimization program memory usage?
Is there any difference in memory usage if the variable is declared globally or locally.
Will it matter what the control statement/selection statements are (like if, switch )
Usage of Serial monitor. Serial.print()
......

Low memory available, stability problems may occur.

How bad are these warnings?
Before marking it duplicate, I have referred the following. But it wasn't satisfactory
Most memory efficient way to program
What are safe memory usage limits?

What are the generally practiced methods for the optimization program
memory usage?

First, note you are searching for ways to lower SRAM memory. This contains global (variable) memory and heap space (dynamic memory + stack memory).

Avoid memory gaps, by not using dynamic memory (with free/malloc/new).
Avoid using the String class.
Avoid global memory in SRAM by using PROGMEM, F(..) if possible.
Use the smallest variable size (e.g. uint8_t instead of int).
Store arrays of booleans into bits (8 booleans per byte).
Use bit flags if applicable.
Use some compressed type of memory internally (affects performance), e.g. if you have many 6 bit values to store, store them not in separate bytes but use 6 bytes for 8 times 6 bit values).
Avoid passing arrays by value.
Avoid a deep call stack with many (big) variables. Note this affects your design, so use it as a last resort.
If you need a calculatable table, calculate each value instead of storing it as a table.
Do not use longer arrays than needed, and think about reasonable maximum array sizes otherwise (see hcheung's comment below).
(this is not a complete list).

Is there any difference in memory usage if the variable is declared
globally or locally.

Yes, local variables are added to the stack, but are removed after the function ends, global variables stay (but are only created once).
Note that variables on the stack (and also dynamic memory) are NOT taken into account in the memory calculated in the warning message during compiling.

Will it matter what the control statement/selection statements are
(like if, switch )

No, this will only affect the program memory.

Usage of Serial monitor. Serial.print()

Probably yes, the serial monitor probably reserves (quite?) some memory as a buffer.

Low memory available, stability problems may occur.
How bad are these warnings?

How bad it is, depends on how much memory is used which is not calculated, which is dynamic memory, and stack memory.
You can calculate it manually (which can be quite cumbersome for a big program), you can also use the GitHub library for this:
Arduino MemoryFree
If you know how much heap memory you use worst case, than add it to the calculated global variables memory. If this is less than your maximum available SRAM memory, you are safe.


Writing and Reading data from RTC module EEPROM_Arduino i have took below code from https://lastminuteengineers.com/ds1307-rtc-arduino-tutorial/. i am not understand what these codes are doing. please help me to understand.

Wire.write((int)(eeaddress >> 8)); // MSB
Wire.write((int)(eeaddress & 0xFF)); // LSB

Thanks

These two lines write a 16 bit (2 8-bit) value, which is signed -32768..32767 or unsigned 0..65535.

Assume a value in bits: 10101010 11001100

Statement 1:

Wire.write((int)(eeaddress >> 8)); // MSB

The first statement shifts the value 8 bits (positions) to the right; this is called the MSB (Most Significant Byte, the left 8 bits). Bits on the right are clipped / fall off. Thus

10101010 11001100

will become

00000000 10101010

When casted to an 8 bit value you get:

10101010

Statement 2:

Wire.write((int)(eeaddress & 0xFF)); // LSB

The second statement will get the LSB (Least Significant Byte). This used the AND operator, meaning a bit is only 1 if both values are 1. 0xFF is the 'mask'

Original value: 10101010 11001100
Mask:           00000000 11111111
                ----------------- AND (&) operator
Result:         00000000 11001100

As you can see only the right 8 bits are kept. When casting this to an 8 bit value:

11001100


Why does SoftwareSerial::read() return int? The documentation on Arduino's website shows SoftwareSerial::read() as returning a char. (link)

The header shows that the method returns an int. (link)

The cpp definition shows SoftwareSerial::read() returning the value from a buffer array of uint8_t values. (link)

Given all of this:

Why would the interface return an int instead of a uint8_t?
Why do the Arduino docs show it as returning a char?
Is it safe to send/receive 8-bits at a time using this library?

For (3) I'm using an HC-06 if that matters.

The documentation on Arduino's website shows SoftwareSerial::read() as returning a char.

No it doesn't. There is nothing in the documentation that tells you the return type. There is only an example where the returned value is assigned to a char variable. That doesn't mean that it returns a char - it just means that whatever data type it does return can be invisibly cast to a char by the compiler.

  The header shows that the method returns an int.

Indeed it does. That is because that is what it returns.

  The cpp definition shows SoftwareSerial::read() returning the value from a buffer array of uint8_t values.

Yes, because the valid data that it deals with is 8 bits in size. Just because it handles 8 bit "valid" data doesn't mean that that's all it ever wants to return.  The "no data available" return value of -1 is obviously not something that is stored in the data. It's a status, not data.

  Why would the interface return an int instead of a uint8_t?

Because a uint8_t cannot encompass all the functionality stated in the "Returns" section:

  the character read, or -1 if none is available

You can't return -1 in a uint8_t.

  Why do the Arduino docs show it as returning a char?

It doesn't - as I mentioned above. It makes no claims at all about the returned data type.

  Is it safe to send/receive 8-bits at a time using this library?

Yes. It performs serial data transfers using 8-N-1 by default. That's 8 data bits, no parity, and one stop bit.

It's this kind of confusion with return types and bytes and integers and things that make people ask why they keep getting ÿÿÿÿÿÿ on the serial monitor. That's -1 cast as a char. I.e., "no data available" but they ignore that and treat everything returned as a char - most probably because the Arduino documentation shows an overly simplified example that ignores the possibility of a -1 being returned and treats everything as a char.

IMHO much of the Arduino documentation is somewhat sub-par and should not be taken literally - only as a rough guide for what is available. The same goes for much of their example code and projects.


Servotimer2, detach "stop" I'm still struggling with the Servotimer2 library

I have an Arduino uno board with a servo motor with the servotimer2 library because I'm using a music shield beside the servomotor and the music shield library and the servo.h wasn't compatible.
But finally I make the two of them working together with the servotimer2.h but now I want my servo to rotate 90 or 180 and then "stop" for a minute and come back again, rotate, stop, rotate,stop, rotate, stop... short of thing so I read this what is commonly done to stop a servo after reaching desired point and now I know that servo can't stop, but they can detach
so I tried making something like this

#include <ServoTimer2.h>  // the servo library
#define rollPin  9

ServoTimer2 servoRoll;

void setup() {
  servoRoll.attach(rollPin);

}

// this function just increments a value until it reaches a maximum
int incPulse(int val, int inc){
   if( val + inc  > 2000 )
      return 1000 ;
   else
       return val + inc;

}

void loop()
{
   mover();
   parar();

}

void mover() {
 int val;

   servoRoll.attach(rollPin);
   val = incPulse( servoRoll.read(), 2);
   servoRoll.write(val);
   delay(10);

}
void parar() {

  servoRoll.detach();
     delay(100);
}

but the servo is only moving very slow and I think is not detaching in any moment. I'm quite lost, I'm very noobie and in the post(what is commonly done to stop a servo after reaching desired point) they said things like making while(true){} loop in the setup? or use millis() and other things that I don't understand quite well
But someone tried to do something like control the time the servo is stopping with the delay, so I tried something like this

#include <ServoTimer2.h>  // the servo library

// define the pins for the servos
#define rollPin  9

int pos = 0;

ServoTimer2 servoRoll;    // declare variables for up to eight servos

void setup() {
  servoRoll.attach(rollPin);     // attach a pin to the servos and they will start pulsing

}

//from https://learn.adafruit.com/multi-tasking-the-arduino-part-1/a-clean-sweep

void loop()
{
 for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    servoRoll.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    servoRoll.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }

}

but with this code, my servo is only moving once, and then stops and don't move again

and I think that my servo with the servotimer2 library is only moving with this

   int incPulse(int val, int inc){
   if( val + inc  > 2000 )
      return 1000 ;
   else
       return val + inc;
}

void loop()
{
 int val;

   val = incPulse( servoRoll.read(), 1);
   servoRoll.write(val);
  delay(10);
}

so, any ideas of what I'm doing wrong?

my servo is only moving once, and then stops You mean it turns 180° then no more? Once it has reached 180° (or 2000 µs) you need to decrease val by one to go the other way (from 2000 to 1000). For example:

int direction = 1;  // 1 or -1
void loop()
{
   int val;

   val = incPulse( servoRoll.read(), direction);
   servoRoll.write(val);
   if (direction <= 1000 || direction >= 2000) {
      direction = -direction;
   }
   delay(10);
}


Water tank false trigger I am trying to make a simple water overflow protection system for my home. I have created it using BC547 and NodeMCU (ESP8266). I have a simple circuit like this:

The problem here is I have 2 wires going into the tank. Which suppose to complete the circuit as soon as water touch both the wires. But the problem here is its by default complete the circuit without even touching, this is happening only in my rooftop water tank. I tried this circuit locally on my desk first and it is working fine. I feel the problem can be humidity inside the tank? Can this be a reason for false trigger?

Here is how I have my code.

    #define RELAY_1 D1
    #define TANK_CONNECTION D4

void setup() {
  Serial.begin(115200);
  delay(10);

  Serial.println("Started");
  secondsTick.attach(1, ISRwatchdog);

  //Set relay pins to outputs
  pinMode(RELAY_1, OUTPUT);
  pinMode(TANK_CONNECTION, INPUT);

  digitalWrite(RELAY_1, relay_on);
  delay(100);

}

void loop() {
  tankFull();
  delay(100);
}

void tankFull(){

  Serial.println(digitalRead(TANK_CONNECTION));
   if(!digitalRead(TANK_CONNECTION) && relay_on == 0){
      Serial.println(motorOnCount);
      motorOnCount++;
      motorOffCount = 0;
      if(motorOnCount >= 10){
        Serial.println("Motor Turn OFF");
        digitalWrite(RELAY_1, HIGH);
         if (client.connected()) {
            client.publish(motor_status, "off", true);
            client.publish(tank_full, "on", true);

          }
        motorOnCount=0;
        relay_on = 1;
      }
      delay(100);
   } else{
      motorOffCount++;
       if (client.connected()) {
          client.publish(tank_full, "off", true);
       }
      //Serial.println(motorOffCount);
      if(motorOffCount>=100){
        motorOffCount=0;
        motorOnCount = 0;

      }
   }
}

Obviously this is not the full code. I am just trying to share the pattern of its working for basic understanding of the setup I have.

Any one have idea about why its always shows circuit complete even without touching the wires. I have tried with 5v as well and 3.3v as well which are present on NodeMcu Board. But none of them worked properly.

Certainly the issue is from EMI but not from the collector side as from the transistor base even the wires are shorter on that side as I understand from the comments.

It's a common mistake to let the transistor base floating, see here a different application but with the same cause and result, the transistor is turning on apparently with no reason. With the base floating the EMI current has no other path than through the transistor base where is amplified by beta ( 110 to 800 for BC547).

Put a 10Kohm resistor between the transistor base and emitter to  let a path for EMI currents to the ground. Try different values, smaller if you still have false triggering, higher if the sensor is not turning on the transistor.

Of course, use  INPUT_PULLUP but the internal resistor is to high 30 to 100 kohm, better use an external resistor arround 10k or lower form the transistor collector to 3V3 to ensure a good noise margin on the collector side to.

simulate this circuit – Schematic created using CircuitLab


myserial.available() returns zero byte I wrote an Arduino program that requires two ports for serial communication. I intended to use both hardware serial and software serial, but the problem is receiving data from receiving buffer of the software serial: it always returns zero byte from myserial.available().

For clarity I used the software serial example in Arduino IDE ver. 1.8.4.
I tried to change the baud rate but still the problem persists. I read somewhere that they made some code changes in the SoftwareSerial library's .cpp and .h files. I tried to find the site without success. And my PC where I installed those libraries was stolen. Before that it was working properly.

The mistake I made is that I just copied the code and pasted in the library without concentrating on it. Here is the example of program with two serial ports.

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup() {
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  Serial.println("Goodnight moon!");
  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);
  mySerial.println("Hello, world?");
}

void loop() {
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

The SoftwareSerial example code
https://www.arduino.cc/en/Reference/SoftwareSerialAvailable
shows that the pins used as tx and rx for SoftwareSerial need to be defined using pinMode() as digital input and output.

  Example

// include the SoftwareSerial library so you can use its functions:
#include <SoftwareSerial.h>

#define rxPin 10
#define txPin 11

// set up a new serial port
SoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);

void setup()  {
  // define pin modes for tx, rx:
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.available()>0){
    mySerial.read();
  }
}


how to write Arduino code for a stepper motor to move an arm back and forth 180 degrees I am currently working on a project which involves picking up plastic balls and depositing them in a box. I am trying to use a stepper motor to move an arm which is attached to a square piece of plywood which has Pringles cans on it. This is how I plan to collect the plastic balls.

The stepper motor needs to move the arm back and forth 180 degrees to collect and deposit the plastic balls. But I am unsure as to how to write the code to accomplish this as I am quite new to Arduino coding. Any form of help would be greatly appreciated. Thank you in advance.

There is not enough information about your stepper motor, so let's assume some: let's use stepper motor with 1.8 degree per step (very popular step motor), and we will drive without any microsteps.
To accomplish the task you would need:

Arduino,
stepper motor,
stepper motor driver (like EasyDriver or some kind of Pololu drivers)
power supply. To avoid interference I would suggest powering up your Arduino with PC (through USB port) and additional, powerful PSU for the motor/motor driver only.

Now, you would need to provide at least two signals from Arduino to stepper driver (what I am saying here is example of EasyDriver). The signals named DIR and STEP. DIR selects the direction of the motor to spin. Depending of the stepper motor to driver PCB connections you may have clockwise spin when signal is in one state and counterclockwise when DIR is in opposite state. STEP accepts pulses to move the step motor. Driver moves the stepper motor when STEP input sees raising edge. One raising edge equals to one step = 1.8 degree (again, this apply when you do not use microstepping). To spin motor 180 degrees you need 100 steps.
To summarise:

Use two ports (simplest solution here with EasyDriver): One defined as DIR, other as STEP.
DIR low (selecting one of directions)
STEP pulse 100 times (step motor rotates 180 degrees)
pause (for whatever needs to be done)
DIR high (opposite direction to rotate back)
STEP pulse 100 times (stepper motor rotates 180 degrees to initial position)


ESP8266 ESP-01s Not Responding, No LED Blinking, Overheating I have an ESP-01s that I want to use as a shield so my Arduino Uno project could communicate with my Blynk app through wi-fi. I used this video as reference.
This is the sketch. It is just the ESP8266_Shield example from the Blynk library.
#define BLYNK_PRINT Serial

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>

char auth[] = "-------";

char ssid[] = "-------";
char pass[] = "-------";

#include <SoftwareSerial.h>
SoftwareSerial EspSerial(2,3); // RX, TX

// Your ESP8266 baud rate:
#define ESP8266_BAUD 115200

ESP8266 wifi(&EspSerial);

void setup()
{
  // Debug console
  Serial.begin(9600);

  delay(10);

  // Set ESP8266 baud rate
  EspSerial.begin(ESP8266_BAUD);
  delay(10);

  Blynk.begin(auth, wifi, ssid, pass);
}

void loop()
{
  Blynk.run();
}

This is the schematic:

What happens:

The moment the Arduino is connected, the Blue LED flashes for a split second then all LEDs will remain off. No red led, no blue led, really just off.
The ESP-01s becomes very hot to the touch
Tried speaking to the ESP-01s through the Serial Monitor with BareMinimum example @115200 baud rate (Many Sources say that this is the default baud rate of the recent boards) however no response whatsoever.
Running the code above will get this error:

What I've done:

Tried using the HW-131 Breadboard Power Supply to supply the 3.3V (Common GND with Arduin) of the ESP-01s because I read that the ESP-01 could need more current than the Arduino Uno could provide. Still the same effect, no LEDs blinking, (even more) hot to touch, not responding to AT commands.
Attempted to follow a video on how to flash the ESP-01s but when I tried to run the flasher, it could not communicate with the ESP-01s.
Switching Rx Tx ESP-01s but no luck.
Added a 10k ohm resistor from 3.3V to the Vcc and EN pins of the ESP-01s. Not heating up anymore but still no response.

I really thought this is a power problem but could it be the ESP-01s itself is defective?
This is what the ESP-01s look like

The ESP8266 is (highly likely) dead. The overheating is the giveaway.
Because you haven't mentioned it, please measure the 3.3V coming out of the Arduino with a multimeter. Unlikely to be the issue but it is easy to check.
You will need to buy a new ESP8266 and connect it up and give it a try with a fresh board. If all is good with the new board then the first thing you will notice is that there is no overheating. (If there is overheating, then you need to check your wiring.)
I notice that quite a lot of people add a 10K pull up resistor between the 3.3V line and the Enable pin. It certainly won't hurt to add a 100 ohm resistor between the Tx pin and D2 of the Arduino as a current limiting resistor, just in case.


Output of Hex of ino I have a hex file of a sketch i.e. sketchname.ino.hex. Can I find out anything from that hex file ?  Can I see the output or anything ? Can I upload it on arduino ?

I have a hex file of a sketch i.e. sketchname.ino.hex. Can I find out anything from that hex file ?

That is a binary image of the compiled sketch in a hexadecimal notation. You could spend hours disassembling it if you understood the right tools to use.

  Can I see the output or anything ?

You can convert it back to a crude form of assembly language maybe, but that is all. Understanding what that means takes skill and knowledge.

  Can I upload it on arduino ?

Sure. It's a compiled program ready to be uploaded to an Arduino.

avrdude -D -patmega328p -PCOM3 -b115200 -C/path/to/avrdude.conf -c arduino -Uflash:w:sketchname.ino.hex:i